Interface: GenerateTextOptions
Defined in: packages/agentos/src/api/generateText.ts:231
Properties
_responseFormat?
optional_responseFormat:Record<string,unknown> | {type:string; }
Defined in: packages/agentos/src/api/generateText.ts:469
Internal
Used by generateObject and AgentSession.send (with responseSchema) to forward a provider-specific response_format payload to the provider. Not part of the public API.
Shape varies by provider: OpenAI accepts json_object or json_schema, Anthropic uses an internal _agentosUseToolForStructuredOutput marker that AnthropicProvider routes to forced tool_use, Gemini uses a _gemini.responseSchema extra. The provider implementations consume whatever shape is here.
apiKey?
optionalapiKey:string
Defined in: packages/agentos/src/api/generateText.ts:308
Override the API key instead of reading from environment variables.
baseUrl?
optionalbaseUrl:string
Defined in: packages/agentos/src/api/generateText.ts:310
Override the provider base URL (useful for local proxies or Ollama).
chainOfThought?
optionalchainOfThought:string|boolean
Defined in: packages/agentos/src/api/generateText.ts:322
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.
fallbackProviders?
optionalfallbackProviders:FallbackProviderEntry[]
Defined in: packages/agentos/src/api/generateText.ts:382
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.
Examples
const result = await generateText({
provider: 'anthropic',
prompt: 'Hello',
});
// On retryable Anthropic failure, walks anthropic -> openai -> gemini -> ...
const result = await generateText({
provider: 'anthropic',
prompt: 'Hello',
fallbackProviders: [],
});
const result = await generateText({
provider: 'anthropic',
prompt: 'Hello',
fallbackProviders: [
{ provider: 'openai', model: 'gpt-4o-mini' },
{ provider: 'openrouter' },
],
});
hostPolicy?
optionalhostPolicy:HostLLMPolicy
Defined in: packages/agentos/src/api/generateText.ts:416
Host-level routing hints that can be forwarded into the model router without requiring callers to construct raw router params directly.
maxSteps?
optionalmaxSteps:number
Defined in: packages/agentos/src/api/generateText.ts:284
Maximum number of agentic steps (LLM calls) to execute before returning.
Each tool-call round trip counts as one step. Defaults to 1.
maxTokens?
optionalmaxTokens:number
Defined in: packages/agentos/src/api/generateText.ts:298
Hard cap on output tokens. Provider-dependent default applies when omitted.
messages?
optionalmessages:Message[]
Defined in: packages/agentos/src/api/generateText.ts:252
Full conversation history. Appended before prompt when both are supplied.
model?
optionalmodel:string
Defined in: packages/agentos/src/api/generateText.ts:246
Model identifier. Accepted in two formats:
- Plain model name (e.g.
"gpt-4o") whenprovideris 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.
onAfterGeneration()?
optionalonAfterGeneration: (result) =>Promise<void|GenerationHookResult>
Defined in: packages/agentos/src/api/generateText.ts:452
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.
Parameters
result
Returns
Promise<void | GenerationHookResult>
onBeforeGeneration()?
optionalonBeforeGeneration: (context) =>Promise<void|GenerationHookContext>
Defined in: packages/agentos/src/api/generateText.ts:446
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.
Parameters
context
Returns
Promise<void | GenerationHookContext>
onBeforeToolExecution()?
optionalonBeforeToolExecution: (info) =>Promise<ToolCallHookInfo|null>
Defined in: packages/agentos/src/api/generateText.ts:457
Called before each tool execution. Can modify arguments, apply
permission checks, or return null to skip the tool call entirely.
Parameters
info
Returns
Promise<ToolCallHookInfo | null>
onFallback()?
optionalonFallback: (error,fallbackProvider) =>void
Defined in: packages/agentos/src/api/generateText.ts:390
Callback invoked when a fallback provider is about to be tried after the primary (or a previous fallback) failed. Useful for logging or metrics.
Parameters
error
Error
The error that triggered the fallback.
fallbackProvider
string
The provider identifier being tried next.
Returns
void
planning?
optionalplanning:boolean|PlanningConfig
Defined in: packages/agentos/src/api/generateText.ts:331
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).
policyTier?
optionalpolicyTier:"safe"|"standard"|"mature"|"private-adult"
Defined in: packages/agentos/src/api/generateText.ts:440
Caller's intended content policy tier. When set to 'mature' or
'private-adult' AND no explicit fallbackProviders was supplied,
the auto-built fallback chain is constructed via
buildPolicyAwareFallbackChain instead of the default
availability chain: prepending an uncensored OpenRouter model
(Hermes 3 405B) so a content-policy refusal from the primary
(gpt-4o, Claude, etc.) 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 existing fallback
loop fire on OpenAI's 400 + code: 'content_policy_violation'
: which the network-only retryable matrix would otherwise treat
as a hard error.
Has no effect for safe/standard tiers (or when omitted):
those keep the existing availability-only fallback behavior.
Mirrors the existing policyTier parameter on
import('./generateImage.js').GenerateImageOptions and
import('./editImage.js').EditImageOptions.
prompt?
optionalprompt:string
Defined in: packages/agentos/src/api/generateText.ts:248
Single user turn to append after any messages. Convenience alternative to building a messages array.
provider?
optionalprovider:string
Defined in: packages/agentos/src/api/generateText.ts:238
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"`
requestTimeout?
optionalrequestTimeout:number
Defined in: packages/agentos/src/api/generateText.ts:279
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.
router?
optionalrouter:IModelRouter
Defined in: packages/agentos/src/api/generateText.ts:406
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?
optionalrouterParams:Partial<ModelRouteParams>
Defined in: packages/agentos/src/api/generateText.ts:411
Routing hints passed to the model router. Extracted automatically from system prompt and tool names when not provided.
source?
optionalsource:string
Defined in: packages/agentos/src/api/generateText.ts:399
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.
system?
optionalsystem:string|SystemContentBlock[]
Defined in: packages/agentos/src/api/generateText.ts:250
System prompt injected as the first message. Accepts a plain string or structured blocks with cache breakpoints.
temperature?
optionaltemperature:number
Defined in: packages/agentos/src/api/generateText.ts:296
Sampling temperature forwarded to the provider (0-2 for most providers).
thinking?
optionalthinking:object
Defined in: packages/agentos/src/api/generateText.ts:306
Extended-thinking switch forwarded to thinking-capable models (Opus
4.7/4.8). Any positive budgetTokens enables adaptive thinking — the
only form this family accepts; the number itself is not sent and
maxTokens passes through unchanged. Omitted = thinking off (provider
default behavior). Has no effect on models that do not support thinking.
budgetTokens
budgetTokens:
number
toolChoice?
optionaltoolChoice:string|Record<string,unknown>
Defined in: packages/agentos/src/api/generateText.ts:271
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).
toolMode?
optionaltoolMode:ToolMode
Defined in: packages/agentos/src/api/generateText.ts:294
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).
tools?
optionaltools:AdaptableToolInput
Defined in: packages/agentos/src/api/generateText.ts:264
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.
usageLedger?
optionalusageLedger:AgentOSUsageLedgerOptions
Defined in: packages/agentos/src/api/generateText.ts:312
Optional durable usage ledger configuration for helper-level accounting.