@nutrient-sdk/document-authoring-ai
v2.0.0
Published
AI tool definitions and editor execution helpers for Nutrient Document Authoring.
Readme
Nutrient Document Authoring AI
Document Authoring AI is the AI toolkit for Nutrient Document Authoring. It gives a Large Language Model (LLM) a list of document tools, validates the tool calls the model sends back, and applies accepted edits through a live Document Authoring editor.
The package is split by where the code runs. The root entrypoint is safe to use
on a server because it only exports prompts, schemas, tool metadata, and
validation helpers. The /editor entrypoint is for browser code that owns a
DocAuthEditor. The /vercel and /langchain entrypoints adapt the same tool
definitions for those AI frameworks.
Install
Install the AI package first. This is enough to call getAiPromptGuide(),
inspect tool definitions, validate tool calls, define workflows, use adapters,
and export tool metadata as JSON.
npm install @nutrient-sdk/document-authoring-aiIf you execute tools against a Document Authoring editor, install Document
Authoring SDK 1.21.0 or newer:
npm install @nutrient-sdk/document-authoring@^1.21.0You do not need @nutrient-sdk/document-authoring when you stay on the root,
/vercel, or /langchain entrypoints. You need it when you import
@nutrient-sdk/document-authoring-ai/editor, because that entrypoint talks to a
live DocAuthEditor.
If you use the Vercel AI SDK adapter, install the Vercel AI SDK too. The
adapter supports ai versions 6 and 7:
npm install aiThe LangChain adapter uses this package's built-in Zod dependency for tool schemas and returns plain JSON Schema for workflow output. It does not need another peer dependency from this package.
Entrypoints
import { getAiPromptGuide, getAiToolDefinitions, getBuiltInWorkflow, parseAiToolCall } from '@nutrient-sdk/document-authoring-ai';
import { getAiToolkit } from '@nutrient-sdk/document-authoring-ai/editor';
import { toVercelAiTools } from '@nutrient-sdk/document-authoring-ai/vercel';
import { toLangChainTools } from '@nutrient-sdk/document-authoring-ai/langchain';Use the root entrypoint for model-facing setup:
getAiPromptGuide()returns instructions you can add to your model's system prompt.getAiToolDefinitions()returns built-in tool names, descriptions, input schemas, output schemas, and read/write metadata.parseAiToolCall(...)validates untrusted tool calls from a model.getBuiltInWorkflow(...)returns the built-in proofreading and translation workflows.createWorkflow(...)defines a custom workflow.prepareWorkflowRun(...)captures one input snapshot, builds model prompts, and optionally validates the input and applied edits.createWorkflowEditsJsonSchema()describes the small edit-list response format.
A typical integration has two halves. Your model runtime gets prompts, tool
definitions, and schemas from the root entrypoint or an adapter entrypoint. Your
browser app receives tool calls and executes them through the /editor
entrypoint, where the live document exists.
Tool Definitions
Send tool definitions to the model. A tool definition names one document action and includes the JSON schema for its arguments. When the model returns a tool call, parse it before it reaches the editor.
import { getAiPromptGuide, getAiToolDefinitions, parseAiToolCall, type UnvalidatedAiToolCall } from '@nutrient-sdk/document-authoring-ai';
const definitions = getAiToolDefinitions({
tools: ['read_document', 'search_elements', 'read_element', 'list_revisions', 'replace_text'],
});
const systemPrompt = `${getAiPromptGuide()}\n\nUse only these document tools.`;
function parseModelToolCall(call: UnvalidatedAiToolCall) {
return parseAiToolCall(call, definitions);
}The read tools inspect the current document:
read_documentsearch_elementsread_elementlist_revisions
list_revisions returns pending tracked changes in document order. It accepts
optional exact author, revision type, body/header/footer story, and
maxResults filters. The default limit is 100; truncated reports whether
more matching revisions exist. Results include revision metadata and preview
text, but not live document anchors.
The write tools edit document content:
add_paragraphsadd_section_breakreplace_paragraphreplace_textadd_tablereplace_tabledelete_blockformat_textformat_list
By default, write tools apply changes directly. At execution time you can switch
to tracked changes. You can also expose a reviewComment argument so the model
can leave a review comment with an edit.
const definitions = getAiToolDefinitions({
reviewComments: 'create',
});Editor Execution
Use getAiToolkit(editor) in browser code that already has a DocAuthEditor.
That is where validated tool calls turn into real document reads and writes.
This entrypoint requires @nutrient-sdk/document-authoring 1.21.0 or newer.
import { parseAiToolCall } from '@nutrient-sdk/document-authoring-ai';
import { getAiToolkit } from '@nutrient-sdk/document-authoring-ai/editor';
import type { DocAuthEditor } from '@nutrient-sdk/document-authoring';
import type { UnvalidatedAiToolCall } from '@nutrient-sdk/document-authoring-ai';
export async function executeDocumentTool(editor: DocAuthEditor, rawCall: UnvalidatedAiToolCall) {
const toolkit = getAiToolkit(editor);
try {
const call = parseAiToolCall(rawCall);
return await toolkit.executeTool(call, {
writeMode: 'track_changes',
reviewComments: 'create',
});
} finally {
toolkit.dispose();
}
}executeTool(...) returns the validated call, the tool result, and an execution
state. Read results have execution.kind === 'read'. Write results say whether
the edit was applied directly or with tracked changes.
Vercel AI SDK
@nutrient-sdk/document-authoring-ai/vercel converts built-in tool definitions
to Vercel AI SDK tool metadata. It needs the ai package.
import { getAiToolDefinitions, getBuiltInWorkflow, prepareWorkflowRun, type WorkflowInput } from '@nutrient-sdk/document-authoring-ai';
import { toVercelAiTools, toVercelAiWorkflowEditsSchema } from '@nutrient-sdk/document-authoring-ai/vercel';
declare const workflowInput: WorkflowInput;
declare const validateFragment: Parameters<typeof prepareWorkflowRun>[0]['validateFragment'];
const tools = toVercelAiTools(getAiToolDefinitions());
const workflow = getBuiltInWorkflow('translation', {
targetLanguage: 'german',
});
const run = prepareWorkflowRun({
workflow,
input: workflowInput,
validateFragment,
});
const outputSchema = toVercelAiWorkflowEditsSchema().schema;
declare const modelEdits: unknown;
const output = run.apply(modelEdits);
const systemPrompt = run.systemPrompt;
const prompt = run.createPrompt();The adapter returns metadata and schemas. It does not execute document writes on
the model server. Pass accepted tool calls to getAiToolkit(editor) in the
browser.
LangChain
@nutrient-sdk/document-authoring-ai/langchain converts built-in tool
definitions to LangChain-style metadata with Zod schemas. It returns plain JSON
Schema for focused workflow edits.
import { getAiToolDefinitions } from '@nutrient-sdk/document-authoring-ai';
import { toLangChainTools, toLangChainWorkflowEditsSchema } from '@nutrient-sdk/document-authoring-ai/langchain';
const tools = toLangChainTools(
getAiToolDefinitions({
tools: ['search_elements', 'read_element', 'replace_text'],
}),
);
const outputSchema = toLangChainWorkflowEditsSchema();These tool definitions do not include execution functions. Keep execution in your application, then pass validated tool calls to the editor toolkit.
Workflows
Use a workflow for a task such as proofreading or translating a selection or
document. Choose a built-in workflow with getBuiltInWorkflow(...):
proofreadingcorrects text errors.translationtranslates intoenglish,german,french, orspanish.
Your application chooses the model and connects the browser to your backend:
- In the browser, call
toolkit.readWorkflowInput(workflow, { scope: 'selection' })or usescope: 'document'. Send the complete result to your backend. - On the backend, call
prepareWorkflowRun({ workflow, input }). Pass the returnedrun.systemPromptandrun.createPrompt()to your model, along with the workflow edits schema from your adapter. - Pass the model's structured response to
run.apply(...)on the same run. Send its output back to the browser. - In the browser, call
toolkit.applyWorkflowOutput(workflow, output, { scope: input.scope }). For selection edits, addwriteMode: 'track_changes'if users should review the changes. Whole-document replacement applies directly.
See the Vercel AI SDK and LangChain examples for adapter setup, and Migrating to 2.0 for request and response examples.
The browser validates the replacement before applying it. If fragment validation fails,
applyWorkflowOutput(...) throws WorkflowFragmentValidationError and leaves
the document and selection unchanged. Its code and issues can be returned
to your backend as retry feedback. You can also supply validateFragment to
prepareWorkflowRun(...) to validate input and output on the backend.
If a model attempt fails, use run.createPrompt(previousFailure) to include
the error message in a retry. Your application decides whether and how often
to retry. Keep the editor in Edit or Review mode when applying workflow output;
View mode is read-only.
Migrating to 2.0
Document Authoring AI 2.0 requires Document Authoring SDK 1.21.0 or later.
In 1.x, the model returned a complete { replacementFragment }. In 2.0, it
returns focused set, insert, and remove operations. Your backend applies
those operations to the captured input with run.apply(...), then sends the
resulting { replacementFragment } to the browser.
Update the model request and response handling
These examples show the values to pass to your existing model call.
workflowInput is the complete result of the browser's
toolkit.readWorkflowInput(workflow, { scope: 'selection' }) call;
modelResponse is the structured output returned by your model provider.
Before, with Document Authoring AI 1.0.2:
import { getBuiltInWorkflow, type WorkflowInput } from '@nutrient-sdk/document-authoring-ai';
import { toVercelAiWorkflowOutputSchema } from '@nutrient-sdk/document-authoring-ai/vercel';
declare const workflowInput: WorkflowInput;
const workflow = getBuiltInWorkflow('proofreading');
const systemPrompt = workflow.systemPrompt;
const prompt = JSON.stringify({ task: workflow.defaultTask, input: workflowInput });
const outputSchema = toVercelAiWorkflowOutputSchema(workflow).schema;
// Call your model with systemPrompt, prompt, and outputSchema.
declare const modelResponse: unknown;
const output = modelResponse; // Already { replacementFragment }.After, with Document Authoring AI 2.0:
import { getBuiltInWorkflow, prepareWorkflowRun, type WorkflowInput } from '@nutrient-sdk/document-authoring-ai';
import { toVercelAiWorkflowEditsSchema } from '@nutrient-sdk/document-authoring-ai/vercel';
declare const workflowInput: WorkflowInput;
const workflow = getBuiltInWorkflow('proofreading');
const run = prepareWorkflowRun({ workflow, input: workflowInput });
const systemPrompt = run.systemPrompt;
const prompt = run.createPrompt();
const outputSchema = toVercelAiWorkflowEditsSchema().schema;
// Call your model with systemPrompt, prompt, and outputSchema.
declare const modelResponse: unknown;
const output = run.apply(modelResponse); // Converts operations to { replacementFragment }.Send output back to the browser. Do not send the raw operations to
applyWorkflowOutput(...). Keep the same run for the model request and
apply(...) so edits target the input snapshot used to generate the prompt.
Transport the complete 2.0 WorkflowInput, including fragmentContract.
For LangChain, replace toLangChainWorkflowOutputSchema(workflow) with
toLangChainWorkflowEditsSchema(). The new helper returns JSON Schema rather
than a Zod schema. For a framework-neutral JSON Schema, use
createWorkflowEditsJsonSchema(). Remove uses of Workflow.outputSchema and
createWorkflowOutputSchema(...); prepareWorkflowRun(...) now prepares the
prompts and assembles the replacement for every adapter.
Keep browser validation and application
The browser still applies a replacement fragment through the toolkit. Here,
output is the value returned by the backend's run.apply(modelResponse):
await toolkit.applyWorkflowOutput(workflow, output, {
scope: workflowInput.scope,
writeMode: 'track_changes',
});You can pass an optional canonical validateFragment function to
prepareWorkflowRun(...) to validate the input and assembled replacement on
the backend. The live browser SDK always performs authoritative deep validation
before mutation and reports invalid fragments as
WorkflowFragmentValidationError. Do not persist replacement fragments for
cross-version migration; this contract covers immediate workflow round trips.
Exporting Tool Definitions
Backends that do not run TypeScript can use the built-in tool metadata as JSON.
npx document-authoring-ai-export > document-authoring-ai-tools.json
npx document-authoring-ai-export --tools search_elements,read_element,replace_textThe command prints a versioned JSON payload with tool names, descriptions, schemas, and read/write metadata.
License
This package uses the same license as
@nutrient-sdk/document-authoring: see the
Nutrient SDK User Evaluation Subscription Agreement.
