Rewriter API
This package wraps the built-in Rewriter API. It adds session reuse, streaming, and optional result caching. For React, see useRewriter.
Before shipping, review the Production checklist for safe rendering, progress, Accept/Reject/Undo flows, and cache freshness.
Use prepareRewriter to warm a session on user intent and release it when the feature closes. See the Session lifecycle guide.
import { rewrite } from "@web-ai-sdk/rewriter";
const result = await rewrite({ input: "hey, can u send me that doc when u get a sec? thx", tone: "more-formal", length: "as-is", onUpdate: (text) => console.log("partial", text),});
console.log(result.output, result.cached);result.output is the rewritten text (trimmed), or null when the input is empty. result.cached tells you whether the response came from the cache without invoking the model.
Options
Section titled “Options”interface RewriteOptions { input: string; // text to rewrite context?: string; // per-call background info language?: string; // BCP-47; drives input/output hints when supported supportedLanguages?: readonly string[]; tone?: "as-is" | "more-formal" | "more-casual"; format?: "as-is" | "markdown" | "plain-text"; length?: "as-is" | "shorter" | "longer"; sharedContext?: string; monitor?: (m: CreateMonitor) => void; cache?: "session" | "local" | { get, set }; cacheKey?: string; cacheTtl?: number; // built-in shortcut TTL in ms; default 1 hour cacheRefresh?: boolean; // skip the cache read, write the fresh result onUpdate?: (text: string) => void; signal?: AbortSignal;}Returns
Section titled “Returns”interface RewriteResult { output: string | null; cached: boolean;}Writer vs. Rewriter
Section titled “Writer vs. Rewriter”The Writer generates new content from a task description; the Rewriter transforms text you already have. They share the same lifecycle (session reuse, streaming, caching) and the same tone / format / length ergonomics, but the Rewriter’s enums are relative adjustments (more-formal, shorter, as-is) rather than absolute targets.
Errors and unavailability
Section titled “Errors and unavailability”The vanilla rewrite() throws RewriterUnavailableError when the API is missing:
import { rewrite, RewriterUnavailableError } from "@web-ai-sdk/rewriter";
try { const result = await rewrite({ input: draft, tone: "more-formal" });} catch (err) { if (err instanceof RewriterUnavailableError) return; throw err;}AbortSignal is supported. Aborting mid-stream resolves cleanly; an opt-in result cache is not written for aborted runs.