import { createOpenRouterResponsesClient } from '../client/index' import type { OpenRouterClient } from '../client/index' import { EventType, isFileSource, normalizeSystemPrompts, unsupportedFileSourceError, } from '@tanstack/ai' import { BaseTextAdapter } from '@tanstack/ai/adapters' import { hashToolCallId, orderedAssistantBlocks, resolveReasoning, tanstackMetadata, toRunErrorDetails, toRunErrorPayload, toRunErrorRawEvent, transformMessagesForReplay, } from '@tanstack/ai/adapter-internals' import { drainAfterTerminal, generateId } from '@tanstack/ai-utils' import { extractRequestOptions } from '../internal/request-options' import { clientForCall } from '../internal/wrap-fetch' import { openRouterSupportsCombinedToolsAndSchema } from '../internal/combined-tools-and-schema' import { openRouterUsesJsonObject, withJsonModePrompt, } from '../internal/json-object-mode' import { makeStructuredOutputCompatible } from '../internal/schema-converter' import { convertFunctionToolToResponsesFormat, createToolInputNormalizer, } from '../internal/responses-tool-converter' import { OPENROUTER_MODEL_INPUT_MODALITIES, OPENROUTER_MODEL_REASONING, } from '../model-meta' import { openRouterEffort } from '../internal/reasoning' import { isWebSearchTool } from '../tools/web-search-tool' import { isWebFetchTool } from '../tools/web-fetch-tool' import { getOpenRouterApiKeyFromEnv } from '../utils' import { toOpenRouterRunErrorPayload } from '../utils/run-error' import { extractUsageCost } from './cost' import type { SDKOptions } from '@openrouter/sdk' import type { ResponsesFunctionTool } from '../internal/responses-tool-converter' import type { ContentPartAddedEventPart, FunctionCallOutputItemOutputUnion1, InputsUnion, OpenResponsesResult, OutputItems, ReasoningEffort, ResponsesRequest, StreamEvents, Usage, } from '@openrouter/sdk/models' import type { StructuredOutputOptions, StructuredOutputResult, } from '@tanstack/ai/adapters' import type { ContentPart, ImagePart, JSONSchema, ModelMessage, AdapterYieldChunk, TextOptions, TokenUsage, ToolChoice, } from '@tanstack/ai' import type { ExternalResponsesProviderOptions } from '../text/responses-provider-options' import type { OpenRouterProviderUsageDetails } from '../usage' import type { OPENROUTER_CHAT_MODELS, OpenRouterChatModelToolCapabilitiesByName, OpenRouterModelInputModalitiesByName, OpenRouterModelReasoningByName, } from '../model-meta' import type { OpenRouterMessageMetadataByModality, OpenRouterResponsesToolCallMetadata, } from '../message-types' /** Element type of `ResponsesRequest.input` when it's the array form (the * SDK union also allows a bare string). Pinning to the array element lets * the convertMessagesToInput logic narrow to the per-item discriminated * union so a TS rename surfaces here. */ type InputsItem = Extract>[number] /** ResponsesRequest input content part shape (per-content-part discriminated union). */ type ResponsesInputContent = unknown interface StreamedFunctionCallMetadata { callId: string index: number itemId: string name: string namespace?: string started: boolean ended?: boolean pendingArguments?: string } export interface OpenRouterResponsesConfig extends SDKOptions {} export type OpenRouterResponsesTextModels = (typeof OPENROUTER_CHAT_MODELS)[number] export type OpenRouterResponsesTextProviderOptions = ExternalResponsesProviderOptions /** The reasoning levels of a model, for `chat({ reasoning })`. `never`: none. */ type ResolveReasoning = TModel extends keyof OpenRouterModelReasoningByName ? OpenRouterModelReasoningByName[TModel] : never type ResolveInputModalities = TModel extends keyof OpenRouterModelInputModalitiesByName ? OpenRouterModelInputModalitiesByName[TModel] : readonly ['text', 'image'] type ResolveToolCapabilities = TModel extends keyof OpenRouterChatModelToolCapabilitiesByName ? NonNullable : readonly [] /** Maps `chat({ toolChoice })` to the OpenRouter Responses `toolChoice`. */ function toOpenRouterResponsesToolChoice( choice: ToolChoice, ): NonNullable { if (typeof choice === 'string') return choice return { type: 'function', name: choice.name } } /** * OpenRouter's SDK raises a proprietary `RequestAbortedError` on a caller * abort. It and a DOM `AbortError` map to `code: 'aborted'`. */ function isOpenRouterAbort(error: unknown): boolean { const name = error && typeof error === 'object' ? (error as { name?: unknown }).name : undefined return name === 'AbortError' || name === 'RequestAbortedError' } /** * OpenRouter Responses (beta) Adapter — standalone implementation that talks * to OpenRouter's `/v1/responses` (beta) endpoint via a fetch client with the * `@openrouter/sdk` API and wire format. * * The wire format is OpenAI-Responses-compatible (so OpenRouter can route * Responses requests to GPT, Claude, Gemini, etc.) but the SDK exposes the * request/response in camelCase TS shapes (`callId`, `imageUrl`, * `fileData`, `outputIndex`, `itemId`, `inputTokens`, `incompleteDetails`, * etc.). This adapter operates directly in those camelCase shapes — there's * no snake_case ↔ camelCase round-trip. * * v1 routes function tools only. Passing a `webSearchTool()` brand throws * — OpenRouter's Responses API exposes richer server-tool variants * (WebSearchServerToolOpenRouter / Preview20250311WebSearchServerTool / * …) that will land in a follow-up. */ export class OpenRouterResponsesTextAdapter< TModel extends OpenRouterResponsesTextModels, TToolCapabilities extends ReadonlyArray = ResolveToolCapabilities, > extends BaseTextAdapter< TModel, OpenRouterResponsesTextProviderOptions, ResolveInputModalities, OpenRouterMessageMetadataByModality, TToolCapabilities, OpenRouterResponsesToolCallMetadata, never, ResolveReasoning > { override readonly kind = 'text' as const readonly name = 'openrouter-responses' as const override readonly provider = 'openrouter' override readonly api = 'openai-responses' override readonly inputModalities = OPENROUTER_MODEL_INPUT_MODALITIES[this.model] protected orClient: Pick private readonly sdkOptions: SDKOptions constructor(config: OpenRouterResponsesConfig, model: TModel) { super({}, model) this.sdkOptions = config this.orClient = createOpenRouterResponsesClient(config) } async *chatStream( options: TextOptions, ): AsyncIterable { const source = { provider: this.provider, api: this.api, model: options.model, } for await (const chunk of this.chatStreamRequest(options)) yield { ...chunk, metadata: { ...chunk.metadata, tanstack: { ...tanstackMetadata(chunk), source }, }, } } private async *chatStreamRequest( options: TextOptions, ): AsyncIterable { // Track tool call metadata by unique ID. The Responses API streams tool // calls with deltas — first chunk has ID/name, subsequent chunks only // have args. We assign our own indices as we encounter unique ids. const toolCallMetadata = new Map() // AG-UI lifecycle tracking const aguiState = { runId: generateId(this.name), threadId: options.threadId, messageId: generateId(this.name), hasEmittedRunStarted: false, } try { // mapOptionsToRequest can throw on caller-side validation failures // (empty user content, unsupported parts, webSearchTool() rejection). // Keep it inside the try so those failures surface as RUN_ERROR events // instead of iterator throws. const responsesRequest = this.mapOptionsToRequest(options) options.logger.request( `activity=chat provider=${this.name} model=${this.model} messages=${options.messages.length} tools=${options.tools?.length ?? 0} stream=true`, { provider: this.name, model: this.model }, ) const reqOptions = extractRequestOptions(options.request) const response = await clientForCall( this.orClient, this.sdkOptions, options.wrapFetch, createOpenRouterResponsesClient, ).beta.responses.send( { responsesRequest: { ...responsesRequest, stream: true } }, { ...(reqOptions.signal != null && { signal: reqOptions.signal }), ...(reqOptions.headers && { headers: reqOptions.headers }), }, ) yield* this.processStreamChunks( response, toolCallMetadata, options, aguiState, ) } catch (error: unknown) { // Narrow before logging: raw SDK errors can carry request metadata // (including auth headers) which we must never surface to user loggers. const errorPayload = toOpenRouterRunErrorPayload( error, `${this.name}.chatStream failed`, ) const rawEvent = toRunErrorRawEvent(error) // Emit RUN_STARTED if not yet emitted if (!aguiState.hasEmittedRunStarted) { aguiState.hasEmittedRunStarted = true yield { type: EventType.RUN_STARTED, runId: aguiState.runId, threadId: aguiState.threadId, model: options.model, timestamp: Date.now(), parentRunId: options.parentRunId, } } yield { type: EventType.RUN_ERROR, model: options.model, timestamp: Date.now(), message: errorPayload.message, code: errorPayload.code, ...(rawEvent !== undefined && { rawEvent }), error: { message: errorPayload.message, code: errorPayload.code, }, } options.logger.errors(`${this.name}.chatStream fatal`, { error: errorPayload, source: `${this.name}.chatStream`, }) } } /** * Generate structured output via OpenRouter's Responses API * `text.format: { type: 'json_schema', ... }`. Uses stream: false. */ async structuredOutput( options: StructuredOutputOptions, ): Promise> { const { chatOptions, outputSchema } = options const jsonMode = openRouterUsesJsonObject( chatOptions.model || this.model, chatOptions.modelOptions, ) const responsesRequest = this.mapOptionsToRequest( jsonMode ? withJsonModePrompt(chatOptions, outputSchema) : chatOptions, ) const textFormat = this.structuredTextFormat(jsonMode, outputSchema) try { chatOptions.logger.request( `activity=structuredOutput provider=${this.name} model=${this.model} messages=${chatOptions.messages.length}`, { provider: this.name, model: this.model }, ) const reqOptions = extractRequestOptions(chatOptions.request) const response = await clientForCall( this.orClient, this.sdkOptions, chatOptions.wrapFetch, createOpenRouterResponsesClient, ).beta.responses.send( { responsesRequest: { ...responsesRequest, stream: false, text: { format: textFormat, }, }, }, { ...(reqOptions.signal != null && { signal: reqOptions.signal }), ...(reqOptions.headers && { headers: reqOptions.headers }), }, ) // Responses API reports usage as inputTokens/outputTokens. A failure // below still carries it: core reads `error.usage`. const usage = buildResponsesUsage(response.usage) const fail = (message: string) => Object.assign(new Error(message), usage && { usage }) // A cut-off response is a truncated JSON document. Report the cutoff // instead of the parse error it would cause. if (response.status === 'incomplete') { throw fail( `${this.name}.structuredOutput: the response ended incomplete (${response.incompleteDetails?.reason ?? 'unknown reason'})`, ) } let rawText: string try { rawText = this.extractTextFromResponse(response) } catch (error: unknown) { // A refusal or an unsupported part: the call was still billed. throw error instanceof Error ? Object.assign(error, usage && { usage }) : error } if (rawText.length === 0) { throw fail( `${this.name}.structuredOutput: response contained no content`, ) } let parsed: unknown try { parsed = JSON.parse(rawText) } catch { throw fail( `Failed to parse structured output as JSON. Content: ${rawText.slice(0, 200)}${rawText.length > 200 ? '...' : ''}`, ) } // OpenRouter override: pass nulls through unchanged. const transformed = this.transformStructuredOutput(parsed) return { data: transformed, rawText, ...(response.id && { responseId: response.id }), ...(response.model && { model: response.model }), ...(usage && { usage }), } } catch (error: unknown) { chatOptions.logger.errors(`${this.name}.structuredOutput fatal`, { error: toRunErrorPayload(error, `${this.name}.structuredOutput failed`), source: `${this.name}.structuredOutput`, }) throw error } } /** * Streamed structured output via OpenRouter's Responses API * (`text.format: { type: 'json_schema', ... }` + `stream: true`). * * Mirrors {@link OpenAIBaseResponsesTextAdapter.structuredOutputStream} * adapted to OpenRouter's SDK call surface * (`orClient.beta.responses.send`) and to the camelCase usage shape on * `response.completed` (`inputTokens` / `outputTokens` / `totalTokens`). * * Events flow through {@link normalizeStreamEvent} so this method reads * the same canonical event shape as `processStreamChunks` (covering * Speakeasy's UNKNOWN-with-`raw` fallback for events that fail strict * per-variant validation upstream). */ async *structuredOutputStream( options: StructuredOutputOptions, ): AsyncIterable { const source = { provider: this.provider, api: this.api, model: options.chatOptions.model, } for await (const chunk of this.structuredOutputRequestStream(options)) yield { ...chunk, metadata: { ...chunk.metadata, tanstack: { ...tanstackMetadata(chunk), source }, }, } } private async *structuredOutputRequestStream( options: StructuredOutputOptions, ): AsyncIterable { const { chatOptions, outputSchema } = options const jsonMode = openRouterUsesJsonObject( chatOptions.model || this.model, chatOptions.modelOptions, ) const responsesRequest = this.mapOptionsToRequest( jsonMode ? withJsonModePrompt(chatOptions, outputSchema) : chatOptions, ) const textFormat = this.structuredTextFormat(jsonMode, outputSchema) const aguiState = { runId: generateId(this.name), threadId: chatOptions.threadId, messageId: generateId(this.name), hasEmittedRunStarted: false, } let accumulatedContent = '' let accumulatedReasoning = '' let hasEmittedTextMessageStart = false let reasoningMessageId: string | undefined let hasClosedReasoning = false let model: string = chatOptions.model let responseId: string | undefined let reportedModel: string | undefined let usage: TokenUsage | undefined // A refusal is reported once the terminal event brings the usage. let refusal: string | undefined let responseCompleted = false const refusalError = (text: string): AdapterYieldChunk => { const message = `Model refused: ${text}` return { type: EventType.RUN_ERROR, ...(usage && { usage }), runId: aguiState.runId, model, timestamp: Date.now(), message, code: 'refusal', error: { message, code: 'refusal' }, } } const closeReasoning = function* (this: { name: string }): Generator { if (reasoningMessageId && !hasClosedReasoning) { hasClosedReasoning = true yield { type: EventType.REASONING_MESSAGE_END, messageId: reasoningMessageId, model, timestamp: Date.now(), } yield { type: EventType.REASONING_END, messageId: reasoningMessageId, model, timestamp: Date.now(), } reasoningMessageId = undefined hasClosedReasoning = false } }.bind(this) const openReasoning = function* (this: { name: string }): Generator { if (reasoningMessageId) return reasoningMessageId = generateId(this.name) yield { type: EventType.REASONING_START, messageId: reasoningMessageId, model, timestamp: Date.now(), } yield { type: EventType.REASONING_MESSAGE_START, messageId: reasoningMessageId, role: 'reasoning' as const, model, timestamp: Date.now(), } }.bind(this) try { chatOptions.logger.request( `activity=structuredOutputStream provider=${this.name} model=${this.model} messages=${chatOptions.messages.length}`, { provider: this.name, model: this.model }, ) const reqOptions = extractRequestOptions(chatOptions.request) const rawStream = await clientForCall( this.orClient, this.sdkOptions, chatOptions.wrapFetch, createOpenRouterResponsesClient, ).beta.responses.send( { responsesRequest: { ...responsesRequest, stream: true, text: { format: textFormat, }, }, }, { ...(reqOptions.signal != null && { signal: reqOptions.signal }), ...(reqOptions.headers && { headers: reqOptions.headers }), }, ) for await (const rawEvent of drainAfterTerminal( rawStream, (e) => normalizeStreamEvent(e).type, )) { const chunk = normalizeStreamEvent(rawEvent) if (chunk.response?.id) responseId = chunk.response.id if (chunk.response?.model) { model = chunk.response.model reportedModel = model } chatOptions.logger.provider( `provider=${this.name} type=${chunk.type}`, { provider: this.name, type: chunk.type }, ) if (!aguiState.hasEmittedRunStarted) { aguiState.hasEmittedRunStarted = true yield { type: EventType.RUN_STARTED, runId: aguiState.runId, threadId: aguiState.threadId, model, timestamp: Date.now(), parentRunId: chatOptions.parentRunId, } } if ( chunk.type === 'response.created' || chunk.type === 'response.in_progress' ) { if (chunk.response?.model) model = chunk.response.model continue } if (chunk.type === 'response.refusal.delta') { const delta = typeof chunk.delta === 'string' ? chunk.delta : '' refusal = (refusal ?? '') + delta continue } if ( chunk.type === 'response.reasoning_text.delta' || chunk.type === 'response.reasoning_summary_text.delta' ) { const reasoningDelta = Array.isArray(chunk.delta) ? chunk.delta.join('') : typeof chunk.delta === 'string' ? chunk.delta : '' if (!reasoningDelta) continue yield* openReasoning() // openReasoning() guarantees reasoningMessageId is set on first // call; TS can't see through the generator side-effect. if (!reasoningMessageId) continue accumulatedReasoning += reasoningDelta yield { type: EventType.REASONING_MESSAGE_CONTENT, messageId: reasoningMessageId, delta: reasoningDelta, model, timestamp: Date.now(), } continue } if (chunk.type === 'response.output_text.delta') { const textDelta = Array.isArray(chunk.delta) ? chunk.delta.join('') : typeof chunk.delta === 'string' ? chunk.delta : '' if (!textDelta) continue yield* closeReasoning() if (!hasEmittedTextMessageStart) { hasEmittedTextMessageStart = true yield { type: EventType.TEXT_MESSAGE_START, messageId: aguiState.messageId, model, timestamp: Date.now(), role: 'assistant', } } accumulatedContent += textDelta yield { type: EventType.TEXT_MESSAGE_CONTENT, messageId: aguiState.messageId, model, timestamp: Date.now(), delta: textDelta, content: accumulatedContent, } continue } if (chunk.type === 'response.completed') { responseCompleted = true if (chunk.response?.model) model = chunk.response.model usage = buildResponsesUsage(chunk.response?.usage) // Terminal event: do not wait for the HTTP body to close (#1445). break } if ( chunk.type === 'response.failed' || chunk.type === 'response.incomplete' ) { const message = chunk.response?.error?.message || chunk.response?.incompleteDetails?.reason || (chunk.type === 'response.failed' ? 'Response failed' : 'Response ended incomplete') const code = normalizeCode(chunk.response?.error?.code) ?? (chunk.response?.incompleteDetails ? 'incomplete' : undefined) const rawError = chunk.response?.error usage = buildResponsesUsage(chunk.response?.usage) if (refusal !== undefined) break yield { type: EventType.RUN_ERROR, ...(usage && { usage }), runId: aguiState.runId, model, timestamp: Date.now(), message, ...(code !== undefined && { code }), ...toRunErrorDetails({ type: chunk.response?.errorType }), // Forward the provider's structured error body when the failure // carried one, so consumers can recover the upstream detail. ...(rawError != null && { rawEvent: rawError }), error: { message, ...(code !== undefined && { code }), }, } return } if (chunk.type === 'error') { const code = normalizeCode(chunk.code) const message = chunk.message ?? 'Responses API stream error' yield { type: EventType.RUN_ERROR, runId: aguiState.runId, model, timestamp: Date.now(), message, ...(code !== undefined && { code }), error: { message, ...(code !== undefined && { code }), }, } return } } yield* closeReasoning() if (hasEmittedTextMessageStart) { yield { type: EventType.TEXT_MESSAGE_END, messageId: aguiState.messageId, model, timestamp: Date.now(), } } if (refusal !== undefined) { yield refusalError(refusal) return } if (!responseCompleted) { const message = 'Response stream ended before response.completed' yield { type: EventType.RUN_ERROR, runId: aguiState.runId, model, timestamp: Date.now(), message, code: 'incomplete-stream', error: { message, code: 'incomplete-stream' }, } return } if (accumulatedContent.length === 0) { yield { type: EventType.RUN_ERROR, ...(usage && { usage }), runId: aguiState.runId, model, timestamp: Date.now(), message: `${this.name}.structuredOutputStream: response contained no content`, code: 'empty-response', error: { message: `${this.name}.structuredOutputStream: response contained no content`, code: 'empty-response', }, } return } let parsed: unknown try { parsed = JSON.parse(accumulatedContent) } catch { yield { type: EventType.RUN_ERROR, ...(usage && { usage }), runId: aguiState.runId, model, timestamp: Date.now(), message: `Failed to parse structured output as JSON. Content: ${accumulatedContent.slice(0, 200)}${accumulatedContent.length > 200 ? '...' : ''}`, code: 'parse-error', error: { message: 'Failed to parse structured output as JSON', code: 'parse-error', }, } return } const transformed = this.transformStructuredOutput(parsed) yield { type: EventType.CUSTOM, name: 'structured-output.complete', value: { object: transformed, raw: accumulatedContent, ...(accumulatedReasoning ? { reasoning: accumulatedReasoning } : {}), }, model, timestamp: Date.now(), } yield { type: EventType.RUN_FINISHED, ...(responseId && { responseId }), metadata: { tanstack: { ...(responseId && { responseId }), ...(reportedModel && { model: reportedModel }), }, }, runId: aguiState.runId, threadId: aguiState.threadId, model, timestamp: Date.now(), finishReason: 'stop', ...(usage && { usage }), } } catch (error: unknown) { if (!aguiState.hasEmittedRunStarted) { aguiState.hasEmittedRunStarted = true yield { type: EventType.RUN_STARTED, runId: aguiState.runId, threadId: aguiState.threadId, model, timestamp: Date.now(), parentRunId: chatOptions.parentRunId, } } const isAbort = isOpenRouterAbort(error) const errorPayload = toOpenRouterRunErrorPayload( error, `${this.name}.structuredOutputStream failed`, ) // The model refused before the stream failed: report the refusal. // A caller abort stays an abort. if (refusal !== undefined && !isAbort) { chatOptions.logger.errors( `${this.name}.structuredOutputStream failed after a refusal`, { error: errorPayload, source: `${this.name}.structuredOutputStream`, }, ) yield refusalError(refusal) return } const resolvedCode = isAbort ? 'aborted' : errorPayload.code const rawEvent = isAbort ? undefined : toRunErrorRawEvent(error) yield { type: EventType.RUN_ERROR, ...(usage && { usage }), runId: aguiState.runId, model, timestamp: Date.now(), message: errorPayload.message, ...(resolvedCode !== undefined && { code: resolvedCode }), ...(rawEvent !== undefined && { rawEvent }), error: { message: errorPayload.message, ...(resolvedCode !== undefined && { code: resolvedCode }), }, } chatOptions.logger.errors(`${this.name}.structuredOutputStream fatal`, { error: errorPayload, source: `${this.name}.structuredOutputStream`, }) } } protected makeStructuredOutputCompatible( schema: Record, originalRequired?: Array, ): Record { return makeStructuredOutputCompatible(schema, originalRequired) } /** * OpenRouter routes through a wide variety of upstream providers; some * return `null` as a distinct sentinel rather than collapsing it to absent, * so we passthrough and let the engine un-widen strict-mode nulls precisely. * Matches the base adapters' default — kept as an explicit override because * OpenRouter extends `BaseTextAdapter` directly, not the OpenAI base. */ protected transformStructuredOutput(parsed: unknown): unknown { return parsed } /** * Extract text content from a non-streaming Responses API response. * Reads OpenRouter's camelCase `OpenResponsesResult` shape directly. */ protected extractTextFromResponse(response: OpenResponsesResult): string { let textContent = '' let refusal: string | undefined let sawMessageItem = false const observedItemTypes = new Set() for (const rawItem of response.output) { const item = camelCaseOutputItem(rawItem) as { type: string content?: ReadonlyArray } observedItemTypes.add(item.type) if (item.type === 'message') { sawMessageItem = true for (const part of item.content ?? []) { // Cast off the discriminated union before the type discrimination // so future SDK variants (e.g. `output_audio`, `output_image`) hit // the explicit error path rather than being misreported as refusals // when they get added to the union. const partType = (part as { type: string }).type if (partType === 'output_text') { textContent += (part as { text?: string }).text ?? '' } else if (partType === 'refusal') { const refusalText = (part as { refusal?: string }).refusal refusal = refusalText || refusal || 'Refused without explanation' } else { throw new Error( `${this.name}.extractTextFromResponse: unsupported message content part type "${partType}"`, ) } } } } // Surface refusals as an explicit error so callers don't see a generic // "Failed to parse structured output as JSON. Content: " when the model // refused for safety / content-policy reasons. if (!textContent && refusal !== undefined) { const err = new Error(`Model refused to respond: ${refusal}`) ;(err as Error & { code?: string }).code = 'refusal' throw err } // Response had items but none carried message text (e.g. only // function_call or reasoning items). Surface that explicitly so a // downstream structured-output caller doesn't see a misleading // "Failed to parse JSON. Content: " from an empty string. if (!textContent && response.output.length > 0 && !sawMessageItem) { throw new Error( `${this.name}.extractTextFromResponse: response.output contained items of type(s) [${[...observedItemTypes].sort().join(', ')}] but no message text — the model returned a non-text response`, ) } return textContent } /** * Processes streamed events from the OpenRouter Responses API and yields * AG-UI events. Reads the SDK's camelCase event shape directly * (`itemId`, `outputIndex`, `incompleteDetails`, `inputTokens`, etc.). * * Speakeasy's discriminated-union parser falls back to * `{ raw, type: 'UNKNOWN', isUnknown: true }` when an event's strict * per-variant schema rejects (missing optional fields like `sequenceNumber` * that some upstreams omit). The `raw` payload is the original wire-shape * event in snake_case. We translate snake_case keys to camelCase for those * unknown events so the rest of the processor reads a uniform shape. */ protected async *processStreamChunks( stream: AsyncIterable, toolCallMetadata: Map, options: TextOptions, aguiState: { runId: string threadId: string messageId: string hasEmittedRunStarted: boolean }, ): AsyncIterable { const normalizeToolInput = createToolInputNormalizer( options.tools, this.makeStructuredOutputCompatible.bind(this), ) let accumulatedContent = '' let hasStreamedContentDeltas = false let hasStreamedReasoningDeltas = false let model: string = options.model let responseId: string | undefined let reportedModel: string | undefined let hasEmittedTextMessageStart = false let reasoningMessageId: string | undefined let hasClosedReasoning = false let runFinishedEmitted = false // A refusal (or unknown content part) RUN_ERROR waits for the terminal // event, so it can carry the usage that only that event reports. let pendingRunError: AdapterYieldChunk | undefined const adapterName = this.name const emitModel = () => model || options.model const openReasoning = function* (): Generator { if (reasoningMessageId) return reasoningMessageId = generateId(adapterName) const timestamp = Date.now() const currentModel = emitModel() yield { type: EventType.REASONING_START, messageId: reasoningMessageId, model: currentModel, timestamp, } yield { type: EventType.REASONING_MESSAGE_START, messageId: reasoningMessageId, role: 'reasoning' as const, model: currentModel, timestamp, } } const closeReasoning = function* (): Generator { if (!reasoningMessageId || hasClosedReasoning) return hasClosedReasoning = true const timestamp = Date.now() const currentModel = emitModel() yield { type: EventType.REASONING_MESSAGE_END, messageId: reasoningMessageId, model: currentModel, timestamp, } yield { type: EventType.REASONING_END, messageId: reasoningMessageId, model: currentModel, timestamp, } reasoningMessageId = undefined hasClosedReasoning = false } const emitReasoningDelta = function* ( text: string, ): Generator { if (!text) return yield* openReasoning() if (!reasoningMessageId) return hasStreamedReasoningDeltas = true yield { type: EventType.REASONING_MESSAGE_CONTENT, messageId: reasoningMessageId, delta: text, model: emitModel(), timestamp: Date.now(), } } try { for await (const rawEvent of drainAfterTerminal( stream, (e) => normalizeStreamEvent(e).type, )) { const chunk = normalizeStreamEvent(rawEvent) if (chunk.response?.id) responseId = chunk.response.id if (chunk.response?.model) { model = chunk.response.model reportedModel = model } options.logger.provider(`provider=${this.name} type=${chunk.type}`, { provider: this.name, type: chunk.type, }) // Emit RUN_STARTED on first chunk if (!aguiState.hasEmittedRunStarted) { aguiState.hasEmittedRunStarted = true yield { type: EventType.RUN_STARTED, runId: aguiState.runId, threadId: aguiState.threadId, model: model || options.model, timestamp: Date.now(), parentRunId: options.parentRunId, } } const handleContentPart = ( contentPart: ContentPartAddedEventPart, ): AdapterYieldChunk => { if (contentPart.type === 'output_text') { accumulatedContent += contentPart.text return { type: EventType.TEXT_MESSAGE_CONTENT, messageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), delta: contentPart.text, content: accumulatedContent, } } if (contentPart.type === 'refusal') { const message = contentPart.refusal || 'Refused without explanation' return { type: EventType.RUN_ERROR, model: model || options.model, timestamp: Date.now(), message, code: 'refusal', error: { message, code: 'refusal' }, } } // Forward-compat `Unknown<"type">` arm. Surface the discriminator // value so unknown parts are debuggable instead of being misreported // as "Unknown refusal". const code = contentPart.type const message = `Unsupported response content_part type: ${code}` return { type: EventType.RUN_ERROR, model: model || options.model, timestamp: Date.now(), message, code, error: { message, code }, } } if (pendingRunError) { if ( chunk.type === 'response.completed' || chunk.type === 'response.failed' || chunk.type === 'response.incomplete' ) { const usage = buildResponsesUsage(chunk.response?.usage) yield { ...pendingRunError, ...(usage && { usage }) } runFinishedEmitted = true return } continue } // Capture model metadata from any of these events. if ( chunk.type === 'response.created' || chunk.type === 'response.in_progress' || chunk.type === 'response.incomplete' || chunk.type === 'response.failed' ) { if (chunk.response?.model) model = chunk.response.model } // response.created marks the start of a fresh run — safe to reset // the per-run accumulators here. if (chunk.type === 'response.created') { hasStreamedContentDeltas = false hasStreamedReasoningDeltas = false hasEmittedTextMessageStart = false reasoningMessageId = undefined hasClosedReasoning = false accumulatedContent = '' } // response.failed and response.incomplete are TERMINAL events. // A response cut off by a known limit is a finished-but-capped // answer, not a failure: end it like response.completed does for // finishReason 'length' / 'content_filter', and recover text that // arrived only on this event. Another reason, and response.failed, // stay RUN_ERROR. if ( chunk.type === 'response.failed' || chunk.type === 'response.incomplete' ) { const cappedFinishReason = chunk.type === 'response.incomplete' ? chunk.response?.incompleteDetails?.reason === 'max_output_tokens' ? ('length' as const) : chunk.response?.incompleteDetails?.reason === 'content_filter' ? ('content_filter' as const) : undefined : undefined yield* closeReasoning() if (cappedFinishReason) { const responseObj = chunk.response ?? {} const outputItems = Array.isArray(responseObj.output) ? responseObj.output : [] const outputItemText = outputItems .flatMap((item) => item.type === 'message' && Array.isArray(item.content) ? item.content : [], ) .filter((part) => part.type === 'output_text') .map((part) => part.text) .join('') const terminalText = typeof responseObj.outputText === 'string' && responseObj.outputText.length > 0 ? responseObj.outputText : outputItemText if (accumulatedContent.length === 0 && terminalText.length > 0) { if (!hasEmittedTextMessageStart) { hasEmittedTextMessageStart = true yield { type: EventType.TEXT_MESSAGE_START, messageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), role: 'assistant', } } accumulatedContent = terminalText hasStreamedContentDeltas = true yield { type: EventType.TEXT_MESSAGE_CONTENT, messageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), delta: terminalText, content: accumulatedContent, } } } if (hasEmittedTextMessageStart) { yield { type: EventType.TEXT_MESSAGE_END, messageId: aguiState.messageId, model, timestamp: Date.now(), } hasEmittedTextMessageStart = false } if (cappedFinishReason) { const usage = buildResponsesUsage(chunk.response?.usage) yield { type: EventType.RUN_FINISHED, ...(responseId && { responseId }), metadata: { tanstack: { ...(responseId && { responseId }), ...(reportedModel && { model: reportedModel }), }, }, runId: aguiState.runId, threadId: aguiState.threadId, model: model || options.model, timestamp: Date.now(), ...(usage && { usage }), finishReason: cappedFinishReason, } runFinishedEmitted = true return } const errorMessage = chunk.response?.error?.message || chunk.response?.incompleteDetails?.reason || (chunk.type === 'response.failed' ? 'Response failed' : 'Response ended incomplete') const errorCode = normalizeCode(chunk.response?.error?.code) ?? (chunk.response?.incompleteDetails ? 'incomplete' : undefined) ?? undefined const rawError = chunk.response?.error const usage = buildResponsesUsage(chunk.response?.usage) yield { type: EventType.RUN_ERROR, ...(usage && { usage }), model, timestamp: Date.now(), message: errorMessage, ...(errorCode !== undefined && { code: errorCode }), ...toRunErrorDetails({ type: chunk.response?.errorType }), ...(rawError != null && { rawEvent: rawError }), error: { message: errorMessage, ...(errorCode !== undefined && { code: errorCode }), }, } runFinishedEmitted = true return } // Handle output text deltas (token-by-token streaming) if (chunk.type === 'response.output_text.delta' && chunk.delta) { const textDelta = Array.isArray(chunk.delta) ? chunk.delta.join('') : typeof chunk.delta === 'string' ? chunk.delta : '' if (textDelta) { yield* closeReasoning() if (!hasEmittedTextMessageStart) { hasEmittedTextMessageStart = true yield { type: EventType.TEXT_MESSAGE_START, messageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), role: 'assistant', } } accumulatedContent += textDelta hasStreamedContentDeltas = true yield { type: EventType.TEXT_MESSAGE_CONTENT, messageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), delta: textDelta, content: accumulatedContent, } } } // Some Responses-compatible providers omit text deltas and expose the // completed text only on the dedicated done event. if ( chunk.type === 'response.output_text.done' && chunk.text && accumulatedContent.length === 0 ) { if (!hasEmittedTextMessageStart) { hasEmittedTextMessageStart = true yield { type: EventType.TEXT_MESSAGE_START, messageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), role: 'assistant', } } accumulatedContent = chunk.text hasStreamedContentDeltas = true yield { type: EventType.TEXT_MESSAGE_CONTENT, messageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), delta: chunk.text, content: accumulatedContent, } } // Handle reasoning deltas if (chunk.type === 'response.reasoning_text.delta' && chunk.delta) { const reasoningDelta = Array.isArray(chunk.delta) ? chunk.delta.join('') : typeof chunk.delta === 'string' ? chunk.delta : '' yield* emitReasoningDelta(reasoningDelta) } // Handle reasoning summary deltas if ( chunk.type === 'response.reasoning_summary_text.delta' && chunk.delta ) { const summaryDelta = typeof chunk.delta === 'string' ? chunk.delta : '' yield* emitReasoningDelta(summaryDelta) } // handle content_part added events for text, reasoning and refusals if (chunk.type === 'response.content_part.added' && chunk.part) { const contentPart = chunk.part // Some Responses-compatible providers announce an empty text part // and put the actual text only on response.completed. Do not count // that placeholder as streamed content; the completion backstop // below must remain eligible to recover the final text. if ( (contentPart.type === 'output_text' || contentPart.type === 'reasoning_text') && !contentPart.text ) { continue } if (contentPart.type === 'reasoning_text') { yield* emitReasoningDelta(contentPart.text) continue } if ( contentPart.type === 'output_text' && !hasEmittedTextMessageStart ) { yield* closeReasoning() hasEmittedTextMessageStart = true yield { type: EventType.TEXT_MESSAGE_START, messageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), role: 'assistant', } } if (contentPart.type === 'output_text') { hasStreamedContentDeltas = true } const partChunk = handleContentPart(contentPart) // A refusal is terminal. Hold it until the terminal event (see // pendingRunError). if (partChunk.type === 'RUN_ERROR') { pendingRunError = partChunk continue } yield partChunk } if (chunk.type === 'response.content_part.done' && chunk.part) { const contentPart = chunk.part // Skip emitting chunks for content parts that we've already streamed via deltas if (contentPart.type === 'output_text' && hasStreamedContentDeltas) { continue } if ( contentPart.type === 'reasoning_text' && hasStreamedReasoningDeltas ) { continue } // Upstreams that emit `content_part.done` without any preceding // deltas (or `content_part.added`) still need a START event before // CONTENT. if (contentPart.type === 'reasoning_text') { yield* emitReasoningDelta(contentPart.text) continue } if ( contentPart.type === 'output_text' && !hasEmittedTextMessageStart ) { yield* closeReasoning() hasEmittedTextMessageStart = true yield { type: EventType.TEXT_MESSAGE_START, messageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), role: 'assistant', } } const doneChunk = handleContentPart(contentPart) if (doneChunk.type === 'RUN_ERROR') { pendingRunError = doneChunk continue } yield doneChunk } // handle output_item.added to capture function call metadata (name) if (chunk.type === 'response.output_item.added') { const item = chunk.item if (item?.type === 'function_call' && item.id) { let metadata = toolCallMetadata.get(item.id) if (!metadata) { metadata = { callId: item.callId || item.id, index: chunk.outputIndex ?? 0, itemId: item.id, name: item.name || '', ...(item.namespace && { namespace: item.namespace }), started: false, } toolCallMetadata.set(item.id, metadata) } else { if (item.callId) metadata.callId = item.callId if (!metadata.name && item.name) metadata.name = item.name if (item.namespace) metadata.namespace = item.namespace } if (!metadata.started && metadata.name) { yield { type: EventType.TOOL_CALL_START, toolCallId: metadata.callId, toolCallName: metadata.name, parentMessageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), index: chunk.outputIndex ?? 0, metadata: { itemId: metadata.itemId, ...(metadata.namespace && { namespace: metadata.namespace }), } satisfies OpenRouterResponsesToolCallMetadata, } metadata.started = true } } } // Handle function call arguments delta (streaming). if ( chunk.type === 'response.function_call_arguments.delta' && chunk.delta ) { const itemId = chunk.itemId ?? '' const metadata = toolCallMetadata.get(itemId) if (!metadata?.started) { options.logger.errors( `${this.name}.processStreamChunks orphan function_call_arguments.delta`, { source: `${this.name}.processStreamChunks`, // No metadata yet, so the `call_id` is unknown here — only the // output item id the delta referenced. itemId, rawDelta: chunk.delta, }, ) continue } yield { type: EventType.TOOL_CALL_ARGS, toolCallId: metadata.callId, model: model || options.model, timestamp: Date.now(), delta: typeof chunk.delta === 'string' ? chunk.delta : '', } } if (chunk.type === 'response.function_call_arguments.done') { const itemId = chunk.itemId ?? '' const metadata = toolCallMetadata.get(itemId) if (!metadata?.started) { if (metadata) { metadata.pendingArguments = chunk.arguments } options.logger.errors( `${this.name}.processStreamChunks deferring function_call_arguments.done — TOOL_CALL_START not yet emitted (waiting for name)`, { source: `${this.name}.processStreamChunks`, ...(metadata && { toolCallId: metadata.callId }), itemId, rawArguments: chunk.arguments, }, ) continue } if (metadata.ended) continue const name = metadata.name || '' metadata.ended = true let parsedInput: unknown = {} if (chunk.arguments) { try { const parsed = JSON.parse(chunk.arguments) parsedInput = normalizeToolInput( name, parsed && typeof parsed === 'object' ? parsed : {}, ) } catch (parseError) { options.logger.errors( `${this.name}.processStreamChunks tool-args JSON parse failed`, { error: toRunErrorPayload( parseError, `tool ${name} (${metadata.callId}) returned malformed JSON arguments`, ), source: `${this.name}.processStreamChunks`, toolCallId: metadata.callId, itemId, toolName: name, rawArguments: chunk.arguments, }, ) parsedInput = undefined } } yield { type: EventType.TOOL_CALL_END, toolCallId: metadata.callId, toolCallName: name, model: model || options.model, timestamp: Date.now(), args: chunk.arguments, ...(parsedInput !== undefined && { input: parsedInput }), } } // `output_item.done` is the last point at which a function_call's // name is guaranteed to be on the wire. if (chunk.type === 'response.output_item.done') { const item = chunk.item if (item?.type === 'function_call' && item.id) { const metadata = toolCallMetadata.get(item.id) ?? { callId: item.callId || item.id, index: chunk.outputIndex ?? 0, itemId: item.id, name: item.name || '', ...(item.namespace && { namespace: item.namespace }), started: false, } if (!toolCallMetadata.has(item.id)) { toolCallMetadata.set(item.id, metadata) } else { if (item.callId) metadata.callId = item.callId if (!metadata.name && item.name) metadata.name = item.name if (item.namespace) metadata.namespace = item.namespace } if (!metadata.started && metadata.name) { yield { type: EventType.TOOL_CALL_START, toolCallId: metadata.callId, toolCallName: metadata.name, parentMessageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), index: metadata.index, metadata: { itemId: metadata.itemId, ...(metadata.namespace && { namespace: metadata.namespace }), } satisfies OpenRouterResponsesToolCallMetadata, } metadata.started = true } const rawArgs = typeof item.arguments === 'string' && item.arguments.length > 0 ? item.arguments : metadata.pendingArguments if (metadata.started && !metadata.ended && rawArgs !== undefined) { const name = metadata.name || '' let parsedInput: unknown = {} if (rawArgs) { try { const parsed = JSON.parse(rawArgs) parsedInput = normalizeToolInput( name, parsed && typeof parsed === 'object' ? parsed : {}, ) } catch (parseError) { options.logger.errors( `${this.name}.processStreamChunks tool-args JSON parse failed (output_item.done backfill)`, { error: toRunErrorPayload( parseError, `tool ${name} (${metadata.callId}) returned malformed JSON arguments`, ), source: `${this.name}.processStreamChunks`, toolCallId: metadata.callId, itemId: item.id, toolName: name, rawArguments: rawArgs, }, ) parsedInput = undefined } } yield { type: EventType.TOOL_CALL_END, toolCallId: metadata.callId, toolCallName: name, model: model || options.model, timestamp: Date.now(), args: rawArgs, ...(parsedInput !== undefined && { input: parsedInput }), } metadata.ended = true metadata.pendingArguments = undefined } } } if (chunk.type === 'response.completed') { const responseObj = chunk.response ?? {} const outputItems = Array.isArray(responseObj.output) ? responseObj.output : [] const outputItemText = outputItems .flatMap((item) => item.type === 'message' && Array.isArray(item.content) ? item.content : [], ) .filter((part) => part.type === 'output_text') .map((part) => part.text) .join('') const completedText = typeof responseObj.outputText === 'string' && responseObj.outputText.length > 0 ? responseObj.outputText : outputItemText if (accumulatedContent.length === 0 && completedText.length > 0) { if (!hasEmittedTextMessageStart) { hasEmittedTextMessageStart = true yield { type: EventType.TEXT_MESSAGE_START, messageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), role: 'assistant', } } accumulatedContent = completedText hasStreamedContentDeltas = true yield { type: EventType.TEXT_MESSAGE_CONTENT, messageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), delta: completedText, content: accumulatedContent, } } // Final backstop for function_call lifecycle. for (const item of outputItems) { if (item.type !== 'function_call' || !item.id) continue const metadata = toolCallMetadata.get(item.id) ?? { callId: item.callId || item.id, index: 0, itemId: item.id, name: item.name || '', ...(item.namespace && { namespace: item.namespace }), started: false, } if (!toolCallMetadata.has(item.id)) { toolCallMetadata.set(item.id, metadata) } else { if (item.callId) metadata.callId = item.callId if (!metadata.name && item.name) metadata.name = item.name if (item.namespace) metadata.namespace = item.namespace } if (!metadata.started && metadata.name) { yield { type: EventType.TOOL_CALL_START, toolCallId: metadata.callId, toolCallName: metadata.name, parentMessageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), index: metadata.index, metadata: { itemId: metadata.itemId, ...(metadata.namespace && { namespace: metadata.namespace }), } satisfies OpenRouterResponsesToolCallMetadata, } metadata.started = true } const rawArgs = typeof item.arguments === 'string' && item.arguments.length > 0 ? item.arguments : metadata.pendingArguments if (metadata.started && !metadata.ended) { const name = metadata.name || '' let parsedInput: unknown = {} if (rawArgs) { try { const parsed = JSON.parse(rawArgs) parsedInput = normalizeToolInput( name, parsed && typeof parsed === 'object' ? parsed : {}, ) } catch (parseError) { options.logger.errors( `${this.name}.processStreamChunks tool-args JSON parse failed (response.completed backfill)`, { error: toRunErrorPayload( parseError, `tool ${name} (${metadata.callId}) returned malformed JSON arguments`, ), source: `${this.name}.processStreamChunks`, toolCallId: metadata.callId, itemId: item.id, toolName: name, rawArguments: rawArgs, }, ) parsedInput = undefined } } yield { type: EventType.TOOL_CALL_END, toolCallId: metadata.callId, toolCallName: name, model: model || options.model, timestamp: Date.now(), args: rawArgs, ...(parsedInput !== undefined && { input: parsedInput }), } metadata.ended = true metadata.pendingArguments = undefined } } yield* closeReasoning() if (hasEmittedTextMessageStart) { yield { type: EventType.TEXT_MESSAGE_END, messageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), } hasEmittedTextMessageStart = false } const hasFunctionCalls = outputItems.some( (item) => item.type === 'function_call', ) const incompleteReason = responseObj.incompleteDetails?.reason const finishReason: | 'tool_calls' | 'length' | 'content_filter' | 'stop' = hasFunctionCalls ? 'tool_calls' : incompleteReason === 'max_output_tokens' ? 'length' : incompleteReason === 'content_filter' ? 'content_filter' : 'stop' const usage = buildResponsesUsage(responseObj.usage) yield { type: EventType.RUN_FINISHED, ...(responseId && { responseId }), metadata: { tanstack: { ...(responseId && { responseId }), ...(reportedModel && { model: reportedModel }), }, }, runId: aguiState.runId, threadId: aguiState.threadId, model: model || options.model, timestamp: Date.now(), ...(usage && { usage }), finishReason, } runFinishedEmitted = true // Terminal event: do not wait for the HTTP body to close (#1445). return } if (chunk.type === 'error') { const code = normalizeCode(chunk.code) yield { type: EventType.RUN_ERROR, model: model || options.model, timestamp: Date.now(), message: chunk.message ?? '', ...(code !== undefined && { code }), error: { message: chunk.message ?? '', ...(code !== undefined && { code }), }, } runFinishedEmitted = true return } } if (pendingRunError) { yield pendingRunError return } // The stream ended without a terminal event (e.g. a truncated // connection). Completion was never confirmed, so this is not a // successful stop (#1447). The partial text was already emitted. if (!runFinishedEmitted && aguiState.hasEmittedRunStarted) { yield* closeReasoning() if (hasEmittedTextMessageStart) { yield { type: EventType.TEXT_MESSAGE_END, messageId: aguiState.messageId, model: model || options.model, timestamp: Date.now(), } } const message = 'Response stream ended before response.completed' yield { type: EventType.RUN_ERROR, model: model || options.model, timestamp: Date.now(), message, code: 'incomplete-stream', error: { message, code: 'incomplete-stream' }, } } } catch (error: unknown) { const errorPayload = toOpenRouterRunErrorPayload( error, `${this.name}.processStreamChunks failed`, ) options.logger.errors(`${this.name}.processStreamChunks fatal`, { error: errorPayload, source: `${this.name}.processStreamChunks`, }) // A held refusal wins over a later stream error. A caller abort stays // an abort. if (pendingRunError && !isOpenRouterAbort(error)) { yield pendingRunError return } const rawEvent = toRunErrorRawEvent(error) yield { type: EventType.RUN_ERROR, model: options.model, timestamp: Date.now(), message: errorPayload.message, ...(errorPayload.code !== undefined && { code: errorPayload.code }), ...(rawEvent !== undefined && { rawEvent }), error: { message: errorPayload.message, ...(errorPayload.code !== undefined && { code: errorPayload.code }), }, } } } /** * Build an OpenRouter `ResponsesRequest` (camelCase) from `TextOptions`. */ protected mapOptionsToRequest( options: TextOptions, ): Omit { // Fail loud on webSearchTool() / webFetchTool() — v1 only routes function tools. if (options.tools) { for (const tool of options.tools) { if (isWebSearchTool(tool)) { throw new Error( `OpenRouterResponsesTextAdapter does not yet support webSearchTool(). ` + `Use the chat-completions adapter (openRouterText) for web search ` + `tools, or pass function tools only to this adapter.`, ) } if (isWebFetchTool(tool)) { throw new Error( `OpenRouterResponsesTextAdapter does not yet support webFetchTool(). ` + `Use the chat-completions adapter (openRouterText) for web fetch ` + `tools, or pass function tools only to this adapter.`, ) } } } // `variant` is OpenRouter metadata used only to build the `:variant` model // suffix — it is not part of the wire `ResponsesRequest`, so strip it out // of the spread body (mirrors the chat-completions adapter). const { variant, ...modelOptions } = (options.modelOptions ?? {}) as Partial & { variant?: string } const variantSuffix = variant ? `:${variant}` : '' const input = this.convertMessagesToInput(options.messages, options.model) // ResponsesFunctionTool already matches OpenRouter's // ResponsesRequestToolFunction shape: // `{ type:'function', name, parameters, description, strict }`. const tools: Array | undefined = options.tools ? options.tools.map((tool) => convertFunctionToolToResponsesFormat( tool, this.makeStructuredOutputCompatible.bind(this), ), ) : undefined // Attach text.format json_schema only when outputSchema is set and the // combined gate passes (every routed model is combined-capable, and not // JSON mode). const combinedOutputSchema: JSONSchema | undefined = options.outputSchema const combinedSchema = combinedOutputSchema && this.supportsCombinedToolsAndSchema(options.modelOptions) ? this.makeStructuredOutputCompatible( combinedOutputSchema, combinedOutputSchema.required, ) : undefined // `chat({ reasoning })`: the effort, a summary so the thinking text // streams back, and the token budget when the request sets one. // `ReasoningEffort` is an open enum, so a newer value still goes out. const resolved = resolveReasoning( options.reasoning, OPENROUTER_MODEL_REASONING[this.model], ) const effort = openRouterEffort(resolved) // `chat({ toolChoice })` is sent only when the request has tools. It goes // before the `modelOptions` spread, so a `toolChoice` there wins. const toolChoiceField = tools?.length && options.toolChoice !== undefined ? { toolChoice: toOpenRouterResponsesToolChoice(options.toolChoice) } : undefined const built: Pick< ResponsesRequest, | 'model' | 'input' | 'instructions' | 'metadata' | 'temperature' | 'topP' | 'maxOutputTokens' | 'tools' | 'toolChoice' | 'parallelToolCalls' | 'text' | 'reasoning' > = { ...toolChoiceField, ...modelOptions, model: options.model + variantSuffix, // Root `metadata` is observability-only and intentionally not forwarded: // the SDK validates wire `metadata` as `Record`, while // root metadata may carry arbitrarily structured values (#735). Callers // set wire metadata via `modelOptions.metadata`, which flows through // the spread. ...(() => { const prompts = normalizeSystemPrompts(options.systemPrompts) if (prompts.length === 0) return {} return { instructions: prompts.map((p) => p.content).join('\n') } })(), input, ...(tools && tools.length > 0 && { tools, }), ...(resolved && effort && { reasoning: { effort: effort as ReasoningEffort, ...(resolved.summary && resolved.level !== 'off' ? { summary: 'auto' as const } : {}), ...(resolved.budgetTokens !== undefined ? { maxTokens: resolved.budgetTokens } : {}), }, }), ...(combinedSchema && { // Merge onto any caller-supplied `text` (spread above via // `...modelOptions`) so sibling fields like `text.verbosity` survive; // only `text.format` is overridden by the combined-mode schema. text: { ...modelOptions.text, format: { type: 'json_schema' as const, name: 'structured_output', schema: combinedSchema, strict: true, }, }, }), } return built } /** * Combined mode is safe only when this model and every `modelOptions.models` * fallback are in `OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS`. JSON mode * is never combined: the schema goes in a system prompt on a separate * structured-output request, not on the tool-calling turns. */ supportsCombinedToolsAndSchema( modelOptions?: OpenRouterResponsesTextProviderOptions, ): boolean { return ( !openRouterUsesJsonObject(this.model, modelOptions) && openRouterSupportsCombinedToolsAndSchema(this.model, modelOptions) ) } /** `json_object` in JSON mode, else strict `json_schema` from `outputSchema`. */ private structuredTextFormat( jsonMode: boolean, outputSchema: JSONSchema, ): | { type: 'json_object' } | { type: 'json_schema' name: 'structured_output' schema: Record strict: true } { if (jsonMode) { return { type: 'json_object' } } return { type: 'json_schema', name: 'structured_output', schema: this.makeStructuredOutputCompatible( outputSchema, outputSchema.required, ), strict: true, } } /** * Convert a list of ModelMessage to OpenRouter's `InputsUnion` array form. * Emits camelCase shapes (`callId`, `imageUrl`, `videoUrl`, `fileData`, * `fileUrl`). */ protected convertMessagesToInput( messages: Array, targetModel: string = this.model, ): Array { // History from another model loses its signatures, and its tool IDs are // rewritten to `call|item` IDs this API accepts. Each call stays paired. const target = { provider: this.provider, api: this.api, model: targetModel, } const itemIds = new Map() const usedCallIds = new Set() const usedItemIds = new Set() const normalizedCompositeIds = new Set() for (const message of messages) { const source = message.metadata?.tanstack?.source const sameSource = !source || (source.provider === target.provider && source.api === target.api && source.model === target.model) for (const call of message.toolCalls ?? []) { const metadata = call.metadata const itemId = typeof metadata === 'object' && metadata !== null && 'itemId' in metadata && typeof metadata.itemId === 'string' ? metadata.itemId : call.id itemIds.set(call.id, itemId) if (sameSource) { usedCallIds.add(call.id) usedItemIds.add(itemId) } } } const normalizePart = (part: string) => part .replace(/[^a-zA-Z0-9_-]/g, '_') .slice(0, 64) .replace(/_+$/, '') messages = transformMessagesForReplay( messages, target, (id, { source, attempt }) => { const [call = '', compositeItem] = id.split('|') const item = compositeItem ?? itemIds.get(id) ?? call let retry = attempt let callId = normalizePart( retry ? `${call.slice(0, 48)}_${hashToolCallId(`${id}:${retry}`)}` : call, ) while (!callId || usedCallIds.has(callId)) { retry++ callId = normalizePart( `${call.slice(0, 48)}_${hashToolCallId(`${id}:${retry}`)}`, ) } usedCallIds.add(callId) let itemId = source && (source.provider !== target.provider || source.api !== target.api) ? `fc_${hashToolCallId(item)}` : normalizePart(item) if (!itemId.startsWith('fc_')) itemId = normalizePart(`fc_${itemId}`) if (itemId === 'fc') itemId = `fc_${hashToolCallId(item)}` let itemRetry = attempt while (usedItemIds.has(itemId)) { itemRetry++ itemId = `fc_${hashToolCallId(`${item}:${itemRetry}`)}` } usedItemIds.add(itemId) const composite = `${callId}|${itemId}` normalizedCompositeIds.add(composite) return composite }, ).messages const callIdFor = (id: string) => normalizedCompositeIds.has(id) ? (id.split('|')[0] ?? id) : id const result: Array = [] for (const message of messages) { if (message.role === 'tool') { const content = message.content // Images stay in the tool output as `input_image` parts. A model // without image input gets the text only. Other media is not sent. const hasImage = Array.isArray(content) && content.some((part) => part.type === 'image') const output = Array.isArray(content) && hasImage && (this.inputModalities?.includes('image') ?? true) ? content.flatMap( (part): Array => part.type === 'text' ? [{ type: 'input_text', text: part.content }] : part.type === 'image' ? [this.convertImagePartToInput(part)] : [], ) : this.extractTextContent(content) || (hasImage ? '(image omitted: this model has no image input)' : '') result.push({ type: 'function_call_output', callId: message.toolCallId ? callIdFor(message.toolCallId) : '', output, }) continue } if (message.role === 'assistant') { const firstItem = result.length const source = message.metadata?.tanstack?.source const foreign = source && (source.provider !== target.provider || source.api !== target.api || source.model !== target.model) if (message.toolCalls && message.toolCalls.length > 0) { for (const toolCall of message.toolCalls) { const argumentsString = typeof toolCall.function.arguments === 'string' ? toolCall.function.arguments : JSON.stringify(toolCall.function.arguments) const metadata = toolCall.metadata as | OpenRouterResponsesToolCallMetadata | undefined result.push({ type: 'function_call', callId: callIdFor(toolCall.id), id: normalizedCompositeIds.has(toolCall.id) ? (toolCall.id.split('|')[1] ?? toolCall.id) : metadata?.itemId || toolCall.id, name: toolCall.function.name, arguments: argumentsString, // Without its namespace, the API cannot find a tool of a // namespace tool group. ...(metadata?.namespace && { namespace: metadata.namespace }), }) } } if (message.content) { const contentStr = this.extractTextContent(message.content) if (contentStr) { result.push({ type: 'message', role: 'assistant', content: contentStr, }) } } // Another model's answer: plain text and calls in the order the // model sent them. if (foreign) { const emitted = result.splice(firstItem) const text = this.extractTextContent(message.content) const blocks = orderedAssistantBlocks(message) ?? [ ...(text ? [{ type: 'text' as const, text }] : []), ...(message.toolCalls ?? []).map((toolCall) => ({ type: 'tool-call' as const, toolCall, })), ] for (const block of blocks) { if (block.type === 'text') result.push({ type: 'message', role: 'assistant', content: block.text, }) else if (block.type === 'tool-call') { const callId = callIdFor(block.toolCall.id) const item = emitted.find( (item) => 'callId' in item && item.callId === callId, ) if (item) result.push(item) } } } continue } // user — fail loud on empty / unsupported content. const contentParts = this.normalizeContent(message.content) const inputContent: Array = [] for (const part of contentParts) { inputContent.push(this.convertContentPartToInput(part)) } if (inputContent.length === 0) { throw new Error( `User message for ${this.name} has no content parts. ` + `Empty user messages would produce a paid request with no input; ` + `provide at least one text/image/audio part or omit the message.`, ) } result.push({ type: 'message', role: 'user', content: inputContent, }) } return result } /** An image part as `input_image`, for user content and tool outputs. */ protected convertImagePartToInput(part: ImagePart) { const source = part.source if (isFileSource(source)) { throw unsupportedFileSourceError(this.name) } const meta = part.metadata as | { detail?: 'auto' | 'low' | 'high' } | undefined const value = source.value const imageUrl = source.type === 'data' && !value.startsWith('data:') ? `data:${source.mimeType || 'application/octet-stream'};base64,${value}` : value return { type: 'input_image' as const, imageUrl, detail: meta?.detail || 'auto', } } protected convertContentPartToInput( part: ContentPart, ): ResponsesInputContent { if (part.type === 'text') { return { type: 'input_text', text: part.content, } } // Narrow once so the branches below can only see url/data sources — a // `{ type: 'file' }` reference has no `value` to mis-map. A part without // a source (unknown/malformed type) is rejected the same way as the // default branch below. const source = (part as { source?: typeof part.source }).source if (source === undefined) { throw new Error( `Unsupported content part type for ${this.name}: ${(part as { type: string }).type}`, ) } if (isFileSource(source)) { throw unsupportedFileSourceError(this.name) } switch (part.type) { case 'image': return this.convertImagePartToInput(part) case 'audio': { if (source.type === 'url') { // OpenRouter's `input_audio` carries `{ data, format }` not a URL — // fall back to `input_file` for URLs so we don't silently drop the // audio reference. return { type: 'input_file', fileUrl: source.value, } } return { type: 'input_audio', inputAudio: { data: source.value, format: 'mp3' }, } } case 'video': return { type: 'input_video', videoUrl: source.value, } case 'document': { if (source.type === 'url') { return { type: 'input_file', fileUrl: source.value, } } const mime = source.mimeType || 'application/octet-stream' const data = source.value.startsWith('data:') ? source.value : `data:${mime};base64,${source.value}` return { type: 'input_file', fileData: data, } } default: throw new Error( `Unsupported content part type for ${this.name}: ${(part as { type: string }).type}`, ) } } protected normalizeContent( content: string | null | undefined | Array, ): Array { if (content === null || content === undefined) { return [] } if (typeof content === 'string') { return [{ type: 'text', content: content }] } return content } protected extractTextContent( content: string | null | undefined | Array, ): string { if (content === null || content === undefined) { return '' } if (typeof content === 'string') { return content } return content .filter((p) => p.type === 'text') .map((p) => p.content) .join('') } } /** * Normalised event shape we read off each OpenRouter SDK stream event after * camel-case translation. Models the loose superset of fields we consult * across all event-type branches; specific branches narrow further inline. */ interface NormalizedStreamEvent { type: string itemId?: string outputIndex?: number contentIndex?: number delta?: string | Array text?: string arguments?: string message?: string code?: unknown param?: string | null sequenceNumber?: number /** camelCased copy of the `response` payload from `response.{completed,failed,incomplete}` events. */ response?: Partial /** SDK discriminated union — narrow with `item.type === ''`. */ item?: OutputItems /** SDK discriminated union — narrow with `part.type === ''`. * Shared by `response.content_part.added` and `response.content_part.done` * (`ContentPartDoneEventPart` is structurally identical). */ part?: ContentPartAddedEventPart } /** * Translate the SDK's discriminated-union event into a uniform camelCase * shape our processor reads. * * The SDK's discriminated-union parser falls back to * `{ raw, type: 'UNKNOWN', isUnknown: true }` when an event's strict per- * variant schema rejects (missing optional-ish fields like `sequenceNumber`/ * `logprobs` that some upstreams — including aimock — omit). The `raw` * payload is the original wire-shape event in snake_case. We translate * snake_case keys to camelCase for those unknown events so the rest of the * processor reads a uniform shape. * * Known events already have camelCase fields. Their output items can still * be the SDK's `UNKNOWN` fallback, so those are read from the raw item. */ function normalizeStreamEvent(event: StreamEvents): NormalizedStreamEvent { const e = event as { isUnknown?: boolean raw?: unknown type?: string [k: string]: unknown } if (e.isUnknown && e.raw && typeof e.raw === 'object') { const raw = e.raw as Record // Translate the snake_case wire-shape fields we need into camelCase. The // adapter only consults the fields below; any others are passed through // verbatim so downstream extraction (e.g. for unknown event types) still // sees them. const out: Record = { ...raw } if ('item_id' in raw) out.itemId = raw.item_id if ('output_index' in raw) out.outputIndex = raw.output_index if ('content_index' in raw) out.contentIndex = raw.content_index if ('sequence_number' in raw) out.sequenceNumber = raw.sequence_number if ('summary_index' in raw) out.summaryIndex = raw.summary_index if ( 'response' in raw && raw['response'] && typeof raw['response'] === 'object' ) { out['response'] = camelCaseResponseShape( raw['response'] as Record, ) } if ('item' in raw && raw.item && typeof raw.item === 'object') { out.item = camelCaseOutputItem(raw.item as Record) } if ('part' in raw) out.part = raw.part out.type = typeof raw['type'] === 'string' ? raw['type'] : e.type || 'unknown' // oxlint-disable-next-line eslint-js/no-restricted-syntax -- NormalizedStreamEvent is a discriminated union built field-by-field from Record; TS can't narrow the variant from construction. return out as unknown as NormalizedStreamEvent } // The SDK falls back to the raw item for an output item that fails its // schema, inside a known event too. if (!e.item && !e.response) { // oxlint-disable-next-line eslint-js/no-restricted-syntax -- NormalizedStreamEvent is a discriminated union; the upstream `event` is a passthrough whose variant TS can't infer here. return event as unknown as NormalizedStreamEvent } const out: Record = { ...e } if (e.item && typeof e.item === 'object') { out.item = camelCaseOutputItem(e.item as Record) } if (e.response && typeof e.response === 'object') { out.response = camelCaseResponseShape(e.response as Record) } // oxlint-disable-next-line eslint-js/no-restricted-syntax -- NormalizedStreamEvent is a discriminated union; the upstream `event` is a passthrough whose variant TS can't infer here. return out as unknown as NormalizedStreamEvent } /** Translate snake_case keys in a `response` payload to camelCase for the * fields our terminal-event handlers read. Unknown keys passthrough. */ function camelCaseResponseShape( src: Record, ): Record { const out: Record = { ...src } if ('incomplete_details' in src) out.incompleteDetails = src.incomplete_details if ('error_type' in src) out.errorType = src.error_type if ('output_text' in src) out.outputText = src.output_text if ( 'input_tokens' in src || 'output_tokens' in src || 'total_tokens' in src ) { // never mutate src; rewrite usage in place if present. } if (src.usage && typeof src.usage === 'object') { const u = src.usage as Record out.usage = { ...u, ...('input_tokens' in u && { inputTokens: u.input_tokens }), ...('output_tokens' in u && { outputTokens: u.output_tokens }), ...('total_tokens' in u && { totalTokens: u.total_tokens }), ...(isRecord(u.input_tokens_details) && typeof u.input_tokens_details.cached_tokens === 'number' && { inputTokensDetails: { cachedTokens: u.input_tokens_details.cached_tokens, }, }), ...(isRecord(u.output_tokens_details) && typeof u.output_tokens_details.reasoning_tokens === 'number' && { outputTokensDetails: { reasoningTokens: u.output_tokens_details.reasoning_tokens, }, }), ...(typeof u.is_byok === 'boolean' && { isByok: u.is_byok }), } } if (Array.isArray(src.output)) { out.output = src.output.map((item) => item && typeof item === 'object' ? camelCaseOutputItem(item as Record) : item, ) } return out } /** Translate snake_case keys in an output item to camelCase. An item the * SDK could not parse (`{ raw, type: 'UNKNOWN', isUnknown: true }`) is read * from its raw wire shape. */ function camelCaseOutputItem( item: Record, ): Record { const src = item.isUnknown === true && isRecord(item.raw) ? item.raw : item const out: Record = { ...src } if ('call_id' in src) out.callId = src.call_id return out } /** * TanStack usage from a Responses `usage` object: tokens, cached and * reasoning tokens, BYOK, and OpenRouter cost. `undefined` when the * provider sent no token counts and no cost, so callers omit the field. * Cost-only usage still forwards with zeroed tokens. */ function buildResponsesUsage( usage: Partial | null | undefined, ): TokenUsage | undefined { if (usage == null) return undefined const cost = extractUsageCost(usage) if ( usage.inputTokens == null && usage.outputTokens == null && usage.totalTokens == null && cost.cost === undefined ) { return undefined } const cachedTokens = usage.inputTokensDetails?.cachedTokens const reasoningTokens = usage.outputTokensDetails?.reasoningTokens return { promptTokens: usage.inputTokens ?? 0, completionTokens: usage.outputTokens ?? 0, totalTokens: usage.totalTokens ?? 0, ...(cachedTokens ? { promptTokensDetails: { cachedTokens } } : {}), ...(reasoningTokens != null && { completionTokensDetails: { reasoningTokens }, }), ...(usage.isByok != null && { providerUsageDetails: { isByok: usage.isByok }, }), ...cost, } } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } /** Normalize an `error.code` to the string slot our RUN_ERROR event reads. */ function normalizeCode(code: unknown): string | undefined { if (typeof code === 'string') return code if (typeof code === 'number' && Number.isFinite(code)) return String(code) return undefined } export function createOpenRouterResponsesText< TModel extends OpenRouterResponsesTextModels, >( model: TModel, apiKey: string, config?: Omit, ): OpenRouterResponsesTextAdapter> { return new OpenRouterResponsesTextAdapter({ apiKey, ...config }, model) } export function openRouterResponsesText< TModel extends OpenRouterResponsesTextModels, >( model: TModel, config?: Omit, ): OpenRouterResponsesTextAdapter> { const apiKey = getOpenRouterApiKeyFromEnv() return createOpenRouterResponsesText(model, apiKey, config) }