Interface GenerateTextOptions

interface GenerateTextOptions {
    provider?: string;
    model?: string;
    prompt?: string;
    system?: string | SystemContentBlock[];
    messages?: Message[];
    tools?: AdaptableToolInput;
    toolChoice?: string | Record<string, unknown>;
    requestTimeout?: number;
    maxAttempts?: number;
    onAttempt?: ((outcome) => void);
    abortSignal?: AbortSignal;
    maxSteps?: number;
    toolMode?: ToolMode;
    temperature?: number;
    topP?: number;
    frequencyPenalty?: number;
    presencePenalty?: number;
    maxTokens?: number;
    thinking?: false | {
        budgetTokens: number;
    };
    effort?: string;
    promptCacheKey?: string | false;
    promptCacheRetention?: "in_memory" | "24h" | "30m";
    serviceTier?: "priority" | "auto" | "default" | "flex";
    cache?: false | {
        ttl?: "5m" | "1h";
    };
    sessionId?: string;
    cacheDiagnostics?: boolean | {
        previousMessageId?: null | string;
    };
    customModelParams?: Record<string, unknown>;
    apiKey?: string;
    baseUrl?: string;
    usageLedger?: AgentOSUsageLedgerOptions;
    chainOfThought?: string | boolean;
    planning?: boolean | PlanningConfig;
    fallbackProviders?: FallbackProviderEntry[];
    onFallback?: ((error, fallbackProvider) => void);
    source?: string;
    router?: IModelRouter;
    routerParams?: Partial<ModelRouteParams>;
    hostPolicy?: HostLLMPolicy;
    policyTier?: "safe" | "standard" | "mature" | "private-adult";
    onBeforeGeneration?: ((context) => Promise<void | GenerationHookContext>);
    onAfterGeneration?: ((result) => Promise<void | GenerationHookResult>);
    budget?: SpendBudget | SpendBudgetOptions;
    hookErrors?: "warn" | "throw";
    onBeforeToolExecution?: ((info) => Promise<null | ToolCallHookInfo>);
    _transcriptIncludeTrailingCallerMessages?: number;
    _continuation?: {
        helperToolRunId: string;
        stepOffset: number;
        prompt?: string;
    };
}

Properties

provider?: string

Provider name. When supplied without model, the default text model for the provider is resolved automatically from the built-in defaults registry.

Example

`"openai"`, `"anthropic"`, `"ollama"`
model?: string

Model identifier. Accepted in two formats:

  • Plain model name (e.g. "gpt-4o") when provider is also set. Preferred.
  • "provider:model" combined string (e.g. "openai:gpt-4o").

Either provider or model (or an API key env var for auto-detection) is required.

prompt?: string

Single user turn to append after any messages. Convenience alternative to building a messages array.

system?: string | SystemContentBlock[]

System prompt injected as the first message. Accepts a plain string or structured blocks with cache breakpoints.

messages?: Message[]

Full conversation history. Appended before prompt when both are supplied.

Tools the model may invoke.

Accepted forms:

  • named high-level tool maps
  • external tool registries (Record, Map, or iterable)
  • prompt-only ToolDefinitionForLLM[]

Prompt-only definitions are visible to the model but return an explicit tool error if the model invokes them without an executor.

toolChoice?: string | Record<string, unknown>

Provider tool_choice passthrough. Forwarded verbatim to the provider so callers can force a specific tool, force tool use, or set 'auto'. Provider support varies; Anthropic + OpenAI honor it. Native path only (ignored on the prompt-emulation shim).

requestTimeout?: number

Per-call request timeout in milliseconds, forwarded to the provider for this call only. Large-output callers (e.g. structured-output generation that emits long strings) can raise the abort window without slowing the provider's default failover for chat or narration traffic. Native path only; providers without a request timeout ignore it. streamText() forwards it to the provider's stream: on Anthropic it bounds the stream's connection (the request and its response headers), and the gap between streamed events after that is the provider's streamIdleTimeoutMs.

maxAttempts?: number

The most attempts this call makes, a first and its retries together; the provider's configured count when left out. Within one attempt, a key-scoped failure (a rejected, unpaid or throttled key) on a pool of several keys re-sends the same request with the next usable key, at most once per key, and those sends are not counted. The OpenAI, Anthropic, Gemini and OpenRouter providers read it, wait no backoff after the last attempt, and refuse a count that is not a whole number of 1 or more with a RangeError before anything is sent, streamed or not; the Anthropic and Gemini streams send one request and retry nothing but key hops. A request sent again on another route after a 404 (a retired Gemini id on its alias, an OpenRouter request without its schema) draws on the same count. Other providers keep their configured retries.

onAttempt?: ((outcome) => void)

Called once per attempt, with the answer of the attempt's last send (a key hop's earlier answers are not reported), so a caller can settle the attempts it paid for. The OpenAI provider (and the providers that send through it) reports attempts; the others report nothing.

Type declaration

abortSignal?: AbortSignal

Ends the call when it aborts: the provider request in flight is cancelled, no further step, retry or fallback hop starts, and the call rejects with the signal's reason. An abort never walks the fallback chain. The signal reaches the provider as ModelCompletionOptions.abortSignal; a request whose provider does not read it runs to its end, and the call then rejects with the signal's reason.

maxSteps?: number

Maximum number of agentic steps (LLM calls) to execute before returning. Each tool-call round trip counts as one step. Defaults to 1.

toolMode?: ToolMode

Tool-calling strategy. 'auto' (default) uses native provider tool-calling, and on a tool-unsupported provider error falls back to a prompt-based shim (tool schemas rendered into the prompt, <tool_call> blocks parsed from the model's text). 'native' forces native only. 'prompt' forces the shim. The shim makes AgentOS tools work on models without native tool-use (e.g. the uncensored OpenRouter catalog). Shim roundtrips are capped by maxSteps (default 5 when unset on the shim path).

temperature?: number

Sampling temperature forwarded to the provider (0-2 for most providers).

topP?: number

Nucleus sampling top-p forwarded to the provider.

frequencyPenalty?: number

Frequency penalty forwarded to the provider (OpenAI / OpenRouter range -2..2). Reduces verbatim token repetition. Anthropic has no equivalent and the provider drops it, so it's a no-op on Claude models.

presencePenalty?: number

Presence penalty forwarded to the provider (OpenAI / OpenRouter range -2..2). Nudges the model toward new topics. Anthropic has no equivalent and the provider drops it, so it's a no-op on Claude models.

maxTokens?: number

Hard cap on output tokens. Provider-dependent default applies when omitted.

thinking?: false | {
    budgetTokens: number;
}

Extended-thinking switch forwarded to Claude models. Any positive budgetTokens turns adaptive thinking on (the number itself is not sent and maxTokens passes through unchanged). false turns thinking off with the model's own off shape; Opus 5.5, Fable and Mythos always think. Omitted keeps the model's default: thinking on for Opus 5 and later, Sonnet 5 and later, Fable and Mythos, off for older models. Other providers ignore it.

Type declaration

  • budgetTokens: number
effort?: string

Reasoning depth / token-spend control forwarded to effort-capable models (Opus 4.5+, Sonnet 4.6, Fable/Mythos 5) as output_config.effort (low|medium|high|xhigh|max). Independent of thinking and tool_choice; the provider drops it on unsupported models or invalid values.

promptCacheKey?: string | false

OpenAI prompt-cache shard key (spec batch-1 C2; other providers ignore it). 'auto' derives a sha256-hashed key from sessionId (omitted when no session id is set; raw ids never leave the process); an explicit string is sent verbatim; false omits the field. Absent defaults to 'auto' on the native OpenAI endpoint unless the call carries cache: false; OpenAI-compatible gateways (custom baseURL) keep the omit default.

promptCacheRetention?: "in_memory" | "24h" | "30m"

OpenAI prompt-cache retention request. Emitted only when the fail-closed capability table allows the model/value combination; unsupported combos are omitted with a debug log. See openai-cache-params.ts.

serviceTier?: "priority" | "auto" | "default" | "flex"

OpenAI service tier (service_tier, verbatim). No default. 'flex' bills at ~batch rates but can 429 under load; automatic tier fallback is deliberately not implemented.

cache?: false | {
    ttl?: "5m" | "1h";
}

Per-call prompt-cache control, forwarded to cache-capable providers (Anthropic directly and on anthropic/* slugs through OpenRouter; false also suppresses OpenAI's session-derived prompt_cache_key).

  • false — this request emits NO cache_control at all: the provider's automatic markers (request-level marker, thinking-mode block markers, the moving message-tail) are suppressed AND any caller-placed system/message markers (e.g. SystemContentBlock.cacheBreakpoint) are stripped before the wire. Set this on TRUE one-shots — a single never-repeated call pays the cache-write premium (1.25x/2x input) on bytes nothing will ever read back.
  • { ttl: '1h' } — the automatic markers (including the moving message-tail pinned for multi-turn history) carry a 1-hour TTL instead of the 5-minute default. Set this on slow loops: codegen orchestrator/tool steps gap 2-14 minutes and human-paced conversation turns regularly exceed 5 minutes, so the default-TTL entry expires between steps and every turn re-writes. Caller-placed markers keep their own TTLs (SystemContentBlock.cacheTtl).
  • omitted / { ttl: '5m' } — default 5-minute auto markers.

Type declaration

  • Optional ttl?: "5m" | "1h"
sessionId?: string

Per-conversation affinity key, forwarded to providers that support request affinity (OpenRouter sends it as session_id for provider sticky routing — upstream prompt caches are host-scoped, so a load-balanced conversation otherwise cold-misses the cache a prior turn wrote on a different host). On the native OpenAI endpoint the prompt_cache_key shard key derives from it automatically, so the same id keeps cache routing warm there too. Pass a stable id per conversation.

cacheDiagnostics?: boolean | {
    previousMessageId?: null | string;
}

Enable Anthropic prompt-cache diagnostics (beta cache-diagnosis-2026-04-07) across the agentic loop. The loop auto-threads each step's response id into the next step's diagnostics.previous_message_id, so every step after the first carries a comparison verdict: cacheMissReason: null = prefix stable, a populated reason (system_changed / tools_changed / messages_changed / ...) = where the cached prefix diverged. Per-step verdicts surface on the GenerationHookResult.cacheDiagnostics hook field; the last step's verdict lands on GenerateTextResult.cacheDiagnostics. Anthropic-only (other providers ignore the option) and best-effort — diagnostics never block or fail a request.

The object form seeds the FIRST step's previous_message_id so a caller can thread across REQUESTS, not just across the steps of one call: pass the prior turn's GenerateTextResult.providerMessageId and the first step's verdict names any divergence from that turn's prompt. true keeps the in-call-only behavior (first step compares nothing).

Type declaration

  • Optional previousMessageId?: null | string
customModelParams?: Record<string, unknown>

Provider-specific TOP-LEVEL request-payload parameters, forwarded verbatim into ModelCompletionOptions.customModelParams. Provider implementations spread these onto the outgoing request body (OpenRouter / OpenAI / Anthropic / Ollama all honor it), so this is the escape hatch for params the typed options don't model — e.g. OpenRouter provider-routing preferences:

customModelParams: { provider: { sort: 'throughput' } }

Keys collide last-wins with the typed fields at the provider layer, so only pass params the target provider understands. The Anthropic provider reconciles three keys with the model: with thinking: false on a model that turns thinking off only at effort high or below (Opus 5, Sonnet 5.5, Haiku 5.5), an output_config.effort of xhigh or max passed here is sent as high; a temperature or top_p passed here for a model that rejects them is dropped (and top_k on Claude Haiku 5.5); and a model passed here is the one the request is shaped for.

With planning on, the planning call takes OpenRouter's routing controls (provider, models, route, transforms) and plugins from this record, so the preferences that say where the caller's messages may go hold for it too. Every other key goes to the turn's requests alone.

apiKey?: string

Override the API key instead of reading from environment variables.

baseUrl?: string

Override the provider base URL (useful for local proxies or Ollama).

Optional durable usage ledger configuration for helper-level accounting.

chainOfThought?: string | boolean

Chain-of-thought instruction prepended to the system prompt when tools are available. Encourages the model to reason explicitly before choosing an action.

  • false (default): no CoT injection.
  • true: inject the default CoT instruction.
  • string: inject a custom CoT instruction.
planning?: boolean | PlanningConfig

Enable plan-then-execute mode. When true (or a PlanningConfig), an upfront LLM call decomposes the task into numbered steps before the tool-calling loop begins. The plan is injected into the system prompt so the model executes with full awareness of the strategy.

Set to false or omit to skip planning entirely (the default).

fallbackProviders?: FallbackProviderEntry[]

Ordered list of fallback providers to try when the primary provider fails with a retryable error (HTTP 402/429/5xx, network errors, auth failures).

Default behavior (omit / undefined): auto-build the canonical fallback chain for the primary provider via buildFallbackChain, filtered to providers that have API keys present in the environment. No import needed: fallback is on by default.

Strict mode ([]): explicitly opt out of fallback. The primary provider's error is re-thrown after exhausting any provider-internal retries. Use this when billing isolation, capability auditing, or provider-pinned testing requires a single-provider guarantee.

Custom chain (array of entries): specify exactly which providers (and optional model overrides) to try, in order. Each entry's model defaults to the provider's text-generation default from PROVIDER_DEFAULTS when omitted. Providers are tried left-to-right; the first successful response wins.

Example: Default: auto-fallback through the canonical chain

const result = await generateText({
provider: 'anthropic',
prompt: 'Hello',
});
// On retryable Anthropic failure, walks anthropic -> openai -> gemini -> ...

Example: Strict mode: fail if the primary is unavailable

const result = await generateText({
provider: 'anthropic',
prompt: 'Hello',
fallbackProviders: [],
});

Example: Custom chain

const result = await generateText({
provider: 'anthropic',
prompt: 'Hello',
fallbackProviders: [
{ provider: 'openai', model: 'gpt-4o-mini' },
{ provider: 'openrouter' },
],
});
onFallback?: ((error, fallbackProvider) => void)

Callback invoked when a fallback provider is about to be tried after the primary (or a previous fallback) failed. Useful for logging or metrics.

Type declaration

    • (error, fallbackProvider): void
    • Parameters

      • error: Error

        The error that triggered the fallback.

      • fallbackProvider: string

        The provider identifier being tried next.

      Returns void

source?: string

Optional source label forwarded to the global LLM usage observer registered via setGlobalLlmObserver. Hosts use this to tag the emitted telemetry row with a caller-defined meter key (e.g. 'narrator_turn', 'companion_reply', 'world_compile_job').

Has no effect when no observer is registered.

router?: IModelRouter

Optional model router for intelligent provider/model selection. When provided, the router's selectModel() is called before provider resolution. The router result overrides model/provider. If the router returns null, falls back to standard resolution.

routerParams?: Partial<ModelRouteParams>

Routing hints passed to the model router. Extracted automatically from system prompt and tool names when not provided.

hostPolicy?: HostLLMPolicy

Host-level routing hints that can be forwarded into the model router without requiring callers to construct raw router params directly.

policyTier?: "safe" | "standard" | "mature" | "private-adult"

Caller's intended content policy tier. On 'mature' or 'private-adult' with no explicit fallbackProviders, the auto-built fallback chain is buildPolicyAwareFallbackChain: the tier's ranked uncensored OpenRouter models, then the availability chain, so a content-policy refusal from the primary (an OpenAI or Anthropic model) re-routes to a model that can complete the request rather than hard-failing.

Combined with the isContentPolicyRefusal branch in isRetryableError, this also makes the fallback loop fire on OpenAI's 400 + code: 'content_policy_violation', which the network-only retryable matrix would otherwise treat as a hard error.

When omitted, the chain follows the tier the call resolves to (resolvePolicyTier): routerParams.policyTier, then this field, then hostPolicy (a host policy without a tier counts as standard), then the router's default tier. safe and standard keep the availability-only chain.

Mirrors the existing policyTier parameter on GenerateImageOptions and EditImageOptions.

onBeforeGeneration?: ((context) => Promise<void | GenerationHookContext>)

Called before each LLM generation step. Can inject memory context into messages, sanitize input via guardrails, or modify the prompt. Return a modified context to transform input, or void to pass through.

Type declaration

onAfterGeneration?: ((result) => Promise<void | GenerationHookResult>)

Called after each LLM generation step. Can check output against guardrails, redact PII, or transform the response. Return a modified result to transform output, or void to pass through.

Type declaration

A spend budget for this call and, when the same SpendBudget instance is passed to several calls, for all of them: each provider call is checked against what is left before it is made and recorded after it, a failed request's billed usage included. A call the budget refuses is not tried on a fallback provider.

hookErrors?: "warn" | "throw"

What a generation or tool hook's error does: 'warn' (the default) logs it and goes on; 'throw' ends the call with it, so a guard written as a hook can stop a call. A call a hook stops is not tried on a fallback provider and does not count against the provider's health.

onBeforeToolExecution?: ((info) => Promise<null | ToolCallHookInfo>)

Called before each tool execution. Can modify arguments, apply permission checks, or return null to skip the tool call entirely.

Type declaration

_transcriptIncludeTrailingCallerMessages?: number

INTERNAL (sessions): how many TRAILING entries of messages belong to THIS call's transcript delta rather than prior history. Sessions that carry a non-string user turn inside messages set 1 so the delta includes it; prompt-based calls leave it unset (the prompt push is captured positionally). Not part of the public API.

_continuation?: {
    helperToolRunId: string;
    stepOffset: number;
    prompt?: string;
}

INTERNAL (failover): the call a fallback leg continues. The leg keeps the call's tool run id, so tool execution contexts carry the same session, numbers its steps from stepOffset in hooks, synthetic tool call ids and tool contexts, and reports the call's original prompt to hooks (a leg that continues after tool rounds receives it inside messages instead). Not part of the public API.

Type declaration

  • helperToolRunId: string
  • stepOffset: number
  • Optional prompt?: string