@fleetagent/pi-ai 0.1.8 → 0.2.0
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/cli.d.ts.map +1 -1
- package/dist/cli.js +29 -24
- package/dist/cli.js.map +1 -1
- package/dist/env-api-keys.d.ts.map +1 -1
- package/dist/env-api-keys.js +1 -1
- package/dist/env-api-keys.js.map +1 -1
- package/dist/image-models.generated.d.ts +225 -0
- package/dist/image-models.generated.d.ts.map +1 -1
- package/dist/image-models.generated.js +227 -2
- package/dist/image-models.generated.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/models.d.ts +37 -2
- package/dist/models.d.ts.map +1 -1
- package/dist/models.generated.d.ts +6120 -2593
- package/dist/models.generated.d.ts.map +1 -1
- package/dist/models.generated.js +5347 -2110
- package/dist/models.generated.js.map +1 -1
- package/dist/models.js +259 -9
- package/dist/models.js.map +1 -1
- package/dist/oauth.d.ts +6 -1
- package/dist/oauth.d.ts.map +1 -1
- package/dist/oauth.js +4 -1
- package/dist/oauth.js.map +1 -1
- package/dist/providers/amazon-bedrock.d.ts +5 -4
- package/dist/providers/amazon-bedrock.d.ts.map +1 -1
- package/dist/providers/amazon-bedrock.js +303 -330
- package/dist/providers/amazon-bedrock.js.map +1 -1
- package/dist/providers/anthropic.d.ts +5 -4
- package/dist/providers/anthropic.d.ts.map +1 -1
- package/dist/providers/anthropic.js +492 -499
- package/dist/providers/anthropic.js.map +1 -1
- package/dist/providers/azure-openai-responses.d.ts +4 -2
- package/dist/providers/azure-openai-responses.d.ts.map +1 -1
- package/dist/providers/azure-openai-responses.js +52 -35
- package/dist/providers/azure-openai-responses.js.map +1 -1
- package/dist/providers/faux.d.ts +19 -22
- package/dist/providers/faux.d.ts.map +1 -1
- package/dist/providers/faux.js +106 -70
- package/dist/providers/faux.js.map +1 -1
- package/dist/providers/github-copilot-headers.d.ts +7 -4
- package/dist/providers/github-copilot-headers.d.ts.map +1 -1
- package/dist/providers/github-copilot-headers.js.map +1 -1
- package/dist/providers/google-shared.d.ts +24 -5
- package/dist/providers/google-shared.d.ts.map +1 -1
- package/dist/providers/google-shared.js +139 -140
- package/dist/providers/google-shared.js.map +1 -1
- package/dist/providers/google-vertex.d.ts +3 -7
- package/dist/providers/google-vertex.d.ts.map +1 -1
- package/dist/providers/google-vertex.js +216 -219
- package/dist/providers/google-vertex.js.map +1 -1
- package/dist/providers/google.d.ts +4 -7
- package/dist/providers/google.d.ts.map +1 -1
- package/dist/providers/google.js +214 -218
- package/dist/providers/google.js.map +1 -1
- package/dist/providers/images/openrouter.d.ts.map +1 -1
- package/dist/providers/images/openrouter.js +37 -27
- package/dist/providers/images/openrouter.js.map +1 -1
- package/dist/providers/mistral.d.ts +7 -6
- package/dist/providers/mistral.d.ts.map +1 -1
- package/dist/providers/mistral.js +287 -265
- package/dist/providers/mistral.js.map +1 -1
- package/dist/providers/openai-codex-responses.d.ts +8 -5
- package/dist/providers/openai-codex-responses.d.ts.map +1 -1
- package/dist/providers/openai-codex-responses.js +493 -391
- package/dist/providers/openai-codex-responses.js.map +1 -1
- package/dist/providers/openai-completions.d.ts +7 -10
- package/dist/providers/openai-completions.d.ts.map +1 -1
- package/dist/providers/openai-completions.js +670 -664
- package/dist/providers/openai-completions.js.map +1 -1
- package/dist/providers/openai-responses-shared.d.ts +5 -4
- package/dist/providers/openai-responses-shared.d.ts.map +1 -1
- package/dist/providers/openai-responses-shared.js +390 -360
- package/dist/providers/openai-responses-shared.js.map +1 -1
- package/dist/providers/openai-responses.d.ts +5 -5
- package/dist/providers/openai-responses.d.ts.map +1 -1
- package/dist/providers/openai-responses.js +134 -109
- package/dist/providers/openai-responses.js.map +1 -1
- package/dist/providers/simple-options.d.ts +4 -2
- package/dist/providers/simple-options.d.ts.map +1 -1
- package/dist/providers/simple-options.js.map +1 -1
- package/dist/providers/transform-messages.d.ts.map +1 -1
- package/dist/providers/transform-messages.js +112 -137
- package/dist/providers/transform-messages.js.map +1 -1
- package/dist/stream.d.ts +0 -1
- package/dist/stream.d.ts.map +1 -1
- package/dist/stream.js +0 -1
- package/dist/stream.js.map +1 -1
- package/dist/types.d.ts +91 -63
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/error-body.d.ts.map +1 -1
- package/dist/utils/error-body.js +15 -4
- package/dist/utils/error-body.js.map +1 -1
- package/dist/utils/estimate.d.ts +4 -0
- package/dist/utils/estimate.d.ts.map +1 -1
- package/dist/utils/estimate.js +3 -1
- package/dist/utils/estimate.js.map +1 -1
- package/dist/utils/headers.d.ts +3 -0
- package/dist/utils/headers.d.ts.map +1 -1
- package/dist/utils/headers.js +21 -0
- package/dist/utils/headers.js.map +1 -1
- package/dist/utils/json-parse.d.ts.map +1 -1
- package/dist/utils/json-parse.js +17 -19
- package/dist/utils/json-parse.js.map +1 -1
- package/dist/utils/oauth/anthropic.d.ts +4 -11
- package/dist/utils/oauth/anthropic.d.ts.map +1 -1
- package/dist/utils/oauth/anthropic.js +100 -117
- package/dist/utils/oauth/anthropic.js.map +1 -1
- package/dist/utils/oauth/device-code.d.ts.map +1 -1
- package/dist/utils/oauth/device-code.js +51 -38
- package/dist/utils/oauth/device-code.js.map +1 -1
- package/dist/utils/oauth/github-copilot.d.ts +6 -9
- package/dist/utils/oauth/github-copilot.d.ts.map +1 -1
- package/dist/utils/oauth/github-copilot.js +47 -42
- package/dist/utils/oauth/github-copilot.js.map +1 -1
- package/dist/utils/oauth/index.d.ts +8 -17
- package/dist/utils/oauth/index.d.ts.map +1 -1
- package/dist/utils/oauth/index.js +27 -23
- package/dist/utils/oauth/index.js.map +1 -1
- package/dist/utils/oauth/oauth-page.d.ts.map +1 -1
- package/dist/utils/oauth/oauth-page.js.map +1 -1
- package/dist/utils/oauth/openai-codex.d.ts +7 -12
- package/dist/utils/oauth/openai-codex.d.ts.map +1 -1
- package/dist/utils/oauth/openai-codex.js +72 -89
- package/dist/utils/oauth/openai-codex.js.map +1 -1
- package/dist/utils/oauth/pkce.d.ts +5 -4
- package/dist/utils/oauth/pkce.d.ts.map +1 -1
- package/dist/utils/oauth/pkce.js.map +1 -1
- package/dist/utils/oauth/types.d.ts +7 -2
- package/dist/utils/oauth/types.d.ts.map +1 -1
- package/dist/utils/oauth/types.js.map +1 -1
- package/dist/utils/provider-retry.d.ts +16 -0
- package/dist/utils/provider-retry.d.ts.map +1 -0
- package/dist/utils/provider-retry.js +94 -0
- package/dist/utils/provider-retry.js.map +1 -0
- package/dist/utils/retry.d.ts +14 -0
- package/dist/utils/retry.d.ts.map +1 -1
- package/dist/utils/retry.js +84 -0
- package/dist/utils/retry.js.map +1 -1
- package/dist/utils/typebox-helpers.d.ts +5 -4
- package/dist/utils/typebox-helpers.d.ts.map +1 -1
- package/dist/utils/typebox-helpers.js.map +1 -1
- package/dist/utils/validation.d.ts.map +1 -1
- package/dist/utils/validation.js +102 -99
- package/dist/utils/validation.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-responses-shared.js","sourceRoot":"","sources":["../../src/providers/openai-responses-shared.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAgB7C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAE5D,gFAAgF;AAChF,YAAY;AACZ,gFAAgF;AAEhF,SAAS,qBAAqB,CAAC,EAAU,EAAE,KAAgC,EAAU;IACpF,MAAM,OAAO,GAAoB,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IAC9C,IAAI,KAAK;QAAE,OAAO,CAAC,KAAK,GAAG,KAAK,C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aAAa,CAAC;QACnB,KAAK,QAAQ;YACZ,OAAO,MAAM,CAAC;QACf,SAAS,CAAC;YACT,MAAM,WAAW,GAAU,MAAM,CAAC;YAClC,MAAM,IAAI,KAAK,CAAC,0BAA0B,WAAW,EAAE,CAAC,CAAC;QAC1D,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import type OpenAI from \"openai\";\nimport type {\n\tTool as OpenAITool,\n\tResponseCreateParamsStreaming,\n\tResponseFunctionCallOutputItemList,\n\tResponseInput,\n\tResponseInputContent,\n\tResponseInputImage,\n\tResponseInputText,\n\tResponseOutputItem,\n\tResponseOutputMessage,\n\tResponseReasoningItem,\n\tResponseStreamEvent,\n} from \"openai/resources/responses/responses.js\";\nimport { calculateCost } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tImageContent,\n\tModel,\n\tStopReason,\n\tTextContent,\n\tTextSignatureV1,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tUsage,\n} from \"../types.ts\";\nimport type { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { parseStreamingJson } from \"../utils/json-parse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\nfunction encodeTextSignatureV1(id: string, phase?: TextSignatureV1[\"phase\"]): string {\n\tconst payload: TextSignatureV1 = { v: 1, id };\n\tif (phase) payload.phase = phase;\n\treturn JSON.stringify(payload);\n}\n\nfunction parseTextSignature(\n\tsignature: string | undefined,\n): { id: string; phase?: TextSignatureV1[\"phase\"] } | undefined {\n\tif (!signature) return undefined;\n\tif (signature.startsWith(\"{\")) {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(signature) as Partial<TextSignatureV1>;\n\t\t\tif (parsed.v === 1 && typeof parsed.id === \"string\") {\n\t\t\t\tif (parsed.phase === \"commentary\" || parsed.phase === \"final_answer\") {\n\t\t\t\t\treturn { id: parsed.id, phase: parsed.phase };\n\t\t\t\t}\n\t\t\t\treturn { id: parsed.id };\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to legacy plain-string handling.\n\t\t}\n\t}\n\treturn { id: signature };\n}\n\nexport interface OpenAIResponsesStreamOptions {\n\tserviceTier?: ResponseCreateParamsStreaming[\"service_tier\"];\n\tresolveServiceTier?: (\n\t\tresponseServiceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t\trequestServiceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t) => ResponseCreateParamsStreaming[\"service_tier\"] | undefined;\n\tapplyServiceTierPricing?: (\n\t\tusage: Usage,\n\t\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t) => void;\n}\n\nexport interface ConvertResponsesMessagesOptions {\n\tincludeSystemPrompt?: boolean;\n}\n\nexport interface ConvertResponsesToolsOptions {\n\tstrict?: boolean | null;\n}\n\n// =============================================================================\n// Message conversion\n// =============================================================================\n\nexport function convertResponsesMessages<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\tallowedToolCallProviders: ReadonlySet<string>,\n\toptions?: ConvertResponsesMessagesOptions,\n): ResponseInput {\n\tconst messages: ResponseInput = [];\n\n\tconst normalizeIdPart = (part: string): string => {\n\t\tconst sanitized = part.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\t\tconst normalized = sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;\n\t\treturn normalized.replace(/_+$/, \"\");\n\t};\n\n\tconst buildForeignResponsesItemId = (itemId: string): string => {\n\t\tconst normalized = `fc_${shortHash(itemId)}`;\n\t\treturn normalized.length > 64 ? normalized.slice(0, 64) : normalized;\n\t};\n\n\tconst normalizeToolCallId = (id: string, _targetModel: Model<TApi>, source: AssistantMessage): string => {\n\t\tif (!allowedToolCallProviders.has(model.provider)) return normalizeIdPart(id);\n\t\tif (!id.includes(\"|\")) return normalizeIdPart(id);\n\t\tconst [callId, itemId] = id.split(\"|\");\n\t\tconst normalizedCallId = normalizeIdPart(callId);\n\t\tconst isForeignToolCall = source.provider !== model.provider || source.api !== model.api;\n\t\tlet normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);\n\t\t// OpenAI Responses API requires item id to start with \"fc\"\n\t\tif (!normalizedItemId.startsWith(\"fc_\")) {\n\t\t\tnormalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);\n\t\t}\n\t\treturn `${normalizedCallId}|${normalizedItemId}`;\n\t};\n\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);\n\n\tconst includeSystemPrompt = options?.includeSystemPrompt ?? true;\n\tif (includeSystemPrompt && context.systemPrompt) {\n\t\tconst role = model.reasoning ? \"developer\" : \"system\";\n\t\tmessages.push({\n\t\t\trole,\n\t\t\tcontent: sanitizeSurrogates(context.systemPrompt),\n\t\t});\n\t}\n\n\tlet msgIndex = 0;\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: [{ type: \"input_text\", text: sanitizeSurrogates(msg.content) }],\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst content: ResponseInputContent[] = msg.content.map((item): ResponseInputContent => {\n\t\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(item.text),\n\t\t\t\t\t\t} satisfies ResponseInputText;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\timage_url: `data:${item.mimeType};base64,${item.data}`,\n\t\t\t\t\t} satisfies ResponseInputImage;\n\t\t\t\t});\n\t\t\t\tif (content.length === 0) continue;\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst output: ResponseInput = [];\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isDifferentModel =\n\t\t\t\tassistantMsg.model !== model.id &&\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api;\n\t\t\tlet textBlockIndex = 0;\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (block.thinkingSignature) {\n\t\t\t\t\t\tconst reasoningItem = JSON.parse(block.thinkingSignature) as ResponseReasoningItem;\n\t\t\t\t\t\toutput.push(reasoningItem);\n\t\t\t\t\t}\n\t\t\t\t} else if (block.type === \"text\") {\n\t\t\t\t\tconst textBlock = block as TextContent;\n\t\t\t\t\tconst parsedSignature = parseTextSignature(textBlock.textSignature);\n\t\t\t\t\tconst fallbackMessageId =\n\t\t\t\t\t\ttextBlockIndex === 0 ? `msg_pi_${msgIndex}` : `msg_pi_${msgIndex}_${textBlockIndex}`;\n\t\t\t\t\ttextBlockIndex++;\n\t\t\t\t\t// OpenAI requires id to be max 64 characters\n\t\t\t\t\tlet msgId = parsedSignature?.id;\n\t\t\t\t\tif (!msgId) {\n\t\t\t\t\t\tmsgId = fallbackMessageId;\n\t\t\t\t\t} else if (msgId.length > 64) {\n\t\t\t\t\t\tmsgId = `msg_${shortHash(msgId)}`;\n\t\t\t\t\t}\n\t\t\t\t\toutput.push({\n\t\t\t\t\t\ttype: \"message\",\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent: [{ type: \"output_text\", text: sanitizeSurrogates(textBlock.text), annotations: [] }],\n\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\tid: msgId,\n\t\t\t\t\t\tphase: parsedSignature?.phase,\n\t\t\t\t\t} satisfies ResponseOutputMessage);\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tconst [callId, itemIdRaw] = toolCall.id.split(\"|\");\n\t\t\t\t\tlet itemId: string | undefined = itemIdRaw;\n\n\t\t\t\t\t// For different-model messages, set id to undefined to avoid pairing validation.\n\t\t\t\t\t// OpenAI tracks which fc_xxx IDs were paired with rs_xxx reasoning items.\n\t\t\t\t\t// By omitting the id, we avoid triggering that validation (like cross-provider does).\n\t\t\t\t\tif (isDifferentModel && itemId?.startsWith(\"fc_\")) {\n\t\t\t\t\t\titemId = undefined;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push({\n\t\t\t\t\t\ttype: \"function_call\",\n\t\t\t\t\t\tid: itemId,\n\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\targuments: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (output.length === 0) continue;\n\t\t\tmessages.push(...output);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst textResult = msg.content\n\t\t\t\t.filter((c): c is TextContent => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\\n\");\n\t\t\tconst hasImages = msg.content.some((c): c is ImageContent => c.type === \"image\");\n\t\t\tconst hasText = textResult.length > 0;\n\t\t\tconst [callId] = msg.toolCallId.split(\"|\");\n\n\t\t\tlet output: string | ResponseFunctionCallOutputItemList;\n\t\t\tif (hasImages && model.input.includes(\"image\")) {\n\t\t\t\tconst contentParts: ResponseFunctionCallOutputItemList = [];\n\n\t\t\t\tif (hasText) {\n\t\t\t\t\tcontentParts.push({\n\t\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\t\ttext: sanitizeSurrogates(textResult),\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tfor (const block of msg.content) {\n\t\t\t\t\tif (block.type === \"image\") {\n\t\t\t\t\t\tcontentParts.push({\n\t\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\t\timage_url: `data:${block.mimeType};base64,${block.data}`,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\toutput = contentParts;\n\t\t\t} else {\n\t\t\t\toutput = sanitizeSurrogates(hasText ? textResult : \"(see attached image)\");\n\t\t\t}\n\n\t\t\tmessages.push({\n\t\t\t\ttype: \"function_call_output\",\n\t\t\t\tcall_id: callId,\n\t\t\t\toutput,\n\t\t\t});\n\t\t}\n\t\tmsgIndex++;\n\t}\n\n\treturn messages;\n}\n\n// =============================================================================\n// Tool conversion\n// =============================================================================\n\nexport function convertResponsesTools(tools: Tool[], options?: ConvertResponsesToolsOptions): OpenAITool[] {\n\tconst strict = options?.strict === undefined ? false : options.strict;\n\treturn tools.map((tool) => ({\n\t\ttype: \"function\",\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: tool.parameters as any, // TypeBox already generates JSON Schema\n\t\tstrict,\n\t}));\n}\n\n// =============================================================================\n// Stream processing\n// =============================================================================\ntype StreamingToolCall = ToolCall & { partialJson: string };\n\ntype ResponsesOutputSlot =\n\t| { type: \"thinking\"; block: ThinkingContent; contentIndex: number }\n\t| { type: \"text\"; block: TextContent; contentIndex: number }\n\t| { type: \"toolCall\"; block: StreamingToolCall; contentIndex: number };\n\nexport async function processResponsesStream<TApi extends Api>(\n\topenaiStream: AsyncIterable<ResponseStreamEvent>,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<TApi>,\n\toptions?: OpenAIResponsesStreamOptions,\n): Promise<void> {\n\tconst outputSlots = new Map<number, ResponsesOutputSlot>();\n\tconst getSlot = <TType extends ResponsesOutputSlot[\"type\"]>(\n\t\toutputIndex: number,\n\t\ttype: TType,\n\t): Extract<ResponsesOutputSlot, { type: TType }> | undefined => {\n\t\tconst slot = outputSlots.get(outputIndex);\n\t\treturn slot?.type === type ? (slot as Extract<ResponsesOutputSlot, { type: TType }>) : undefined;\n\t};\n\tconst createSlot = (outputIndex: number, item: ResponseOutputItem): ResponsesOutputSlot | undefined => {\n\t\tif (item.type === \"reasoning\") {\n\t\t\tconst block: ThinkingContent = { type: \"thinking\", thinking: \"\" };\n\t\t\toutput.content.push(block);\n\t\t\tconst slot = {\n\t\t\t\ttype: \"thinking\",\n\t\t\t\tblock,\n\t\t\t\tcontentIndex: output.content.length - 1,\n\t\t\t} satisfies ResponsesOutputSlot;\n\t\t\toutputSlots.set(outputIndex, slot);\n\t\t\tstream.push({ type: \"thinking_start\", contentIndex: slot.contentIndex, partial: output });\n\t\t\treturn slot;\n\t\t}\n\t\tif (item.type === \"message\") {\n\t\t\tconst block: TextContent = { type: \"text\", text: \"\" };\n\t\t\toutput.content.push(block);\n\t\t\tconst slot = { type: \"text\", block, contentIndex: output.content.length - 1 } satisfies ResponsesOutputSlot;\n\t\t\toutputSlots.set(outputIndex, slot);\n\t\t\tstream.push({ type: \"text_start\", contentIndex: slot.contentIndex, partial: output });\n\t\t\treturn slot;\n\t\t}\n\t\tif (item.type === \"function_call\") {\n\t\t\tconst block: StreamingToolCall = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: `${item.call_id}|${item.id}`,\n\t\t\t\tname: item.name,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: item.arguments || \"\",\n\t\t\t};\n\t\t\toutput.content.push(block);\n\t\t\tconst slot = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tblock,\n\t\t\t\tcontentIndex: output.content.length - 1,\n\t\t\t} satisfies ResponsesOutputSlot;\n\t\t\toutputSlots.set(outputIndex, slot);\n\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: slot.contentIndex, partial: output });\n\t\t\treturn slot;\n\t\t}\n\t\treturn undefined;\n\t};\n\tconst getOrCreateSlot = (outputIndex: number, item: ResponseOutputItem): ResponsesOutputSlot | undefined => {\n\t\treturn outputSlots.get(outputIndex) ?? createSlot(outputIndex, item);\n\t};\n\n\tfor await (const event of openaiStream) {\n\t\tif (event.type === \"response.created\") {\n\t\t\toutput.responseId = event.response.id;\n\t\t} else if (event.type === \"response.output_item.added\") {\n\t\t\tcreateSlot(event.output_index, event.item);\n\t\t} else if (event.type === \"response.reasoning_summary_text.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"thinking\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.thinking += event.delta;\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: event.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.reasoning_summary_part.done\") {\n\t\t\tconst slot = getSlot(event.output_index, \"thinking\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.thinking += \"\\n\\n\";\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: \"\\n\\n\",\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.reasoning_text.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"thinking\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.thinking += event.delta;\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: event.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.output_text.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"text\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.text += event.delta;\n\t\t\tstream.push({\n\t\t\t\ttype: \"text_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: event.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.refusal.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"text\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.text += event.delta;\n\t\t\tstream.push({\n\t\t\t\ttype: \"text_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: event.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.function_call_arguments.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"toolCall\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.partialJson += event.delta;\n\t\t\tslot.block.arguments = parseStreamingJson(slot.block.partialJson);\n\t\t\tstream.push({\n\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: event.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.function_call_arguments.done\") {\n\t\t\tconst slot = getSlot(event.output_index, \"toolCall\");\n\t\t\tif (!slot) continue;\n\t\t\tconst previousPartialJson = slot.block.partialJson;\n\t\t\tslot.block.partialJson = event.arguments;\n\t\t\tslot.block.arguments = parseStreamingJson(slot.block.partialJson);\n\n\t\t\tif (event.arguments.startsWith(previousPartialJson)) {\n\t\t\t\tconst delta = event.arguments.slice(previousPartialJson.length);\n\t\t\t\tif (delta.length > 0) {\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.output_item.done\") {\n\t\t\tconst item = event.item;\n\t\t\tconst slot = getOrCreateSlot(event.output_index, item);\n\n\t\t\tif (item.type === \"reasoning\" && slot?.type === \"thinking\") {\n\t\t\t\tconst summaryText = item.summary?.map((summary) => summary.text).join(\"\\n\\n\") || \"\";\n\t\t\t\tconst contentText = item.content?.map((content) => content.text).join(\"\\n\\n\") || \"\";\n\t\t\t\tslot.block.thinking = summaryText || contentText || slot.block.thinking;\n\t\t\t\tslot.block.thinkingSignature = JSON.stringify(item);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\tcontent: slot.block.thinking,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t} else if (item.type === \"message\" && slot?.type === \"text\") {\n\t\t\t\tslot.block.text =\n\t\t\t\t\titem.content\n\t\t\t\t\t\t?.map((content) => (content.type === \"output_text\" ? content.text : content.refusal))\n\t\t\t\t\t\t.join(\"\") || \"\";\n\t\t\t\tslot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\tcontent: slot.block.text,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t} else if (item.type === \"function_call\" && slot?.type === \"toolCall\") {\n\t\t\t\tslot.block.arguments = parseStreamingJson(item.arguments || slot.block.partialJson || \"{}\");\n\t\t\t\tdelete (slot.block as { partialJson?: string }).partialJson;\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\ttoolCall: slot.block,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t}\n\t\t} else if (event.type === \"response.completed\") {\n\t\t\tconst response = event.response;\n\t\t\tif (response?.id) {\n\t\t\t\toutput.responseId = response.id;\n\t\t\t}\n\t\t\tif (response?.usage) {\n\t\t\t\tconst cachedTokens = response.usage.input_tokens_details?.cached_tokens || 0;\n\t\t\t\toutput.usage = {\n\t\t\t\t\tinput: (response.usage.input_tokens || 0) - cachedTokens,\n\t\t\t\t\toutput: response.usage.output_tokens || 0,\n\t\t\t\t\tcacheRead: cachedTokens,\n\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\ttotalTokens: response.usage.total_tokens || 0,\n\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t};\n\t\t\t}\n\t\t\tcalculateCost(model, output.usage);\n\t\t\tif (options?.applyServiceTierPricing) {\n\t\t\t\tconst serviceTier = options.resolveServiceTier\n\t\t\t\t\t? options.resolveServiceTier(response?.service_tier, options.serviceTier)\n\t\t\t\t\t: (response?.service_tier ?? options.serviceTier);\n\t\t\t\toptions.applyServiceTierPricing(output.usage, serviceTier);\n\t\t\t}\n\t\t\toutput.stopReason = mapStopReason(response?.status);\n\t\t\tif (output.content.some((block) => block.type === \"toolCall\") && output.stopReason === \"stop\") {\n\t\t\t\toutput.stopReason = \"toolUse\";\n\t\t\t}\n\t\t} else if (event.type === \"error\") {\n\t\t\tthrow new Error(`Error Code ${event.code}: ${event.message}` || \"Unknown error\");\n\t\t} else if (event.type === \"response.failed\") {\n\t\t\tconst error = event.response?.error;\n\t\t\tconst details = event.response?.incomplete_details;\n\t\t\tconst message = error\n\t\t\t\t? `${error.code || \"unknown\"}: ${error.message || \"no message\"}`\n\t\t\t\t: details?.reason\n\t\t\t\t\t? `incomplete: ${details.reason}`\n\t\t\t\t\t: \"Unknown error (no error details in response)\";\n\t\t\tthrow new Error(message);\n\t\t}\n\t}\n}\n\nfunction mapStopReason(status: OpenAI.Responses.ResponseStatus | undefined): StopReason {\n\tif (!status) return \"stop\";\n\tswitch (status) {\n\t\tcase \"completed\":\n\t\t\treturn \"stop\";\n\t\tcase \"incomplete\":\n\t\t\treturn \"length\";\n\t\tcase \"failed\":\n\t\tcase \"cancelled\":\n\t\t\treturn \"error\";\n\t\t// These two are wonky ...\n\t\tcase \"in_progress\":\n\t\tcase \"queued\":\n\t\t\treturn \"stop\";\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = status;\n\t\t\tthrow new Error(`Unhandled stop reason: ${_exhaustive}`);\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"openai-responses-shared.js","sourceRoot":"","sources":["../../src/providers/openai-responses-shared.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAmB7C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAW5D,SAAS,qBAAqB,CAAC,EAAU,EAAE,KAA0B,EAAU;IAC9E,MAAM,OAAO,GAAoB,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IAC9C,IAAI,KAAK;QAAE,OAAO,CAAC,KAAK,GAAG,KAAK,CAAC;IACjC,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;AAAA,CAC/B;AAED,SAAS,kBAAkB,CAAC,SAA6B,EAAmC;IAC3F,IAAI,CAAC,SAAS;QAAE,OAAO,SAAS,CAAC;IACjC,IAAI,SAAS,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;QAC/B,IAAI,CAAC;YACJ,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAA6B,CAAC;YACjE,IAAI,MAAM,CAAC,CAAC,KAAK,CAAC,IAAI,OAAO,MAAM,CAAC,EAAE,KAAK,QAAQ,EAAE,CAAC;gBACrD,IAAI,MAAM,CAAC,KAAK,KAAK,YAAY,IAAI,MAAM,CAAC,KAAK,KAAK,cAAc,EAAE,CAAC;oBACtE,OAAO,EAAE,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC;gBAC/C,CAAC;gBACD,OAAO,EAAE,EAAE,EAAE,MAA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ACtB;IAChB,MAAM,KAAK,GAA+B;QACzC,MAAM;QACN,MAAM;QACN,KAAK;QACL,OAAO;QACP,wBAAwB,EAAE,KAAK;QAC/B,WAAW,EAAE,IAAI,GAAG,EAAE;QACtB,mBAAmB,EAAE,IAAI,GAAG,EAAE;KAC9B,CAAC;IACF,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,YAAY;QAAE,2BAA2B,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAClF,IAAI,CAAC,KAAK,CAAC,wBAAwB,EAAE,CAAC;QACrC,MAAM,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAC;IACnF,CAAC;AAAA,CACD;AAED,SAAS,aAAa,CAAC,MAAmD,EAAc;IACvF,IAAI,CAAC,MAAM;QAAE,OAAO,MAAM,CAAC;IAC3B,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,WAAW;YACf,OAAO,MAAM,CAAC;QACf,KAAK,YAAY;YAChB,OAAO,QAAQ,CAAC;QACjB,KAAK,QAAQ,CAAC;QACd,KAAK,WAAW;YACf,OAAO,OAAO,CAAC;QAChB,0BAA0B;QAC1B,KAAK,aAAa,CAAC;QACnB,KAAK,QAAQ;YACZ,OAAO,MAAM,CAAC;QACf,SAAS,CAAC;YACT,MAAM,WAAW,GAAU,MAAM,CAAC;YAClC,MAAM,IAAI,KAAK,CAAC,0BAA0B,WAAW,EAAE,CAAC,CAAC;QAC1D,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import type OpenAI from \"openai\";\nimport type {\n\tResponse as OpenAIResponse,\n\tTool as OpenAITool,\n\tResponseFunctionCallOutputItemList,\n\tResponseFunctionToolCall,\n\tResponseInput,\n\tResponseInputContent,\n\tResponseInputImage,\n\tResponseInputText,\n\tResponseOutputItem,\n\tResponseOutputMessage,\n\tResponseReasoningItem,\n\tResponseStreamEvent,\n} from \"openai/resources/responses/responses.js\";\nimport { calculateCost } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tImageContent,\n\tModel,\n\tStopReason,\n\tTextContent,\n\tTextSignaturePhase,\n\tTextSignatureV1,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n\tUsage,\n\tUserMessage,\n} from \"../types.ts\";\nimport type { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { parseStreamingJson } from \"../utils/json-parse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\ninterface ParsedTextSignature {\n\tid: string;\n\tphase?: TextSignaturePhase;\n}\n\nfunction encodeTextSignatureV1(id: string, phase?: TextSignaturePhase): string {\n\tconst payload: TextSignatureV1 = { v: 1, id };\n\tif (phase) payload.phase = phase;\n\treturn JSON.stringify(payload);\n}\n\nfunction parseTextSignature(signature: string | undefined): ParsedTextSignature | undefined {\n\tif (!signature) return undefined;\n\tif (signature.startsWith(\"{\")) {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(signature) as Partial<TextSignatureV1>;\n\t\t\tif (parsed.v === 1 && typeof parsed.id === \"string\") {\n\t\t\t\tif (parsed.phase === \"commentary\" || parsed.phase === \"final_answer\") {\n\t\t\t\t\treturn { id: parsed.id, phase: parsed.phase };\n\t\t\t\t}\n\t\t\t\treturn { id: parsed.id };\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to legacy plain-string handling.\n\t\t}\n\t}\n\treturn { id: signature };\n}\n\nexport type OpenAIResponseServiceTier = \"auto\" | \"default\" | \"flex\" | \"scale\" | \"priority\" | null;\n\nexport interface OpenAIResponsesStreamOptions {\n\tserviceTier?: OpenAIResponseServiceTier;\n\tresolveServiceTier?: (\n\t\tresponseServiceTier: OpenAIResponseServiceTier | undefined,\n\t\trequestServiceTier: OpenAIResponseServiceTier | undefined,\n\t) => OpenAIResponseServiceTier | undefined;\n\tapplyServiceTierPricing?: (usage: Usage, serviceTier: OpenAIResponseServiceTier | undefined) => void;\n}\n\nexport interface ConvertResponsesMessagesOptions {\n\tincludeSystemPrompt?: boolean;\n}\n\nexport interface ConvertResponsesToolsOptions {\n\tstrict?: boolean | null;\n}\n\n// =============================================================================\n// Message conversion\n// =============================================================================\n\nfunction normalizeResponsesIdPart(part: string): string {\n\tconst sanitized = part.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\tconst normalized = sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;\n\treturn normalized.replace(/_+$/, \"\");\n}\n\nfunction buildForeignResponsesItemId(itemId: string): string {\n\tconst normalized = `fc_${shortHash(itemId)}`;\n\treturn normalized.length > 64 ? normalized.slice(0, 64) : normalized;\n}\n\nfunction normalizeResponsesToolCallId<TApi extends Api>(\n\tid: string,\n\tmodel: Model<TApi>,\n\tsource: AssistantMessage,\n\tallowedToolCallProviders: ReadonlySet<string>,\n): string {\n\tif (!allowedToolCallProviders.has(model.provider)) return normalizeResponsesIdPart(id);\n\tif (!id.includes(\"|\")) return normalizeResponsesIdPart(id);\n\tconst [callId, itemId] = id.split(\"|\");\n\tconst normalizedCallId = normalizeResponsesIdPart(callId);\n\tconst isForeignToolCall = source.provider !== model.provider || source.api !== model.api;\n\tlet normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeResponsesIdPart(itemId);\n\t// OpenAI Responses API requires item IDs to start with \"fc\".\n\tif (!normalizedItemId.startsWith(\"fc_\")) normalizedItemId = normalizeResponsesIdPart(`fc_${normalizedItemId}`);\n\treturn `${normalizedCallId}|${normalizedItemId}`;\n}\n\nfunction convertResponsesUserMessage(message: UserMessage): ResponseInput {\n\tif (typeof message.content === \"string\") {\n\t\treturn [\n\t\t\t{\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: [{ type: \"input_text\", text: sanitizeSurrogates(message.content) }],\n\t\t\t},\n\t\t];\n\t}\n\tconst content: ResponseInputContent[] = message.content.map((item): ResponseInputContent => {\n\t\tif (item.type === \"text\") {\n\t\t\treturn {\n\t\t\t\ttype: \"input_text\",\n\t\t\t\ttext: sanitizeSurrogates(item.text),\n\t\t\t} satisfies ResponseInputText;\n\t\t}\n\t\treturn {\n\t\t\ttype: \"input_image\",\n\t\t\tdetail: \"auto\",\n\t\t\timage_url: `data:${item.mimeType};base64,${item.data}`,\n\t\t} satisfies ResponseInputImage;\n\t});\n\treturn content.length === 0 ? [] : [{ role: \"user\", content }];\n}\n\nfunction resolveResponsesMessageId(\n\ttextBlock: TextContent,\n\tmessageIndex: number,\n\ttextBlockIndex: number,\n): ParsedTextSignature {\n\tconst parsedSignature = parseTextSignature(textBlock.textSignature);\n\tconst fallbackId = textBlockIndex === 0 ? `msg_pi_${messageIndex}` : `msg_pi_${messageIndex}_${textBlockIndex}`;\n\tif (!parsedSignature?.id) return { id: fallbackId };\n\treturn {\n\t\t...parsedSignature,\n\t\tid: parsedSignature.id.length > 64 ? `msg_${shortHash(parsedSignature.id)}` : parsedSignature.id,\n\t};\n}\n\nfunction convertResponsesTextBlock(\n\tblock: TextContent,\n\tmessageIndex: number,\n\ttextBlockIndex: number,\n): ResponseOutputMessage {\n\tconst signature = resolveResponsesMessageId(block, messageIndex, textBlockIndex);\n\treturn {\n\t\ttype: \"message\",\n\t\trole: \"assistant\",\n\t\tcontent: [{ type: \"output_text\", text: sanitizeSurrogates(block.text), annotations: [] }],\n\t\tstatus: \"completed\",\n\t\tid: signature.id,\n\t\tphase: signature.phase,\n\t};\n}\n\nfunction convertResponsesToolCall(block: ToolCall, isDifferentModel: boolean): ResponseFunctionToolCall {\n\tconst [callId, rawItemId] = block.id.split(\"|\");\n\tconst itemId = isDifferentModel && rawItemId?.startsWith(\"fc_\") ? undefined : rawItemId;\n\treturn {\n\t\ttype: \"function_call\",\n\t\tid: itemId,\n\t\tcall_id: callId,\n\t\tname: block.name,\n\t\targuments: JSON.stringify(block.arguments),\n\t};\n}\n\nfunction convertResponsesAssistantMessage<TApi extends Api>(\n\tmessage: AssistantMessage,\n\tmodel: Model<TApi>,\n\tmessageIndex: number,\n): ResponseInput {\n\tconst output: ResponseInput = [];\n\tconst isDifferentModel =\n\t\tmessage.model !== model.id && message.provider === model.provider && message.api === model.api;\n\tlet textBlockIndex = 0;\n\tfor (const block of message.content) {\n\t\tif (block.type === \"thinking\") {\n\t\t\tif (block.thinkingSignature) output.push(JSON.parse(block.thinkingSignature) as ResponseReasoningItem);\n\t\t\tcontinue;\n\t\t}\n\t\tif (block.type === \"text\") {\n\t\t\toutput.push(convertResponsesTextBlock(block, messageIndex, textBlockIndex));\n\t\t\ttextBlockIndex++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (block.type === \"toolCall\") output.push(convertResponsesToolCall(block, isDifferentModel));\n\t}\n\treturn output;\n}\n\nfunction buildResponsesToolOutput(\n\tmessage: ToolResultMessage,\n\tsupportsImages: boolean,\n): string | ResponseFunctionCallOutputItemList {\n\tconst textResult = message.content\n\t\t.filter((content): content is TextContent => content.type === \"text\")\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\");\n\tconst hasImages = message.content.some((content): content is ImageContent => content.type === \"image\");\n\tconst hasText = textResult.length > 0;\n\tif (!hasImages || !supportsImages) {\n\t\treturn sanitizeSurrogates(hasText ? textResult : hasImages ? \"(see attached image)\" : \"(no tool output)\");\n\t}\n\tconst contentParts: ResponseFunctionCallOutputItemList = [];\n\tif (hasText) contentParts.push({ type: \"input_text\", text: sanitizeSurrogates(textResult) });\n\tfor (const block of message.content) {\n\t\tif (block.type !== \"image\") continue;\n\t\tcontentParts.push({\n\t\t\ttype: \"input_image\",\n\t\t\tdetail: \"auto\",\n\t\t\timage_url: `data:${block.mimeType};base64,${block.data}`,\n\t\t});\n\t}\n\treturn contentParts;\n}\n\nfunction convertResponsesToolResult<TApi extends Api>(message: ToolResultMessage, model: Model<TApi>): ResponseInput {\n\tconst [callId] = message.toolCallId.split(\"|\");\n\treturn [\n\t\t{\n\t\t\ttype: \"function_call_output\",\n\t\t\tcall_id: callId,\n\t\t\toutput: buildResponsesToolOutput(message, model.input.includes(\"image\")),\n\t\t},\n\t];\n}\n\nexport function convertResponsesMessages<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\tallowedToolCallProviders: ReadonlySet<string>,\n\toptions?: ConvertResponsesMessagesOptions,\n): ResponseInput {\n\tconst messages: ResponseInput = [];\n\tconst normalizeToolCallId = (id: string, _targetModel: Model<TApi>, source: AssistantMessage): string =>\n\t\tnormalizeResponsesToolCallId(id, model, source, allowedToolCallProviders);\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);\n\tif ((options?.includeSystemPrompt ?? true) && context.systemPrompt) {\n\t\tmessages.push({\n\t\t\trole: model.reasoning ? \"developer\" : \"system\",\n\t\t\tcontent: sanitizeSurrogates(context.systemPrompt),\n\t\t});\n\t}\n\tlet messageIndex = 0;\n\tfor (const message of transformedMessages) {\n\t\tlet converted: ResponseInput;\n\t\tif (message.role === \"user\") converted = convertResponsesUserMessage(message);\n\t\telse if (message.role === \"assistant\") converted = convertResponsesAssistantMessage(message, model, messageIndex);\n\t\telse converted = convertResponsesToolResult(message, model);\n\t\tif (converted.length === 0) continue;\n\t\tmessages.push(...converted);\n\t\tmessageIndex++;\n\t}\n\treturn messages;\n}\n\n// =============================================================================\n// Tool conversion\n// =============================================================================\n\nexport function convertResponsesTools(tools: Tool[], options?: ConvertResponsesToolsOptions): OpenAITool[] {\n\tconst strict = options?.strict === undefined ? false : options.strict;\n\treturn tools.map((tool) => ({\n\t\ttype: \"function\",\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: tool.parameters as any, // TypeBox already generates JSON Schema\n\t\tstrict,\n\t}));\n}\n\n// =============================================================================\n// Stream processing\n// =============================================================================\ntype StreamingToolCall = ToolCall & { partialJson: string };\n\ninterface ResponsesThinkingOutputSlot {\n\ttype: \"thinking\";\n\tblock: ThinkingContent;\n\tcontentIndex: number;\n}\n\ninterface ResponsesTextOutputSlot {\n\ttype: \"text\";\n\tblock: TextContent;\n\tcontentIndex: number;\n}\n\ninterface ResponsesToolCallOutputSlot {\n\ttype: \"toolCall\";\n\tblock: StreamingToolCall;\n\tcontentIndex: number;\n}\n\ntype ResponsesOutputSlot = ResponsesThinkingOutputSlot | ResponsesTextOutputSlot | ResponsesToolCallOutputSlot;\n\ninterface ResponsesStreamState<TApi extends Api> {\n\toutput: AssistantMessage;\n\tstream: AssistantMessageEventStream;\n\tmodel: Model<TApi>;\n\toptions: OpenAIResponsesStreamOptions | undefined;\n\tsawTerminalResponseEvent: boolean;\n\toutputSlots: Map<number, ResponsesOutputSlot>;\n\treasoningBlocksById: Map<string, ThinkingContent>;\n}\n\nfunction applyResponsesMessagePhaseStopReason(output: AssistantMessage, item: ResponseOutputItem): void {\n\tif (item.type === \"message\" && item.phase === \"final_answer\") output.stopReason = \"stop\";\n}\n\nfunction getResponsesThinkingSlot<TApi extends Api>(\n\tstate: ResponsesStreamState<TApi>,\n\toutputIndex: number,\n): ResponsesThinkingOutputSlot | undefined {\n\tconst slot = state.outputSlots.get(outputIndex);\n\treturn slot?.type === \"thinking\" ? slot : undefined;\n}\n\nfunction getResponsesTextSlot<TApi extends Api>(\n\tstate: ResponsesStreamState<TApi>,\n\toutputIndex: number,\n): ResponsesTextOutputSlot | undefined {\n\tconst slot = state.outputSlots.get(outputIndex);\n\treturn slot?.type === \"text\" ? slot : undefined;\n}\n\nfunction getResponsesToolCallSlot<TApi extends Api>(\n\tstate: ResponsesStreamState<TApi>,\n\toutputIndex: number,\n): ResponsesToolCallOutputSlot | undefined {\n\tconst slot = state.outputSlots.get(outputIndex);\n\treturn slot?.type === \"toolCall\" ? slot : undefined;\n}\n\nfunction createResponsesOutputSlot<TApi extends Api>(\n\tstate: ResponsesStreamState<TApi>,\n\toutputIndex: number,\n\titem: ResponseOutputItem,\n): ResponsesOutputSlot | undefined {\n\tswitch (item.type) {\n\t\tcase \"reasoning\": {\n\t\t\tconst block: ThinkingContent = { type: \"thinking\", thinking: \"\" };\n\t\t\tstate.output.content.push(block);\n\t\t\tconst slot: ResponsesThinkingOutputSlot = {\n\t\t\t\ttype: \"thinking\",\n\t\t\t\tblock,\n\t\t\t\tcontentIndex: state.output.content.length - 1,\n\t\t\t};\n\t\t\tstate.outputSlots.set(outputIndex, slot);\n\t\t\tstate.stream.push({ type: \"thinking_start\", contentIndex: slot.contentIndex, partial: state.output });\n\t\t\treturn slot;\n\t\t}\n\t\tcase \"message\": {\n\t\t\tapplyResponsesMessagePhaseStopReason(state.output, item);\n\t\t\tconst block: TextContent = { type: \"text\", text: \"\" };\n\t\t\tstate.output.content.push(block);\n\t\t\tconst slot: ResponsesTextOutputSlot = {\n\t\t\t\ttype: \"text\",\n\t\t\t\tblock,\n\t\t\t\tcontentIndex: state.output.content.length - 1,\n\t\t\t};\n\t\t\tstate.outputSlots.set(outputIndex, slot);\n\t\t\tstate.stream.push({ type: \"text_start\", contentIndex: slot.contentIndex, partial: state.output });\n\t\t\treturn slot;\n\t\t}\n\t\tcase \"function_call\": {\n\t\t\tconst block: StreamingToolCall = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: `${item.call_id}|${item.id}`,\n\t\t\t\tname: item.name,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: item.arguments || \"\",\n\t\t\t};\n\t\t\tstate.output.content.push(block);\n\t\t\tconst slot: ResponsesToolCallOutputSlot = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tblock,\n\t\t\t\tcontentIndex: state.output.content.length - 1,\n\t\t\t};\n\t\t\tstate.outputSlots.set(outputIndex, slot);\n\t\t\tstate.stream.push({ type: \"toolcall_start\", contentIndex: slot.contentIndex, partial: state.output });\n\t\t\treturn slot;\n\t\t}\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction getOrCreateResponsesOutputSlot<TApi extends Api>(\n\tstate: ResponsesStreamState<TApi>,\n\toutputIndex: number,\n\titem: ResponseOutputItem,\n): ResponsesOutputSlot | undefined {\n\treturn state.outputSlots.get(outputIndex) ?? createResponsesOutputSlot(state, outputIndex, item);\n}\n\nfunction backfillResponsesReasoningSignatures<TApi extends Api>(\n\tstate: ResponsesStreamState<TApi>,\n\tresponseOutput: ResponseOutputItem[],\n): void {\n\tfor (const item of responseOutput) {\n\t\tif (item.type !== \"reasoning\" || !item.encrypted_content) continue;\n\t\tconst block = state.reasoningBlocksById.get(item.id);\n\t\tif (!block?.thinkingSignature) continue;\n\t\tconst storedItem = JSON.parse(block.thinkingSignature) as ResponseReasoningItem;\n\t\tif (storedItem.encrypted_content) continue;\n\t\tblock.thinkingSignature = JSON.stringify({ ...storedItem, encrypted_content: item.encrypted_content });\n\t}\n}\n\nfunction finalizeResponsesResponse<TApi extends Api>(\n\tstate: ResponsesStreamState<TApi>,\n\tresponse: OpenAIResponse,\n): void {\n\tstate.sawTerminalResponseEvent = true;\n\tbackfillResponsesReasoningSignatures(state, response.output ?? []);\n\tif (response.id) state.output.responseId = response.id;\n\tif (response.usage) {\n\t\tconst inputDetails = response.usage.input_tokens_details as\n\t\t\t| { cached_tokens?: number; cache_write_tokens?: number }\n\t\t\t| undefined;\n\t\tconst cachedTokens = inputDetails?.cached_tokens || 0;\n\t\tconst cacheWriteTokens = inputDetails?.cache_write_tokens || 0;\n\t\tstate.output.usage = {\n\t\t\tinput: Math.max(0, (response.usage.input_tokens || 0) - cachedTokens - cacheWriteTokens),\n\t\t\toutput: response.usage.output_tokens || 0,\n\t\t\tcacheRead: cachedTokens,\n\t\t\tcacheWrite: cacheWriteTokens,\n\t\t\treasoning: response.usage.output_tokens_details?.reasoning_tokens || 0,\n\t\t\ttotalTokens: response.usage.total_tokens || 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t};\n\t}\n\tcalculateCost(state.model, state.output.usage);\n\tif (state.options?.applyServiceTierPricing) {\n\t\tconst serviceTier = state.options.resolveServiceTier\n\t\t\t? state.options.resolveServiceTier(response.service_tier, state.options.serviceTier)\n\t\t\t: (response.service_tier ?? state.options.serviceTier);\n\t\tstate.options.applyServiceTierPricing(state.output.usage, serviceTier);\n\t}\n\tstate.output.rawStopReason = response.status;\n\tstate.output.stopReason = mapStopReason(response.status);\n\tif (state.output.content.some((block) => block.type === \"toolCall\") && state.output.stopReason === \"stop\") {\n\t\tstate.output.stopReason = \"toolUse\";\n\t}\n}\n\nfunction appendResponsesThinkingDelta<TApi extends Api>(\n\tstate: ResponsesStreamState<TApi>,\n\toutputIndex: number,\n\tdelta: string,\n): void {\n\tconst slot = getResponsesThinkingSlot(state, outputIndex);\n\tif (!slot) return;\n\tslot.block.thinking += delta;\n\tstate.stream.push({\n\t\ttype: \"thinking_delta\",\n\t\tcontentIndex: slot.contentIndex,\n\t\tdelta,\n\t\tpartial: state.output,\n\t});\n}\n\nfunction appendResponsesTextDelta<TApi extends Api>(\n\tstate: ResponsesStreamState<TApi>,\n\toutputIndex: number,\n\tdelta: string,\n): void {\n\tconst slot = getResponsesTextSlot(state, outputIndex);\n\tif (!slot) return;\n\tslot.block.text += delta;\n\tstate.stream.push({ type: \"text_delta\", contentIndex: slot.contentIndex, delta, partial: state.output });\n}\n\nfunction appendResponsesToolCallDelta<TApi extends Api>(\n\tstate: ResponsesStreamState<TApi>,\n\toutputIndex: number,\n\tdelta: string,\n): void {\n\tconst slot = getResponsesToolCallSlot(state, outputIndex);\n\tif (!slot) return;\n\tslot.block.partialJson += delta;\n\tslot.block.arguments = parseStreamingJson(slot.block.partialJson);\n\tstate.stream.push({ type: \"toolcall_delta\", contentIndex: slot.contentIndex, delta, partial: state.output });\n}\n\nfunction completeResponsesToolCallArguments<TApi extends Api>(\n\tstate: ResponsesStreamState<TApi>,\n\toutputIndex: number,\n\targumentsJson: string,\n): void {\n\tconst slot = getResponsesToolCallSlot(state, outputIndex);\n\tif (!slot) return;\n\tconst previousPartialJson = slot.block.partialJson;\n\tslot.block.partialJson = argumentsJson;\n\tslot.block.arguments = parseStreamingJson(slot.block.partialJson);\n\tif (!argumentsJson.startsWith(previousPartialJson)) return;\n\tconst delta = argumentsJson.slice(previousPartialJson.length);\n\tif (delta.length > 0) {\n\t\tstate.stream.push({ type: \"toolcall_delta\", contentIndex: slot.contentIndex, delta, partial: state.output });\n\t}\n}\n\nfunction finalizeResponsesOutputItem<TApi extends Api>(\n\tstate: ResponsesStreamState<TApi>,\n\toutputIndex: number,\n\titem: ResponseOutputItem,\n): void {\n\tapplyResponsesMessagePhaseStopReason(state.output, item);\n\tconst slot = getOrCreateResponsesOutputSlot(state, outputIndex, item);\n\tswitch (item.type) {\n\t\tcase \"reasoning\":\n\t\t\tif (slot?.type !== \"thinking\") return;\n\t\t\tslot.block.thinking =\n\t\t\t\titem.summary?.map((summary) => summary.text).join(\"\\n\\n\") ||\n\t\t\t\titem.content?.map((content) => content.text).join(\"\\n\\n\") ||\n\t\t\t\tslot.block.thinking;\n\t\t\tslot.block.thinkingSignature = JSON.stringify(item);\n\t\t\tstate.reasoningBlocksById.set(item.id, slot.block);\n\t\t\tstate.stream.push({\n\t\t\t\ttype: \"thinking_end\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tcontent: slot.block.thinking,\n\t\t\t\tpartial: state.output,\n\t\t\t});\n\t\t\tstate.outputSlots.delete(outputIndex);\n\t\t\treturn;\n\t\tcase \"message\":\n\t\t\tif (slot?.type !== \"text\") return;\n\t\t\tslot.block.text =\n\t\t\t\titem.content\n\t\t\t\t\t?.map((content) => (content.type === \"output_text\" ? content.text : content.refusal))\n\t\t\t\t\t.join(\"\") || \"\";\n\t\t\tslot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);\n\t\t\tstate.stream.push({\n\t\t\t\ttype: \"text_end\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tcontent: slot.block.text,\n\t\t\t\tpartial: state.output,\n\t\t\t});\n\t\t\tstate.outputSlots.delete(outputIndex);\n\t\t\treturn;\n\t\tcase \"function_call\":\n\t\t\tif (slot?.type !== \"toolCall\") return;\n\t\t\tslot.block.arguments = parseStreamingJson(item.arguments || slot.block.partialJson || \"{}\");\n\t\t\tdelete (slot.block as { partialJson?: string }).partialJson;\n\t\t\tstate.stream.push({\n\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\ttoolCall: slot.block,\n\t\t\t\tpartial: state.output,\n\t\t\t});\n\t\t\tstate.outputSlots.delete(outputIndex);\n\t\t\treturn;\n\t\tdefault:\n\t\t\treturn;\n\t}\n}\n\nfunction failResponsesStream<TApi extends Api>(\n\tstate: ResponsesStreamState<TApi>,\n\tresponse: OpenAIResponse | undefined,\n): never {\n\tstate.sawTerminalResponseEvent = true;\n\tstate.output.rawStopReason = response?.status;\n\tconst error = response?.error;\n\tconst details = response?.incomplete_details;\n\tconst message = error\n\t\t? `${error.code || \"unknown\"}: ${error.message || \"no message\"}`\n\t\t: details?.reason\n\t\t\t? `incomplete: ${details.reason}`\n\t\t\t: \"Unknown error (no error details in response)\";\n\tthrow new Error(message);\n}\n\nfunction processResponsesStreamEvent<TApi extends Api>(\n\tstate: ResponsesStreamState<TApi>,\n\tevent: ResponseStreamEvent,\n): void {\n\tswitch (event.type) {\n\t\tcase \"response.created\":\n\t\t\tstate.output.responseId = event.response.id;\n\t\t\tbreak;\n\t\tcase \"response.output_item.added\":\n\t\t\tcreateResponsesOutputSlot(state, event.output_index, event.item);\n\t\t\tbreak;\n\t\tcase \"response.reasoning_summary_text.delta\":\n\t\tcase \"response.reasoning_text.delta\":\n\t\t\tappendResponsesThinkingDelta(state, event.output_index, event.delta);\n\t\t\tbreak;\n\t\tcase \"response.reasoning_summary_part.done\":\n\t\t\tappendResponsesThinkingDelta(state, event.output_index, \"\\n\\n\");\n\t\t\tbreak;\n\t\tcase \"response.output_text.delta\":\n\t\tcase \"response.refusal.delta\":\n\t\t\tappendResponsesTextDelta(state, event.output_index, event.delta);\n\t\t\tbreak;\n\t\tcase \"response.function_call_arguments.delta\":\n\t\t\tappendResponsesToolCallDelta(state, event.output_index, event.delta);\n\t\t\tbreak;\n\t\tcase \"response.function_call_arguments.done\":\n\t\t\tcompleteResponsesToolCallArguments(state, event.output_index, event.arguments);\n\t\t\tbreak;\n\t\tcase \"response.output_item.done\":\n\t\t\tfinalizeResponsesOutputItem(state, event.output_index, event.item);\n\t\t\tbreak;\n\t\tcase \"response.completed\":\n\t\tcase \"response.incomplete\":\n\t\t\tfinalizeResponsesResponse(state, event.response);\n\t\t\tbreak;\n\t\tcase \"error\":\n\t\t\tthrow new Error(`Error Code ${event.code}: ${event.message}` || \"Unknown error\");\n\t\tcase \"response.failed\":\n\t\t\tfailResponsesStream(state, event.response);\n\t}\n}\n\nexport async function processResponsesStream<TApi extends Api>(\n\topenaiStream: AsyncIterable<ResponseStreamEvent>,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<TApi>,\n\toptions?: OpenAIResponsesStreamOptions,\n): Promise<void> {\n\tconst state: ResponsesStreamState<TApi> = {\n\t\toutput,\n\t\tstream,\n\t\tmodel,\n\t\toptions,\n\t\tsawTerminalResponseEvent: false,\n\t\toutputSlots: new Map(),\n\t\treasoningBlocksById: new Map(),\n\t};\n\tfor await (const event of openaiStream) processResponsesStreamEvent(state, event);\n\tif (!state.sawTerminalResponseEvent) {\n\t\tthrow new Error(\"OpenAI Responses stream ended before a terminal response event\");\n\t}\n}\n\nfunction mapStopReason(status: OpenAI.Responses.ResponseStatus | undefined): StopReason {\n\tif (!status) return \"stop\";\n\tswitch (status) {\n\t\tcase \"completed\":\n\t\t\treturn \"stop\";\n\t\tcase \"incomplete\":\n\t\t\treturn \"length\";\n\t\tcase \"failed\":\n\t\tcase \"cancelled\":\n\t\t\treturn \"error\";\n\t\t// These two are wonky ...\n\t\tcase \"in_progress\":\n\t\tcase \"queued\":\n\t\t\treturn \"stop\";\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = status;\n\t\t\tthrow new Error(`Unhandled stop reason: ${_exhaustive}`);\n\t\t}\n\t}\n}\n"]}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import type { ResponseCreateParamsStreaming } from "openai/resources/responses/responses.js";
|
|
2
2
|
import type { SimpleStreamOptions, StreamFunction, StreamOptions } from "../types.ts";
|
|
3
|
+
export type OpenAIResponsesReasoningEffort = "minimal" | "low" | "medium" | "high" | "xhigh";
|
|
4
|
+
export type OpenAIResponsesReasoningSummary = "auto" | "detailed" | "concise";
|
|
3
5
|
export interface OpenAIResponsesOptions extends StreamOptions {
|
|
4
|
-
reasoningEffort?:
|
|
5
|
-
reasoningSummary?:
|
|
6
|
+
reasoningEffort?: OpenAIResponsesReasoningEffort;
|
|
7
|
+
reasoningSummary?: OpenAIResponsesReasoningSummary | null;
|
|
6
8
|
serviceTier?: ResponseCreateParamsStreaming["service_tier"];
|
|
7
9
|
}
|
|
8
|
-
/**
|
|
9
|
-
* Generate function for OpenAI Responses API
|
|
10
|
-
*/
|
|
10
|
+
/** Generate a stream using the OpenAI Responses API. */
|
|
11
11
|
export declare const streamOpenAIResponses: StreamFunction<"openai-responses", OpenAIResponsesOptions>;
|
|
12
12
|
export declare const streamSimpleOpenAIResponses: StreamFunction<"openai-responses", SimpleStreamOptions>;
|
|
13
13
|
//# sourceMappingURL=openai-responses.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-responses.d.ts","sourceRoot":"","sources":["../../src/providers/openai-responses.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,CAAC;AAG7F,OAAO,KAAK,EAOX,mBAAmB,EACnB,cAAc,EACd,aAAa,EAEb,MAAM,aAAa,CAAC;AA+CrB,MAAM,WAAW,sBAAuB,SAAQ,aAAa;IAC5D,eAAe,CAAC,EAAE,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;IAClE,gBAAgB,CAAC,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,GAAG,IAAI,CAAC;IAC1D,WAAW,CAAC,EAAE,6BAA6B,CAAC,cAAc,CAAC,CAAC;CAC5D;AAED;;GAEG;AACH,eAAO,MAAM,qBAAqB,EAAE,cAAc,CAAC,kBAAkB,EAAE,sBAAsB,CA4E5F,CAAC;AAEF,eAAO,MAAM,2BAA2B,EAAE,cAAc,CAAC,kBAAkB,EAAE,mBAAmB,CAkB/F,CAAC","sourcesContent":["import OpenAI from \"openai\";\nimport type { ResponseCreateParamsStreaming } from \"openai/resources/responses/responses.js\";\nimport { getEnvApiKey } from \"../env-api-keys.ts\";\nimport { clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tModel,\n\tOpenAIResponsesCompat,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tUsage,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { isCloudflareProvider, resolveCloudflareBaseUrl } from \"./cloudflare.ts\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.ts\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.ts\";\nimport { convertResponsesMessages, convertResponsesTools, processResponsesStream } from \"./openai-responses-shared.ts\";\nimport { buildBaseOptions } from \"./simple-options.ts\";\n\nconst OPENAI_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-codex\", \"opencode\"]);\n// OpenAI Responses rejects max_output_tokens below 16: https://github.com/earendil-works/pi/issues/6265\nconst OPENAI_RESPONSES_MIN_OUTPUT_TOKENS = 16;\n\n/**\n * Resolve cache retention preference.\n * Defaults to \"short\" and uses PI_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(cacheRetention?: CacheRetention): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction getCompat(model: Model<\"openai-responses\">): Required<OpenAIResponsesCompat> {\n\treturn {\n\t\tsendSessionIdHeader: model.compat?.sendSessionIdHeader ?? true,\n\t\tsupportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,\n\t};\n}\n\nfunction getPromptCacheRetention(\n\tcompat: Required<OpenAIResponsesCompat>,\n\tcacheRetention: CacheRetention,\n): \"24h\" | undefined {\n\treturn cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"24h\" : undefined;\n}\n\nfunction formatOpenAIResponsesError(error: unknown): string {\n\treturn formatProviderError(normalizeProviderError(error), \"OpenAI API error\");\n}\n\n// OpenAI Responses-specific options\nexport interface OpenAIResponsesOptions extends StreamOptions {\n\treasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\treasoningSummary?: \"auto\" | \"detailed\" | \"concise\" | null;\n\tserviceTier?: ResponseCreateParamsStreaming[\"service_tier\"];\n}\n\n/**\n * Generate function for OpenAI Responses API\n */\nexport const streamOpenAIResponses: StreamFunction<\"openai-responses\", OpenAIResponsesOptions> = (\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions?: OpenAIResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t// Start async processing\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api as Api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\t// Create OpenAI client\n\t\t\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider) || \"\";\n\t\t\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention);\n\t\t\tconst cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\n\t\t\tconst client = createClient(model, context, apiKey, options?.headers, cacheSessionId);\n\t\t\tlet params = buildParams(model, context, options);\n\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\tif (nextParams !== undefined) {\n\t\t\t\tparams = nextParams as ResponseCreateParamsStreaming;\n\t\t\t}\n\t\t\tconst requestOptions = {\n\t\t\t\t...(options?.signal ? { signal: options.signal } : {}),\n\t\t\t\t...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n\t\t\t\tmaxRetries: options?.maxRetries ?? 0,\n\t\t\t};\n\t\t\tconst { data: openaiStream, response } = await client.responses.create(params, requestOptions).withResponse();\n\t\t\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tawait processResponsesStream(openaiStream, output, stream, model, {\n\t\t\t\tserviceTier: options?.serviceTier,\n\t\t\t\tapplyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\n\t\t\t});\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(\"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\tdelete (block as { index?: number }).index;\n\t\t\t\t// partialJson is only a streaming scratch buffer; never persist it.\n\t\t\t\tdelete (block as { partialJson?: string }).partialJson;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatOpenAIResponsesError(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\nexport const streamSimpleOpenAIResponses: StreamFunction<\"openai-responses\", SimpleStreamOptions> = (\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider);\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = buildBaseOptions(model, context, options, apiKey);\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoningEffort = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n\n\treturn streamOpenAIResponses(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t} satisfies OpenAIResponsesOptions);\n};\n\nfunction createClient(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\tapiKey?: string,\n\toptionsHeaders?: Record<string, string>,\n\tsessionId?: string,\n) {\n\tif (!apiKey) {\n\t\tif (!process.env.OPENAI_API_KEY) {\n\t\t\tthrow new Error(\n\t\t\t\t\"OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.\",\n\t\t\t);\n\t\t}\n\t\tapiKey = process.env.OPENAI_API_KEY;\n\t}\n\n\tconst compat = getCompat(model);\n\tconst headers = { ...model.headers };\n\tif (model.provider === \"github-copilot\") {\n\t\tconst hasImages = hasCopilotVisionInput(context.messages);\n\t\tconst copilotHeaders = buildCopilotDynamicHeaders({\n\t\t\tmessages: context.messages,\n\t\t\thasImages,\n\t\t});\n\t\tObject.assign(headers, copilotHeaders);\n\t}\n\n\tif (sessionId) {\n\t\tif (compat.sendSessionIdHeader) {\n\t\t\theaders.session_id = sessionId;\n\t\t}\n\t\theaders[\"x-client-request-id\"] = sessionId;\n\t}\n\n\t// Merge options headers last so they can override defaults\n\tif (optionsHeaders) {\n\t\tObject.assign(headers, optionsHeaders);\n\t}\n\n\tconst defaultHeaders =\n\t\tmodel.provider === \"cloudflare-ai-gateway\"\n\t\t\t? {\n\t\t\t\t\t...headers,\n\t\t\t\t\tAuthorization: headers.Authorization ?? null,\n\t\t\t\t\t\"cf-aig-authorization\": `Bearer ${apiKey}`,\n\t\t\t\t}\n\t\t\t: headers;\n\n\treturn new OpenAI({\n\t\tapiKey,\n\t\tbaseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model) : model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders,\n\t});\n}\n\nfunction buildParams(model: Model<\"openai-responses\">, context: Context, options?: OpenAIResponsesOptions) {\n\tconst messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS);\n\n\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention);\n\tconst compat = getCompat(model);\n\tconst params: ResponseCreateParamsStreaming = {\n\t\tmodel: model.id,\n\t\tinput: messages,\n\t\tstream: true,\n\t\tprompt_cache_key: cacheRetention === \"none\" ? undefined : clampOpenAIPromptCacheKey(options?.sessionId),\n\t\tprompt_cache_retention: getPromptCacheRetention(compat, cacheRetention),\n\t\tstore: false,\n\t};\n\n\tif (options?.maxTokens) {\n\t\tparams.max_output_tokens = Math.max(options.maxTokens, OPENAI_RESPONSES_MIN_OUTPUT_TOKENS);\n\t}\n\n\tif (options?.temperature !== undefined) {\n\t\tparams.temperature = options?.temperature;\n\t}\n\n\tif (options?.serviceTier !== undefined) {\n\t\tparams.service_tier = options.serviceTier;\n\t}\n\n\tif (context.tools && context.tools.length > 0) {\n\t\tparams.tools = convertResponsesTools(context.tools);\n\t}\n\n\tif (model.reasoning) {\n\t\tif (options?.reasoningEffort || options?.reasoningSummary) {\n\t\t\tconst effort = options?.reasoningEffort\n\t\t\t\t? (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort)\n\t\t\t\t: \"medium\";\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: effort as NonNullable<typeof params.reasoning>[\"effort\"],\n\t\t\t\tsummary: options?.reasoningSummary || \"auto\",\n\t\t\t};\n\t\t\tparams.include = [\"reasoning.encrypted_content\"];\n\t\t} else if (model.provider !== \"github-copilot\" && model.thinkingLevelMap?.off !== null) {\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: (model.thinkingLevelMap?.off ?? \"none\") as NonNullable<typeof params.reasoning>[\"effort\"],\n\t\t\t};\n\t\t}\n\t}\n\n\treturn params;\n}\n\nfunction getServiceTierCostMultiplier(\n\tmodel: Pick<Model<\"openai-responses\">, \"id\">,\n\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n): number {\n\tswitch (serviceTier) {\n\t\tcase \"flex\":\n\t\t\treturn 0.5;\n\t\tcase \"priority\":\n\t\t\treturn model.id === \"gpt-5.5\" ? 2.5 : 2;\n\t\tdefault:\n\t\t\treturn 1;\n\t}\n}\n\nfunction applyServiceTierPricing(\n\tusage: Usage,\n\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\tmodel: Pick<Model<\"openai-responses\">, \"id\">,\n) {\n\tconst multiplier = getServiceTierCostMultiplier(model, serviceTier);\n\tif (multiplier === 1) return;\n\n\tusage.cost.input *= multiplier;\n\tusage.cost.output *= multiplier;\n\tusage.cost.cacheRead *= multiplier;\n\tusage.cost.cacheWrite *= multiplier;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"openai-responses.d.ts","sourceRoot":"","sources":["../../src/providers/openai-responses.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,6BAA6B,EAAuB,MAAM,yCAAyC,CAAC;AAGlH,OAAO,KAAK,EAQX,mBAAmB,EACnB,cAAc,EACd,aAAa,EAEb,MAAM,aAAa,CAAC;AAsDrB,MAAM,MAAM,8BAA8B,GAAG,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;AAC7F,MAAM,MAAM,+BAA+B,GAAG,MAAM,GAAG,UAAU,GAAG,SAAS,CAAC;AAC9E,MAAM,WAAW,sBAAuB,SAAQ,aAAa;IAC5D,eAAe,CAAC,EAAE,8BAA8B,CAAC;IACjD,gBAAgB,CAAC,EAAE,+BAA+B,GAAG,IAAI,CAAC;IAC1D,WAAW,CAAC,EAAE,6BAA6B,CAAC,cAAc,CAAC,CAAC;CAC5D;AA+GD,wDAAwD;AACxD,eAAO,MAAM,qBAAqB,EAAE,cAAc,CAAC,kBAAkB,EAAE,sBAAsB,CAQ5F,CAAC;AAEF,eAAO,MAAM,2BAA2B,EAAE,cAAc,CAAC,kBAAkB,EAAE,mBAAmB,CAkB/F,CAAC","sourcesContent":["import OpenAI from \"openai\";\nimport type { ResponseCreateParamsStreaming, ResponseStreamEvent } from \"openai/resources/responses/responses.js\";\nimport { getEnvApiKey } from \"../env-api-keys.ts\";\nimport { clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tModel,\n\tOpenAIResponsesCompat,\n\tProviderHeaders,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tUsage,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { isCloudflareProvider, resolveCloudflareBaseUrl } from \"./cloudflare.ts\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.ts\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.ts\";\nimport {\n\tconvertResponsesMessages,\n\tconvertResponsesTools,\n\ttype OpenAIResponseServiceTier,\n\tprocessResponsesStream,\n} from \"./openai-responses-shared.ts\";\nimport { buildBaseOptions } from \"./simple-options.ts\";\n\nconst OPENAI_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-codex\", \"opencode\"]);\n// OpenAI Responses rejects max_output_tokens below 16: https://github.com/fleetagent/pi/issues/6265\nconst OPENAI_RESPONSES_MIN_OUTPUT_TOKENS = 16;\n\n/**\n * Resolve cache retention preference.\n * Defaults to \"short\" and uses PI_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(cacheRetention?: CacheRetention): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction getCompat(model: Model<\"openai-responses\">): Required<OpenAIResponsesCompat> {\n\treturn {\n\t\tsupportsReasoningEffort: model.compat?.supportsReasoningEffort ?? true,\n\t\tsendSessionIdHeader: model.compat?.sendSessionIdHeader ?? true,\n\t\tsupportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,\n\t};\n}\n\nfunction getPromptCacheRetention(\n\tcompat: Required<OpenAIResponsesCompat>,\n\tcacheRetention: CacheRetention,\n): \"24h\" | undefined {\n\treturn cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"24h\" : undefined;\n}\n\nfunction formatOpenAIResponsesError(error: unknown): string {\n\treturn formatProviderError(normalizeProviderError(error), \"OpenAI API error\");\n}\n\n// OpenAI Responses-specific options\nexport type OpenAIResponsesReasoningEffort = \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\nexport type OpenAIResponsesReasoningSummary = \"auto\" | \"detailed\" | \"concise\";\nexport interface OpenAIResponsesOptions extends StreamOptions {\n\treasoningEffort?: OpenAIResponsesReasoningEffort;\n\treasoningSummary?: OpenAIResponsesReasoningSummary | null;\n\tserviceTier?: ResponseCreateParamsStreaming[\"service_tier\"];\n}\n\ntype CompletedOpenAIResponsesMessage = AssistantMessage & { stopReason: \"stop\" | \"length\" | \"toolUse\" };\n\nfunction createOpenAIResponsesOutput(model: Model<\"openai-responses\">): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi: model.api as Api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"pending\",\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nasync function startOpenAIResponsesRequest(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions: OpenAIResponsesOptions | undefined,\n): Promise<AsyncIterable<ResponseStreamEvent>> {\n\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider) || \"\";\n\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention);\n\tconst cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\n\tconst client = createClient(model, context, apiKey, options?.headers, cacheSessionId);\n\tlet params = buildParams(model, context, options);\n\tconst nextParams = await options?.onPayload?.(params, model);\n\tif (nextParams !== undefined) params = nextParams as ResponseCreateParamsStreaming;\n\tconst requestOptions = {\n\t\t...(options?.signal ? { signal: options.signal } : {}),\n\t\t...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n\t\tmaxRetries: 0,\n\t};\n\tconst { data, response } = await retryProviderRequest(\n\t\t() => client.responses.create(params, requestOptions).withResponse(),\n\t\t{\n\t\t\tmaxRetries: options?.maxRetries,\n\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t\t\tsignal: options?.signal,\n\t\t},\n\t);\n\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\treturn data;\n}\n\nfunction validateOpenAIResponsesCompletion(\n\toutput: AssistantMessage,\n\tsignal?: AbortSignal,\n): asserts output is CompletedOpenAIResponsesMessage {\n\tif (signal?.aborted) throw new Error(\"Request was aborted\");\n\tif (output.stopReason === \"pending\") throw new Error(\"OpenAI Responses stream ended without a stop reason\");\n\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") throw new Error(\"An unknown error occurred\");\n}\n\nasync function executeOpenAIResponsesStream(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions: OpenAIResponsesOptions | undefined,\n\tstream: AssistantMessageEventStream,\n\toutput: AssistantMessage,\n): Promise<void> {\n\tconst openaiStream = await startOpenAIResponsesRequest(model, context, options);\n\tstream.push({ type: \"start\", partial: output });\n\tawait processResponsesStream(openaiStream, output, stream, model, {\n\t\tserviceTier: options?.serviceTier,\n\t\tapplyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\n\t});\n\tvalidateOpenAIResponsesCompletion(output, options?.signal);\n\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\tstream.end();\n}\n\nfunction failOpenAIResponsesStream(\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\terror: unknown,\n\toptions: OpenAIResponsesOptions | undefined,\n): void {\n\tfor (const block of output.content) {\n\t\tdelete (block as { index?: number }).index;\n\t\t// partialJson is only a streaming scratch buffer; never persist it.\n\t\tdelete (block as { partialJson?: string }).partialJson;\n\t}\n\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\toutput.errorMessage = formatOpenAIResponsesError(error);\n\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\tstream.end();\n}\n\nasync function runOpenAIResponsesStream(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions: OpenAIResponsesOptions | undefined,\n\tstream: AssistantMessageEventStream,\n): Promise<void> {\n\tconst output = createOpenAIResponsesOutput(model);\n\ttry {\n\t\tawait executeOpenAIResponsesStream(model, context, options, stream, output);\n\t} catch (error) {\n\t\tfailOpenAIResponsesStream(output, stream, error, options);\n\t}\n}\n\n/** Generate a stream using the OpenAI Responses API. */\nexport const streamOpenAIResponses: StreamFunction<\"openai-responses\", OpenAIResponsesOptions> = (\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions?: OpenAIResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\tvoid runOpenAIResponsesStream(model, context, options, stream);\n\treturn stream;\n};\n\nexport const streamSimpleOpenAIResponses: StreamFunction<\"openai-responses\", SimpleStreamOptions> = (\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider);\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = buildBaseOptions(model, context, options, apiKey);\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoningEffort = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n\n\treturn streamOpenAIResponses(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t} satisfies OpenAIResponsesOptions);\n};\n\nfunction resolveOpenAIResponsesApiKey(apiKey?: string): string {\n\tif (apiKey) return apiKey;\n\tconst environmentApiKey = process.env.OPENAI_API_KEY;\n\tif (environmentApiKey) return environmentApiKey;\n\tthrow new Error(\"OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.\");\n}\n\nfunction buildOpenAIResponsesHeaders(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\tapiKey: string,\n\toptionsHeaders?: ProviderHeaders,\n\tsessionId?: string,\n): ProviderHeaders {\n\tconst compat = getCompat(model);\n\tconst headers: ProviderHeaders = { ...model.headers };\n\tif (model.provider === \"github-copilot\") {\n\t\tconst hasImages = hasCopilotVisionInput(context.messages);\n\t\tObject.assign(\n\t\t\theaders,\n\t\t\tbuildCopilotDynamicHeaders({\n\t\t\t\tmessages: context.messages,\n\t\t\t\thasImages,\n\t\t\t}),\n\t\t);\n\t}\n\n\tif (sessionId) {\n\t\tif (compat.sendSessionIdHeader) headers.session_id = sessionId;\n\t\theaders[\"x-client-request-id\"] = sessionId;\n\t}\n\n\tif (model.provider === \"cloudflare-ai-gateway\") {\n\t\tif (!(\"Authorization\" in headers)) headers.Authorization = null;\n\t\tif (!(\"cf-aig-authorization\" in headers)) headers[\"cf-aig-authorization\"] = `Bearer ${apiKey}`;\n\t}\n\n\t// Merge options headers last so they can override or suppress defaults.\n\tif (optionsHeaders) Object.assign(headers, optionsHeaders);\n\treturn headers;\n}\n\nfunction createClient(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\tapiKey?: string,\n\toptionsHeaders?: ProviderHeaders,\n\tsessionId?: string,\n) {\n\tconst resolvedApiKey = resolveOpenAIResponsesApiKey(apiKey);\n\tconst headers = buildOpenAIResponsesHeaders(model, context, resolvedApiKey, optionsHeaders, sessionId);\n\treturn new OpenAI({\n\t\tapiKey: resolvedApiKey,\n\t\tbaseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model) : model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders: headers,\n\t});\n}\n\nfunction applyOpenAIResponsesReasoning(\n\tparams: ResponseCreateParamsStreaming,\n\tmodel: Model<\"openai-responses\">,\n\tcompat: Required<OpenAIResponsesCompat>,\n\toptions?: OpenAIResponsesOptions,\n): void {\n\tif (!model.reasoning || !compat.supportsReasoningEffort) return;\n\tif (options?.reasoningEffort || options?.reasoningSummary) {\n\t\tconst effort = options.reasoningEffort\n\t\t\t? (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort)\n\t\t\t: \"medium\";\n\t\tparams.reasoning = {\n\t\t\teffort: effort as NonNullable<typeof params.reasoning>[\"effort\"],\n\t\t\tsummary: options.reasoningSummary || \"auto\",\n\t\t};\n\t\tparams.include = [\"reasoning.encrypted_content\"];\n\t\treturn;\n\t}\n\tif (model.provider !== \"github-copilot\" && model.thinkingLevelMap?.off !== null) {\n\t\tparams.reasoning = {\n\t\t\teffort: (model.thinkingLevelMap?.off ?? \"none\") as NonNullable<typeof params.reasoning>[\"effort\"],\n\t\t};\n\t}\n}\n\nfunction buildParams(model: Model<\"openai-responses\">, context: Context, options?: OpenAIResponsesOptions) {\n\tconst messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS);\n\n\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention);\n\tconst compat = getCompat(model);\n\tconst params: ResponseCreateParamsStreaming = {\n\t\tmodel: model.id,\n\t\tinput: messages,\n\t\tstream: true,\n\t\tprompt_cache_key: cacheRetention === \"none\" ? undefined : clampOpenAIPromptCacheKey(options?.sessionId),\n\t\tprompt_cache_retention: getPromptCacheRetention(compat, cacheRetention),\n\t\tstore: false,\n\t};\n\n\tif (options?.maxTokens) {\n\t\tparams.max_output_tokens = Math.max(options.maxTokens, OPENAI_RESPONSES_MIN_OUTPUT_TOKENS);\n\t}\n\n\tif (options?.temperature !== undefined) {\n\t\tparams.temperature = options?.temperature;\n\t}\n\n\tif (options?.serviceTier !== undefined) {\n\t\tparams.service_tier = options.serviceTier;\n\t}\n\n\tif (context.tools && context.tools.length > 0) {\n\t\tparams.tools = convertResponsesTools(context.tools);\n\t}\n\tapplyOpenAIResponsesReasoning(params, model, compat, options);\n\n\treturn params;\n}\n\nfunction getServiceTierCostMultiplier(\n\tmodel: Pick<Model<\"openai-responses\">, \"id\">,\n\tserviceTier: OpenAIResponseServiceTier | undefined,\n): number {\n\tswitch (serviceTier) {\n\t\tcase \"flex\":\n\t\t\treturn 0.5;\n\t\tcase \"priority\":\n\t\t\treturn model.id === \"gpt-5.5\" ? 2.5 : 2;\n\t\tdefault:\n\t\t\treturn 1;\n\t}\n}\n\nfunction applyServiceTierPricing(\n\tusage: Usage,\n\tserviceTier: OpenAIResponseServiceTier | undefined,\n\tmodel: Pick<Model<\"openai-responses\">, \"id\">,\n) {\n\tconst multiplier = getServiceTierCostMultiplier(model, serviceTier);\n\tif (multiplier === 1) return;\n\n\tusage.cost.input *= multiplier;\n\tusage.cost.output *= multiplier;\n\tusage.cost.cacheRead *= multiplier;\n\tusage.cost.cacheWrite *= multiplier;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n}\n"]}
|
|
@@ -4,13 +4,14 @@ import { clampThinkingLevel } from "../models.js";
|
|
|
4
4
|
import { formatProviderError, normalizeProviderError } from "../utils/error-body.js";
|
|
5
5
|
import { AssistantMessageEventStream } from "../utils/event-stream.js";
|
|
6
6
|
import { headersToRecord } from "../utils/headers.js";
|
|
7
|
+
import { retryProviderRequest } from "../utils/provider-retry.js";
|
|
7
8
|
import { isCloudflareProvider, resolveCloudflareBaseUrl } from "./cloudflare.js";
|
|
8
9
|
import { buildCopilotDynamicHeaders, hasCopilotVisionInput } from "./github-copilot-headers.js";
|
|
9
10
|
import { clampOpenAIPromptCacheKey } from "./openai-prompt-cache.js";
|
|
10
|
-
import { convertResponsesMessages, convertResponsesTools, processResponsesStream } from "./openai-responses-shared.js";
|
|
11
|
+
import { convertResponsesMessages, convertResponsesTools, processResponsesStream, } from "./openai-responses-shared.js";
|
|
11
12
|
import { buildBaseOptions } from "./simple-options.js";
|
|
12
13
|
const OPENAI_TOOL_CALL_PROVIDERS = new Set(["openai", "openai-codex", "opencode"]);
|
|
13
|
-
// OpenAI Responses rejects max_output_tokens below 16: https://github.com/
|
|
14
|
+
// OpenAI Responses rejects max_output_tokens below 16: https://github.com/fleetagent/pi/issues/6265
|
|
14
15
|
const OPENAI_RESPONSES_MIN_OUTPUT_TOKENS = 16;
|
|
15
16
|
/**
|
|
16
17
|
* Resolve cache retention preference.
|
|
@@ -27,6 +28,7 @@ function resolveCacheRetention(cacheRetention) {
|
|
|
27
28
|
}
|
|
28
29
|
function getCompat(model) {
|
|
29
30
|
return {
|
|
31
|
+
supportsReasoningEffort: model.compat?.supportsReasoningEffort ?? true,
|
|
30
32
|
sendSessionIdHeader: model.compat?.sendSessionIdHeader ?? true,
|
|
31
33
|
supportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,
|
|
32
34
|
};
|
|
@@ -37,74 +39,90 @@ function getPromptCacheRetention(compat, cacheRetention) {
|
|
|
37
39
|
function formatOpenAIResponsesError(error) {
|
|
38
40
|
return formatProviderError(normalizeProviderError(error), "OpenAI API error");
|
|
39
41
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
42
|
+
function createOpenAIResponsesOutput(model) {
|
|
43
|
+
return {
|
|
44
|
+
role: "assistant",
|
|
45
|
+
content: [],
|
|
46
|
+
api: model.api,
|
|
47
|
+
provider: model.provider,
|
|
48
|
+
model: model.id,
|
|
49
|
+
usage: {
|
|
50
|
+
input: 0,
|
|
51
|
+
output: 0,
|
|
52
|
+
cacheRead: 0,
|
|
53
|
+
cacheWrite: 0,
|
|
54
|
+
totalTokens: 0,
|
|
55
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
56
|
+
},
|
|
57
|
+
stopReason: "pending",
|
|
58
|
+
timestamp: Date.now(),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
async function startOpenAIResponsesRequest(model, context, options) {
|
|
62
|
+
const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
|
|
63
|
+
const cacheRetention = resolveCacheRetention(options?.cacheRetention);
|
|
64
|
+
const cacheSessionId = cacheRetention === "none" ? undefined : options?.sessionId;
|
|
65
|
+
const client = createClient(model, context, apiKey, options?.headers, cacheSessionId);
|
|
66
|
+
let params = buildParams(model, context, options);
|
|
67
|
+
const nextParams = await options?.onPayload?.(params, model);
|
|
68
|
+
if (nextParams !== undefined)
|
|
69
|
+
params = nextParams;
|
|
70
|
+
const requestOptions = {
|
|
71
|
+
...(options?.signal ? { signal: options.signal } : {}),
|
|
72
|
+
...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),
|
|
73
|
+
maxRetries: 0,
|
|
74
|
+
};
|
|
75
|
+
const { data, response } = await retryProviderRequest(() => client.responses.create(params, requestOptions).withResponse(), {
|
|
76
|
+
maxRetries: options?.maxRetries,
|
|
77
|
+
maxRetryDelayMs: options?.maxRetryDelayMs,
|
|
78
|
+
signal: options?.signal,
|
|
79
|
+
});
|
|
80
|
+
await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
|
|
81
|
+
return data;
|
|
82
|
+
}
|
|
83
|
+
function validateOpenAIResponsesCompletion(output, signal) {
|
|
84
|
+
if (signal?.aborted)
|
|
85
|
+
throw new Error("Request was aborted");
|
|
86
|
+
if (output.stopReason === "pending")
|
|
87
|
+
throw new Error("OpenAI Responses stream ended without a stop reason");
|
|
88
|
+
if (output.stopReason === "aborted" || output.stopReason === "error")
|
|
89
|
+
throw new Error("An unknown error occurred");
|
|
90
|
+
}
|
|
91
|
+
async function executeOpenAIResponsesStream(model, context, options, stream, output) {
|
|
92
|
+
const openaiStream = await startOpenAIResponsesRequest(model, context, options);
|
|
93
|
+
stream.push({ type: "start", partial: output });
|
|
94
|
+
await processResponsesStream(openaiStream, output, stream, model, {
|
|
95
|
+
serviceTier: options?.serviceTier,
|
|
96
|
+
applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),
|
|
97
|
+
});
|
|
98
|
+
validateOpenAIResponsesCompletion(output, options?.signal);
|
|
99
|
+
stream.push({ type: "done", reason: output.stopReason, message: output });
|
|
100
|
+
stream.end();
|
|
101
|
+
}
|
|
102
|
+
function failOpenAIResponsesStream(output, stream, error, options) {
|
|
103
|
+
for (const block of output.content) {
|
|
104
|
+
delete block.index;
|
|
105
|
+
// partialJson is only a streaming scratch buffer; never persist it.
|
|
106
|
+
delete block.partialJson;
|
|
107
|
+
}
|
|
108
|
+
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
|
|
109
|
+
output.errorMessage = formatOpenAIResponsesError(error);
|
|
110
|
+
stream.push({ type: "error", reason: output.stopReason, error: output });
|
|
111
|
+
stream.end();
|
|
112
|
+
}
|
|
113
|
+
async function runOpenAIResponsesStream(model, context, options, stream) {
|
|
114
|
+
const output = createOpenAIResponsesOutput(model);
|
|
115
|
+
try {
|
|
116
|
+
await executeOpenAIResponsesStream(model, context, options, stream, output);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
failOpenAIResponsesStream(output, stream, error, options);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** Generate a stream using the OpenAI Responses API. */
|
|
43
123
|
export const streamOpenAIResponses = (model, context, options) => {
|
|
44
124
|
const stream = new AssistantMessageEventStream();
|
|
45
|
-
|
|
46
|
-
(async () => {
|
|
47
|
-
const output = {
|
|
48
|
-
role: "assistant",
|
|
49
|
-
content: [],
|
|
50
|
-
api: model.api,
|
|
51
|
-
provider: model.provider,
|
|
52
|
-
model: model.id,
|
|
53
|
-
usage: {
|
|
54
|
-
input: 0,
|
|
55
|
-
output: 0,
|
|
56
|
-
cacheRead: 0,
|
|
57
|
-
cacheWrite: 0,
|
|
58
|
-
totalTokens: 0,
|
|
59
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
60
|
-
},
|
|
61
|
-
stopReason: "stop",
|
|
62
|
-
timestamp: Date.now(),
|
|
63
|
-
};
|
|
64
|
-
try {
|
|
65
|
-
// Create OpenAI client
|
|
66
|
-
const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
|
|
67
|
-
const cacheRetention = resolveCacheRetention(options?.cacheRetention);
|
|
68
|
-
const cacheSessionId = cacheRetention === "none" ? undefined : options?.sessionId;
|
|
69
|
-
const client = createClient(model, context, apiKey, options?.headers, cacheSessionId);
|
|
70
|
-
let params = buildParams(model, context, options);
|
|
71
|
-
const nextParams = await options?.onPayload?.(params, model);
|
|
72
|
-
if (nextParams !== undefined) {
|
|
73
|
-
params = nextParams;
|
|
74
|
-
}
|
|
75
|
-
const requestOptions = {
|
|
76
|
-
...(options?.signal ? { signal: options.signal } : {}),
|
|
77
|
-
...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),
|
|
78
|
-
maxRetries: options?.maxRetries ?? 0,
|
|
79
|
-
};
|
|
80
|
-
const { data: openaiStream, response } = await client.responses.create(params, requestOptions).withResponse();
|
|
81
|
-
await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
|
|
82
|
-
stream.push({ type: "start", partial: output });
|
|
83
|
-
await processResponsesStream(openaiStream, output, stream, model, {
|
|
84
|
-
serviceTier: options?.serviceTier,
|
|
85
|
-
applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),
|
|
86
|
-
});
|
|
87
|
-
if (options?.signal?.aborted) {
|
|
88
|
-
throw new Error("Request was aborted");
|
|
89
|
-
}
|
|
90
|
-
if (output.stopReason === "aborted" || output.stopReason === "error") {
|
|
91
|
-
throw new Error("An unknown error occurred");
|
|
92
|
-
}
|
|
93
|
-
stream.push({ type: "done", reason: output.stopReason, message: output });
|
|
94
|
-
stream.end();
|
|
95
|
-
}
|
|
96
|
-
catch (error) {
|
|
97
|
-
for (const block of output.content) {
|
|
98
|
-
delete block.index;
|
|
99
|
-
// partialJson is only a streaming scratch buffer; never persist it.
|
|
100
|
-
delete block.partialJson;
|
|
101
|
-
}
|
|
102
|
-
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
|
|
103
|
-
output.errorMessage = formatOpenAIResponsesError(error);
|
|
104
|
-
stream.push({ type: "error", reason: output.stopReason, error: output });
|
|
105
|
-
stream.end();
|
|
106
|
-
}
|
|
107
|
-
})();
|
|
125
|
+
void runOpenAIResponsesStream(model, context, options, stream);
|
|
108
126
|
return stream;
|
|
109
127
|
};
|
|
110
128
|
export const streamSimpleOpenAIResponses = (model, context, options) => {
|
|
@@ -120,47 +138,70 @@ export const streamSimpleOpenAIResponses = (model, context, options) => {
|
|
|
120
138
|
reasoningEffort,
|
|
121
139
|
});
|
|
122
140
|
};
|
|
123
|
-
function
|
|
124
|
-
if (
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
141
|
+
function resolveOpenAIResponsesApiKey(apiKey) {
|
|
142
|
+
if (apiKey)
|
|
143
|
+
return apiKey;
|
|
144
|
+
const environmentApiKey = process.env.OPENAI_API_KEY;
|
|
145
|
+
if (environmentApiKey)
|
|
146
|
+
return environmentApiKey;
|
|
147
|
+
throw new Error("OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.");
|
|
148
|
+
}
|
|
149
|
+
function buildOpenAIResponsesHeaders(model, context, apiKey, optionsHeaders, sessionId) {
|
|
130
150
|
const compat = getCompat(model);
|
|
131
151
|
const headers = { ...model.headers };
|
|
132
152
|
if (model.provider === "github-copilot") {
|
|
133
153
|
const hasImages = hasCopilotVisionInput(context.messages);
|
|
134
|
-
|
|
154
|
+
Object.assign(headers, buildCopilotDynamicHeaders({
|
|
135
155
|
messages: context.messages,
|
|
136
156
|
hasImages,
|
|
137
|
-
});
|
|
138
|
-
Object.assign(headers, copilotHeaders);
|
|
157
|
+
}));
|
|
139
158
|
}
|
|
140
159
|
if (sessionId) {
|
|
141
|
-
if (compat.sendSessionIdHeader)
|
|
160
|
+
if (compat.sendSessionIdHeader)
|
|
142
161
|
headers.session_id = sessionId;
|
|
143
|
-
}
|
|
144
162
|
headers["x-client-request-id"] = sessionId;
|
|
145
163
|
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
164
|
+
if (model.provider === "cloudflare-ai-gateway") {
|
|
165
|
+
if (!("Authorization" in headers))
|
|
166
|
+
headers.Authorization = null;
|
|
167
|
+
if (!("cf-aig-authorization" in headers))
|
|
168
|
+
headers["cf-aig-authorization"] = `Bearer ${apiKey}`;
|
|
149
169
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
170
|
+
// Merge options headers last so they can override or suppress defaults.
|
|
171
|
+
if (optionsHeaders)
|
|
172
|
+
Object.assign(headers, optionsHeaders);
|
|
173
|
+
return headers;
|
|
174
|
+
}
|
|
175
|
+
function createClient(model, context, apiKey, optionsHeaders, sessionId) {
|
|
176
|
+
const resolvedApiKey = resolveOpenAIResponsesApiKey(apiKey);
|
|
177
|
+
const headers = buildOpenAIResponsesHeaders(model, context, resolvedApiKey, optionsHeaders, sessionId);
|
|
157
178
|
return new OpenAI({
|
|
158
|
-
apiKey,
|
|
179
|
+
apiKey: resolvedApiKey,
|
|
159
180
|
baseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model) : model.baseUrl,
|
|
160
181
|
dangerouslyAllowBrowser: true,
|
|
161
|
-
defaultHeaders,
|
|
182
|
+
defaultHeaders: headers,
|
|
162
183
|
});
|
|
163
184
|
}
|
|
185
|
+
function applyOpenAIResponsesReasoning(params, model, compat, options) {
|
|
186
|
+
if (!model.reasoning || !compat.supportsReasoningEffort)
|
|
187
|
+
return;
|
|
188
|
+
if (options?.reasoningEffort || options?.reasoningSummary) {
|
|
189
|
+
const effort = options.reasoningEffort
|
|
190
|
+
? (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort)
|
|
191
|
+
: "medium";
|
|
192
|
+
params.reasoning = {
|
|
193
|
+
effort: effort,
|
|
194
|
+
summary: options.reasoningSummary || "auto",
|
|
195
|
+
};
|
|
196
|
+
params.include = ["reasoning.encrypted_content"];
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (model.provider !== "github-copilot" && model.thinkingLevelMap?.off !== null) {
|
|
200
|
+
params.reasoning = {
|
|
201
|
+
effort: (model.thinkingLevelMap?.off ?? "none"),
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
}
|
|
164
205
|
function buildParams(model, context, options) {
|
|
165
206
|
const messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS);
|
|
166
207
|
const cacheRetention = resolveCacheRetention(options?.cacheRetention);
|
|
@@ -185,23 +226,7 @@ function buildParams(model, context, options) {
|
|
|
185
226
|
if (context.tools && context.tools.length > 0) {
|
|
186
227
|
params.tools = convertResponsesTools(context.tools);
|
|
187
228
|
}
|
|
188
|
-
|
|
189
|
-
if (options?.reasoningEffort || options?.reasoningSummary) {
|
|
190
|
-
const effort = options?.reasoningEffort
|
|
191
|
-
? (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort)
|
|
192
|
-
: "medium";
|
|
193
|
-
params.reasoning = {
|
|
194
|
-
effort: effort,
|
|
195
|
-
summary: options?.reasoningSummary || "auto",
|
|
196
|
-
};
|
|
197
|
-
params.include = ["reasoning.encrypted_content"];
|
|
198
|
-
}
|
|
199
|
-
else if (model.provider !== "github-copilot" && model.thinkingLevelMap?.off !== null) {
|
|
200
|
-
params.reasoning = {
|
|
201
|
-
effort: (model.thinkingLevelMap?.off ?? "none"),
|
|
202
|
-
};
|
|
203
|
-
}
|
|
204
|
-
}
|
|
229
|
+
applyOpenAIResponsesReasoning(params, model, compat, options);
|
|
205
230
|
return params;
|
|
206
231
|
}
|
|
207
232
|
function getServiceTierCostMultiplier(model, serviceTier) {
|