@tanstack/ai-anthropic 0.16.0 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/adapters/text.js +17 -4
- package/dist/esm/adapters/text.js.map +1 -1
- package/dist/esm/model-meta.d.ts +42 -0
- package/dist/esm/model-meta.js +42 -11
- package/dist/esm/model-meta.js.map +1 -1
- package/package.json +3 -3
- package/src/adapters/text.ts +39 -3
- package/src/model-meta.ts +75 -0
|
@@ -6,7 +6,7 @@ import { readCodeExecutionSkills, readCodeExecutionConfig } from "../tools/code-
|
|
|
6
6
|
import { validateTextProviderOptions } from "../text/text-provider-options.js";
|
|
7
7
|
import { buildAnthropicUsage } from "../usage.js";
|
|
8
8
|
import { createAnthropicClient, generateId, getAnthropicApiKeyFromEnv } from "../utils/client.js";
|
|
9
|
-
import { ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS } from "../model-meta.js";
|
|
9
|
+
import { getAnthropicDefaultMaxTokens, ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS } from "../model-meta.js";
|
|
10
10
|
function readAnthropicServerToolMetadata(metadata) {
|
|
11
11
|
if (typeof metadata !== "object" || metadata === null) return null;
|
|
12
12
|
const outer = metadata;
|
|
@@ -121,7 +121,9 @@ class AnthropicTextAdapter extends BaseTextAdapter {
|
|
|
121
121
|
async structuredOutput(options) {
|
|
122
122
|
const { chatOptions, outputSchema } = options;
|
|
123
123
|
const { logger } = chatOptions;
|
|
124
|
-
const requestParams = this.mapCommonOptionsToAnthropic(chatOptions
|
|
124
|
+
const requestParams = this.mapCommonOptionsToAnthropic(chatOptions, {
|
|
125
|
+
stream: false
|
|
126
|
+
});
|
|
125
127
|
const structuredOutputTool = {
|
|
126
128
|
name: "structured_output",
|
|
127
129
|
description: "Use this tool to provide your response in the required structured format.",
|
|
@@ -193,7 +195,7 @@ class AnthropicTextAdapter extends BaseTextAdapter {
|
|
|
193
195
|
);
|
|
194
196
|
}
|
|
195
197
|
}
|
|
196
|
-
mapCommonOptionsToAnthropic(options) {
|
|
198
|
+
mapCommonOptionsToAnthropic(options, { stream = true } = {}) {
|
|
197
199
|
const modelOptions = options.modelOptions;
|
|
198
200
|
const formattedMessages = this.formatMessages(options.messages);
|
|
199
201
|
const tools = options.tools ? convertToolsToProviderFormat(options.tools) : void 0;
|
|
@@ -241,7 +243,7 @@ class AnthropicTextAdapter extends BaseTextAdapter {
|
|
|
241
243
|
}
|
|
242
244
|
}
|
|
243
245
|
const thinkingBudget = validProviderOptions.thinking?.type === "enabled" ? validProviderOptions.thinking.budget_tokens : void 0;
|
|
244
|
-
const defaultMaxTokens = modelOptions?.max_tokens ??
|
|
246
|
+
const defaultMaxTokens = modelOptions?.max_tokens ?? getAnthropicDefaultMaxTokens(this.model, { stream });
|
|
245
247
|
const maxTokens = thinkingBudget && thinkingBudget >= defaultMaxTokens ? thinkingBudget + 1 : defaultMaxTokens;
|
|
246
248
|
const systemBlocks = (() => {
|
|
247
249
|
const normalized = normalizeSystemPrompts(
|
|
@@ -868,6 +870,17 @@ class AnthropicTextAdapter extends BaseTextAdapter {
|
|
|
868
870
|
break;
|
|
869
871
|
}
|
|
870
872
|
case "max_tokens": {
|
|
873
|
+
if (options.modelOptions?.max_tokens == null) {
|
|
874
|
+
const defaultedMaxTokens = getAnthropicDefaultMaxTokens(model);
|
|
875
|
+
logger.warn(
|
|
876
|
+
`anthropic response truncated at the default max_tokens (${defaultedMaxTokens}) for model=${model}; pass maxTokens (or modelOptions.max_tokens) to raise the output ceiling`,
|
|
877
|
+
{
|
|
878
|
+
source: "anthropic.processAnthropicStream",
|
|
879
|
+
model,
|
|
880
|
+
defaultedMaxTokens
|
|
881
|
+
}
|
|
882
|
+
);
|
|
883
|
+
}
|
|
871
884
|
yield {
|
|
872
885
|
type: EventType.RUN_ERROR,
|
|
873
886
|
model,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"text.js","sources":["../../../src/adapters/text.ts"],"sourcesContent":["import { EventType, normalizeSystemPrompts } from '@tanstack/ai'\nimport { toRunErrorRawEvent } from '@tanstack/ai/adapter-internals'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport { convertToolsToProviderFormat } from '../tools/tool-converter'\nimport { readCodeExecutionConfig, readCodeExecutionSkills } from '../tools'\nimport { validateTextProviderOptions } from '../text/text-provider-options'\nimport { buildAnthropicUsage } from '../usage'\nimport {\n createAnthropicClient,\n generateId,\n getAnthropicApiKeyFromEnv,\n} from '../utils'\nimport { ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS } from '../model-meta'\nimport type {\n ANTHROPIC_MODELS,\n AnthropicChatModelProviderOptionsByName,\n AnthropicChatModelToolCapabilitiesByName,\n AnthropicModelInputModalitiesByName,\n} from '../model-meta'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type { InternalLogger } from '@tanstack/ai/adapter-internals'\nimport type {\n Base64ImageSource,\n Base64PDFSource,\n ContentBlockParam,\n DocumentBlockParam,\n ImageBlockParam,\n ServerToolUseBlockParam,\n TextBlockParam,\n ThinkingBlockParam,\n ToolUseBlockParam,\n URLImageSource,\n URLPDFSource,\n WebFetchToolResultBlockParam,\n WebSearchToolResultBlockParam,\n} from '@anthropic-ai/sdk/resources/messages'\nimport type Anthropic_SDK from '@anthropic-ai/sdk'\nimport type { AnthropicBeta } from '@anthropic-ai/sdk/resources/beta/beta'\nimport type {\n AnyTool,\n ContentPart,\n Modality,\n ModelMessage,\n StreamChunk,\n TextOptions,\n} from '@tanstack/ai'\nimport type {\n AnthropicSystemPromptMetadata,\n ExternalTextProviderOptions,\n InternalTextProviderOptions,\n} from '../text/text-provider-options'\nimport type {\n AnthropicDocumentMetadata,\n AnthropicImageMetadata,\n AnthropicMessageMetadataByModality,\n AnthropicTextMetadata,\n} from '../message-types'\nimport type { AnthropicClientConfig } from '../utils'\n\n/**\n * The block type carried by an Anthropic provider-executed (server) tool's\n * stored result. Mirrors the `*_tool_result` block emitted by the streaming\n * API so it can be replayed verbatim into a later turn.\n */\ntype AnthropicServerToolResultBlockType =\n | 'web_search_tool_result'\n | 'web_fetch_tool_result'\n\n/**\n * Anthropic payload stashed on a provider-executed tool call's `metadata`\n * (under the `anthropic` key, alongside `providerExecuted: true`). Holds enough\n * to reconstruct the original `server_tool_use` + `*_tool_result` blocks so the\n * model still sees prior `web_search` / `web_fetch` evidence on the next turn.\n */\ninterface AnthropicServerToolMetadata {\n serverToolType: ServerToolUseBlockParam['name']\n resultBlockType: AnthropicServerToolResultBlockType\n /** Raw result block content, preserved verbatim from the stream. */\n result: unknown\n}\n\n/**\n * Narrow an opaque tool-call `metadata` to {@link AnthropicServerToolMetadata}\n * when it follows the provider-executed convention, else `null`.\n */\nfunction readAnthropicServerToolMetadata(\n metadata: unknown,\n): AnthropicServerToolMetadata | null {\n if (typeof metadata !== 'object' || metadata === null) return null\n const outer = metadata as { providerExecuted?: unknown; anthropic?: unknown }\n if (outer.providerExecuted !== true) return null\n const inner = outer.anthropic\n if (typeof inner !== 'object' || inner === null) return null\n const { serverToolType, resultBlockType, result } = inner as {\n serverToolType?: unknown\n resultBlockType?: unknown\n result?: unknown\n }\n if (\n typeof serverToolType !== 'string' ||\n (resultBlockType !== 'web_search_tool_result' &&\n resultBlockType !== 'web_fetch_tool_result')\n ) {\n return null\n }\n return {\n // Validated as a string above; widen back to the SDK's tool-name union.\n serverToolType: serverToolType as ServerToolUseBlockParam['name'],\n resultBlockType,\n result,\n }\n}\n\n/**\n * Reconstruct the `*_tool_result` block param from stored server-tool metadata.\n * The `result` content is opaque round-trip data, asserted to the SDK's param\n * content type at this single boundary.\n */\nfunction buildServerToolResultBlock(\n toolUseId: string,\n meta: AnthropicServerToolMetadata,\n): WebSearchToolResultBlockParam | WebFetchToolResultBlockParam {\n if (meta.resultBlockType === 'web_search_tool_result') {\n return {\n type: 'web_search_tool_result',\n tool_use_id: toolUseId,\n content: meta.result as WebSearchToolResultBlockParam['content'],\n }\n }\n return {\n type: 'web_fetch_tool_result',\n tool_use_id: toolUseId,\n content: meta.result as WebFetchToolResultBlockParam['content'],\n }\n}\n\n/**\n * Computes the `betas` array for a Messages request. Unions:\n * - `interleaved-thinking-2025-05-14` when interleaved thinking is enabled,\n * - `code-execution-2025-08-25` when a `code_execution` tool is present,\n * - `skills-2025-10-02` when that tool carries skills.\n * Returns `undefined` when none apply (so the call site omits `betas`).\n */\nexport function computeAnthropicBetas(\n tools: Array<AnyTool> | undefined,\n modelOptions:\n | {\n thinking?: {\n type?: 'enabled' | 'disabled' | 'adaptive'\n budget_tokens?: number\n }\n }\n | undefined,\n): Array<AnthropicBeta> | undefined {\n const betas = new Set<AnthropicBeta>()\n\n const useInterleavedThinking =\n modelOptions?.thinking?.type === 'enabled' &&\n typeof modelOptions.thinking.budget_tokens === 'number' &&\n modelOptions.thinking.budget_tokens > 0\n if (useInterleavedThinking) betas.add('interleaved-thinking-2025-05-14')\n\n // Code-execution beta is version-aware: select from the FIRST code_execution\n // tool's config type.\n const codeExecTool = tools?.find((t) => t.name === 'code_execution')\n if (codeExecTool) {\n const cfgType = readCodeExecutionConfig(codeExecTool)?.type\n // Each code_execution tool version pairs with a specific beta. Known\n // legacy variant maps explicitly; current/future variants (e.g.\n // `code_execution_20250825` and later) use the latest `-08-25` beta.\n betas.add(\n cfgType === 'code_execution_20250522'\n ? 'code-execution-2025-05-22'\n : 'code-execution-2025-08-25',\n )\n }\n\n // Skills beta: scan ALL code_execution tools so this AGREES with the\n // container-lift, which lifts skills from any code_execution tool that\n // carries them (not just the first).\n const hasSkills = tools?.some(\n (t) =>\n t.name === 'code_execution' &&\n (readCodeExecutionSkills(t)?.length ?? 0) > 0,\n )\n if (hasSkills) betas.add('skills-2025-10-02')\n\n return betas.size > 0 ? Array.from(betas) : undefined\n}\n\n/**\n * Configuration for Anthropic text adapter\n */\nexport interface AnthropicTextConfig extends AnthropicClientConfig {}\n\n/**\n * Anthropic-specific provider options for text/chat\n */\nexport type AnthropicTextProviderOptions = ExternalTextProviderOptions\n\n// ===========================\n// Type Resolution Helpers\n// ===========================\n\n/**\n * Resolve provider options for a specific model.\n * If the model has explicit options in the map, use those; otherwise use base options.\n */\ntype ResolveProviderOptions<TModel extends string> =\n TModel extends keyof AnthropicChatModelProviderOptionsByName\n ? AnthropicChatModelProviderOptionsByName[TModel]\n : AnthropicTextProviderOptions\n\n/**\n * Resolve input modalities for a specific model.\n * If the model has explicit modalities in the map, use those; otherwise use default.\n */\ntype ResolveInputModalities<TModel extends string> =\n TModel extends keyof AnthropicModelInputModalitiesByName\n ? AnthropicModelInputModalitiesByName[TModel]\n : readonly ['text', 'image', 'document']\n\ntype ResolveToolCapabilities<TModel extends string> =\n TModel extends keyof AnthropicChatModelToolCapabilitiesByName\n ? NonNullable<AnthropicChatModelToolCapabilitiesByName[TModel]>\n : readonly []\n\n// ===========================\n// Adapter Implementation\n// ===========================\n\n/**\n * Anthropic Text (Chat) Adapter\n *\n * Tree-shakeable adapter for Anthropic chat/text completion functionality.\n * Import only what you need for smaller bundle sizes.\n */\nexport class AnthropicTextAdapter<\n TModel extends (typeof ANTHROPIC_MODELS)[number],\n TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,\n TInputModalities extends ReadonlyArray<Modality> =\n ResolveInputModalities<TModel>,\n TToolCapabilities extends ReadonlyArray<string> =\n ResolveToolCapabilities<TModel>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n AnthropicMessageMetadataByModality,\n TToolCapabilities,\n // TToolCallMetadata — anthropic has no tool-call metadata round-tripping\n unknown,\n // TSystemPromptMetadata — narrows `systemPrompts[i].metadata` at the\n // chat() call site so users get `cache_control` autocomplete.\n AnthropicSystemPromptMetadata\n> {\n override readonly kind = 'text' as const\n readonly name = 'anthropic' as const\n\n private readonly client: Anthropic_SDK\n\n constructor(config: AnthropicTextConfig, model: TModel) {\n super({}, model)\n this.client = createAnthropicClient(config)\n }\n\n async *chatStream(\n options: TextOptions<TProviderOptions>,\n ): AsyncIterable<StreamChunk> {\n const { logger } = options\n try {\n const requestParams = this.mapCommonOptionsToAnthropic(options)\n\n logger.request(\n `activity=chat provider=anthropic model=${this.model} messages=${options.messages.length} tools=${options.tools?.length ?? 0} stream=true`,\n { provider: 'anthropic', model: this.model },\n )\n\n // `betas` is attached at the call site rather than in the shared mapper\n // because the beta set depends on both the tools and the modelOptions.\n const betas = computeAnthropicBetas(options.tools, options.modelOptions)\n\n // `client.beta.messages` is Anthropic's permanent staging surface, not a\n // sunset path: it's a superset of `client.messages` that additionally\n // accepts the `betas: AnthropicBeta[]` header (e.g. interleaved\n // thinking) plus richer `container` (skills) and `context_management`\n // shapes that `InternalTextProviderOptions` carries. We route every\n // Messages call through it so the request mapper stays single-shape.\n const stream = await this.client.beta.messages.create(\n {\n ...requestParams,\n stream: true,\n ...(betas && { betas }),\n },\n {\n signal: options.request?.signal,\n headers: options.request?.headers,\n },\n )\n\n yield* this.processAnthropicStream(\n stream,\n options,\n () => generateId(this.name),\n logger,\n )\n } catch (error: unknown) {\n const err = error as Error & { status?: number; code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n logger.errors('anthropic.chatStream fatal', {\n error,\n source: 'anthropic.chatStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model: options.model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n // Forward the Anthropic SDK error's `.error` response body (e.g.\n // `{ type, message }`) when present; never the raw exception object.\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n },\n }\n }\n }\n\n /**\n * Generate structured output using Anthropic's tool-based approach.\n * Anthropic doesn't have native structured output, so we use a tool with the schema\n * and force the model to call it.\n * The outputSchema is already JSON Schema (converted in the ai layer).\n */\n async structuredOutput(\n options: StructuredOutputOptions<TProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const { logger } = chatOptions\n\n const requestParams = this.mapCommonOptionsToAnthropic(chatOptions)\n\n // Create a tool that will capture the structured output\n // Anthropic's SDK requires input_schema with type: 'object' literal\n const structuredOutputTool = {\n name: 'structured_output',\n description:\n 'Use this tool to provide your response in the required structured format.',\n input_schema: {\n type: 'object' as const,\n properties: outputSchema.properties ?? {},\n required: outputSchema.required ?? [],\n },\n }\n\n try {\n logger.request(\n `activity=chat provider=anthropic model=${this.model} messages=${chatOptions.messages.length} tools=${chatOptions.tools?.length ?? 0} stream=false`,\n { provider: 'anthropic', model: this.model },\n )\n const betas = computeAnthropicBetas(\n chatOptions.tools,\n chatOptions.modelOptions,\n )\n // Make non-streaming request with tool_choice forced to our structured output tool\n const response = await this.client.beta.messages.create(\n {\n ...requestParams,\n stream: false,\n tools: [structuredOutputTool],\n tool_choice: { type: 'tool', name: 'structured_output' },\n ...(betas && { betas }),\n },\n {\n signal: chatOptions.request?.signal,\n headers: chatOptions.request?.headers,\n },\n )\n\n // Extract the tool use content from the response\n let parsed: unknown = null\n let rawText = ''\n\n for (const block of response.content) {\n if (block.type === 'tool_use' && block.name === 'structured_output') {\n parsed = block.input\n rawText = JSON.stringify(block.input)\n break\n }\n }\n\n if (parsed === null) {\n // Fallback: try to extract text content and parse as JSON\n rawText = response.content\n .map((b) => {\n if (b.type === 'text') {\n return b.text\n }\n return ''\n })\n .join('')\n try {\n parsed = JSON.parse(rawText)\n } catch {\n throw new Error(\n `Failed to extract structured output from response. Content: ${rawText.slice(0, 200)}${rawText.length > 200 ? '...' : ''}`,\n )\n }\n }\n\n return {\n data: parsed,\n rawText,\n usage: buildAnthropicUsage(response.usage),\n }\n } catch (error: unknown) {\n const err = error as Error\n logger.errors('anthropic.structuredOutput fatal', {\n error,\n source: 'anthropic.structuredOutput',\n })\n throw new Error(\n `Structured output generation failed: ${err.message || 'Unknown error occurred'}`,\n )\n }\n }\n\n private mapCommonOptionsToAnthropic(\n options: TextOptions<AnthropicTextProviderOptions>,\n ) {\n const modelOptions = options.modelOptions\n\n const formattedMessages = this.formatMessages(options.messages)\n const tools = options.tools\n ? convertToolsToProviderFormat(options.tools)\n : undefined\n\n const validProviderOptions: Partial<InternalTextProviderOptions> = {}\n if (modelOptions) {\n const validKeys: Array<keyof AnthropicTextProviderOptions> = [\n 'container',\n 'context_management',\n 'effort',\n 'mcp_servers',\n 'output_config',\n 'service_tier',\n 'stop_sequences',\n 'thinking',\n 'tool_choice',\n 'top_k',\n 'temperature',\n 'top_p',\n ]\n // `max_tokens` is a legitimate public modelOptions field, but it is read\n // via a dedicated path (defaultMaxTokens below) rather than copied into\n // validProviderOptions. Exempt it from the dropped-key warning here so a\n // correct `modelOptions: { max_tokens }` call doesn't log a spurious\n // \"dropped unknown key\" error, while keeping it out of the copy loop.\n const droppedKeyExemptSet = new Set<string>([...validKeys, 'max_tokens'])\n const droppedKeys = Object.keys(modelOptions).filter(\n (key) => !droppedKeyExemptSet.has(key),\n )\n if (droppedKeys.length > 0) {\n // Reachable when callers cast around the public type (e.g.\n // `modelOptions: { system: ... } as any`). Without this warning the\n // unknown keys are silently dropped — `system` in particular was a\n // previously-tested path for attaching `cache_control` and we don't\n // want that to fail in production with no signal.\n options.logger.errors(\n `anthropic.mapCommonOptionsToAnthropic dropped unknown modelOptions key(s): ${droppedKeys.join(', ')}`,\n {\n source: 'anthropic.mapCommonOptionsToAnthropic',\n droppedKeys,\n hint: droppedKeys.includes('system')\n ? 'pass system prompts via the top-level `systemPrompts` option; `modelOptions.system` is no longer honored'\n : undefined,\n },\n )\n }\n for (const key of validKeys) {\n if (key in modelOptions) {\n const value = modelOptions[key]\n if (key === 'tool_choice' && typeof value === 'string') {\n ;(validProviderOptions as Record<string, unknown>)[key] = {\n type: value,\n }\n } else {\n ;(validProviderOptions as Record<string, unknown>)[key] = value\n }\n }\n }\n }\n\n const thinkingBudget =\n validProviderOptions.thinking?.type === 'enabled'\n ? validProviderOptions.thinking.budget_tokens\n : undefined\n const defaultMaxTokens = modelOptions?.max_tokens ?? 1024\n const maxTokens =\n thinkingBudget && thinkingBudget >= defaultMaxTokens\n ? thinkingBudget + 1\n : defaultMaxTokens\n\n // `InternalTextProviderOptions.system` is typed\n // `string | Array<TextBlockParam>` (no `| undefined`), so build it\n // outside the literal and spread it conditionally rather than\n // assigning `undefined` under exactOptionalPropertyTypes.\n const systemBlocks = ((): Array<TextBlockParam> | undefined => {\n const normalized = normalizeSystemPrompts<AnthropicSystemPromptMetadata>(\n options.systemPrompts,\n )\n if (normalized.length === 0) return undefined\n return normalized.map(\n (p): TextBlockParam => ({\n type: 'text',\n text: p.content,\n ...(p.metadata?.cache_control && {\n cache_control: p.metadata.cache_control,\n }),\n }),\n )\n })()\n // Wire engine-threaded outputSchema into Messages `output_config.format`\n // alongside any `tools` so the model emits tool calls during the agent\n // loop and a single schema-constrained JSON message on its final turn.\n // Merge into any existing `output_config` so callers can keep tuning\n // `output_config.effort` alongside the schema.\n const combinedSchema = options.outputSchema as\n | Record<string, unknown>\n | undefined\n const outputConfig = combinedSchema\n ? {\n output_config: {\n ...(validProviderOptions.output_config ?? {}),\n format: {\n type: 'json_schema' as const,\n schema: combinedSchema,\n },\n },\n }\n : undefined\n\n // Lift skills attached to a `code_execution` tool into the top-level\n // `container.skills` request param (Anthropic's required shape). Preserve any\n // `container.id` supplied via modelOptions for container reuse. This is the\n // canonical path for skills; `modelOptions.container.skills` is deprecated.\n const toolSkills = options.tools\n ?.map((tool) =>\n tool.name === 'code_execution'\n ? readCodeExecutionSkills(tool)\n : undefined,\n )\n .find((skills) => skills && skills.length > 0)\n\n if (toolSkills && toolSkills.length > 0) {\n const existingContainer = validProviderOptions.container ?? undefined\n validProviderOptions.container = {\n id: existingContainer?.id ?? null,\n skills: toolSkills,\n }\n }\n\n // `temperature`/`top_p` arrive via `...validProviderOptions` (sourced from\n // `modelOptions`). `InternalTextProviderOptions` declares `system` and\n // `tools` as `T?: ...` (no `| undefined`), so spread them conditionally\n // rather than passing explicit `undefined` under exactOptionalPropertyTypes.\n const requestParams: InternalTextProviderOptions = {\n model: options.model,\n max_tokens: maxTokens,\n messages: formattedMessages,\n ...(systemBlocks !== undefined && { system: systemBlocks }),\n ...(tools !== undefined && { tools }),\n ...validProviderOptions,\n ...(outputConfig ?? {}),\n }\n validateTextProviderOptions(requestParams)\n return requestParams\n }\n\n /**\n * Anthropic supports `output_config.format` + `tools` in a single streaming\n * Messages request only for Claude 4.5+ (GA 2026-01-29). For 4.4 and\n * earlier we keep the forced-tool-use workaround in\n * {@link structuredOutput} via the engine's finalization path.\n */\n supportsCombinedToolsAndSchema(): boolean {\n return ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS.has(this.model)\n }\n\n private convertContentPartToAnthropic(\n part: ContentPart,\n ): TextBlockParam | ImageBlockParam | DocumentBlockParam {\n switch (part.type) {\n case 'text': {\n const metadata = part.metadata as AnthropicTextMetadata | undefined\n return {\n type: 'text',\n text: part.content,\n ...metadata,\n }\n }\n\n case 'image': {\n const metadata = part.metadata as AnthropicImageMetadata | undefined\n const imageSource: Base64ImageSource | URLImageSource =\n part.source.type === 'data'\n ? {\n type: 'base64',\n data: part.source.value,\n media_type: part.source.mimeType as\n | 'image/jpeg'\n | 'image/png'\n | 'image/gif'\n | 'image/webp',\n }\n : {\n type: 'url',\n url: part.source.value,\n }\n return {\n type: 'image',\n source: imageSource,\n ...metadata,\n }\n }\n case 'document': {\n const metadata = part.metadata as AnthropicDocumentMetadata | undefined\n const docSource: Base64PDFSource | URLPDFSource =\n part.source.type === 'data'\n ? {\n type: 'base64',\n data: part.source.value,\n media_type: part.source.mimeType as 'application/pdf',\n }\n : {\n type: 'url',\n url: part.source.value,\n }\n return {\n type: 'document',\n source: docSource,\n ...metadata,\n }\n }\n case 'audio':\n case 'video':\n throw new Error(\n `Anthropic does not support ${part.type} content directly`,\n )\n default: {\n const _exhaustiveCheck: never = part\n throw new Error(\n `Unsupported content part type: ${(_exhaustiveCheck as ContentPart).type}`,\n )\n }\n }\n }\n\n private formatMessages(\n messages: Array<ModelMessage>,\n ): InternalTextProviderOptions['messages'] {\n const formattedMessages: InternalTextProviderOptions['messages'] = []\n\n for (const message of messages) {\n const role = message.role\n\n if (role === 'tool' && message.toolCallId) {\n const toolContent = message.content\n formattedMessages.push({\n role: 'user',\n content: [\n {\n type: 'tool_result',\n tool_use_id: message.toolCallId,\n content: Array.isArray(toolContent)\n ? toolContent.map((part) =>\n this.convertContentPartToAnthropic(part),\n )\n : typeof toolContent === 'string'\n ? toolContent\n : '',\n },\n ],\n })\n continue\n }\n\n if (role === 'assistant' && message.toolCalls?.length) {\n const contentBlocks: Array<ContentBlockParam> = []\n\n this.appendThinkingBlocks(contentBlocks, message.thinking)\n\n if (message.content) {\n const content =\n typeof message.content === 'string' ? message.content : ''\n const textBlock: TextBlockParam = {\n type: 'text',\n text: content,\n }\n contentBlocks.push(textBlock)\n }\n\n for (const toolCall of message.toolCalls) {\n let parsedInput: unknown = {}\n try {\n const parsed = toolCall.function.arguments\n ? JSON.parse(toolCall.function.arguments)\n : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = toolCall.function.arguments\n }\n\n // Provider-executed server tools (e.g. web_search) replay as the\n // original `server_tool_use` + result blocks so the model still sees\n // the prior evidence. Their result was captured verbatim during\n // streaming (see processAnthropicStream).\n const serverMeta = readAnthropicServerToolMetadata(toolCall.metadata)\n if (serverMeta) {\n const serverToolUseBlock: ServerToolUseBlockParam = {\n type: 'server_tool_use',\n id: toolCall.id,\n name: serverMeta.serverToolType,\n input: parsedInput,\n }\n contentBlocks.push(serverToolUseBlock)\n contentBlocks.push(\n buildServerToolResultBlock(toolCall.id, serverMeta),\n )\n continue\n }\n\n const toolUseBlock: ToolUseBlockParam = {\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.function.name,\n input: parsedInput,\n }\n contentBlocks.push(toolUseBlock)\n }\n\n formattedMessages.push({\n role: 'assistant',\n content: contentBlocks,\n })\n\n continue\n }\n\n if (role === 'assistant') {\n const contentBlocks: Array<ContentBlockParam> = []\n this.appendThinkingBlocks(contentBlocks, message.thinking)\n\n if (Array.isArray(message.content)) {\n for (const part of message.content) {\n contentBlocks.push(this.convertContentPartToAnthropic(part))\n }\n } else if (message.content) {\n contentBlocks.push({\n type: 'text',\n text: message.content,\n })\n }\n\n formattedMessages.push({\n role: 'assistant',\n content: contentBlocks.length > 0 ? contentBlocks : '',\n })\n continue\n }\n\n if (role === 'user' && Array.isArray(message.content)) {\n const contentBlocks = message.content.map((part) =>\n this.convertContentPartToAnthropic(part),\n )\n formattedMessages.push({\n role: 'user',\n content: contentBlocks,\n })\n continue\n }\n\n formattedMessages.push({\n role: 'user',\n content:\n typeof message.content === 'string'\n ? message.content\n : message.content\n ? message.content.map((c) =>\n this.convertContentPartToAnthropic(c),\n )\n : '',\n })\n }\n\n // Post-process: Anthropic requires strictly alternating user/assistant roles.\n // Tool results are sent as role:'user' messages, which can create consecutive\n // user messages when followed by a new user message. Merge them.\n return this.mergeConsecutiveSameRoleMessages(formattedMessages)\n }\n\n private appendThinkingBlocks(\n contentBlocks: Array<ContentBlockParam>,\n thinkingParts: ModelMessage['thinking'],\n ): void {\n if (!thinkingParts?.length) return\n\n for (const thinking of thinkingParts) {\n if (!thinking.signature) continue\n const block: ThinkingBlockParam = {\n type: 'thinking',\n thinking: thinking.content,\n signature: thinking.signature,\n }\n contentBlocks.push(block)\n }\n }\n\n /**\n * Merge consecutive messages of the same role into a single message.\n * Anthropic's API requires strictly alternating user/assistant roles.\n * Tool results are wrapped as role:'user' messages, which can collide\n * with actual user messages in multi-turn conversations.\n *\n * Also filters out empty assistant messages (e.g., from a previous failed request).\n */\n private mergeConsecutiveSameRoleMessages(\n messages: InternalTextProviderOptions['messages'],\n ): InternalTextProviderOptions['messages'] {\n const merged: InternalTextProviderOptions['messages'] = []\n\n for (const msg of messages) {\n // Skip empty assistant messages (no content or empty string)\n if (msg.role === 'assistant') {\n const hasContent = Array.isArray(msg.content)\n ? msg.content.length > 0\n : typeof msg.content === 'string' && msg.content.length > 0\n if (!hasContent) {\n continue\n }\n }\n\n const prev = merged[merged.length - 1]\n if (prev && prev.role === msg.role) {\n // Normalize both contents to arrays and concatenate\n const prevBlocks = Array.isArray(prev.content)\n ? prev.content\n : typeof prev.content === 'string' && prev.content\n ? [{ type: 'text' as const, text: prev.content }]\n : []\n const msgBlocks = Array.isArray(msg.content)\n ? msg.content\n : typeof msg.content === 'string' && msg.content\n ? [{ type: 'text' as const, text: msg.content }]\n : []\n prev.content = [...prevBlocks, ...msgBlocks]\n } else {\n merged.push({ ...msg })\n }\n }\n\n // De-duplicate tool_result blocks with the same tool_use_id.\n // This can happen when the core layer generates tool results from both\n // the tool-result part and the tool-call part's output field.\n for (const msg of merged) {\n if (Array.isArray(msg.content)) {\n const seenToolResultIds = new Set<string>()\n msg.content = msg.content.filter((block: any) => {\n if (block.type === 'tool_result' && block.tool_use_id) {\n if (seenToolResultIds.has(block.tool_use_id)) {\n return false // Remove duplicate\n }\n seenToolResultIds.add(block.tool_use_id)\n }\n return true\n })\n }\n }\n\n return merged\n }\n\n private async *processAnthropicStream(\n stream: AsyncIterable<Anthropic_SDK.Beta.BetaRawMessageStreamEvent>,\n options: TextOptions<AnthropicTextProviderOptions>,\n genId: () => string,\n logger: InternalLogger,\n ): AsyncIterable<StreamChunk> {\n const model = options.model\n let accumulatedContent = ''\n let accumulatedThinking = ''\n let accumulatedSignature = ''\n const toolCallsMap = new Map<\n number,\n { id: string; name: string; input: string; started: boolean }\n >()\n let currentToolIndex = -1\n // Server-side tools share the `input_json_delta` wire format with client\n // `tool_use` blocks; routing both to the same buffer corrupts client tool\n // input.\n let currentServerTool: { id: string; name: string; input: string } | null =\n null\n // Completed server tools awaiting their matching result block. Anthropic\n // emits `server_tool_use` then a separate `*_tool_result` block; we hold\n // the call here (keyed by id) until the result arrives so we can emit a\n // single provider-executed tool call carrying the raw result for round-trip.\n const completedServerTools = new Map<\n string,\n { id: string; name: string; input: string }\n >()\n\n // AG-UI lifecycle tracking\n const runId = options.runId ?? genId()\n const threadId = options.threadId ?? genId()\n const messageId = genId()\n let stepId: string | null = null\n let reasoningMessageId: string | null = null\n let hasClosedReasoning = false\n let hasEmittedRunStarted = false\n let hasEmittedTextMessageStart = false\n let hasEmittedRunFinished = false\n // Track current content block type for proper content_block_stop handling\n let currentBlockType: string | null = null\n\n try {\n for await (const event of stream) {\n logger.provider(`provider=anthropic type=${event.type}`, {\n chunk: event,\n })\n // Emit RUN_STARTED on first event\n if (!hasEmittedRunStarted) {\n hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n parentRunId: options.parentRunId,\n }\n }\n\n if (event.type === 'content_block_start') {\n currentBlockType = event.content_block.type\n if (event.content_block.type === 'tool_use') {\n currentToolIndex++\n toolCallsMap.set(currentToolIndex, {\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n started: false,\n })\n } else if (event.content_block.type === 'server_tool_use') {\n currentServerTool = {\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n }\n } else if (\n event.content_block.type === 'web_fetch_tool_result' ||\n event.content_block.type === 'web_search_tool_result'\n ) {\n // The result content arrives in full at content_block_start (no\n // deltas). Surface error variants so a failed fetch/search isn't\n // invisible to the consumer.\n const content = event.content_block.content as\n | { type?: string; error_code?: string }\n | Array<unknown>\n const errorBlock =\n !Array.isArray(content) &&\n (content.type === 'web_fetch_tool_result_error' ||\n content.type === 'web_search_tool_result_error')\n ? content\n : null\n if (errorBlock) {\n logger.errors(\n `anthropic.${event.content_block.type} error_code=${errorBlock.error_code}`,\n {\n toolUseId: event.content_block.tool_use_id,\n blockType: event.content_block.type,\n errorCode: errorBlock.error_code,\n source: 'anthropic.processAnthropicStream',\n },\n )\n }\n\n // Emit the server tool as a single provider-executed tool call,\n // carrying its raw result so the evidence (e.g. web_search sources)\n // round-trips into the next turn's request. The agent loop skips\n // provider-executed calls, so this never triggers client execution.\n const serverTool = completedServerTools.get(\n event.content_block.tool_use_id,\n )\n if (serverTool) {\n completedServerTools.delete(serverTool.id)\n\n let parsedInput: unknown = {}\n try {\n const parsed = serverTool.input\n ? JSON.parse(serverTool.input)\n : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = {}\n }\n\n const serverToolMetadata = {\n providerExecuted: true,\n anthropic: {\n serverToolType: serverTool.name,\n resultBlockType: event.content_block.type,\n result: content,\n },\n }\n\n currentToolIndex++\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: serverTool.id,\n toolCallName: serverTool.name,\n toolName: serverTool.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n metadata: serverToolMetadata,\n }\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: serverTool.id,\n toolCallName: serverTool.name,\n toolName: serverTool.name,\n model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n\n // Text after the server tool starts a fresh message segment.\n hasEmittedTextMessageStart = false\n }\n } else if (event.content_block.type === 'thinking') {\n accumulatedThinking = ''\n accumulatedSignature = ''\n // Emit REASONING and STEP_STARTED for thinking\n stepId = genId()\n reasoningMessageId = genId()\n\n // Spec REASONING events\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning' as const,\n model,\n timestamp: Date.now(),\n }\n\n // Legacy STEP events (kept during transition)\n yield {\n type: EventType.STEP_STARTED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n stepType: 'thinking',\n }\n }\n } else if (event.type === 'content_block_delta') {\n if (event.delta.type === 'text_delta') {\n // Close reasoning before text starts\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n // Emit TEXT_MESSAGE_START on first text content\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n\n const delta = event.delta.text\n accumulatedContent += delta\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp: Date.now(),\n delta,\n content: accumulatedContent,\n }\n } else if (\n event.delta.type === 'thinking_delta' &&\n reasoningMessageId\n ) {\n const delta = event.delta.thinking\n accumulatedThinking += delta\n\n // Spec REASONING content event\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta,\n model,\n timestamp: Date.now(),\n }\n\n // Legacy STEP event\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId || genId(),\n stepId: stepId || genId(),\n model,\n timestamp: Date.now(),\n delta,\n content: accumulatedThinking,\n }\n } else if (\n (event.delta as { type: string }).type === 'signature_delta'\n ) {\n accumulatedSignature +=\n (event.delta as { signature: string }).signature || ''\n } else if (event.delta.type === 'input_json_delta') {\n // Route deltas by current block type so server_tool_use input\n // never appends onto the prior client tool's buffer.\n if (currentBlockType === 'tool_use') {\n const existing = toolCallsMap.get(currentToolIndex)\n if (existing) {\n // Emit TOOL_CALL_START on first args delta\n if (!existing.started) {\n existing.started = true\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n }\n }\n\n existing.input += event.delta.partial_json\n\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: existing.id,\n model,\n timestamp: Date.now(),\n delta: event.delta.partial_json,\n args: existing.input,\n }\n }\n } else if (\n currentBlockType === 'server_tool_use' &&\n currentServerTool\n ) {\n // Accumulate server tool input internally. We don't emit\n // TOOL_CALL_* events: the call is executed by Anthropic, not\n // by our agent loop, so surfacing it as a client tool call\n // would cause downstream code to try (and fail) to run it.\n currentServerTool.input += event.delta.partial_json\n }\n }\n } else if (event.type === 'content_block_stop') {\n if (currentBlockType === 'thinking') {\n // Emit signature so it can be replayed in multi-turn context\n if (accumulatedSignature && stepId) {\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n delta: '',\n content: accumulatedThinking,\n signature: accumulatedSignature,\n }\n }\n } else if (currentBlockType === 'tool_use') {\n const existing = toolCallsMap.get(currentToolIndex)\n if (existing) {\n // If tool call wasn't started yet (no args), start it now\n if (!existing.started) {\n existing.started = true\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n }\n }\n\n // Emit TOOL_CALL_END\n let parsedInput: unknown = {}\n try {\n const parsed = existing.input ? JSON.parse(existing.input) : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = {}\n }\n\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n\n // Reset so a new TEXT_MESSAGE_START is emitted if text follows tool calls\n hasEmittedTextMessageStart = false\n }\n } else if (currentBlockType === 'server_tool_use') {\n if (currentServerTool) {\n // Anthropic executes the call; we only need a breadcrumb so\n // consumers (devtools, telemetry) can see what ran.\n logger.provider(\n `provider=anthropic server_tool_use name=${currentServerTool.name}`,\n {\n toolUseId: currentServerTool.id,\n name: currentServerTool.name,\n input: currentServerTool.input,\n },\n )\n // Hold the call until its result block arrives so we can emit\n // both together as one provider-executed tool call.\n completedServerTools.set(currentServerTool.id, currentServerTool)\n }\n currentServerTool = null\n } else if (\n currentBlockType === 'web_fetch_tool_result' ||\n currentBlockType === 'web_search_tool_result'\n ) {\n // The model already consumed the result; error variants were\n // already surfaced at content_block_start.\n } else {\n // Emit TEXT_MESSAGE_END only for text blocks (not tool_use blocks)\n if (hasEmittedTextMessageStart && accumulatedContent) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n model,\n timestamp: Date.now(),\n }\n }\n }\n currentBlockType = null\n } else if (event.type === 'message_stop') {\n // Close reasoning events if still open\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n // Only emit RUN_FINISHED from message_stop if message_delta didn't already emit one.\n // message_delta carries the real stop_reason (tool_use, end_turn, etc.),\n // while message_stop is just a completion signal.\n if (!hasEmittedRunFinished) {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'stop',\n }\n }\n } else if (event.type === 'message_delta') {\n if (event.delta.stop_reason) {\n hasEmittedRunFinished = true\n\n // Close reasoning events if still open\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n switch (event.delta.stop_reason) {\n case 'tool_use': {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'tool_calls',\n usage: buildAnthropicUsage(event.usage),\n }\n break\n }\n case 'max_tokens': {\n yield {\n type: EventType.RUN_ERROR,\n model,\n timestamp: Date.now(),\n message:\n 'The response was cut off because the maximum token limit was reached.',\n code: 'max_tokens',\n error: {\n message:\n 'The response was cut off because the maximum token limit was reached.',\n code: 'max_tokens',\n },\n }\n break\n }\n case 'stop_sequence':\n case 'end_turn':\n case 'pause_turn':\n case 'refusal':\n case 'model_context_window_exceeded':\n case 'compaction':\n default: {\n // All remaining Anthropic stop_reason variants map to the\n // generic \"stop\" finish reason — they describe *why* the\n // stream ended, but for AG-UI consumers the resulting event\n // shape is identical.\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'stop',\n usage: buildAnthropicUsage(event.usage),\n }\n }\n }\n }\n }\n }\n } catch (error: unknown) {\n const err = error as Error & { status?: number; code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n\n logger.errors('anthropic.processAnthropicStream fatal', {\n error,\n source: 'anthropic.processAnthropicStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n // Forward the Anthropic SDK error's `.error` response body when present.\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n },\n }\n }\n }\n}\n\n/**\n * Creates an Anthropic chat adapter with explicit API key.\n * Type resolution happens here at the call site.\n */\nexport function createAnthropicChat<\n TModel extends (typeof ANTHROPIC_MODELS)[number],\n>(\n model: TModel,\n apiKey: string,\n config?: Omit<AnthropicTextConfig, 'apiKey'>,\n): AnthropicTextAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>\n> {\n return new AnthropicTextAdapter({ apiKey, ...config }, model)\n}\n\n/**\n * Creates an Anthropic text adapter with automatic API key detection.\n * Type resolution happens here at the call site.\n */\nexport function anthropicText<TModel extends (typeof ANTHROPIC_MODELS)[number]>(\n model: TModel,\n config?: Omit<AnthropicTextConfig, 'apiKey'>,\n): AnthropicTextAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>\n> {\n const apiKey = getAnthropicApiKeyFromEnv()\n return createAnthropicChat(model, apiKey, config)\n}\n"],"names":[],"mappings":";;;;;;;;;A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+
{"version":3,"file":"text.js","sources":["../../../src/adapters/text.ts"],"sourcesContent":["import { EventType, normalizeSystemPrompts } from '@tanstack/ai'\nimport { toRunErrorRawEvent } from '@tanstack/ai/adapter-internals'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport { convertToolsToProviderFormat } from '../tools/tool-converter'\nimport { readCodeExecutionConfig, readCodeExecutionSkills } from '../tools'\nimport { validateTextProviderOptions } from '../text/text-provider-options'\nimport { buildAnthropicUsage } from '../usage'\nimport {\n createAnthropicClient,\n generateId,\n getAnthropicApiKeyFromEnv,\n} from '../utils'\nimport {\n ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS,\n getAnthropicDefaultMaxTokens,\n} from '../model-meta'\nimport type {\n ANTHROPIC_MODELS,\n AnthropicChatModelProviderOptionsByName,\n AnthropicChatModelToolCapabilitiesByName,\n AnthropicModelInputModalitiesByName,\n} from '../model-meta'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type { InternalLogger } from '@tanstack/ai/adapter-internals'\nimport type {\n Base64ImageSource,\n Base64PDFSource,\n ContentBlockParam,\n DocumentBlockParam,\n ImageBlockParam,\n ServerToolUseBlockParam,\n TextBlockParam,\n ThinkingBlockParam,\n ToolUseBlockParam,\n URLImageSource,\n URLPDFSource,\n WebFetchToolResultBlockParam,\n WebSearchToolResultBlockParam,\n} from '@anthropic-ai/sdk/resources/messages'\nimport type Anthropic_SDK from '@anthropic-ai/sdk'\nimport type { AnthropicBeta } from '@anthropic-ai/sdk/resources/beta/beta'\nimport type {\n AnyTool,\n ContentPart,\n Modality,\n ModelMessage,\n StreamChunk,\n TextOptions,\n} from '@tanstack/ai'\nimport type {\n AnthropicSystemPromptMetadata,\n ExternalTextProviderOptions,\n InternalTextProviderOptions,\n} from '../text/text-provider-options'\nimport type {\n AnthropicDocumentMetadata,\n AnthropicImageMetadata,\n AnthropicMessageMetadataByModality,\n AnthropicTextMetadata,\n} from '../message-types'\nimport type { AnthropicClientConfig } from '../utils'\n\n/**\n * The block type carried by an Anthropic provider-executed (server) tool's\n * stored result. Mirrors the `*_tool_result` block emitted by the streaming\n * API so it can be replayed verbatim into a later turn.\n */\ntype AnthropicServerToolResultBlockType =\n | 'web_search_tool_result'\n | 'web_fetch_tool_result'\n\n/**\n * Anthropic payload stashed on a provider-executed tool call's `metadata`\n * (under the `anthropic` key, alongside `providerExecuted: true`). Holds enough\n * to reconstruct the original `server_tool_use` + `*_tool_result` blocks so the\n * model still sees prior `web_search` / `web_fetch` evidence on the next turn.\n */\ninterface AnthropicServerToolMetadata {\n serverToolType: ServerToolUseBlockParam['name']\n resultBlockType: AnthropicServerToolResultBlockType\n /** Raw result block content, preserved verbatim from the stream. */\n result: unknown\n}\n\n/**\n * Narrow an opaque tool-call `metadata` to {@link AnthropicServerToolMetadata}\n * when it follows the provider-executed convention, else `null`.\n */\nfunction readAnthropicServerToolMetadata(\n metadata: unknown,\n): AnthropicServerToolMetadata | null {\n if (typeof metadata !== 'object' || metadata === null) return null\n const outer = metadata as { providerExecuted?: unknown; anthropic?: unknown }\n if (outer.providerExecuted !== true) return null\n const inner = outer.anthropic\n if (typeof inner !== 'object' || inner === null) return null\n const { serverToolType, resultBlockType, result } = inner as {\n serverToolType?: unknown\n resultBlockType?: unknown\n result?: unknown\n }\n if (\n typeof serverToolType !== 'string' ||\n (resultBlockType !== 'web_search_tool_result' &&\n resultBlockType !== 'web_fetch_tool_result')\n ) {\n return null\n }\n return {\n // Validated as a string above; widen back to the SDK's tool-name union.\n serverToolType: serverToolType as ServerToolUseBlockParam['name'],\n resultBlockType,\n result,\n }\n}\n\n/**\n * Reconstruct the `*_tool_result` block param from stored server-tool metadata.\n * The `result` content is opaque round-trip data, asserted to the SDK's param\n * content type at this single boundary.\n */\nfunction buildServerToolResultBlock(\n toolUseId: string,\n meta: AnthropicServerToolMetadata,\n): WebSearchToolResultBlockParam | WebFetchToolResultBlockParam {\n if (meta.resultBlockType === 'web_search_tool_result') {\n return {\n type: 'web_search_tool_result',\n tool_use_id: toolUseId,\n content: meta.result as WebSearchToolResultBlockParam['content'],\n }\n }\n return {\n type: 'web_fetch_tool_result',\n tool_use_id: toolUseId,\n content: meta.result as WebFetchToolResultBlockParam['content'],\n }\n}\n\n/**\n * Computes the `betas` array for a Messages request. Unions:\n * - `interleaved-thinking-2025-05-14` when interleaved thinking is enabled,\n * - `code-execution-2025-08-25` when a `code_execution` tool is present,\n * - `skills-2025-10-02` when that tool carries skills.\n * Returns `undefined` when none apply (so the call site omits `betas`).\n */\nexport function computeAnthropicBetas(\n tools: Array<AnyTool> | undefined,\n modelOptions:\n | {\n thinking?: {\n type?: 'enabled' | 'disabled' | 'adaptive'\n budget_tokens?: number\n }\n }\n | undefined,\n): Array<AnthropicBeta> | undefined {\n const betas = new Set<AnthropicBeta>()\n\n const useInterleavedThinking =\n modelOptions?.thinking?.type === 'enabled' &&\n typeof modelOptions.thinking.budget_tokens === 'number' &&\n modelOptions.thinking.budget_tokens > 0\n if (useInterleavedThinking) betas.add('interleaved-thinking-2025-05-14')\n\n // Code-execution beta is version-aware: select from the FIRST code_execution\n // tool's config type.\n const codeExecTool = tools?.find((t) => t.name === 'code_execution')\n if (codeExecTool) {\n const cfgType = readCodeExecutionConfig(codeExecTool)?.type\n // Each code_execution tool version pairs with a specific beta. Known\n // legacy variant maps explicitly; current/future variants (e.g.\n // `code_execution_20250825` and later) use the latest `-08-25` beta.\n betas.add(\n cfgType === 'code_execution_20250522'\n ? 'code-execution-2025-05-22'\n : 'code-execution-2025-08-25',\n )\n }\n\n // Skills beta: scan ALL code_execution tools so this AGREES with the\n // container-lift, which lifts skills from any code_execution tool that\n // carries them (not just the first).\n const hasSkills = tools?.some(\n (t) =>\n t.name === 'code_execution' &&\n (readCodeExecutionSkills(t)?.length ?? 0) > 0,\n )\n if (hasSkills) betas.add('skills-2025-10-02')\n\n return betas.size > 0 ? Array.from(betas) : undefined\n}\n\n/**\n * Configuration for Anthropic text adapter\n */\nexport interface AnthropicTextConfig extends AnthropicClientConfig {}\n\n/**\n * Anthropic-specific provider options for text/chat\n */\nexport type AnthropicTextProviderOptions = ExternalTextProviderOptions\n\n// ===========================\n// Type Resolution Helpers\n// ===========================\n\n/**\n * Resolve provider options for a specific model.\n * If the model has explicit options in the map, use those; otherwise use base options.\n */\ntype ResolveProviderOptions<TModel extends string> =\n TModel extends keyof AnthropicChatModelProviderOptionsByName\n ? AnthropicChatModelProviderOptionsByName[TModel]\n : AnthropicTextProviderOptions\n\n/**\n * Resolve input modalities for a specific model.\n * If the model has explicit modalities in the map, use those; otherwise use default.\n */\ntype ResolveInputModalities<TModel extends string> =\n TModel extends keyof AnthropicModelInputModalitiesByName\n ? AnthropicModelInputModalitiesByName[TModel]\n : readonly ['text', 'image', 'document']\n\ntype ResolveToolCapabilities<TModel extends string> =\n TModel extends keyof AnthropicChatModelToolCapabilitiesByName\n ? NonNullable<AnthropicChatModelToolCapabilitiesByName[TModel]>\n : readonly []\n\n// ===========================\n// Adapter Implementation\n// ===========================\n\n/**\n * Anthropic Text (Chat) Adapter\n *\n * Tree-shakeable adapter for Anthropic chat/text completion functionality.\n * Import only what you need for smaller bundle sizes.\n */\nexport class AnthropicTextAdapter<\n TModel extends (typeof ANTHROPIC_MODELS)[number],\n TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,\n TInputModalities extends ReadonlyArray<Modality> =\n ResolveInputModalities<TModel>,\n TToolCapabilities extends ReadonlyArray<string> =\n ResolveToolCapabilities<TModel>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n AnthropicMessageMetadataByModality,\n TToolCapabilities,\n // TToolCallMetadata — anthropic has no tool-call metadata round-tripping\n unknown,\n // TSystemPromptMetadata — narrows `systemPrompts[i].metadata` at the\n // chat() call site so users get `cache_control` autocomplete.\n AnthropicSystemPromptMetadata\n> {\n override readonly kind = 'text' as const\n readonly name = 'anthropic' as const\n\n private readonly client: Anthropic_SDK\n\n constructor(config: AnthropicTextConfig, model: TModel) {\n super({}, model)\n this.client = createAnthropicClient(config)\n }\n\n async *chatStream(\n options: TextOptions<TProviderOptions>,\n ): AsyncIterable<StreamChunk> {\n const { logger } = options\n try {\n const requestParams = this.mapCommonOptionsToAnthropic(options)\n\n logger.request(\n `activity=chat provider=anthropic model=${this.model} messages=${options.messages.length} tools=${options.tools?.length ?? 0} stream=true`,\n { provider: 'anthropic', model: this.model },\n )\n\n // `betas` is attached at the call site rather than in the shared mapper\n // because the beta set depends on both the tools and the modelOptions.\n const betas = computeAnthropicBetas(options.tools, options.modelOptions)\n\n // `client.beta.messages` is Anthropic's permanent staging surface, not a\n // sunset path: it's a superset of `client.messages` that additionally\n // accepts the `betas: AnthropicBeta[]` header (e.g. interleaved\n // thinking) plus richer `container` (skills) and `context_management`\n // shapes that `InternalTextProviderOptions` carries. We route every\n // Messages call through it so the request mapper stays single-shape.\n const stream = await this.client.beta.messages.create(\n {\n ...requestParams,\n stream: true,\n ...(betas && { betas }),\n },\n {\n signal: options.request?.signal,\n headers: options.request?.headers,\n },\n )\n\n yield* this.processAnthropicStream(\n stream,\n options,\n () => generateId(this.name),\n logger,\n )\n } catch (error: unknown) {\n const err = error as Error & { status?: number; code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n logger.errors('anthropic.chatStream fatal', {\n error,\n source: 'anthropic.chatStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model: options.model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n // Forward the Anthropic SDK error's `.error` response body (e.g.\n // `{ type, message }`) when present; never the raw exception object.\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n },\n }\n }\n }\n\n /**\n * Generate structured output using Anthropic's tool-based approach.\n * Anthropic doesn't have native structured output, so we use a tool with the schema\n * and force the model to call it.\n * The outputSchema is already JSON Schema (converted in the ai layer).\n */\n async structuredOutput(\n options: StructuredOutputOptions<TProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const { logger } = chatOptions\n\n // `structuredOutput()` issues a non-streaming `messages.create({ stream:\n // false })` below, so the defaulted `max_tokens` must stay under the SDK's\n // non-streaming 10-minute guard (issue #849) — pass `stream: false`.\n const requestParams = this.mapCommonOptionsToAnthropic(chatOptions, {\n stream: false,\n })\n\n // Create a tool that will capture the structured output\n // Anthropic's SDK requires input_schema with type: 'object' literal\n const structuredOutputTool = {\n name: 'structured_output',\n description:\n 'Use this tool to provide your response in the required structured format.',\n input_schema: {\n type: 'object' as const,\n properties: outputSchema.properties ?? {},\n required: outputSchema.required ?? [],\n },\n }\n\n try {\n logger.request(\n `activity=chat provider=anthropic model=${this.model} messages=${chatOptions.messages.length} tools=${chatOptions.tools?.length ?? 0} stream=false`,\n { provider: 'anthropic', model: this.model },\n )\n const betas = computeAnthropicBetas(\n chatOptions.tools,\n chatOptions.modelOptions,\n )\n // Make non-streaming request with tool_choice forced to our structured output tool\n const response = await this.client.beta.messages.create(\n {\n ...requestParams,\n stream: false,\n tools: [structuredOutputTool],\n tool_choice: { type: 'tool', name: 'structured_output' },\n ...(betas && { betas }),\n },\n {\n signal: chatOptions.request?.signal,\n headers: chatOptions.request?.headers,\n },\n )\n\n // Extract the tool use content from the response\n let parsed: unknown = null\n let rawText = ''\n\n for (const block of response.content) {\n if (block.type === 'tool_use' && block.name === 'structured_output') {\n parsed = block.input\n rawText = JSON.stringify(block.input)\n break\n }\n }\n\n if (parsed === null) {\n // Fallback: try to extract text content and parse as JSON\n rawText = response.content\n .map((b) => {\n if (b.type === 'text') {\n return b.text\n }\n return ''\n })\n .join('')\n try {\n parsed = JSON.parse(rawText)\n } catch {\n throw new Error(\n `Failed to extract structured output from response. Content: ${rawText.slice(0, 200)}${rawText.length > 200 ? '...' : ''}`,\n )\n }\n }\n\n return {\n data: parsed,\n rawText,\n usage: buildAnthropicUsage(response.usage),\n }\n } catch (error: unknown) {\n const err = error as Error\n logger.errors('anthropic.structuredOutput fatal', {\n error,\n source: 'anthropic.structuredOutput',\n })\n throw new Error(\n `Structured output generation failed: ${err.message || 'Unknown error occurred'}`,\n )\n }\n }\n\n private mapCommonOptionsToAnthropic(\n options: TextOptions<AnthropicTextProviderOptions>,\n { stream = true }: { stream?: boolean } = {},\n ) {\n const modelOptions = options.modelOptions\n\n const formattedMessages = this.formatMessages(options.messages)\n const tools = options.tools\n ? convertToolsToProviderFormat(options.tools)\n : undefined\n\n const validProviderOptions: Partial<InternalTextProviderOptions> = {}\n if (modelOptions) {\n const validKeys: Array<keyof AnthropicTextProviderOptions> = [\n 'container',\n 'context_management',\n 'effort',\n 'mcp_servers',\n 'output_config',\n 'service_tier',\n 'stop_sequences',\n 'thinking',\n 'tool_choice',\n 'top_k',\n 'temperature',\n 'top_p',\n ]\n // `max_tokens` is a legitimate public modelOptions field, but it is read\n // via a dedicated path (defaultMaxTokens below) rather than copied into\n // validProviderOptions. Exempt it from the dropped-key warning here so a\n // correct `modelOptions: { max_tokens }` call doesn't log a spurious\n // \"dropped unknown key\" error, while keeping it out of the copy loop.\n const droppedKeyExemptSet = new Set<string>([...validKeys, 'max_tokens'])\n const droppedKeys = Object.keys(modelOptions).filter(\n (key) => !droppedKeyExemptSet.has(key),\n )\n if (droppedKeys.length > 0) {\n // Reachable when callers cast around the public type (e.g.\n // `modelOptions: { system: ... } as any`). Without this warning the\n // unknown keys are silently dropped — `system` in particular was a\n // previously-tested path for attaching `cache_control` and we don't\n // want that to fail in production with no signal.\n options.logger.errors(\n `anthropic.mapCommonOptionsToAnthropic dropped unknown modelOptions key(s): ${droppedKeys.join(', ')}`,\n {\n source: 'anthropic.mapCommonOptionsToAnthropic',\n droppedKeys,\n hint: droppedKeys.includes('system')\n ? 'pass system prompts via the top-level `systemPrompts` option; `modelOptions.system` is no longer honored'\n : undefined,\n },\n )\n }\n for (const key of validKeys) {\n if (key in modelOptions) {\n const value = modelOptions[key]\n if (key === 'tool_choice' && typeof value === 'string') {\n ;(validProviderOptions as Record<string, unknown>)[key] = {\n type: value,\n }\n } else {\n ;(validProviderOptions as Record<string, unknown>)[key] = value\n }\n }\n }\n }\n\n const thinkingBudget =\n validProviderOptions.thinking?.type === 'enabled'\n ? validProviderOptions.thinking.budget_tokens\n : undefined\n // Anthropic's Messages API *requires* `max_tokens`, so we must always send a\n // value. When the caller doesn't specify one, default to the resolved\n // model's real output ceiling (from model-meta) rather than a low constant\n // that silently truncates long responses with `stop_reason: \"max_tokens\"`\n // (issue #849). `max_tokens` is a ceiling, not a reservation — billing is on\n // tokens actually generated, so a higher default costs nothing extra.\n // For non-streaming requests (the `structuredOutput()` path) the default is\n // clamped to the SDK's non-streaming-safe limit so it doesn't trip the\n // \"streaming required\" 10-minute guard — see getAnthropicDefaultMaxTokens.\n const defaultMaxTokens =\n modelOptions?.max_tokens ??\n getAnthropicDefaultMaxTokens(this.model, { stream })\n const maxTokens =\n thinkingBudget && thinkingBudget >= defaultMaxTokens\n ? thinkingBudget + 1\n : defaultMaxTokens\n\n // `InternalTextProviderOptions.system` is typed\n // `string | Array<TextBlockParam>` (no `| undefined`), so build it\n // outside the literal and spread it conditionally rather than\n // assigning `undefined` under exactOptionalPropertyTypes.\n const systemBlocks = ((): Array<TextBlockParam> | undefined => {\n const normalized = normalizeSystemPrompts<AnthropicSystemPromptMetadata>(\n options.systemPrompts,\n )\n if (normalized.length === 0) return undefined\n return normalized.map(\n (p): TextBlockParam => ({\n type: 'text',\n text: p.content,\n ...(p.metadata?.cache_control && {\n cache_control: p.metadata.cache_control,\n }),\n }),\n )\n })()\n // Wire engine-threaded outputSchema into Messages `output_config.format`\n // alongside any `tools` so the model emits tool calls during the agent\n // loop and a single schema-constrained JSON message on its final turn.\n // Merge into any existing `output_config` so callers can keep tuning\n // `output_config.effort` alongside the schema.\n const combinedSchema = options.outputSchema as\n | Record<string, unknown>\n | undefined\n const outputConfig = combinedSchema\n ? {\n output_config: {\n ...(validProviderOptions.output_config ?? {}),\n format: {\n type: 'json_schema' as const,\n schema: combinedSchema,\n },\n },\n }\n : undefined\n\n // Lift skills attached to a `code_execution` tool into the top-level\n // `container.skills` request param (Anthropic's required shape). Preserve any\n // `container.id` supplied via modelOptions for container reuse. This is the\n // canonical path for skills; `modelOptions.container.skills` is deprecated.\n const toolSkills = options.tools\n ?.map((tool) =>\n tool.name === 'code_execution'\n ? readCodeExecutionSkills(tool)\n : undefined,\n )\n .find((skills) => skills && skills.length > 0)\n\n if (toolSkills && toolSkills.length > 0) {\n const existingContainer = validProviderOptions.container ?? undefined\n validProviderOptions.container = {\n id: existingContainer?.id ?? null,\n skills: toolSkills,\n }\n }\n\n // `temperature`/`top_p` arrive via `...validProviderOptions` (sourced from\n // `modelOptions`). `InternalTextProviderOptions` declares `system` and\n // `tools` as `T?: ...` (no `| undefined`), so spread them conditionally\n // rather than passing explicit `undefined` under exactOptionalPropertyTypes.\n const requestParams: InternalTextProviderOptions = {\n model: options.model,\n max_tokens: maxTokens,\n messages: formattedMessages,\n ...(systemBlocks !== undefined && { system: systemBlocks }),\n ...(tools !== undefined && { tools }),\n ...validProviderOptions,\n ...(outputConfig ?? {}),\n }\n validateTextProviderOptions(requestParams)\n return requestParams\n }\n\n /**\n * Anthropic supports `output_config.format` + `tools` in a single streaming\n * Messages request only for Claude 4.5+ (GA 2026-01-29). For 4.4 and\n * earlier we keep the forced-tool-use workaround in\n * {@link structuredOutput} via the engine's finalization path.\n */\n supportsCombinedToolsAndSchema(): boolean {\n return ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS.has(this.model)\n }\n\n private convertContentPartToAnthropic(\n part: ContentPart,\n ): TextBlockParam | ImageBlockParam | DocumentBlockParam {\n switch (part.type) {\n case 'text': {\n const metadata = part.metadata as AnthropicTextMetadata | undefined\n return {\n type: 'text',\n text: part.content,\n ...metadata,\n }\n }\n\n case 'image': {\n const metadata = part.metadata as AnthropicImageMetadata | undefined\n const imageSource: Base64ImageSource | URLImageSource =\n part.source.type === 'data'\n ? {\n type: 'base64',\n data: part.source.value,\n media_type: part.source.mimeType as\n | 'image/jpeg'\n | 'image/png'\n | 'image/gif'\n | 'image/webp',\n }\n : {\n type: 'url',\n url: part.source.value,\n }\n return {\n type: 'image',\n source: imageSource,\n ...metadata,\n }\n }\n case 'document': {\n const metadata = part.metadata as AnthropicDocumentMetadata | undefined\n const docSource: Base64PDFSource | URLPDFSource =\n part.source.type === 'data'\n ? {\n type: 'base64',\n data: part.source.value,\n media_type: part.source.mimeType as 'application/pdf',\n }\n : {\n type: 'url',\n url: part.source.value,\n }\n return {\n type: 'document',\n source: docSource,\n ...metadata,\n }\n }\n case 'audio':\n case 'video':\n throw new Error(\n `Anthropic does not support ${part.type} content directly`,\n )\n default: {\n const _exhaustiveCheck: never = part\n throw new Error(\n `Unsupported content part type: ${(_exhaustiveCheck as ContentPart).type}`,\n )\n }\n }\n }\n\n private formatMessages(\n messages: Array<ModelMessage>,\n ): InternalTextProviderOptions['messages'] {\n const formattedMessages: InternalTextProviderOptions['messages'] = []\n\n for (const message of messages) {\n const role = message.role\n\n if (role === 'tool' && message.toolCallId) {\n const toolContent = message.content\n formattedMessages.push({\n role: 'user',\n content: [\n {\n type: 'tool_result',\n tool_use_id: message.toolCallId,\n content: Array.isArray(toolContent)\n ? toolContent.map((part) =>\n this.convertContentPartToAnthropic(part),\n )\n : typeof toolContent === 'string'\n ? toolContent\n : '',\n },\n ],\n })\n continue\n }\n\n if (role === 'assistant' && message.toolCalls?.length) {\n const contentBlocks: Array<ContentBlockParam> = []\n\n this.appendThinkingBlocks(contentBlocks, message.thinking)\n\n if (message.content) {\n const content =\n typeof message.content === 'string' ? message.content : ''\n const textBlock: TextBlockParam = {\n type: 'text',\n text: content,\n }\n contentBlocks.push(textBlock)\n }\n\n for (const toolCall of message.toolCalls) {\n let parsedInput: unknown = {}\n try {\n const parsed = toolCall.function.arguments\n ? JSON.parse(toolCall.function.arguments)\n : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = toolCall.function.arguments\n }\n\n // Provider-executed server tools (e.g. web_search) replay as the\n // original `server_tool_use` + result blocks so the model still sees\n // the prior evidence. Their result was captured verbatim during\n // streaming (see processAnthropicStream).\n const serverMeta = readAnthropicServerToolMetadata(toolCall.metadata)\n if (serverMeta) {\n const serverToolUseBlock: ServerToolUseBlockParam = {\n type: 'server_tool_use',\n id: toolCall.id,\n name: serverMeta.serverToolType,\n input: parsedInput,\n }\n contentBlocks.push(serverToolUseBlock)\n contentBlocks.push(\n buildServerToolResultBlock(toolCall.id, serverMeta),\n )\n continue\n }\n\n const toolUseBlock: ToolUseBlockParam = {\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.function.name,\n input: parsedInput,\n }\n contentBlocks.push(toolUseBlock)\n }\n\n formattedMessages.push({\n role: 'assistant',\n content: contentBlocks,\n })\n\n continue\n }\n\n if (role === 'assistant') {\n const contentBlocks: Array<ContentBlockParam> = []\n this.appendThinkingBlocks(contentBlocks, message.thinking)\n\n if (Array.isArray(message.content)) {\n for (const part of message.content) {\n contentBlocks.push(this.convertContentPartToAnthropic(part))\n }\n } else if (message.content) {\n contentBlocks.push({\n type: 'text',\n text: message.content,\n })\n }\n\n formattedMessages.push({\n role: 'assistant',\n content: contentBlocks.length > 0 ? contentBlocks : '',\n })\n continue\n }\n\n if (role === 'user' && Array.isArray(message.content)) {\n const contentBlocks = message.content.map((part) =>\n this.convertContentPartToAnthropic(part),\n )\n formattedMessages.push({\n role: 'user',\n content: contentBlocks,\n })\n continue\n }\n\n formattedMessages.push({\n role: 'user',\n content:\n typeof message.content === 'string'\n ? message.content\n : message.content\n ? message.content.map((c) =>\n this.convertContentPartToAnthropic(c),\n )\n : '',\n })\n }\n\n // Post-process: Anthropic requires strictly alternating user/assistant roles.\n // Tool results are sent as role:'user' messages, which can create consecutive\n // user messages when followed by a new user message. Merge them.\n return this.mergeConsecutiveSameRoleMessages(formattedMessages)\n }\n\n private appendThinkingBlocks(\n contentBlocks: Array<ContentBlockParam>,\n thinkingParts: ModelMessage['thinking'],\n ): void {\n if (!thinkingParts?.length) return\n\n for (const thinking of thinkingParts) {\n if (!thinking.signature) continue\n const block: ThinkingBlockParam = {\n type: 'thinking',\n thinking: thinking.content,\n signature: thinking.signature,\n }\n contentBlocks.push(block)\n }\n }\n\n /**\n * Merge consecutive messages of the same role into a single message.\n * Anthropic's API requires strictly alternating user/assistant roles.\n * Tool results are wrapped as role:'user' messages, which can collide\n * with actual user messages in multi-turn conversations.\n *\n * Also filters out empty assistant messages (e.g., from a previous failed request).\n */\n private mergeConsecutiveSameRoleMessages(\n messages: InternalTextProviderOptions['messages'],\n ): InternalTextProviderOptions['messages'] {\n const merged: InternalTextProviderOptions['messages'] = []\n\n for (const msg of messages) {\n // Skip empty assistant messages (no content or empty string)\n if (msg.role === 'assistant') {\n const hasContent = Array.isArray(msg.content)\n ? msg.content.length > 0\n : typeof msg.content === 'string' && msg.content.length > 0\n if (!hasContent) {\n continue\n }\n }\n\n const prev = merged[merged.length - 1]\n if (prev && prev.role === msg.role) {\n // Normalize both contents to arrays and concatenate\n const prevBlocks = Array.isArray(prev.content)\n ? prev.content\n : typeof prev.content === 'string' && prev.content\n ? [{ type: 'text' as const, text: prev.content }]\n : []\n const msgBlocks = Array.isArray(msg.content)\n ? msg.content\n : typeof msg.content === 'string' && msg.content\n ? [{ type: 'text' as const, text: msg.content }]\n : []\n prev.content = [...prevBlocks, ...msgBlocks]\n } else {\n merged.push({ ...msg })\n }\n }\n\n // De-duplicate tool_result blocks with the same tool_use_id.\n // This can happen when the core layer generates tool results from both\n // the tool-result part and the tool-call part's output field.\n for (const msg of merged) {\n if (Array.isArray(msg.content)) {\n const seenToolResultIds = new Set<string>()\n msg.content = msg.content.filter((block: any) => {\n if (block.type === 'tool_result' && block.tool_use_id) {\n if (seenToolResultIds.has(block.tool_use_id)) {\n return false // Remove duplicate\n }\n seenToolResultIds.add(block.tool_use_id)\n }\n return true\n })\n }\n }\n\n return merged\n }\n\n private async *processAnthropicStream(\n stream: AsyncIterable<Anthropic_SDK.Beta.BetaRawMessageStreamEvent>,\n options: TextOptions<AnthropicTextProviderOptions>,\n genId: () => string,\n logger: InternalLogger,\n ): AsyncIterable<StreamChunk> {\n const model = options.model\n let accumulatedContent = ''\n let accumulatedThinking = ''\n let accumulatedSignature = ''\n const toolCallsMap = new Map<\n number,\n { id: string; name: string; input: string; started: boolean }\n >()\n let currentToolIndex = -1\n // Server-side tools share the `input_json_delta` wire format with client\n // `tool_use` blocks; routing both to the same buffer corrupts client tool\n // input.\n let currentServerTool: { id: string; name: string; input: string } | null =\n null\n // Completed server tools awaiting their matching result block. Anthropic\n // emits `server_tool_use` then a separate `*_tool_result` block; we hold\n // the call here (keyed by id) until the result arrives so we can emit a\n // single provider-executed tool call carrying the raw result for round-trip.\n const completedServerTools = new Map<\n string,\n { id: string; name: string; input: string }\n >()\n\n // AG-UI lifecycle tracking\n const runId = options.runId ?? genId()\n const threadId = options.threadId ?? genId()\n const messageId = genId()\n let stepId: string | null = null\n let reasoningMessageId: string | null = null\n let hasClosedReasoning = false\n let hasEmittedRunStarted = false\n let hasEmittedTextMessageStart = false\n let hasEmittedRunFinished = false\n // Track current content block type for proper content_block_stop handling\n let currentBlockType: string | null = null\n\n try {\n for await (const event of stream) {\n logger.provider(`provider=anthropic type=${event.type}`, {\n chunk: event,\n })\n // Emit RUN_STARTED on first event\n if (!hasEmittedRunStarted) {\n hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n parentRunId: options.parentRunId,\n }\n }\n\n if (event.type === 'content_block_start') {\n currentBlockType = event.content_block.type\n if (event.content_block.type === 'tool_use') {\n currentToolIndex++\n toolCallsMap.set(currentToolIndex, {\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n started: false,\n })\n } else if (event.content_block.type === 'server_tool_use') {\n currentServerTool = {\n id: event.content_block.id,\n name: event.content_block.name,\n input: '',\n }\n } else if (\n event.content_block.type === 'web_fetch_tool_result' ||\n event.content_block.type === 'web_search_tool_result'\n ) {\n // The result content arrives in full at content_block_start (no\n // deltas). Surface error variants so a failed fetch/search isn't\n // invisible to the consumer.\n const content = event.content_block.content as\n | { type?: string; error_code?: string }\n | Array<unknown>\n const errorBlock =\n !Array.isArray(content) &&\n (content.type === 'web_fetch_tool_result_error' ||\n content.type === 'web_search_tool_result_error')\n ? content\n : null\n if (errorBlock) {\n logger.errors(\n `anthropic.${event.content_block.type} error_code=${errorBlock.error_code}`,\n {\n toolUseId: event.content_block.tool_use_id,\n blockType: event.content_block.type,\n errorCode: errorBlock.error_code,\n source: 'anthropic.processAnthropicStream',\n },\n )\n }\n\n // Emit the server tool as a single provider-executed tool call,\n // carrying its raw result so the evidence (e.g. web_search sources)\n // round-trips into the next turn's request. The agent loop skips\n // provider-executed calls, so this never triggers client execution.\n const serverTool = completedServerTools.get(\n event.content_block.tool_use_id,\n )\n if (serverTool) {\n completedServerTools.delete(serverTool.id)\n\n let parsedInput: unknown = {}\n try {\n const parsed = serverTool.input\n ? JSON.parse(serverTool.input)\n : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = {}\n }\n\n const serverToolMetadata = {\n providerExecuted: true,\n anthropic: {\n serverToolType: serverTool.name,\n resultBlockType: event.content_block.type,\n result: content,\n },\n }\n\n currentToolIndex++\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: serverTool.id,\n toolCallName: serverTool.name,\n toolName: serverTool.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n metadata: serverToolMetadata,\n }\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: serverTool.id,\n toolCallName: serverTool.name,\n toolName: serverTool.name,\n model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n\n // Text after the server tool starts a fresh message segment.\n hasEmittedTextMessageStart = false\n }\n } else if (event.content_block.type === 'thinking') {\n accumulatedThinking = ''\n accumulatedSignature = ''\n // Emit REASONING and STEP_STARTED for thinking\n stepId = genId()\n reasoningMessageId = genId()\n\n // Spec REASONING events\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning' as const,\n model,\n timestamp: Date.now(),\n }\n\n // Legacy STEP events (kept during transition)\n yield {\n type: EventType.STEP_STARTED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n stepType: 'thinking',\n }\n }\n } else if (event.type === 'content_block_delta') {\n if (event.delta.type === 'text_delta') {\n // Close reasoning before text starts\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n // Emit TEXT_MESSAGE_START on first text content\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp: Date.now(),\n role: 'assistant',\n }\n }\n\n const delta = event.delta.text\n accumulatedContent += delta\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp: Date.now(),\n delta,\n content: accumulatedContent,\n }\n } else if (\n event.delta.type === 'thinking_delta' &&\n reasoningMessageId\n ) {\n const delta = event.delta.thinking\n accumulatedThinking += delta\n\n // Spec REASONING content event\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta,\n model,\n timestamp: Date.now(),\n }\n\n // Legacy STEP event\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId || genId(),\n stepId: stepId || genId(),\n model,\n timestamp: Date.now(),\n delta,\n content: accumulatedThinking,\n }\n } else if (\n (event.delta as { type: string }).type === 'signature_delta'\n ) {\n accumulatedSignature +=\n (event.delta as { signature: string }).signature || ''\n } else if (event.delta.type === 'input_json_delta') {\n // Route deltas by current block type so server_tool_use input\n // never appends onto the prior client tool's buffer.\n if (currentBlockType === 'tool_use') {\n const existing = toolCallsMap.get(currentToolIndex)\n if (existing) {\n // Emit TOOL_CALL_START on first args delta\n if (!existing.started) {\n existing.started = true\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n }\n }\n\n existing.input += event.delta.partial_json\n\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: existing.id,\n model,\n timestamp: Date.now(),\n delta: event.delta.partial_json,\n args: existing.input,\n }\n }\n } else if (\n currentBlockType === 'server_tool_use' &&\n currentServerTool\n ) {\n // Accumulate server tool input internally. We don't emit\n // TOOL_CALL_* events: the call is executed by Anthropic, not\n // by our agent loop, so surfacing it as a client tool call\n // would cause downstream code to try (and fail) to run it.\n currentServerTool.input += event.delta.partial_json\n }\n }\n } else if (event.type === 'content_block_stop') {\n if (currentBlockType === 'thinking') {\n // Emit signature so it can be replayed in multi-turn context\n if (accumulatedSignature && stepId) {\n yield {\n type: EventType.STEP_FINISHED,\n stepName: stepId,\n stepId,\n model,\n timestamp: Date.now(),\n delta: '',\n content: accumulatedThinking,\n signature: accumulatedSignature,\n }\n }\n } else if (currentBlockType === 'tool_use') {\n const existing = toolCallsMap.get(currentToolIndex)\n if (existing) {\n // If tool call wasn't started yet (no args), start it now\n if (!existing.started) {\n existing.started = true\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n parentMessageId: messageId,\n model,\n timestamp: Date.now(),\n index: currentToolIndex,\n }\n }\n\n // Emit TOOL_CALL_END\n let parsedInput: unknown = {}\n try {\n const parsed = existing.input ? JSON.parse(existing.input) : {}\n parsedInput = parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n parsedInput = {}\n }\n\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: existing.id,\n toolCallName: existing.name,\n toolName: existing.name,\n model,\n timestamp: Date.now(),\n input: parsedInput,\n }\n\n // Reset so a new TEXT_MESSAGE_START is emitted if text follows tool calls\n hasEmittedTextMessageStart = false\n }\n } else if (currentBlockType === 'server_tool_use') {\n if (currentServerTool) {\n // Anthropic executes the call; we only need a breadcrumb so\n // consumers (devtools, telemetry) can see what ran.\n logger.provider(\n `provider=anthropic server_tool_use name=${currentServerTool.name}`,\n {\n toolUseId: currentServerTool.id,\n name: currentServerTool.name,\n input: currentServerTool.input,\n },\n )\n // Hold the call until its result block arrives so we can emit\n // both together as one provider-executed tool call.\n completedServerTools.set(currentServerTool.id, currentServerTool)\n }\n currentServerTool = null\n } else if (\n currentBlockType === 'web_fetch_tool_result' ||\n currentBlockType === 'web_search_tool_result'\n ) {\n // The model already consumed the result; error variants were\n // already surfaced at content_block_start.\n } else {\n // Emit TEXT_MESSAGE_END only for text blocks (not tool_use blocks)\n if (hasEmittedTextMessageStart && accumulatedContent) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n model,\n timestamp: Date.now(),\n }\n }\n }\n currentBlockType = null\n } else if (event.type === 'message_stop') {\n // Close reasoning events if still open\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n // Only emit RUN_FINISHED from message_stop if message_delta didn't already emit one.\n // message_delta carries the real stop_reason (tool_use, end_turn, etc.),\n // while message_stop is just a completion signal.\n if (!hasEmittedRunFinished) {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'stop',\n }\n }\n } else if (event.type === 'message_delta') {\n if (event.delta.stop_reason) {\n hasEmittedRunFinished = true\n\n // Close reasoning events if still open\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp: Date.now(),\n }\n }\n\n switch (event.delta.stop_reason) {\n case 'tool_use': {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'tool_calls',\n usage: buildAnthropicUsage(event.usage),\n }\n break\n }\n case 'max_tokens': {\n // Surface a warning when the truncating cap was the\n // adapter-supplied default (caller didn't pass `max_tokens`), so\n // the truncation isn't silently attributed to the model \"doing\n // nothing\" (issue #849). When the caller set `max_tokens`\n // themselves, hitting it is their own deliberate ceiling.\n if (options.modelOptions?.max_tokens == null) {\n const defaultedMaxTokens = getAnthropicDefaultMaxTokens(model)\n logger.warn(\n `anthropic response truncated at the default max_tokens (${defaultedMaxTokens}) for model=${model}; pass maxTokens (or modelOptions.max_tokens) to raise the output ceiling`,\n {\n source: 'anthropic.processAnthropicStream',\n model,\n defaultedMaxTokens,\n },\n )\n }\n yield {\n type: EventType.RUN_ERROR,\n model,\n timestamp: Date.now(),\n message:\n 'The response was cut off because the maximum token limit was reached.',\n code: 'max_tokens',\n error: {\n message:\n 'The response was cut off because the maximum token limit was reached.',\n code: 'max_tokens',\n },\n }\n break\n }\n case 'stop_sequence':\n case 'end_turn':\n case 'pause_turn':\n case 'refusal':\n case 'model_context_window_exceeded':\n case 'compaction':\n default: {\n // All remaining Anthropic stop_reason variants map to the\n // generic \"stop\" finish reason — they describe *why* the\n // stream ended, but for AG-UI consumers the resulting event\n // shape is identical.\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: Date.now(),\n finishReason: 'stop',\n usage: buildAnthropicUsage(event.usage),\n }\n }\n }\n }\n }\n }\n } catch (error: unknown) {\n const err = error as Error & { status?: number; code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n\n logger.errors('anthropic.processAnthropicStream fatal', {\n error,\n source: 'anthropic.processAnthropicStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n // Forward the Anthropic SDK error's `.error` response body when present.\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n code: err.code || String(err.status),\n },\n }\n }\n }\n}\n\n/**\n * Creates an Anthropic chat adapter with explicit API key.\n * Type resolution happens here at the call site.\n */\nexport function createAnthropicChat<\n TModel extends (typeof ANTHROPIC_MODELS)[number],\n>(\n model: TModel,\n apiKey: string,\n config?: Omit<AnthropicTextConfig, 'apiKey'>,\n): AnthropicTextAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>\n> {\n return new AnthropicTextAdapter({ apiKey, ...config }, model)\n}\n\n/**\n * Creates an Anthropic text adapter with automatic API key detection.\n * Type resolution happens here at the call site.\n */\nexport function anthropicText<TModel extends (typeof ANTHROPIC_MODELS)[number]>(\n model: TModel,\n config?: Omit<AnthropicTextConfig, 'apiKey'>,\n): AnthropicTextAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>\n> {\n const apiKey = getAnthropicApiKeyFromEnv()\n return createAnthropicChat(model, apiKey, config)\n}\n"],"names":[],"mappings":";;;;;;;;;AA2FA,SAAS,gCACP,UACoC;AACpC,MAAI,OAAO,aAAa,YAAY,aAAa,KAAM,QAAO;AAC9D,QAAM,QAAQ;AACd,MAAI,MAAM,qBAAqB,KAAM,QAAO;AAC5C,QAAM,QAAQ,MAAM;AACpB,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,EAAE,gBAAgB,iBAAiB,OAAA,IAAW;AAKpD,MACE,OAAO,mBAAmB,YACzB,oBAAoB,4BACnB,oBAAoB,yBACtB;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ClD;"}
|
package/dist/esm/model-meta.d.ts
CHANGED
|
@@ -225,6 +225,48 @@ declare const CLAUDE_SONNET_5: {
|
|
|
225
225
|
* turned them off.
|
|
226
226
|
*/
|
|
227
227
|
export declare const ANTHROPIC_MODELS: readonly ["claude-opus-4-6", "claude-opus-4-5", "claude-sonnet-4-6", "claude-sonnet-4-5", "claude-haiku-4-5", "claude-opus-4-1", "claude-opus-4-7", "claude-opus-4-8", "claude-fable-5", "claude-sonnet-5"];
|
|
228
|
+
/**
|
|
229
|
+
* Fallback `max_tokens` ceiling for a model whose metadata carries no
|
|
230
|
+
* `max_output_tokens` (e.g. an unrecognized model id). Anthropic's Messages
|
|
231
|
+
* API *requires* `max_tokens`, so the adapter must always send a value. 64K is
|
|
232
|
+
* the output ceiling of the current mainstream Claude tier (Sonnet/Haiku 4.5),
|
|
233
|
+
* so it's a sane default for an unknown — almost certainly modern — model and
|
|
234
|
+
* avoids silently truncating long generations (issue #849). Recognized models
|
|
235
|
+
* use their exact `max_output_tokens` from {@link ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS}
|
|
236
|
+
* (e.g. 128K for Opus), so this fallback only ever applies to ids not in the
|
|
237
|
+
* map.
|
|
238
|
+
*/
|
|
239
|
+
export declare const ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS = 64000;
|
|
240
|
+
/**
|
|
241
|
+
* Largest `max_tokens` the Anthropic SDK permits on a **non-streaming**
|
|
242
|
+
* request. The SDK refuses to make a non-streaming call it estimates could
|
|
243
|
+
* exceed its 10-minute timeout, computed as
|
|
244
|
+
* `(60min * max_tokens) / 128_000 > 10min` — i.e. it throws
|
|
245
|
+
* `"Streaming is required for operations that may take longer than 10 minutes"`
|
|
246
|
+
* once `max_tokens > 128_000 * 10 / 60 ≈ 21_333`
|
|
247
|
+
* (`@anthropic-ai/sdk`'s `calculateNonstreamingTimeout`). The text adapter's
|
|
248
|
+
* only non-streaming call is the forced-tool `structuredOutput()` request, so
|
|
249
|
+
* its defaulted ceiling must stay at or below this; the streaming chat path
|
|
250
|
+
* keeps the model's full {@link getAnthropicDefaultMaxTokens} ceiling. We sit
|
|
251
|
+
* just under the boundary (`21_333` would round-trip to exactly 10min). This
|
|
252
|
+
* caps only the *default* — an explicit oversized `max_tokens` from the caller
|
|
253
|
+
* still surfaces the SDK's "use streaming" error, which is the correct signal.
|
|
254
|
+
*/
|
|
255
|
+
export declare const ANTHROPIC_MAX_NONSTREAMING_TOKENS = 21000;
|
|
256
|
+
/**
|
|
257
|
+
* Resolve the default `max_tokens` for a model: its known `max_output_tokens`
|
|
258
|
+
* ceiling, or {@link ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS} for unknown models.
|
|
259
|
+
* Callers that pass an explicit `max_tokens` bypass this entirely.
|
|
260
|
+
*
|
|
261
|
+
* Pass `stream: false` for non-streaming requests (the `structuredOutput()`
|
|
262
|
+
* path): the result is then clamped to {@link ANTHROPIC_MAX_NONSTREAMING_TOKENS}
|
|
263
|
+
* so the defaulted ceiling doesn't trip the SDK's non-streaming 10-minute guard
|
|
264
|
+
* (issue #849). Streaming requests (the default) are unaffected and get the
|
|
265
|
+
* model's full ceiling.
|
|
266
|
+
*/
|
|
267
|
+
export declare function getAnthropicDefaultMaxTokens(model: string, { stream }?: {
|
|
268
|
+
stream?: boolean;
|
|
269
|
+
}): number;
|
|
228
270
|
/**
|
|
229
271
|
* Anthropic models that support combining `tools` + JSON-Schema-constrained
|
|
230
272
|
* output in a single streaming Messages request (per issue #605). GA'd
|
package/dist/esm/model-meta.js
CHANGED
|
@@ -1,32 +1,42 @@
|
|
|
1
1
|
const CLAUDE_OPUS_4_6 = {
|
|
2
|
-
id: "claude-opus-4-6"
|
|
2
|
+
id: "claude-opus-4-6",
|
|
3
|
+
max_output_tokens: 128e3
|
|
3
4
|
};
|
|
4
5
|
const CLAUDE_OPUS_4_5 = {
|
|
5
|
-
id: "claude-opus-4-5"
|
|
6
|
+
id: "claude-opus-4-5",
|
|
7
|
+
max_output_tokens: 32e3
|
|
6
8
|
};
|
|
7
9
|
const CLAUDE_SONNET_4_6 = {
|
|
8
|
-
id: "claude-sonnet-4-6"
|
|
10
|
+
id: "claude-sonnet-4-6",
|
|
11
|
+
max_output_tokens: 64e3
|
|
9
12
|
};
|
|
10
13
|
const CLAUDE_SONNET_4_5 = {
|
|
11
|
-
id: "claude-sonnet-4-5"
|
|
14
|
+
id: "claude-sonnet-4-5",
|
|
15
|
+
max_output_tokens: 64e3
|
|
12
16
|
};
|
|
13
17
|
const CLAUDE_HAIKU_4_5 = {
|
|
14
|
-
id: "claude-haiku-4-5"
|
|
18
|
+
id: "claude-haiku-4-5",
|
|
19
|
+
max_output_tokens: 64e3
|
|
15
20
|
};
|
|
16
21
|
const CLAUDE_OPUS_4_1 = {
|
|
17
|
-
id: "claude-opus-4-1"
|
|
22
|
+
id: "claude-opus-4-1",
|
|
23
|
+
max_output_tokens: 64e3
|
|
18
24
|
};
|
|
19
25
|
const CLAUDE_OPUS_4_7 = {
|
|
20
|
-
id: "claude-opus-4-7"
|
|
26
|
+
id: "claude-opus-4-7",
|
|
27
|
+
max_output_tokens: 128e3
|
|
21
28
|
};
|
|
22
29
|
const CLAUDE_OPUS_4_8 = {
|
|
23
|
-
id: "claude-opus-4-8"
|
|
30
|
+
id: "claude-opus-4-8",
|
|
31
|
+
max_output_tokens: 128e3
|
|
24
32
|
};
|
|
25
33
|
const CLAUDE_FABLE_5 = {
|
|
26
|
-
id: "claude-fable-5"
|
|
34
|
+
id: "claude-fable-5",
|
|
35
|
+
max_output_tokens: 128e3
|
|
27
36
|
};
|
|
28
37
|
const CLAUDE_SONNET_5 = {
|
|
29
|
-
id: "claude-sonnet-5"
|
|
38
|
+
id: "claude-sonnet-5",
|
|
39
|
+
max_output_tokens: 128e3
|
|
30
40
|
};
|
|
31
41
|
const ANTHROPIC_MODELS = [
|
|
32
42
|
CLAUDE_OPUS_4_6.id,
|
|
@@ -40,6 +50,24 @@ const ANTHROPIC_MODELS = [
|
|
|
40
50
|
CLAUDE_FABLE_5.id,
|
|
41
51
|
CLAUDE_SONNET_5.id
|
|
42
52
|
];
|
|
53
|
+
const ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS = 64e3;
|
|
54
|
+
const ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS = {
|
|
55
|
+
[CLAUDE_OPUS_4_6.id]: CLAUDE_OPUS_4_6.max_output_tokens,
|
|
56
|
+
[CLAUDE_OPUS_4_5.id]: CLAUDE_OPUS_4_5.max_output_tokens,
|
|
57
|
+
[CLAUDE_SONNET_4_6.id]: CLAUDE_SONNET_4_6.max_output_tokens,
|
|
58
|
+
[CLAUDE_SONNET_4_5.id]: CLAUDE_SONNET_4_5.max_output_tokens,
|
|
59
|
+
[CLAUDE_HAIKU_4_5.id]: CLAUDE_HAIKU_4_5.max_output_tokens,
|
|
60
|
+
[CLAUDE_OPUS_4_1.id]: CLAUDE_OPUS_4_1.max_output_tokens,
|
|
61
|
+
[CLAUDE_OPUS_4_7.id]: CLAUDE_OPUS_4_7.max_output_tokens,
|
|
62
|
+
[CLAUDE_OPUS_4_8.id]: CLAUDE_OPUS_4_8.max_output_tokens,
|
|
63
|
+
[CLAUDE_FABLE_5.id]: CLAUDE_FABLE_5.max_output_tokens,
|
|
64
|
+
[CLAUDE_SONNET_5.id]: CLAUDE_SONNET_5.max_output_tokens
|
|
65
|
+
};
|
|
66
|
+
const ANTHROPIC_MAX_NONSTREAMING_TOKENS = 21e3;
|
|
67
|
+
function getAnthropicDefaultMaxTokens(model, { stream = true } = {}) {
|
|
68
|
+
const ceiling = ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS[model] ?? ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS;
|
|
69
|
+
return stream ? ceiling : Math.min(ceiling, ANTHROPIC_MAX_NONSTREAMING_TOKENS);
|
|
70
|
+
}
|
|
43
71
|
const ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS = /* @__PURE__ */ new Set([
|
|
44
72
|
CLAUDE_OPUS_4_5.id,
|
|
45
73
|
CLAUDE_OPUS_4_6.id,
|
|
@@ -53,6 +81,9 @@ const ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS = /* @__PURE__ */ new Set([
|
|
|
53
81
|
]);
|
|
54
82
|
export {
|
|
55
83
|
ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS,
|
|
56
|
-
|
|
84
|
+
ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS,
|
|
85
|
+
ANTHROPIC_MAX_NONSTREAMING_TOKENS,
|
|
86
|
+
ANTHROPIC_MODELS,
|
|
87
|
+
getAnthropicDefaultMaxTokens
|
|
57
88
|
};
|
|
58
89
|
//# sourceMappingURL=model-meta.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-meta.js","sources":["../../src/model-meta.ts"],"sourcesContent":["import type {\n AnthropicAdaptiveOnlyThinkingOptions,\n AnthropicAdaptiveOrDisabledThinkingOptions,\n AnthropicAdaptiveThinkingOptions,\n AnthropicContainerOptions,\n AnthropicContextManagementOptions,\n AnthropicMCPOptions,\n AnthropicMaxTokensOptions,\n AnthropicOutputConfigOptions,\n AnthropicSamplingOptions,\n AnthropicServiceTierOptions,\n AnthropicStopSequencesOptions,\n AnthropicThinkingOptions,\n AnthropicToolChoiceOptions,\n} from './text/text-provider-options'\n\ninterface ModelMeta<\n TProviderOptions = unknown,\n TToolCapabilities = unknown,\n TMessageCapabilities = unknown,\n> {\n name: string\n id: string\n supports: {\n input: Array<'text' | 'image' | 'audio' | 'video' | 'document'>\n extended_thinking?: boolean\n adaptive_thinking?: boolean\n priority_tier?: boolean\n tools?: Array<\n | 'web_search'\n | 'web_fetch'\n | 'code_execution'\n | 'computer_use'\n | 'bash'\n | 'text_editor'\n | 'memory'\n >\n }\n context_window?: number\n max_output_tokens?: number\n knowledge_cutoff?: string\n pricing: {\n input: {\n normal: number\n cached?: number\n }\n output: {\n normal: number\n }\n }\n /**\n * Type-level description of which provider options this model supports.\n */\n providerOptions?: TProviderOptions\n /**\n * Type-level description of which tool capabilities this model supports.\n */\n toolCapabilities?: TToolCapabilities\n /**\n * Type-level description of which message/input capabilities this model supports.\n */\n messageCapabilities?: TMessageCapabilities\n}\n\n// Claude Opus 4.6 accepts adaptive thinking alongside the deprecated\n// budget-based extended thinking, and still accepts sampling parameters.\nconst CLAUDE_OPUS_4_6 = {\n name: 'claude-opus-4-6',\n id: 'claude-opus-4-6',\n context_window: 200_000,\n max_output_tokens: 128_000,\n knowledge_cutoff: '2025-05-01',\n pricing: {\n input: {\n normal: 5,\n },\n output: {\n normal: 25,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_OPUS_4_5 = {\n name: 'claude-opus-4-5',\n id: 'claude-opus-4-5',\n context_window: 200_000,\n max_output_tokens: 32_000,\n knowledge_cutoff: '2025-11-01',\n pricing: {\n input: {\n normal: 15,\n },\n output: {\n normal: 75,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\n// Claude Sonnet 4.6 accepts adaptive thinking alongside the deprecated\n// budget-based extended thinking, and still accepts sampling parameters.\nconst CLAUDE_SONNET_4_6 = {\n name: 'claude-sonnet-4-6',\n id: 'claude-sonnet-4-6',\n context_window: 1_000_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-08-01',\n pricing: {\n input: {\n normal: 3,\n },\n output: {\n normal: 15,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_SONNET_4_5 = {\n name: 'claude-sonnet-4-5',\n id: 'claude-sonnet-4-5',\n context_window: 200_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-09-29',\n pricing: {\n input: {\n normal: 3,\n },\n output: {\n normal: 15,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_HAIKU_4_5 = {\n name: 'claude-haiku-4-5',\n id: 'claude-haiku-4-5',\n context_window: 200_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-10-01',\n pricing: {\n input: {\n normal: 1,\n },\n output: {\n normal: 5,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_OPUS_4_1 = {\n name: 'claude-opus-4-1',\n id: 'claude-opus-4-1',\n context_window: 200_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-08-05',\n pricing: {\n input: {\n normal: 15,\n },\n output: {\n normal: 75,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\n// Claude Opus 4.7 removed budget-based extended thinking and the sampling\n// parameters (`temperature`, `top_p`, `top_k`) — sending either returns a\n// 400. Use adaptive thinking with `output_config.effort` instead.\nconst CLAUDE_OPUS_4_7 = {\n name: 'claude-opus-4-7',\n id: 'claude-opus-4-7',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 5,\n cached: 0.5,\n },\n output: {\n normal: 25,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n// Claude Opus 4.8 keeps the same request surface as Opus 4.7: adaptive\n// thinking only (budget_tokens 400s), no sampling parameters.\nconst CLAUDE_OPUS_4_8 = {\n name: 'claude-opus-4-8',\n id: 'claude-opus-4-8',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 5,\n cached: 0.5,\n },\n output: {\n normal: 25,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n// Claude Fable 5: thinking is always on — the only accepted explicit\n// `thinking` config is `{type: 'adaptive'}` (disabled/budget_tokens 400),\n// and the sampling parameters (`temperature`, `top_p`, `top_k`) are\n// rejected. Its provider options therefore use the adaptive-only thinking\n// shape and `max_tokens` without the sampling knobs.\nconst CLAUDE_FABLE_5 = {\n name: 'claude-fable-5',\n id: 'claude-fable-5',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 10,\n cached: 1,\n },\n output: {\n normal: 50,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOnlyThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n// Claude Sonnet 5: adaptive thinking is the default (omitting `thinking`\n// runs adaptive); `{type: 'disabled'}` opts out, but the manual\n// `{type: 'enabled', budget_tokens}` shape and non-default sampling\n// parameters (`temperature`, `top_p`, `top_k`) are rejected with a 400.\n// Pricing below is the sticker $3/$15 per MTok (an introductory $2/$10\n// applies through 2026-08-31).\nconst CLAUDE_SONNET_5 = {\n name: 'claude-sonnet-5',\n id: 'claude-sonnet-5',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 3,\n cached: 0.3,\n },\n output: {\n normal: 15,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n/**\n * Model ids accepted by the Anthropic text adapter.\n *\n * Every id here resolves against the first-party Anthropic API\n * (`GET /v1/models/{id}`). Retired models (Claude 3.x, Sonnet 3.7,\n * Opus 4 / Sonnet 4) and the `-fast` variant ids (fast mode is requested\n * via the `speed` parameter, not a model id) were removed after Anthropic\n * turned them off.\n */\nexport const ANTHROPIC_MODELS = [\n CLAUDE_OPUS_4_6.id,\n CLAUDE_OPUS_4_5.id,\n CLAUDE_SONNET_4_6.id,\n CLAUDE_SONNET_4_5.id,\n CLAUDE_HAIKU_4_5.id,\n CLAUDE_OPUS_4_1.id,\n\n CLAUDE_OPUS_4_7.id,\n CLAUDE_OPUS_4_8.id,\n\n CLAUDE_FABLE_5.id,\n CLAUDE_SONNET_5.id,\n] as const\n\n/**\n * Anthropic models that support combining `tools` + JSON-Schema-constrained\n * output in a single streaming Messages request (per issue #605). GA'd\n * 2026-01-29 for Claude 4.5+ via `output_format` on the beta messages\n * endpoint. Older Claude models still need the forced-tool-use workaround\n * in `structuredOutput`.\n */\nexport const ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS = new Set<string>([\n CLAUDE_OPUS_4_5.id,\n CLAUDE_OPUS_4_6.id,\n CLAUDE_OPUS_4_7.id,\n CLAUDE_OPUS_4_8.id,\n CLAUDE_FABLE_5.id,\n CLAUDE_SONNET_5.id,\n CLAUDE_SONNET_4_5.id,\n CLAUDE_SONNET_4_6.id,\n CLAUDE_HAIKU_4_5.id,\n])\n\n// const ANTHROPIC_IMAGE_MODELS = [] as const\n// const ANTHROPIC_EMBEDDING_MODELS = [] as const\n// const ANTHROPIC_AUDIO_MODELS = [] as const\n// const ANTHROPIC_VIDEO_MODELS = [] as const\n\nexport type AnthropicChatModel = (typeof ANTHROPIC_MODELS)[number]\n// Manual type map for per-model provider options\n// Models are differentiated by which thinking shapes and sampling\n// parameters the API accepts.\nexport type AnthropicChatModelProviderOptionsByName = {\n // 4.6 generation: adaptive thinking plus the deprecated budget-based\n // shape; sampling parameters still accepted.\n [CLAUDE_OPUS_4_6.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_SONNET_4_6.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n\n // Pre-4.6 models: budget-based extended thinking and sampling parameters.\n [CLAUDE_OPUS_4_5.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_SONNET_4_5.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_HAIKU_4_5.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_OPUS_4_1.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n\n // Opus 4.7/4.8: adaptive thinking (or explicit disable), no\n // budget_tokens, no sampling parameters — see the constants above.\n [CLAUDE_OPUS_4_7.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n [CLAUDE_OPUS_4_8.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n\n // Claude Fable 5: thinking always on (adaptive-only config); sampling\n // parameters removed — see the CLAUDE_FABLE_5 constant above.\n [CLAUDE_FABLE_5.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOnlyThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n // Claude Sonnet 5: adaptive thinking by default, explicit disable\n // allowed; no budget_tokens, no sampling parameters — see the\n // CLAUDE_SONNET_5 constant above.\n [CLAUDE_SONNET_5.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n}\n\nexport type AnthropicChatModelToolCapabilitiesByName = {\n [CLAUDE_OPUS_4_6.id]: typeof CLAUDE_OPUS_4_6.supports.tools\n [CLAUDE_OPUS_4_5.id]: typeof CLAUDE_OPUS_4_5.supports.tools\n [CLAUDE_SONNET_4_6.id]: typeof CLAUDE_SONNET_4_6.supports.tools\n [CLAUDE_SONNET_4_5.id]: typeof CLAUDE_SONNET_4_5.supports.tools\n [CLAUDE_HAIKU_4_5.id]: typeof CLAUDE_HAIKU_4_5.supports.tools\n [CLAUDE_OPUS_4_1.id]: typeof CLAUDE_OPUS_4_1.supports.tools\n [CLAUDE_OPUS_4_7.id]: typeof CLAUDE_OPUS_4_7.supports.tools\n [CLAUDE_OPUS_4_8.id]: typeof CLAUDE_OPUS_4_8.supports.tools\n [CLAUDE_FABLE_5.id]: typeof CLAUDE_FABLE_5.supports.tools\n [CLAUDE_SONNET_5.id]: typeof CLAUDE_SONNET_5.supports.tools\n}\n\n/**\n * Type-only map from chat model name to its supported input modalities.\n * All Anthropic Claude models support text, image, and document (PDF) input.\n * Used by the core AI types to constrain ContentPart types based on the selected model.\n * Note: These must be inlined as readonly arrays (not typeof) because the model\n * constants are not exported and typeof references don't work in .d.ts files\n * when consumed by external packages.\n *\n * @see https://docs.anthropic.com/claude/docs/vision\n * @see https://docs.anthropic.com/claude/docs/pdf-support\n */\nexport type AnthropicModelInputModalitiesByName = {\n [CLAUDE_OPUS_4_6.id]: typeof CLAUDE_OPUS_4_6.supports.input\n [CLAUDE_OPUS_4_5.id]: typeof CLAUDE_OPUS_4_5.supports.input\n [CLAUDE_SONNET_4_6.id]: typeof CLAUDE_SONNET_4_6.supports.input\n [CLAUDE_SONNET_4_5.id]: typeof CLAUDE_SONNET_4_5.supports.input\n [CLAUDE_HAIKU_4_5.id]: typeof CLAUDE_HAIKU_4_5.supports.input\n [CLAUDE_OPUS_4_1.id]: typeof CLAUDE_OPUS_4_1.supports.input\n [CLAUDE_OPUS_4_7.id]: typeof CLAUDE_OPUS_4_7.supports.input\n [CLAUDE_OPUS_4_8.id]: typeof CLAUDE_OPUS_4_8.supports.input\n [CLAUDE_FABLE_5.id]: typeof CLAUDE_FABLE_5.supports.input\n [CLAUDE_SONNET_5.id]: typeof CLAUDE_SONNET_5.supports.input\n}\n"],"names":[],"mappings":"AAkEA,MAAM,kBAAkB;AAAA,EAEtB,IAAI;AA2BN;AAWA,MAAM,kBAAkB;AAAA,EAEtB,IAAI;AA0BN;AAaA,MAAM,oBAAoB;AAAA,EAExB,IAAI;AA2BN;AAWA,MAAM,oBAAoB;AAAA,EAExB,IAAI;AA0BN;AAWA,MAAM,mBAAmB;AAAA,EAEvB,IAAI;AA0BN;AAWA,MAAM,kBAAkB;AAAA,EAEtB,IAAI;AA0BN;AAcA,MAAM,kBAAkB;AAAA,EAEtB,IAAI;AA2BN;AAcA,MAAM,kBAAkB;AAAA,EAEtB,IAAI;AA2BN;AAiBA,MAAM,iBAAiB;AAAA,EAErB,IAAI;AA2BN;AAkBA,MAAM,kBAAkB;AAAA,EAEtB,IAAI;AA2BN;AAqBO,MAAM,mBAAmB;AAAA,EAC9B,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,kBAAkB;AAAA,EAClB,kBAAkB;AAAA,EAClB,iBAAiB;AAAA,EACjB,gBAAgB;AAAA,EAEhB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAEhB,eAAe;AAAA,EACf,gBAAgB;AAClB;AASO,MAAM,iEAAiD,IAAY;AAAA,EACxE,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,kBAAkB;AAAA,EAClB,kBAAkB;AAAA,EAClB,iBAAiB;AACnB,CAAC;"}
|
|
1
|
+
{"version":3,"file":"model-meta.js","sources":["../../src/model-meta.ts"],"sourcesContent":["import type {\n AnthropicAdaptiveOnlyThinkingOptions,\n AnthropicAdaptiveOrDisabledThinkingOptions,\n AnthropicAdaptiveThinkingOptions,\n AnthropicContainerOptions,\n AnthropicContextManagementOptions,\n AnthropicMCPOptions,\n AnthropicMaxTokensOptions,\n AnthropicOutputConfigOptions,\n AnthropicSamplingOptions,\n AnthropicServiceTierOptions,\n AnthropicStopSequencesOptions,\n AnthropicThinkingOptions,\n AnthropicToolChoiceOptions,\n} from './text/text-provider-options'\n\ninterface ModelMeta<\n TProviderOptions = unknown,\n TToolCapabilities = unknown,\n TMessageCapabilities = unknown,\n> {\n name: string\n id: string\n supports: {\n input: Array<'text' | 'image' | 'audio' | 'video' | 'document'>\n extended_thinking?: boolean\n adaptive_thinking?: boolean\n priority_tier?: boolean\n tools?: Array<\n | 'web_search'\n | 'web_fetch'\n | 'code_execution'\n | 'computer_use'\n | 'bash'\n | 'text_editor'\n | 'memory'\n >\n }\n context_window?: number\n max_output_tokens?: number\n knowledge_cutoff?: string\n pricing: {\n input: {\n normal: number\n cached?: number\n }\n output: {\n normal: number\n }\n }\n /**\n * Type-level description of which provider options this model supports.\n */\n providerOptions?: TProviderOptions\n /**\n * Type-level description of which tool capabilities this model supports.\n */\n toolCapabilities?: TToolCapabilities\n /**\n * Type-level description of which message/input capabilities this model supports.\n */\n messageCapabilities?: TMessageCapabilities\n}\n\n// Claude Opus 4.6 accepts adaptive thinking alongside the deprecated\n// budget-based extended thinking, and still accepts sampling parameters.\nconst CLAUDE_OPUS_4_6 = {\n name: 'claude-opus-4-6',\n id: 'claude-opus-4-6',\n context_window: 200_000,\n max_output_tokens: 128_000,\n knowledge_cutoff: '2025-05-01',\n pricing: {\n input: {\n normal: 5,\n },\n output: {\n normal: 25,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_OPUS_4_5 = {\n name: 'claude-opus-4-5',\n id: 'claude-opus-4-5',\n context_window: 200_000,\n max_output_tokens: 32_000,\n knowledge_cutoff: '2025-11-01',\n pricing: {\n input: {\n normal: 15,\n },\n output: {\n normal: 75,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\n// Claude Sonnet 4.6 accepts adaptive thinking alongside the deprecated\n// budget-based extended thinking, and still accepts sampling parameters.\nconst CLAUDE_SONNET_4_6 = {\n name: 'claude-sonnet-4-6',\n id: 'claude-sonnet-4-6',\n context_window: 1_000_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-08-01',\n pricing: {\n input: {\n normal: 3,\n },\n output: {\n normal: 15,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_SONNET_4_5 = {\n name: 'claude-sonnet-4-5',\n id: 'claude-sonnet-4-5',\n context_window: 200_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-09-29',\n pricing: {\n input: {\n normal: 3,\n },\n output: {\n normal: 15,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_HAIKU_4_5 = {\n name: 'claude-haiku-4-5',\n id: 'claude-haiku-4-5',\n context_window: 200_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-10-01',\n pricing: {\n input: {\n normal: 1,\n },\n output: {\n normal: 5,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\nconst CLAUDE_OPUS_4_1 = {\n name: 'claude-opus-4-1',\n id: 'claude-opus-4-1',\n context_window: 200_000,\n max_output_tokens: 64_000,\n knowledge_cutoff: '2025-08-05',\n pricing: {\n input: {\n normal: 15,\n },\n output: {\n normal: 75,\n },\n },\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n>\n\n// Claude Opus 4.7 removed budget-based extended thinking and the sampling\n// parameters (`temperature`, `top_p`, `top_k`) — sending either returns a\n// 400. Use adaptive thinking with `output_config.effort` instead.\nconst CLAUDE_OPUS_4_7 = {\n name: 'claude-opus-4-7',\n id: 'claude-opus-4-7',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 5,\n cached: 0.5,\n },\n output: {\n normal: 25,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n// Claude Opus 4.8 keeps the same request surface as Opus 4.7: adaptive\n// thinking only (budget_tokens 400s), no sampling parameters.\nconst CLAUDE_OPUS_4_8 = {\n name: 'claude-opus-4-8',\n id: 'claude-opus-4-8',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 5,\n cached: 0.5,\n },\n output: {\n normal: 25,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n// Claude Fable 5: thinking is always on — the only accepted explicit\n// `thinking` config is `{type: 'adaptive'}` (disabled/budget_tokens 400),\n// and the sampling parameters (`temperature`, `top_p`, `top_k`) are\n// rejected. Its provider options therefore use the adaptive-only thinking\n// shape and `max_tokens` without the sampling knobs.\nconst CLAUDE_FABLE_5 = {\n name: 'claude-fable-5',\n id: 'claude-fable-5',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 10,\n cached: 1,\n },\n output: {\n normal: 50,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOnlyThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n// Claude Sonnet 5: adaptive thinking is the default (omitting `thinking`\n// runs adaptive); `{type: 'disabled'}` opts out, but the manual\n// `{type: 'enabled', budget_tokens}` shape and non-default sampling\n// parameters (`temperature`, `top_p`, `top_k`) are rejected with a 400.\n// Pricing below is the sticker $3/$15 per MTok (an introductory $2/$10\n// applies through 2026-08-31).\nconst CLAUDE_SONNET_5 = {\n name: 'claude-sonnet-5',\n id: 'claude-sonnet-5',\n context_window: 1_000_000,\n max_output_tokens: 128_000,\n supports: {\n input: ['text', 'image', 'document'],\n extended_thinking: false,\n adaptive_thinking: true,\n priority_tier: true,\n tools: [\n 'web_search',\n 'web_fetch',\n 'code_execution',\n 'computer_use',\n 'bash',\n 'text_editor',\n 'memory',\n ],\n },\n pricing: {\n input: {\n normal: 3,\n cached: 0.3,\n },\n output: {\n normal: 15,\n },\n },\n} as const satisfies ModelMeta<\n AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n>\n\n/**\n * Model ids accepted by the Anthropic text adapter.\n *\n * Every id here resolves against the first-party Anthropic API\n * (`GET /v1/models/{id}`). Retired models (Claude 3.x, Sonnet 3.7,\n * Opus 4 / Sonnet 4) and the `-fast` variant ids (fast mode is requested\n * via the `speed` parameter, not a model id) were removed after Anthropic\n * turned them off.\n */\nexport const ANTHROPIC_MODELS = [\n CLAUDE_OPUS_4_6.id,\n CLAUDE_OPUS_4_5.id,\n CLAUDE_SONNET_4_6.id,\n CLAUDE_SONNET_4_5.id,\n CLAUDE_HAIKU_4_5.id,\n CLAUDE_OPUS_4_1.id,\n\n CLAUDE_OPUS_4_7.id,\n CLAUDE_OPUS_4_8.id,\n\n CLAUDE_FABLE_5.id,\n CLAUDE_SONNET_5.id,\n] as const\n\n/**\n * Fallback `max_tokens` ceiling for a model whose metadata carries no\n * `max_output_tokens` (e.g. an unrecognized model id). Anthropic's Messages\n * API *requires* `max_tokens`, so the adapter must always send a value. 64K is\n * the output ceiling of the current mainstream Claude tier (Sonnet/Haiku 4.5),\n * so it's a sane default for an unknown — almost certainly modern — model and\n * avoids silently truncating long generations (issue #849). Recognized models\n * use their exact `max_output_tokens` from {@link ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS}\n * (e.g. 128K for Opus), so this fallback only ever applies to ids not in the\n * map.\n */\nexport const ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS = 64_000\n\n/**\n * Runtime lookup of each model's maximum output-token ceiling, keyed by model\n * id. Lets the text adapter default the required `max_tokens` request field to\n * the model's real ceiling when the caller doesn't specify one, rather than a\n * low constant that truncates responses mid-stream (issue #849).\n *\n * Kept in sync with {@link ANTHROPIC_MODELS} by `scripts/sync-provider-models.ts`\n * — when that script adds a model it also inserts the model's `max_output_tokens`\n * here, so a freshly-synced model resolves to its real ceiling rather than the\n * fallback above.\n */\nconst ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS: Record<string, number> = {\n [CLAUDE_OPUS_4_6.id]: CLAUDE_OPUS_4_6.max_output_tokens,\n [CLAUDE_OPUS_4_5.id]: CLAUDE_OPUS_4_5.max_output_tokens,\n [CLAUDE_SONNET_4_6.id]: CLAUDE_SONNET_4_6.max_output_tokens,\n [CLAUDE_SONNET_4_5.id]: CLAUDE_SONNET_4_5.max_output_tokens,\n [CLAUDE_HAIKU_4_5.id]: CLAUDE_HAIKU_4_5.max_output_tokens,\n [CLAUDE_OPUS_4_1.id]: CLAUDE_OPUS_4_1.max_output_tokens,\n [CLAUDE_OPUS_4_7.id]: CLAUDE_OPUS_4_7.max_output_tokens,\n [CLAUDE_OPUS_4_8.id]: CLAUDE_OPUS_4_8.max_output_tokens,\n [CLAUDE_FABLE_5.id]: CLAUDE_FABLE_5.max_output_tokens,\n [CLAUDE_SONNET_5.id]: CLAUDE_SONNET_5.max_output_tokens,\n}\n\n/**\n * Largest `max_tokens` the Anthropic SDK permits on a **non-streaming**\n * request. The SDK refuses to make a non-streaming call it estimates could\n * exceed its 10-minute timeout, computed as\n * `(60min * max_tokens) / 128_000 > 10min` — i.e. it throws\n * `\"Streaming is required for operations that may take longer than 10 minutes\"`\n * once `max_tokens > 128_000 * 10 / 60 ≈ 21_333`\n * (`@anthropic-ai/sdk`'s `calculateNonstreamingTimeout`). The text adapter's\n * only non-streaming call is the forced-tool `structuredOutput()` request, so\n * its defaulted ceiling must stay at or below this; the streaming chat path\n * keeps the model's full {@link getAnthropicDefaultMaxTokens} ceiling. We sit\n * just under the boundary (`21_333` would round-trip to exactly 10min). This\n * caps only the *default* — an explicit oversized `max_tokens` from the caller\n * still surfaces the SDK's \"use streaming\" error, which is the correct signal.\n */\nexport const ANTHROPIC_MAX_NONSTREAMING_TOKENS = 21_000\n\n/**\n * Resolve the default `max_tokens` for a model: its known `max_output_tokens`\n * ceiling, or {@link ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS} for unknown models.\n * Callers that pass an explicit `max_tokens` bypass this entirely.\n *\n * Pass `stream: false` for non-streaming requests (the `structuredOutput()`\n * path): the result is then clamped to {@link ANTHROPIC_MAX_NONSTREAMING_TOKENS}\n * so the defaulted ceiling doesn't trip the SDK's non-streaming 10-minute guard\n * (issue #849). Streaming requests (the default) are unaffected and get the\n * model's full ceiling.\n */\nexport function getAnthropicDefaultMaxTokens(\n model: string,\n { stream = true }: { stream?: boolean } = {},\n): number {\n const ceiling =\n ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS[model] ??\n ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS\n return stream ? ceiling : Math.min(ceiling, ANTHROPIC_MAX_NONSTREAMING_TOKENS)\n}\n\n/**\n * Anthropic models that support combining `tools` + JSON-Schema-constrained\n * output in a single streaming Messages request (per issue #605). GA'd\n * 2026-01-29 for Claude 4.5+ via `output_format` on the beta messages\n * endpoint. Older Claude models still need the forced-tool-use workaround\n * in `structuredOutput`.\n */\nexport const ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS = new Set<string>([\n CLAUDE_OPUS_4_5.id,\n CLAUDE_OPUS_4_6.id,\n CLAUDE_OPUS_4_7.id,\n CLAUDE_OPUS_4_8.id,\n CLAUDE_FABLE_5.id,\n CLAUDE_SONNET_5.id,\n CLAUDE_SONNET_4_5.id,\n CLAUDE_SONNET_4_6.id,\n CLAUDE_HAIKU_4_5.id,\n])\n\n// const ANTHROPIC_IMAGE_MODELS = [] as const\n// const ANTHROPIC_EMBEDDING_MODELS = [] as const\n// const ANTHROPIC_AUDIO_MODELS = [] as const\n// const ANTHROPIC_VIDEO_MODELS = [] as const\n\nexport type AnthropicChatModel = (typeof ANTHROPIC_MODELS)[number]\n// Manual type map for per-model provider options\n// Models are differentiated by which thinking shapes and sampling\n// parameters the API accepts.\nexport type AnthropicChatModelProviderOptionsByName = {\n // 4.6 generation: adaptive thinking plus the deprecated budget-based\n // shape; sampling parameters still accepted.\n [CLAUDE_OPUS_4_6.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_SONNET_4_6.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n\n // Pre-4.6 models: budget-based extended thinking and sampling parameters.\n [CLAUDE_OPUS_4_5.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_SONNET_4_5.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_HAIKU_4_5.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n [CLAUDE_OPUS_4_1.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicSamplingOptions\n\n // Opus 4.7/4.8: adaptive thinking (or explicit disable), no\n // budget_tokens, no sampling parameters — see the constants above.\n [CLAUDE_OPUS_4_7.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n [CLAUDE_OPUS_4_8.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n\n // Claude Fable 5: thinking always on (adaptive-only config); sampling\n // parameters removed — see the CLAUDE_FABLE_5 constant above.\n [CLAUDE_FABLE_5.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOnlyThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n // Claude Sonnet 5: adaptive thinking by default, explicit disable\n // allowed; no budget_tokens, no sampling parameters — see the\n // CLAUDE_SONNET_5 constant above.\n [CLAUDE_SONNET_5.id]: AnthropicContainerOptions &\n AnthropicContextManagementOptions &\n AnthropicMCPOptions &\n AnthropicServiceTierOptions &\n AnthropicStopSequencesOptions &\n AnthropicAdaptiveOrDisabledThinkingOptions &\n AnthropicToolChoiceOptions &\n AnthropicMaxTokensOptions &\n AnthropicOutputConfigOptions\n}\n\nexport type AnthropicChatModelToolCapabilitiesByName = {\n [CLAUDE_OPUS_4_6.id]: typeof CLAUDE_OPUS_4_6.supports.tools\n [CLAUDE_OPUS_4_5.id]: typeof CLAUDE_OPUS_4_5.supports.tools\n [CLAUDE_SONNET_4_6.id]: typeof CLAUDE_SONNET_4_6.supports.tools\n [CLAUDE_SONNET_4_5.id]: typeof CLAUDE_SONNET_4_5.supports.tools\n [CLAUDE_HAIKU_4_5.id]: typeof CLAUDE_HAIKU_4_5.supports.tools\n [CLAUDE_OPUS_4_1.id]: typeof CLAUDE_OPUS_4_1.supports.tools\n [CLAUDE_OPUS_4_7.id]: typeof CLAUDE_OPUS_4_7.supports.tools\n [CLAUDE_OPUS_4_8.id]: typeof CLAUDE_OPUS_4_8.supports.tools\n [CLAUDE_FABLE_5.id]: typeof CLAUDE_FABLE_5.supports.tools\n [CLAUDE_SONNET_5.id]: typeof CLAUDE_SONNET_5.supports.tools\n}\n\n/**\n * Type-only map from chat model name to its supported input modalities.\n * All Anthropic Claude models support text, image, and document (PDF) input.\n * Used by the core AI types to constrain ContentPart types based on the selected model.\n * Note: These must be inlined as readonly arrays (not typeof) because the model\n * constants are not exported and typeof references don't work in .d.ts files\n * when consumed by external packages.\n *\n * @see https://docs.anthropic.com/claude/docs/vision\n * @see https://docs.anthropic.com/claude/docs/pdf-support\n */\nexport type AnthropicModelInputModalitiesByName = {\n [CLAUDE_OPUS_4_6.id]: typeof CLAUDE_OPUS_4_6.supports.input\n [CLAUDE_OPUS_4_5.id]: typeof CLAUDE_OPUS_4_5.supports.input\n [CLAUDE_SONNET_4_6.id]: typeof CLAUDE_SONNET_4_6.supports.input\n [CLAUDE_SONNET_4_5.id]: typeof CLAUDE_SONNET_4_5.supports.input\n [CLAUDE_HAIKU_4_5.id]: typeof CLAUDE_HAIKU_4_5.supports.input\n [CLAUDE_OPUS_4_1.id]: typeof CLAUDE_OPUS_4_1.supports.input\n [CLAUDE_OPUS_4_7.id]: typeof CLAUDE_OPUS_4_7.supports.input\n [CLAUDE_OPUS_4_8.id]: typeof CLAUDE_OPUS_4_8.supports.input\n [CLAUDE_FABLE_5.id]: typeof CLAUDE_FABLE_5.supports.input\n [CLAUDE_SONNET_5.id]: typeof CLAUDE_SONNET_5.supports.input\n}\n"],"names":[],"mappings":"AAkEA,MAAM,kBAAkB;AAAA,EAEtB,IAAI;AAAA,EAEJ,mBAAmB;AAyBrB;AAWA,MAAM,kBAAkB;AAAA,EAEtB,IAAI;AAAA,EAEJ,mBAAmB;AAwBrB;AAaA,MAAM,oBAAoB;AAAA,EAExB,IAAI;AAAA,EAEJ,mBAAmB;AAyBrB;AAWA,MAAM,oBAAoB;AAAA,EAExB,IAAI;AAAA,EAEJ,mBAAmB;AAwBrB;AAWA,MAAM,mBAAmB;AAAA,EAEvB,IAAI;AAAA,EAEJ,mBAAmB;AAwBrB;AAWA,MAAM,kBAAkB;AAAA,EAEtB,IAAI;AAAA,EAEJ,mBAAmB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IAAY;AAAA,EACxE,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,kBAAkB;AAAA,EAClB,kBAAkB;AAAA,EAClB,iBAAiB;AACnB,CAAC;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/ai-anthropic",
|
|
3
|
-
"version": "0.16.
|
|
3
|
+
"version": "0.16.1",
|
|
4
4
|
"description": "Anthropic Claude adapter for TanStack AI chat, tool calling, thinking, and structured outputs.",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -53,12 +53,12 @@
|
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
55
55
|
"zod": "^4.0.0",
|
|
56
|
-
"@tanstack/ai": "^0.
|
|
56
|
+
"@tanstack/ai": "^0.40.0"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
59
|
"@vitest/coverage-v8": "4.0.14",
|
|
60
60
|
"zod": "^4.2.0",
|
|
61
|
-
"@tanstack/ai": "0.
|
|
61
|
+
"@tanstack/ai": "0.40.0"
|
|
62
62
|
},
|
|
63
63
|
"scripts": {
|
|
64
64
|
"build": "vite build",
|
package/src/adapters/text.ts
CHANGED
|
@@ -10,7 +10,10 @@ import {
|
|
|
10
10
|
generateId,
|
|
11
11
|
getAnthropicApiKeyFromEnv,
|
|
12
12
|
} from '../utils'
|
|
13
|
-
import {
|
|
13
|
+
import {
|
|
14
|
+
ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS,
|
|
15
|
+
getAnthropicDefaultMaxTokens,
|
|
16
|
+
} from '../model-meta'
|
|
14
17
|
import type {
|
|
15
18
|
ANTHROPIC_MODELS,
|
|
16
19
|
AnthropicChatModelProviderOptionsByName,
|
|
@@ -343,7 +346,12 @@ export class AnthropicTextAdapter<
|
|
|
343
346
|
const { chatOptions, outputSchema } = options
|
|
344
347
|
const { logger } = chatOptions
|
|
345
348
|
|
|
346
|
-
|
|
349
|
+
// `structuredOutput()` issues a non-streaming `messages.create({ stream:
|
|
350
|
+
// false })` below, so the defaulted `max_tokens` must stay under the SDK's
|
|
351
|
+
// non-streaming 10-minute guard (issue #849) — pass `stream: false`.
|
|
352
|
+
const requestParams = this.mapCommonOptionsToAnthropic(chatOptions, {
|
|
353
|
+
stream: false,
|
|
354
|
+
})
|
|
347
355
|
|
|
348
356
|
// Create a tool that will capture the structured output
|
|
349
357
|
// Anthropic's SDK requires input_schema with type: 'object' literal
|
|
@@ -432,6 +440,7 @@ export class AnthropicTextAdapter<
|
|
|
432
440
|
|
|
433
441
|
private mapCommonOptionsToAnthropic(
|
|
434
442
|
options: TextOptions<AnthropicTextProviderOptions>,
|
|
443
|
+
{ stream = true }: { stream?: boolean } = {},
|
|
435
444
|
) {
|
|
436
445
|
const modelOptions = options.modelOptions
|
|
437
446
|
|
|
@@ -500,7 +509,18 @@ export class AnthropicTextAdapter<
|
|
|
500
509
|
validProviderOptions.thinking?.type === 'enabled'
|
|
501
510
|
? validProviderOptions.thinking.budget_tokens
|
|
502
511
|
: undefined
|
|
503
|
-
|
|
512
|
+
// Anthropic's Messages API *requires* `max_tokens`, so we must always send a
|
|
513
|
+
// value. When the caller doesn't specify one, default to the resolved
|
|
514
|
+
// model's real output ceiling (from model-meta) rather than a low constant
|
|
515
|
+
// that silently truncates long responses with `stop_reason: "max_tokens"`
|
|
516
|
+
// (issue #849). `max_tokens` is a ceiling, not a reservation — billing is on
|
|
517
|
+
// tokens actually generated, so a higher default costs nothing extra.
|
|
518
|
+
// For non-streaming requests (the `structuredOutput()` path) the default is
|
|
519
|
+
// clamped to the SDK's non-streaming-safe limit so it doesn't trip the
|
|
520
|
+
// "streaming required" 10-minute guard — see getAnthropicDefaultMaxTokens.
|
|
521
|
+
const defaultMaxTokens =
|
|
522
|
+
modelOptions?.max_tokens ??
|
|
523
|
+
getAnthropicDefaultMaxTokens(this.model, { stream })
|
|
504
524
|
const maxTokens =
|
|
505
525
|
thinkingBudget && thinkingBudget >= defaultMaxTokens
|
|
506
526
|
? thinkingBudget + 1
|
|
@@ -1346,6 +1366,22 @@ export class AnthropicTextAdapter<
|
|
|
1346
1366
|
break
|
|
1347
1367
|
}
|
|
1348
1368
|
case 'max_tokens': {
|
|
1369
|
+
// Surface a warning when the truncating cap was the
|
|
1370
|
+
// adapter-supplied default (caller didn't pass `max_tokens`), so
|
|
1371
|
+
// the truncation isn't silently attributed to the model "doing
|
|
1372
|
+
// nothing" (issue #849). When the caller set `max_tokens`
|
|
1373
|
+
// themselves, hitting it is their own deliberate ceiling.
|
|
1374
|
+
if (options.modelOptions?.max_tokens == null) {
|
|
1375
|
+
const defaultedMaxTokens = getAnthropicDefaultMaxTokens(model)
|
|
1376
|
+
logger.warn(
|
|
1377
|
+
`anthropic response truncated at the default max_tokens (${defaultedMaxTokens}) for model=${model}; pass maxTokens (or modelOptions.max_tokens) to raise the output ceiling`,
|
|
1378
|
+
{
|
|
1379
|
+
source: 'anthropic.processAnthropicStream',
|
|
1380
|
+
model,
|
|
1381
|
+
defaultedMaxTokens,
|
|
1382
|
+
},
|
|
1383
|
+
)
|
|
1384
|
+
}
|
|
1349
1385
|
yield {
|
|
1350
1386
|
type: EventType.RUN_ERROR,
|
|
1351
1387
|
model,
|
package/src/model-meta.ts
CHANGED
|
@@ -506,6 +506,81 @@ export const ANTHROPIC_MODELS = [
|
|
|
506
506
|
CLAUDE_SONNET_5.id,
|
|
507
507
|
] as const
|
|
508
508
|
|
|
509
|
+
/**
|
|
510
|
+
* Fallback `max_tokens` ceiling for a model whose metadata carries no
|
|
511
|
+
* `max_output_tokens` (e.g. an unrecognized model id). Anthropic's Messages
|
|
512
|
+
* API *requires* `max_tokens`, so the adapter must always send a value. 64K is
|
|
513
|
+
* the output ceiling of the current mainstream Claude tier (Sonnet/Haiku 4.5),
|
|
514
|
+
* so it's a sane default for an unknown — almost certainly modern — model and
|
|
515
|
+
* avoids silently truncating long generations (issue #849). Recognized models
|
|
516
|
+
* use their exact `max_output_tokens` from {@link ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS}
|
|
517
|
+
* (e.g. 128K for Opus), so this fallback only ever applies to ids not in the
|
|
518
|
+
* map.
|
|
519
|
+
*/
|
|
520
|
+
export const ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS = 64_000
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Runtime lookup of each model's maximum output-token ceiling, keyed by model
|
|
524
|
+
* id. Lets the text adapter default the required `max_tokens` request field to
|
|
525
|
+
* the model's real ceiling when the caller doesn't specify one, rather than a
|
|
526
|
+
* low constant that truncates responses mid-stream (issue #849).
|
|
527
|
+
*
|
|
528
|
+
* Kept in sync with {@link ANTHROPIC_MODELS} by `scripts/sync-provider-models.ts`
|
|
529
|
+
* — when that script adds a model it also inserts the model's `max_output_tokens`
|
|
530
|
+
* here, so a freshly-synced model resolves to its real ceiling rather than the
|
|
531
|
+
* fallback above.
|
|
532
|
+
*/
|
|
533
|
+
const ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS: Record<string, number> = {
|
|
534
|
+
[CLAUDE_OPUS_4_6.id]: CLAUDE_OPUS_4_6.max_output_tokens,
|
|
535
|
+
[CLAUDE_OPUS_4_5.id]: CLAUDE_OPUS_4_5.max_output_tokens,
|
|
536
|
+
[CLAUDE_SONNET_4_6.id]: CLAUDE_SONNET_4_6.max_output_tokens,
|
|
537
|
+
[CLAUDE_SONNET_4_5.id]: CLAUDE_SONNET_4_5.max_output_tokens,
|
|
538
|
+
[CLAUDE_HAIKU_4_5.id]: CLAUDE_HAIKU_4_5.max_output_tokens,
|
|
539
|
+
[CLAUDE_OPUS_4_1.id]: CLAUDE_OPUS_4_1.max_output_tokens,
|
|
540
|
+
[CLAUDE_OPUS_4_7.id]: CLAUDE_OPUS_4_7.max_output_tokens,
|
|
541
|
+
[CLAUDE_OPUS_4_8.id]: CLAUDE_OPUS_4_8.max_output_tokens,
|
|
542
|
+
[CLAUDE_FABLE_5.id]: CLAUDE_FABLE_5.max_output_tokens,
|
|
543
|
+
[CLAUDE_SONNET_5.id]: CLAUDE_SONNET_5.max_output_tokens,
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* Largest `max_tokens` the Anthropic SDK permits on a **non-streaming**
|
|
548
|
+
* request. The SDK refuses to make a non-streaming call it estimates could
|
|
549
|
+
* exceed its 10-minute timeout, computed as
|
|
550
|
+
* `(60min * max_tokens) / 128_000 > 10min` — i.e. it throws
|
|
551
|
+
* `"Streaming is required for operations that may take longer than 10 minutes"`
|
|
552
|
+
* once `max_tokens > 128_000 * 10 / 60 ≈ 21_333`
|
|
553
|
+
* (`@anthropic-ai/sdk`'s `calculateNonstreamingTimeout`). The text adapter's
|
|
554
|
+
* only non-streaming call is the forced-tool `structuredOutput()` request, so
|
|
555
|
+
* its defaulted ceiling must stay at or below this; the streaming chat path
|
|
556
|
+
* keeps the model's full {@link getAnthropicDefaultMaxTokens} ceiling. We sit
|
|
557
|
+
* just under the boundary (`21_333` would round-trip to exactly 10min). This
|
|
558
|
+
* caps only the *default* — an explicit oversized `max_tokens` from the caller
|
|
559
|
+
* still surfaces the SDK's "use streaming" error, which is the correct signal.
|
|
560
|
+
*/
|
|
561
|
+
export const ANTHROPIC_MAX_NONSTREAMING_TOKENS = 21_000
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* Resolve the default `max_tokens` for a model: its known `max_output_tokens`
|
|
565
|
+
* ceiling, or {@link ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS} for unknown models.
|
|
566
|
+
* Callers that pass an explicit `max_tokens` bypass this entirely.
|
|
567
|
+
*
|
|
568
|
+
* Pass `stream: false` for non-streaming requests (the `structuredOutput()`
|
|
569
|
+
* path): the result is then clamped to {@link ANTHROPIC_MAX_NONSTREAMING_TOKENS}
|
|
570
|
+
* so the defaulted ceiling doesn't trip the SDK's non-streaming 10-minute guard
|
|
571
|
+
* (issue #849). Streaming requests (the default) are unaffected and get the
|
|
572
|
+
* model's full ceiling.
|
|
573
|
+
*/
|
|
574
|
+
export function getAnthropicDefaultMaxTokens(
|
|
575
|
+
model: string,
|
|
576
|
+
{ stream = true }: { stream?: boolean } = {},
|
|
577
|
+
): number {
|
|
578
|
+
const ceiling =
|
|
579
|
+
ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS[model] ??
|
|
580
|
+
ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
|
|
581
|
+
return stream ? ceiling : Math.min(ceiling, ANTHROPIC_MAX_NONSTREAMING_TOKENS)
|
|
582
|
+
}
|
|
583
|
+
|
|
509
584
|
/**
|
|
510
585
|
* Anthropic models that support combining `tools` + JSON-Schema-constrained
|
|
511
586
|
* output in a single streaming Messages request (per issue #605). GA'd
|