@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,1140 @@
|
|
|
1
|
+
import { Effect, Option, Schema } from "effect";
|
|
2
|
+
import { Tool } from "@radheim/schema/tool";
|
|
3
|
+
import { Route } from "../route/client.js";
|
|
4
|
+
import { Auth } from "../route/auth.js";
|
|
5
|
+
import { Endpoint } from "../route/endpoint.js";
|
|
6
|
+
import { Framing } from "../route/framing.js";
|
|
7
|
+
import { HttpTransport } from "../route/transport/index.js";
|
|
8
|
+
import { Protocol } from "../route/protocol.js";
|
|
9
|
+
import { AIError, AIErrorReason, InvalidProviderOutputError, StreamEvent, ProviderInternalError, UnknownProviderError, Usage, } from "../schema/index.js";
|
|
10
|
+
import { classifyProviderFailure } from "../provider-error.js";
|
|
11
|
+
import { JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared.js";
|
|
12
|
+
import { placesMarkers, requestTTL } from "../cache-policy.js";
|
|
13
|
+
import * as Cache from "./utils/cache.js";
|
|
14
|
+
import { resolveParallelToolCalls } from "./open-responses.js";
|
|
15
|
+
import { OpenResponsesOptions } from "./utils/open-responses-options.js";
|
|
16
|
+
import { Lifecycle } from "./utils/lifecycle.js";
|
|
17
|
+
import { ToolStream } from "./utils/tool-stream.js";
|
|
18
|
+
import { OpenAIFreeform } from "./openai-freeform.js";
|
|
19
|
+
const ADAPTER = "openai-chat";
|
|
20
|
+
const RESERVED_REASONING_FIELDS = new Set(["role", "content", "refusal", "tool_calls"]);
|
|
21
|
+
export const DEFAULT_BASE_URL = "https://api.openai.com/v1";
|
|
22
|
+
export const PATH = "/chat/completions";
|
|
23
|
+
// =============================================================================
|
|
24
|
+
// Request Body Schema
|
|
25
|
+
// =============================================================================
|
|
26
|
+
// The body schema is the provider-native JSON body. `fromRequest` below builds
|
|
27
|
+
// this shape from the common `LLMRequest`, then `Route.make` validates and
|
|
28
|
+
// JSON-encodes it before transport.
|
|
29
|
+
const OpenAIChatCacheControl = Schema.Struct({
|
|
30
|
+
type: Schema.Literal("ephemeral"),
|
|
31
|
+
ttl: Schema.optional(Schema.String),
|
|
32
|
+
});
|
|
33
|
+
const OpenAIChatTool = Schema.Union([
|
|
34
|
+
Schema.Struct({
|
|
35
|
+
type: Schema.tag("function"),
|
|
36
|
+
function: Schema.Struct({
|
|
37
|
+
name: Schema.String,
|
|
38
|
+
description: Schema.String,
|
|
39
|
+
parameters: JsonObject,
|
|
40
|
+
strict: Schema.optional(Schema.Boolean),
|
|
41
|
+
}),
|
|
42
|
+
cache_control: Schema.optional(OpenAIChatCacheControl),
|
|
43
|
+
}),
|
|
44
|
+
Schema.Struct({
|
|
45
|
+
type: Schema.tag("custom"),
|
|
46
|
+
custom: Schema.Struct({
|
|
47
|
+
name: Schema.String,
|
|
48
|
+
description: Schema.String,
|
|
49
|
+
format: Schema.Union([
|
|
50
|
+
Schema.Struct({ type: Schema.tag("text") }),
|
|
51
|
+
Schema.Struct({
|
|
52
|
+
type: Schema.tag("grammar"),
|
|
53
|
+
grammar: Schema.Struct({ syntax: Schema.Literals(["lark", "regex"]), definition: Schema.String }),
|
|
54
|
+
}),
|
|
55
|
+
]),
|
|
56
|
+
}),
|
|
57
|
+
cache_control: Schema.optional(OpenAIChatCacheControl),
|
|
58
|
+
}),
|
|
59
|
+
]);
|
|
60
|
+
// Gemini's OpenAI-compatible surface carries thought signatures in tool call
|
|
61
|
+
// `extra_content` and rejects replayed parallel calls without them:
|
|
62
|
+
// https://ai.google.dev/gemini-api/docs/thinking#signatures
|
|
63
|
+
const ExtraContent = Schema.Struct({
|
|
64
|
+
google: Schema.Struct({ thought_signature: Schema.String }),
|
|
65
|
+
});
|
|
66
|
+
const decodeExtraContent = (value) => Option.getOrUndefined(Schema.decodeUnknownOption(ExtraContent)(value));
|
|
67
|
+
export const OpenAIChatAssistantToolCall = Schema.Struct({
|
|
68
|
+
id: Schema.String,
|
|
69
|
+
type: Schema.tag("function"),
|
|
70
|
+
function: Schema.Struct({
|
|
71
|
+
name: Schema.String,
|
|
72
|
+
arguments: Schema.String,
|
|
73
|
+
}),
|
|
74
|
+
extra_content: Schema.optional(ExtraContent),
|
|
75
|
+
});
|
|
76
|
+
export const OpenAIChatAssistantCustomToolCall = Schema.Struct({
|
|
77
|
+
id: Schema.String,
|
|
78
|
+
type: Schema.tag("custom"),
|
|
79
|
+
custom: Schema.Struct({
|
|
80
|
+
name: Schema.String,
|
|
81
|
+
input: Schema.String,
|
|
82
|
+
}),
|
|
83
|
+
});
|
|
84
|
+
// `reasoning_details` carries two dialects. OpenRouter's `reasoning.*` entries
|
|
85
|
+
// must be replayed unmodified (`index` included), so they keep every field they
|
|
86
|
+
// arrived with. Kimi's OpenAI-compatible surface streams preserved thinking as
|
|
87
|
+
// bare `summary` / `encrypted` entries keyed by a stream-only `index`; Kimi does
|
|
88
|
+
// not document this publicly, so the handling follows Kimi Code (Kimi's own
|
|
89
|
+
// client): merge summary deltas by `index`, replay without `index`, and always
|
|
90
|
+
// send `reasoning_content` alongside. Anything else is dropped at the boundary.
|
|
91
|
+
const OpenRouterDetailFields = {
|
|
92
|
+
id: Schema.optional(Schema.NullOr(Schema.String)),
|
|
93
|
+
format: Schema.optional(Schema.String),
|
|
94
|
+
index: Schema.optional(Schema.Number),
|
|
95
|
+
signature: Schema.optional(Schema.NullOr(Schema.String)),
|
|
96
|
+
};
|
|
97
|
+
const ReasoningDetail = Schema.Union([
|
|
98
|
+
Schema.StructWithRest(Schema.Struct({
|
|
99
|
+
type: Schema.Literal("reasoning.text"),
|
|
100
|
+
text: Schema.optional(Schema.String),
|
|
101
|
+
...OpenRouterDetailFields,
|
|
102
|
+
}), [Schema.Record(Schema.String, Schema.Unknown)]),
|
|
103
|
+
Schema.StructWithRest(Schema.Struct({
|
|
104
|
+
type: Schema.Literal("reasoning.summary"),
|
|
105
|
+
summary: Schema.optional(Schema.String),
|
|
106
|
+
...OpenRouterDetailFields,
|
|
107
|
+
}), [Schema.Record(Schema.String, Schema.Unknown)]),
|
|
108
|
+
Schema.StructWithRest(Schema.Struct({ type: Schema.Literal("reasoning.encrypted"), data: Schema.String, ...OpenRouterDetailFields }), [Schema.Record(Schema.String, Schema.Unknown)]),
|
|
109
|
+
Schema.Struct({ type: Schema.Literal("summary"), summary: Schema.String, index: Schema.optional(Schema.Number) }),
|
|
110
|
+
Schema.Struct({ type: Schema.Literal("encrypted"), encrypted: Schema.String, index: Schema.optional(Schema.Number) }),
|
|
111
|
+
]);
|
|
112
|
+
const decodeReasoningDetail = Schema.decodeUnknownOption(ReasoningDetail);
|
|
113
|
+
const knownReasoningDetails = (details) => details.flatMap((detail) => Option.toArray(decodeReasoningDetail(detail)));
|
|
114
|
+
const OpenAIChatTextContent = Schema.Struct({
|
|
115
|
+
type: Schema.Literal("text"),
|
|
116
|
+
text: Schema.String,
|
|
117
|
+
cache_control: Schema.optional(OpenAIChatCacheControl),
|
|
118
|
+
});
|
|
119
|
+
const OpenAIChatUserContent = Schema.Union([
|
|
120
|
+
OpenAIChatTextContent,
|
|
121
|
+
Schema.Struct({
|
|
122
|
+
type: Schema.Literal("image_url"),
|
|
123
|
+
image_url: Schema.Struct({ url: Schema.String }),
|
|
124
|
+
}),
|
|
125
|
+
Schema.Struct({
|
|
126
|
+
type: Schema.Literal("video_url"),
|
|
127
|
+
video_url: Schema.Struct({ url: Schema.String }),
|
|
128
|
+
}),
|
|
129
|
+
Schema.Struct({
|
|
130
|
+
type: Schema.Literal("file"),
|
|
131
|
+
file: Schema.Struct({ filename: Schema.String, file_data: Schema.String }),
|
|
132
|
+
}),
|
|
133
|
+
]);
|
|
134
|
+
export const OpenAIChatMessage = Schema.Union([
|
|
135
|
+
Schema.Struct({
|
|
136
|
+
role: Schema.Literal("system"),
|
|
137
|
+
content: Schema.Union([Schema.String, Schema.Array(OpenAIChatUserContent)]),
|
|
138
|
+
}),
|
|
139
|
+
Schema.Struct({
|
|
140
|
+
role: Schema.Literal("user"),
|
|
141
|
+
content: Schema.Union([Schema.String, Schema.Array(OpenAIChatUserContent)]),
|
|
142
|
+
}),
|
|
143
|
+
Schema.StructWithRest(Schema.Struct({
|
|
144
|
+
role: Schema.Literal("assistant"),
|
|
145
|
+
content: Schema.NullOr(Schema.Union([Schema.String, Schema.Array(OpenAIChatTextContent)])),
|
|
146
|
+
tool_calls: optionalArray(Schema.Union([OpenAIChatAssistantToolCall, OpenAIChatAssistantCustomToolCall])),
|
|
147
|
+
reasoning_content: Schema.optional(Schema.String),
|
|
148
|
+
reasoning: Schema.optional(Schema.String),
|
|
149
|
+
reasoning_text: Schema.optional(Schema.String),
|
|
150
|
+
reasoning_details: Schema.optional(Schema.Unknown),
|
|
151
|
+
reasoning_opaque: Schema.optional(Schema.String),
|
|
152
|
+
}), [Schema.Record(Schema.String, Schema.Unknown)]),
|
|
153
|
+
Schema.Struct({
|
|
154
|
+
role: Schema.Literal("tool"),
|
|
155
|
+
tool_call_id: Schema.String,
|
|
156
|
+
content: Schema.Union([Schema.String, Schema.Array(OpenAIChatTextContent)]),
|
|
157
|
+
}),
|
|
158
|
+
]).pipe(Schema.toTaggedUnion("role"));
|
|
159
|
+
const OpenAIChatToolChoice = Schema.Union([
|
|
160
|
+
Schema.Literals(["auto", "none", "required"]),
|
|
161
|
+
Schema.Struct({
|
|
162
|
+
type: Schema.tag("function"),
|
|
163
|
+
function: Schema.Struct({ name: Schema.String }),
|
|
164
|
+
}),
|
|
165
|
+
Schema.Struct({
|
|
166
|
+
type: Schema.tag("custom"),
|
|
167
|
+
custom: Schema.Struct({ name: Schema.String }),
|
|
168
|
+
}),
|
|
169
|
+
]);
|
|
170
|
+
export const bodyFields = {
|
|
171
|
+
model: Schema.String,
|
|
172
|
+
messages: Schema.Array(OpenAIChatMessage),
|
|
173
|
+
tools: optionalArray(OpenAIChatTool),
|
|
174
|
+
tool_choice: Schema.optional(OpenAIChatToolChoice),
|
|
175
|
+
stream: Schema.Literal(true),
|
|
176
|
+
stream_options: Schema.optional(Schema.Struct({ include_usage: Schema.Boolean })),
|
|
177
|
+
store: Schema.optional(Schema.Boolean),
|
|
178
|
+
prompt_cache_key: Schema.optional(Schema.String),
|
|
179
|
+
prompt_cache_retention: Schema.optional(Schema.String),
|
|
180
|
+
prompt_cache_options: Schema.optional(Schema.Struct({ ttl: Schema.optional(Schema.String) })),
|
|
181
|
+
reasoning_effort: Schema.optional(OpenResponsesOptions.ReasoningEffort),
|
|
182
|
+
verbosity: Schema.optional(OpenResponsesOptions.TextVerbositySchema),
|
|
183
|
+
service_tier: Schema.optional(OpenResponsesOptions.ServiceTierSchema),
|
|
184
|
+
parallel_tool_calls: Schema.optional(Schema.Boolean),
|
|
185
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
186
|
+
safety_identifier: Schema.optional(Schema.String),
|
|
187
|
+
tool_stream: Schema.optional(Schema.Boolean),
|
|
188
|
+
max_completion_tokens: Schema.optional(Schema.Number),
|
|
189
|
+
max_tokens: Schema.optional(Schema.Number),
|
|
190
|
+
temperature: Schema.optional(Schema.Number),
|
|
191
|
+
top_p: Schema.optional(Schema.Number),
|
|
192
|
+
frequency_penalty: Schema.optional(Schema.Number),
|
|
193
|
+
presence_penalty: Schema.optional(Schema.Number),
|
|
194
|
+
seed: Schema.optional(Schema.Number),
|
|
195
|
+
stop: optionalArray(Schema.String),
|
|
196
|
+
};
|
|
197
|
+
const OpenAIChatBody = Schema.Struct(bodyFields);
|
|
198
|
+
// =============================================================================
|
|
199
|
+
// Streaming Event Schema
|
|
200
|
+
// =============================================================================
|
|
201
|
+
// The event schema is one decoded SSE `data:` payload. `Framing.sse` splits the
|
|
202
|
+
// byte stream into strings, then `Protocol.jsonEvent` decodes each string into
|
|
203
|
+
// this provider-native event shape.
|
|
204
|
+
export const OpenAIChatUsage = Schema.StructWithRest(Schema.Struct({
|
|
205
|
+
prompt_tokens: optionalNull(Schema.Number),
|
|
206
|
+
completion_tokens: optionalNull(Schema.Number),
|
|
207
|
+
total_tokens: optionalNull(Schema.Number),
|
|
208
|
+
// Provider-specific cache accounting fields.
|
|
209
|
+
cached_tokens: optionalNull(Schema.Number),
|
|
210
|
+
prompt_cache_hit_tokens: optionalNull(Schema.Number),
|
|
211
|
+
cache_read_input_tokens: optionalNull(Schema.Number),
|
|
212
|
+
cache_created_input_tokens: optionalNull(Schema.Number),
|
|
213
|
+
// GitHub Copilot reports reasoning at the top level instead of in `completion_tokens_details`.
|
|
214
|
+
reasoning_tokens: optionalNull(Schema.Number),
|
|
215
|
+
prompt_tokens_details: optionalNull(Schema.StructWithRest(Schema.Struct({
|
|
216
|
+
cached_tokens: optionalNull(Schema.Number),
|
|
217
|
+
cache_write_tokens: optionalNull(Schema.Number),
|
|
218
|
+
}), [Schema.Record(Schema.String, Schema.Unknown)])),
|
|
219
|
+
completion_tokens_details: optionalNull(Schema.StructWithRest(Schema.Struct({
|
|
220
|
+
reasoning_tokens: optionalNull(Schema.Number),
|
|
221
|
+
accepted_prediction_tokens: optionalNull(Schema.Number),
|
|
222
|
+
rejected_prediction_tokens: optionalNull(Schema.Number),
|
|
223
|
+
}), [Schema.Record(Schema.String, Schema.Unknown)])),
|
|
224
|
+
}), [Schema.Record(Schema.String, Schema.Unknown)]);
|
|
225
|
+
const OpenAIChatToolCallDeltaFunction = Schema.Struct({
|
|
226
|
+
name: optionalNull(Schema.String),
|
|
227
|
+
arguments: optionalNull(Schema.String),
|
|
228
|
+
});
|
|
229
|
+
export const OpenAIChatToolCallDelta = Schema.Struct({
|
|
230
|
+
index: optionalNull(Schema.Number),
|
|
231
|
+
id: optionalNull(Schema.String),
|
|
232
|
+
function: optionalNull(OpenAIChatToolCallDeltaFunction),
|
|
233
|
+
custom: optionalNull(Schema.Struct({ name: optionalNull(Schema.String), input: optionalNull(Schema.String) })),
|
|
234
|
+
extra_content: optionalNull(Schema.Unknown),
|
|
235
|
+
});
|
|
236
|
+
export const OpenAIChatDelta = Schema.StructWithRest(Schema.Struct({
|
|
237
|
+
content: optionalNull(Schema.String),
|
|
238
|
+
refusal: optionalNull(Schema.String),
|
|
239
|
+
reasoning_content: optionalNull(Schema.String),
|
|
240
|
+
reasoning: optionalNull(Schema.String),
|
|
241
|
+
reasoning_text: optionalNull(Schema.String),
|
|
242
|
+
reasoning_details: optionalNull(Schema.Unknown),
|
|
243
|
+
// GitHub Copilot's opaque reasoning state, which must be replayed for multi-turn reasoning.
|
|
244
|
+
reasoning_opaque: optionalNull(Schema.String),
|
|
245
|
+
tool_calls: optionalNull(Schema.Array(OpenAIChatToolCallDelta)),
|
|
246
|
+
}), [Schema.Record(Schema.String, Schema.Unknown)]);
|
|
247
|
+
export const OpenAIChatChoice = Schema.StructWithRest(Schema.Struct({
|
|
248
|
+
delta: optionalNull(OpenAIChatDelta),
|
|
249
|
+
finish_reason: optionalNull(Schema.String),
|
|
250
|
+
native_finish_reason: optionalNull(Schema.String),
|
|
251
|
+
// Moonshot streams usage on `choice.usage` instead of top-level `usage`.
|
|
252
|
+
usage: optionalNull(OpenAIChatUsage),
|
|
253
|
+
}), [Schema.Record(Schema.String, Schema.Unknown)]);
|
|
254
|
+
const OpenAIChatError = Schema.StructWithRest(Schema.Struct({
|
|
255
|
+
code: optionalNull(Schema.Union([Schema.String, Schema.Number])),
|
|
256
|
+
message: Schema.String,
|
|
257
|
+
}), [Schema.Record(Schema.String, Schema.Unknown)]);
|
|
258
|
+
export const OpenAIChatEvent = Schema.StructWithRest(Schema.Struct({
|
|
259
|
+
choices: optionalNull(Schema.Array(OpenAIChatChoice)),
|
|
260
|
+
usage: optionalNull(OpenAIChatUsage),
|
|
261
|
+
error: optionalNull(OpenAIChatError),
|
|
262
|
+
}), [Schema.Record(Schema.String, Schema.Unknown)]);
|
|
263
|
+
const DONE = "[DONE]";
|
|
264
|
+
const OpenAIChatStreamEvent = Schema.Union([Schema.Literal(DONE), Protocol.jsonEvent(OpenAIChatEvent)]);
|
|
265
|
+
const lowerTool = (tool, options, supportsStrictMode, custom) => {
|
|
266
|
+
if (custom) {
|
|
267
|
+
const grammar = OpenAIFreeform.grammar(custom);
|
|
268
|
+
return {
|
|
269
|
+
type: "custom",
|
|
270
|
+
custom: {
|
|
271
|
+
name: tool.name,
|
|
272
|
+
description: OpenAIFreeform.description(tool, custom),
|
|
273
|
+
format: grammar ? { type: "grammar", grammar } : { type: "text" },
|
|
274
|
+
},
|
|
275
|
+
cache_control: options.cacheControl?.(tool.cache),
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
return {
|
|
279
|
+
type: "function",
|
|
280
|
+
function: {
|
|
281
|
+
name: tool.name,
|
|
282
|
+
description: tool.description,
|
|
283
|
+
parameters: tool.inputSchema,
|
|
284
|
+
...(supportsStrictMode ? { strict: false } : {}),
|
|
285
|
+
},
|
|
286
|
+
cache_control: options.cacheControl?.(tool.cache),
|
|
287
|
+
};
|
|
288
|
+
};
|
|
289
|
+
const lowerToolChoice = (toolChoice, custom) => ProviderShared.matchToolChoice(toolChoice, {
|
|
290
|
+
auto: () => "auto",
|
|
291
|
+
none: () => "none",
|
|
292
|
+
required: () => "required",
|
|
293
|
+
tool: (name) => custom.has(name)
|
|
294
|
+
? { type: "custom", custom: { name } }
|
|
295
|
+
: { type: "function", function: { name } },
|
|
296
|
+
});
|
|
297
|
+
// A call replays as the type its tool is declared with in this request.
|
|
298
|
+
const lowerToolCall = (part, options) => {
|
|
299
|
+
const custom = options.custom.get(part.name);
|
|
300
|
+
if (custom)
|
|
301
|
+
return {
|
|
302
|
+
id: options.toolCallID?.(part.id) ?? part.id,
|
|
303
|
+
type: "custom",
|
|
304
|
+
custom: {
|
|
305
|
+
name: part.name,
|
|
306
|
+
input: OpenAIFreeform.toRaw(custom, part.input, part.providerMetadata?.[options.providerMetadataKey]?.header),
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
return {
|
|
310
|
+
id: options.toolCallID?.(part.id) ?? part.id,
|
|
311
|
+
type: "function",
|
|
312
|
+
function: {
|
|
313
|
+
name: part.name,
|
|
314
|
+
arguments: ProviderShared.encodeJson(part.input === undefined ? {} : part.input),
|
|
315
|
+
},
|
|
316
|
+
extra_content: decodeExtraContent(part.providerMetadata?.[options.providerMetadataKey]?.extraContent),
|
|
317
|
+
};
|
|
318
|
+
};
|
|
319
|
+
const lowerMedia = Effect.fnUntraced(function* (part) {
|
|
320
|
+
// Chat Completions accepts PDFs, and no other documents, as inline `file` parts; file URLs are not supported.
|
|
321
|
+
if (part.media.mediaType.toLowerCase() === "application/pdf")
|
|
322
|
+
return {
|
|
323
|
+
type: "file",
|
|
324
|
+
file: {
|
|
325
|
+
filename: part.filename ?? "document.pdf",
|
|
326
|
+
file_data: (yield* ProviderShared.requireInlineMedia("OpenAI Chat", part.media)).dataUrl,
|
|
327
|
+
},
|
|
328
|
+
};
|
|
329
|
+
if (part.media.kind !== "image" && part.media.kind !== "video")
|
|
330
|
+
return yield* ProviderShared.invalidRequest(`OpenAI Chat does not support media type ${part.media.mediaType}`);
|
|
331
|
+
const url = ProviderShared.mediaUrl(part.media) ?? (yield* ProviderShared.requireInlineMedia("OpenAI Chat", part.media)).dataUrl;
|
|
332
|
+
if (part.media.kind === "video")
|
|
333
|
+
return { type: "video_url", video_url: { url } };
|
|
334
|
+
return { type: "image_url", image_url: { url } };
|
|
335
|
+
});
|
|
336
|
+
const reasoningField = (part, providerMetadataKey) => {
|
|
337
|
+
const field = part.providerMetadata?.[providerMetadataKey]?.reasoningField;
|
|
338
|
+
return typeof field === "string" ? field : undefined;
|
|
339
|
+
};
|
|
340
|
+
const reasoningDetails = (parts, providerMetadataKey) => {
|
|
341
|
+
const observed = parts.flatMap((part) => {
|
|
342
|
+
const details = part.providerMetadata?.[providerMetadataKey]?.reasoningDetails;
|
|
343
|
+
return Array.isArray(details) ? details : [];
|
|
344
|
+
});
|
|
345
|
+
if (parts.some((part) => Array.isArray(part.providerMetadata?.[providerMetadataKey]?.reasoningDetails)))
|
|
346
|
+
return knownReasoningDetails(observed).map(lowerReasoningDetail);
|
|
347
|
+
};
|
|
348
|
+
// Kimi rejects its stream-only `index` on requests
|
|
349
|
+
// ("the reasoning_details ... must not contain streaming index").
|
|
350
|
+
const lowerReasoningDetail = (detail) => {
|
|
351
|
+
if (detail.type === "summary")
|
|
352
|
+
return { type: detail.type, summary: detail.summary };
|
|
353
|
+
if (detail.type === "encrypted")
|
|
354
|
+
return { type: detail.type, encrypted: detail.encrypted };
|
|
355
|
+
return detail;
|
|
356
|
+
};
|
|
357
|
+
// Interleaved reasoning yields one opaque value per segment; like the Copilot VS Code
|
|
358
|
+
// client, replay the latest one with the concatenated reasoning text.
|
|
359
|
+
const reasoningOpaque = (parts, providerMetadataKey) => parts
|
|
360
|
+
.map((part) => part.providerMetadata?.[providerMetadataKey]?.reasoningOpaque)
|
|
361
|
+
.findLast((value) => typeof value === "string");
|
|
362
|
+
const isKimiDetail = (detail) => detail.type === "summary" || detail.type === "encrypted";
|
|
363
|
+
const lowerUserMessage = Effect.fnUntraced(function* (message, options) {
|
|
364
|
+
const content = [];
|
|
365
|
+
for (const part of message.content) {
|
|
366
|
+
if (part.type === "text") {
|
|
367
|
+
content.push({ type: "text", text: part.text, cache_control: options.cacheControl?.(part.cache) });
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
if (part.type === "media") {
|
|
371
|
+
content.push(yield* lowerMedia(part));
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
if (content.every((part) => part.type === "text" && part.cache_control === undefined))
|
|
376
|
+
return {
|
|
377
|
+
role: "user",
|
|
378
|
+
content: content.map((part) => (part.type === "text" ? part.text : "")).join(""),
|
|
379
|
+
};
|
|
380
|
+
return { role: "user", content };
|
|
381
|
+
});
|
|
382
|
+
const lowerAssistantMessage = Effect.fnUntraced(function* (message, configuredField, requireReasoning, options) {
|
|
383
|
+
const content = [];
|
|
384
|
+
const reasoning = [];
|
|
385
|
+
const toolCalls = [];
|
|
386
|
+
for (const part of message.content) {
|
|
387
|
+
if (!ProviderShared.supportsContent(part, ["text", "reasoning", "tool-call"]))
|
|
388
|
+
return yield* ProviderShared.unsupportedContent("OpenAI Chat", "assistant", ["text", "reasoning", "tool-call"]);
|
|
389
|
+
if (part.type === "text") {
|
|
390
|
+
content.push({ type: "text", text: part.text, cache_control: options.cacheControl?.(part.cache) });
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
if (part.type === "reasoning") {
|
|
394
|
+
reasoning.push(part);
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
if (part.type === "tool-call") {
|
|
398
|
+
toolCalls.push(lowerToolCall(part, options));
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
const text = reasoning.map((part) => part.text).join("");
|
|
403
|
+
const details = reasoningDetails(reasoning, options.providerMetadataKey);
|
|
404
|
+
const observedField = reasoning
|
|
405
|
+
.map((part) => reasoningField(part, options.providerMetadataKey))
|
|
406
|
+
.find((value) => value !== undefined);
|
|
407
|
+
const fullyStructured = reasoning.every((part) => Array.isArray(part.providerMetadata?.[options.providerMetadataKey]?.reasoningDetails));
|
|
408
|
+
const field = (() => {
|
|
409
|
+
if (configuredField !== undefined && (requireReasoning || reasoning.length > 0))
|
|
410
|
+
return configuredField;
|
|
411
|
+
if (reasoning.length === 0)
|
|
412
|
+
return requireReasoning ? "reasoning_content" : undefined;
|
|
413
|
+
if (observedField !== undefined)
|
|
414
|
+
return observedField;
|
|
415
|
+
if (!fullyStructured || requireReasoning)
|
|
416
|
+
return "reasoning_content";
|
|
417
|
+
// Kimi always expects `reasoning_content` on replayed assistant messages,
|
|
418
|
+
// even when thinking arrived only through structured details.
|
|
419
|
+
if (details?.some(isKimiDetail))
|
|
420
|
+
return "reasoning_content";
|
|
421
|
+
})();
|
|
422
|
+
const opaque = reasoningOpaque(reasoning, options.providerMetadataKey);
|
|
423
|
+
const reasoningText = reasoning.length === 0 || (opaque !== undefined && text === "") ? (requireReasoning ? "" : undefined) : text;
|
|
424
|
+
// A model that declares a different reasoning field reads reasoning there, so structured details and opaque values
|
|
425
|
+
// from earlier turns (including another model served under the same provider metadata key) must not be replayed.
|
|
426
|
+
const replaysStructured = configuredField === undefined || configuredField === "reasoning_details";
|
|
427
|
+
const result = {
|
|
428
|
+
role: "assistant",
|
|
429
|
+
content: (() => {
|
|
430
|
+
if (content.some((part) => part.cache_control !== undefined))
|
|
431
|
+
return content;
|
|
432
|
+
if (content.length === 0 && toolCalls.length > 0)
|
|
433
|
+
return null;
|
|
434
|
+
return content.map((part) => part.text).join("");
|
|
435
|
+
})(),
|
|
436
|
+
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
|
437
|
+
...(details !== undefined && replaysStructured ? { reasoning_details: details } : {}),
|
|
438
|
+
...(opaque !== undefined && replaysStructured ? { reasoning_opaque: opaque } : {}),
|
|
439
|
+
};
|
|
440
|
+
// `reasoning_details` is the structured list itself, so scalar text must not be written over it.
|
|
441
|
+
if (field === undefined || reasoningText === undefined || field === "reasoning_details")
|
|
442
|
+
return result;
|
|
443
|
+
return { ...result, [field]: reasoningText };
|
|
444
|
+
});
|
|
445
|
+
const lowerToolMessages = Effect.fnUntraced(function* (message, options) {
|
|
446
|
+
const messages = [];
|
|
447
|
+
const attachments = [];
|
|
448
|
+
for (const part of message.content) {
|
|
449
|
+
if (part.result.type !== "content") {
|
|
450
|
+
messages.push(toolMessage(options.toolCallID?.(part.id) ?? part.id, ProviderShared.toolResultText(part), options.cacheControl?.(part.cache)));
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
const content = part.result.value;
|
|
454
|
+
const text = content.filter((item) => item.type === "text").map((item) => item.text);
|
|
455
|
+
messages.push(toolMessage(options.toolCallID?.(part.id) ?? part.id, text.join("\n"), options.cacheControl?.(part.cache)));
|
|
456
|
+
const files = content.filter((item) => item.type === "file");
|
|
457
|
+
attachments.push(...(yield* Effect.forEach(files, (item) => lowerMedia(ProviderShared.toolFileMedia(item)))));
|
|
458
|
+
}
|
|
459
|
+
return { messages, attachments };
|
|
460
|
+
});
|
|
461
|
+
// Chat cache breakpoints belong on text content parts, not on the message itself.
|
|
462
|
+
const toolMessage = (toolCallID, text, cacheControl) => ({
|
|
463
|
+
role: "tool",
|
|
464
|
+
tool_call_id: toolCallID,
|
|
465
|
+
content: cacheControl === undefined ? text : [{ type: "text", text, cache_control: cacheControl }],
|
|
466
|
+
});
|
|
467
|
+
const lowerMessage = Effect.fnUntraced(function* (message, reasoningField, requireReasoning, options) {
|
|
468
|
+
if (message.role === "user")
|
|
469
|
+
return [yield* lowerUserMessage(message, options)];
|
|
470
|
+
const lowered = yield* lowerAssistantMessage(message, reasoningField, requireReasoning, options);
|
|
471
|
+
return [options.assistant?.(message, lowered) ?? lowered];
|
|
472
|
+
});
|
|
473
|
+
const lowerMessages = Effect.fnUntraced(function* (request, options) {
|
|
474
|
+
const system = request.system.length === 0
|
|
475
|
+
? []
|
|
476
|
+
: request.system.some((part) => part.cache !== undefined) && options.cacheControl !== undefined
|
|
477
|
+
? [
|
|
478
|
+
{
|
|
479
|
+
role: "system",
|
|
480
|
+
content: request.system.map((part) => ({
|
|
481
|
+
type: "text",
|
|
482
|
+
text: part.text,
|
|
483
|
+
cache_control: options.cacheControl?.(part.cache),
|
|
484
|
+
})),
|
|
485
|
+
},
|
|
486
|
+
]
|
|
487
|
+
: [{ role: "system", content: ProviderShared.joinText(request.system) }];
|
|
488
|
+
const messages = [...system];
|
|
489
|
+
const modelID = request.model.id.toLowerCase();
|
|
490
|
+
const requireReasoning = request.model.compatibility?.requireReasoning ??
|
|
491
|
+
(request.model.compatibility?.reasoningField !== undefined ||
|
|
492
|
+
request.model.provider === "deepseek" ||
|
|
493
|
+
request.model.route.endpoint.baseURL?.toLowerCase().includes("deepseek.com") ||
|
|
494
|
+
modelID.includes("deepseek"));
|
|
495
|
+
const reasoningField = request.model.compatibility?.reasoningField;
|
|
496
|
+
const mistral = ["mistral", "devstral", "codestral", "pixtral", "mixtral"].some((family) => modelID.includes(family));
|
|
497
|
+
const lowering = {
|
|
498
|
+
...options,
|
|
499
|
+
providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
|
|
500
|
+
toolCallID: (id) => {
|
|
501
|
+
if (mistral)
|
|
502
|
+
return id
|
|
503
|
+
.replace(/[^a-zA-Z0-9]/g, "")
|
|
504
|
+
.slice(0, 9)
|
|
505
|
+
.padEnd(9, "0");
|
|
506
|
+
if (modelID.includes("claude"))
|
|
507
|
+
return id.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
508
|
+
if (request.model.provider === "openai" || request.model.provider === "azure" || modelID.startsWith("openai/"))
|
|
509
|
+
return id.slice(0, 40);
|
|
510
|
+
return id;
|
|
511
|
+
},
|
|
512
|
+
};
|
|
513
|
+
const requireAssistantAfterTool = request.model.compatibility?.requireAssistantAfterTool ?? mistral;
|
|
514
|
+
const bridgeTools = () => {
|
|
515
|
+
if (requireAssistantAfterTool && messages.at(-1)?.role === "tool")
|
|
516
|
+
messages.push({ role: "assistant", content: "Done." });
|
|
517
|
+
};
|
|
518
|
+
const pendingAttachments = [];
|
|
519
|
+
const flushAttachments = () => {
|
|
520
|
+
if (pendingAttachments.length === 0)
|
|
521
|
+
return;
|
|
522
|
+
bridgeTools();
|
|
523
|
+
messages.push({ role: "user", content: pendingAttachments.splice(0) });
|
|
524
|
+
};
|
|
525
|
+
for (const message of request.messages) {
|
|
526
|
+
if (message.role === "user")
|
|
527
|
+
bridgeTools();
|
|
528
|
+
if (message.role === "system") {
|
|
529
|
+
const part = yield* ProviderShared.wrappedSystemUpdate("OpenAI Chat", message);
|
|
530
|
+
const cacheControl = options.cacheControl?.(part.cache);
|
|
531
|
+
if (pendingAttachments.length > 0) {
|
|
532
|
+
messages.push({
|
|
533
|
+
role: "user",
|
|
534
|
+
content: [...pendingAttachments.splice(0), { type: "text", text: part.text, cache_control: cacheControl }],
|
|
535
|
+
});
|
|
536
|
+
continue;
|
|
537
|
+
}
|
|
538
|
+
const previous = messages.at(-1);
|
|
539
|
+
if (previous?.role === "user" && typeof previous.content === "string")
|
|
540
|
+
messages[messages.length - 1] = cacheControl
|
|
541
|
+
? {
|
|
542
|
+
role: "user",
|
|
543
|
+
content: [
|
|
544
|
+
{ type: "text", text: previous.content },
|
|
545
|
+
{ type: "text", text: part.text, cache_control: cacheControl },
|
|
546
|
+
],
|
|
547
|
+
}
|
|
548
|
+
: { role: "user", content: `${previous.content}\n${part.text}` };
|
|
549
|
+
else if (previous?.role === "user" && Array.isArray(previous.content))
|
|
550
|
+
messages[messages.length - 1] = {
|
|
551
|
+
role: "user",
|
|
552
|
+
content: [...previous.content, { type: "text", text: part.text, cache_control: cacheControl }],
|
|
553
|
+
};
|
|
554
|
+
else
|
|
555
|
+
messages.push(cacheControl
|
|
556
|
+
? {
|
|
557
|
+
role: "user",
|
|
558
|
+
content: [{ type: "text", text: part.text, cache_control: cacheControl }],
|
|
559
|
+
}
|
|
560
|
+
: { role: "user", content: part.text });
|
|
561
|
+
continue;
|
|
562
|
+
}
|
|
563
|
+
if (message.role === "assistant" &&
|
|
564
|
+
message.content.every((part) => part.type === "text" && part.text.trim() === ""))
|
|
565
|
+
continue;
|
|
566
|
+
if (message.role === "tool") {
|
|
567
|
+
const lowered = yield* lowerToolMessages(message, lowering);
|
|
568
|
+
messages.push(...lowered.messages);
|
|
569
|
+
pendingAttachments.push(...lowered.attachments);
|
|
570
|
+
continue;
|
|
571
|
+
}
|
|
572
|
+
flushAttachments();
|
|
573
|
+
messages.push(...(yield* lowerMessage(message, reasoningField, requireReasoning, lowering)));
|
|
574
|
+
}
|
|
575
|
+
flushAttachments();
|
|
576
|
+
return messages;
|
|
577
|
+
});
|
|
578
|
+
// Anthropic via LiteLLM and Amazon Bedrock require `tools` to be present
|
|
579
|
+
// whenever the conversation history contains tool calls/results. Send an
|
|
580
|
+
// explicit empty array when we have history but no active tools.
|
|
581
|
+
const hasToolHistory = (messages) => {
|
|
582
|
+
for (const message of messages) {
|
|
583
|
+
if (message.role === "tool")
|
|
584
|
+
return true;
|
|
585
|
+
if (message.role === "assistant" && message.content.some((part) => part.type === "tool-call"))
|
|
586
|
+
return true;
|
|
587
|
+
}
|
|
588
|
+
return false;
|
|
589
|
+
};
|
|
590
|
+
// Derive `max_tokens` vs `max_completion_tokens` from provider/baseURL when
|
|
591
|
+
// explicit `compatibility.maxTokensField` is not set. Aligned with
|
|
592
|
+
// models.dev provider naming: DeepSeek, Moonshot AI, Together AI, ZAI
|
|
593
|
+
// (Zhipu + Coding Plan variants), Nvidia, Cerebras, Chutes, etc. still
|
|
594
|
+
// require `max_tokens`.
|
|
595
|
+
const detectMaxTokensField = (provider, baseURL) => {
|
|
596
|
+
const p = provider.toLowerCase();
|
|
597
|
+
const url = (baseURL ?? "").toLowerCase();
|
|
598
|
+
if (p === "deepseek" ||
|
|
599
|
+
url.includes("deepseek.com") ||
|
|
600
|
+
p === "moonshotai" ||
|
|
601
|
+
url.includes("api.moonshot.ai") ||
|
|
602
|
+
p === "togetherai" ||
|
|
603
|
+
url.includes("api.together.") ||
|
|
604
|
+
p === "zai" ||
|
|
605
|
+
p === "zai-coding-plan" ||
|
|
606
|
+
p === "zhipuai" ||
|
|
607
|
+
p === "zhipuai-coding-plan" ||
|
|
608
|
+
url.includes("api.z.ai") ||
|
|
609
|
+
url.includes("open.bigmodel.cn") ||
|
|
610
|
+
p === "nvidia" ||
|
|
611
|
+
url.includes("integrate.api.nvidia.com") ||
|
|
612
|
+
p === "cerebras" ||
|
|
613
|
+
url.includes("cerebras.ai") ||
|
|
614
|
+
url.includes("llm.chutes.ai") ||
|
|
615
|
+
p === "chutes" ||
|
|
616
|
+
p === "cloudflare-ai-gateway" ||
|
|
617
|
+
url.includes("gateway.ai.cloudflare.com") ||
|
|
618
|
+
p === "cloudflare-workers-ai" ||
|
|
619
|
+
url.includes("api.cloudflare.com"))
|
|
620
|
+
return "max_tokens";
|
|
621
|
+
return "max_completion_tokens";
|
|
622
|
+
};
|
|
623
|
+
// `store` defaults to false on OpenAI and Azure, but org-level logging can still
|
|
624
|
+
// store requests that omit it, so send an explicit `store: false` there. Strict
|
|
625
|
+
// OpenAI-style APIs reject the field with a 400, so omit it everywhere else.
|
|
626
|
+
const detectSupportsStore = (provider, baseURL) => {
|
|
627
|
+
const p = provider.toLowerCase();
|
|
628
|
+
const url = (baseURL ?? "").toLowerCase();
|
|
629
|
+
return (p === "openai" ||
|
|
630
|
+
p === "azure" ||
|
|
631
|
+
url.includes("api.openai.com") ||
|
|
632
|
+
url.includes(".openai.azure.com") ||
|
|
633
|
+
url.includes(".cognitiveservices.azure.com") ||
|
|
634
|
+
url.includes(".services.ai.azure.com"));
|
|
635
|
+
};
|
|
636
|
+
const detectSupportsStrictMode = (provider, baseURL) => {
|
|
637
|
+
const p = provider.toLowerCase();
|
|
638
|
+
const url = (baseURL ?? "").toLowerCase();
|
|
639
|
+
const isMoonshot = p === "moonshotai" || p === "moonshotai-cn" || url.includes("api.moonshot.");
|
|
640
|
+
const isTogether = p === "togetherai" || p === "together" || url.includes("api.together.");
|
|
641
|
+
const isCloudflareAiGateway = p === "cloudflare-ai-gateway" || url.includes("gateway.ai.cloudflare.com");
|
|
642
|
+
const isNvidia = p === "nvidia" || url.includes("integrate.api.nvidia.com");
|
|
643
|
+
return !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia;
|
|
644
|
+
};
|
|
645
|
+
const detectZaiToolStream = (provider, baseURL, modelID) => {
|
|
646
|
+
const p = provider.toLowerCase();
|
|
647
|
+
const url = (baseURL ?? "").toLowerCase();
|
|
648
|
+
const isZai = p === "zai" ||
|
|
649
|
+
p === "zai-coding-plan" ||
|
|
650
|
+
p === "zhipuai" ||
|
|
651
|
+
p === "zhipuai-coding-plan" ||
|
|
652
|
+
url.includes("api.z.ai") ||
|
|
653
|
+
url.includes("open.bigmodel.cn");
|
|
654
|
+
if (!isZai)
|
|
655
|
+
return false;
|
|
656
|
+
const id = modelID.toLowerCase();
|
|
657
|
+
if (id === "glm-4.5" || id === "glm-4.5-air" || id === "glm-4.5-flash" || id === "glm-4.5v")
|
|
658
|
+
return false;
|
|
659
|
+
return true;
|
|
660
|
+
};
|
|
661
|
+
const lowerOptions = (request, supportsStore, hasActiveTools) => {
|
|
662
|
+
const options = OpenResponsesOptions.resolve(request);
|
|
663
|
+
// OpenAI rejects `parallel_tool_calls` unless tools are present.
|
|
664
|
+
const parallelToolCalls = hasActiveTools ? resolveParallelToolCalls(request, options) : undefined;
|
|
665
|
+
// Default off: strict providers 400 on unknown body fields, so only send
|
|
666
|
+
// the key where compatibility explicitly allows it. Header-based affinity
|
|
667
|
+
// (x-session-affinity, x-grok-conv-id, ...) is unaffected.
|
|
668
|
+
const cacheKey = (ProviderShared.acceptsAffinity(request.model) ?? false) ? ProviderShared.promptCacheKey(request) : undefined;
|
|
669
|
+
return {
|
|
670
|
+
...(supportsStore ? { store: options.store ?? false } : {}),
|
|
671
|
+
...(cacheKey ? { prompt_cache_key: cacheKey } : {}),
|
|
672
|
+
// Inline markers carry the lifetime when the policy places them.
|
|
673
|
+
...(placesMarkers(request) ? {} : Cache.openAIRequestTTL(requestTTL(request))),
|
|
674
|
+
...(options.reasoningEffort ? { reasoning_effort: options.reasoningEffort } : {}),
|
|
675
|
+
...(options.textVerbosity ? { verbosity: options.textVerbosity } : {}),
|
|
676
|
+
...(options.serviceTier ? { service_tier: options.serviceTier } : {}),
|
|
677
|
+
...(parallelToolCalls !== undefined ? { parallel_tool_calls: parallelToolCalls } : {}),
|
|
678
|
+
...(options.metadata ? { metadata: options.metadata } : {}),
|
|
679
|
+
...(options.safetyIdentifier ? { safety_identifier: options.safetyIdentifier } : {}),
|
|
680
|
+
};
|
|
681
|
+
};
|
|
682
|
+
/** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
|
|
683
|
+
export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (request, options = {}) {
|
|
684
|
+
// `fromRequest` returns the provider body only. Endpoint, auth, framing,
|
|
685
|
+
// validation, and HTTP execution are composed by `Route.make`.
|
|
686
|
+
const reasoningField = request.model.compatibility?.reasoningField;
|
|
687
|
+
if (reasoningField && RESERVED_REASONING_FIELDS.has(reasoningField))
|
|
688
|
+
return yield* ProviderShared.invalidRequest(`OpenAI Chat reasoning field conflicts with reserved field ${reasoningField}`);
|
|
689
|
+
const definitions = ProviderShared.flattenTools(request.tools);
|
|
690
|
+
const provider = request.model.provider;
|
|
691
|
+
const baseURL = request.model.route.endpoint.baseURL;
|
|
692
|
+
const detectedMaxTokensField = detectMaxTokensField(provider, baseURL);
|
|
693
|
+
const maxTokensField = request.model.compatibility?.maxTokensField ?? detectedMaxTokensField;
|
|
694
|
+
const supportsStore = request.model.capabilities?.store ?? detectSupportsStore(provider, baseURL);
|
|
695
|
+
const supportsStrictMode = request.model.capabilities?.tools?.strict ?? detectSupportsStrictMode(provider, baseURL);
|
|
696
|
+
const zaiToolStream = request.model.compatibility?.zaiToolStream ?? detectZaiToolStream(provider, baseURL, request.model.id);
|
|
697
|
+
const hasHistory = hasToolHistory(request.messages);
|
|
698
|
+
const hasActiveTools = definitions.length > 0;
|
|
699
|
+
const custom = OpenAIFreeform.tools(request);
|
|
700
|
+
const lowering = { ...options, cacheControl: options.cacheControl ?? declaredCacheControl(request), custom };
|
|
701
|
+
return {
|
|
702
|
+
model: request.model.id,
|
|
703
|
+
messages: yield* lowerMessages(request, lowering),
|
|
704
|
+
tools: definitions.length === 0
|
|
705
|
+
? hasHistory
|
|
706
|
+
? []
|
|
707
|
+
: undefined
|
|
708
|
+
: definitions.map((tool) => lowerTool(tool, lowering, supportsStrictMode, custom.get(tool.name))),
|
|
709
|
+
tool_choice: hasActiveTools && request.toolChoice ? lowerToolChoice(request.toolChoice, custom) : undefined,
|
|
710
|
+
stream: true,
|
|
711
|
+
...((request.model.capabilities?.streamUsage ?? true) ? { stream_options: { include_usage: true } } : {}),
|
|
712
|
+
...(zaiToolStream && hasActiveTools ? { tool_stream: true } : {}),
|
|
713
|
+
...(maxTokensField === "max_completion_tokens"
|
|
714
|
+
? { max_completion_tokens: request.maxTokens }
|
|
715
|
+
: { max_tokens: request.maxTokens }),
|
|
716
|
+
temperature: request.temperature,
|
|
717
|
+
top_p: request.topP,
|
|
718
|
+
frequency_penalty: request.frequencyPenalty,
|
|
719
|
+
presence_penalty: request.presencePenalty,
|
|
720
|
+
seed: request.seed,
|
|
721
|
+
stop: request.stop,
|
|
722
|
+
...lowerOptions(request, supportsStore, hasActiveTools),
|
|
723
|
+
};
|
|
724
|
+
});
|
|
725
|
+
// Provider wrappers that pass their own marker writer keep it; otherwise a declared cache format adds one.
|
|
726
|
+
const declaredCacheControl = (request) => request.model.compatibility?.cacheFormat === undefined ? undefined : Cache.cacheControl();
|
|
727
|
+
// =============================================================================
|
|
728
|
+
// Stream Parsing
|
|
729
|
+
// =============================================================================
|
|
730
|
+
// Streaming parsers are small state machines: every event returns a new state
|
|
731
|
+
// plus the common `StreamEvent`s produced by that event. Tool calls are accumulated
|
|
732
|
+
// because OpenAI streams JSON arguments across multiple deltas.
|
|
733
|
+
const mapFinishReason = Effect.fnUntraced(function* (event, reason) {
|
|
734
|
+
switch (reason) {
|
|
735
|
+
case "error":
|
|
736
|
+
return yield* new AIError({
|
|
737
|
+
reason: new UnknownProviderError({
|
|
738
|
+
message: "Provider reported an error (finish_reason: error)",
|
|
739
|
+
body: ProviderShared.encodeJson(event),
|
|
740
|
+
}),
|
|
741
|
+
});
|
|
742
|
+
case "network_error":
|
|
743
|
+
return yield* new AIError({
|
|
744
|
+
reason: new ProviderInternalError({
|
|
745
|
+
message: "Provider reported a network error (finish_reason: network_error)",
|
|
746
|
+
body: ProviderShared.encodeJson(event),
|
|
747
|
+
}),
|
|
748
|
+
});
|
|
749
|
+
case "stop":
|
|
750
|
+
case "end":
|
|
751
|
+
return "stop";
|
|
752
|
+
case "length":
|
|
753
|
+
// Z.AI stops with this when the prompt plus the generated output fill the context window.
|
|
754
|
+
case "model_context_window_exceeded":
|
|
755
|
+
return "length";
|
|
756
|
+
case "content_filter":
|
|
757
|
+
// Z.AI ends a response its safety review blocked with "sensitive".
|
|
758
|
+
case "sensitive":
|
|
759
|
+
return "content-filter";
|
|
760
|
+
case "function_call":
|
|
761
|
+
case "tool_calls":
|
|
762
|
+
return "tool-calls";
|
|
763
|
+
default:
|
|
764
|
+
return "unknown";
|
|
765
|
+
}
|
|
766
|
+
});
|
|
767
|
+
// OpenAI Chat reports `prompt_tokens` (inclusive total) with a
|
|
768
|
+
// cached-read and cache-write subsets, and `completion_tokens` (inclusive
|
|
769
|
+
// total) with a `reasoning_tokens` subset. We pass the inclusive totals
|
|
770
|
+
// through and derive the non-cached breakdown so the `AI.Usage` contract is
|
|
771
|
+
// satisfied on both sides.
|
|
772
|
+
// Providers differ on cache-hit location: OpenAI uses
|
|
773
|
+
// `prompt_tokens_details.cached_tokens`, DeepSeek uses
|
|
774
|
+
// `prompt_cache_hit_tokens`, Zai uses top-level `cached_tokens`, and
|
|
775
|
+
// DigitalOcean uses top-level `cache_read_input_tokens` / `cache_created_input_tokens`.
|
|
776
|
+
const mapUsage = (usage, providerMetadataKey, frame) => {
|
|
777
|
+
if (!usage)
|
|
778
|
+
return undefined;
|
|
779
|
+
const input = usage.prompt_tokens ?? undefined;
|
|
780
|
+
const completion = usage.completion_tokens ?? undefined;
|
|
781
|
+
const cached = usage.prompt_tokens_details?.cached_tokens ??
|
|
782
|
+
usage.prompt_cache_hit_tokens ??
|
|
783
|
+
usage.cached_tokens ??
|
|
784
|
+
usage.cache_read_input_tokens ??
|
|
785
|
+
undefined;
|
|
786
|
+
const cacheWrite = usage.prompt_tokens_details?.cache_write_tokens ?? usage.cache_created_input_tokens ?? undefined;
|
|
787
|
+
const reasoning = usage.completion_tokens_details?.reasoning_tokens ?? usage.reasoning_tokens ?? undefined;
|
|
788
|
+
// Copilot's Gemini counts reasoning beside `completion_tokens` rather than inside it; the total tells which.
|
|
789
|
+
const output = completion !== undefined &&
|
|
790
|
+
reasoning !== undefined &&
|
|
791
|
+
usage.total_tokens === ProviderShared.sumTokens(input, completion, reasoning)
|
|
792
|
+
? completion + reasoning
|
|
793
|
+
: completion;
|
|
794
|
+
const nonCached = ProviderShared.subtractTokens(input, ProviderShared.sumTokens(cached, cacheWrite));
|
|
795
|
+
return new Usage({
|
|
796
|
+
inputTokens: input,
|
|
797
|
+
outputTokens: output,
|
|
798
|
+
nonCachedInputTokens: nonCached,
|
|
799
|
+
cacheReadInputTokens: cached,
|
|
800
|
+
cacheWriteInputTokens: cacheWrite,
|
|
801
|
+
reasoningTokens: reasoning,
|
|
802
|
+
totalTokens: ProviderShared.totalTokens(input, output, usage.total_tokens ?? undefined),
|
|
803
|
+
...ProviderShared.reportedBilling(usage, frame),
|
|
804
|
+
providerMetadata: { [providerMetadataKey]: usage },
|
|
805
|
+
});
|
|
806
|
+
};
|
|
807
|
+
const toolIndexByID = (tools, pendingTools, id) => {
|
|
808
|
+
if (!id)
|
|
809
|
+
return undefined;
|
|
810
|
+
const entry = Object.entries({ ...pendingTools, ...tools }).find(([, tool]) => tool?.id === id);
|
|
811
|
+
return entry ? Number(entry[0]) : undefined;
|
|
812
|
+
};
|
|
813
|
+
const reasoningDelta = (delta, configuredField) => {
|
|
814
|
+
if (!delta)
|
|
815
|
+
return undefined;
|
|
816
|
+
const fields = new Set([configuredField, "reasoning_content", "reasoning", "reasoning_text"]);
|
|
817
|
+
for (const field of fields) {
|
|
818
|
+
if (field === undefined)
|
|
819
|
+
continue;
|
|
820
|
+
const text = delta[field];
|
|
821
|
+
if (typeof text === "string" && text.length > 0)
|
|
822
|
+
return { field, text };
|
|
823
|
+
}
|
|
824
|
+
return undefined;
|
|
825
|
+
};
|
|
826
|
+
const detailText = (details, hideKimiSummary) => {
|
|
827
|
+
const text = details.flatMap((detail) => {
|
|
828
|
+
if (detail.type === "reasoning.text")
|
|
829
|
+
return detail.text ? [detail.text] : [];
|
|
830
|
+
if (detail.type === "reasoning.summary")
|
|
831
|
+
return detail.summary ? [detail.summary] : [];
|
|
832
|
+
// Kimi streams the full thinking through `reasoning_content` and a separate
|
|
833
|
+
// summary through details; show the summary only when nothing else does.
|
|
834
|
+
if (detail.type === "summary")
|
|
835
|
+
return detail.summary && !hideKimiSummary ? [detail.summary] : [];
|
|
836
|
+
return [];
|
|
837
|
+
});
|
|
838
|
+
if (text.length > 0)
|
|
839
|
+
return text.join("");
|
|
840
|
+
};
|
|
841
|
+
const appendReasoningDetails = (result, details) => {
|
|
842
|
+
for (const detail of details) {
|
|
843
|
+
const previous = result.at(-1);
|
|
844
|
+
const merged = previous === undefined ? undefined : mergeReasoningDetails(previous, detail);
|
|
845
|
+
if (merged === undefined) {
|
|
846
|
+
result.push(detail);
|
|
847
|
+
continue;
|
|
848
|
+
}
|
|
849
|
+
result[result.length - 1] = merged;
|
|
850
|
+
}
|
|
851
|
+
};
|
|
852
|
+
// Consecutive text or summary deltas of the same kind accumulate into one
|
|
853
|
+
// entry; encrypted entries are opaque and never merge.
|
|
854
|
+
const mergeReasoningDetails = (previous, detail) => {
|
|
855
|
+
if (conflictingReasoningDetails(previous, detail))
|
|
856
|
+
return undefined;
|
|
857
|
+
if (previous.type === "reasoning.text" && detail.type === "reasoning.text")
|
|
858
|
+
return {
|
|
859
|
+
...previous,
|
|
860
|
+
...detail,
|
|
861
|
+
text: `${previous.text ?? ""}${detail.text ?? ""}`,
|
|
862
|
+
...mergeDetailIdentity(previous, detail),
|
|
863
|
+
};
|
|
864
|
+
if (previous.type === "reasoning.summary" && detail.type === "reasoning.summary")
|
|
865
|
+
return {
|
|
866
|
+
...previous,
|
|
867
|
+
...detail,
|
|
868
|
+
summary: `${previous.summary ?? ""}${detail.summary ?? ""}`,
|
|
869
|
+
...mergeDetailIdentity(previous, detail),
|
|
870
|
+
};
|
|
871
|
+
if (previous.type === "summary" && detail.type === "summary")
|
|
872
|
+
return { ...previous, ...detail, summary: previous.summary + detail.summary };
|
|
873
|
+
};
|
|
874
|
+
// The first non-empty signature and format win; a later delta may carry the
|
|
875
|
+
// signature for text that streamed earlier.
|
|
876
|
+
const mergeDetailIdentity = (previous, current) => {
|
|
877
|
+
const signature = mergeDetailValue(previous.signature, current.signature);
|
|
878
|
+
const format = mergeDetailValue(previous.format, current.format);
|
|
879
|
+
return {
|
|
880
|
+
...(signature === undefined ? {} : { signature }),
|
|
881
|
+
...(format === undefined ? {} : { format }),
|
|
882
|
+
};
|
|
883
|
+
};
|
|
884
|
+
const mergeDetailValue = (previous, current) => previous || current || (previous !== undefined ? previous : current);
|
|
885
|
+
const conflictingReasoningDetails = (previous, current) => conflictingDetailValue(previous.id, current.id) ||
|
|
886
|
+
conflictingDetailValue(previous.index, current.index) ||
|
|
887
|
+
conflictingDetailValue(previous.format, current.format) ||
|
|
888
|
+
(Boolean(previous.signature) && Boolean(current.signature) && previous.signature !== current.signature);
|
|
889
|
+
const conflictingDetailValue = (previous, current) => previous !== undefined && previous !== null && current !== undefined && current !== null && previous !== current;
|
|
890
|
+
const reasoningMetadata = (providerMetadataKey, field, details, opaque) => ({
|
|
891
|
+
[providerMetadataKey]: {
|
|
892
|
+
...(field ? { reasoningField: field } : {}),
|
|
893
|
+
...(details ? { reasoningDetails: details } : {}),
|
|
894
|
+
...(opaque ? { reasoningOpaque: opaque } : {}),
|
|
895
|
+
},
|
|
896
|
+
});
|
|
897
|
+
const step = (state, event) => Effect.gen(function* () {
|
|
898
|
+
if (event.error) {
|
|
899
|
+
const body = ProviderShared.encodeJson(event);
|
|
900
|
+
return yield* new AIError({
|
|
901
|
+
reason: classifyProviderFailure({
|
|
902
|
+
message: event.error.message,
|
|
903
|
+
status: typeof event.error.code === "number" ? event.error.code : undefined,
|
|
904
|
+
rawBody: body,
|
|
905
|
+
}),
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
const events = [];
|
|
909
|
+
const choice = event.choices?.[0];
|
|
910
|
+
// Moonshot (and a few other OpenAI-compatible providers) attach usage to
|
|
911
|
+
// `choice.usage` instead of the top-level `usage` field.
|
|
912
|
+
const usage = mapUsage(event.usage, state.providerMetadataKey, event) ??
|
|
913
|
+
mapUsage(choice?.usage, state.providerMetadataKey, event) ??
|
|
914
|
+
state.usage;
|
|
915
|
+
const rawFinishReason = choice?.finish_reason;
|
|
916
|
+
const finish = rawFinishReason
|
|
917
|
+
? {
|
|
918
|
+
reason: yield* mapFinishReason(event, rawFinishReason),
|
|
919
|
+
raw: choice?.native_finish_reason ?? rawFinishReason,
|
|
920
|
+
...(rawFinishReason === "content_filter"
|
|
921
|
+
? {
|
|
922
|
+
detail: ProviderShared.contentFilterCategory(choice?.delta?.copilot_annotations, choice?.content_filter_results),
|
|
923
|
+
}
|
|
924
|
+
: {}),
|
|
925
|
+
}
|
|
926
|
+
: state.finish;
|
|
927
|
+
const delta = choice?.delta;
|
|
928
|
+
const toolDeltas = delta?.tool_calls ?? [];
|
|
929
|
+
let tools = state.tools;
|
|
930
|
+
let pendingTools = state.pendingTools;
|
|
931
|
+
let customCalls = state.customCalls;
|
|
932
|
+
let latestToolIndex = state.latestToolIndex;
|
|
933
|
+
let nextToolIndex = state.nextToolIndex;
|
|
934
|
+
let lifecycle = state.lifecycle;
|
|
935
|
+
const reasoning = reasoningDelta(delta, state.reasoningField);
|
|
936
|
+
if (state.finish !== undefined &&
|
|
937
|
+
toolDeltas.some((tool) => Boolean(tool.id) ||
|
|
938
|
+
Boolean(tool.function?.name) ||
|
|
939
|
+
Boolean(tool.function?.arguments) ||
|
|
940
|
+
Boolean(tool.custom?.input)))
|
|
941
|
+
return yield* ProviderShared.eventError(ADAPTER, "OpenAI Chat received content after the finish reason", ProviderShared.encodeJson(event));
|
|
942
|
+
const reasoningField = state.reasoningField ?? reasoning?.field;
|
|
943
|
+
const reasoningTextObserved = state.reasoningTextObserved || reasoning !== undefined;
|
|
944
|
+
const detailDelta = Array.isArray(delta?.reasoning_details)
|
|
945
|
+
? knownReasoningDetails(delta.reasoning_details)
|
|
946
|
+
: undefined;
|
|
947
|
+
if (detailDelta !== undefined)
|
|
948
|
+
appendReasoningDetails(state.reasoningDetails, detailDelta);
|
|
949
|
+
const reasoningDetailsObserved = state.reasoningDetailsObserved || detailDelta !== undefined;
|
|
950
|
+
const reasoningOpaque = delta?.reasoning_opaque || state.reasoningOpaque;
|
|
951
|
+
const deltaMetadata = reasoningMetadata(state.providerMetadataKey, reasoningField);
|
|
952
|
+
const text = detailDelta?.length
|
|
953
|
+
? (detailText(detailDelta, reasoningTextObserved) ?? reasoning?.text)
|
|
954
|
+
: reasoning?.text;
|
|
955
|
+
if (text !== undefined)
|
|
956
|
+
lifecycle = Lifecycle.reasoningDelta(lifecycle, events, "reasoning-0", text, deltaMetadata);
|
|
957
|
+
else if ((reasoningDetailsObserved || reasoningOpaque !== undefined) &&
|
|
958
|
+
!lifecycle.reasoning.has("reasoning-0") &&
|
|
959
|
+
(Boolean(delta?.content) || Boolean(delta?.refusal) || toolDeltas.length > 0))
|
|
960
|
+
lifecycle = Lifecycle.reasoningStart(lifecycle, events, "reasoning-0", deltaMetadata);
|
|
961
|
+
const reasoningEmitted = state.reasoningEmitted || lifecycle.reasoning.has("reasoning-0");
|
|
962
|
+
// Reasoning is one response-wide channel: it stays open alongside text and
|
|
963
|
+
// refusal output so late reasoning deltas and details join the same block,
|
|
964
|
+
// and `finishEvents` closes it once with the complete metadata.
|
|
965
|
+
if (delta?.content)
|
|
966
|
+
lifecycle = Lifecycle.textDelta(lifecycle, events, "text-0", delta.content);
|
|
967
|
+
if (delta?.refusal)
|
|
968
|
+
lifecycle = Lifecycle.textDelta(lifecycle, events, "text-0", delta.refusal);
|
|
969
|
+
// Compatible providers may omit indexes. Prefer durable identity, then use
|
|
970
|
+
// batch position for parallel deltas or the latest call for sparse chunks.
|
|
971
|
+
for (const [position, tool] of toolDeltas.entries()) {
|
|
972
|
+
const matched = toolIndexByID(tools, pendingTools, tool.id || undefined);
|
|
973
|
+
const fallback = toolDeltas.length > 1 ? position : (latestToolIndex ?? position);
|
|
974
|
+
const fallbackTool = tools[fallback] ?? pendingTools[fallback];
|
|
975
|
+
const index = tool.index ?? matched ?? (tool.id && fallbackTool?.id && fallbackTool.id !== tool.id ? nextToolIndex : fallback);
|
|
976
|
+
const current = tools[index];
|
|
977
|
+
const pending = pendingTools[index];
|
|
978
|
+
const id = current?.id ?? pending?.id ?? (tool.id || undefined);
|
|
979
|
+
const name = current?.name ?? pending?.name ?? (tool.function?.name || tool.custom?.name || undefined);
|
|
980
|
+
// Custom calls stream raw text; re-encode it as JSON arguments for the call's field.
|
|
981
|
+
const opening = Boolean(tool.custom) && !customCalls.has(index);
|
|
982
|
+
if (opening)
|
|
983
|
+
customCalls = new Set([...customCalls, index]);
|
|
984
|
+
const raw = tool.custom?.input ?? "";
|
|
985
|
+
const fragment = tool.custom
|
|
986
|
+
? opening
|
|
987
|
+
? OpenAIFreeform.streamStart(state.custom.get(name ?? ""), raw)
|
|
988
|
+
: OpenAIFreeform.streamDelta(raw)
|
|
989
|
+
: (tool.function?.arguments ?? "");
|
|
990
|
+
const text = `${pending?.input ?? ""}${fragment}`;
|
|
991
|
+
const extraContent = pending?.extraContent ?? decodeExtraContent(tool.extra_content);
|
|
992
|
+
latestToolIndex = index;
|
|
993
|
+
nextToolIndex = Math.max(nextToolIndex, index + 1);
|
|
994
|
+
if (!current && (!id || !name)) {
|
|
995
|
+
pendingTools = {
|
|
996
|
+
...pendingTools,
|
|
997
|
+
[index]: { id: id || undefined, name: name || undefined, input: text, extraContent },
|
|
998
|
+
};
|
|
999
|
+
continue;
|
|
1000
|
+
}
|
|
1001
|
+
if (pending) {
|
|
1002
|
+
pendingTools = { ...pendingTools };
|
|
1003
|
+
delete pendingTools[index];
|
|
1004
|
+
}
|
|
1005
|
+
const result = ToolStream.appendOrStart(ADAPTER, tools, index, {
|
|
1006
|
+
id: id || undefined,
|
|
1007
|
+
name: name || undefined,
|
|
1008
|
+
text,
|
|
1009
|
+
providerMetadata: extraContent && { [state.providerMetadataKey]: { extraContent } },
|
|
1010
|
+
}, "OpenAI Chat tool call delta is missing id or name");
|
|
1011
|
+
if (ToolStream.isError(result))
|
|
1012
|
+
return yield* new AIError({
|
|
1013
|
+
reason: AIErrorReason.make({
|
|
1014
|
+
...result.reason,
|
|
1015
|
+
message: result.message,
|
|
1016
|
+
cause: result.reason.cause,
|
|
1017
|
+
body: ProviderShared.encodeJson(event),
|
|
1018
|
+
}),
|
|
1019
|
+
});
|
|
1020
|
+
tools = result.tools;
|
|
1021
|
+
if (result.events.length)
|
|
1022
|
+
lifecycle = Lifecycle.start(lifecycle);
|
|
1023
|
+
events.push(...result.events);
|
|
1024
|
+
}
|
|
1025
|
+
const incompleteTools = finish?.reason === "content-filter" || finish?.reason === "length";
|
|
1026
|
+
if (finish !== undefined && !incompleteTools && state.finish === undefined && Object.keys(pendingTools).length)
|
|
1027
|
+
return yield* ProviderShared.eventError(ADAPTER, "OpenAI Chat tool call delta is missing id or name", ProviderShared.encodeJson(event));
|
|
1028
|
+
// Filtering or truncation terminates the response without confirming pending tool calls.
|
|
1029
|
+
const finished = finish !== undefined && !incompleteTools && state.finish === undefined && Object.keys(tools).length > 0
|
|
1030
|
+
? yield* finishTools(state, tools, customCalls)
|
|
1031
|
+
: undefined;
|
|
1032
|
+
return [
|
|
1033
|
+
{
|
|
1034
|
+
providerMetadataKey: state.providerMetadataKey,
|
|
1035
|
+
tools: finished?.tools ?? tools,
|
|
1036
|
+
custom: state.custom,
|
|
1037
|
+
customCalls,
|
|
1038
|
+
pendingTools,
|
|
1039
|
+
toolCallEvents: finished?.events ?? state.toolCallEvents,
|
|
1040
|
+
usage,
|
|
1041
|
+
finish: state.finish ?? finish,
|
|
1042
|
+
lifecycle,
|
|
1043
|
+
reasoningField,
|
|
1044
|
+
reasoningTextObserved,
|
|
1045
|
+
reasoningDetails: state.reasoningDetails,
|
|
1046
|
+
reasoningDetailsObserved,
|
|
1047
|
+
reasoningOpaque,
|
|
1048
|
+
reasoningEmitted,
|
|
1049
|
+
latestToolIndex,
|
|
1050
|
+
nextToolIndex,
|
|
1051
|
+
requireFinishReason: state.requireFinishReason,
|
|
1052
|
+
},
|
|
1053
|
+
events,
|
|
1054
|
+
];
|
|
1055
|
+
});
|
|
1056
|
+
// Custom calls close their JSON fragment before every pending call finishes.
|
|
1057
|
+
const finishTools = Effect.fnUntraced(function* (state, tools, customCalls) {
|
|
1058
|
+
const closed = OpenAIFreeform.close(tools, customCalls, state.custom, state.providerMetadataKey);
|
|
1059
|
+
const finished = yield* ToolStream.finishAll(ADAPTER, closed.tools);
|
|
1060
|
+
return { tools: finished.tools, events: [...closed.events, ...finished.events] };
|
|
1061
|
+
});
|
|
1062
|
+
export const finishEvents = Effect.fnUntraced(function* (state) {
|
|
1063
|
+
if (state.finish === undefined && state.requireFinishReason)
|
|
1064
|
+
return yield* new AIError({
|
|
1065
|
+
reason: new InvalidProviderOutputError({
|
|
1066
|
+
message: "OpenAI Chat stream ended without finish_reason",
|
|
1067
|
+
classification: "incomplete-stream",
|
|
1068
|
+
route: ADAPTER,
|
|
1069
|
+
}),
|
|
1070
|
+
});
|
|
1071
|
+
const events = [];
|
|
1072
|
+
const toolCallEvents = state.finish === undefined && Object.keys(state.tools).length > 0
|
|
1073
|
+
? (yield* finishTools(state, state.tools, state.customCalls)).events
|
|
1074
|
+
: state.toolCallEvents;
|
|
1075
|
+
const hasToolCalls = toolCallEvents.length > 0;
|
|
1076
|
+
const finish = state.finish
|
|
1077
|
+
? { ...state.finish, reason: state.finish.reason === "stop" && hasToolCalls ? "tool-calls" : state.finish.reason }
|
|
1078
|
+
: { reason: hasToolCalls ? "tool-calls" : "stop" };
|
|
1079
|
+
// Snapshot details at publish time so the emitted event never observes later
|
|
1080
|
+
// mutation of the accumulated `reasoningDetails` array.
|
|
1081
|
+
const metadata = reasoningMetadata(state.providerMetadataKey, state.reasoningField, state.reasoningDetailsObserved ? [...state.reasoningDetails] : undefined, state.reasoningOpaque);
|
|
1082
|
+
const started = (state.reasoningDetailsObserved || state.reasoningOpaque !== undefined) && !state.reasoningEmitted
|
|
1083
|
+
? Lifecycle.reasoningStart(state.lifecycle, events, "reasoning-0", reasoningMetadata(state.providerMetadataKey, state.reasoningField))
|
|
1084
|
+
: state.lifecycle;
|
|
1085
|
+
const ended = Lifecycle.reasoningEnd(started, events, "reasoning-0", metadata);
|
|
1086
|
+
const lifecycle = toolCallEvents.length ? Lifecycle.start(ended) : ended;
|
|
1087
|
+
events.push(...toolCallEvents);
|
|
1088
|
+
Lifecycle.finish(lifecycle, events, { ...finish, usage: state.usage });
|
|
1089
|
+
return events;
|
|
1090
|
+
});
|
|
1091
|
+
// =============================================================================
|
|
1092
|
+
// Protocol And OpenAI Route
|
|
1093
|
+
// =============================================================================
|
|
1094
|
+
/**
|
|
1095
|
+
* The OpenAI Chat protocol — request body construction, body schema, and the
|
|
1096
|
+
* streaming-event state machine. Reused by every route that speaks OpenAI Chat
|
|
1097
|
+
* over HTTP+SSE: native OpenAI, DeepSeek, TogetherAI, Cerebras, Baseten,
|
|
1098
|
+
* Fireworks, DeepInfra, and (once added) Azure OpenAI Chat.
|
|
1099
|
+
*/
|
|
1100
|
+
export const protocol = Protocol.make({
|
|
1101
|
+
id: ADAPTER,
|
|
1102
|
+
body: {
|
|
1103
|
+
schema: OpenAIChatBody,
|
|
1104
|
+
from: fromRequest,
|
|
1105
|
+
},
|
|
1106
|
+
stream: {
|
|
1107
|
+
event: OpenAIChatStreamEvent,
|
|
1108
|
+
initial: (request) => ({
|
|
1109
|
+
providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
|
|
1110
|
+
tools: ToolStream.empty(),
|
|
1111
|
+
custom: OpenAIFreeform.tools(request),
|
|
1112
|
+
customCalls: new Set(),
|
|
1113
|
+
pendingTools: {},
|
|
1114
|
+
toolCallEvents: [],
|
|
1115
|
+
lifecycle: Lifecycle.initial(),
|
|
1116
|
+
reasoningField: request.model.compatibility?.reasoningField,
|
|
1117
|
+
reasoningTextObserved: false,
|
|
1118
|
+
reasoningDetails: [],
|
|
1119
|
+
reasoningDetailsObserved: false,
|
|
1120
|
+
reasoningEmitted: false,
|
|
1121
|
+
nextToolIndex: 0,
|
|
1122
|
+
requireFinishReason: request.model.compatibility?.requireFinishReason ?? true,
|
|
1123
|
+
}),
|
|
1124
|
+
step: (state, event) => (event === DONE ? Effect.succeed([state, []]) : step(state, event)),
|
|
1125
|
+
terminal: (event) => event === DONE,
|
|
1126
|
+
onHalt: finishEvents,
|
|
1127
|
+
},
|
|
1128
|
+
});
|
|
1129
|
+
export const framing = Framing.sseWithDone;
|
|
1130
|
+
export const httpTransport = HttpTransport.sseJson.with().with({ framing });
|
|
1131
|
+
export const route = Route.make({
|
|
1132
|
+
id: ADAPTER,
|
|
1133
|
+
provider: "openai",
|
|
1134
|
+
providerMetadataKey: "openai",
|
|
1135
|
+
protocol,
|
|
1136
|
+
endpoint: Endpoint.path(PATH, { baseURL: DEFAULT_BASE_URL }),
|
|
1137
|
+
auth: Auth.none,
|
|
1138
|
+
transport: httpTransport,
|
|
1139
|
+
});
|
|
1140
|
+
export * as OpenAIChat from "./openai-chat.js";
|