# Sapling.ai Developer Documentation > API and SDK documentation for Sapling.ai: grammar/spell checking, autocomplete, AI content detection, paraphrasing, and language tools via HTTP API and JavaScript/Python SDKs. ## docs API Overview   - [Welcome](https://sapling.ai/docs.md): API Overview   ### api Overview of the Sapling.ai API offerings. - [API Overview](https://sapling.ai/docs/api.md): Overview of the Sapling.ai API offerings. - [Account Status](https://sapling.ai/docs/api/account-status.md): One-call self-diagnosis for a Sapling API key — whether it can make billable calls right now, why not, when a block clears, and the limits configured on the key. - [Advanced Edits](https://sapling.ai/docs/api/advanced-edits.md): Sapling provides customizable proofreading settings that go beyond regular spelling and grammar checking. These include suggestions around making text simpler and more confident, as well as edits around DEI. The Advanced Edits settings are configurable for your account (here) as well as on a per API call level (documented below) because these suggestions may not be applicable to all styles of writing. Advanced Edits are currently only available for English. - [Analysis](https://sapling.ai/docs/api/analysis.md): The Analysis endpoints compute syntactic information about the input text. Outputs include: - [API Access](https://sapling.ai/docs/api/api-access.md): Anyone can test out Sapling's API. To get started with the API, simply: - [API Reporting](https://sapling.ai/docs/api/api-reporting.md): Sapling's API endpoints for retrieving API usage analytics, plus the - [Applying Edits](https://sapling.ai/docs/api/applying-edits.md): Programmatically Applying Edits - [Autocomplete](https://sapling.ai/docs/api/autocomplete.md): Sapling's autocomplete provides predictions of the next few characters or words - [Chunking](https://sapling.ai/docs/api/chunk.md): Also refered to as segmentation, chunking text allows you to parallelize - [Text Classification API](https://sapling.ai/docs/api/classify.md): The classify endpoint sorts a piece of text into labels you define in the request — no training data, - [5 Best Grammar and Spell Checking APIs / SDKs](https://sapling.ai/docs/api/comparison.md): Looking for a grammar check API? A comparison of 5 grammar and spell checking APIs — Bing, Ginger, LanguageTool, ProWritingAid, and Sapling — with features, latency, and drawbacks of each. - [Custom Mappings](https://sapling.ai/docs/api/custom-mappings.md): Custom Mappings can be used to enforce specific corrections or capitalization for the following purposes: - [AI Detector API](https://sapling.ai/docs/api/detector.md): Sapling's AI detector API scores how likely text is AI-generated, at the document, sentence, and token level. REST endpoint plus Python and JavaScript SDKs. - [Dictionary](https://sapling.ai/docs/api/dictionary.md): Add terms such as industry-specific jargon or product names to your dictionary so that Sapling will ignore these terms. The dictionary can also be managed in your web dashboard. - [Grammar Check API](https://sapling.ai/docs/api/edits-overview.md): Sapling's grammar check API returns grammar, spelling, and style corrections as JSON edits with character offsets and error types. REST endpoint plus Python and JavaScript SDKs. - [Error Categories](https://sapling.ai/docs/api/error-categories.md): Error categories are returned as part of the Edits API. They provide additional classification and detail on the types of edits that Sapling suggests. These categories can be used for analysis, reporting, or coaching purposes. - [Benchmarking & Evaluation](https://sapling.ai/docs/api/evaluation.md): How do you determine whether one NLP system that suggests edits - [Data Extraction API](https://sapling.ai/docs/api/extract.md): The extract endpoint pulls fields you name out of unstructured text — invoices, emails, resumes, - [Files](https://sapling.ai/docs/api/files.md): In addition to plain text, Sapling also supports PDF and DOCX processing - [Handling Fragments](https://sapling.ai/docs/api/fragments.md): Sometimes the text in requests may not be full sentences but instead - [Guardrails](https://sapling.ai/docs/api/guardrails.md): Despite their amazing capabilities, LLMs can often behave in undesired - [Humanizer API](https://sapling.ai/docs/api/humanizer.md): Rewrite stiff or mechanical drafts into clear, natural-sounding copy while preserving facts, numbers, and paragraph structure. Available by request. - [Inclusive Language API](https://sapling.ai/docs/api/inclusive.md): The Inclusive Language endpoint finds non-inclusive or biased wording in a text: gendered defaults - [Job Description Match API](https://sapling.ai/docs/api/jd-match.md): Measure how closely a resume overlaps with a job description, with keyword coverage and passages copied word for word. - [Language Detection API](https://sapling.ai/docs/api/langdetect.md): The language detection endpoint identifies the language of a given text and returns a confidence score. - [Named-Entity Recognition API](https://sapling.ai/docs/api/ner.md): The NER endpoint finds named entities in a text — people, organizations, locations, dates, times, - [5 Best Paraphrase APIs](https://sapling.ai/docs/api/paraphrase-comparison.md): Looking for a paraphrasing API? A comparison of 5 paraphrase and rephrase API services (Sapling, DeepL Write, NeuralWriter, Paraphrasing Tool and Cloudmersive), with options, languages, free tiers and self-hosting. - [PII Detection & Redaction API](https://sapling.ai/docs/api/pii.md): The PII endpoint finds personally identifiable information in a text — email addresses, phone numbers, - [Plagiarism API](https://sapling.ai/docs/api/plagiarism.md): Detect verbatim copying and lightly edited passages across the public web, with character offsets, matched source URLs, excerpts, and search coverage. - [Postprocessing](https://sapling.ai/docs/api/postprocess.md): The Postprocess endpoint performs a variety of operations that are useful - [Preprocessing Overview](https://sapling.ai/docs/api/preprocess-overview.md): Ingestion + Extraction - [Profanity Filter API](https://sapling.ai/docs/api/profanity.md): The profanity API checks for profanity in the given text - it provides a 0/1 label for each token, where 1 indicates profanity was detected. - [Quality Score](https://sapling.ai/docs/api/quality.md): The quality endpoint computes a writing-quality score for a given text. - [Rephrase](https://sapling.ai/docs/api/rephrase.md): The Paraphrase and Rephrase endpoints offer paraphrasing for particular styles. - [Research Credits](https://sapling.ai/docs/api/research-credits.md): Free AI Detector API credits for research projects studying AI-generated text. - [Content Safety API](https://sapling.ai/docs/api/safety.md): The content safety endpoint scores a text on seven moderation categories — - [SCIM Provisioning](https://sapling.ai/docs/api/scim.md): Provision and deprovision Sapling Enterprise users from Okta, Microsoft Entra ID (Azure AD), or another SCIM 2.0 identity provider. - [Semantic Search](https://sapling.ai/docs/api/semsearch.md): Semantic search provides the ability to query/search over a set of documents based off the - [Sentiment Analysis](https://sapling.ai/docs/api/sentiment.md): The sentiment endpoint checks the sentiment for a given text - positive, negative, or neutral. - [SEO Analysis API](https://sapling.ai/docs/api/seo.md): The SEO endpoint analyzes a page or article and returns everything needed to publish it well: - [Similar Terms](https://sapling.ai/docs/api/similar-terms.md): Many times you may need to find terms that have a similar meaning to another term. - [Plain Language Simplification API](https://sapling.ai/docs/api/simplify.md): The simplify endpoint rewrites a text in plain language at a reading level you choose — for - [Service Level Agreement (“SLA”)](https://sapling.ai/docs/api/sla.md): Definitions - [Source Match API](https://sapling.ai/docs/api/source-match.md): Find the passages a text copies word for word from documents you supply, with character offsets and an overall similarity. - [Spellcheck](https://sapling.ai/docs/api/spellcheck.md): For some use cases, grammar and phrase-level edits may not be necessary. - [Statistics](https://sapling.ai/docs/api/statistics.md): The Statistics endpoint computes simple statistics for a given text document. These statistics include word and sentence counts as well as Flesch-Kincaid score. - [Style Guide Compliance API](https://sapling.ai/docs/api/styleguide.md): The styleguide endpoint checks a text for compliance with style rules you define in the request — - [Summarize API](https://sapling.ai/docs/api/summarize.md): The summarize endpoint condenses a longer document — an article, call transcript, meeting notes, - [Superuser Management](https://sapling.ai/docs/api/superuser-management.md): For changing the team directly through API, the key holder must be an superuser for the deployment. - [Team Custom Mappings](https://sapling.ai/docs/api/team-custom-mappings.md): API key holder must be an admin for the team to access a team's dictionary. - [Team Dictionary](https://sapling.ai/docs/api/team-dictionary.md): API key holder must be an admin for the team to access a team's dictionary. - [Team Reporting](https://sapling.ai/docs/api/team-reporting.md): Sapling's API endpoint for exporting team user activity and analytics. See Team Management for getting the IDs for a particular team. - [Team Snippets](https://sapling.ai/docs/api/team-snippets.md): Snippets is a way to save time on frequently used pieces of text. - [User Management](https://sapling.ai/docs/api/team-user-management.md): Teams GET - [Tone Detection](https://sapling.ai/docs/api/tone.md): The tone endpoint checks the tone for a given text. - [Transcriptions](https://sapling.ai/docs/api/transcriptions.md): As part of postprocessing, Sapling offers the ability to process - [Translation API](https://sapling.ai/docs/api/translate.md): The translate endpoint translates text into a target language you name — as an ISO 639 code ### sdk Overview of the Sapling.ai SDK offerings. - [SDK Overview](https://sapling.ai/docs/sdk.md): Overview of the Sapling.ai SDK offerings. - [Deploying to Production](https://sapling.ai/docs/sdk/deploying.md): Here's a sample deployment setup using the JavaScript SDK along with a Python backend. - [Editors Overview](https://sapling.ai/docs/sdk/editors.md): Overview of the Sapling.ai editor integrations. - [CKEditor](https://sapling.ai/docs/sdk/Editors/ckeditor.md): Sample Code - [Froala](https://sapling.ai/docs/sdk/Editors/froala.md): Sample Code - [Quill](https://sapling.ai/docs/sdk/Editors/quill.md): Sample Code - [TinyMCE](https://sapling.ai/docs/sdk/Editors/tinymce.md): Sample Code - [Electron](https://sapling.ai/docs/sdk/electron.md): Electron is a library/framework for building cross-platform desktop apps with JavaScript, HTML, and CSS. - [AI Detect HTML Quickstart](https://sapling.ai/docs/sdk/HTML/ai_detect_quickstart.md): Here's a minimal webpage using the Sapling SDK that includes a button for AI Detection. - [HTML Quickstart](https://sapling.ai/docs/sdk/HTML/quickstart.md): This page has two minimal webpages that use the Sapling SDK: one for AI detection and one for grammar and spelling edits. - [Accessibility](https://sapling.ai/docs/sdk/Integration Details/accessibility.md): On May 9, 2024, the Department of Health and Human Services - [Style Customization](https://sapling.ai/docs/sdk/Integration Details/customize.md): For technical support, contact support@sapling.ai. - [Flagging Issues in Text](https://sapling.ai/docs/sdk/Integration Details/flagging-issues.md): Sapling's API and SDK can be used in a variety of different ways to process text and automatically flag issues. These can range from grammatical mistakes to making writing more confident, concise, or inclusive. - [Migrating from the Grammarly Text Editor SDK](https://sapling.ai/docs/sdk/Integration Details/grammarly-migration.md): Important: The Grammarly Text Editor SDK will no longer be updated and will be deprecated on January 10, 2024. We suggest removing the integration from your app or website before that date. - Grammarly - [Salesforce Lightning](https://sapling.ai/docs/sdk/Integration Details/lightning.md): For technical support, contact support@sapling.ai. - [AI Detect JavaScript Quickstart](https://sapling.ai/docs/sdk/JavaScript/ai_detect_quickstart.md): Javascript SDK for AI Detection - [Backend Documentation](https://sapling.ai/docs/sdk/JavaScript/backend_documentation.md): Import the Sapling client with: - [Frontend Documentation](https://sapling.ai/docs/sdk/JavaScript/frontend_documentation.md): The Sapling JavaScript SDK enables easy integration of Sapling's functionality -- such as grammar/spell checking and autocomplete -- in any web application. - [Frontend Key Management](https://sapling.ai/docs/sdk/JavaScript/frontend_key_management.md): There are two main ways of authenticating SDK server requests without exposing your API key in public environments: - [JavaScript Quickstart](https://sapling.ai/docs/sdk/JavaScript/quickstart.md): The @saplingai/sapling-js package has a client for calling the Sapling API from Node and an observer that adds Sapling to text fields in the browser. This page shows how to use them for AI detection and for grammar and spelling edits. - [Tone Detection JavaScript Quickstart](https://sapling.ai/docs/sdk/JavaScript/tone_quickstart.md): Javascript SDK for Tone Detection - [Overview](https://sapling.ai/docs/sdk/overview.md): Sapling has SDKs that assist in grammar checking text for Python and JavaScript, and an HTTP API that is language agnostic. - [Python Documentation](https://sapling.ai/docs/sdk/Python/documentation.md): The sapling-py package provides a Python wrapper around the Sapling HTTP API. - [Python Quickstart](https://sapling.ai/docs/sdk/Python/quickstart.md): This page shows how to use the sapling-py package to detect AI-generated content and to get grammar and spelling edits. ### onprem - [On-Premises Grammar Checkers and Language Model Assistants](https://sapling.ai/docs/onprem/comparison.md): Looking for a self-hosted grammar/spell check tool? Here's a comparison of 4 different products that offer on-premises deployments, along with the benefits and drawbacks of each product. - [Overview](https://sapling.ai/docs/onprem/overview.md): Self-Hosting ### custom-models Language Variety - [Custom Models](https://sapling.ai/docs/custom-models.md): Language Variety ### data Activation - [Data Transfer, Processing, & Retention](https://sapling.ai/docs/data.md): Activation ### help There are several ways to get answers to any questions you have about Sapling. - [Support](https://sapling.ai/docs/help.md): There are several ways to get answers to any questions you have about Sapling. ### integrations With developer platforms, there is often a trade-off - [Other Integrations](https://sapling.ai/docs/integrations.md): With developer platforms, there is often a trade-off ### mcp Connect Sapling's grammar, AI detection, rephrase, summarization, sentiment, language, PII, quality, SEO, classification and extraction tools to an MCP-compatible AI assistant, hosted or local. - [Sapling MCP Server](https://sapling.ai/docs/mcp.md): Connect Sapling's grammar, AI detection, rephrase, summarization, sentiment, language, PII, quality, SEO, classification and extraction tools to an MCP-compatible AI assistant, hosted or local. ### openapi Machine-readable OpenAPI 3.1 description of Sapling's REST API — import it into Postman, generate typed clients, or register Sapling endpoints as tools for ChatGPT Actions and other agent frameworks. - [OpenAPI Specification](https://sapling.ai/docs/openapi.md): Machine-readable OpenAPI 3.1 description of Sapling's REST API — import it into Postman, generate typed clients, or register Sapling endpoints as tools for ChatGPT Actions and other agent frameworks. ### playground We noticed that "playground" is a popular term for AI apps in search traffic analytics. - [Sapling Playground](https://sapling.ai/docs/playground.md): We noticed that "playground" is a popular term for AI apps in search traffic analytics. ### rate_limits Sapling API rate limits, rate-limit headers, the JSON error format, what each HTTP status means, and when to retry. - [Rate Limits & Errors](https://sapling.ai/docs/rate_limits.md): Sapling API rate limits, rate-limit headers, the JSON error format, what each HTTP status means, and when to retry. ### sandbox How to build and test a Sapling API integration safely — the free trial key as a sandbox, zero-cost health checks, which calls change stored state, and moving from test to production. - [Sandbox & Testing](https://sapling.ai/docs/sandbox.md): How to build and test a Sapling API integration safely — the free trial key as a sandbox, zero-cost health checks, which calls change stored state, and moving from test to production. ### uptime You can check on the Sapling API status by checking our status page. - [Status and Uptime](https://sapling.ai/docs/uptime.md): You can check on the Sapling API status by checking our status page. ### usage-pricing Before you subscribe, your API key has a free trial quota of 50,000 characters/day, with 250,000 characters/month. Subscribe for production access and usage-based pricing; subscribed keys default to 20 million characters/day and 50 million characters/month (see Rate Limits). Higher usage volumes are discounted. API subscriptions started on or after August 12, 2026 require a one-time \$5 minimum payment at signup; see Billing for details. - [Usage and Pricing](https://sapling.ai/docs/usage-pricing.md): Before you subscribe, your API key has a free trial quota of 50,000 characters/day, with 250,000 characters/month. Subscribe for production access and usage-based pricing; subscribed keys default to 20 million characters/day and 50 million characters/month (see Rate Limits). Higher usage volumes are discounted. API subscriptions started on or after August 12, 2026 require a one-time \$5 minimum payment at signup; see Billing for details. ## devblog Sapling.ai's developer blog. - [Sapling.ai Dev Blog](https://sapling.ai/devblog.md): Sapling.ai's developer blog. ### archive Archive - [Archive](https://sapling.ai/devblog/archive.md): Archive ### authors Develop AI-powered messaging applications using Sapling.ai's developer platform. Includes grammar/spelling correction and autocomplete through HTTP API or JavaScript SDK. - [Authors](https://sapling.ai/devblog/authors.md): Develop AI-powered messaging applications using Sapling.ai's developer platform. Includes grammar/spelling correction and autocomplete through HTTP API or JavaScript SDK. ### chatgpt-grammar-checking-editing LLMs such as ChatGPT can be used for grammar checking and editing, but there are challenges to be aware of before deploying such systems to production. - [ChatGPT as a Grammar Checker and Editor](https://sapling.ai/devblog/chatgpt-grammar-checking-editing.md): LLMs such as ChatGPT can be used for grammar checking and editing, but there are challenges to be aware of before deploying such systems to production. ### chatgpt-phrases What phrases are used much more frequently by large language models than by people, and what does this reveal about their training process? - [ChatGPT's Favorite Phrases](https://sapling.ai/devblog/chatgpt-phrases.md): What phrases are used much more frequently by large language models than by people, and what does this reveal about their training process? ### tags Develop AI-powered messaging applications using Sapling.ai's developer platform. Includes grammar/spelling correction and autocomplete through HTTP API or JavaScript SDK. - [Tags](https://sapling.ai/devblog/tags.md): Develop AI-powered messaging applications using Sapling.ai's developer platform. Includes grammar/spelling correction and autocomplete through HTTP API or JavaScript SDK. - [2 posts tagged with "llms"](https://sapling.ai/devblog/tags/llms.md): Develop AI-powered messaging applications using Sapling.ai's developer platform. Includes grammar/spelling correction and autocomplete through HTTP API or JavaScript SDK. ## search Develop AI-powered messaging applications using Sapling.ai's developer platform. Includes grammar/spelling correction and autocomplete through HTTP API or JavaScript SDK. - [Search the documentation](https://sapling.ai/search.md): Develop AI-powered messaging applications using Sapling.ai's developer platform. Includes grammar/spelling correction and autocomplete through HTTP API or JavaScript SDK. ## Optional - [Sapling.ai (main site)](https://sapling.ai/): Product overview, live demos, and account signup. - [Sapling MCP Server Guide](https://sapling.ai/docs/mcp/): Install Sapling grammar, AI detection, and language tools in Claude and other MCP-compatible AI assistants. - [Sapling OpenAPI Specification](https://api.sapling.ai/openapi.json): Machine-readable OpenAPI 3.1 description of the REST API, for client generators, Postman, and agent frameworks. No API key needed to fetch it. - [LLM Index](https://sapling.ai/llm/index): Comparison of large language models. - [API Status](https://sapling.statuspage.io/): Live API uptime and incident history. --- # Full Documentation Content ## [ChatGPT as a Grammar Checker and Editor](https://sapling.ai/devblog/chatgpt-grammar-checking-editing.md) November 10, 2024 · 6 min read Ziang Xie CEO, Sapling.ai ## Introduction[​](#introduction "Direct link to Introduction") A popular use case for LLMs is as a writing assistant, for example for editing text as a grammar and spelling checker. Students may need help with writing essays, while businesses use it for drafting and editing emails, marketing copy, reports, etc. An early adopter of language models for writing assistance was [Google](https://arxiv.org/abs/1906.00080) within the Gmail product. With broader availability of LLM platforms for lower costs, major companies have integrated LLMs into their products for writing assistance, such as [Apple](https://www.apple.com/apple-intelligence/) and [Microsoft](https://www.microsoft.com/en-us/microsoft-365/word/ai-writing). However, many of these systems present a popup and do not display suggestions inline. ![Screenshots of writing assistant popups on popular platforms (MacOS, Notion, Gmail)](/img/writing-popups.png) Screenshots of writing assistant popups on popular platforms (MacOS, Notion, Gmail) There has been a gap between the ability of LLMs to generate text and the tight integration of LLMs within text editors. We consider why this is the case, taking the current most popular frontier LLM, ChatGPT-4o mini, as an example, and explain why you should consider using a task-specific LLM for grammar checking (such as the one offered by [Sapling's API](https://sapling.ai/docs/api/edits-overview)). **Tags:** * [llms](https://sapling.ai/devblog/tags/llms.md) [**Read more**](https://sapling.ai/devblog/chatgpt-grammar-checking-editing.md) --- ### 2024[​](#2024 "Direct link to 2024") * [November 10](https://sapling.ai/devblog/chatgpt-grammar-checking-editing.md) [ - ](https://sapling.ai/devblog/chatgpt-grammar-checking-editing.md) [ChatGPT as a Grammar Checker and Editor](https://sapling.ai/devblog/chatgpt-grammar-checking-editing.md) --- # Authors * ## Ziang Xie 2 CEO, Sapling.ai --- # ChatGPT as a Grammar Checker and Editor November 10, 2024 · 6 min read Ziang Xie CEO, Sapling.ai ## Introduction[​](#introduction "Direct link to Introduction") A popular use case for LLMs is as a writing assistant, for example for editing text as a grammar and spelling checker. Students may need help with writing essays, while businesses use it for drafting and editing emails, marketing copy, reports, etc. An early adopter of language models for writing assistance was [Google](https://arxiv.org/abs/1906.00080) within the Gmail product. With broader availability of LLM platforms for lower costs, major companies have integrated LLMs into their products for writing assistance, such as [Apple](https://www.apple.com/apple-intelligence/) and [Microsoft](https://www.microsoft.com/en-us/microsoft-365/word/ai-writing). However, many of these systems present a popup and do not display suggestions inline. ![Screenshots of writing assistant popups on popular platforms (MacOS, Notion, Gmail)](/img/writing-popups.png) Screenshots of writing assistant popups on popular platforms (MacOS, Notion, Gmail) There has been a gap between the ability of LLMs to generate text and the tight integration of LLMs within text editors. We consider why this is the case, taking the current most popular frontier LLM, ChatGPT-4o mini, as an example, and explain why you should consider using a task-specific LLM for grammar checking (such as the one offered by [Sapling's API](https://sapling.ai/docs/api/edits-overview)). ## Limitations of LLMs[​](#limitations-of-llms "Direct link to Limitations of LLMs") While LLMs are now powerful assistants for Q\&A, they often do not generate text in a specific format. For example, OpenAI must enforce that models follow a [Structured Output schema](https://platform.openai.com/docs/guides/structured-outputs) as a separate model capability. For the task of text editing, the simplest output is just the corrected version of the text (the output could also be a list of edits with the edit positions, but this is more expensive in terms of token count, and many LLMs are not great at providing exact numbers without invoking separate modules). During pretraining, LLMs are simply trained to predict the next word in a sequence. In order to perform well at the chat / Q\&A task, LLMs are then instruction fine-tuned so that they respond with a helpful answer instead of just a continuation. To consistently attain an exact output format, either a long prompt or finetuning is needed. Take the following conversations as examples: \[All conversations were with **ChatGPT-4o mini** on `2024-11-14` with no previous context or system prompt.] **Example 1** ``` Human: Correct the grammar: Hi how are you doing Assistant: The corrected sentence is: “Hi, how are you doing?” ``` This results in the **extraneous phrase** "The corrected sentence is:" at the beginning of the response. **Example 2** ``` Human: Correct the grammar: Let me see what we can Assistant: Certainly! A grammatically complete version of the phrase would be: “Let me see what we can do.” This completes the thought and makes the sentence clear and grammatically correct. ``` There is unnecessary text preceding and following the output sentence. The output sentence includes an autocompletion which may or may not be what was desired. **Example 3** ``` Human: Correct the grammar: Hope all's well Assistant: The grammatically correct version would be: “I hope all is well.” ``` The casual statement "Hope all's well" may very well be what the user intended, especially say in a less formal email response. ## Workarounds[​](#workarounds "Direct link to Workarounds") There are two methods to mitigate the above issues: 1. Provide more detailed instructions in the prompt. 2. Finetune the system on the editing task. The first method is easier to get started with, but can be costly as the prompt may often be longer than the input text. ``` Human: You are a grammar assistant for real-time editing. Do not complete partial sentences. Also, do not provide unnecessary edits for casual statements. Only output the corrected text. Now correct the following text: How's it going? Assistant: How's it going? ``` The second method requires some data collection, and also doubles the cost of each API call (as of this writing, for GPT-4o mini, this is `$0.300 / 1M` input tokens and `$0.600 / 1M` output tokens). ## Deployment Considerations[​](#deployment-considerations "Direct link to Deployment Considerations") Outside of the output format, here are some other considerations prior to deploying LLMs for the editing task. ### Benchmarking[​](#benchmarking "Direct link to Benchmarking") We highly recommend benchmarking the performance of the system on a real-world dataset prior to deployment. You can find our guidelines for this [here](https://sapling.ai/docs/api/evaluation/). The intuition is that intentional errors made by developers and administrators doing testing are very different from accidental errors made by users. During testing, false negatives are the emphasis, while during production, false positives get annoying very quickly. ### Latency[​](#latency "Direct link to Latency") While LLMs have become very fast, there is still often a significant delay (time to first token) and processing time (tokens per second). Fortunately, for editing latency is not as critical of a requirement as for autocompletion. Even so, latencies of well under a second are desirable for real-time editing. ### Refusals[​](#refusals "Direct link to Refusals") Surprisingly, sometimes even frontier LLMs will have guardrails in place that prevent them from making recommendations. This can occur, for example, when the text contains offensive language or content. ### Postprocessing[​](#postprocessing "Direct link to Postprocessing") Once you have the corrected text, you'll still need to compute the diff between the old and new text to obtain the edit positions. This is simple for small edits, but for a paragraph where there may be cross-sentence edits, this may not be do-able with a plain edit distance-based method. Sapling's backend handles this for you. ### Customization Options[​](#customization-options "Direct link to Customization Options") Language is not one-size-fits-all. We previously mentioned the example of casual vs. formal English. Another example is that you may need to handle different English varieties (US/UK/AU/CA/etc.). Different businesses may also have their own style guides. Despite learning-based systems greatly outperforming rule-based systems in their ability to generalize, most editing use cases still involve some deterministic logic. ### Displaying Edits[​](#displaying-edits "Direct link to Displaying Edits") Lastly, you'll need to display the edits to the user, which may require significant time from a frontend developer. This is especially true if you wish to display the edits overlaid on top of the editable text. [Sapling's SDK](https://sapling.ai/docs/sdk/overview/) allows you to attach grammar checking functionality to any text input field (`textarea` or `contenteditable`) with a few lines of code. ## Conclusion[​](#conclusion "Direct link to Conclusion") We hope this has been a helpful guide for how you may use ChatGPT as a grammar checker. In case you face some of the challenges presented above, Sapling's API offers a task-specific LLM for grammar checking that may be a good fit. Depending on usage volume, our pricing is competitive with major LLM providers. As of this writing, on our benchmark of 5000 sentences, Sapling's API also significantly outperforms GPT-4o mini on the industry-standard F0.5-score metric (contact us for more details). Contact us at or through our contact form [here](https://www.sapling.ai/contact) for more information. **Tags:** * [llms](https://sapling.ai/devblog/tags/llms.md) --- # ChatGPT's Favorite Phrases October 18, 2023 · 8 min read Ziang Xie CEO, Sapling.ai ![Falling stream of characters.](/img/falling-strings.png) ## Introduction[​](#introduction "Direct link to Introduction") Since the release of OpenAI's ChatGPT in November of 2022, [hundreds of millions](https://www.reuters.com/technology/chatgpt-sets-record-fastest-growing-user-base-analyst-note-2023-02-01/) of users have used it to generate billions of tokens per day. ChatGPT, like other large language models (LLMs), has a distinctive style, and in the initial months of its release would frequently use the phrase "as a large language model" as a precursor to its responses. Since then, this tic appears to have been [reduced](https://www.reddit.com/r/ChatGPT/comments/1576v41/finally_chatgpt_is_no_longer_going_to_say_as_a/), but led us to wonder: what other phrases are strongly associated with ChatGPT's style, but not with the writing of humans? Beyond these statistics, what does this tell us about its training? ## Method[​](#method "Direct link to Method") Our approach was to take question-answer (QA) data with responses by both humans and by ChatGPT. We then determine the phrases that *frequently occur in ChatGPT responses but infrequently occur in human responses*. While this can be done by manually inspecting outputs and making observations, we instead form all possible subsequences of words in the texts (up to length 5) and count the frequency of each. ### Data[​](#data "Direct link to Data") To perform an empirical analysis of ChatGPT's favorite phrases, we used the [HC3 dataset](https://huggingface.co/datasets/Hello-SimpleAI/HC3). This dataset contains \~24K examples of human and AI-generated responses to prompts from Reddit, WikiQA, StackExchange, and other sources of question-answer pairs. We note that this is just one snapshot of responses, and while we may expect the human styles and phrasings to hold steady (at least over the course of a few years), LLMs such as ChatGPT are evolving and changing by the week; the datasets described may need to be updated. ### n-grams[​](#n-grams "Direct link to n-grams") After some simple preprocessing of the data, we computed the 5-grams in each split (human, AI) in the dataset. This resulted in 6,036,620 human n-grams and 3,631,482 ChatGPT n-grams: the first difference we observe is that human-generated text remains more diverse than AI-generated text. We would expect certain [n-grams](https://github.com/orgtre/google-books-ngram-frequency/blob/main/ngrams/5grams_english.csv) to appear frequently in both splits (`at the end of the`, `in whole or in part`) but others to appear much more frequently in human-generated text and others to appear much more frequently in AI-generated text. More precisely perhaps, we would not expect LLMs to generate specific sequences of text due to the methods in which they've been trained and finetuned with human preferences. ## Results[​](#results "Direct link to Results") Based on the analysis above, here are the top 20 phrases most indicative of ***human-generated text***: | Phrase | Log Probability Delta | | --------------------------------- | --------------------- | | the end of the trading | -2.3243 | | put a lot of strain | -2.0574 | | what you want to achieve | -2.0332 | | to give you a basic | -2.0118 | | for the most part its | -2.0069 | | a bit of a mystery | -1.9875 | | i am not a medical | -1.9823 | | is a matter of personal | -1.9750 | | a few of the many | -1.9646 | | i hope that helps let | -1.9407 | | it is up to each | -1.9109 | | the money in the account | -1.9042 | | if you are a nonresident | -1.8966 | | the ratio of the circumference | -1.8936 | | to do this is by | -1.8752 | | are some of the main | -1.8651 | | to the united states constitution | -1.8348 | | the tip of the \[redacted] | -1.8265 | | come up with a plan | -1.7752 | | as a matter of law | -1.7748 | | the best of my ability | -1.7566 | | the length of the side | -1.7447 | | the energy that is released | -1.7409 | | the result of a combination | -1.7016 | | there is also the risk | -1.6976 | Here are the top 20 phrases most likely to appear in ***ChatGPT-generated text*** and not in human-generated text: | Phrase | Log Probability Delta | | ----------------------------------- | --------------------- | | \ there are a couple | 2.9191 | | its also important to think | 2.3774 | | is always a good thing | 2.1334 | | it is also important that | 2.0646 | | it is important to know | 2.0253 | | can vary depending on what | 2.0024 | | i hope this helps \ | 1.9463 | | you may want to check | 1.9204 | | \ another reason is because | 1.9133 | | i hope that helps \ | 1.8907 | | best course of action is | 1.8803 | | it is generally considered impolite | 1.8401 | | it is important to study | 1.8371 | | to keep in mind is | 1.8360 | | i hope this helps you | 1.8343 | | a good idea to go | 1.8296 | | \ there are a lot | 1.8218 | | by a variety of methods | 1.8128 | | \ there are many theories | 1.8114 | | to keep in mind the | 1.8098 | | one way to think of | 1.8061 | | it can be difficult if | 1.7998 | | a good idea to put | 1.7873 | | be able to determine that | 1.7555 | | is important to remember however | 1.7528 | Aside: `` and `` are special tokens indicating the start and end of a text. The number following each n-gram is the difference in log-probability between that text appearing in human vs. ChatGPT-generated text. ## Observations[​](#observations "Direct link to Observations") There are clear patterns in the phrases associated with ChatGPT: * Emphasizing important points (`it is important...`, `is always a good thing`, ...) * Expressing uncertainty (`can vary depending`, `you may want to check`, ...) * Presenting multiple options and viewpoints (`its also important to...`, `it is important to remember...`, ...) Many of these patterns are likely a result of the human examples and preferences that ChatGPT has been tuned on. It's more difficult to immediately identify patterns in the human n-grams. Perhaps a slightly lower degree of formality (`to give you a basic`, `for the most part its`) and also topics such as medical and financial advice where LLMs can be more strict and formulaic given the gravity of the topic. ## Conclusion[​](#conclusion "Direct link to Conclusion") The phrases we've identified demonstrate patterns in ChatGPT's responses that are a reflection of the data that was used to train it. But how strong a signal are they of whether a text was AI-generated or not? AI-generated content is proliferating, and it can be helpful to have surefire "signatures" (such as `as a large language model`) that a text was produced by an LLM. But this is only effective in cases where the user was sloppy and left these telltale signs in the generated text. Many of tried to create **watermarks** that indicate whether an image is AI-generated. These properties can also be put in an image's metadata to indicate its provenance. However, the same is much harder to bake into easily editable text. Some researchers have proposed probabilistic watermarks based on [partitioning vocabularies](https://twitter.com/tomgoldsteincs/status/1618287665006403585); however, these require the participation of all major LLM developers. Interested in other, up-to-date approaches for flagging AI-generated text? Try Sapling's regularly updated [AI detector](https://sapling.ai/ai-content-detector?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs) and [contact us](https://sapling.ai/contact?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs) if you're interested in using it for your business. **Tags:** * [llms](https://sapling.ai/devblog/tags/llms.md) --- ## L[​](#L "Direct link to L") * [llms2](https://sapling.ai/devblog/tags/llms.md) *** --- ## [ChatGPT as a Grammar Checker and Editor](https://sapling.ai/devblog/chatgpt-grammar-checking-editing.md) November 10, 2024 · 6 min read Ziang Xie CEO, Sapling.ai ## Introduction[​](#introduction "Direct link to Introduction") A popular use case for LLMs is as a writing assistant, for example for editing text as a grammar and spelling checker. Students may need help with writing essays, while businesses use it for drafting and editing emails, marketing copy, reports, etc. An early adopter of language models for writing assistance was [Google](https://arxiv.org/abs/1906.00080) within the Gmail product. With broader availability of LLM platforms for lower costs, major companies have integrated LLMs into their products for writing assistance, such as [Apple](https://www.apple.com/apple-intelligence/) and [Microsoft](https://www.microsoft.com/en-us/microsoft-365/word/ai-writing). However, many of these systems present a popup and do not display suggestions inline. ![Screenshots of writing assistant popups on popular platforms (MacOS, Notion, Gmail)](/img/writing-popups.png) Screenshots of writing assistant popups on popular platforms (MacOS, Notion, Gmail) There has been a gap between the ability of LLMs to generate text and the tight integration of LLMs within text editors. We consider why this is the case, taking the current most popular frontier LLM, ChatGPT-4o mini, as an example, and explain why you should consider using a task-specific LLM for grammar checking (such as the one offered by [Sapling's API](https://sapling.ai/docs/api/edits-overview)). **Tags:** * [llms](https://sapling.ai/devblog/tags/llms.md) [**Read more**](https://sapling.ai/devblog/chatgpt-grammar-checking-editing.md) --- [Skip to main content](#__docusaurus_skipToContent_fallback) [![Sapling.ai](/img/logo.svg)![Sapling.ai](/img/logo_dark.svg)](https://sapling.ai/docs.md) [****](https://sapling.ai/docs.md)[Docs](https://sapling.ai/docs.md)[Demo](https://sapling.ai/sdk-demo) [Dev Blog](https://sapling.ai/devblog.md)[Contact](https://sapling.ai/contact)[GitHub](https://github.com/saplingai) Search # Search the documentation Type your search here Powered by[](https://www.algolia.com/) Docs * [API](https://sapling.ai/docs/api/api-access.md) * [SDK](https://sapling.ai/docs/sdk/overview.md) * [LLM Index](https://sapling.ai/llm/index) Community * [Hugging Face](https://huggingface.co/saplingai) * [Discord](https://discord.gg/p5gDc684TX) * [Twitter](https://twitter.com/saplingai) More * [GitHub](https://github.com/saplingai) * [Support](https://sapling.ai/docs/help) Copyright © 2026 Sapling.ai. --- # Welcome [API Overview](https://sapling.ai/docs/api.md)   [SDK Overview](https://sapling.ai/docs/sdk.md) Welcome to the documentation for [Sapling.ai](https://sapling.ai/?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs)'s developer platform. 🚀 Sapling is a platform for building language model applications. Sapling's API provides endpoints for text preprocessing, classification, prediction, correction, and more. Sapling's SDK provides convenient wrappers around the API, as well as UI components for quickly integrating LM-powered functionality in your web application. ## Announcements[​](#announcements "Direct link to Announcements") * **December 2, 2026:** Meet **Delta 1** (`20261202`), our new default English [AI detector model](https://sapling.ai/docs/api/detector.md#december-2026-model-upgrade) — much improved on AI-edited, polished, paraphrased, and humanized writing, with far fewer false positives on short texts, academic abstracts, and ESL essays, competing with frontier detectors at up to 24× lower API cost. [Read the full announcement and benchmarks](https://sapling.ai/news/delta1?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs). No request changes are needed, and you can [pin a previous version](https://sapling.ai/docs/api/detector.md#request-parameters). * **November 27, 2026:** A more accurate English [grammar model](https://sapling.ai/docs/api/edits-overview.md) is now the default for the grammar check API. It makes fewer unnecessary corrections and catches more spelling and homophone mistakes, especially in legal, financial and scientific writing. No request changes are needed. * **November 23, 2026:** A new default English [AI detector model](https://sapling.ai/docs/api/detector.md#november-2026-model-upgrades) (`20261123`) flags less human-written text as AI, most of all short texts and essays, and catches more AI-written text, including paraphrased and humanized text. Earlier announcements * **November 19, 2026:** A new default English [AI detector model](https://sapling.ai/docs/api/detector.md#november-2026-model-upgrades) (`20261119`) flags far less human-written academic writing and personal essays as AI. * **November 18, 2026:** [Prepaid API credits](https://sapling.ai/docs/api/pricing) are cheaper when bought in bulk, and automatic top-ups get the same discount. * **November 13, 2026:** A more accurate multilingual [AI detector model](https://sapling.ai/docs/api/detector.md#november-2026-model-upgrades) for the 15 supported non-English languages. It flags less human-written text as AI and catches more AI-written text. No request changes are needed, and you can [pin a previous version](https://sapling.ai/docs/api/detector.md#request-parameters). * **November 4, 2026:** The default English [AI detector model](https://sapling.ai/docs/api/detector.md#november-2026-model-upgrades) flags far less human-written text such as customer reviews and testimonials as AI. It catches slightly less AI-written text overall. No request changes are needed, and you can [pin a previous version](https://sapling.ai/docs/api/detector.md#request-parameters) to keep the old scores. * **November 4, 2026:** The [AI detector API](https://sapling.ai/docs/api/detector.md#languages) now also scores Polish, Chinese, Arabic, Russian, Swedish, Korean, Turkish and Romanian with the multilingual model, instead of the English model, and the other non-English languages have moved to the updated model. No request changes are needed, and `lang` accepts the new language codes too. Scores change for requests that don't pin a `version`, so recheck any thresholds you set for these languages. * **November 3, 2026:** [More accurate AI detector models](https://sapling.ai/docs/api/detector.md#november-2026-model-upgrades) in every supported language. They flag far less human-written text with bullets or headings as AI, and the English model catches more text from recent models such as Claude 5.5. No request changes are needed, and you can [pin a previous version](https://sapling.ai/docs/api/detector.md#request-parameters) to keep the old scores. ## Getting Started[​](#getting-started "Direct link to Getting Started") Get started by **[following the instructions here](https://sapling.ai/docs/api/api-access.md)**. You can see some of these capabilities by visiting our [Demo](https://sapling.ai/sdk-demo?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs) page. From there, you can start using the Sapling **[HTTP API](https://sapling.ai/docs/api/api-access.md)** or **[SDK](https://sapling.ai/docs/sdk/overview.md)**. To use Sapling's language tools directly from an AI assistant, install the **[Sapling MCP Server](https://sapling.ai/docs/mcp.md)**. You can also try out Sapling using Postman or Zapier. For questions, email us or join our Discord: | Send HTTP requests | Create Zaps | Chat with us | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | [![Run in Postman](https://run.pstmn.io/button.svg)](https://app.getpostman.com/run-collection/20248607-4e2eafd4-e941-4d52-88a8-b4bb90c1d26a?action=collection%2Ffork\&collection-url=entityId%3D20248607-4e2eafd4-e941-4d52-88a8-b4bb90c1d26a%26entityType%3Dcollection%26workspaceId%3Dcea8d224-5c5e-4604-a8f6-46f228f46f78) | [![Connect in Zapier](/img/zapier.svg)](https://zapier.com/developer/public-invite/153371/ea005ac414d48f5f1323bb424c48cf69) | [![Join Discord](/img/discord.svg)](https://discord.gg/p5gDc684TX) | ## Code Examples[​](#code-examples "Direct link to Code Examples") Find example code in our [GitHub repository](https://github.com/saplingai/sapling-samples), including examples for Python and JavaScript (React, Angular). Start a GitHub issue if your use case isn't handled. ## Use Cases[​](#use-cases "Direct link to Use Cases") Here are some of the things you can do with Sapling: * ⚙️ Integrate deep learning-powered [grammar/spell checking](https://sapling.ai/docs/api/edits-overview.md) into any application, either through the [SDK](https://sapling.ai/docs/sdk/overview.md) or through the [grammar check API](https://sapling.ai/docs/api/edits-overview.md). * ✨ [Autocomplete phrases and sentences](https://sapling.ai/docs/api/autocomplete.md) to save users time typing. * 😀 [Check the tone](https://sapling.ai/docs/api/tone.md) of messages. * [Check the sentiment](https://sapling.ai/docs/api/sentiment.md) of messages. * 🟰 Search for [semantically similar terms](https://sapling.ai/docs/api/similar-terms.md) to augment tagging and search. * 🔍 Pull [semantically relevant responses](https://sapling.ai/docs/api/semsearch.md) for knowledge-base retrieval and search. * 💫 [Rephrase sentences](https://sapling.ai/docs/api/rephrase.md) to adjust formality, length, or syntax. * 🕵🏽‍♀️ [Detect AI-generated content with the AI detector API](https://sapling.ai/docs/api/detector.md) or score the quality of content (contact us for details on quality scoring). You can try out many of the examples on our [utilities page](https://sapling.ai/utilities?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs). New functionality is being released every week. Contact us to learn more or to discuss if Sapling can support your use case. ## Key Principles[​](#key-principles "Direct link to Key Principles") Sapling allows you to easily integrate language model-powered functionality into your application. * **End-to-end**: Sapling is designed to handle the *entire stack*, from preprocessing text inputs, to model inference, to postprocessing outputs, to scoring and filtering outputs. It covers the *last mile* that's required for production systems. * **Predictable**: Sapling is designed to not hallucinate or produce unexpected texts. It returns structured outputs that can reliably be used by production systems. * **Efficient**: Sapling is designed for use in real-time settings. This is true for both Sapling's cloud API as well as its self-hosted offerings. * **Turnkey**: For many applications, Sapling can be integrated with just a few lines of JavaScript/Python code. We ensure that the API/SDK are stable and well-documented (see our [SLA](https://sapling.ai/docs/api/sla.md)). * **Secure**: Whether you use our cloud and require finetuning or you require an airgapped deployment with zero data retention, Sapling can support your data security requirements. ## Subscribing[​](#subscribing "Direct link to Subscribing") Signing up and generating an API key will start you on a free trial of the API. There is a character limit and a 1-month expiration date for the trial. [Subscribe](https://sapling.ai/api-checkout)  to remove quota limits and begin [usage-based pricing](https://sapling.ai/docs/api/pricing) (billed monthly). This will also increase the character limit (up to 20 million characters per day for the `/edits` endpoint, as one example) and upgrade the key so that it does not expire. ## About Us[​](#about-us "Direct link to About Us") Sapling is developed by former engineers and researchers from Berkeley, Google, Meta, and Stanford. ![Cal](https://sapling.ai/static/img/berkeley-logo.svg)![Stanford](https://sapling.ai/static/img/stanford-logo.svg)![Meta](https://sapling.ai/static/img/meta-logo.svg)![Google](https://sapling.ai/static/img/google-logo.svg) --- ## [📄️API Access](https://sapling.ai/docs/api/api-access.md) [Anyone can test out Sapling's API. To get started with the API, simply:](https://sapling.ai/docs/api/api-access.md) --- # Account Status Checks whether an API key can make billable API calls right now. If it can't, the response says why and when the block may clear. Call this endpoint after an unexpected `402`, after a `429` whose `msg` starts with `Rate Limited. Monthly quota used.`, or before a large batch job. It gives a single machine-readable verdict instead of leaving you to work out the account's state from individual error messages. It also works when the key is blocked, because a blocked key is the one that needs this check most. The verdict uses the same payment and quota checks as the billable endpoints, so for **account-wide** blocks it matches what a real request would get: an expired key or subscription, depleted credits, a billing limit, the trial daily allowance or the monthly quota. It does **not** report the short-term, per-endpoint rate limit. If one endpoint answers `429` with `Rate limited. Capacity used.`, this endpoint can still return `api_access: true`, because each endpoint has its own allowance. For that case, use the `429`'s `retry_after` and the `X-RateLimit-*` headers described in [Rate Limits & Errors](https://sapling.ai/docs/rate_limits.md#rate-limit-headers). To read the limits themselves (the per-endpoint allowance, the monthly quota, the key's expiry and the account's spend limit), use [Account Limits](#account-limits) below. ## Request Parameters[​](#request-parameters "Direct link to Request Parameters") `https://api.sapling.ai/api/v1/account/status` HTTP method: `GET` or `POST` **key**: String
32-character API key. With `GET`, pass it as a `?key=` query parameter. With `POST`, pass it in the JSON body. With either method you can instead send it as a bearer token in the `Authorization` header. If both are provided, the `key` parameter takes precedence. The endpoint takes no other parameters. Keys only * The public client-side key used by Sapling's website demos gets a `403`. * OAuth access tokens issued for the [MCP server](https://sapling.ai/docs/mcp.md) also get a `403`. Send an API key instead. This call is not billed. Each call counts as 2,000 characters against a separate rate-limit bucket, so polling it doesn't use up your main allowance. Check it when something goes wrong rather than before every request. ## Sample Code[​](#sample-code "Direct link to Sample Code") * cURL * Python * JavaScript ``` curl "https://api.sapling.ai/api/v1/account/status?key=" ``` ``` import requests from pprint import pprint try: response = requests.get( "https://api.sapling.ai/api/v1/account/status", params={"key": ""}, ) if 200 <= response.status_code < 300: pprint(response.json()) else: print('Error: ', str(response.status_code), response.text) except Exception as e: print('Error: ', e) ``` ``` import { Client } from '@saplingai/sapling-js/client'; const client = new Client(''); const { data: status } = await client.accountStatus(); if (!status.api_access) { console.log(`Blocked (${status.blocked_reason}): ${status.message}`); console.log(`Check again in ${status.retry_after} seconds`); } ``` ## Response Parameters[​](#response-parameters "Direct link to Response Parameters") A JSON object. `api_access`, `blocked_reason`, `message` and `usage` are always present. **api\_access**: Boolean
`true` when no account-wide block applies to this key. An individual endpoint can still answer a short-term `429` if its own allowance is used up. **blocked\_reason**: String or null
`null` when `api_access` is `true`. Otherwise it is one of the values below. These values are stable, so you can safely branch on them in code. | `blocked_reason` | Meaning | What a real request returns | Clears when | | ------------------------- | ---------------------------------------------------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `key_expired` | The API key has expired. | `402` | You renew the subscription or buy credits. | | `subscription_expired` | The API subscription is no longer active. | `402` | You resubscribe or buy credits. | | `credits_depleted` | The prepaid credit balance is used up. | `402` | You [buy more credits](https://sapling.ai/docs/api/api-access.md#prepaid-api-credits). | | `monthly_billing_limit` | The account reached the monthly billing limit set on its subscription. | `402` | You raise the limit in [API settings](https://sapling.ai/api_settings?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs#billing), or the next billing month starts. | | `trial_daily_limit` | A free-trial key used up its daily character allowance. | `402` | The next UTC midnight. | | `monthly_quota_exhausted` | The key used up its monthly character quota. | `429` | The next UTC month starts. | **message**: String or null
Human-readable explanation of the block, the same text a real request's `msg` would contain. `null` when not blocked. **retry\_after**: Integer
Only present when blocked. The number of seconds until the block may clear, matching the `Retry-After` header a real request would carry: * `trial_daily_limit`: seconds until the next UTC midnight. * `monthly_quota_exhausted`: seconds until the next UTC month starts. * Every other reason: `3600`. That is only a backoff hint. These blocks don't clear on their own, so resolve them in your [API settings](https://sapling.ai/api_settings?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs). **usage**: Object
* **monthly\_quota\_chars** (Integer or null): this key's monthly character quota, or `null` when it has none. * **month\_start** (String (ISO date)): first day of the current UTC month. * **chars\_this\_month** (Integer): characters used by the account since `month_start`. This figure is updated periodically, so it can trail your most recent requests slightly. **subscription**: Object
* **active** (Boolean): whether the account has an API subscription. * **trial\_only** (Boolean): whether the account has only free-trial API access. * **key\_expired** (Boolean): whether this key has passed its expiry date. **credits**: Object
The prepaid credit summary shown in the API dashboard. When `credits.enabled` is `false`, the account has no prepaid credits and only `currency`, `alert_threshold_percent` and `credits_only` are included. `credits_only` is `true` for an account that can be funded only by prepaid credits, so its API access needs a positive balance (otherwise requests get `402` with `credits_depleted`). Sapling can set it automatically after a card payment on your API invoice fails; see [Prepaid API credits](https://sapling.ai/docs/api/api-access.md#prepaid-api-credits). When `enabled` is `true` the object also includes: * `balance_credits`, `purchased_credits`, `consumed_credits` and `consumed_percent` * `low_balance` and `depleted` * `billing_mode` and `stops_when_depleted` * `auto_topup`: saved automatic credit top-up settings and status, including whether it is enabled and any reason it was disabled. See [Automatic credit top-ups](https://sapling.ai/docs/api/api-access.md#automatic-credit-top-ups) for setup and payment-method requirements. `low_balance` turns on when you have used `alert_threshold_percent` of the credits bought since the last low-balance warning (or of all credits bought, if there has been no warning yet). It stays on until your next purchase. For example, with an 80% threshold: buy 20 credits and it turns on at 16 used. If you then buy 10 more, it turns off and turns on again at 28 used (the 20 from before the warning, plus 80% of the 10 new credits). `consumed_percent` is always measured against all credits bought. One credit equals one US dollar. **trial**: Object
Only present for free-trial accounts. * **daily\_limit\_chars** (Integer or null): the daily character allowance. * **chars\_used\_today** (Integer): characters used since the last UTC midnight. * **resets\_at** (String): always `utc_midnight`. Team-scoped keys A team-scoped key can be shared by many people, so its response leaves out the personal `subscription`, `credits` and `trial` sections, and `usage.month_start` and `usage.chars_this_month`. You still get the verdict fields (`api_access`, `blocked_reason`, `message`, `retry_after`) and `usage.monthly_quota_chars`. ### Sample Response[​](#sample-response "Direct link to Sample Response") A free-trial key that has used up today's allowance: ``` { "api_access": false, "blocked_reason": "trial_daily_limit", "message": "Free trial daily API character limit reached. Purchase API credits at https://sapling.ai/api_settings#billing to continue, or wait for the limit to reset at UTC midnight.", "retry_after": 22140, "usage": { "monthly_quota_chars": 250000, "month_start": "2026-09-01", "chars_this_month": 131872 }, "subscription": { "active": false, "trial_only": true, "key_expired": false }, "credits": { "enabled": false, "credits_only": false, "currency": "USD", "alert_threshold_percent": 80.0 }, "trial": { "daily_limit_chars": 100000, "chars_used_today": 100412, "resets_at": "utc_midnight" } } ``` A key that is ready to use: ``` { "api_access": true, "blocked_reason": null, "message": null, "usage": { "monthly_quota_chars": 25000000, "month_start": "2026-09-01", "chars_this_month": 1840533 }, "subscription": { "active": true, "trial_only": false, "key_expired": false }, "credits": { "enabled": false, "credits_only": false, "currency": "USD", "alert_threshold_percent": 80.0 } } ``` ## Account Limits[​](#account-limits "Direct link to Account Limits") `https://api.sapling.ai/api/v1/account/limits` HTTP method: `GET` or `POST` Returns the limits configured on the key: how much it may send, as opposed to whether it can call right now. Use it to pace a batch job before its first request instead of discovering the allowance from a `429`. It takes the same `key` parameter as Account Status and follows the same rules: it is not billed, it works while the key is blocked, the public demo key and MCP OAuth access tokens get a `403`, and each call counts as 2,000 characters against its own rate-limit bucket. * cURL * Python * JavaScript ``` curl "https://api.sapling.ai/api/v1/account/limits?key=" ``` ``` import requests from pprint import pprint try: response = requests.get( "https://api.sapling.ai/api/v1/account/limits", params={"key": ""}, ) if 200 <= response.status_code < 300: pprint(response.json()) else: print('Error: ', str(response.status_code), response.text) except Exception as e: print('Error: ', e) ``` ``` import { Client } from '@saplingai/sapling-js/client'; const client = new Client(''); const { data: limits } = await client.accountLimits(); if (limits.rate_limit) { const { capacity_chars, window_seconds } = limits.rate_limit; console.log(`${capacity_chars} characters per ${window_seconds}s per endpoint`); } console.log(limits.monthly_quota_chars, limits.key_expires_at); ``` `accountLimits()` needs `@saplingai/sapling-js` 1.0.58 or later. ### Limits Response Parameters[​](#limits-response-parameters "Direct link to Limits Response Parameters") `rate_limit`, `monthly_quota_chars` and `key_expires_at` are always present. **rate\_limit**: Object or null
The short-term allowance. Each endpoint keeps its own allowance of this size for the key, refilled evenly over the window, and it is the same allowance the `X-RateLimit-*` [headers](https://sapling.ai/docs/rate_limits.md#rate-limit-headers) describe. `null` when the key is configured without a rate limit, or on a self-hosted deployment that turns API rate limiting off. * **capacity\_chars** (Integer): size of the allowance, in characters. `0` means the key is disabled. * **window\_seconds** (Integer): the time it takes an empty allowance to refill completely. **monthly\_quota\_chars**: Integer or null
The key's monthly character quota, which resets at the start of each UTC month. `null` when the key has none. To see how much of it is used, call [Account Status](#response-parameters) (`usage.chars_this_month`) or [API Reporting](https://sapling.ai/docs/api/api-reporting.md). **key\_expires\_at**: String or null
When the key expires, in ISO 8601 UTC (for example `2027-11-01T00:00:00Z`). `null` when it doesn't expire. **monthly\_spend\_limit\_usd**: Number or null
The monthly billing limit set in [API settings](https://sapling.ai/api_settings?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs#billing), in US dollars per billing period. If more than one of the account's subscriptions sets a limit, this is the lowest. `null` when no limit is set. Reaching it blocks the key with `monthly_billing_limit`. **trial**: Object
Only present for free-trial accounts. * **daily\_limit\_chars** (Integer or null): the daily character allowance shared across all endpoints. * **resets\_at** (String): always `utc_midnight`. A team-scoped key gets only `rate_limit`, `monthly_quota_chars` and `key_expires_at`, because `monthly_spend_limit_usd` and `trial` describe the personal account. ### Limits Sample Response[​](#limits-sample-response "Direct link to Limits Sample Response") A subscribed key with the default limits: ``` { "rate_limit": { "capacity_chars": 20000000, "window_seconds": 86400 }, "monthly_quota_chars": 50000000, "key_expires_at": null, "monthly_spend_limit_usd": null } ``` ## Errors[​](#errors "Direct link to Errors") Both endpoints return the same errors. | Status | When | | ------ | ---------------------------------------------------------------------------------------------- | | `401` | The key is missing or invalid: `{"msg": "Missing API key."}` or `{"msg": "Invalid API key."}`. | | `403` | The public demo key or an MCP OAuth access token was sent. | | `429` | The endpoint's own bucket is exhausted. Wait `retry_after` seconds. | See [Rate Limits & Errors](https://sapling.ai/docs/rate_limits.md) for the shared error format. --- # Advanced Edits Sapling provides customizable proofreading settings that go beyond regular spelling and grammar checking. These include suggestions around making text simpler and more confident, as well as edits around DEI. The Advanced Edits settings are configurable for your account ([here](https://sapling.ai/language_settings?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs)) as well as on a per API call level (documented below) because these suggestions may not be applicable to all styles of writing. Advanced Edits are currently only available for English. You can find a demo of the sort of suggestions Advanced Edits generates [here](https://sapling.ai/utilities/issue-highlighter?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs). #### Adverbs[​](#adverbs "Direct link to Adverbs") Adverbs can usually be replaced either with a stronger verb. He ran quickly towards the exit. -> He dashed towards the exit. #### Simplifications[​](#simplifications "Direct link to Simplifications") Consider replacing complex phrases with a simpler one with the same meaning. A number of people feel this way. -> Many people feel this way. #### Hard to read[​](#hard-to-read "Direct link to Hard to read") Sentences that are too long can be hard to read. Consider breaking them up for clarity. In the age of digital technology and social media, it's becoming increasingly important for individuals to be aware of their online presence and the impact that their actions and words can have on others. -> In the digital age, it's vital to be aware of how our online presence and actions can impact others. #### Passive Voice[​](#passive-voice "Direct link to Passive Voice") Sentences in the active voice are usually more concise and clear. The ball was kicked by him. -> He kicked the ball. #### Qualifiers[​](#qualifiers "Direct link to Qualifiers") Qualifiers lead to less confident communication. Consider removing them. I was wondering if we can meet tomorrow? -> Can we meet tomorrow? #### DEI[​](#dei "Direct link to DEI") Sapling breaks DEI into the following categories. Example of each are also given: * Gender Pronouns Prefer "they"/"them" over "he"/"him" * Gender Nouns Prefer "chairperson" over "chairman" * Gender Identity Prefer "transgender" over "transexual" * Disability Prefer "autistic" over "aspie" * Age Prefer "person born betwen 1946-1964" over "boomer" * Race Prefer "primary-secondary" over "master-slave" * Social Class Prefer "sex worker" over "prostitute" * Violence Prefer "situation room" over "war room" ## Advanced Edits POST[​](#advanced-edits-post "Direct link to Advanced Edits POST") ### Request Parameters[​](#request-parameters "Direct link to Request Parameters") `https://api.sapling.ai/api/v1/edits` HTTP method: `POST` The Advanced Edits API POST endpoint takes JSON parameters documented below: **key**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. **text**: String
Text to compute statistics for. **session\_id**: Optional String
Unique name or UUID of document or portion of text that is being processed. If not provided, defaults to current date in `YYYYMMDD` format. **advanced\_edits**: Dictionary
Advanced Edit Options Options for advanced edits. Option keys are `String`, and option values are `Boolean`. * `advanced_edits`: Group setting, covering all the options below * `adverbs` * `simplifications` * `hard_to_read` * `qualifiers` * `voice` * `dei`: Group setting, covering all DEI options below * `gender`: Group setting, covering `gender_pronoun`, `gender_noun`, and `gender_id` * `gender_pronoun` * `gender_noun` * `gender_id` * `sensitivity` * `disability` * `age` * `race` * `social_class` * `violence` A group setting marked `false` will disable all categories it covers. ### Response Parameters[​](#response-parameters "Direct link to Response Parameters") The Edits endpoint with `advanced_edits` specified returns JSON in the format of regular edits [link](https://sapling.ai/docs/api/edits-overview.md#response-parameters). ### Sample Code[​](#sample-code "Direct link to Sample Code") * cURL * JavaScript * Python ``` curl -X POST https://api.sapling.ai/api/v1/edits \ -H "Content-Type: application/json" \ -d '{ "key":"", "text":"The ball was kicked. Suddenly there was the sound of an aircraft.", "session_id": "test session", "advanced_edits": { "advanced_edits": true } }' ``` ``` import axios from 'axios'; async function run(text) { try { const response = await axios.post( 'https://api.sapling.ai/api/v1/edits', { key: '', session_id: 'test session', text, advanced_edits: { advanced_edits: true, }, }, ); const {status, data} = response; console.log({status}); console.log(JSON.stringify(data, null, 4)); } catch (err) { const { msg } = err.response.data; console.log({err: msg}); } } run('The ball was kicked. Suddenly there was the sound of an aircraft.'); ``` ``` import requests from pprint import pprint key = '' url = 'https://api.sapling.ai/api/v1/edits' data = { 'key': key, 'text': 'The ball was kicked. Suddenly there was the sound of an aircraft.', 'session_id': 'Test Document UUID', 'advanced_edits': { 'advanced_edits': True, }, } try: response = requests.post(url, json=data) if 200 <= response.status_code < 300: resp_json = response.json() edits = resp_json['edits'] pprint(edits) else: print('Error: ', str(response.status_code), response.text) except Exception as e: print('Error: ', e) ``` ### Sample Response[​](#sample-response "Direct link to Sample Response") ``` [ { "description": "Reduce the use of passive voice.", "end": 19, "error_type": "voice", "general_error_type": "Advanced Edit", "id": "81695ccc-2916-50ba-8b93-c3ed7bb55f54", "replacement": "", "sentence": "The ball was kicked.", "sentence_start": 0, "start": 9 }, { "description": "Reduce the use of adverbs.", "end": 8, "error_type": "adverbs", "general_error_type": "Advanced Edit", "id": "62cb63df-7c3d-52de-aab2-eded6924d689", "replacement": "", "sentence": "Suddenly there was the sound of an aircraft.", "sentence_start": 21, "start": 0 }, { "description": "Use simpler language where possible.", "end": 43, "error_type": "simplifications", "general_error_type": "Advanced Edit", "id": "a0367693-de21-524f-9a3e-abe7a62b46f6", "replacement": "plane", "sentence": "Suddenly there was the sound of an aircraft.", "sentence_start": 21, "start": 35 } ] ``` --- # Analysis The Analysis endpoints compute syntactic information about the input text. Outputs include: * Adverbs and other parts of speech of tokens; * Whether input sentences are in passive or active voice; * Whether input sentences are hard to read (`hard`) or very hard to read (`very_hard`); * Phrases that can be simplified (e.g., `utilize` -> `use`); ## Analysis POST[​](#analysis-post "Direct link to Analysis POST") ### Request Parameters[​](#request-parameters "Direct link to Request Parameters") `https://api.sapling.ai/api/v1/analysis_h1` HTTP method: `POST` The `analysis_h1` API POST endpoint takes JSON parameters documented below: **key**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. **text**: String
Text to compute analysis for. **session\_id**: Optional String
Unique name or UUID of document or portion of text that is being processed. If not provided, defaults to current date in `YYYYMMDD` format. ### Response Parameters[​](#response-parameters "Direct link to Response Parameters") The `analysis_h1` POST endpoint returns JSON of the following format: ``` { "adverbs": [ // Adverbs with word indices ["really", 9], ["so", 17], ... ], "hard_to_read": [ { "difficulty": "hard", "sentence": "A long sentence that is hard to read..." }, ... ], "simplifications": [ { "start": 373, // Character index "end": 382, "original": "utilize", "replacements": [ "use" ] }, ... ], "voice": [ { "sentence": "The ball was caught", "voice": "passive" }, ... ] } ```   --- # API Access Anyone can test out Sapling's API. To get started with the API, simply: 1. Register for a Sapling account [here](https://sapling.ai/user/register?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs). 2. Once you've registered and signed in, visit your Sapling [API settings dashboard](https://sapling.ai/api_settings?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs). 3. Click the Generate Key button under the "API" section of the settings pane. 4. Start using the API by following the API documentation. We recommend starting with the [Grammar Check API (Edits)](https://sapling.ai/docs/api/edits-overview.md) guide. The key starts a free trial that works as a sandbox: it is never charged, and almost every endpoint only reads the text you send. See [Sandbox & Testing](https://sapling.ai/docs/sandbox.md) for the trial limits, zero-cost health checks, and the few calls that change stored state. When making requests, you can authenticate by including your API key as a `key` parameter or by providing it as a bearer token in the `Authorization` header. If both are supplied, the `key` parameter takes precedence. A machine-readable [OpenAPI 3.1 specification](https://sapling.ai/docs/openapi.md) of the API is available at `https://api.sapling.ai/openapi.json`. Use it to import the API into Postman, generate a typed client in any language, or register Sapling endpoints as tools for an AI agent. ## Team API keys[​](#team-api-keys "Direct link to Team API keys") Team administrators can create and rotate team-scoped API keys in their team's settings. If the team already has an active paid API key, an administrator who does not personally subscribe to the API can create a replacement key using the eligible paying account behind an existing active team key. If no eligible paying account exists, creating a key still requires paid API access. API usage is charged to the account that owns the new key, which may differ from the administrator who created it. Check the billed account before sharing a team key or rotating production credentials. A team-scoped key can manage only its own team and the other teams in the same organization, and organization-level calls (such as creating teams or [organization reporting](https://sapling.ai/docs/api/team-reporting.md)) work only for that organization. It never carries superuser rights, even when the account that owns it is a superuser. To administer teams in another organization, use a personal key or a key issued for a team in that organization. The [superuser routes](https://sapling.ai/docs/api/superuser-management.md) need a superuser's personal key. When a member is removed from a team or organization, Sapling ends their personal API key if nothing else pays for their API access. That means no API, Pro, or Enterprise plan of their own, none through another team or organization, and no prepaid credit account. Requests with that key then return `402 Payment Required` with the [`key_expired`](https://sapling.ai/docs/api/account-status.md) reason. Team-scoped keys the member created keep working. If the member is added back later, they generate a new personal key. ## Prepaid API credits[​](#prepaid-api-credits "Direct link to Prepaid API credits") You can purchase prepaid API credits from the **Billing** section of the [API settings dashboard](https://sapling.ai/api_settings?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs#billing). One credit equals one US dollar, and API usage draws down the balance using the same per-character prices described on the [API pricing](https://sapling.ai/docs/api/pricing) page. The dashboard shows purchased, consumed, and remaining credits. Sapling sends a low-balance warning once you have used the configured share (shown as `alert_threshold_percent` in [Account Status](https://sapling.ai/docs/api/account-status.md)) of the credits bought since the last warning, so a top-up after a warning starts a fresh count. A positive prepaid balance can activate or reactivate API access without a metered subscription; when the balance is depleted, API requests return `402 Payment Required` until more credits are purchased. If a card payment on your API invoice fails, Sapling can switch the account to prepaid credits only. [Account Status](https://sapling.ai/docs/api/account-status.md) then reports `credits_only: true`, and API requests are served only while you have a positive prepaid balance. Buy credits to keep using the API, and [contact us](https://sapling.ai/contact?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs) once your card is fixed to go back to monthly billing. ### Automatic credit top-ups[​](#automatic-credit-top-ups "Direct link to Automatic credit top-ups") In the **Billing** section of [API settings](https://sapling.ai/api_settings?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs#billing), accounts with prepaid credits can optionally turn on **Automatic top-up**. Choose the balance threshold, the number of credits to add per top-up, and a monthly top-up limit. Review the terms and confirm the consent dialog before enabling it; automatic charges are not enabled by a credit purchase alone. Credit purchases securely save the payment method with Stripe for possible future top-ups. If you already have a usable payment method on file, you may be able to enable top-ups without another purchase. After your balance falls below the chosen threshold, eligible top-ups are processed periodically rather than during the API request itself. Failed payments or a missing usable payment method can disable automatic top-ups; review the dashboard to update your settings or payment method. The monthly limit caps the credits added automatically, not manual credit purchases. ## Monthly metered spend limit[​](#monthly-metered-spend-limit "Direct link to Monthly metered spend limit") For monthly usage billing, the **Spend limit** control in the **Billing** section of [API settings](https://sapling.ai/api_settings?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs#billing) lets you choose when metered API access should be paused. Enter `0` for **No limit** (the default), or set a whole-dollar limit of at least **$10**. You can change or remove the limit later. When metered usage reaches the limit, requests can return `402 Payment Required` until the limit is raised or a new billing cycle begins. If your account uses prepaid credits followed by metered billing, the limit applies only to the metered charges after credits run out, not to prepaid credit purchases. Prepaid-only accounts do not have this metered spend-limit control; the [automatic top-up limit](#automatic-credit-top-ups) separately caps automatic credit purchases. ## Payment-required responses[​](#payment-required-responses "Direct link to Payment-required responses") Authenticated API requests can return `402 Payment Required` when the API key has expired, the associated subscription is inactive, the account has reached its monthly billing limit, or its prepaid credit balance is depleted. These responses include a `Retry-After: 3600` header, where the value is the number of seconds clients should wait before trying again. The header is listed in `Access-Control-Expose-Headers`, so cross-origin browser clients can read it. Because resolving a `402` usually requires renewing access or updating billing settings, clients should inspect the response's `msg` field and avoid retrying continuously while the account remains inactive. One `402` is temporary. When a free-trial account uses up its daily character allowance, the block clears at the next UTC midnight. That response's `Retry-After` header and a numeric `retry_after` body field both give the seconds until the reset. To check a key's state without making a billable call, including the exact reason it is blocked, use [Account Status](https://sapling.ai/docs/api/account-status.md). See [Rate Limits & Errors](https://sapling.ai/docs/rate_limits.md) for every status code. The response body is JSON with a `msg` field describing the reason: ``` { "msg": "API credit balance depleted. Purchase more credits at https://sapling.ai/api_settings#billing." } ```
Production Key Trial development keys allow for processing of 50,000 characters every 24 hours. [Subscribe](https://sapling.ai/api-checkout) for production access and [usage-based pricing](https://sapling.ai/docs/api/pricing), or purchase [prepaid API credits](#prepaid-api-credits) to activate production access without a metered subscription. --- # API Reporting Sapling's API endpoints for retrieving API usage analytics, plus the per-request `return_usage` flag for seeing a request's own usage inline. ## Per-Request Usage[​](#per-request-usage "Direct link to Per-Request Usage") Every API-key-authenticated endpoint accepts an opt-in `return_usage` flag. When set, a successful JSON response additionally reports the usage this request submitted for metering, as a top-level `usage` field: ``` { "usage": {"characters": 1000} } ``` **return\_usage**: Optional Boolean
Pass `true` in the JSON request body. For GET and multipart (file upload) requests, pass it as a `?return_usage=true` query or form parameter — on the PDF/DOCX file endpoints it can also ride in the `jsonParams` part. Defaults to `false`. ``` curl -X POST https://api.sapling.ai/api/v1/classify \ -H "Content-Type: application/json" \ -d '{"key":"", "text":"I was charged twice.", "labels":["billing", "other"], "return_usage": true}' ``` `characters` is the count the request submitted for metering, before repeat-request deduplication (see below). It may therefore exceed what this request adds to your bill; use the [reporting endpoints](#api-usage-post) or your receipt for billed totals. It is counted per sentence for `/edits` and `/spellcheck`, once per **distinct** item of a batch `texts` request, and honors endpoint-specific metering (for example, `/seo` meters the page text). The 2.5× multiplier for Chinese, Japanese and Korean text is included, so CJK requests report more than their raw length. Requests that don't bill report `{"characters": 0}`. A few things to know: * The count is captured in the request itself, **before** the billing pipeline's repeat-request handling applies (see [Characters and Repeat Requests](https://sapling.ai/docs/api/pricing#characters-and-repeat-requests)), so it is an upper bound on what the request finally adds to your bill: text that was already billed recently is counted here but not re-charged. * `usage` is attached only to successful (2xx) JSON object responses. Error responses, responses whose body is not a JSON object, streamed responses, and responses that already carry a `usage` key (such as [`/account/status`](https://sapling.ai/docs/api/account-status.md) and the LLM completion endpoints' token usage) are returned unchanged. * The flag is advertised on every API-key-authenticated operation in [`GET /api/v1/openapi.json`](https://sapling.ai/docs/openapi.md), so generated SDKs and agents pick it up automatically. ## API Usage POST[​](#api-usage-post "Direct link to API Usage POST") A self-serve endpoint for retrieving aggregate API usage, cost, and quota information for the account that owns the calling API key. Usage is scoped to the account that owns the calling key: * For a **team-scoped** key, the response covers all of the team's active keys. * For a **user** key, the response covers all of that user's active keys. The endpoint returns **aggregates only**. It does not return per-call rows and does not support pagination or `limit`/`offset` parameters. No request text or content hashes are stored in, or returned by, this endpoint. Masked key IDs API keys are never returned in raw form. In every section of the response, each key is identified by a stable, masked ID of the form `****-`, where `` is the last four characters of the key and `` is the first eight hex characters of the SHA-256 hash of the key. The same key always maps to the same masked ID, and the ID is consistent across every section of the response (`by_api_key`, `daily_usage`, and `monthly_usage`). ### Request Parameters[​](#request-parameters "Direct link to Request Parameters") `https://api.sapling.ai/api/v1/reporting/api_usage` HTTP method: `POST` **key**: String
32-character API key. Can also be supplied as a `?key=` query parameter or via the `Authorization` header as a bearer token. If multiple are provided, the `key` parameter takes precedence. **start\_days\_back**: Optional Integer
Number of days back at which the reporting window starts (e.g. `7` starts the window one week ago). Defaults to the start of the current calendar month. **end\_days\_back**: Optional Integer
Number of days back at which the reporting window ends. Defaults to `0` (today, inclusive). Both `start_days_back` and `end_days_back` are validated as follows: * Each must be an integer, otherwise the endpoint returns HTTP `400`. * Each must be non-negative, otherwise the endpoint returns HTTP `400`. * `start_days_back` must be greater than or equal to `end_days_back`, otherwise the endpoint returns HTTP `400`. * The resolved window may not exceed 1 year, otherwise the endpoint returns HTTP `403`. The window is also clamped to the age of the account, so it will never start before the account was created. ### Sample Code[​](#sample-code "Direct link to Sample Code") * cURL * Python * JavaScript ``` curl -X POST https://api.sapling.ai/api/v1/reporting/api_usage \ -H "Content-Type: application/json" \ -d '{"key":"", "start_days_back": 30, "end_days_back": 0}' ``` ``` import requests from pprint import pprint try: response = requests.post( "https://api.sapling.ai/api/v1/reporting/api_usage", json={ "key": "", "start_days_back": 30, "end_days_back": 0, } ) if 200 <= response.status_code < 300: pprint(response.json()) else: print('Error: ', str(response.status_code), response.text) except Exception as e: print('Error: ', e) ``` ``` import { Client } from '@saplingai/sapling-js/client'; const client = new Client(''); const { data: usage } = await client.apiUsage({ start_days_back: 30, end_days_back: 0 }); console.log(usage.total_characters, usage.total_cost_usd, usage.by_endpoint); ``` The JavaScript client (`@saplingai/sapling-js` 1.0.54 and later) also has `apiQuotaUsage()`, `apiEndpointUsage()` and `apiUserActivity()` for the endpoints below. See [Usage and quota reporting](https://sapling.ai/docs/sdk/JavaScript/backend_documentation.md#usage-and-quota-reporting). ### Response Parameters[​](#response-parameters "Direct link to Response Parameters") JSON structure with aggregate usage, cost, and quota information for the resolved window. **start\_date** / **end\_date**: String (ISO date)
Inclusive start and end dates of the resolved reporting window. **total\_characters**: Integer
Total characters processed across the account during the window. **total\_cost\_usd**: Float
Cost of the usage in the window at list pricing, computed per (endpoint, month). See the [Pricing](https://sapling.ai/docs/api/pricing) page for list rates. **currency**: String
Currency of `total_cost_usd` and `by_endpoint[*].cost_usd` (e.g. `USD`). **by\_api\_key**: Object
Map keyed by masked key ID. Each value has the following fields: * **api\_key** (String): The masked key ID, e.g. `****abcd-1a2b3c4d`. * **tag** (String): The key's tag/label, if any. * **characters** (Integer): Characters processed by this key in the window. * **monthly\_limit** (Integer): Monthly character limit (`-1` means no limit). * **monthly\_usage** (Integer): Characters used in the current calendar month. * **remaining\_quota** (Integer or null): Remaining characters this month (`null` when there is no limit). * **quota\_exceeded** (Boolean): Whether the monthly limit has been exceeded. **daily\_usage**: Object
Map of masked key ID to a `{ "YYYY-MM-DD": }` object giving characters processed per day. **monthly\_usage**: Object
Map of masked key ID to a `{ "YYYY-MM": }` object giving characters processed per calendar month. **by\_endpoint**: Object
Map of endpoint name (e.g. `EDIT`) to `{ "characters": , "cost_usd": }`. **last\_updated**: String (ISO timestamp) or null
Timestamp of the most recent usage record in the window, or `null` if there is no usage in the window. **credit\_balance\_data**: Object
Your prepaid credit balance: the same object as `credits` in [Account Status](https://sapling.ai/docs/api/account-status.md). It is omitted for team-scoped keys, so a key shared across a team doesn't expose one person's balance. #### Sample Response[​](#sample-response "Direct link to Sample Response") ``` { "start_date": "2026-05-13", "end_date": "2026-06-12", "total_characters": 36000, "total_cost_usd": 0.9, "currency": "USD", "by_api_key": { "****abcd-1a2b3c4d": { "api_key": "****abcd-1a2b3c4d", "tag": "production", "characters": 20000, "monthly_limit": 1000000, "monthly_usage": 20000, "remaining_quota": 980000, "quota_exceeded": false }, "****wxyz-9f8e7d6c": { "api_key": "****wxyz-9f8e7d6c", "tag": "staging", "characters": 16000, "monthly_limit": -1, "monthly_usage": 16000, "remaining_quota": null, "quota_exceeded": false } }, "daily_usage": { "****abcd-1a2b3c4d": { "2026-06-10": 4000, "2026-06-11": 16000 }, "****wxyz-9f8e7d6c": { "2026-06-11": 16000 } }, "monthly_usage": { "****abcd-1a2b3c4d": { "2026-05": 0, "2026-06": 20000 }, "****wxyz-9f8e7d6c": { "2026-06": 16000 } }, "by_endpoint": { "EDIT": { "characters": 20000, "cost_usd": 0.5 }, "SPELLCHECK": { "characters": 16000, "cost_usd": 0.4 } }, "last_updated": "2026-06-11T17:06:15.416190", "credit_balance_data": { "enabled": false, "credits_only": false, "currency": "USD", "alert_threshold_percent": 80.0 } } ``` ## API Quota Usage POST[​](#api-quota-usage-post "Direct link to API Quota Usage POST") This endpoint allows users to get API usage for a given time period as well as check their current quota. ### Request Parameters[​](#request-parameters-1 "Direct link to Request Parameters") `https://api.sapling.ai/api/v1/reporting/api_quota_usage` HTTP method: `POST` **key**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. **start\_days\_back**: Optional Integer
Starting number of days ago (7 would consider usage starting 1 week ago). Defaults to `1`; `0` is also read as `1`, so the shortest window is yesterday and today. **end\_days\_back**: Optional Integer
Ending number of days ago (0 would mean up until current date). Defaults to `0`. ### Response Parameters[​](#response-parameters-1 "Direct link to Response Parameters") JSON structure with API usage reporting information. There may be additional metadata that is subject to change. ``` { "quota": , // Monthly character limit of the API key (-1 when there is none) "usage": , // Usage volume during time period "accepts": , // Suggestions accepted via the accept endpoint since the 1st of this month "ignores": , // Suggestions ignored via the reject endpoint since the 1st of this month "last_updated": , // Timestamp that usage information was last updated (Unix epoch seconds) } ``` `accepts` and `ignores` always cover the current calendar month, whatever window you request. ## API Endpoint Usage[​](#api-endpoint-usage "Direct link to API Endpoint Usage") This endpoint allows users to get API usage for each endpoint over a given time period. ### Request Parameters[​](#request-parameters-2 "Direct link to Request Parameters") `https://api.sapling.ai/api/v1/reporting/api_endpoint_usage` HTTP method: `POST` **key**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. **start\_days\_back**: Optional Integer
Starting number of days ago (7 would consider usage starting 1 week ago). Defaults to `6`. **end\_days\_back**: Optional Integer
Ending number of days ago (0 would mean up until current date). Defaults to `0`. **interval**: Optional String
Interval to report usage by. Can be `Daily`, `Weekly`, or `Monthly`. Defaults to `Daily`. ### Response Parameters[​](#response-parameters-2 "Direct link to Response Parameters") JSON structure with API endpoint usage reporting information. For each endpoint, e.g. `EDIT` or `SPELLCHECK`, the usage is reported for each interval range in the time period. ``` { "data": { "": { "": , ... } }, "last_updated": "" } ``` Example: ``` { "data": { "EDIT": { "0": 0, "1": 16000, "2": 0, "3": 0, }, "SPELLCHECK": { "0": 0, "1": 0, "2": 20000, "3": 0, } }, "last_updated": "2025-03-14T17:06:15.416190" } ``` ## API User Activity[​](#api-user-activity "Direct link to API User Activity") This endpoint allows users to get recorded user actions over a given time period. The current actions recorded are: * Edits shown * Edits accepted * Edits ignored Please note these require that the `accept` and `reject` API endpoints have been used. The endpoint also returns active users. ### Request Parameters[​](#request-parameters-3 "Direct link to Request Parameters") `https://api.sapling.ai/api/v1/reporting/api_user_activity` HTTP method: `POST` **key**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. **start\_days\_back**: Optional Integer
Starting number of days ago (7 would consider usage starting 1 week ago). Defaults to `6`. **end\_days\_back**: Optional Integer
Ending number of days ago (0 would mean up until current date). Defaults to `0`. ### Response Parameters[​](#response-parameters-3 "Direct link to Response Parameters") JSON structure with activity reporting information. ``` { "edits_shown": , "edits_accepted": , "edits_ignored": , "active_users": { "logged_in": , "anonymous": } } ``` --- # Applying Edits After you've sent the Sapling API text and gotten JSON edits in the response, how do you apply the edits to get updated text? The simplest way is to use the `auto_apply` argument. By setting this to true, the returned response will have an extra field, `applied_text`, that contains the text with the edits applied. However, you can also easily apply edits programmatically. ## Programmatically Applying Edits[​](#programmatically-applying-edits "Direct link to Programmatically Applying Edits") Recall the Edit data structure: ``` { "id": , // Opaque edit id, used to give feedback "sentence": , // Unedited sentence "sentence_start": , // Offset of sentence from start of text "start": , // Offset of edit start relative to sentence "end": , // Offset of edit end relative to sentence "replacement": , // Suggested replacement "error_type": , // Error type, see "Error Categories" "general_error_type": , // See "Error Categories" } ``` When programmatically applying edits, go in *reverse* start offset (`sentence_start + start`) order so changes don't affect the offsets of the remaining edits. For example, consider the sentence: `Lets go to the housee.` where Sapling returns the following list of edits: ``` [ { 'sentence_start': 0, 'start': 0, 'end': 4, 'replacement': "Let's", ... }, { 'sentence_start': 0, 'start': 15, 'end': 21, 'replacement': 'house', ... } ] ``` The simplest way to apply the edits to your text is in reverse order: 1. Replace characters `15-21` with `house`. 2. Replace characters `0-4` with `Let's`. If the characters for `Lets` are replaced before `housee`, the offsets for other edits would need to be updated. ## Sample Code[​](#sample-code "Direct link to Sample Code") We provide sample code below for applying edits. A few things to keep in mind: * The `edits` array is ordered by starting position, though we include logic below to ensure this is the case. * For some languages where assignment is by reference, you will want to create a copy of the original string before modifying it. - Python - JavaScript - PHP ``` text = str(text) edits = sorted(edits, key=lambda e: (e['sentence_start'] + e['start']), reverse=True) for edit in edits: start = edit['sentence_start'] + edit['start'] end = edit['sentence_start'] + edit['end'] if start > len(text) or end > len(text): print(f'Edit start:{start}/end:{end} outside of bounds of text:{text}') continue text = text[: start] + edit['replacement'] + text[end:] return text ``` ``` function apply_edits(text, edits) { text = text.slice(); const reversed = edits.sort((a, b) => b['sentence_start'] + b['start'] - a['sentence_start'] - a['start']); for (const edit of reversed) { const start = edit['sentence_start'] + edit['start']; const end = edit['sentence_start'] + edit['end']; if (start > text.length || end > text.length) { console.log(`Edit start:${start}/end:${end} outside of bounds of text:${text}`); continue; } text = text.slice(0, start) + edit['replacement'] + text.slice(end); } return text; } ``` ``` function cmp($a, $b) { return $b->sentence_start + $b->start - $a->sentence_start - $a->start; } function apply_edits($text, $edits) { usort($edits, 'cmp'); foreach($edits as $edit) { $start = $edit->sentence_start + $edit->start; $end = $edit->sentence_start + $edit->end; if ($start > strlen($text) or $end > strlen($text)) { echo 'Index out of range'; continue; } $text = substr($text, 0, $start) + $edit->replacement + substr($text, $end, null); } return $text; } ``` --- # Autocomplete Sapling's autocomplete provides predictions of the next few characters or words given the current context in a particular editable. The predictions are based on the previous text. Example: a possible completion for the context, `Let us know if `  might be `you need anything else`. [Try it out](https://sapling.ai/sdk-demo) You can easily integrate the autocomplete UI and functionality into your application using the [SDK](https://sapling.ai/docs/sdk.md). ## Request Completion POST[​](#request-completion-post "Direct link to Request Completion POST") ### Sample Code[​](#sample-code "Direct link to Sample Code") * cURL * JavaScript * Python ``` curl -X POST https://api.sapling.ai/api/v1/complete \ -H "Content-Type: application/json" \ -d '{ "key":"", "query":"Hi how are", "session_id": "test session", }' ``` ``` import axios from 'axios'; async function run(query) { try { const response = await axios.post( 'https://api.sapling.ai/api/v1/complete', { key: '', session_id: 'test session', query, }, ); const {status, data} = response; console.log({status}); console.log(JSON.stringify(data, null, 4)); } catch (err) { const { msg } = err.response.data; console.log({err: msg}); } } run('Hi how are'); ``` ``` import requests from pprint import pprint key = '' url = 'https://api.sapling.ai/api/v1/complete' data = { 'key': key, 'query': 'Hi how are', 'session_id': 'test session', } try: response = requests.post(url, json=data) if 200 <= response.status_code < 300: resp_json = response.json() edits = resp_json['edits'] pprint(edits) else: print('Error: ', str(response.status_code), response.text) except Exception as e: print('Error: ', e) ``` ### Sample Response[​](#sample-response "Direct link to Sample Response") ``` { "hash":"e3fffa5f-1f11-531e-8a8e-d9e758677e0c", "output":" you", "query":"Hi how are" } ``` ### Request Parameters[​](#request-parameters "Direct link to Request Parameters") `https://api.sapling.ai/api/v1/complete` HTTP method: `POST` JSON parameters: **key**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. **session\_id**: Optional String
Unique name or UUID of document or portion of text that is being checked. If not provided, defaults to current date in `YYYYMMDD` format. **query**: String
Text that should be autocompleted. ### Response Parameters[​](#response-parameters "Direct link to Response Parameters") The Autocomplete endpoint returns JSON with parameters documented below: **output**: String
Predicted completion. For example, for the query `Hi, how are`, the predicted completion should be `you` (with a leading space). **query**: String
Actual query used to generate completion (may be a truncated version of request query). **hash**: String (UUID)
Opaque ID of completion for use with accept event. ## Accept Completion POST[​](#accept-completion-post "Direct link to Accept Completion POST") Use this API endpoint to have Sapling adapt its system over time. Each suggested completion has an completion UUID. You can pass this information back to Sapling to indicate the completion was used. For each unique completion UUID, use the accept endpoint up to once. ### Request Parameters[​](#request-parameters-1 "Direct link to Request Parameters") `https://api.sapling.ai/api/v1/complete//accept` HTTP method: `POST` **\**: String (UUID)
ID of completion returned from a Completion POST. Here's a sample request body: ``` { "key": "", "context": { "query": "Hi how are", "completion": " you" }, "session_id": "Test Document UUID" } ``` Note that the `query` and `completion` arguments are required. ### Response Parameters[​](#response-parameters-1 "Direct link to Response Parameters") Will return error or `{"result": "success"}`. --- # Chunking Also refered to as **segmentation**, **chunking** text allows you to parallelize the processing of a piece of text or reduce it into pieces that fall under the length limit of a particular system (e.g., under the context length of a Large Language Model). The first step is to identify delimiters where the text can be chunked. For many use cases, this might be a double newline indicating the start of a new paragraph. In other instances, you may want chunks of roughly equal length; there you can instead chunk on the closest ending punctuation marker (e.g., `.`, `?`, `!`). If latency is critical for your use of Sapling, you'll definitely want to chunk longer documents into much shorter texts so that you can process them in parallel. Sapling also provides certain endpoints such as the AI detection endpoint that have a length limit though you may want to feed a piece of text with length exceeding that limit. What follows are some notes on how we would approach chunking, but contact us if you need help doing this. Levels: * At the highest level, you have a **corpus** of documents. You may have heard of Common Crawl as one such corpus of documents across the web, but there are also corpora based on just Wikipedia, or Reddit, or internal documents belonging to a corporation. * Beneath the corpus level, we have **documents**. Documents represent a cohesive piece of text and are a familiar concept--think Microsoft Word or Google Docs. For news or magazine publications, **article** may be a more accurate term than **document**. In some cases, it may be unclear if text should be grouped into one or many documents--e.g., in the case of book chapters--but regardless, in these cases it's straightforward to segment the text in either fashion. * Within a document, there is a greater variety of segments that may work best. We present one that's drawn from the HTML DOM standard: a document is composed of **sections**, where each section contains **headings** and **paragraphs**. The paragraphs are further grouped into **sentences**, which consist of **tokens**. Tokens can be words, or subwords/morphemes, or characters, or even longer text segments when lexicons are built using information-theoretic approaches. Hence we arrive at a structure that looks like the following (in JSON format): ``` { "corpus": [ { "title": "Test Document 1", "body": [ { "title": "Section 1", "body": [ { "heading": "Heading 1" }, { "paragraph": "Paragraph text" }, { "paragraph": "More paragraph text" } ] } ] } ] } ``` To help with the tasks above, Sapling offers endpoints for performing simple length-based chunking. Given an input text or HTML document, Sapling will break the text into blocks of length of most `max_length`. When splitting the text, the API follows the following preference stack: ``` page break > paragraph breaks > line breaks > tabs > punctuation > all other whitespace ``` Chunks don't overlap, and each delimiter stays at the end of the chunk before the split, so joining the chunks gives back the original text. If no preferred split point is found, the text is cut at exactly `max_length` characters. tip This endpoint is free of charge. ## Chunk Text POST[​](#chunk-text-post "Direct link to Chunk Text POST") ### Sample Code[​](#sample-code "Direct link to Sample Code") * cURL * Python * JavaScript SDK ``` curl -X POST https://api.sapling.ai/api/v1/ingest/chunk_text \ -H "Content-Type: application/json" \ -d '{"key": "", "text": "Here is one paragraph.\n\nHere is another.", "max_length": 25}' ``` info If you want to pretty-print JSON output so it's easier to read and you have Python installed, you can pipe command line outputs into `| python -m json.tool`. Example: `echo "{\"text\": \"Some text\"}" | python -m json.tool` ``` import requests from pprint import pprint try: response = requests.post( "https://api.sapling.ai/api/v1/ingest/chunk_text", json={ "key": "", "text": "Here is one paragraph.\n\nHere is another.", "max_length": 25 } ) if 200 <= response.status_code < 300: resp_json = response.json() chunks = resp_json['chunks'] pprint(chunks) else: print("Error: ", str(response.status_code), response.text) except Exception as e: print("Error: ", e) ``` ``` // npm install @saplingai/sapling-js (1.0.55 or later) import { Client } from '@saplingai/sapling-js/client'; const client = new Client(''); const { data } = await client.chunkText('Here is one paragraph.\n\nHere is another.', 25); console.log(data.chunks); ``` Pass `step_size` in the options argument, as in `client.chunkText(text, 25, { step_size: 5 })`. ### Request Parameters[​](#request-parameters "Direct link to Request Parameters") `https://api.sapling.ai/api/v1/ingest/chunk_text` HTTP method: `POST` **key**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. **text**: String
Text to chunk. **max\_length**: Integer
Maximum length of each chunk, in characters. Required: it must be a positive JSON integer, so a quoted number such as `"25"` returns a `400`. **step\_size**: Optional Integer
Size of window to look for split points. The larger the step size, the greater the variance in chunk sizes, but the higher the chance of splitting on a preferred split type (see preference stack above). Defaults to 10% of the text length. ### Response Parameters[​](#response-parameters "Direct link to Response Parameters") JSON with the field `chunks` containing a list of strings will be returned, representing the segmented text. For the sample request above: ``` { "chunks": [ "Here is one paragraph.\n\n", "Here is another." ] } ``` ## Chunk HTML POST[​](#chunk-html-post "Direct link to Chunk HTML POST") In the JavaScript SDK, use `client.chunkHtml(html, maxLength)`, which takes the same options as `chunkText()`. ### Request Parameters[​](#request-parameters-1 "Direct link to Request Parameters") `https://api.sapling.ai/api/v1/ingest/chunk_html` HTTP method: `POST` **key**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. **html**: String
HTML to extract text from and chunk. **max\_length**: Integer
Maximum length of each chunk, in characters. Required: it must be a positive JSON integer, so a quoted number such as `"25"` returns a `400`. **step\_size**: Optional Integer
Size of window to look for split points. The larger the step size, the greater the variance in chunk sizes, but the higher the chance of splitting on a preferred split type (see preference stack above). Defaults to 10% of the text length. ### Response Parameters[​](#response-parameters-1 "Direct link to Response Parameters") info This endpoint not only breaks up the HTML but also discards all HTML tags, resulting in plain text. Some HTML fields that you wish to keep may also be discarded; contact us if this is the case so we can better support your use case. JSON with the field `chunks` containing a list of strings will be returned, representing the segmented text contained within the HTML. ``` { "chunks": [ "First chunk", "Second chunk" ] } ``` --- # Text Classification API The classify endpoint sorts a piece of text into **labels you define** in the request — no training data, no per-customer model. Send the text together with 2–20 label names (optionally with a short description of each), and the endpoint returns the best-matching label, a score for every label, and a one-sentence rationale pointing at the evidence in the text. Two modes are supported: * **Single-label** (the default): exactly one label applies. The scores form a probability distribution over your labels (they sum to \~1) and `label` is the top one. * **Multi-label** (`multi_label: true`): zero, one or several labels may apply at once. Each label gets an independent 0–1 score, and `labels` lists every label at or above a `threshold` you control. It is built for support-ticket intent routing, topic tagging, lead qualification, content categorization and feedback bucketing. For fixed category sets, see the [sentiment](https://sapling.ai/docs/api/sentiment.md) and [tone](https://sapling.ai/docs/api/tone.md) endpoints. [Try it out](https://sapling.ai/utilities/text-classifier?utm_campaign=apidocs) ## Sample Code[​](#sample-code "Direct link to Sample Code") * cURL * JavaScript * Python * Python (Sapling client) ``` curl -X POST https://api.sapling.ai/api/v1/classify \ -H "Content-Type: application/json" \ -d '{"key":"", "text":"Hi, I was charged twice for my March invoice. Can you refund the duplicate payment?", "labels": ["billing", "technical issue", "shipping", "other"], "context": "Support tickets for a SaaS billing product"}' ``` ``` import axios from 'axios'; async function run(text) { try { const response = await axios.post( 'https://api.sapling.ai/api/v1/classify', { key: '', text, labels: ['billing', 'technical issue', 'shipping', 'other'], context: 'Support tickets for a SaaS billing product', }, ); const {status, data} = response; console.log({status}); console.log(JSON.stringify(data, null, 4)); } catch (err) { const msg = err.response?.data?.msg || err.message; console.log({err: msg}); } } run('Hi, I was charged twice for my March invoice. Can you refund the duplicate payment?'); ``` ``` import requests from pprint import pprint response = requests.post( "https://api.sapling.ai/api/v1/classify", json={ "key": "", "text": "Hi, I was charged twice for my March invoice. Can you refund the duplicate payment?", "labels": ["billing", "technical issue", "shipping", "other"], "context": "Support tickets for a SaaS billing product", } ) if 200 <= response.status_code < 300: pprint(response.json()) else: print('Error: ', response.status_code, response.text) ``` ``` from sapling import SaplingClient api_key = '' client = SaplingClient(api_key=api_key) text = 'Hi, I was charged twice for my March invoice. Can you refund the duplicate payment?' labels = [ {'name': 'billing', 'description': 'Charges, invoices, refunds and payment methods'}, {'name': 'technical issue', 'description': 'Bugs, errors, crashes and outages'}, {'name': 'shipping', 'description': 'Delivery status, addresses and tracking'}, {'name': 'other', 'description': 'Anything that does not fit the other labels'}, ] result = client.classify(text, labels, context='Support tickets for a SaaS billing product') print(result['label'], '|', result['rationale']) for entry in result['scores']: print(f"{entry['label']}: {entry['score']}") # Multi-label tagging: every label scoring >= threshold is returned in `labels` tags = client.classify( 'I was charged twice and the app crashes on launch', labels, multi_label=True, threshold=0.5, ) print(tags['labels']) # ['billing', 'technical issue'] ``` ## Sample Response[​](#sample-response "Direct link to Sample Response") ``` { "label": "billing", "labels": ["billing"], "scores": [ {"label": "billing", "score": 0.86}, {"label": "technical issue", "score": 0.07}, {"label": "shipping", "score": 0.04}, {"label": "other", "score": 0.03} ], "rationale": "The customer reports being charged twice on one invoice.", "multi_label": false } ``` With `"multi_label": true` and the text `"I was charged twice and the app crashes on launch"`, several labels can apply at once and the scores no longer need to sum to 1: ``` { "label": "billing", "labels": ["billing", "technical issue"], "scores": [ {"label": "billing", "score": 0.92}, {"label": "technical issue", "score": 0.81}, {"label": "shipping", "score": 0.03}, {"label": "other", "score": 0.02} ], "rationale": "Mentions a duplicate charge and an app crash.", "multi_label": true } ``` ## Batch Requests[​](#batch-requests "Direct link to Batch Requests") To classify many short texts — a queue of support tickets, a page of reviews — in one request, send `texts` (a list of 1–10 strings) instead of `text`. The same `labels`, `multi_label`, `threshold` and `context` apply to every item, and the combined length of all items may be up to 10,000 characters (the same cap as a single `text`). Exactly one of `text` and `texts` must be provided. ``` curl -X POST https://api.sapling.ai/api/v1/classify \ -H "Content-Type: application/json" \ -d '{"key":"", "texts": ["I was charged twice this month.", "Where is my package?"], "labels": ["billing", "shipping", "other"]}' ``` The batch response is `{"results": [...]}` with one entry per input, in input order; each entry has exactly the single-response shape above: ``` { "results": [ { "label": "billing", "labels": ["billing"], "scores": [ {"label": "billing", "score": 0.91}, {"label": "shipping", "score": 0.05}, {"label": "other", "score": 0.04} ], "rationale": "Reports a duplicate charge.", "multi_label": false }, { "label": "shipping", "labels": ["shipping"], "scores": [ {"label": "shipping", "score": 0.93}, {"label": "other", "score": 0.04}, {"label": "billing", "score": 0.03} ], "rationale": "Asks about a package's whereabouts.", "multi_label": false } ] } ``` Items are billed individually (a batch of N costs the same as N single requests), and each item is cached the same way as a single request — batches and single calls share the cache. If any item fails to classify, the whole request returns a `502` and nothing is billed; the items that did succeed are already cached, so a retry only re-runs the failures. ## Request Parameters[​](#request-parameters "Direct link to Request Parameters") **POST** to `https://api.sapling.ai/api/v1/classify` **key**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. **text**: String
The text to classify, up to 10,000 characters (measured on the raw input, before any HTML is stripped). Plain text or HTML — tags are stripped server-side. Text that is empty after stripping returns a `400`. The text is treated as untrusted data: instructions inside it are ignored and it is classified on its content alone. Provide exactly one of `text` and `texts`. **texts**: List\[String]
Batch form (see [Batch Requests](#batch-requests)): 1–10 texts to classify in one request, each treated exactly like `text` above, with a combined length of up to 10,000 characters. An item that is empty after stripping returns a `400` naming its index. The response becomes `{"results": [...]}`, one entry per item in input order. **labels**: List\[String | Object]
The set of labels to choose from: between 2 and 20 entries. Each entry is either a string (the label name) or an object `{"name": "...", "description": "..."}` where `description` is optional. Names are trimmed, internal whitespace is collapsed, and they must be at most 50 characters and case-insensitively unique; descriptions are at most 200 characters. Names are returned in this normalized form in the response, so match your application logic on the normalized names. A short description per label sharpens borderline decisions — see [Tips](#tips). **multi\_label**: Boolean, optional, defaults to false
`false`: exactly one label applies — scores are a probability distribution over the labels and `labels` is `[label]`. `true`: zero, one or several labels may apply — each label gets an independent 0–1 score and `labels` contains every label whose score is at least `threshold`. Non-boolean values return a `400`. **threshold**: Number, optional, defaults to 0.5
Multi-label cut-off between 0 and 1: a label is included in `labels` when `score >= threshold`. Ignored in single-label mode. Values outside 0–1 (or non-numbers) return a `400`. **context**: String, optional
Up to 500 characters describing what the texts are and how to decide between labels, for example `"Support tickets for a SaaS billing product; pick billing for anything about charges or refunds"`. Guidance only — it steers the decision but can never add a label outside `labels`. ## Response Parameters[​](#response-parameters "Direct link to Response Parameters") **label**: String
The best-matching label. Always one of the submitted label names (as normalized: trimmed, internal whitespace collapsed). **labels**: List\[String]
Single-label mode: `[label]`. Multi-label mode: every label whose score is at least `threshold`, in descending score order — this **may be empty**, which means none of the labels apply. **scores**: List\[Object]
Exactly one entry per submitted label, sorted by descending score (ties keep the model's pick first, then input order). Each has: * `label`: the label name. * `score`: 0–1, rounded to 4 decimals. In single-label mode the scores sum to \~1 (a probability distribution over the labels); in multi-label mode each is an independent applicability probability and they need not sum to 1. **rationale**: String
One sentence (at most 300 characters) naming the evidence in the text that drove the decision. May be an empty string. **multi\_label**: Boolean
Echo of the mode used for this request. ## Errors[​](#errors "Direct link to Errors") | Status | Meaning | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | Validation error — missing or oversized `text`, text empty after stripping, both or neither of `text`/`texts` provided, an invalid or over-length `texts` batch, or invalid `labels` (e.g. `{"msg": "Invalid labels: Needs between 2 and 20 labels."}`), `multi_label`, `threshold` or `context`. The body is `{"msg": "..."}`. | | `401` / `403` | Missing or invalid API key. | | `429` | Rate limit exceeded or key over capacity. | | `502` | `{"msg": "Unexpected error classifying text."}` — the classification model failed; safe to retry. Not billed and not cached. | ## Tips[​](#tips "Direct link to Tips") * **Describe your labels.** Plain names work, but a one-line `description` per label (what belongs in it, and what does not) noticeably improves borderline cases, especially when labels overlap (`billing` vs `account`) or are domain-specific jargon. * **Add an "other" label.** In single-label mode the endpoint always picks one of your labels, so include a catch-all (`other`, `unrelated`, `none of the above`) unless every text is guaranteed to fit one of your categories. * **Use `context`** to say what the texts are and how to decide — e.g. `"Inbound sales emails; pick qualified only when a budget or timeline is mentioned"`. This is usually the cheapest way to fix systematic mistakes. * **Multi-label for tagging, single-label for routing.** Use `multi_label: true` when a text can legitimately belong to several buckets (topic tags, feature areas) and `false` when you need exactly one decision (queue assignment, intent). * **Tune `threshold` from the scores.** Start at the default `0.5`; lower it to recall more tags, raise it for precision. Results are cached on Sapling's side for about three days keyed on the text, labels, mode and context — the threshold is applied on top, so re-running with a different threshold returns the same underlying scores. * Scores are calibrated guidance, not guarantees — for high-stakes automation, act on high-confidence results and route low-margin ones (top two scores close together) to a human.   --- # 5 Best Grammar and Spell Checking APIs / SDKs [Try the Sapling API](https://sapling.ai/docs/api/edits-overview.md)       [Try the Sapling SDK](https://sapling.ai/docs/sdk/overview.md) Short answer Five grammar and spell checking APIs are compared here: **Bing** (spell check only, Azure, <0.3s), **Ginger** (REST, English dialects, rich edit metadata), **LanguageTool** (20+ languages, self-hostable, <2s), **ProWritingAid** (detailed error categories, SDKs in five languages), and **Sapling** (learning-based, self-serve keys, error categories, self-hosting, \~1s). Which is best depends on your use case — see [Which solution is best?](#which-solution-is-best) and the [note on evaluation](#note-on-evaluation) before picking one. ## Grammar check APIs[​](#grammar-check-apis "Direct link to Grammar check APIs") Grammar and spell checkers have a long history as part of document processing applications. Today, simple systems exist in our browsers, email clients, and even our mobile keyboards. However, these systems tend not to go beyond basic spellchecking and autocorrect, and even then often have frustratingly low accuracy. Today, popular systems such as Grammarly, Microsoft Editor, and Sapling offer functionality that goes beyond the built-in spellcheck of most applications. These systems offer browser and desktop integrations and make inline recommendations for ease of use. Of course, it's impossible to integrate across all applications or provide a customized experience for each application. If a one-size-fits-all integration doesn't suit your application, you may consider using an application programming interface (API). These allow your application to interface with an existing grammar and spell checking system through a communication standard. If you Google "grammar check API", many esoteric results will come up. This article tries to summarize the most useful APIs. For now, this covers English grammar check APIs, though we also include multilingual offerings in the future (Sapling supports many languages, which you can find [here](https://sapling.ai/langs?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs)). ![Example API flow](/img/api-flow.svg) Example of grammar checking API flow with input query and output result. ## Application programming interfaces[​](#application-programming-interfaces "Direct link to Application programming interfaces") While APIs have a rich history, in this article we'll assume that an API exposes a set of web **endpoints** of a grammar application. Your application can make HTTP **requests** to these web endpoints in order to fetch the set of edits for a particular piece of text. note You may have heard of **REST** APIs. Sapling (and many other APIs) follow the REST style, but you don't need to know the details of REST to use these systems. For example, suppose your application has a text input in which one of your users types the text: `Helo world`. Your system uses a third-party API to retrieve edits. It sends the following JSON to a third-party POST endpoint: ``` { "query": "Helo world" } ``` It then gets back the following JSON in response: ``` { "edits": [ { "start": 0, "end": 4, "replacement": "Hello" }, { "start": 5, "end": 10, "replacement": "world." } ] } ``` These two edits fix the first misspelling and also add a missing period. The third-party service has detected all the edits you need. It's then up to your system to render the edits on your frontend to your user in whatever manner you see fit. info In case you're interested in [autocomplete](https://sapling.ai/docs/api/autocomplete.md) and [similarity/semantic search](https://sapling.ai/docs/api/semsearch.md), Sapling also offers APIs for those as well — please contact us. ## Software development kits[​](#software-development-kits "Direct link to Software development kits") Note that in addition to APIs, some systems also offer SDKs that can make it even easier to integrate their system. For example, Sapling offers an [SDK](https://sapling.ai/docs/sdk/overview.md) that allows developers to integrate Sapling with 5 lines of JavaScript. We'll save more on SDKs for a separate article. ## Building your own[​](#building-your-own "Direct link to Building your own") Before we discuss providers, why use a third-party API instead of building your own? For example, there are great libraries out there such as [Stanza](https://stanfordnlp.github.io/stanza/) for preprocessing of text, and also deep learning libraries such as [TensorFlow](https://tensorflow.org/) and [PyTorch](https://pytorch.org/) that allow you to train your own system, and even higher-level libraries if you've decided on a specific model. ![Tensorflow](/img/comp/tensorflow.png) ![Pytorch](/img/comp/pytorch.png)
There are a few reasons why this is challenging. 1. *Language is really complex*. For every scenario you might come up with where you think a certain edit is appropriate, there are dozens if not hundreds of variations. If you're using a heuristic-based approach, you're likely not considering many of these variations. If you're using a machine learning-based approach, you'll need lots of data. 2. It'll take engineers some time to set up and maintain the system, and *engineers are expensive*. So too are servers if you'll be using a machine learning-based system that requires lots of compute. It's quite likely that using an API will not only be more time-efficient, but also cost-efficient. 3. You and your team have other things to focus on. If grammar correction and natural language processing are not a core competency, it's likely best to *focus* on your system's specialized offerings instead. Buying is almost always cheaper than building. As you likely rent cloud infrastructure from AWS or Azure, so too should you try and offload other services. ## Providers[​](#providers "Direct link to Providers") As of this writing, here are some common grammar checkers/writing assistant tools that offer API access: * Bing * Ginger * LanguageTool * ProWritingAid * Sapling We'll use the following broad criteria when evaluating the different APIs: * **Overview**: What type of API is offered? Does it do both grammar and spell checking, or exclusively spell checking? * **Strengths**: What type of suggestions are given and what is the performance in terms of accuracy and recall? * **Latency**: How long does it take for these systems to make suggestions for a typical query? This will of course depend on the document size, but parallelization should allow for scaling to large documents with latency then being the primary bottleneck. * **Other features**: What other suggestions or information beyond the edits does the system provide? What are the language and deployment options? Let's first give a brief introduction to the different systems. ### Bing[​](#bing "Direct link to Bing") ![Bing](/img/comp/bing.png)
The Bing Spell Check API helps correct spelling and adjust slang. It's especially helpful for brands and names as it also uses the Bing Search API. Types of corrections include word breaks, slang, names, homonyms, and brands. You can find out more about the Bing API on the Microsoft website: ### Ginger[​](#ginger "Direct link to Ginger") ![Ginger](/img/comp/ginger.png)
Ginger's grammar check API allows users to embed the Ginger system into their own application. While light on details, their information page mentions that it is used to check millions of documents a month. Given that the Ginger API provides a different interface to the Ginger platform, it's possible to get a sense of the performance by installing one of Ginger's other integrations, for example for the browser. Ginger is one of the grammar checking services that has been around longest — it was founded since 2010 — so you may have already tried its services and wish to try the API. ### LanguageTool[​](#languagetool "Direct link to LanguageTool") ![LanguageTool](/img/comp/languagetool.png)
LanguageTool is another of the most popular grammar checking programs that offers grammar, spelling, and style suggestions. LanguageTool has support for over 20 languages, though certain languages have a greater number of suggestions available. Its API offering can be hosted on-premises. It also offers the ability to specify the rules that should and should not be applied as well as set dictionaries. ### ProWritingAid[​](#prowritingaid "Direct link to ProWritingAid") ![ProWritingAid](/img/comp/prowritingaid.png)
ProWritingAid offers a grammar and spell check API for the system that also powers its own product. It offers SDKs in several languages, including C#, JavaScript, Python, PHP, and Java. Similar to Ginger, ProWritingAid is a popular solution that has been available since 2012, so you may be a user and wish to use the API as well. In addition to grammar and spell checking, ProWritingAid also offers thesaurus and text tagging endpoints. ### Sapling[​](#sapling "Direct link to Sapling") ![Sapling](/img/logo.svg)
Sapling is the language model copilot for businesses. Its technology is based off of research in the Stanford AI lab. The most recently developed of the solutions described here, Sapling is specifically geared towards business teams such as customer support teams or inside sales teams. Sapling uses a learning-based approach to catch up to [60% more errors](https://sapling.ai/comp?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs) than other systems. Users can provision a test API key themselves right after signing up for an account. You can find out more about [Sapling's grammar check API](https://sapling.ai/docs/api/edits-overview.md) in the API documentation. ## Comparison[​](#comparison "Direct link to Comparison") We've included a table below summarizing some of the benefits and drawbacks of the different systems. | Provider | Overview | Strengths | Latency | Other Features | | ------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------ | ------------------------------------------------------- | | Bing | Available with Azure subscription. Only supports spell checking. | Highly scalable system, leverages Bing Search API, multilingual support. | <0.3 seconds | Market code customization in addition to language code. | | Ginger | REST API, English dialects. | Detailed metadata for edits. | ? | Synonym and vocabulary recommendations. | | LanguageTool | REST API, multiple languages. | Support for many languages, self-hosting options. | <2 seconds | Configurable rules and custom dictionaries. | | ProWritingAid | REST API, detailed error categories. | Detailed error categories, multi-language SDKs. | ? | Thesaurus, SDKs available, text tagging. | | Sapling | Machine learning-powered system designed for the enterprise. Self-serve. | Learning-based system that catches complex errors, self-hosting, multiple languages. | \~1 second | Error categories and SDK available. | Comparison of API providers. ## Which solution is best?[​](#which-solution-is-best "Direct link to Which solution is best?") The best solution depends on your use case. Since there are many considerations here, we won't make a recommendation besides to try out each. But please consider the next section on evaluation. ## Note on evaluation[​](#note-on-evaluation "Direct link to Note on evaluation") Sometimes evaluation criteria are obvious — for example, to evaluate the latency of a system you would submit text of varying length and record the wall-clock time elapsed. info Constructing a sizable evaluation dataset with examples from real-world usage is the best way to judge the performance of different systems. From talking to users, we've frequently seen poor practices when it comes to evaluating different systems for accuracy and recall. Oftentimes, users will start by entering intentional errors such as the following: > Helo howare u. > fdsafsdafdsa. It seems natural that a spelling and grammar checking system should flag these errors. This approach, however, favors strict approaches, such as those that use simple dictionaries and lookup tables — let's call these **classical approaches** — instead of approaches that learn based off of real-world data — we'll call these **learning-based approaches**. Learning-based approaches are not trained on intentional errors, but actual errors seen in practice, and therefore can perform worse than classical approaches on blatant errors such as the ones in the example above. However, if you consider actual usage, learning-based approaches tend to capture many more errors and provide more useful suggestions. We recommend constructing your own evaluation dataset of at least a few dozen sentences containing errors by collecting example sentences that you or others on your team have seen. These examples should also be representative of examples you expect in the future. This is the best way to ensure that you get a good estimate of the actual performance of the systems you're testing and also to avoid cherry picking of examples. You can read more about evaluation [here](https://sapling.ai/docs/api/evaluation.md). ## Conclusion[​](#conclusion "Direct link to Conclusion") We recommend that you try out all of the different APIs and see what best fits your use case. This is because the requirements for a [medical application](https://sapling.ai/utilities/medical-spellcheck?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs) differ greatly from a legal application, which differ greatly from a customer service application. Obviously, we're biased. Get started with Sapling's documentation: Or you can reach out to us here: [https://sapling.ai/contact](https://sapling.ai/contact?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs) We're happy to talk through the customizations required for your particular use case. If you don't have time for a call, you can give Sapling a try using one of our [prebuilt integrations](https://sapling.ai/integrations?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs).

Other tools we didn't mention? Please let us know: --- # Custom Mappings Custom Mappings can be used to enforce specific corrections or capitalization for the following purposes: * Brand voice: Ensure that a consistent, on-brand style is used in all outward communication. * Compliance: If there is a specific way to communicate an issue, or if certain terms should be flagged, custom mappings can help. * Other use cases: Company or industry-specific jargon, product names, or unusual capitalization. ## Custom Mapping GET[​](#custom-mapping-get "Direct link to Custom Mapping GET") ### Request Parameters[​](#request-parameters "Direct link to Request Parameters") ``` import requests key = '' url = f'https://api.sapling.ai/api/v1/custom_mapping?key={key}' try: resp = requests.get(url) if 200 <= resp.status_code < 300: resp_json = resp.json() print('Custom mapping: ', resp_json) else: print('Error: ', str(resp.status_code), resp.text) except Exception as e: print('Error: ', e) ``` `https://api.sapling.ai/api/v1/custom_mapping?key=` HTTP method: `GET` **\**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. ### Response Parameters[​](#response-parameters "Direct link to Response Parameters") JSON array of custom mapping entries under key `custom_mappings`. Custom mapping entry structure: ``` { "id": , // Opaque id, used for deletion "entry": , // Word to match "mapping": , // Word to suggest as replacement "description": , // Shown with the suggestion; "" or null when none "case_sensitive": // true or false "created_at": // e.g. "Wed, 07 Oct 2020 21:15:47 GMT" "updated_at": // e.g. "Wed, 07 Oct 2020 21:15:47 GMT" } ``` ## Custom Mapping POST[​](#custom-mapping-post "Direct link to Custom Mapping POST") ### Request Parameters[​](#request-parameters-1 "Direct link to Request Parameters") ``` import requests key = '' url = 'https://api.sapling.ai/api/v1/custom_mapping' data = { 'key': key, 'entry': 'foobazbar', 'mapping': 'foobarbaz', 'case_sensitive': False, } try: resp = requests.post(url, json=data) if 200 <= resp.status_code < 300: resp_json = resp.json() print('Entry: ', str(resp_json)) else: print('Error: ', str(resp.status_code), resp.text) except Exception as e: print('Error: ', e) ``` `https://api.sapling.ai/api/v1/custom_mapping` HTTP method: `POST` **key**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. **entry**: String
Word to match. There are currently a couple types of regular expression-like options: * `^` and `$` match the start and end of a sentence, respectively. Example: `^the` will only match `the` at the start of a sentence and can be used to enforce capitalization. * `#` will match a number; example: `Gate #` will match in `Boarding is at Gate 5`. **mapping**: String
Word to suggest for a match. You can use `#` in the resulting expression to substitute a number back in. **case\_sensitive**: Boolean
Whether match is case-sensitive or not. If not case-sensitive, lower case and title case will both match. Defaults to true. **description**: Optional String
The description will be shown when the edit is suggested to the end user. If a description field is specified, the user will not have the option to ignore the edit. ### Response Parameters[​](#response-parameters-1 "Direct link to Response Parameters") JSON, Created Custom Mapping Entry Custom Mapping Entry Structure: ``` { "id": , // Opaque id, used for deletion "entry": , // Word to match "mapping": , // Word to suggest as replacement "description": , // Shown with the suggestion; "" or null when none "case_sensitive": // true or false "created_at": // e.g. "Wed, 07 Oct 2020 21:15:47 GMT" "updated_at": // e.g. "Wed, 07 Oct 2020 21:15:47 GMT" } ``` ### Errors[​](#errors "Direct link to Errors") The API answers 400, with the reason in `msg`, when: * the account already has a mapping for `entry` (`Entry already exists.`) * `entry` and `mapping` are the same * `entry` contains more than two digits * `case_sensitive` is false but `entry` and `mapping` differ only in case, e.g. `iphone` → `iPhone`. Such a rule must be case-sensitive. ## Custom Mapping DELETE[​](#custom-mapping-delete "Direct link to Custom Mapping DELETE") ### Request Parameters[​](#request-parameters-2 "Direct link to Request Parameters") ``` import requests key = '' entry_id = '' url = f'https://api.sapling.ai/api/v1/custom_mapping/{entry_id}' data = { 'key': key, } try: resp = requests.delete(url, json=data) if 200 <= resp.status_code < 300: print('Success') else: print('Error: ', str(resp.status_code), resp.text) except Exception as e: print('Error: ', e) ``` `https://api.sapling.ai/api/v1/custom_mapping/` HTTP method: `DELETE` **\**: String (UUID)
ID of custom mapping. **key**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. ### Response Parameters[​](#response-parameters-2 "Direct link to Response Parameters") Empty, HTTP status code 204. # Custom Filters Custom Filters allow you to ignore specific edits that match defined patterns during the editing process. This is useful for suppressing certain types of corrections that you don't want to see suggested. ## Custom Filter GET[​](#custom-filter-get "Direct link to Custom Filter GET") ### Request Parameters[​](#request-parameters-3 "Direct link to Request Parameters") ``` import requests key = '' url = f'https://api.sapling.ai/api/v1/custom_filter?key={key}' try: resp = requests.get(url) if 200 <= resp.status_code < 300: resp_json = resp.json() print('Custom filters: ', resp_json) else: print('Error: ', str(resp.status_code), resp.text) except Exception as e: print('Error: ', e) ``` `https://api.sapling.ai/api/v1/custom_filter?key=` HTTP method: `GET` **\**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. ### Response Parameters[​](#response-parameters-3 "Direct link to Response Parameters") JSON array of custom filter entries under key `custom_filters`. Custom filter entry structure: ``` { "id": , // Opaque id, used for deletion "created_at": , // e.g. "Wed, 07 Oct 2020 21:15:47 GMT" "updated_at": , // e.g. "Wed, 07 Oct 2020 21:15:47 GMT" "input": , // Input text to match (can be empty string for wildcards) "output": , // Output text to match (can be empty string for wildcards) "case_sensitive": // true or false } ``` ## Custom Filter POST[​](#custom-filter-post "Direct link to Custom Filter POST") ### Request Parameters[​](#request-parameters-4 "Direct link to Request Parameters") ``` import requests key = '' url = 'https://api.sapling.ai/api/v1/custom_filter' data = { 'key': key, 'inp': 'Patient', 'out': 'The patient', 'case_sensitive': False, } try: resp = requests.post(url, json=data) if 200 <= resp.status_code < 300: resp_json = resp.json() print('Filter created: ', resp_json) else: print('Error: ', str(resp.status_code), resp.text) except Exception as e: print('Error: ', e) ``` `https://api.sapling.ai/api/v1/custom_filter` HTTP method: `POST` **key**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. **inp**: String
Input text to match. Can be empty string for wildcards. **out**: String
Output text to match. Can be empty string for wildcards. **case\_sensitive**: Boolean
Whether the filter should be case-sensitive. Defaults to true. ### Response Parameters[​](#response-parameters-4 "Direct link to Response Parameters") JSON, Created Custom Filter Entry Custom Filter Entry Structure: ``` { "id": , // Opaque id, used for deletion "created_at": , // e.g. "Wed, 07 Oct 2020 21:15:47 GMT" "updated_at": , // e.g. "Wed, 07 Oct 2020 21:15:47 GMT" "input": , // Input text to match "output": , // Output text to match "case_sensitive": // true or false } ``` ### Errors[​](#errors-1 "Direct link to Errors") The API answers 400, with the reason in `msg`, when: * `inp` and `out` are both blank after trimming whitespace * `inp` and `out` are the same * the account already has a filter with this `inp` and `out` (`Filter already exists.`) * `inp` contains more than two digits * `case_sensitive` is false but `inp` and `out` differ only in case, e.g. `apple` → `Apple`. Such a filter must be case-sensitive. ## Custom Filter DELETE[​](#custom-filter-delete "Direct link to Custom Filter DELETE") ### Request Parameters[​](#request-parameters-5 "Direct link to Request Parameters") ``` import requests key = '' filter_id = '' url = f'https://api.sapling.ai/api/v1/custom_filter/{filter_id}' data = { 'key': key, } try: resp = requests.delete(url, json=data) if 200 <= resp.status_code < 300: print('Success') else: print('Error: ', str(resp.status_code), resp.text) except Exception as e: print('Error: ', e) ``` `https://api.sapling.ai/api/v1/custom_filter/` HTTP method: `DELETE` **\**: String (UUID)
ID of custom filter to delete. **key**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. ### Response Parameters[​](#response-parameters-5 "Direct link to Response Parameters") Empty, HTTP status code 204. --- # AI Detector API Sapling's **AI detector API** computes the probability that a piece of text is AI-generated (sometimes called "AI slop"), as well as the probability that each constituent sentence and token is AI-generated. Use this AI detection API to flag machine-generated content in user submissions, marketplace listings, reviews, job applications, student work, and content pipelines — or as an AI slop detector API for identifying low-quality, machine-generated content. The system is trained to be able to handle LLMs from different vendors, such as OpenAI's GPT family of models, Google's Gemini models, Anthropic's Claude models, and the open-release Llama and Mistral models. It is also somewhat robust to small changes and noisy text. | AI detection API | At a glance | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Pricing** | **$0.005 per 1,000 characters** ($5 per million, about $0.025 for a 1,000-word document), down to $0.0025 at volume. Free trial, no credit card. See [API Pricing](https://sapling.ai/docs/api/pricing) | | **Endpoint** | `POST https://api.sapling.ai/api/v1/aidetect` | | **Returns** | Document score from 0 to 1, the fraction of the text that reads as AI-generated, per-sentence scores with offsets, per-token probabilities, and an optional HTML heatmap | | **Input limits** | Up to 200,000 characters per request; at least 300 characters recommended | | **Languages** | English, Spanish, Portuguese, French, German, Italian, Dutch, Japanese, Polish, Chinese, Arabic, Russian, Swedish, Korean, Turkish and Romanian, detected automatically (see [Languages](#languages)) | | **SDKs** | [Python](https://sapling.ai/docs/sdk/Python/documentation.md), [JavaScript](https://sapling.ai/docs/sdk/JavaScript/ai_detect_quickstart.md) | [Run Detector](https://sapling.ai/utilities/ai-content-detector?utm_campaign=apidocs) Accuracy and Trade-offs All AI detection systems have false positives and false negatives. In some cases, small modifications to AI-generated text can cause that text to no longer be flagged as AI-generated. In other cases, human-written (but perhaps rote) text can be misclassified as AI-generated. Please do not interpret this as conclusive belief that your text is AI slop. Depending on the application, false positives or false negatives may be less desirable. Contact us for ways to adjust for your use case. ## Quickstart[​](#quickstart "Direct link to Quickstart") 1. [Register for a Sapling account](https://sapling.ai/user/register?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs) and generate a key from your [API settings dashboard](https://sapling.ai/api_settings?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs). See [API Access](https://sapling.ai/docs/api/api-access.md) for the full walkthrough. 2. `POST` your text to `https://api.sapling.ai/api/v1/aidetect` with your key, using one of the samples below. 3. Read `score` from the response — closer to `1` means more confidence the text is AI-generated. Read `ai_fraction` to see how much of a document reads as AI-generated (useful when only part of it is), and use `segments`, `sentence_scores` or `token_probs` to show *where* in the text that comes from. `verdict` sums the result up as `human`, `mixed` or `ai`, and `low_confidence` tells you when to hedge it. ## Sample Code[​](#sample-code "Direct link to Sample Code") * cURL * JavaScript * Python * Python SDK ``` curl -X POST https://api.sapling.ai/api/v1/aidetect \ -H "Content-Type: application/json" \ -d '{"key":"", "text":"This is sample text."}' ``` ``` import axios from 'axios'; async function run(text) { try { const response = await axios.post( 'https://api.sapling.ai/api/v1/aidetect', { key: '', text, }, ); const {status, data} = response; console.log({status}); console.log(JSON.stringify(data, null, 4)); } catch (err) { const { msg } = err.response.data; console.log({err: msg}); } } run('This is sample text'); // replace with the text you want to analyze ``` ``` import requests from pprint import pprint response = requests.post( "https://api.sapling.ai/api/v1/aidetect", json={ "key": "", "text": "This is sample text." } ) if 200 <= response.status_code < 300: pprint(response.json()) else: print('Error: ', response.status_code, response.text) ``` ``` # pip: python -m pip install sapling-py # uv: uv add sapling-py from sapling import SaplingClient from pprint import pprint api_key ='' client = SaplingClient(api_key=api_key) detection_scores = client.aidetect('This is sample text.', sent_scores=True) pprint(detection_scores) ``` AI Detector UI integration Sapling's Javascript SDK provides a complete end-to-end UI integration for AI content detection capabilities. Head over to our **[AI Detect JavaScript Quickstart ](https://sapling.ai/docs/sdk/JavaScript/ai_detect_quickstart.md)**for more details. ## AI Detector POST[​](#ai-detector-post "Direct link to AI Detector POST") ### Request Parameters[​](#request-parameters "Direct link to Request Parameters") `https://api.sapling.ai/api/v1/aidetect` HTTP method: `POST` The AI Detector API POST endpoint takes JSON parameters documented below: **key**: String
32-character API key. Can also be supplied via the Authorization header as a bearer token; if both are provided, the `key` parameter takes precedence. **text**: String
Text to run detection on. The limit is currently **200,000 characters**. If latency is high or requests time out, we recommend adapting [this script](https://github.com/saplingai/sapling-samples/blob/master/python/scripts/get_ai_detection.py). Please contact us if you need to run the system on longer inputs. We can also provide suggestions on how to chunk your text into smaller pieces and then combine detection results. Supply **plain text**, not HTML markup, in the `text` field. The API analyzes the string as provided; literal tags and encoded entities count as input text. For a `contenteditable` element, send its rendered `innerText`; for a ` ``` --- # Flagging Issues in Text Sapling's API and SDK can be used in a variety of different ways to process text and automatically flag issues. These can range from grammatical mistakes to making writing more confident, concise, or inclusive. We list some of the issues that you can flag in your text as part of a processing pipeline, or integrated into an application that acts as an AI writing assistant for your users. To get started, you'll need to generate an API key following the steps [here](https://sapling.ai/docs/api/api-access.md). ## Contents[​](#contents "Direct link to Contents") 1. [Spell Checking](#spell-checking) 2. [Grammar Issues](#grammar-issues) 3. [Advanced Edits](#advanced-edits) 4. [AI Content Detection](#ai-content) 5. [Tone Issues](#tone) 6. [Diversity, Equity and Inclusion (DEI)](#diversity-equity-and-inclusion-dei) ## Spell Checking[​](#spell-checking "Direct link to Spell Checking") Spell checking is the quickest and cheapest API endpoint for flagging issues in text. You can check this page to see which languages are supported: [/docs/api/spellcheck](https://sapling.ai/docs/api/spellcheck.md). If you are looking to add spell checking functionality to a website or web application, you can use the [JavaScript SDK](https://sapling.ai/docs/sdk/JavaScript/quickstart.md#getting-edits). #### Sample Code[​](#sample-code "Direct link to Sample Code") ``` import requests key = '' url = 'https://api.sapling.ai/api/v1/spellcheck' data = { 'key': key, 'text': 'Here is a recomendation.', 'session_id': 'Test Document UUID', } resp = requests.post(url, json=data) if 200 <= resp.status_code < 300: resp_json = resp.json() print('Edits: ', resp_json['edits']) else: print('Error: ', str(resp.status_code), resp.text) ``` #### Sample Output[​](#sample-output "Direct link to Sample Output") ``` [{ "id": "c7a85578-2391-5d9e-81b5-fc5c1574d07a", "replacement": "recommendation", "sentence": "Here is a recomendation.", "sentence_start": 0, "start": 10, "end": 23 }] ``` ## Grammar Issues[​](#grammar-issues "Direct link to Grammar Issues") Sapling can help suggest edits around grammatical errors and ensure that your writing is idiomatic and fluent. Check [http://sapling.ai/docs/api/edits-overview](https://sapling.ai/docs/api/edits-overview.md) to see which languages are supported. If you are looking to add grammar checking functionality to a website or web application, you can use the [JavaScript SDK](https://sapling.ai/docs/sdk/JavaScript/quickstart.md#getting-edits). #### Sample Code[​](#sample-code-1 "Direct link to Sample Code") ``` import requests key = '' url = 'https://api.sapling.ai/api/v1/edits' data = { 'key': key, 'text': 'Lets get started!', 'session_id': 'Test Document UUID', } resp = requests.post(url, json=data) if 200 <= resp.status_code < 300: resp_json = resp.json() print('Edits: ', resp_json['edits']) else: print('Error: ', str(resp.status_code), resp.text) ``` #### Sample Output[​](#sample-output-1 "Direct link to Sample Output") ``` [{ "error_type": "R:OTHER", "general_error_type": "Other", "id": "aa5ee291-a073-5146-8ebc-c9c899d01278", "replacement": "Let's", "sentence": "Lets get started!", "sentence_start": 0, "start": 0 "end": 4, }] ``` ## Advanced Edits[​](#advanced-edits "Direct link to Advanced Edits") This is a category of writing suggestions that go beyond regular grammatical correctness. Advanced Edits are a set of more opionated recommendations for effective written communication. These suggestions may make more sense applied to a press release or a business email compared to a creative novel. Below is a list of configurable advanced edits categories and corresponding examples: #### Adverbs[​](#adverbs "Direct link to Adverbs") Adverbs can usually be replaced either with a stronger verb. He ran quickly towards the exit. -> He dashed towards the exit. #### Simplifications[​](#simplifications "Direct link to Simplifications") Consider replacing complex phrases with a simpler one with the same meaning. A number of people feel this way. -> Many people feel this way. #### Hard to read[​](#hard-to-read "Direct link to Hard to read") Sentences that are too long can be hard to read. Consider breaking them up for clarity. In the age of digital technology and social media, it's becoming increasingly important for individuals to be aware of their online presence and the impact that their actions and words can have on others. -> In the digital age, it's vital to be aware of how our online presence and actions can impact others. #### Passive Voice[​](#passive-voice "Direct link to Passive Voice") Sentences in the active voice are usually more concise and clear. The ball was kicked by him. -> He kicked the ball. #### Qualifiers[​](#qualifiers "Direct link to Qualifiers") Qualifiers lead to less confident communication. Consider removing them. I was wondering if we can meet tomorrow? -> Can we meet tomorrow? You can find a demo of advanced edits [here](https://sapling.ai/utilities/issue-highlighter?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs). * cURL * JavaScript * Python ``` curl -X POST https://api.sapling.ai/api/v1/edits \ -H "Content-Type: application/json" \ -d '{ "key":"", "text":"The ball was kicked. Suddenly there was the sound of an aircraft.", "session_id": "test session", "advanced_edits": { "advanced_edits": true } }' ``` ``` import axios from 'axios'; async function run(text) { try { const response = await axios.post( 'https://api.sapling.ai/api/v1/edits', { key: '', session_id: 'test session', text, advanced_edits: { advanced_edits: true, }, }, ); const {status, data} = response; console.log({status}); console.log(JSON.stringify(data, null, 4)); } catch (err) { const { msg } = err.response.data; console.log({err: msg}); } } run('The ball was kicked. Suddenly there was the sound of an aircraft.'); ``` ``` import requests from pprint import pprint key = '' url = 'https://api.sapling.ai/api/v1/edits' data = { 'key': key, 'text': 'The ball was kicked. Suddenly there was the sound of an aircraft.', 'session_id': 'Test Document UUID', 'advanced_edits': { 'advanced_edits': True, }, } try: response = requests.post(url, json=data) if 200 <= response.status_code < 300: resp_json = response.json() edits = resp_json['edits'] pprint(edits) else: print('Error: ', str(response.status_code), response.text) except Exception as e: print('Error: ', e) ``` ### Sample Response[​](#sample-response "Direct link to Sample Response") ``` [ { "description": "Reduce the use of passive voice.", "end": 19, "error_type": "voice", "general_error_type": "Advanced Edit", "id": "81695ccc-2916-50ba-8b93-c3ed7bb55f54", "replacement": "", "sentence": "The ball was kicked.", "sentence_start": 0, "start": 9 }, { "description": "Reduce the use of adverbs.", "end": 8, "error_type": "adverbs", "general_error_type": "Advanced Edit", "id": "62cb63df-7c3d-52de-aab2-eded6924d689", "replacement": "", "sentence": "Suddenly there was the sound of an aircraft.", "sentence_start": 21, "start": 0 }, { "description": "Use simpler language where possible.", "end": 43, "error_type": "simplifications", "general_error_type": "Advanced Edit", "id": "a0367693-de21-524f-9a3e-abe7a62b46f6", "replacement": "plane", "sentence": "Suddenly there was the sound of an aircraft.", "sentence_start": 21, "start": 35 } ] ``` ## AI Content[​](#ai-content "Direct link to AI Content") The AI Content detector can be used to flag sentences or sections of text that were likely to have been generated by an AI language model. Depending on how the text is being used, AI content may not be allowed for legal, educational or regulatory reasons. Using an AI content detector can help reduce the costs of detecting such content. Details on the [AI detection API](https://sapling.ai/docs/api/detector.md) can be found in the API documentation. #### Sample Code[​](#sample-code "Direct link to Sample Code") ``` import requests from pprint import pprint key = '' url = 'https://api.sapling.ai/api/v1/aidetect' data = { 'key': key, 'text': 'I am an artificial intelligence system designed to help people solve complex problems. My capabilities include natural language processing, machine learning, and predictive analytics.', } try: response = requests.post(url, json=data) if 200 <= response.status_code < 300: resp_json = response.json() pprint(resp_json) else: print('Error: ', str(response.status_code), response.text) except Exception as e: print('Error: ', e) ``` #### Sample Output[​](#sample-output "Direct link to Sample Output") ``` { "score": 0.9989707556330055, "ai_fraction": 1.0, "verdict": "ai", "segments": [ { "start": 0, "end": 183, "score": 0.985 } ], "low_confidence": true, "low_confidence_reasons": ["short_text"], "sentence_scores": [ { "score": 0.9764397893790885, "sentence": "I am an artificial intelligence system designed to help people solve complex problems.", "start": 0, "end": 86 }, { "score": 0.9923806397189778, "sentence": "My capabilities include natural language processing, machine learning, and predictive analytics.", "start": 87, "end": 183 } ], "text": "I am an artificial intelligence system designed to help people solve complex problems. My capabilities include natural language processing, machine learning, and predictive analytics." } ``` ## Tone[​](#tone "Direct link to Tone") Tone analysis is done on an overall level as well as on a per sentence level. We flag negative passages of text that could be interpreted negatively for review. If you or your users want to avoid coming off as angry or disapproving, this endpoint can help. More details on the tone api and all the tones classified can be found [here](https://sapling.ai/docs/api/tone.md). Here is an example of how the Tone API is used in the Sapling browser extension. Note how the negative sentence is highlighted. ![](/img/sdk/tone_ui1.png) This is an example of another UI component from the Sapling tone checker. You can display the overal analyzed tone of a piece of text. ![](/img/sdk/tone_ui2.png) #### Sample Code[​](#sample-code "Direct link to Sample Code") ``` import requests key = '' url = 'https://api.sapling.ai/api/v1/tone' data = { 'key': key, 'text': 'You are amazing', } resp = requests.post(url, json=data) if 200 <= resp.status_code < 300: print(resp.json()) else: print('Error: ', str(resp.status_code), resp.text) ``` #### Sample Output[​](#sample-output "Direct link to Sample Output") ``` { "overall": [ [0.8885115385055542, "admiring", "😲"], [0.06413709372282028, "excited", "😀"], [0.02678699605166912, "approving", "👍"] ], "results": [ [ [0.8885115385055542, "admiring", "😲"], [0.06413709372282028, "excited", "😀"], [0.02678699605166912, "approving", "👍"] ] ], "sents": ["You are amazing"] } ``` ## Diversity, Equity and Inclusion (DEI)[​](#diversity-equity-and-inclusion-dei "Direct link to Diversity, Equity and Inclusion (DEI)") When writing in a way that is "DEI", we want to respect the linguistic viewpoints and cultures of different people. Inclusion in language refers to treating people with respect and making them feel included. While there is no absolute standard for DEI language, we can always avoid using certain terms that are considered racist or derogatory towards disadvantaged groups of people. Sapling breaks DEI into the following categories. Example of each are also given: * Gender Pronouns Prefer "they"/"them" over "he"/"him" * Gender Nouns Prefer "chairperson" over "chairman" * Gender Identity Prefer "transgender" over "transexual" * Disability Prefer "autistic" over "aspie" * Age Prefer "person born betwen 1946-1964" over "boomer" * Race Prefer "primary-secondary" over "master-slave" * Social Class Prefer "sex worker" over "prostitute" * Violence Prefer "situation room" over "war room" You can fine-tune your DEI settings in the language settings dashboard here: [https://sapling.ai/language\_settings](https://sapling.ai/language_settings?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs). A demo of DEI checking can be found [here](https://sapling.ai/utilities/issue-highlighter?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs). #### Sample Code[​](#sample-code "Direct link to Sample Code") ``` import requests key = '' url = 'https://api.sapling.ai/api/v1/edits' data = { 'key': key, 'text': 'This is the master bedroom.', 'session_id': 'Test Document UUID', 'advanced_edits': { 'dei': True, }, } try: resp = requests.post(url, json=data) if 200 <= resp.status_code < 300: resp_json = resp.json() edits = resp_json['edits'] print('Edits: ', edits) else: print('Error: ', str(resp.status_code), resp.text) except Exception as e: print('Error: ', e) ``` #### Sample Output[​](#sample-output "Direct link to Sample Output") ``` [ { "description": "Use more inclusive language where possible.", "end": 18, "error_type": "dei", "general_error_type": "Advanced Edit", "id": "fa409ba8-a51c-5d9e-b007-1bde1ac6183a", "replacement": "primary", "sentence": "This is the master bedroom.", "sentence_start": 0, "start": 12 } ] ``` --- # Migrating from the Grammarly Text Editor SDK warning Important: The Grammarly Text Editor SDK will no longer be updated and will be deprecated on January 10, 2024. We suggest removing the integration from your app or website before that date. - [Grammarly](https://developer.grammarly.com/sdk-deprecation) The Grammarly Text Editor SDK will be discontinued on January 10, 2024 [(source)](https://developer.grammarly.com/sdk-deprecation). Current Grammarly for Developers applications will function normally until the discontinuation date, new registrations are halted, and developers with recent registrations have until July 26, 2023, to create new apps with the SDK. ## Grammarly SDK alternative[​](#grammarly-sdk-alternative "Direct link to Grammarly SDK alternative") This is a quick guide for developers using the Grammarly SDK who are interested in maintaining spelling or grammar check functionality in their web applications. The functionality of Sapling's AI Writing Assistant can be included in any application as a drop-in replacement for the Grammarly SDK. The AI-powered Sapling SDK offers not only spelling and grammar checking, but also additional features such as tone analysis, AI content detection, context-aware suggestions, multilingual support, and much more. If you're looking for a Grammarly SDK alternative, this guide will help you make the transition. # API Access Anyone can test out Sapling's API. To get started with the API, simply: 1. Register for a Sapling account [here](https://sapling.ai/user/register?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs). 2. Once you've registered and signed in, visit your Sapling [API settings dashboard](https://sapling.ai/api_settings?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs). 3. Click the Generate Key button under the "API" section of the settings pane. 4. Start using the API by following the API documentation. We recommend starting with the [Grammar Check API (Edits)](https://sapling.ai/docs/api/edits-overview.md) guide. The key starts a free trial that works as a sandbox: it is never charged, and almost every endpoint only reads the text you send. See [Sandbox & Testing](https://sapling.ai/docs/sandbox.md) for the trial limits, zero-cost health checks, and the few calls that change stored state. When making requests, you can authenticate by including your API key as a `key` parameter or by providing it as a bearer token in the `Authorization` header. If both are supplied, the `key` parameter takes precedence. A machine-readable [OpenAPI 3.1 specification](https://sapling.ai/docs/openapi.md) of the API is available at `https://api.sapling.ai/openapi.json`. Use it to import the API into Postman, generate a typed client in any language, or register Sapling endpoints as tools for an AI agent. ## Team API keys[​](#team-api-keys "Direct link to Team API keys") Team administrators can create and rotate team-scoped API keys in their team's settings. If the team already has an active paid API key, an administrator who does not personally subscribe to the API can create a replacement key using the eligible paying account behind an existing active team key. If no eligible paying account exists, creating a key still requires paid API access. API usage is charged to the account that owns the new key, which may differ from the administrator who created it. Check the billed account before sharing a team key or rotating production credentials. A team-scoped key can manage only its own team and the other teams in the same organization, and organization-level calls (such as creating teams or [organization reporting](https://sapling.ai/docs/api/team-reporting.md)) work only for that organization. It never carries superuser rights, even when the account that owns it is a superuser. To administer teams in another organization, use a personal key or a key issued for a team in that organization. The [superuser routes](https://sapling.ai/docs/api/superuser-management.md) need a superuser's personal key. When a member is removed from a team or organization, Sapling ends their personal API key if nothing else pays for their API access. That means no API, Pro, or Enterprise plan of their own, none through another team or organization, and no prepaid credit account. Requests with that key then return `402 Payment Required` with the [`key_expired`](https://sapling.ai/docs/api/account-status.md) reason. Team-scoped keys the member created keep working. If the member is added back later, they generate a new personal key. ## Prepaid API credits[​](#prepaid-api-credits "Direct link to Prepaid API credits") You can purchase prepaid API credits from the **Billing** section of the [API settings dashboard](https://sapling.ai/api_settings?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs#billing). One credit equals one US dollar, and API usage draws down the balance using the same per-character prices described on the [API pricing](https://sapling.ai/docs/api/pricing) page. The dashboard shows purchased, consumed, and remaining credits. Sapling sends a low-balance warning once you have used the configured share (shown as `alert_threshold_percent` in [Account Status](https://sapling.ai/docs/api/account-status.md)) of the credits bought since the last warning, so a top-up after a warning starts a fresh count. A positive prepaid balance can activate or reactivate API access without a metered subscription; when the balance is depleted, API requests return `402 Payment Required` until more credits are purchased. If a card payment on your API invoice fails, Sapling can switch the account to prepaid credits only. [Account Status](https://sapling.ai/docs/api/account-status.md) then reports `credits_only: true`, and API requests are served only while you have a positive prepaid balance. Buy credits to keep using the API, and [contact us](https://sapling.ai/contact?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs) once your card is fixed to go back to monthly billing. ### Automatic credit top-ups[​](#automatic-credit-top-ups "Direct link to Automatic credit top-ups") In the **Billing** section of [API settings](https://sapling.ai/api_settings?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs#billing), accounts with prepaid credits can optionally turn on **Automatic top-up**. Choose the balance threshold, the number of credits to add per top-up, and a monthly top-up limit. Review the terms and confirm the consent dialog before enabling it; automatic charges are not enabled by a credit purchase alone. Credit purchases securely save the payment method with Stripe for possible future top-ups. If you already have a usable payment method on file, you may be able to enable top-ups without another purchase. After your balance falls below the chosen threshold, eligible top-ups are processed periodically rather than during the API request itself. Failed payments or a missing usable payment method can disable automatic top-ups; review the dashboard to update your settings or payment method. The monthly limit caps the credits added automatically, not manual credit purchases. ## Monthly metered spend limit[​](#monthly-metered-spend-limit "Direct link to Monthly metered spend limit") For monthly usage billing, the **Spend limit** control in the **Billing** section of [API settings](https://sapling.ai/api_settings?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs#billing) lets you choose when metered API access should be paused. Enter `0` for **No limit** (the default), or set a whole-dollar limit of at least **$10**. You can change or remove the limit later. When metered usage reaches the limit, requests can return `402 Payment Required` until the limit is raised or a new billing cycle begins. If your account uses prepaid credits followed by metered billing, the limit applies only to the metered charges after credits run out, not to prepaid credit purchases. Prepaid-only accounts do not have this metered spend-limit control; the [automatic top-up limit](#automatic-credit-top-ups) separately caps automatic credit purchases. ## Payment-required responses[​](#payment-required-responses "Direct link to Payment-required responses") Authenticated API requests can return `402 Payment Required` when the API key has expired, the associated subscription is inactive, the account has reached its monthly billing limit, or its prepaid credit balance is depleted. These responses include a `Retry-After: 3600` header, where the value is the number of seconds clients should wait before trying again. The header is listed in `Access-Control-Expose-Headers`, so cross-origin browser clients can read it. Because resolving a `402` usually requires renewing access or updating billing settings, clients should inspect the response's `msg` field and avoid retrying continuously while the account remains inactive. One `402` is temporary. When a free-trial account uses up its daily character allowance, the block clears at the next UTC midnight. That response's `Retry-After` header and a numeric `retry_after` body field both give the seconds until the reset. To check a key's state without making a billable call, including the exact reason it is blocked, use [Account Status](https://sapling.ai/docs/api/account-status.md). See [Rate Limits & Errors](https://sapling.ai/docs/rate_limits.md) for every status code. The response body is JSON with a `msg` field describing the reason: ``` { "msg": "API credit balance depleted. Purchase more credits at https://sapling.ai/api_settings#billing." } ```
Production Key Trial development keys allow for processing of 50,000 characters every 24 hours. [Subscribe](https://sapling.ai/api-checkout) for production access and [usage-based pricing](https://sapling.ai/docs/api/pricing), or purchase [prepaid API credits](#prepaid-api-credits) to activate production access without a metered subscription.
# Replacing Grammarly with Sapling We cover both how to use Sapling through an HTML `script` tag, as well as how to bundle it with your JavaScript application with `npm`. Besides changing an import and a new mechanism for observing an editable, remember to tag editables with `sapling-ignore` to prevent users of the Sapling browser extension from getting duplicate UI elements. ## HTML / JavaScript[​](#html--javascript "Direct link to HTML / JavaScript") ### Old Grammarly Code[​](#old-grammarly-code "Direct link to Old Grammarly Code") ```
``` ### New Sapling Code[​](#new-sapling-code "Direct link to New Sapling Code") ```
``` ## NPM[​](#npm "Direct link to NPM") ### Old Grammarly Code[​](#old-grammarly-code-1 "Direct link to Old Grammarly Code") Installation: `npm install @grammarly/editor-sdk` Editor initialization: ```
``` JavaScript initialization (we recommend adding this after the editor HTML): ``` import * as Grammarly from "@grammarly/editor-sdk"; await Grammarly.init("YOUR_CLIENT_ID"); ``` ### New Sapling Code[​](#new-sapling-code-1 "Direct link to New Sapling Code") Installation: `npm install @saplingai/sapling-js` Editor initialization: ```
``` JavaScript initialization (we recommend adding this after the editor HTML): ``` Sapling.init({ key: '', mode: 'dev', }); const editor = document.getElementById('editor'); Sapling.observe(editor); ``` ## Additional Functionality[​](#additional-functionality "Direct link to Additional Functionality") ### Initialization Flags[​](#initialization-flags "Direct link to Initialization Flags") Sapling's SDK also provides additional functionality that is not available in the Grammarly SDK: * Support for other languages as well as language varieties (e.g., US or UK English). * Custom error mappings and custom dictionaries. * The ability to check text on a JavaScript callback instead of during textchange events to trigger checks manually or to reduce usage. * [Advanced Edits:](https://sapling.ai/docs/api/advanced-edits.md) corrections that go beyond regular spelling and grammar checking such as for DEI initiatives. * Customization of the edit UI and color scheme through [style customization](). ### Backend API[​](#backend-api "Direct link to Backend API") Sapling provides a "headless" API that works without HTML UI elements as well. You can use this to power your backend applications. The `npm` JavaScript SDK supports this behavior natively, and we also provide a Python SDK. For other languages, you can call the HTTP endpoint with your API key. We include examples here: [https://sapling.ai/programming-languages](https://sapling.ai/programming-languages?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs). ## Next Steps[​](#next-steps "Direct link to Next Steps") * You can browse Sapling's SDK functionality and learn more about the platform through our [Developer Documentation](https://sapling.ai/docs/sdk/JavaScript/quickstart.md). * Remember to remove the Grammarly SDK in your code as well as in your `package.json`. * If at any point you run into issues with implementation or testing, feel free to reach out to us at or our [Discord channel](https://discord.com/invite/p5gDc684TX). We also try to answer all questions tagged `sapling` on [Stackoverflow](https://stackoverflow.com/questions/tagged/sapling). --- # Salesforce Lightning info For technical support, contact . Sapling's SDK integrates with Salesforce Lightning applications, offering the simplest way to add grammar and spell checking functionality to a Lightning application. ## Lightning Web Components (LWC) / Locker Service[​](#lightning-web-components-lwc--locker-service "Direct link to Lightning Web Components (LWC) / Locker Service") Locker Service is a Salesforce-specific JavaScript runtime environment that does not behave completely like browser web APIs. Platform differences and Salesforce-specific JavaScript implementation details are noted here. ## Shadow DOM / Shadow Root[​](#shadow-dom--shadow-root "Direct link to Shadow DOM / Shadow Root") By default, Sapling's SDK renders markup in encapsulated ShadowRoot (Shadow DOM) elements to isolate them from the parent DOM's HTML, CSS, and JavaScript. Salesforce Lightning Web Components do not support shadow DOMs, so set the flag to `false` on instantiation. ``` Sapling.init({ ... shadowRoot: false, }); ``` Refer to: [Salesforce Shadow DOM Documentation](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.create_dom) ## Textarea Parent Access[​](#textarea-parent-access "Direct link to Textarea Parent Access") When the Sapling SDK observes an HTML DOM element, it uses the element's non-static parent to position edit suggestions properly. The Lightning platform will sometimes prevent access to parent objects not owned by the Lightning Web Component. Without this, Chrome will render Sapling markup against the wrong non-static parent. A workaround is to wrap Sapling elements in a div with a non-static position: ```
``` The non-static element does not have to be immediate. If it's simpler, the root (accessible) element can be a non-static position. ## Component Element Access[​](#component-element-access "Direct link to Component Element Access") Lightning DOM elements are accessed through the `template` property instead of the document `property`. ``` const textareas = this.template.querySelectorAll('textarea'); textareas.forEach(ta => { Sapling.observe(ta); }); ``` Refer to: [Salesforce DOM Access Documentation](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/create_components_dom_work) ## HTML Element Support[​](#html-element-support "Direct link to HTML Element Support") info We recommend using `textarea` elements instead with Sapling for best compatibility, instead of Lightning web elements such as `lightning-textarea` and `lightning-input-field`. Sapling can work with all standard web HTML text elements: `textarea`, `contenteditable`, `input`. The Lightning platform also includes additional web elements like `lightning-textarea` and `lightning-input-field`. These elements encapsulate standard web text elements like `textarea`. The DOM elements are proxied and underlying web elements cannot be accessed. Sapling has partial support for Lightning web elements like `lightning-textarea` and `lightning-input-field`. Issues with encapsulated Lightning components are listed below: #### Scroll Events[​](#scroll-events "Direct link to Scroll Events") Lightning text wrapper do not emit scroll events that other DOM scrollables normally emit. This means that Sapling markup on these components does not update when scrolled. A workaround is to disable scrolling in these elements and wrap them in a scrollable parent (`div`) that Sapling can access. Another workaround is to call `Sapling.checkOnce` on components manually when you believe the Sapling markup needs to be refreshed, either based on DOM events, a timer, or a manually triggered button. #### Positioning[​](#positioning "Direct link to Positioning") Lightning text wrappers do not allow inspection of the computed vertical and horizontal positioning of the underlying textarea that is being wrapped. Things that affect the positioning include padding, margin, and label sizes. If Sapling markup is positioned incorrectly, make sure that custom padding, margin, and label sizes apply to standard classes like `slds-form-element__label` and `slds-textarea`. A workaround is instantiating the Sapling SDK with horizontal and vertical pixel offsets to adjust for positioning issues. ``` Sapling.init({ ... lightningCompatTop: 10, lightningCompatLeft: 12, }); ``` --- # AI Detect JavaScript Quickstart Developer Key A rate-limited API developer key can be provisioned from the [Sapling API dashboard](https://sapling.ai/api_settings?utm_source=sapling.ai\&utm_medium=documentation\&utm_campaign=apidocs). Developer keys allow for processing of 50,000 characters every 24 hours. [Subscribe](https://sapling.ai/api-checkout) for production access and [usage-based pricing](https://sapling.ai/docs/api/pricing). ## Javascript SDK for AI Detection[​](#javascript-sdk-for-ai-detection "Direct link to Javascript SDK for AI Detection") This page explains how Sapling's Javascript SDK provides a plug-and-play UI integration for AI content detection. Using this AI detection SDK allows developers to easily add the ability to flag AI-generated content in any textarea / contenteditable. If you would rather call the endpoint from your own backend, see the [Node example](https://sapling.ai/docs/sdk/JavaScript/quickstart.md#from-a-node-backend) or the [AI detector API reference](https://sapling.ai/docs/api/detector.md). ### 1. Full-stack setup[​](#1-full-stack-setup "Direct link to 1. Full-stack setup") The AI Detect integration builds upon our **[Fullstack Javascript Quickstart](https://sapling.ai/docs/sdk/JavaScript/quickstart.md#fullstack-quickstart)**. Be sure to complete that guide before continuing. ### 2. Add AI Detection button[​](#2-add-ai-detection-button "Direct link to 2. Add AI Detection button") Open `App.js` and replace its contents with the following code /\/client/src/App.js ``` import './App.css'; import { useEffect } from 'react'; import { Sapling } from "@saplingai/sapling-js/observer"; function App() { useEffect(() => { Sapling.init({ endpointHostname: 'http://127.0.0.1:5000', saplingPathPrefix: '/sapling', }); const editor = document.getElementById('editor'); Sapling.observe(editor); const button = document.getElementById('ai-detect-btn'); button.addEventListener('click', () => { Sapling.checkOnce(editor, {aiDetect: true}); }); }); return ( <>
Phone chargers are essential accessories that have become an integral part of modern life. These devices are designed to replenish the battery life of our smartphones and other electronic gadgets, enabling us to stay connected and productive throughout the day. With advancements in technology, phone chargers have evolved significantly, offering various types such as wired, wireless, fast-charging, and portable chargers. The convenience and versatility of phone chargers have revolutionized the way we use our devices, ensuring we can always stay powered up and connected in our fast-paced, digital world. Portable phone chargers, also known as power banks, have become a lifesaver for people on the go. These compact, battery-powered devices store electrical energy that can be used to charge our phones when an outlet is unavailable. Whether traveling, camping, or during emergencies, power banks ensure we are never left stranded with a dead phone battery.
); } export default App; ``` ### 3. Test it out\![​](#3-test-it-out "Direct link to 3. Test it out!") That's it! Go to **** and click the button! You'll see an overall score pop-up, and suspicious sentences higlighted in red. ![](/img/sdk/ai_detect_sdk_2.png) ### 4. One-time checks in a textarea[​](#4-one-time-checks-in-a-textarea "Direct link to 4. One-time checks in a textarea") With the browser SDK bundled in `@saplingai/sapling-js` 1.0.54 (SDK bundle v1.1.3), you can run a one-time AI detection check on a `