@radheim/ai 0.0.0-stage → 2.4.3
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/README.md +1890 -3
- package/dist/ai.d.ts +36 -0
- package/dist/ai.js +46 -0
- package/dist/cache-policy.d.ts +6 -0
- package/dist/cache-policy.js +205 -0
- package/dist/decision-client.d.ts +10 -0
- package/dist/decision-client.js +42 -0
- package/dist/decision.d.ts +378 -0
- package/dist/decision.js +171 -0
- package/dist/effect.d.ts +59 -0
- package/dist/effect.js +33 -0
- package/dist/effort-updates.d.ts +12 -0
- package/dist/effort-updates.js +23 -0
- package/dist/embedding-client.d.ts +10 -0
- package/dist/embedding-client.js +17 -0
- package/dist/embedding.d.ts +113 -0
- package/dist/embedding.js +76 -0
- package/dist/experimental/cloudflare-run-extraction.d.ts +17 -0
- package/dist/experimental/cloudflare-run-extraction.js +85 -0
- package/dist/experimental/extraction.d.ts +153 -0
- package/dist/experimental/extraction.js +103 -0
- package/dist/experimental/realtime.d.ts +80 -0
- package/dist/experimental/realtime.js +96 -0
- package/dist/experimental.d.ts +10 -0
- package/dist/experimental.js +6 -0
- package/dist/fetch-middleware.d.ts +7 -0
- package/dist/fetch-middleware.js +41 -0
- package/dist/generation.d.ts +77 -0
- package/dist/generation.js +109 -0
- package/dist/image-client.d.ts +14 -0
- package/dist/image-client.js +39 -0
- package/dist/image.d.ts +323 -0
- package/dist/image.js +103 -0
- package/dist/index.d.ts +300 -0
- package/dist/index.js +179 -0
- package/dist/llm.d.ts +109 -0
- package/dist/llm.js +177 -0
- package/dist/loop.d.ts +38 -0
- package/dist/loop.js +139 -0
- package/dist/media-client.d.ts +30 -0
- package/dist/media-client.js +44 -0
- package/dist/media-model.d.ts +49 -0
- package/dist/media-model.js +55 -0
- package/dist/media.d.ts +237 -0
- package/dist/media.js +285 -0
- package/dist/promise-media.d.ts +20 -0
- package/dist/promise-media.js +16 -0
- package/dist/protocols/alibaba-chat.d.ts +315 -0
- package/dist/protocols/alibaba-chat.js +78 -0
- package/dist/protocols/alibaba-images.d.ts +22 -0
- package/dist/protocols/alibaba-images.js +77 -0
- package/dist/protocols/alibaba-messages.d.ts +413 -0
- package/dist/protocols/alibaba-messages.js +44 -0
- package/dist/protocols/alibaba-responses.d.ts +298 -0
- package/dist/protocols/alibaba-responses.js +67 -0
- package/dist/protocols/anthropic-messages.d.ts +1213 -0
- package/dist/protocols/anthropic-messages.js +1412 -0
- package/dist/protocols/assemblyai-transcription.d.ts +41 -0
- package/dist/protocols/assemblyai-transcription.js +137 -0
- package/dist/protocols/bedrock-converse.d.ts +548 -0
- package/dist/protocols/bedrock-converse.js +801 -0
- package/dist/protocols/bedrock-event-stream.d.ts +14 -0
- package/dist/protocols/bedrock-event-stream.js +100 -0
- package/dist/protocols/cartesia-speech.d.ts +117 -0
- package/dist/protocols/cartesia-speech.js +120 -0
- package/dist/protocols/cloudflare-run-decisions.d.ts +9 -0
- package/dist/protocols/cloudflare-run-decisions.js +36 -0
- package/dist/protocols/cloudflare-workers-ai-images.d.ts +23 -0
- package/dist/protocols/cloudflare-workers-ai-images.js +80 -0
- package/dist/protocols/cohere-chat.d.ts +184 -0
- package/dist/protocols/cohere-chat.js +317 -0
- package/dist/protocols/deepgram-speech.d.ts +109 -0
- package/dist/protocols/deepgram-speech.js +93 -0
- package/dist/protocols/deepgram-transcription.d.ts +26 -0
- package/dist/protocols/deepgram-transcription.js +119 -0
- package/dist/protocols/elevenlabs-speech.d.ts +112 -0
- package/dist/protocols/elevenlabs-speech.js +111 -0
- package/dist/protocols/elevenlabs-transcription.d.ts +28 -0
- package/dist/protocols/elevenlabs-transcription.js +137 -0
- package/dist/protocols/gemini.d.ts +388 -0
- package/dist/protocols/gemini.js +741 -0
- package/dist/protocols/google-decisions.d.ts +13 -0
- package/dist/protocols/google-decisions.js +133 -0
- package/dist/protocols/google-embed-content.d.ts +34 -0
- package/dist/protocols/google-embed-content.js +110 -0
- package/dist/protocols/google-images.d.ts +18 -0
- package/dist/protocols/google-images.js +169 -0
- package/dist/protocols/google-interactions-video.d.ts +38 -0
- package/dist/protocols/google-interactions-video.js +185 -0
- package/dist/protocols/google-interactions.d.ts +554 -0
- package/dist/protocols/google-interactions.js +756 -0
- package/dist/protocols/google-speech.d.ts +120 -0
- package/dist/protocols/google-speech.js +94 -0
- package/dist/protocols/google-transcription.d.ts +148 -0
- package/dist/protocols/google-transcription.js +129 -0
- package/dist/protocols/google-vertex-predict-embeddings.d.ts +18 -0
- package/dist/protocols/google-vertex-predict-embeddings.js +74 -0
- package/dist/protocols/index.d.ts +21 -0
- package/dist/protocols/index.js +21 -0
- package/dist/protocols/meta-images.d.ts +26 -0
- package/dist/protocols/meta-images.js +101 -0
- package/dist/protocols/meta-messages.d.ts +423 -0
- package/dist/protocols/meta-messages.js +63 -0
- package/dist/protocols/meta-responses.d.ts +533 -0
- package/dist/protocols/meta-responses.js +189 -0
- package/dist/protocols/minimax-images.d.ts +25 -0
- package/dist/protocols/minimax-images.js +150 -0
- package/dist/protocols/minimax-video.d.ts +45 -0
- package/dist/protocols/minimax-video.js +296 -0
- package/dist/protocols/mistral-chat.d.ts +565 -0
- package/dist/protocols/mistral-chat.js +606 -0
- package/dist/protocols/open-responses-channel.d.ts +25 -0
- package/dist/protocols/open-responses-channel.js +137 -0
- package/dist/protocols/open-responses-continuation.d.ts +18 -0
- package/dist/protocols/open-responses-continuation.js +172 -0
- package/dist/protocols/open-responses.d.ts +2509 -0
- package/dist/protocols/open-responses.js +1335 -0
- package/dist/protocols/openai-chat.d.ts +2571 -0
- package/dist/protocols/openai-chat.js +1140 -0
- package/dist/protocols/openai-compatible-chat.d.ts +184 -0
- package/dist/protocols/openai-compatible-chat.js +19 -0
- package/dist/protocols/openai-compatible-responses.d.ts +231 -0
- package/dist/protocols/openai-compatible-responses.js +18 -0
- package/dist/protocols/openai-decisions.d.ts +22 -0
- package/dist/protocols/openai-decisions.js +141 -0
- package/dist/protocols/openai-embeddings.d.ts +16 -0
- package/dist/protocols/openai-embeddings.js +76 -0
- package/dist/protocols/openai-freeform.d.ts +78 -0
- package/dist/protocols/openai-freeform.js +222 -0
- package/dist/protocols/openai-images.d.ts +148 -0
- package/dist/protocols/openai-images.js +303 -0
- package/dist/protocols/openai-responses.d.ts +1600 -0
- package/dist/protocols/openai-responses.js +360 -0
- package/dist/protocols/openai-speech.d.ts +110 -0
- package/dist/protocols/openai-speech.js +112 -0
- package/dist/protocols/openai-transcription.d.ts +185 -0
- package/dist/protocols/openai-transcription.js +206 -0
- package/dist/protocols/openrouter-video.d.ts +36 -0
- package/dist/protocols/openrouter-video.js +139 -0
- package/dist/protocols/seedance-video.d.ts +45 -0
- package/dist/protocols/seedance-video.js +217 -0
- package/dist/protocols/shared.d.ts +249 -0
- package/dist/protocols/shared.js +446 -0
- package/dist/protocols/system-one.d.ts +145 -0
- package/dist/protocols/system-one.js +272 -0
- package/dist/protocols/utils/bedrock-auth.d.ts +60 -0
- package/dist/protocols/utils/bedrock-auth.js +86 -0
- package/dist/protocols/utils/bedrock-cache.d.ts +19 -0
- package/dist/protocols/utils/bedrock-cache.js +49 -0
- package/dist/protocols/utils/bedrock-media.d.ts +53 -0
- package/dist/protocols/utils/bedrock-media.js +98 -0
- package/dist/protocols/utils/cache.d.ts +25 -0
- package/dist/protocols/utils/cache.js +33 -0
- package/dist/protocols/utils/claude-model.d.ts +8 -0
- package/dist/protocols/utils/claude-model.js +15 -0
- package/dist/protocols/utils/gateway-protocol.d.ts +17 -0
- package/dist/protocols/utils/gateway-protocol.js +59 -0
- package/dist/protocols/utils/gemini-generate-content.d.ts +75 -0
- package/dist/protocols/utils/gemini-generate-content.js +96 -0
- package/dist/protocols/utils/gemini-json-schema.d.ts +8 -0
- package/dist/protocols/utils/gemini-json-schema.js +76 -0
- package/dist/protocols/utils/image-sizing.d.ts +31 -0
- package/dist/protocols/utils/image-sizing.js +73 -0
- package/dist/protocols/utils/lifecycle.d.ts +24 -0
- package/dist/protocols/utils/lifecycle.js +62 -0
- package/dist/protocols/utils/media-input.d.ts +32 -0
- package/dist/protocols/utils/media-input.js +62 -0
- package/dist/protocols/utils/mistral-tool-id.d.ts +5 -0
- package/dist/protocols/utils/mistral-tool-id.js +31 -0
- package/dist/protocols/utils/open-responses-options.d.ts +54 -0
- package/dist/protocols/utils/open-responses-options.js +59 -0
- package/dist/protocols/utils/partial-json-options.d.ts +61 -0
- package/dist/protocols/utils/partial-json-options.js +51 -0
- package/dist/protocols/utils/partial-json.d.ts +8 -0
- package/dist/protocols/utils/partial-json.js +280 -0
- package/dist/protocols/utils/responses-checkpoint.d.ts +4 -0
- package/dist/protocols/utils/responses-checkpoint.js +103 -0
- package/dist/protocols/utils/responses-compaction.d.ts +6 -0
- package/dist/protocols/utils/responses-compaction.js +162 -0
- package/dist/protocols/utils/responses-hosted-tools.d.ts +122 -0
- package/dist/protocols/utils/responses-hosted-tools.js +63 -0
- package/dist/protocols/utils/speaker-turns.d.ts +3 -0
- package/dist/protocols/utils/speaker-turns.js +9 -0
- package/dist/protocols/utils/speech-stream.d.ts +49 -0
- package/dist/protocols/utils/speech-stream.js +64 -0
- package/dist/protocols/utils/tool-schema.d.ts +10 -0
- package/dist/protocols/utils/tool-schema.js +109 -0
- package/dist/protocols/utils/tool-stream.d.ts +478 -0
- package/dist/protocols/utils/tool-stream.js +153 -0
- package/dist/protocols/venice-chat.d.ts +340 -0
- package/dist/protocols/venice-chat.js +283 -0
- package/dist/protocols/xai-images.d.ts +25 -0
- package/dist/protocols/xai-images.js +87 -0
- package/dist/protocols/xai-responses.d.ts +294 -0
- package/dist/protocols/xai-responses.js +86 -0
- package/dist/protocols/xai-video.d.ts +35 -0
- package/dist/protocols/xai-video.js +159 -0
- package/dist/protocols/zai-chat.d.ts +296 -0
- package/dist/protocols/zai-chat.js +56 -0
- package/dist/protocols/zai-images.d.ts +20 -0
- package/dist/protocols/zai-images.js +79 -0
- package/dist/protocols/zai-messages.d.ts +409 -0
- package/dist/protocols/zai-messages.js +30 -0
- package/dist/protocols.d.ts +1 -0
- package/dist/protocols.js +1 -0
- package/dist/provider-error.d.ts +22 -0
- package/dist/provider-error.js +228 -0
- package/dist/provider-package.d.ts +17 -0
- package/dist/provider-package.js +1 -0
- package/dist/providers/alibaba/chat.d.ts +1 -0
- package/dist/providers/alibaba/chat.js +1 -0
- package/dist/providers/alibaba/embeddings.d.ts +2 -0
- package/dist/providers/alibaba/embeddings.js +1 -0
- package/dist/providers/alibaba/images.d.ts +2 -0
- package/dist/providers/alibaba/images.js +1 -0
- package/dist/providers/alibaba/messages.d.ts +3 -0
- package/dist/providers/alibaba/messages.js +1 -0
- package/dist/providers/alibaba/responses.d.ts +3 -0
- package/dist/providers/alibaba/responses.js +1 -0
- package/dist/providers/alibaba.d.ts +905 -0
- package/dist/providers/alibaba.js +119 -0
- package/dist/providers/amazon-bedrock/mantle/chat.d.ts +2 -0
- package/dist/providers/amazon-bedrock/mantle/chat.js +1 -0
- package/dist/providers/amazon-bedrock/mantle/messages.d.ts +2 -0
- package/dist/providers/amazon-bedrock/mantle/messages.js +1 -0
- package/dist/providers/amazon-bedrock/mantle/responses.d.ts +2 -0
- package/dist/providers/amazon-bedrock/mantle/responses.js +1 -0
- package/dist/providers/amazon-bedrock/mantle.d.ts +2 -0
- package/dist/providers/amazon-bedrock/mantle.js +1 -0
- package/dist/providers/amazon-bedrock-mantle.d.ts +789 -0
- package/dist/providers/amazon-bedrock-mantle.js +107 -0
- package/dist/providers/amazon-bedrock.d.ts +190 -0
- package/dist/providers/amazon-bedrock.js +44 -0
- package/dist/providers/anthropic-compatible.d.ts +364 -0
- package/dist/providers/anthropic-compatible.js +47 -0
- package/dist/providers/anthropic.d.ts +362 -0
- package/dist/providers/anthropic.js +36 -0
- package/dist/providers/assemblyai.d.ts +19 -0
- package/dist/providers/assemblyai.js +19 -0
- package/dist/providers/azure/chat.d.ts +2 -0
- package/dist/providers/azure/chat.js +1 -0
- package/dist/providers/azure/embeddings.d.ts +2 -0
- package/dist/providers/azure/embeddings.js +1 -0
- package/dist/providers/azure/images.d.ts +2 -0
- package/dist/providers/azure/images.js +1 -0
- package/dist/providers/azure/messages.d.ts +2 -0
- package/dist/providers/azure/messages.js +1 -0
- package/dist/providers/azure/responses.d.ts +2 -0
- package/dist/providers/azure/responses.js +1 -0
- package/dist/providers/azure.d.ts +1074 -0
- package/dist/providers/azure.js +150 -0
- package/dist/providers/baseten/decisions.d.ts +2 -0
- package/dist/providers/baseten/decisions.js +1 -0
- package/dist/providers/baseten.d.ts +384 -0
- package/dist/providers/baseten.js +56 -0
- package/dist/providers/byteplus/videos.d.ts +2 -0
- package/dist/providers/byteplus/videos.js +1 -0
- package/dist/providers/byteplus.d.ts +24 -0
- package/dist/providers/byteplus.js +21 -0
- package/dist/providers/cartesia.d.ts +18 -0
- package/dist/providers/cartesia.js +17 -0
- package/dist/providers/cerebras.d.ts +375 -0
- package/dist/providers/cerebras.js +33 -0
- package/dist/providers/cloudflare-ai-gateway/decisions.d.ts +2 -0
- package/dist/providers/cloudflare-ai-gateway/decisions.js +1 -0
- package/dist/providers/cloudflare-ai-gateway.d.ts +1581 -0
- package/dist/providers/cloudflare-ai-gateway.js +120 -0
- package/dist/providers/cloudflare-shared.d.ts +9 -0
- package/dist/providers/cloudflare-shared.js +25 -0
- package/dist/providers/cloudflare-workers-ai/decisions.d.ts +2 -0
- package/dist/providers/cloudflare-workers-ai/decisions.js +1 -0
- package/dist/providers/cloudflare-workers-ai/images.d.ts +2 -0
- package/dist/providers/cloudflare-workers-ai/images.js +1 -0
- package/dist/providers/cloudflare-workers-ai.d.ts +391 -0
- package/dist/providers/cloudflare-workers-ai.js +69 -0
- package/dist/providers/cohere/chat.d.ts +4 -0
- package/dist/providers/cohere/chat.js +3 -0
- package/dist/providers/cohere/embeddings.d.ts +2 -0
- package/dist/providers/cohere/embeddings.js +1 -0
- package/dist/providers/cohere.d.ts +502 -0
- package/dist/providers/cohere.js +55 -0
- package/dist/providers/deepgram.d.ts +22 -0
- package/dist/providers/deepgram.js +20 -0
- package/dist/providers/deepinfra/embeddings.d.ts +2 -0
- package/dist/providers/deepinfra/embeddings.js +1 -0
- package/dist/providers/deepinfra.d.ts +378 -0
- package/dist/providers/deepinfra.js +52 -0
- package/dist/providers/deepseek.d.ts +376 -0
- package/dist/providers/deepseek.js +30 -0
- package/dist/providers/digitalocean/decisions.d.ts +2 -0
- package/dist/providers/digitalocean/decisions.js +1 -0
- package/dist/providers/digitalocean/embeddings.d.ts +2 -0
- package/dist/providers/digitalocean/embeddings.js +1 -0
- package/dist/providers/digitalocean/images.d.ts +2 -0
- package/dist/providers/digitalocean/images.js +1 -0
- package/dist/providers/digitalocean/responses.d.ts +4 -0
- package/dist/providers/digitalocean/responses.js +1 -0
- package/dist/providers/digitalocean.d.ts +874 -0
- package/dist/providers/digitalocean.js +106 -0
- package/dist/providers/elevenlabs.d.ts +22 -0
- package/dist/providers/elevenlabs.js +22 -0
- package/dist/providers/fireworks/embeddings.d.ts +2 -0
- package/dist/providers/fireworks/embeddings.js +1 -0
- package/dist/providers/fireworks.d.ts +379 -0
- package/dist/providers/fireworks.js +40 -0
- package/dist/providers/google/decisions.d.ts +2 -0
- package/dist/providers/google/decisions.js +1 -0
- package/dist/providers/google/embeddings.d.ts +2 -0
- package/dist/providers/google/embeddings.js +1 -0
- package/dist/providers/google/images.d.ts +2 -0
- package/dist/providers/google/images.js +1 -0
- package/dist/providers/google/interactions.d.ts +7 -0
- package/dist/providers/google/interactions.js +3 -0
- package/dist/providers/google/videos.d.ts +2 -0
- package/dist/providers/google/videos.js +1 -0
- package/dist/providers/google-vertex/chat.d.ts +2 -0
- package/dist/providers/google-vertex/chat.js +1 -0
- package/dist/providers/google-vertex/embeddings.d.ts +2 -0
- package/dist/providers/google-vertex/embeddings.js +1 -0
- package/dist/providers/google-vertex/gemini.d.ts +2 -0
- package/dist/providers/google-vertex/gemini.js +1 -0
- package/dist/providers/google-vertex/images.d.ts +2 -0
- package/dist/providers/google-vertex/images.js +1 -0
- package/dist/providers/google-vertex/interactions.d.ts +2 -0
- package/dist/providers/google-vertex/interactions.js +1 -0
- package/dist/providers/google-vertex/messages.d.ts +2 -0
- package/dist/providers/google-vertex/messages.js +1 -0
- package/dist/providers/google-vertex/mistral.d.ts +2 -0
- package/dist/providers/google-vertex/mistral.js +1 -0
- package/dist/providers/google-vertex/responses.d.ts +2 -0
- package/dist/providers/google-vertex/responses.js +1 -0
- package/dist/providers/google-vertex-chat.d.ts +204 -0
- package/dist/providers/google-vertex-chat.js +29 -0
- package/dist/providers/google-vertex-interactions.d.ts +111 -0
- package/dist/providers/google-vertex-interactions.js +62 -0
- package/dist/providers/google-vertex-messages.d.ts +362 -0
- package/dist/providers/google-vertex-messages.js +51 -0
- package/dist/providers/google-vertex-mistral.d.ts +120 -0
- package/dist/providers/google-vertex-mistral.js +43 -0
- package/dist/providers/google-vertex-responses.d.ts +253 -0
- package/dist/providers/google-vertex-responses.js +30 -0
- package/dist/providers/google-vertex-shared.d.ts +58 -0
- package/dist/providers/google-vertex-shared.js +128 -0
- package/dist/providers/google-vertex.d.ts +132 -0
- package/dist/providers/google-vertex.js +161 -0
- package/dist/providers/google.d.ts +246 -0
- package/dist/providers/google.js +80 -0
- package/dist/providers/groq.d.ts +470 -0
- package/dist/providers/groq.js +63 -0
- package/dist/providers/index.d.ts +45 -0
- package/dist/providers/index.js +45 -0
- package/dist/providers/meta/chat.d.ts +2 -0
- package/dist/providers/meta/chat.js +1 -0
- package/dist/providers/meta/images.d.ts +2 -0
- package/dist/providers/meta/images.js +1 -0
- package/dist/providers/meta/messages.d.ts +2 -0
- package/dist/providers/meta/messages.js +1 -0
- package/dist/providers/meta/responses.d.ts +2 -0
- package/dist/providers/meta/responses.js +1 -0
- package/dist/providers/meta.d.ts +804 -0
- package/dist/providers/meta.js +96 -0
- package/dist/providers/minimax/chat.d.ts +4 -0
- package/dist/providers/minimax/chat.js +3 -0
- package/dist/providers/minimax/images.d.ts +3 -0
- package/dist/providers/minimax/images.js +1 -0
- package/dist/providers/minimax/messages.d.ts +1 -0
- package/dist/providers/minimax/messages.js +1 -0
- package/dist/providers/minimax/responses.d.ts +4 -0
- package/dist/providers/minimax/responses.js +3 -0
- package/dist/providers/minimax/videos.d.ts +3 -0
- package/dist/providers/minimax/videos.js +1 -0
- package/dist/providers/minimax.d.ts +798 -0
- package/dist/providers/minimax.js +99 -0
- package/dist/providers/mistral.d.ts +208 -0
- package/dist/providers/mistral.js +17 -0
- package/dist/providers/moonshot/chat.d.ts +1 -0
- package/dist/providers/moonshot/chat.js +1 -0
- package/dist/providers/moonshot/messages.d.ts +4 -0
- package/dist/providers/moonshot/messages.js +3 -0
- package/dist/providers/moonshot/responses.d.ts +4 -0
- package/dist/providers/moonshot/responses.js +3 -0
- package/dist/providers/moonshot.d.ts +785 -0
- package/dist/providers/moonshot.js +78 -0
- package/dist/providers/open-responses-options.d.ts +5 -0
- package/dist/providers/open-responses-options.js +1 -0
- package/dist/providers/openai/chat.d.ts +2 -0
- package/dist/providers/openai/chat.js +1 -0
- package/dist/providers/openai/embeddings.d.ts +2 -0
- package/dist/providers/openai/embeddings.js +1 -0
- package/dist/providers/openai/images.d.ts +2 -0
- package/dist/providers/openai/images.js +1 -0
- package/dist/providers/openai/responses.d.ts +2 -0
- package/dist/providers/openai/responses.js +1 -0
- package/dist/providers/openai-compatible/decisions.d.ts +2 -0
- package/dist/providers/openai-compatible/decisions.js +1 -0
- package/dist/providers/openai-compatible/embeddings.d.ts +2 -0
- package/dist/providers/openai-compatible/embeddings.js +1 -0
- package/dist/providers/openai-compatible/images.d.ts +2 -0
- package/dist/providers/openai-compatible/images.js +1 -0
- package/dist/providers/openai-compatible/responses.d.ts +1 -0
- package/dist/providers/openai-compatible/responses.js +1 -0
- package/dist/providers/openai-compatible-responses.d.ts +250 -0
- package/dist/providers/openai-compatible-responses.js +26 -0
- package/dist/providers/openai-compatible.d.ts +208 -0
- package/dist/providers/openai-compatible.js +71 -0
- package/dist/providers/openai-options.d.ts +21 -0
- package/dist/providers/openai-options.js +37 -0
- package/dist/providers/openai.d.ts +522 -0
- package/dist/providers/openai.js +118 -0
- package/dist/providers/opencode/decisions.d.ts +2 -0
- package/dist/providers/opencode/decisions.js +1 -0
- package/dist/providers/opencode.d.ts +23 -0
- package/dist/providers/opencode.js +25 -0
- package/dist/providers/openrouter/decisions.d.ts +2 -0
- package/dist/providers/openrouter/decisions.js +1 -0
- package/dist/providers/openrouter/embeddings.d.ts +2 -0
- package/dist/providers/openrouter/embeddings.js +1 -0
- package/dist/providers/openrouter/images.d.ts +2 -0
- package/dist/providers/openrouter/images.js +1 -0
- package/dist/providers/openrouter/responses.d.ts +3 -0
- package/dist/providers/openrouter/responses.js +1 -0
- package/dist/providers/openrouter/videos.d.ts +2 -0
- package/dist/providers/openrouter/videos.js +1 -0
- package/dist/providers/openrouter.d.ts +1204 -0
- package/dist/providers/openrouter.js +210 -0
- package/dist/providers/settings.d.ts +40 -0
- package/dist/providers/settings.js +18 -0
- package/dist/providers/togetherai.d.ts +375 -0
- package/dist/providers/togetherai.js +30 -0
- package/dist/providers/typesafe-ai/decisions.d.ts +2 -0
- package/dist/providers/typesafe-ai/decisions.js +1 -0
- package/dist/providers/typesafe-ai.d.ts +23 -0
- package/dist/providers/typesafe-ai.js +25 -0
- package/dist/providers/venice/responses.d.ts +4 -0
- package/dist/providers/venice/responses.js +1 -0
- package/dist/providers/venice.d.ts +632 -0
- package/dist/providers/venice.js +57 -0
- package/dist/providers/vercel-ai-gateway/chat.d.ts +2 -0
- package/dist/providers/vercel-ai-gateway/chat.js +1 -0
- package/dist/providers/vercel-ai-gateway/decisions.d.ts +2 -0
- package/dist/providers/vercel-ai-gateway/decisions.js +1 -0
- package/dist/providers/vercel-ai-gateway/embeddings.d.ts +2 -0
- package/dist/providers/vercel-ai-gateway/embeddings.js +1 -0
- package/dist/providers/vercel-ai-gateway/images.d.ts +2 -0
- package/dist/providers/vercel-ai-gateway/images.js +1 -0
- package/dist/providers/vercel-ai-gateway/messages.d.ts +2 -0
- package/dist/providers/vercel-ai-gateway/messages.js +1 -0
- package/dist/providers/vercel-ai-gateway/responses.d.ts +2 -0
- package/dist/providers/vercel-ai-gateway/responses.js +1 -0
- package/dist/providers/vercel-ai-gateway.d.ts +111 -0
- package/dist/providers/vercel-ai-gateway.js +181 -0
- package/dist/providers/volcengine/videos.d.ts +2 -0
- package/dist/providers/volcengine/videos.js +1 -0
- package/dist/providers/volcengine.d.ts +24 -0
- package/dist/providers/volcengine.js +21 -0
- package/dist/providers/xai/images.d.ts +2 -0
- package/dist/providers/xai/images.js +1 -0
- package/dist/providers/xai/videos.d.ts +2 -0
- package/dist/providers/xai/videos.js +1 -0
- package/dist/providers/xai.d.ts +235 -0
- package/dist/providers/xai.js +89 -0
- package/dist/providers/zai/chat.d.ts +1 -0
- package/dist/providers/zai/chat.js +1 -0
- package/dist/providers/zai/images.d.ts +2 -0
- package/dist/providers/zai/images.js +1 -0
- package/dist/providers/zai-coding-plan/chat.d.ts +1 -0
- package/dist/providers/zai-coding-plan/chat.js +1 -0
- package/dist/providers/zai-coding-plan/messages.d.ts +4 -0
- package/dist/providers/zai-coding-plan/messages.js +3 -0
- package/dist/providers/zai-coding-plan/responses.d.ts +4 -0
- package/dist/providers/zai-coding-plan/responses.js +3 -0
- package/dist/providers/zai-coding-plan.d.ts +846 -0
- package/dist/providers/zai-coding-plan.js +56 -0
- package/dist/providers/zai.d.ts +285 -0
- package/dist/providers/zai.js +44 -0
- package/dist/providers.d.ts +1 -0
- package/dist/providers.js +1 -0
- package/dist/public.d.ts +18 -0
- package/dist/public.js +7 -0
- package/dist/route/auth-options.d.ts +35 -0
- package/dist/route/auth-options.js +17 -0
- package/dist/route/auth.d.ts +52 -0
- package/dist/route/auth.js +92 -0
- package/dist/route/client.d.ts +229 -0
- package/dist/route/client.js +293 -0
- package/dist/route/decision.d.ts +55 -0
- package/dist/route/decision.js +73 -0
- package/dist/route/embedding.d.ts +58 -0
- package/dist/route/embedding.js +85 -0
- package/dist/route/endpoint.d.ts +29 -0
- package/dist/route/endpoint.js +21 -0
- package/dist/route/executor-service.d.ts +54 -0
- package/dist/route/executor-service.js +115 -0
- package/dist/route/executor.d.ts +37 -0
- package/dist/route/executor.js +225 -0
- package/dist/route/framing.d.ts +44 -0
- package/dist/route/framing.js +63 -0
- package/dist/route/index.d.ts +21 -0
- package/dist/route/index.js +18 -0
- package/dist/route/media-protocol.d.ts +187 -0
- package/dist/route/media-protocol.js +117 -0
- package/dist/route/media.d.ts +91 -0
- package/dist/route/media.js +251 -0
- package/dist/route/protocol.d.ts +85 -0
- package/dist/route/protocol.js +19 -0
- package/dist/route/transport/http.d.ts +34 -0
- package/dist/route/transport/http.js +67 -0
- package/dist/route/transport/index.d.ts +42 -0
- package/dist/route/transport/index.js +4 -0
- package/dist/route/transport/websocket-channel.d.ts +56 -0
- package/dist/route/transport/websocket-channel.js +1 -0
- package/dist/route/transport/websocket.d.ts +32 -0
- package/dist/route/transport/websocket.js +315 -0
- package/dist/route.d.ts +1 -0
- package/dist/route.js +1 -0
- package/dist/schema/errors.d.ts +194 -0
- package/dist/schema/errors.js +217 -0
- package/dist/schema/events.d.ts +11001 -0
- package/dist/schema/events.js +542 -0
- package/dist/schema/ids.d.ts +17 -0
- package/dist/schema/ids.js +10 -0
- package/dist/schema/index.d.ts +5 -0
- package/dist/schema/index.js +5 -0
- package/dist/schema/messages.d.ts +2706 -0
- package/dist/schema/messages.js +344 -0
- package/dist/schema/options.d.ts +270 -0
- package/dist/schema/options.js +198 -0
- package/dist/speech.d.ts +266 -0
- package/dist/speech.js +114 -0
- package/dist/test-ai.d.ts +15 -0
- package/dist/test-ai.js +49 -0
- package/dist/testing.d.ts +1585 -0
- package/dist/testing.js +108 -0
- package/dist/tool-history.d.ts +2 -0
- package/dist/tool-history.js +91 -0
- package/dist/tool-runtime.d.ts +22 -0
- package/dist/tool-runtime.js +55 -0
- package/dist/tool-updates.d.ts +34 -0
- package/dist/tool-updates.js +93 -0
- package/dist/tool.d.ts +150 -0
- package/dist/tool.js +159 -0
- package/dist/transcription.d.ts +254 -0
- package/dist/transcription.js +119 -0
- package/dist/utils/bytes.d.ts +1 -0
- package/dist/utils/bytes.js +10 -0
- package/dist/utils/json.d.ts +4 -0
- package/dist/utils/json.js +4 -0
- package/dist/utils/media-type.d.ts +8 -0
- package/dist/utils/media-type.js +93 -0
- package/dist/utils/provider-codes.d.ts +3 -0
- package/dist/utils/provider-codes.js +41 -0
- package/dist/utils/record.d.ts +2 -0
- package/dist/utils/record.js +2 -0
- package/dist/utils/sanitize.d.ts +5 -0
- package/dist/utils/sanitize.js +31 -0
- package/dist/video-client.d.ts +12 -0
- package/dist/video-client.js +24 -0
- package/dist/video.d.ts +178 -0
- package/dist/video.js +79 -0
- package/package.json +648 -4
|
@@ -0,0 +1,1335 @@
|
|
|
1
|
+
import { Effect, Option, Schema } from "effect";
|
|
2
|
+
import { HttpTransport } from "../route/transport/index.js";
|
|
3
|
+
import { Protocol } from "../route/protocol.js";
|
|
4
|
+
import { AIError, StreamEvent, ProviderInternalError, Usage, } from "../schema/index.js";
|
|
5
|
+
import { JsonObject, lenient, optionalArray, optionalNull, optionalNullish, ProviderShared, withUntypedFrames, } from "./shared.js";
|
|
6
|
+
import { classifyProviderFailure } from "../provider-error.js";
|
|
7
|
+
import { effortUpdate, resolveEffortUpdates } from "../effort-updates.js";
|
|
8
|
+
import { toolsUpdate } from "../tool-updates.js";
|
|
9
|
+
import { OpenResponsesOptions } from "./utils/open-responses-options.js";
|
|
10
|
+
import { Lifecycle } from "./utils/lifecycle.js";
|
|
11
|
+
import { ToolStream } from "./utils/tool-stream.js";
|
|
12
|
+
import { OpenAIFreeform } from "./openai-freeform.js";
|
|
13
|
+
const ADAPTER = "open-responses";
|
|
14
|
+
const NAME = "Open Responses";
|
|
15
|
+
export const PATH = "/responses";
|
|
16
|
+
// =============================================================================
|
|
17
|
+
// Request Body Schema
|
|
18
|
+
// =============================================================================
|
|
19
|
+
export const OpenResponsesInputText = Schema.Struct({
|
|
20
|
+
type: Schema.tag("input_text"),
|
|
21
|
+
text: Schema.String,
|
|
22
|
+
});
|
|
23
|
+
export const OpenResponsesInputImage = Schema.Struct({
|
|
24
|
+
type: Schema.tag("input_image"),
|
|
25
|
+
image_url: Schema.String,
|
|
26
|
+
detail: Schema.optional(Schema.String),
|
|
27
|
+
});
|
|
28
|
+
export const OpenResponsesInputFile = Schema.Struct({
|
|
29
|
+
type: Schema.tag("input_file"),
|
|
30
|
+
filename: Schema.optional(Schema.String),
|
|
31
|
+
detail: Schema.optional(Schema.String),
|
|
32
|
+
file_data: Schema.optional(Schema.String),
|
|
33
|
+
file_url: Schema.optional(Schema.String),
|
|
34
|
+
});
|
|
35
|
+
const OpenResponsesInputVideo = Schema.Struct({
|
|
36
|
+
type: Schema.tag("input_video"),
|
|
37
|
+
video_url: Schema.String,
|
|
38
|
+
});
|
|
39
|
+
const MediaInput = Schema.Union([OpenResponsesInputImage, OpenResponsesInputFile, OpenResponsesInputVideo]);
|
|
40
|
+
const OpenResponsesInputContent = Schema.Union([OpenResponsesInputText, MediaInput]);
|
|
41
|
+
export const OpenResponsesOutputText = Schema.Struct({
|
|
42
|
+
type: Schema.tag("output_text"),
|
|
43
|
+
text: Schema.String,
|
|
44
|
+
});
|
|
45
|
+
export const MessagePhase = Schema.NullOr(Schema.Literals(["commentary", "final_answer"]));
|
|
46
|
+
export const MessageMetadata = Schema.Struct({
|
|
47
|
+
itemId: Schema.optional(Schema.String),
|
|
48
|
+
status: Schema.optional(Schema.String),
|
|
49
|
+
phase: Schema.optional(MessagePhase),
|
|
50
|
+
});
|
|
51
|
+
const messagePhase = (value) => {
|
|
52
|
+
if (value === null || value === "commentary" || value === "final_answer")
|
|
53
|
+
return value;
|
|
54
|
+
return undefined;
|
|
55
|
+
};
|
|
56
|
+
const OpenResponsesReasoningSummaryText = Schema.Struct({
|
|
57
|
+
type: Schema.tag("summary_text"),
|
|
58
|
+
text: Schema.String,
|
|
59
|
+
});
|
|
60
|
+
export const OpenResponsesReasoningItem = Schema.Struct({
|
|
61
|
+
type: Schema.tag("reasoning"),
|
|
62
|
+
id: Schema.optionalKey(Schema.String),
|
|
63
|
+
summary: Schema.Array(OpenResponsesReasoningSummaryText),
|
|
64
|
+
encrypted_content: optionalNull(Schema.String),
|
|
65
|
+
});
|
|
66
|
+
const OpenResponsesWebSearchCall = Schema.StructWithRest(Schema.Struct({
|
|
67
|
+
type: Schema.tag("web_search_call"),
|
|
68
|
+
id: Schema.String,
|
|
69
|
+
status: Schema.optional(Schema.String),
|
|
70
|
+
action: optionalNull(JsonObject),
|
|
71
|
+
}), [JsonObject]);
|
|
72
|
+
const OpenResponsesFileSearchCall = Schema.StructWithRest(Schema.Struct({
|
|
73
|
+
type: Schema.tag("file_search_call"),
|
|
74
|
+
id: Schema.String,
|
|
75
|
+
status: Schema.optional(Schema.String),
|
|
76
|
+
queries: Schema.optional(Schema.Array(Schema.String)),
|
|
77
|
+
results: optionalNull(Schema.Array(JsonObject)),
|
|
78
|
+
}), [JsonObject]);
|
|
79
|
+
const OpenResponsesCodeInterpreterCall = Schema.StructWithRest(Schema.Struct({
|
|
80
|
+
type: Schema.tag("code_interpreter_call"),
|
|
81
|
+
id: Schema.String,
|
|
82
|
+
status: Schema.optional(Schema.String),
|
|
83
|
+
code: optionalNull(Schema.String),
|
|
84
|
+
container_id: optionalNull(Schema.String),
|
|
85
|
+
outputs: optionalNull(Schema.Array(JsonObject)),
|
|
86
|
+
}), [JsonObject]);
|
|
87
|
+
const OpenResponsesMCPCall = Schema.StructWithRest(Schema.Struct({
|
|
88
|
+
type: Schema.tag("mcp_call"),
|
|
89
|
+
id: Schema.String,
|
|
90
|
+
status: Schema.optional(Schema.String),
|
|
91
|
+
server_label: Schema.optional(Schema.String),
|
|
92
|
+
name: Schema.optional(Schema.String),
|
|
93
|
+
arguments: Schema.optional(Schema.String),
|
|
94
|
+
output: optionalNull(Schema.String),
|
|
95
|
+
error: Schema.optional(Schema.Unknown),
|
|
96
|
+
}), [JsonObject]);
|
|
97
|
+
export const HostedToolItem = Schema.Union([
|
|
98
|
+
OpenResponsesWebSearchCall,
|
|
99
|
+
OpenResponsesFileSearchCall,
|
|
100
|
+
OpenResponsesCodeInterpreterCall,
|
|
101
|
+
OpenResponsesMCPCall,
|
|
102
|
+
]);
|
|
103
|
+
// `function_call_output.output` accepts either a plain string or an ordered
|
|
104
|
+
// array of content items so tools can return images and files in addition to text.
|
|
105
|
+
// https://www.openresponses.org/reference
|
|
106
|
+
const OpenResponsesFunctionCallOutputContent = Schema.Union([
|
|
107
|
+
OpenResponsesInputText,
|
|
108
|
+
OpenResponsesInputImage,
|
|
109
|
+
OpenResponsesInputFile,
|
|
110
|
+
OpenResponsesInputVideo,
|
|
111
|
+
]);
|
|
112
|
+
const OpenResponsesFunctionCallOutput = Schema.Union([
|
|
113
|
+
Schema.String,
|
|
114
|
+
Schema.Array(OpenResponsesFunctionCallOutputContent),
|
|
115
|
+
]);
|
|
116
|
+
export const CompactionItem = Schema.Struct({
|
|
117
|
+
type: Schema.Literal("compaction"),
|
|
118
|
+
id: optionalNull(Schema.String),
|
|
119
|
+
encrypted_content: Schema.String,
|
|
120
|
+
});
|
|
121
|
+
// Kept out of the baseline `InputItem` union: only the OpenAI extension accepts it.
|
|
122
|
+
export const ConfigurationUpdate = Schema.Struct({
|
|
123
|
+
type: Schema.Literal("configuration_update"),
|
|
124
|
+
reasoning: Schema.Struct({ effort: OpenResponsesOptions.ReasoningEffort }),
|
|
125
|
+
});
|
|
126
|
+
export const HostedToolReplay = Schema.StructWithRest(Schema.Struct({
|
|
127
|
+
type: Schema.String,
|
|
128
|
+
id: Schema.String,
|
|
129
|
+
}), [JsonObject]);
|
|
130
|
+
export const Tool = Schema.Struct({
|
|
131
|
+
type: Schema.tag("function"),
|
|
132
|
+
name: Schema.String,
|
|
133
|
+
description: Schema.String,
|
|
134
|
+
parameters: JsonObject,
|
|
135
|
+
strict: Schema.optional(Schema.Boolean),
|
|
136
|
+
});
|
|
137
|
+
export const CustomTool = Schema.Struct({
|
|
138
|
+
type: Schema.tag("custom"),
|
|
139
|
+
name: Schema.String,
|
|
140
|
+
description: Schema.String,
|
|
141
|
+
format: Schema.Union([
|
|
142
|
+
Schema.Struct({ type: Schema.tag("text") }),
|
|
143
|
+
Schema.Struct({
|
|
144
|
+
type: Schema.tag("grammar"),
|
|
145
|
+
syntax: Schema.Literals(["lark", "regex"]),
|
|
146
|
+
definition: Schema.String,
|
|
147
|
+
}),
|
|
148
|
+
]),
|
|
149
|
+
});
|
|
150
|
+
export const HostedTool = Schema.StructWithRest(Schema.Struct({
|
|
151
|
+
type: Schema.String,
|
|
152
|
+
}), [JsonObject]);
|
|
153
|
+
const NamedTool = Schema.Struct({ type: Schema.Literals(["function", "custom"]), name: Schema.String });
|
|
154
|
+
// Tools added mid-conversation. Only the OpenAI extension lowers it; other hosts fold tool updates.
|
|
155
|
+
export const AdditionalTools = Schema.Struct({
|
|
156
|
+
type: Schema.Literal("additional_tools"),
|
|
157
|
+
role: Schema.Literal("developer"),
|
|
158
|
+
tools: Schema.Array(Schema.Union([Tool, CustomTool, HostedTool])),
|
|
159
|
+
});
|
|
160
|
+
export const InputItem = Schema.Union([
|
|
161
|
+
CompactionItem,
|
|
162
|
+
ConfigurationUpdate,
|
|
163
|
+
AdditionalTools,
|
|
164
|
+
Schema.Struct({ type: Schema.tag("message"), role: Schema.tag("system"), content: Schema.String }),
|
|
165
|
+
Schema.Struct({ type: Schema.tag("message"), role: Schema.tag("developer"), content: Schema.String }),
|
|
166
|
+
Schema.Struct({
|
|
167
|
+
type: Schema.tag("message"),
|
|
168
|
+
role: Schema.tag("user"),
|
|
169
|
+
content: Schema.Array(OpenResponsesInputContent),
|
|
170
|
+
id: Schema.optional(Schema.String),
|
|
171
|
+
status: Schema.optional(Schema.String),
|
|
172
|
+
}),
|
|
173
|
+
Schema.Struct({
|
|
174
|
+
type: Schema.tag("message"),
|
|
175
|
+
id: Schema.optionalKey(Schema.String),
|
|
176
|
+
role: Schema.tag("assistant"),
|
|
177
|
+
content: Schema.Array(OpenResponsesOutputText),
|
|
178
|
+
phase: Schema.optionalKey(MessagePhase),
|
|
179
|
+
status: Schema.optional(Schema.String),
|
|
180
|
+
}),
|
|
181
|
+
OpenResponsesReasoningItem,
|
|
182
|
+
Schema.Struct({
|
|
183
|
+
type: Schema.tag("function_call"),
|
|
184
|
+
id: Schema.optionalKey(Schema.String),
|
|
185
|
+
call_id: Schema.String,
|
|
186
|
+
name: Schema.String,
|
|
187
|
+
namespace: Schema.optional(Schema.String),
|
|
188
|
+
arguments: Schema.String,
|
|
189
|
+
}),
|
|
190
|
+
Schema.Struct({
|
|
191
|
+
type: Schema.Literals(["function_call_output", "custom_tool_call_output"]),
|
|
192
|
+
call_id: Schema.String,
|
|
193
|
+
output: OpenResponsesFunctionCallOutput,
|
|
194
|
+
}),
|
|
195
|
+
Schema.Struct({
|
|
196
|
+
type: Schema.tag("custom_tool_call"),
|
|
197
|
+
id: Schema.optionalKey(Schema.String),
|
|
198
|
+
call_id: Schema.String,
|
|
199
|
+
name: Schema.String,
|
|
200
|
+
input: Schema.String,
|
|
201
|
+
}),
|
|
202
|
+
HostedToolItem,
|
|
203
|
+
HostedToolReplay,
|
|
204
|
+
]);
|
|
205
|
+
export const ToolChoice = Schema.Union([
|
|
206
|
+
Schema.Literals(["auto", "none", "required"]),
|
|
207
|
+
NamedTool,
|
|
208
|
+
Schema.Struct({
|
|
209
|
+
type: Schema.tag("allowed_tools"),
|
|
210
|
+
mode: Schema.Literals(["auto", "none", "required"]),
|
|
211
|
+
tools: Schema.Array(NamedTool),
|
|
212
|
+
}),
|
|
213
|
+
]);
|
|
214
|
+
// Fields shared between the HTTP body and the WebSocket `response.create`
|
|
215
|
+
// message. The HTTP body adds `stream: true`; the WebSocket message adds
|
|
216
|
+
// `type: "response.create"`. Defining the shared shape once keeps the two
|
|
217
|
+
// transports in sync without a destructure-and-strip dance.
|
|
218
|
+
export const coreFields = {
|
|
219
|
+
model: Schema.String,
|
|
220
|
+
input: Schema.Array(InputItem),
|
|
221
|
+
instructions: Schema.optional(Schema.String),
|
|
222
|
+
tools: optionalArray(Schema.Union([Tool, CustomTool, HostedTool])),
|
|
223
|
+
tool_choice: Schema.optional(ToolChoice),
|
|
224
|
+
store: Schema.optional(Schema.Boolean),
|
|
225
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
226
|
+
safety_identifier: Schema.optional(Schema.String),
|
|
227
|
+
stream_options: Schema.optional(Schema.Struct({
|
|
228
|
+
include_obfuscation: Schema.optional(Schema.Boolean),
|
|
229
|
+
})),
|
|
230
|
+
top_logprobs: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 20 }))),
|
|
231
|
+
truncation: Schema.optional(OpenResponsesOptions.TruncationSchema),
|
|
232
|
+
service_tier: Schema.optional(OpenResponsesOptions.ServiceTierSchema),
|
|
233
|
+
prompt_cache_key: Schema.optional(Schema.String),
|
|
234
|
+
include: optionalArray(OpenResponsesOptions.ResponseIncludableSchema),
|
|
235
|
+
reasoning: Schema.optional(Schema.Struct({
|
|
236
|
+
effort: Schema.optional(OpenResponsesOptions.ReasoningEffort),
|
|
237
|
+
summary: Schema.optional(Schema.Literals(["auto", "concise", "detailed"])),
|
|
238
|
+
})),
|
|
239
|
+
text: Schema.optional(Schema.Struct({
|
|
240
|
+
verbosity: Schema.optional(OpenResponsesOptions.TextVerbositySchema),
|
|
241
|
+
})),
|
|
242
|
+
max_output_tokens: Schema.optional(Schema.Number),
|
|
243
|
+
max_tool_calls: Schema.optional(Schema.Int),
|
|
244
|
+
parallel_tool_calls: Schema.optional(Schema.Boolean),
|
|
245
|
+
temperature: Schema.optional(Schema.Number),
|
|
246
|
+
top_p: Schema.optional(Schema.Number),
|
|
247
|
+
presence_penalty: Schema.optional(Schema.Number),
|
|
248
|
+
frequency_penalty: Schema.optional(Schema.Number),
|
|
249
|
+
};
|
|
250
|
+
export const OpenResponsesBody = Schema.Struct({
|
|
251
|
+
...coreFields,
|
|
252
|
+
stream: Schema.Literal(true),
|
|
253
|
+
});
|
|
254
|
+
export const OpenResponsesUsage = Schema.StructWithRest(Schema.Struct({
|
|
255
|
+
input_tokens: lenient(Schema.Number),
|
|
256
|
+
input_tokens_details: optionalNull(Schema.StructWithRest(Schema.Struct({
|
|
257
|
+
cached_tokens: lenient(Schema.Number),
|
|
258
|
+
cache_write_tokens: lenient(Schema.Number),
|
|
259
|
+
}), [JsonObject])),
|
|
260
|
+
output_tokens: lenient(Schema.Number),
|
|
261
|
+
output_tokens_details: optionalNull(Schema.StructWithRest(Schema.Struct({ reasoning_tokens: lenient(Schema.Number) }), [JsonObject])),
|
|
262
|
+
total_tokens: lenient(Schema.Number),
|
|
263
|
+
}), [JsonObject]);
|
|
264
|
+
// The spec requires `id` on every output item, but some gateways drop it from
|
|
265
|
+
// later item events (Bedrock Mantle renames it to `item_id` on
|
|
266
|
+
// `output_item.done` and `response.completed.output`). Decode it as optional
|
|
267
|
+
// and let `normalize` recover or mint it once before the parser runs.
|
|
268
|
+
// https://www.openresponses.org/specification#extending-items
|
|
269
|
+
export const StreamItem = Schema.StructWithRest(Schema.Struct({
|
|
270
|
+
type: Schema.String,
|
|
271
|
+
id: optionalNullish(Schema.String),
|
|
272
|
+
call_id: optionalNullish(Schema.String),
|
|
273
|
+
name: optionalNullish(Schema.String),
|
|
274
|
+
namespace: optionalNullish(Schema.String),
|
|
275
|
+
arguments: optionalNullish(Schema.String),
|
|
276
|
+
encrypted_content: optionalNull(Schema.String),
|
|
277
|
+
}), [Schema.Record(Schema.String, Schema.Unknown)]);
|
|
278
|
+
// Responses-compatible providers put error details at the top level, under `error`, or under
|
|
279
|
+
// `response.error`, and gateways reshape them freely: strings, numeric codes, extra fields. Those
|
|
280
|
+
// fields decode as opaque values and `errorDetail` reads them defensively, so an error frame can
|
|
281
|
+
// only fail on invalid JSON and otherwise always classifies with the raw body as the fallback.
|
|
282
|
+
// https://www.openresponses.org/specification
|
|
283
|
+
const asText = (value) => typeof value === "string" && value.length > 0 ? value : typeof value === "number" ? String(value) : undefined;
|
|
284
|
+
const TypedEvent = Schema.StructWithRest(Schema.Struct({
|
|
285
|
+
type: Schema.String,
|
|
286
|
+
delta: optionalNullish(Schema.String),
|
|
287
|
+
arguments: optionalNullish(Schema.String),
|
|
288
|
+
text: optionalNullish(Schema.String),
|
|
289
|
+
// Kept strict: item-scoped events always carry an id, so null means a broken stream.
|
|
290
|
+
item_id: Schema.optional(Schema.String),
|
|
291
|
+
output_index: optionalNullish(Schema.Number),
|
|
292
|
+
summary_index: optionalNullish(Schema.Number),
|
|
293
|
+
// OutputItemAdded/Done permit a null item in the Open Responses OpenAPI schema.
|
|
294
|
+
item: optionalNull(StreamItem),
|
|
295
|
+
response: optionalNullish(Schema.StructWithRest(Schema.Struct({
|
|
296
|
+
id: optionalNullish(Schema.String),
|
|
297
|
+
service_tier: optionalNull(Schema.String),
|
|
298
|
+
incomplete_details: optionalNull(Schema.Struct({ reason: optionalNullish(Schema.String) })),
|
|
299
|
+
output: optionalNullish(Schema.Array(StreamItem)),
|
|
300
|
+
usage: optionalNull(OpenResponsesUsage),
|
|
301
|
+
error: Schema.optional(Schema.Unknown),
|
|
302
|
+
}), [Schema.Record(Schema.String, Schema.Unknown)])),
|
|
303
|
+
code: Schema.optional(Schema.Unknown),
|
|
304
|
+
message: Schema.optional(Schema.Unknown),
|
|
305
|
+
error: Schema.optional(Schema.Unknown),
|
|
306
|
+
status: Schema.optional(Schema.Unknown),
|
|
307
|
+
status_code: Schema.optional(Schema.Unknown),
|
|
308
|
+
}), [Schema.Record(Schema.String, Schema.Unknown)]);
|
|
309
|
+
export const Event = withUntypedFrames(TypedEvent);
|
|
310
|
+
/** Decodes one WebSocket frame. */
|
|
311
|
+
export const decodeChannelEvent = Schema.decodeUnknownEffect(Protocol.jsonEvent(Event));
|
|
312
|
+
const BASE_ADAPTER = { id: ADAPTER, name: NAME };
|
|
313
|
+
// =============================================================================
|
|
314
|
+
// Request Lowering
|
|
315
|
+
// =============================================================================
|
|
316
|
+
export const lowerTool = Effect.fnUntraced(function* (protocolName, tool) {
|
|
317
|
+
if (tool.native !== undefined)
|
|
318
|
+
return yield* ProviderShared.invalidRequest(`${protocolName} does not support provider-native tool ${tool.name}`);
|
|
319
|
+
return {
|
|
320
|
+
type: "function",
|
|
321
|
+
name: tool.name,
|
|
322
|
+
description: tool.description,
|
|
323
|
+
parameters: tool.inputSchema,
|
|
324
|
+
// The common tool definition does not currently express Responses strict-schema policy.
|
|
325
|
+
strict: false,
|
|
326
|
+
};
|
|
327
|
+
});
|
|
328
|
+
export const lowerCustomTool = (tool, custom) => {
|
|
329
|
+
const grammar = OpenAIFreeform.grammar(custom);
|
|
330
|
+
return {
|
|
331
|
+
type: "custom",
|
|
332
|
+
name: tool.name,
|
|
333
|
+
description: OpenAIFreeform.description(tool, custom),
|
|
334
|
+
format: grammar ? { type: "grammar", ...grammar } : { type: "text" },
|
|
335
|
+
};
|
|
336
|
+
};
|
|
337
|
+
export const lowerTools = (tools, adapter, custom) => Effect.forEach(tools, (tool) => {
|
|
338
|
+
if (tool.native !== undefined && adapter.nativeTool)
|
|
339
|
+
return adapter.nativeTool(tool.native);
|
|
340
|
+
const definition = custom.get(tool.name);
|
|
341
|
+
return definition ? Effect.succeed(lowerCustomTool(tool, definition)) : lowerTool(adapter.name, tool);
|
|
342
|
+
});
|
|
343
|
+
export const namedTool = (name, custom) => ({
|
|
344
|
+
type: custom.has(name) ? "custom" : "function",
|
|
345
|
+
name,
|
|
346
|
+
});
|
|
347
|
+
export const lowerToolChoice = (toolChoice, custom) => ProviderShared.matchToolChoice(toolChoice, {
|
|
348
|
+
auto: () => "auto",
|
|
349
|
+
none: () => "none",
|
|
350
|
+
required: () => "required",
|
|
351
|
+
tool: (toolName) => namedTool(toolName, custom),
|
|
352
|
+
});
|
|
353
|
+
// Server-issued item ids need a nonempty prefix and suffix, but the prefix is
|
|
354
|
+
// provider-defined and does not necessarily identify the item's semantic type.
|
|
355
|
+
const itemID = (providerMetadata, providerMetadataKey) => {
|
|
356
|
+
const metadata = providerMetadata?.[providerMetadataKey];
|
|
357
|
+
if (!metadata || typeof metadata.itemId !== "string")
|
|
358
|
+
return undefined;
|
|
359
|
+
const separator = metadata.itemId.indexOf("_");
|
|
360
|
+
return separator > 0 && separator < metadata.itemId.length - 1 ? metadata.itemId : undefined;
|
|
361
|
+
};
|
|
362
|
+
// A call replays as the type its tool is declared with now; the item id only survives when that type is unchanged.
|
|
363
|
+
const lowerToolCall = (part, providerMetadataKey, custom) => {
|
|
364
|
+
const id = OpenAIFreeform.keepsItemID(part.providerMetadata, providerMetadataKey, custom !== undefined)
|
|
365
|
+
? itemID(part.providerMetadata, providerMetadataKey)
|
|
366
|
+
: undefined;
|
|
367
|
+
if (custom)
|
|
368
|
+
return {
|
|
369
|
+
type: "custom_tool_call",
|
|
370
|
+
...(id === undefined ? {} : { id }),
|
|
371
|
+
call_id: part.id,
|
|
372
|
+
name: part.name,
|
|
373
|
+
input: OpenAIFreeform.toRaw(custom, part.input, part.providerMetadata?.[providerMetadataKey]?.header),
|
|
374
|
+
};
|
|
375
|
+
return {
|
|
376
|
+
type: "function_call",
|
|
377
|
+
...(id === undefined ? {} : { id }),
|
|
378
|
+
call_id: part.id,
|
|
379
|
+
name: part.name,
|
|
380
|
+
namespace: part.namespace,
|
|
381
|
+
arguments: ProviderShared.encodeJson(part.input === undefined ? {} : part.input),
|
|
382
|
+
};
|
|
383
|
+
};
|
|
384
|
+
const lowerReasoning = (part, providerMetadataKey) => {
|
|
385
|
+
const metadata = part.providerMetadata?.[providerMetadataKey];
|
|
386
|
+
if (!metadata)
|
|
387
|
+
return undefined;
|
|
388
|
+
const id = itemID(part.providerMetadata, providerMetadataKey);
|
|
389
|
+
const encryptedContent = typeof metadata.reasoningEncryptedContent === "string" || metadata.reasoningEncryptedContent === null
|
|
390
|
+
? metadata.reasoningEncryptedContent
|
|
391
|
+
: undefined;
|
|
392
|
+
if (part.text.length === 0 && !encryptedContent)
|
|
393
|
+
return undefined;
|
|
394
|
+
return {
|
|
395
|
+
type: "reasoning",
|
|
396
|
+
...(id === undefined ? {} : { id }),
|
|
397
|
+
summary: part.text.length > 0 ? [{ type: "summary_text", text: part.text }] : [],
|
|
398
|
+
encrypted_content: encryptedContent,
|
|
399
|
+
};
|
|
400
|
+
};
|
|
401
|
+
const decodeImageDetail = ProviderShared.validateWith(Schema.decodeUnknownEffect(OpenResponsesInputImage.fields.detail));
|
|
402
|
+
const decodeMessageMetadata = ProviderShared.validateWith(Schema.decodeUnknownEffect(MessageMetadata));
|
|
403
|
+
const lowerMedia = Effect.fnUntraced(function* (part, request, adapter) {
|
|
404
|
+
const media = part.media.inline();
|
|
405
|
+
const providerMedia = adapter.lowerMedia?.({ part, media, request });
|
|
406
|
+
if (providerMedia)
|
|
407
|
+
return providerMedia;
|
|
408
|
+
const rawDetail = part.providerMetadata?.[metadataKey(request.model)]?.detail;
|
|
409
|
+
const detail = rawDetail === undefined ? undefined : yield* decodeImageDetail(rawDetail);
|
|
410
|
+
const mime = part.media.mediaType.toLowerCase();
|
|
411
|
+
const url = ProviderShared.mediaUrl(part.media);
|
|
412
|
+
const location = url ?? (yield* ProviderShared.requireInlineMedia(adapter.name, part.media)).dataUrl;
|
|
413
|
+
if (part.media.kind !== "image") {
|
|
414
|
+
if (part.media.kind === "video")
|
|
415
|
+
return { type: "input_video", video_url: location };
|
|
416
|
+
if (url)
|
|
417
|
+
return { type: "input_file", file_url: url, detail };
|
|
418
|
+
return {
|
|
419
|
+
type: "input_file",
|
|
420
|
+
filename: part.filename ?? (mime === "application/pdf" ? "document.pdf" : "file"),
|
|
421
|
+
detail,
|
|
422
|
+
file_data: location,
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
return {
|
|
426
|
+
type: "input_image",
|
|
427
|
+
image_url: location,
|
|
428
|
+
detail,
|
|
429
|
+
};
|
|
430
|
+
});
|
|
431
|
+
const lowerUserContent = Effect.fnUntraced(function* (part, request, adapter) {
|
|
432
|
+
if (part.type === "text")
|
|
433
|
+
return { type: "input_text", text: part.text };
|
|
434
|
+
return yield* lowerMedia(part, request, adapter);
|
|
435
|
+
});
|
|
436
|
+
// Tool results may carry structured text, images, and files. Keep media as provider-native
|
|
437
|
+
// content instead of JSON-stringifying base64 into a prompt string.
|
|
438
|
+
const lowerToolResultContentItem = Effect.fnUntraced(function* (item, request, adapter) {
|
|
439
|
+
if (item.type === "text")
|
|
440
|
+
return { type: "input_text", text: item.text };
|
|
441
|
+
return yield* lowerMedia(ProviderShared.toolFileMedia(item), request, adapter);
|
|
442
|
+
});
|
|
443
|
+
const lowerToolResultOutput = Effect.fnUntraced(function* (part, request, adapter) {
|
|
444
|
+
// Text/json/error results are encoded as a plain string for backward
|
|
445
|
+
// compatibility with existing cassettes and provider expectations.
|
|
446
|
+
if (part.result.type !== "content")
|
|
447
|
+
return ProviderShared.toolResultText(part);
|
|
448
|
+
// Preserve the narrowed array element type when compiled through a consumer package.
|
|
449
|
+
const content = part.result.value;
|
|
450
|
+
return yield* Effect.forEach(content, (item) => lowerToolResultContentItem(item, request, adapter));
|
|
451
|
+
});
|
|
452
|
+
const DEFAULT_EFFORT = "medium";
|
|
453
|
+
// A call's output only follows the whole assistant turn, and Meta's Muse models, directly or through a gateway,
|
|
454
|
+
// reject a commentary message replayed while a call is waiting for it. Text after a call keeps its place without
|
|
455
|
+
// the phase there; other providers accept it and keep the phase.
|
|
456
|
+
const rejectsPendingCommentary = (request) => request.model.provider === "meta" || /(?:^|\/)muse-/i.test(request.model.id);
|
|
457
|
+
export const lowerMessages = Effect.fnUntraced(function* (request, adapter) {
|
|
458
|
+
const input = [];
|
|
459
|
+
const providerMetadataKey = metadataKey(request.model);
|
|
460
|
+
const custom = OpenAIFreeform.tools(request);
|
|
461
|
+
const pendingCommentaryRejected = rejectsPendingCommentary(request);
|
|
462
|
+
const customTool = (part) => part.namespace === undefined ? custom.get(part.name) : undefined;
|
|
463
|
+
for (const message of request.messages) {
|
|
464
|
+
const rawMetadata = message.role === "user" || message.role === "assistant"
|
|
465
|
+
? message.providerMetadata?.[providerMetadataKey]
|
|
466
|
+
: undefined;
|
|
467
|
+
const metadata = rawMetadata === undefined ? undefined : yield* decodeMessageMetadata(rawMetadata);
|
|
468
|
+
if (message.role === "system") {
|
|
469
|
+
const update = effortUpdate(message);
|
|
470
|
+
if (update) {
|
|
471
|
+
// Consecutive updates are rejected, so a newer one replaces its predecessor.
|
|
472
|
+
const last = input.at(-1);
|
|
473
|
+
if (last !== undefined && "type" in last && last.type === "configuration_update")
|
|
474
|
+
input.pop();
|
|
475
|
+
input.push({ type: "configuration_update", reasoning: { effort: update.effort ?? DEFAULT_EFFORT } });
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
// Planning folds every marker on routes whose protocol has no `toolUpdates`, so only adapters with
|
|
479
|
+
// `lowerToolChanges` see one.
|
|
480
|
+
const tools = toolsUpdate(message);
|
|
481
|
+
if (tools && adapter.lowerToolChanges) {
|
|
482
|
+
input.push(...(yield* adapter.lowerToolChanges(tools)));
|
|
483
|
+
if (message.content.length === 0)
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
input.push({
|
|
487
|
+
type: "message",
|
|
488
|
+
role: "developer",
|
|
489
|
+
content: ProviderShared.joinText(yield* ProviderShared.systemUpdateText(adapter.name, message)),
|
|
490
|
+
});
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
493
|
+
if (message.role === "user") {
|
|
494
|
+
const content = yield* Effect.forEach(message.content, (part) => lowerUserContent(part, request, adapter));
|
|
495
|
+
if (content.length > 0)
|
|
496
|
+
input.push({ type: "message", role: "user", content, id: metadata?.itemId, status: metadata?.status });
|
|
497
|
+
continue;
|
|
498
|
+
}
|
|
499
|
+
if (message.role === "assistant") {
|
|
500
|
+
const content = [];
|
|
501
|
+
const reasoningItems = {};
|
|
502
|
+
const hostedToolItems = new Set();
|
|
503
|
+
let calledTool = false;
|
|
504
|
+
const flushText = () => {
|
|
505
|
+
if (content.length === 0)
|
|
506
|
+
return;
|
|
507
|
+
const groups = content.reduce((groups, part) => {
|
|
508
|
+
const partMetadata = part.providerMetadata?.[providerMetadataKey];
|
|
509
|
+
const id = itemID(part.providerMetadata, providerMetadataKey) ?? metadata?.itemId;
|
|
510
|
+
const partPhase = messagePhase(partMetadata?.phase);
|
|
511
|
+
const declared = partPhase === undefined ? metadata?.phase : partPhase;
|
|
512
|
+
const phase = calledTool && declared === "commentary" && pendingCommentaryRejected ? undefined : declared;
|
|
513
|
+
const group = groups.at(-1);
|
|
514
|
+
if (group && group.id === id && group.phase === phase)
|
|
515
|
+
group.parts.push(part);
|
|
516
|
+
else
|
|
517
|
+
groups.push({ id, phase, parts: [part] });
|
|
518
|
+
return groups;
|
|
519
|
+
}, []);
|
|
520
|
+
input.push(...groups.map((group) => ({
|
|
521
|
+
type: "message",
|
|
522
|
+
...(group.id === undefined ? {} : { id: group.id }),
|
|
523
|
+
role: "assistant",
|
|
524
|
+
// Replayed text is a finished input item, even if generation was cut short.
|
|
525
|
+
status: "completed",
|
|
526
|
+
content: group.parts.map((part) => ({ type: "output_text", text: part.text })),
|
|
527
|
+
...(group.phase === undefined ? {} : { phase: group.phase }),
|
|
528
|
+
})));
|
|
529
|
+
content.splice(0, content.length);
|
|
530
|
+
};
|
|
531
|
+
for (const part of message.content) {
|
|
532
|
+
if (part.type === "compaction") {
|
|
533
|
+
flushText();
|
|
534
|
+
if (part.provider !== request.model.provider || part.encrypted === undefined)
|
|
535
|
+
return yield* ProviderShared.invalidRequest("Compaction state must be replayed to its originating provider and API");
|
|
536
|
+
input.push({ type: "compaction", id: part.id, encrypted_content: part.encrypted });
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
539
|
+
if (part.type === "text") {
|
|
540
|
+
content.push(part);
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
if (part.type === "reasoning") {
|
|
544
|
+
flushText();
|
|
545
|
+
const reasoning = lowerReasoning(part, providerMetadataKey);
|
|
546
|
+
if (!reasoning)
|
|
547
|
+
continue;
|
|
548
|
+
const existing = reasoning.id === undefined ? undefined : reasoningItems[reasoning.id];
|
|
549
|
+
if (existing) {
|
|
550
|
+
existing.summary.push(...reasoning.summary);
|
|
551
|
+
if (typeof reasoning.encrypted_content === "string")
|
|
552
|
+
existing.encrypted_content = reasoning.encrypted_content;
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
if (reasoning.id !== undefined)
|
|
556
|
+
reasoningItems[reasoning.id] = reasoning;
|
|
557
|
+
input.push(reasoning);
|
|
558
|
+
continue;
|
|
559
|
+
}
|
|
560
|
+
if (part.type === "tool-call") {
|
|
561
|
+
flushText();
|
|
562
|
+
if (part.providerExecuted === true)
|
|
563
|
+
continue;
|
|
564
|
+
input.push(lowerToolCall(part, providerMetadataKey, customTool(part)));
|
|
565
|
+
calledTool = true;
|
|
566
|
+
continue;
|
|
567
|
+
}
|
|
568
|
+
if (part.type === "tool-result" && part.providerExecuted === true) {
|
|
569
|
+
flushText();
|
|
570
|
+
const id = itemID(part.providerMetadata, providerMetadataKey);
|
|
571
|
+
const hosted = part.result.type !== "json"
|
|
572
|
+
? undefined
|
|
573
|
+
: Schema.is(HostedToolItem)(part.result.value)
|
|
574
|
+
? part.result.value
|
|
575
|
+
: adapter.restoreHostedToolItem?.(part.result.value);
|
|
576
|
+
if (id !== undefined && hosted?.id === id) {
|
|
577
|
+
if (!hostedToolItems.has(id)) {
|
|
578
|
+
input.push(hosted);
|
|
579
|
+
hostedToolItems.add(id);
|
|
580
|
+
}
|
|
581
|
+
continue;
|
|
582
|
+
}
|
|
583
|
+
const content = part.result.type === "content"
|
|
584
|
+
? part.result.value
|
|
585
|
+
: [{ type: "text", text: ProviderShared.toolResultText(part) }];
|
|
586
|
+
input.push({
|
|
587
|
+
type: "message",
|
|
588
|
+
role: "user",
|
|
589
|
+
content: yield* Effect.forEach(content, (item) => lowerToolResultContentItem(item, request, adapter)),
|
|
590
|
+
});
|
|
591
|
+
continue;
|
|
592
|
+
}
|
|
593
|
+
if (part.type === "media") {
|
|
594
|
+
flushText();
|
|
595
|
+
// Responses has no assistant-authored image item; replay generated media (e.g. from Gemini) as user input.
|
|
596
|
+
input.push({
|
|
597
|
+
type: "message",
|
|
598
|
+
role: "user",
|
|
599
|
+
content: [yield* lowerMedia(part, request, adapter)],
|
|
600
|
+
});
|
|
601
|
+
continue;
|
|
602
|
+
}
|
|
603
|
+
return yield* ProviderShared.unsupportedContent(adapter.name, "assistant", [
|
|
604
|
+
"text",
|
|
605
|
+
"reasoning",
|
|
606
|
+
"tool-call",
|
|
607
|
+
"tool-result",
|
|
608
|
+
"media",
|
|
609
|
+
]);
|
|
610
|
+
}
|
|
611
|
+
flushText();
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
for (const part of message.content) {
|
|
615
|
+
input.push({
|
|
616
|
+
type: customTool(part) ? "custom_tool_call_output" : "function_call_output",
|
|
617
|
+
call_id: part.id,
|
|
618
|
+
output: yield* lowerToolResultOutput(part, request, adapter),
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
return input;
|
|
623
|
+
});
|
|
624
|
+
// The system prompt leads `input` as a developer message: GPT-6.2 models never cache top-level `instructions`.
|
|
625
|
+
export const lowerConversation = Effect.fnUntraced(function* (request, adapter) {
|
|
626
|
+
const system = ProviderShared.joinText(request.system);
|
|
627
|
+
return {
|
|
628
|
+
model: request.model.id,
|
|
629
|
+
input: [
|
|
630
|
+
...(system ? [{ type: "message", role: "developer", content: system }] : []),
|
|
631
|
+
...(yield* lowerMessages(request, adapter)),
|
|
632
|
+
],
|
|
633
|
+
};
|
|
634
|
+
});
|
|
635
|
+
export const lowerGeneration = (request, options = OpenResponsesOptions.resolve(request)) => {
|
|
636
|
+
const cacheKey = ProviderShared.promptCacheKey(request);
|
|
637
|
+
const parallelToolCalls = resolveParallelToolCalls(request, options);
|
|
638
|
+
return {
|
|
639
|
+
stream: true,
|
|
640
|
+
max_output_tokens: request.maxTokens,
|
|
641
|
+
temperature: request.temperature,
|
|
642
|
+
top_p: request.topP,
|
|
643
|
+
presence_penalty: request.presencePenalty,
|
|
644
|
+
frequency_penalty: request.frequencyPenalty,
|
|
645
|
+
...(options.store !== undefined ? { store: options.store } : {}),
|
|
646
|
+
...(options.metadata ? { metadata: options.metadata } : {}),
|
|
647
|
+
...(options.safetyIdentifier ? { safety_identifier: options.safetyIdentifier } : {}),
|
|
648
|
+
...(options.streamOptions?.includeObfuscation !== undefined
|
|
649
|
+
? { stream_options: { include_obfuscation: options.streamOptions.includeObfuscation } }
|
|
650
|
+
: {}),
|
|
651
|
+
...(options.topLogprobs !== undefined ? { top_logprobs: options.topLogprobs } : {}),
|
|
652
|
+
...(cacheKey ? { prompt_cache_key: cacheKey } : {}),
|
|
653
|
+
...(options.include ? { include: options.include } : {}),
|
|
654
|
+
...(options.reasoningEffort || options.reasoningSummary
|
|
655
|
+
? { reasoning: { effort: options.reasoningEffort, summary: options.reasoningSummary } }
|
|
656
|
+
: {}),
|
|
657
|
+
...(options.textVerbosity ? { text: { verbosity: options.textVerbosity } } : {}),
|
|
658
|
+
...(options.serviceTier ? { service_tier: options.serviceTier } : {}),
|
|
659
|
+
...(options.maxToolCalls !== undefined ? { max_tool_calls: options.maxToolCalls } : {}),
|
|
660
|
+
...(parallelToolCalls !== undefined ? { parallel_tool_calls: parallelToolCalls } : {}),
|
|
661
|
+
...(options.truncation ? { truncation: options.truncation } : {}),
|
|
662
|
+
};
|
|
663
|
+
};
|
|
664
|
+
export const resolveParallelToolCalls = (request, options = OpenResponsesOptions.resolve(request)) => {
|
|
665
|
+
const configured = options.parallelToolCalls;
|
|
666
|
+
if (configured !== undefined)
|
|
667
|
+
return configured;
|
|
668
|
+
const disabled = request.toolChoice?.disableParallelToolUse;
|
|
669
|
+
return disabled === undefined ? undefined : !disabled;
|
|
670
|
+
};
|
|
671
|
+
export const allowedToolChoice = (options, custom) => {
|
|
672
|
+
const allowed = options.allowedTools;
|
|
673
|
+
if (!allowed)
|
|
674
|
+
return undefined;
|
|
675
|
+
return {
|
|
676
|
+
type: "allowed_tools",
|
|
677
|
+
mode: allowed.mode,
|
|
678
|
+
tools: allowed.toolNames.map((name) => namedTool(name, custom)),
|
|
679
|
+
};
|
|
680
|
+
};
|
|
681
|
+
/** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
|
|
682
|
+
export const fromRequestWithAdapter = Effect.fn("OpenResponses.fromRequestWithAdapter")(function* (request, adapter) {
|
|
683
|
+
const definitions = ProviderShared.flattenTools(request.tools);
|
|
684
|
+
const options = OpenResponsesOptions.resolve(request);
|
|
685
|
+
const custom = OpenAIFreeform.tools(request);
|
|
686
|
+
const updates = resolveEffortUpdates(request, options.reasoningEffort);
|
|
687
|
+
return {
|
|
688
|
+
...(yield* lowerConversation(updates.request, adapter)),
|
|
689
|
+
...lowerGeneration(request, { ...options, reasoningEffort: updates.effort }),
|
|
690
|
+
tools: definitions.length === 0 ? undefined : yield* lowerTools(definitions, adapter, custom),
|
|
691
|
+
tool_choice: allowedToolChoice(options, custom) ??
|
|
692
|
+
(request.toolChoice ? lowerToolChoice(request.toolChoice, custom) : undefined),
|
|
693
|
+
};
|
|
694
|
+
});
|
|
695
|
+
/** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
|
|
696
|
+
export const fromRequest = (request) => fromRequestWithAdapter(request, BASE_ADAPTER);
|
|
697
|
+
// =============================================================================
|
|
698
|
+
// Stream Parsing
|
|
699
|
+
// =============================================================================
|
|
700
|
+
// Responses APIs report `input_tokens` (inclusive total) with a
|
|
701
|
+
// cached-read and cache-write subsets, and `output_tokens` (inclusive total)
|
|
702
|
+
// with a `reasoning_tokens` subset. Pass the totals through and derive the
|
|
703
|
+
// non-cached breakdown.
|
|
704
|
+
export const mapUsage = (usage, providerMetadataKey, ...frames) => {
|
|
705
|
+
if (!usage)
|
|
706
|
+
return undefined;
|
|
707
|
+
const cached = usage.input_tokens_details?.cached_tokens;
|
|
708
|
+
const cacheWrite = usage.input_tokens_details?.cache_write_tokens;
|
|
709
|
+
const reasoning = usage.output_tokens_details?.reasoning_tokens;
|
|
710
|
+
const nonCached = ProviderShared.subtractTokens(usage.input_tokens, ProviderShared.sumTokens(cached, cacheWrite));
|
|
711
|
+
return new Usage({
|
|
712
|
+
inputTokens: usage.input_tokens,
|
|
713
|
+
outputTokens: usage.output_tokens,
|
|
714
|
+
nonCachedInputTokens: nonCached,
|
|
715
|
+
cacheReadInputTokens: cached,
|
|
716
|
+
cacheWriteInputTokens: cacheWrite,
|
|
717
|
+
reasoningTokens: reasoning,
|
|
718
|
+
totalTokens: ProviderShared.totalTokens(usage.input_tokens, usage.output_tokens, usage.total_tokens),
|
|
719
|
+
...ProviderShared.reportedBilling(usage, ...frames),
|
|
720
|
+
providerMetadata: { [providerMetadataKey]: usage },
|
|
721
|
+
});
|
|
722
|
+
};
|
|
723
|
+
// GitHub Copilot lists the filters that ran; the blocking one names its rule in `content_filter_raw`.
|
|
724
|
+
const decodeContentFilters = Schema.decodeUnknownOption(Schema.Array(Schema.Struct({
|
|
725
|
+
source_type: Schema.optional(Schema.String),
|
|
726
|
+
blocked: Schema.optional(Schema.Boolean),
|
|
727
|
+
content_filter_raw: Schema.optional(Schema.Array(Schema.Struct({
|
|
728
|
+
action: Schema.optional(Schema.String),
|
|
729
|
+
label: Schema.optional(Schema.String),
|
|
730
|
+
result: Schema.optional(Schema.Unknown),
|
|
731
|
+
}))),
|
|
732
|
+
content_filter_results: Schema.optional(Schema.Unknown),
|
|
733
|
+
})));
|
|
734
|
+
const contentFilterCategory = (raw) => {
|
|
735
|
+
const blocked = Option.getOrElse(decodeContentFilters(raw), () => []).filter((filter) => filter.blocked);
|
|
736
|
+
const filter = blocked.find((item) => item.source_type === "completion") ?? blocked[0];
|
|
737
|
+
if (!filter)
|
|
738
|
+
return undefined;
|
|
739
|
+
return (filter.content_filter_raw?.find((rule) => rule.action === "BLOCK" && rule.result === true)?.label ??
|
|
740
|
+
ProviderShared.contentFilterCategory(filter.content_filter_results));
|
|
741
|
+
};
|
|
742
|
+
const mapFinishReason = (event, hasFunctionCall) => {
|
|
743
|
+
const reason = event.response?.incomplete_details?.reason;
|
|
744
|
+
if (reason === undefined) {
|
|
745
|
+
if (hasFunctionCall)
|
|
746
|
+
return "tool-calls";
|
|
747
|
+
if (event.type === "response.incomplete")
|
|
748
|
+
return "unknown";
|
|
749
|
+
return "stop";
|
|
750
|
+
}
|
|
751
|
+
if (reason === "max_output_tokens")
|
|
752
|
+
return "length";
|
|
753
|
+
if (reason === "content_filter")
|
|
754
|
+
return "content-filter";
|
|
755
|
+
return hasFunctionCall ? "tool-calls" : "unknown";
|
|
756
|
+
};
|
|
757
|
+
export const metadataKey = (model) => model.route.providerMetadataKey ?? "openresponses";
|
|
758
|
+
export const providerMetadata = (state, metadata) => ({
|
|
759
|
+
[state.providerMetadataKey]: metadata,
|
|
760
|
+
});
|
|
761
|
+
const NO_EVENTS = [];
|
|
762
|
+
// `response.completed` / `response.incomplete` are clean finishes that emit a
|
|
763
|
+
// `finish` event; `response.failed` and `error` are hard failures. All four end
|
|
764
|
+
// the stream, so keep this set aligned with `step` and the protocol's terminal predicate.
|
|
765
|
+
const TERMINAL_TYPES = new Set(["error", "response.completed", "response.incomplete", "response.failed"]);
|
|
766
|
+
export const terminal = (event) => TERMINAL_TYPES.has(event.type);
|
|
767
|
+
const onOutputTextDelta = (state, event, id) => {
|
|
768
|
+
if (!event.delta || state.message?.id !== id)
|
|
769
|
+
return [state, NO_EVENTS];
|
|
770
|
+
const events = [];
|
|
771
|
+
const phase = state.message.phase;
|
|
772
|
+
const metadata = providerMetadata(state, { itemId: id, ...(phase === undefined ? {} : { phase }) });
|
|
773
|
+
const lifecycle = Lifecycle.textStart(state.lifecycle, events, id, metadata);
|
|
774
|
+
return [{ ...state, lifecycle: Lifecycle.textDelta(lifecycle, events, id, event.delta) }, events];
|
|
775
|
+
};
|
|
776
|
+
const onOutputTextDone = (state, event, id) => {
|
|
777
|
+
if (state.message?.id === id) {
|
|
778
|
+
if (state.lifecycle.text.has(id) || event.text === undefined)
|
|
779
|
+
return [state, NO_EVENTS];
|
|
780
|
+
return onOutputTextDelta(state, { ...event, delta: event.text }, id);
|
|
781
|
+
}
|
|
782
|
+
const events = [];
|
|
783
|
+
return [{ ...state, lifecycle: Lifecycle.textEnd(state.lifecycle, events, id) }, events];
|
|
784
|
+
};
|
|
785
|
+
const decodeMessagePart = Schema.decodeUnknownOption(Schema.Union([OpenResponsesOutputText, Schema.Struct({ type: Schema.tag("refusal"), refusal: Schema.String })]));
|
|
786
|
+
const decodeSummaryPart = Schema.decodeUnknownOption(OpenResponsesReasoningSummaryText);
|
|
787
|
+
const decodeReasoningPart = Schema.decodeUnknownOption(Schema.Struct({ type: Schema.tag("reasoning_text"), text: Schema.String }));
|
|
788
|
+
const joinReasoningText = (parts) => {
|
|
789
|
+
if (!parts.some((part) => part !== undefined && part.length > 0))
|
|
790
|
+
return undefined;
|
|
791
|
+
return parts.filter((part) => part !== undefined).join("\n\n");
|
|
792
|
+
};
|
|
793
|
+
const outputItemID = (state, event) => event.output_index === undefined ? event.item_id : (state.outputItems[event.output_index] ?? event.item_id);
|
|
794
|
+
const ITEM_ID_PREFIX = {
|
|
795
|
+
message: "msg",
|
|
796
|
+
reasoning: "rs",
|
|
797
|
+
function_call: "fc",
|
|
798
|
+
custom_tool_call: "ctc",
|
|
799
|
+
compaction: "cmp",
|
|
800
|
+
};
|
|
801
|
+
// An item adopts the id already open in its output slot, since GitHub Copilot
|
|
802
|
+
// sends a different id on every event, including the item's own done event.
|
|
803
|
+
// Otherwise it keeps its id or gets a locally minted one.
|
|
804
|
+
const resolveItem = (state, item, index) => ({
|
|
805
|
+
...item,
|
|
806
|
+
id: (index === undefined ? undefined : state.outputItems[index]) ??
|
|
807
|
+
item.id ??
|
|
808
|
+
`${ITEM_ID_PREFIX[item.type] ?? "item"}_${crypto.randomUUID().replaceAll("-", "")}`,
|
|
809
|
+
});
|
|
810
|
+
// Registered output slots are authoritative for `item_id` routing, and items
|
|
811
|
+
// are resolved here so everything downstream can rely on `item.id`.
|
|
812
|
+
export const normalize = (state, input) => ({
|
|
813
|
+
...input,
|
|
814
|
+
item_id: input.item_id === undefined ? undefined : outputItemID(state, input),
|
|
815
|
+
item: input.item ? resolveItem(state, input.item, input.output_index) : input.item,
|
|
816
|
+
});
|
|
817
|
+
const startReasoningSummaryPart = (state, itemID, index) => {
|
|
818
|
+
const item = state.reasoningItems[itemID];
|
|
819
|
+
if (!item || index === 0 || item.summaryParts[index] !== undefined)
|
|
820
|
+
return [state, NO_EVENTS];
|
|
821
|
+
const events = [];
|
|
822
|
+
const lifecycle = Object.entries(item.summaryParts)
|
|
823
|
+
.filter((entry) => entry[1] !== "concluded")
|
|
824
|
+
.reduce((lifecycle, entry) => Lifecycle.reasoningEnd(lifecycle, events, `${itemID}:${entry[0]}`, providerMetadata(state, { itemId: itemID })), state.lifecycle);
|
|
825
|
+
return [
|
|
826
|
+
{
|
|
827
|
+
...state,
|
|
828
|
+
lifecycle: Lifecycle.reasoningStart(lifecycle, events, `${itemID}:${index}`, providerMetadata(state, { itemId: itemID, reasoningEncryptedContent: item.encryptedContent ?? null })),
|
|
829
|
+
reasoningItems: {
|
|
830
|
+
...state.reasoningItems,
|
|
831
|
+
[itemID]: {
|
|
832
|
+
...item,
|
|
833
|
+
summaryParts: {
|
|
834
|
+
...Object.fromEntries(Object.entries(item.summaryParts).map((entry) => entry[1] === "concluded" ? entry : [entry[0], "concluded"])),
|
|
835
|
+
[index]: "active",
|
|
836
|
+
},
|
|
837
|
+
},
|
|
838
|
+
},
|
|
839
|
+
},
|
|
840
|
+
events,
|
|
841
|
+
];
|
|
842
|
+
};
|
|
843
|
+
export const onReasoningDelta = (state, event, itemID) => {
|
|
844
|
+
const item = state.reasoningItems[itemID];
|
|
845
|
+
if (!event.delta || !item)
|
|
846
|
+
return [state, NO_EVENTS];
|
|
847
|
+
const index = event.summary_index ?? 0;
|
|
848
|
+
if (item.summaryParts[index] === "concluded")
|
|
849
|
+
return [state, NO_EVENTS];
|
|
850
|
+
const [started, emitted] = startReasoningSummaryPart(state, itemID, index);
|
|
851
|
+
const current = started.reasoningItems[itemID];
|
|
852
|
+
if (!current)
|
|
853
|
+
return [started, emitted];
|
|
854
|
+
const events = [...emitted];
|
|
855
|
+
return [
|
|
856
|
+
{
|
|
857
|
+
...started,
|
|
858
|
+
lifecycle: Lifecycle.reasoningDelta(started.lifecycle, events, `${itemID}:${index}`, event.delta),
|
|
859
|
+
reasoningItems: {
|
|
860
|
+
...started.reasoningItems,
|
|
861
|
+
[itemID]: { ...current, deltaIndexes: new Set([...current.deltaIndexes, index]) },
|
|
862
|
+
},
|
|
863
|
+
},
|
|
864
|
+
events,
|
|
865
|
+
];
|
|
866
|
+
};
|
|
867
|
+
// Some compatible gateways emit a reasoning final without streaming any
|
|
868
|
+
// deltas, mirroring `response.output_text.done`. Reconcile the complete text
|
|
869
|
+
// as a single delta unless that summary index already streamed one.
|
|
870
|
+
export const onReasoningDone = (state, event, itemID) => {
|
|
871
|
+
const item = state.reasoningItems[itemID];
|
|
872
|
+
if (!item || event.text === undefined)
|
|
873
|
+
return [state, NO_EVENTS];
|
|
874
|
+
const index = event.summary_index ?? 0;
|
|
875
|
+
if (item.deltaIndexes.has(index))
|
|
876
|
+
return [state, NO_EVENTS];
|
|
877
|
+
return onReasoningDelta(state, { ...event, delta: event.text }, itemID);
|
|
878
|
+
};
|
|
879
|
+
const reasoningMetadata = (state, item) => providerMetadata(state, { itemId: item.id, reasoningEncryptedContent: item.encrypted_content ?? null });
|
|
880
|
+
// Responses APIs normally stream reasoning items in this order:
|
|
881
|
+
// `output_item.added` (reasoning) →
|
|
882
|
+
// `reasoning_summary_part.added` (index=0) →
|
|
883
|
+
// `reasoning_summary_text.delta` →
|
|
884
|
+
// `reasoning_summary_part.done` (index=0) →
|
|
885
|
+
// (repeat for index>0) →
|
|
886
|
+
// `output_item.done` (reasoning).
|
|
887
|
+
// `onOutputItemAdded` seeds the per-item entry, while each later part start is
|
|
888
|
+
// also an implicit boundary for the previous part. This keeps the common event
|
|
889
|
+
// lifecycle ordered when a compatible provider omits or delays a part-done event.
|
|
890
|
+
const onOutputItemAdded = (state, event) => {
|
|
891
|
+
const item = event.item;
|
|
892
|
+
if (!item)
|
|
893
|
+
return [state, NO_EVENTS];
|
|
894
|
+
if (item.type === "message") {
|
|
895
|
+
const phase = messagePhase(item.phase);
|
|
896
|
+
// A new message closes earlier messages, including ones that never streamed.
|
|
897
|
+
const events = [];
|
|
898
|
+
const lifecycle = [...state.lifecycle.text]
|
|
899
|
+
.filter((id) => id !== item.id)
|
|
900
|
+
.reduce((lifecycle, id) => {
|
|
901
|
+
const openPhase = state.message?.id === id ? state.message.phase : undefined;
|
|
902
|
+
return Lifecycle.textEnd(lifecycle, events, id, providerMetadata(state, { itemId: id, ...(openPhase === undefined ? {} : { phase: openPhase }) }));
|
|
903
|
+
}, state.lifecycle);
|
|
904
|
+
return [
|
|
905
|
+
{
|
|
906
|
+
...state,
|
|
907
|
+
lifecycle,
|
|
908
|
+
message: {
|
|
909
|
+
id: item.id,
|
|
910
|
+
phase: phase === undefined && state.message?.id === item.id ? state.message.phase : phase,
|
|
911
|
+
},
|
|
912
|
+
},
|
|
913
|
+
events,
|
|
914
|
+
];
|
|
915
|
+
}
|
|
916
|
+
if (item.type === "reasoning") {
|
|
917
|
+
if (state.reasoningItems[item.id] !== undefined)
|
|
918
|
+
return [state, NO_EVENTS];
|
|
919
|
+
const events = [];
|
|
920
|
+
return [
|
|
921
|
+
{
|
|
922
|
+
...state,
|
|
923
|
+
lifecycle: Lifecycle.reasoningStart(state.lifecycle, events, `${item.id}:0`, reasoningMetadata(state, item)),
|
|
924
|
+
reasoningItems: {
|
|
925
|
+
...state.reasoningItems,
|
|
926
|
+
[item.id]: {
|
|
927
|
+
encryptedContent: item.encrypted_content,
|
|
928
|
+
summaryParts: { 0: "active" },
|
|
929
|
+
deltaIndexes: new Set(),
|
|
930
|
+
},
|
|
931
|
+
},
|
|
932
|
+
},
|
|
933
|
+
events,
|
|
934
|
+
];
|
|
935
|
+
}
|
|
936
|
+
if ((item.type !== "function_call" && item.type !== "custom_tool_call") || !item.call_id)
|
|
937
|
+
return [state, NO_EVENTS];
|
|
938
|
+
if (state.tools[item.id] !== undefined)
|
|
939
|
+
return [state, NO_EVENTS];
|
|
940
|
+
const custom = item.type === "custom_tool_call";
|
|
941
|
+
const metadata = providerMetadata(state, OpenAIFreeform.metadata(item.id, custom));
|
|
942
|
+
const events = [];
|
|
943
|
+
const lifecycle = Lifecycle.start(state.lifecycle);
|
|
944
|
+
const tools = ToolStream.start(state.tools, item.id, {
|
|
945
|
+
id: item.call_id,
|
|
946
|
+
name: item.name ?? "",
|
|
947
|
+
namespace: item.namespace,
|
|
948
|
+
input: custom ? "" : (item.arguments ?? ""),
|
|
949
|
+
providerMetadata: metadata,
|
|
950
|
+
});
|
|
951
|
+
const opened = custom
|
|
952
|
+
? ToolStream.append(tools, item.id, OpenAIFreeform.streamStart(state.custom.get(item.name ?? ""), rawInput(item)))
|
|
953
|
+
: undefined;
|
|
954
|
+
return [
|
|
955
|
+
{ ...state, lifecycle, tools: opened?.tools ?? tools },
|
|
956
|
+
[
|
|
957
|
+
...events,
|
|
958
|
+
StreamEvent.toolInputStart({
|
|
959
|
+
id: item.call_id,
|
|
960
|
+
name: item.name ?? "",
|
|
961
|
+
namespace: item.namespace,
|
|
962
|
+
providerMetadata: metadata,
|
|
963
|
+
}),
|
|
964
|
+
...(opened?.events ?? []),
|
|
965
|
+
],
|
|
966
|
+
];
|
|
967
|
+
};
|
|
968
|
+
const rawInput = (item) => (typeof item.input === "string" ? item.input : "");
|
|
969
|
+
const onReasoningSummaryPartAdded = (state, event) => {
|
|
970
|
+
if (event.item_id === undefined || event.summary_index === undefined)
|
|
971
|
+
return [state, NO_EVENTS];
|
|
972
|
+
return startReasoningSummaryPart(state, event.item_id, event.summary_index);
|
|
973
|
+
};
|
|
974
|
+
const onReasoningSummaryPartDone = (state, event) => {
|
|
975
|
+
if (event.item_id === undefined || event.summary_index === undefined)
|
|
976
|
+
return [state, NO_EVENTS];
|
|
977
|
+
const item = state.reasoningItems[event.item_id];
|
|
978
|
+
if (!item)
|
|
979
|
+
return [state, NO_EVENTS];
|
|
980
|
+
if (item.summaryParts[event.summary_index] !== "active")
|
|
981
|
+
return [state, NO_EVENTS];
|
|
982
|
+
return [
|
|
983
|
+
{
|
|
984
|
+
...state,
|
|
985
|
+
reasoningItems: {
|
|
986
|
+
...state.reasoningItems,
|
|
987
|
+
[event.item_id]: {
|
|
988
|
+
...item,
|
|
989
|
+
summaryParts: {
|
|
990
|
+
...item.summaryParts,
|
|
991
|
+
[event.summary_index]: "can-conclude",
|
|
992
|
+
},
|
|
993
|
+
},
|
|
994
|
+
},
|
|
995
|
+
},
|
|
996
|
+
NO_EVENTS,
|
|
997
|
+
];
|
|
998
|
+
};
|
|
999
|
+
const onFunctionCallArgumentsDelta = Effect.fnUntraced(function* (state, event) {
|
|
1000
|
+
if (event.item_id === undefined)
|
|
1001
|
+
return [state, NO_EVENTS];
|
|
1002
|
+
const tool = state.tools[event.item_id];
|
|
1003
|
+
if (!tool)
|
|
1004
|
+
return [state, NO_EVENTS];
|
|
1005
|
+
const final = event.type === "response.function_call_arguments.done" ? event.arguments : undefined;
|
|
1006
|
+
if (event.type === "response.function_call_arguments.done" && final === undefined)
|
|
1007
|
+
return [state, NO_EVENTS];
|
|
1008
|
+
if (final !== undefined && !final.startsWith(tool.input))
|
|
1009
|
+
return [
|
|
1010
|
+
{ ...state, tools: ToolStream.start(state.tools, event.item_id, { ...tool, input: final }) },
|
|
1011
|
+
NO_EVENTS,
|
|
1012
|
+
];
|
|
1013
|
+
const delta = final === undefined ? event.delta : final.slice(tool.input.length);
|
|
1014
|
+
if (!delta)
|
|
1015
|
+
return [state, NO_EVENTS];
|
|
1016
|
+
const result = ToolStream.appendExisting(state.id, state.tools, event.item_id, delta, `${state.name} tool argument delta is missing its tool call`);
|
|
1017
|
+
if (ToolStream.isError(result))
|
|
1018
|
+
return yield* result;
|
|
1019
|
+
const events = [];
|
|
1020
|
+
const lifecycle = result.events.length ? Lifecycle.start(state.lifecycle) : state.lifecycle;
|
|
1021
|
+
events.push(...result.events);
|
|
1022
|
+
return [{ ...state, lifecycle, tools: result.tools }, events];
|
|
1023
|
+
});
|
|
1024
|
+
const onOutputItemDone = Effect.fnUntraced(function* (state, item) {
|
|
1025
|
+
if (!item)
|
|
1026
|
+
return [state, NO_EVENTS];
|
|
1027
|
+
if (item.type === "compaction") {
|
|
1028
|
+
if (typeof item.encrypted_content !== "string")
|
|
1029
|
+
return yield* ProviderShared.eventError(state.id, "Compaction output is missing its encrypted content");
|
|
1030
|
+
if (state.completedCompactions.has(item.id))
|
|
1031
|
+
return [state, NO_EVENTS];
|
|
1032
|
+
const events = [];
|
|
1033
|
+
const lifecycle = Lifecycle.start(state.lifecycle);
|
|
1034
|
+
events.push(StreamEvent.compaction({
|
|
1035
|
+
provider: state.provider,
|
|
1036
|
+
id: item.id,
|
|
1037
|
+
encrypted: item.encrypted_content,
|
|
1038
|
+
}));
|
|
1039
|
+
return [
|
|
1040
|
+
{ ...state, lifecycle, completedCompactions: new Set([...state.completedCompactions, item.id]) },
|
|
1041
|
+
events,
|
|
1042
|
+
];
|
|
1043
|
+
}
|
|
1044
|
+
if (item.type === "message") {
|
|
1045
|
+
const active = state.message?.id === item.id;
|
|
1046
|
+
const itemPhase = messagePhase(item.phase);
|
|
1047
|
+
const phase = itemPhase === undefined && active ? state.message?.phase : itemPhase;
|
|
1048
|
+
const parts = Array.isArray(item.content) ? item.content : [];
|
|
1049
|
+
const content = [];
|
|
1050
|
+
for (const part of parts) {
|
|
1051
|
+
const decoded = Option.getOrUndefined(decodeMessagePart(part));
|
|
1052
|
+
if (!decoded)
|
|
1053
|
+
continue;
|
|
1054
|
+
content.push(decoded.type === "output_text" ? decoded.text : decoded.refusal);
|
|
1055
|
+
}
|
|
1056
|
+
const text = content.length > 0 ? content.join("") : undefined;
|
|
1057
|
+
const metadata = providerMetadata(state, { itemId: item.id, ...(phase === undefined ? {} : { phase }) });
|
|
1058
|
+
const events = [];
|
|
1059
|
+
const lifecycle = text ? Lifecycle.textStart(state.lifecycle, events, item.id, metadata) : state.lifecycle;
|
|
1060
|
+
return [
|
|
1061
|
+
{
|
|
1062
|
+
...state,
|
|
1063
|
+
lifecycle: Lifecycle.textEnd(lifecycle, events, item.id, metadata, text),
|
|
1064
|
+
message: active ? undefined : state.message,
|
|
1065
|
+
},
|
|
1066
|
+
events,
|
|
1067
|
+
];
|
|
1068
|
+
}
|
|
1069
|
+
if (item.type === "function_call" || item.type === "custom_tool_call") {
|
|
1070
|
+
if (!item.call_id || !item.name)
|
|
1071
|
+
return [state, NO_EVENTS];
|
|
1072
|
+
const custom = item.type === "custom_tool_call";
|
|
1073
|
+
const metadata = providerMetadata(state, OpenAIFreeform.metadata(item.id, custom));
|
|
1074
|
+
const registered = state.tools[item.id] !== undefined;
|
|
1075
|
+
const started = registered
|
|
1076
|
+
? state.tools
|
|
1077
|
+
: ToolStream.start(state.tools, item.id, {
|
|
1078
|
+
id: item.call_id,
|
|
1079
|
+
name: item.name,
|
|
1080
|
+
namespace: item.namespace,
|
|
1081
|
+
providerMetadata: metadata,
|
|
1082
|
+
});
|
|
1083
|
+
// A custom call's final raw text sets its input, so it finishes without an override.
|
|
1084
|
+
const closed = custom
|
|
1085
|
+
? OpenAIFreeform.close(started, [item.id], state.custom, state.providerMetadataKey, rawInput(item))
|
|
1086
|
+
: undefined;
|
|
1087
|
+
const result = yield* ToolStream.finish(state.id, closed?.tools ?? started, item.id, custom ? undefined : item.arguments);
|
|
1088
|
+
const events = [];
|
|
1089
|
+
const finished = [...(closed?.events ?? []), ...(result.events ?? [])];
|
|
1090
|
+
// A done-only call never streamed a start event, so open its lifecycle here.
|
|
1091
|
+
const resultEvents = registered || finished.length === 0
|
|
1092
|
+
? finished
|
|
1093
|
+
: [
|
|
1094
|
+
StreamEvent.toolInputStart({
|
|
1095
|
+
id: item.call_id,
|
|
1096
|
+
name: item.name,
|
|
1097
|
+
namespace: item.namespace,
|
|
1098
|
+
providerMetadata: metadata,
|
|
1099
|
+
}),
|
|
1100
|
+
...finished,
|
|
1101
|
+
];
|
|
1102
|
+
const lifecycle = resultEvents.length ? Lifecycle.start(state.lifecycle) : state.lifecycle;
|
|
1103
|
+
events.push(...resultEvents);
|
|
1104
|
+
return [
|
|
1105
|
+
{
|
|
1106
|
+
...state,
|
|
1107
|
+
lifecycle,
|
|
1108
|
+
hasFunctionCall: resultEvents.some((event) => event.type === "tool-call" || event.type === "tool-input-error") ||
|
|
1109
|
+
state.hasFunctionCall,
|
|
1110
|
+
tools: result.tools,
|
|
1111
|
+
},
|
|
1112
|
+
events,
|
|
1113
|
+
];
|
|
1114
|
+
}
|
|
1115
|
+
if (item.type === "reasoning") {
|
|
1116
|
+
const metadata = reasoningMetadata(state, item);
|
|
1117
|
+
const summaryParts = Array.isArray(item.summary) ? item.summary : [];
|
|
1118
|
+
const summary = [];
|
|
1119
|
+
for (const part of summaryParts) {
|
|
1120
|
+
const decoded = Option.getOrUndefined(decodeSummaryPart(part));
|
|
1121
|
+
// Keep missing entries so the array still matches the provider's summary indexes.
|
|
1122
|
+
summary.push(decoded?.text);
|
|
1123
|
+
}
|
|
1124
|
+
const reasoningParts = Array.isArray(item.content) ? item.content : [];
|
|
1125
|
+
const content = [];
|
|
1126
|
+
for (const part of reasoningParts) {
|
|
1127
|
+
const decoded = Option.getOrUndefined(decodeReasoningPart(part));
|
|
1128
|
+
if (decoded)
|
|
1129
|
+
content.push(decoded.text);
|
|
1130
|
+
}
|
|
1131
|
+
const itemText = joinReasoningText(summary) ?? joinReasoningText(content);
|
|
1132
|
+
const events = [];
|
|
1133
|
+
const reasoningItem = state.reasoningItems[item.id];
|
|
1134
|
+
if (reasoningItem) {
|
|
1135
|
+
const fragments = Object.entries(reasoningItem.summaryParts);
|
|
1136
|
+
let lifecycle = state.lifecycle;
|
|
1137
|
+
for (const [index, status] of fragments) {
|
|
1138
|
+
if (status === "concluded")
|
|
1139
|
+
continue;
|
|
1140
|
+
// Do not repeat earlier summaries that were already emitted as separate fragments.
|
|
1141
|
+
const finalText = fragments.length === 1 ? itemText : summary[Number(index)];
|
|
1142
|
+
lifecycle = Lifecycle.reasoningEnd(lifecycle, events, `${item.id}:${index}`, metadata, finalText || undefined);
|
|
1143
|
+
}
|
|
1144
|
+
const reasoningItems = { ...state.reasoningItems };
|
|
1145
|
+
delete reasoningItems[item.id];
|
|
1146
|
+
return [{ ...state, lifecycle, reasoningItems }, events];
|
|
1147
|
+
}
|
|
1148
|
+
const lifecycle = Lifecycle.start(state.lifecycle);
|
|
1149
|
+
events.push(StreamEvent.reasoningStart({ id: item.id, providerMetadata: metadata }));
|
|
1150
|
+
events.push(StreamEvent.reasoningEnd({ id: item.id, providerMetadata: metadata, text: itemText }));
|
|
1151
|
+
return [{ ...state, lifecycle }, events];
|
|
1152
|
+
}
|
|
1153
|
+
return [state, NO_EVENTS];
|
|
1154
|
+
});
|
|
1155
|
+
const onResponseFinish = Effect.fnUntraced(function* (state, event) {
|
|
1156
|
+
let current = state;
|
|
1157
|
+
const events = [];
|
|
1158
|
+
if (event.type === "response.completed") {
|
|
1159
|
+
// An output item's array position is its output index.
|
|
1160
|
+
for (const item of (event.response?.output ?? []).map((item, index) => resolveItem(state, item, index))) {
|
|
1161
|
+
// Terminal recovery cannot insert a checkpoint before already-emitted content.
|
|
1162
|
+
if (item.type === "compaction" && state.lifecycle.started && !state.completedCompactions.has(item.id))
|
|
1163
|
+
return yield* ProviderShared.eventError(state.id, "Cannot recover a compaction checkpoint after output has been emitted");
|
|
1164
|
+
const recoverable = item.type === "compaction" ||
|
|
1165
|
+
((item.type === "function_call" || item.type === "custom_tool_call") && current.tools[item.id] !== undefined);
|
|
1166
|
+
if (!recoverable)
|
|
1167
|
+
continue;
|
|
1168
|
+
const [next, emitted] = yield* onOutputItemDone(current, item);
|
|
1169
|
+
current = next;
|
|
1170
|
+
events.push(...emitted);
|
|
1171
|
+
}
|
|
1172
|
+
// Some compatible providers omit output_item.done even after completing the response.
|
|
1173
|
+
const open = OpenAIFreeform.close(current.tools, Object.keys(current.tools).filter((key) => current.tools[key]?.providerMetadata?.[current.providerMetadataKey]?.custom === true), current.custom, current.providerMetadataKey);
|
|
1174
|
+
events.push(...open.events);
|
|
1175
|
+
const pending = yield* ToolStream.finishAll(current.id, open.tools);
|
|
1176
|
+
current = {
|
|
1177
|
+
...current,
|
|
1178
|
+
tools: pending.tools,
|
|
1179
|
+
hasFunctionCall: current.hasFunctionCall ||
|
|
1180
|
+
pending.events.some((event) => event.type === "tool-call" || event.type === "tool-input-error"),
|
|
1181
|
+
};
|
|
1182
|
+
events.push(...pending.events);
|
|
1183
|
+
}
|
|
1184
|
+
const reason = mapFinishReason(event, current.hasFunctionCall);
|
|
1185
|
+
const lifecycle = Lifecycle.finish(current.lifecycle, events, {
|
|
1186
|
+
reason,
|
|
1187
|
+
raw: event.response?.incomplete_details?.reason,
|
|
1188
|
+
...(reason === "content-filter" ? { detail: contentFilterCategory(event.response?.content_filters) } : {}),
|
|
1189
|
+
// Copilot reports its billing on the terminal event, beside `response`.
|
|
1190
|
+
usage: mapUsage(event.response?.usage, current.providerMetadataKey, event, event.response),
|
|
1191
|
+
providerMetadata: event.response?.id || event.response?.service_tier
|
|
1192
|
+
? providerMetadata(current, {
|
|
1193
|
+
responseId: event.response.id,
|
|
1194
|
+
serviceTier: event.response.service_tier,
|
|
1195
|
+
})
|
|
1196
|
+
: undefined,
|
|
1197
|
+
});
|
|
1198
|
+
return [{ ...current, lifecycle }, events];
|
|
1199
|
+
});
|
|
1200
|
+
/** Error code and message from wherever the frame put them; top-level fields win over nested ones. */
|
|
1201
|
+
export const errorDetail = (event) => {
|
|
1202
|
+
const raw = event.error ?? event.response?.error;
|
|
1203
|
+
const nested = typeof raw === "string" ? { message: raw } : ProviderShared.isRecord(raw) ? raw : undefined;
|
|
1204
|
+
return {
|
|
1205
|
+
message: asText(event.message) ?? asText(nested?.message),
|
|
1206
|
+
code: asText(event.code) ?? asText(nested?.code),
|
|
1207
|
+
};
|
|
1208
|
+
};
|
|
1209
|
+
// Prefix the code when both are present (`rate_limit_exceeded: Slow down`) so the failure mode is
|
|
1210
|
+
// visible; fall back to the raw frame rather than a generic message when neither decodes.
|
|
1211
|
+
export const providerFailure = (event, fallback, body = ProviderShared.encodeJson(event)) => {
|
|
1212
|
+
const detail = errorDetail(event);
|
|
1213
|
+
const summary = detail.message && detail.code ? `${detail.code}: ${detail.message}` : (detail.message ?? detail.code);
|
|
1214
|
+
const message = summary ?? (body === "{}" ? fallback : body);
|
|
1215
|
+
const status = typeof event.status === "number"
|
|
1216
|
+
? event.status
|
|
1217
|
+
: typeof event.status_code === "number"
|
|
1218
|
+
? event.status_code
|
|
1219
|
+
: undefined;
|
|
1220
|
+
const reason = event.type === "error" &&
|
|
1221
|
+
event.error === undefined &&
|
|
1222
|
+
event.response === undefined &&
|
|
1223
|
+
summary === undefined &&
|
|
1224
|
+
status === undefined
|
|
1225
|
+
? new ProviderInternalError({ message, body })
|
|
1226
|
+
: classifyProviderFailure({ message, status, rawBody: body });
|
|
1227
|
+
return new AIError({ reason });
|
|
1228
|
+
};
|
|
1229
|
+
// Callers must pass events through `normalize` first. The OpenAPI requires
|
|
1230
|
+
// string IDs but imposes no minLength; empty is not missing.
|
|
1231
|
+
export const step = (state, event) => {
|
|
1232
|
+
if (event.type === "response.output_text.delta" || event.type === "response.output_text.done") {
|
|
1233
|
+
if (event.item_id === undefined)
|
|
1234
|
+
return ProviderShared.eventError(state.id, `${event.type} is missing item_id`);
|
|
1235
|
+
return Effect.succeed(event.type === "response.output_text.delta"
|
|
1236
|
+
? onOutputTextDelta(state, event, event.item_id)
|
|
1237
|
+
: onOutputTextDone(state, event, event.item_id));
|
|
1238
|
+
}
|
|
1239
|
+
if (event.type === "response.refusal.delta" || event.type === "response.refusal.done") {
|
|
1240
|
+
const value = event.type === "response.refusal.delta" ? event.delta : event.refusal;
|
|
1241
|
+
if (event.item_id === undefined || typeof value !== "string")
|
|
1242
|
+
return ProviderShared.eventError(state.id, `${event.type} is malformed`);
|
|
1243
|
+
return Effect.succeed(event.type === "response.refusal.delta"
|
|
1244
|
+
? onOutputTextDelta(state, event, event.item_id)
|
|
1245
|
+
: onOutputTextDone(state, { ...event, text: value }, event.item_id));
|
|
1246
|
+
}
|
|
1247
|
+
if (event.type === "response.reasoning.delta" || event.type === "response.reasoning_summary_text.delta") {
|
|
1248
|
+
if (event.item_id === undefined)
|
|
1249
|
+
return ProviderShared.eventError(state.id, `${event.type} is missing item_id`);
|
|
1250
|
+
return Effect.succeed(onReasoningDelta(state, event, event.item_id));
|
|
1251
|
+
}
|
|
1252
|
+
if (event.type === "response.reasoning.done" ||
|
|
1253
|
+
event.type === "response.reasoning_summary_text.done" ||
|
|
1254
|
+
event.type === "response.reasoning_text.done") {
|
|
1255
|
+
if (event.item_id === undefined)
|
|
1256
|
+
return ProviderShared.eventError(state.id, `${event.type} is missing item_id`);
|
|
1257
|
+
return Effect.succeed(onReasoningDone(state, event, event.item_id));
|
|
1258
|
+
}
|
|
1259
|
+
if (event.type === "response.reasoning_summary_part.added")
|
|
1260
|
+
return event.item_id !== undefined
|
|
1261
|
+
? Effect.succeed(onReasoningSummaryPartAdded(state, event))
|
|
1262
|
+
: ProviderShared.eventError(state.id, `${event.type} is missing item_id`);
|
|
1263
|
+
if (event.type === "response.reasoning_summary_part.done")
|
|
1264
|
+
return event.item_id !== undefined
|
|
1265
|
+
? Effect.succeed(onReasoningSummaryPartDone(state, event))
|
|
1266
|
+
: ProviderShared.eventError(state.id, `${event.type} is missing item_id`);
|
|
1267
|
+
if (event.type === "response.output_item.added") {
|
|
1268
|
+
if (event.item?.type === "reasoning" &&
|
|
1269
|
+
state.reasoningItems[event.item.id] === undefined &&
|
|
1270
|
+
state.lifecycle.reasoning.size > 0)
|
|
1271
|
+
return ProviderShared.eventError(state.id, `${event.type} started reasoning before the previous item ended`);
|
|
1272
|
+
return Effect.succeed(onOutputItemAdded(event.output_index !== undefined && event.item
|
|
1273
|
+
? { ...state, outputItems: { ...state.outputItems, [event.output_index]: event.item.id } }
|
|
1274
|
+
: state, event));
|
|
1275
|
+
}
|
|
1276
|
+
if (event.type === "response.function_call_arguments.delta" || event.type === "response.function_call_arguments.done")
|
|
1277
|
+
return event.item_id !== undefined
|
|
1278
|
+
? onFunctionCallArgumentsDelta(state, event)
|
|
1279
|
+
: ProviderShared.eventError(state.id, `${event.type} is missing item_id`);
|
|
1280
|
+
if (event.type === "response.custom_tool_call_input.delta")
|
|
1281
|
+
return event.item_id !== undefined
|
|
1282
|
+
? onFunctionCallArgumentsDelta(state, {
|
|
1283
|
+
...event,
|
|
1284
|
+
type: "response.function_call_arguments.delta",
|
|
1285
|
+
delta: OpenAIFreeform.streamDelta(event.delta ?? ""),
|
|
1286
|
+
})
|
|
1287
|
+
: ProviderShared.eventError(state.id, `${event.type} is missing item_id`);
|
|
1288
|
+
if (event.type === "response.output_item.done")
|
|
1289
|
+
return onOutputItemDone(state, event.item);
|
|
1290
|
+
if (event.type === "response.completed" || event.type === "response.incomplete")
|
|
1291
|
+
return onResponseFinish(state, event);
|
|
1292
|
+
if (event.type === "response.failed")
|
|
1293
|
+
return providerFailure(event, `${state.name} response failed`);
|
|
1294
|
+
if (event.type === "error")
|
|
1295
|
+
return providerFailure(event, `${state.name} stream error`);
|
|
1296
|
+
return Effect.succeed([state, NO_EVENTS]);
|
|
1297
|
+
};
|
|
1298
|
+
// =============================================================================
|
|
1299
|
+
// Protocol
|
|
1300
|
+
// =============================================================================
|
|
1301
|
+
/**
|
|
1302
|
+
* The provider-neutral Open Responses protocol. Provider-specific Responses
|
|
1303
|
+
* implementations compose this baseline with their own tools and event variants.
|
|
1304
|
+
*/
|
|
1305
|
+
export const initial = (request, adapter = BASE_ADAPTER) => ({
|
|
1306
|
+
provider: request.model.provider,
|
|
1307
|
+
completedCompactions: new Set(),
|
|
1308
|
+
id: adapter.id,
|
|
1309
|
+
name: adapter.name,
|
|
1310
|
+
providerMetadataKey: metadataKey(request.model),
|
|
1311
|
+
hasFunctionCall: false,
|
|
1312
|
+
tools: ToolStream.empty(),
|
|
1313
|
+
custom: OpenAIFreeform.tools(request),
|
|
1314
|
+
lifecycle: Lifecycle.initial(),
|
|
1315
|
+
outputItems: {},
|
|
1316
|
+
message: undefined,
|
|
1317
|
+
reasoningItems: {},
|
|
1318
|
+
});
|
|
1319
|
+
export const protocol = Protocol.make({
|
|
1320
|
+
id: ADAPTER,
|
|
1321
|
+
body: {
|
|
1322
|
+
schema: OpenResponsesBody,
|
|
1323
|
+
from: fromRequest,
|
|
1324
|
+
},
|
|
1325
|
+
stream: {
|
|
1326
|
+
event: Protocol.jsonEvent(Event),
|
|
1327
|
+
initial,
|
|
1328
|
+
step: (state, event) => step(state, normalize(state, event)),
|
|
1329
|
+
terminal,
|
|
1330
|
+
},
|
|
1331
|
+
// Not every Open Responses server accepts `configuration_update`, so only models that opt in get it.
|
|
1332
|
+
supportsEffortUpdates: (request) => request.model.capabilities?.reasoning?.updates === true,
|
|
1333
|
+
});
|
|
1334
|
+
export const httpTransport = HttpTransport.sseJson.with();
|
|
1335
|
+
export * as OpenResponses from "./open-responses.js";
|