feat(ai): OpenAI-style Chat routes for xAI, Anthropic and Google

This commit is contained in:
Aiden Cline 2026-10-31 12:10:21 -05:00
parent 7ce35879b8
commit 3eb96a04fb
15 changed files with 478 additions and 6 deletions

View file

@ -34,6 +34,7 @@
"./providers/amazon-bedrock/mantle/responses": "./src/providers/amazon-bedrock/mantle/responses.ts",
"./providers/anthropic": "./src/providers/anthropic.ts",
"./providers/anthropic-compatible": "./src/providers/anthropic-compatible.ts",
"./providers/anthropic/chat": "./src/providers/anthropic/chat.ts",
"./providers/assemblyai": "./src/providers/assemblyai.ts",
"./providers/azure": "./src/providers/azure.ts",
"./providers/azure/chat": "./src/providers/azure/chat.ts",
@ -70,6 +71,7 @@
"./providers/google-vertex/messages": "./src/providers/google-vertex/messages.ts",
"./providers/google-vertex/mistral": "./src/providers/google-vertex/mistral.ts",
"./providers/google-vertex/responses": "./src/providers/google-vertex/responses.ts",
"./providers/google/chat": "./src/providers/google/chat.ts",
"./providers/google/images": "./src/providers/google/images.ts",
"./providers/google/interactions": "./src/providers/google/interactions.ts",
"./providers/groq": "./src/providers/groq.ts",
@ -115,6 +117,7 @@
"./providers/vercel-ai-gateway/messages": "./src/providers/vercel-ai-gateway/messages.ts",
"./providers/vercel-ai-gateway/responses": "./src/providers/vercel-ai-gateway/responses.ts",
"./providers/xai": "./src/providers/xai.ts",
"./providers/xai/chat": "./src/providers/xai/chat.ts",
"./providers/xai/images": "./src/providers/xai/images.ts",
"./providers/zai": "./src/providers/zai.ts",
"./providers/zai-coding-plan": "./src/providers/zai-coding-plan.ts",

View file

@ -1,10 +1,13 @@
import type { RouteDefaultsInput } from "../route/client.js"
import { Route, type RouteDefaultsInput } from "../route/client.js"
import { Endpoint } from "../route/endpoint.js"
import { Auth } from "../route/auth.js"
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
import type { ProviderPackage } from "../provider-package.js"
import { ProviderConfigurationError, ProviderID, type ModelID } from "../schema/index.js"
import { AnthropicMessages } from "../protocols/anthropic-messages.js"
import { OpenAIChat } from "../protocols/openai-chat.js"
import { AnthropicCompatible } from "./anthropic-compatible.js"
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
export type AnthropicOptionsInput = AnthropicMessages.OptionsInput
export type AnthropicProviderOptionsInput = AnthropicMessages.ProviderOptionsInput
@ -12,7 +15,17 @@ export type AnthropicThinkingInput = AnthropicMessages.ThinkingInput
export const id = ProviderID.make("anthropic")
export const routes = [AnthropicMessages.route]
// Anthropic's OpenAI SDK compatibility layer: https://platform.claude.com/docs/en/cli-sdks-libraries/libraries/openai-sdk
const chatRoute = Route.make({
id: "anthropic-chat",
provider: id,
providerMetadataKey: "anthropic",
protocol: OpenAIChat.protocol,
endpoint: Endpoint.path("/chat/completions", { baseURL: AnthropicMessages.DEFAULT_BASE_URL }),
framing: OpenAIChat.framing,
})
export const routes = [AnthropicMessages.route, chatRoute]
export type Config = RouteDefaultsInput &
ProviderAuthOption<"optional"> & {
@ -20,6 +33,7 @@ export type Config = RouteDefaultsInput &
readonly providerOptions?: AnthropicMessages.ProviderOptionsInput
}
export type Settings = ProviderPackage.Settings &
AnthropicMessages.ProviderOptionsInput &
(
@ -29,25 +43,47 @@ export type Settings = ProviderPackage.Settings &
readonly baseURL?: string
}
export type ChatSettings = ProviderPackage.Settings &
OpenAIProviderOptionsInput & {
readonly apiKey?: string | false
readonly baseURL?: string
}
const auth = (options: ProviderAuthOption<"optional">) =>
AuthOptions.apiKey(options, "ANTHROPIC_API_KEY", Auth.header("x-api-key"))
export const configure = (input: Config = {}) => {
const { apiKey: _, auth: _auth, baseURL, ...rest } = input
const { apiKey: _, auth: _auth, baseURL, providerOptions, ...defaults } = input
const compatible = AnthropicCompatible.configure({
...rest,
...defaults,
providerOptions,
auth: auth(input),
baseURL: baseURL ?? AnthropicMessages.DEFAULT_BASE_URL,
provider: id,
})
// Messages provider options don't apply to Chat; pass Chat options through `chatModel` instead.
const chatRoute = configuredChat({ ...defaults, baseURL, auth: chatAuth(input) })
return {
id,
model: (modelID: string | ModelID) => compatible.model(modelID),
chat: (modelID: string | ModelID) => chatRoute.model<OpenAIProviderOptionsInput>({ id: modelID }),
configure,
}
}
const chatAuth = (options: ProviderAuthOption<"optional">) => AuthOptions.bearer(options, "ANTHROPIC_API_KEY")
const configuredChat = ({
baseURL,
...rest
}: Omit<RouteDefaultsInput, "providerOptions"> & {
readonly baseURL?: string
readonly auth: Auth.Definition
readonly providerOptions?: OpenAIProviderOptionsInput
}) => chatRoute.with({ ...rest, endpoint: { baseURL: baseURL ?? AnthropicMessages.DEFAULT_BASE_URL } })
export const provider = configure()
export const chat = provider.chat
export const model: ProviderPackage.Model<Settings, AnthropicMessages.ProviderOptionsInput> = (
modelID,
{ apiKey, authToken, baseURL, body, headers, ...providerOptions }: Settings = {},
@ -65,3 +101,15 @@ export const model: ProviderPackage.Model<Settings, AnthropicMessages.ProviderOp
providerOptions,
}).model(modelID)
}
export const chatModel: ProviderPackage.Model<ChatSettings, OpenAIProviderOptionsInput> = (
modelID,
{ apiKey, baseURL, body, headers, ...providerOptions }: ChatSettings = {},
) =>
configuredChat({
auth: chatAuth({ apiKey }),
baseURL,
headers,
http: body === undefined ? undefined : { body },
providerOptions,
}).model<OpenAIProviderOptionsInput>({ id: modelID })

View file

@ -0,0 +1,2 @@
export { chatModel as model } from "../anthropic.js"
export type { ChatSettings as Settings } from "../anthropic.js"

View file

@ -1,15 +1,18 @@
import type { RouteDefaultsInput } from "../route/client.js"
import { Route, type RouteDefaultsInput } from "../route/client.js"
import { Endpoint } from "../route/endpoint.js"
import { Auth } from "../route/auth.js"
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
import { MediaRoute } from "../route/media.js"
import type { ProviderPackage } from "../provider-package.js"
import { ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js"
import { Gemini } from "../protocols/gemini.js"
import { OpenAIChat } from "../protocols/openai-chat.js"
import { GoogleInteractions } from "../protocols/google-interactions.js"
import { GoogleImages } from "../protocols/google-images.js"
import { GoogleSpeech } from "../protocols/google-speech.js"
import { GoogleTranscription } from "../protocols/google-transcription.js"
import { GoogleVideo } from "../protocols/google-video.js"
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
export type { GoogleImageOptions } from "../protocols/google-images.js"
export type { GoogleSpeechOptions } from "../protocols/google-speech.js"
@ -21,7 +24,19 @@ export type GoogleInteractionsOptionsInput = GoogleInteractions.OptionsInput
export const id = ProviderID.make("google")
export const routes = [Gemini.route, GoogleInteractions.route]
const CHAT_BASE_URL = `${Gemini.DEFAULT_BASE_URL}/openai`
// Gemini's OpenAI-compatible endpoint: https://ai.google.dev/gemini-api/docs/openai
const chatRoute = Route.make({
id: "google-chat",
provider: id,
providerMetadataKey: "google",
protocol: OpenAIChat.protocol,
endpoint: Endpoint.path("/chat/completions", { baseURL: CHAT_BASE_URL }),
framing: OpenAIChat.framing,
})
export const routes = [Gemini.route, GoogleInteractions.route, chatRoute]
export type Config = RouteDefaultsInput &
ProviderAuthOption<"optional"> & {
@ -35,6 +50,12 @@ export type Settings = ProviderPackage.Settings &
readonly baseURL?: string
}
export type ChatSettings = ProviderPackage.Settings &
OpenAIProviderOptionsInput & {
readonly apiKey?: string | false
readonly baseURL?: string
}
const auth = (options: ProviderAuthOption<"optional">) =>
AuthOptions.apiKey(options, "GOOGLE_GENERATIVE_AI_API_KEY", Auth.header("x-goog-api-key"))
@ -48,8 +69,28 @@ const interactionsRoute = (input: Config) => {
return GoogleInteractions.route.with({ ...rest, endpoint: { baseURL }, auth: auth(input) })
}
const chatAuth = (options: ProviderAuthOption<"optional">) =>
AuthOptions.bearer(options, "GOOGLE_GENERATIVE_AI_API_KEY")
const configuredChatRoute = ({
baseURL,
...rest
}: Omit<RouteDefaultsInput, "providerOptions"> & {
readonly baseURL?: string
readonly auth: Auth.Definition
readonly providerOptions?: OpenAIProviderOptionsInput
}) => chatRoute.with({ ...rest, endpoint: { baseURL: baseURL ?? CHAT_BASE_URL } })
export const configure = (input: Config = {}) => {
const route = configuredRoute(input)
const { apiKey: _, auth: _auth, baseURL, providerOptions: _options, ...defaults } = input
// `baseURL` is the Gemini API root, which serves Chat under `/openai`. Gemini provider options don't apply to Chat;
// pass Chat options through `chatModel` instead.
const chat = configuredChatRoute({
...defaults,
baseURL: baseURL === undefined ? undefined : `${baseURL}/openai`,
auth: chatAuth(input),
})
const media = MediaRoute.deployment(input, auth(input))
const gemini = (modelID: string | ModelID) => route.model<Gemini.ProviderOptionsInput>({ id: modelID })
return {
@ -58,6 +99,7 @@ export const configure = (input: Config = {}) => {
gemini,
interactions: (modelID: string | ModelID) =>
interactionsRoute(input).model<GoogleInteractions.ProviderOptionsInput>({ id: modelID }),
chat: (modelID: string | ModelID) => chat.model<OpenAIProviderOptionsInput>({ id: modelID }),
image: (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
GoogleImages.model({ ...media, id: modelID, providerOptions }),
video: (modelID: string | ModelID) => GoogleVideo.model({ ...media, id: modelID }),
@ -70,6 +112,17 @@ export const configure = (input: Config = {}) => {
export const provider = configure()
export const model: ProviderPackage.Model<Settings, Gemini.ProviderOptionsInput> = (modelID, settings) =>
configure(config(settings)).model(modelID)
export const chatModel: ProviderPackage.Model<ChatSettings, OpenAIProviderOptionsInput> = (
modelID,
{ apiKey, baseURL, body, headers, ...providerOptions }: ChatSettings = {},
) =>
configuredChatRoute({
auth: chatAuth({ apiKey }),
baseURL,
headers,
http: body === undefined ? undefined : { body },
providerOptions,
}).model<OpenAIProviderOptionsInput>({ id: modelID })
export const imageModel = (modelID: string, settings?: Settings) => {
const input = config(settings)
return configure(input).image(modelID, input.providerOptions)
@ -87,6 +140,7 @@ function config({ apiKey, baseURL, body, headers, ...providerOptions }: Settings
export const image = provider.image
export const gemini = provider.gemini
export const chat = provider.chat
export const interactions = provider.interactions
export const video = provider.video
export const speech = provider.speech

View file

@ -0,0 +1,2 @@
export { chatModel as model } from "../google.js"
export type { ChatSettings as Settings } from "../google.js"

View file

@ -109,6 +109,8 @@ export const model: ProviderPackage.Model<Settings, XAIProviderOptionsInput, typ
modelID,
settings,
) => configure(config(settings)).model(modelID)
export const chatModel: ProviderPackage.Model<Settings, XAIProviderOptionsInput> = (modelID, settings) =>
configure(config(settings)).chat(modelID)
export const imageModel = (modelID: string, settings?: Settings) => {
const input = config(settings)
return configure(input).image(modelID, input.providerOptions)

View file

@ -0,0 +1,2 @@
export { chatModel as model } from "../xai.js"
export type { Settings } from "../xai.js"

View file

@ -0,0 +1,53 @@
{
"version": 1,
"metadata": {
"model": "claude-haiku-4-5",
"tags": [
"prefix:anthropic-chat",
"provider:anthropic",
"protocol:openai-chat",
"tool",
"tool-loop"
],
"name": "anthropic-chat/continues-a-tool-call",
"recordedAt": "2026-10-31T17:08:34.257Z"
},
"interactions": [
{
"transport": "http",
"request": {
"method": "POST",
"url": "https://api.anthropic.com/v1/chat/completions",
"headers": {
"content-type": "application/json"
},
"body": "{\"model\":\"claude-haiku-4-5\",\"messages\":[{\"role\":\"system\",\"content\":\"Use the get_weather tool exactly once. After the tool result, reply exactly: Paris is sunny.\"},{\"role\":\"user\",\"content\":\"What is the weather in Paris?\"}],\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"description\":\"Get current weather for a city.\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"],\"additionalProperties\":false},\"strict\":false}}],\"stream\":true,\"stream_options\":{\"include_usage\":true},\"max_completion_tokens\":256}"
},
"response": {
"status": 200,
"headers": {
"content-type": "text/event-stream"
},
"body": "data: {\"id\":\"msg_011CgagakAzJNVzjZhYL4GVk\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\"}}],\"created\":1793466513,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\" }\n\ndata: {\"id\":\"msg_011CgagakAzJNVzjZhYL4GVk\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"toolu_018jrkS2pzcUKPcYpzZP7JUR\",\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"arguments\":\"\"}}]}}],\"created\":1793466513,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\" }\n\ndata: {\"id\":\"msg_011CgagakAzJNVzjZhYL4GVk\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"type\":\"function\",\"function\":{\"arguments\":\"\"}}]}}],\"created\":1793466513,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\" }\n\ndata: {\"id\":\"msg_011CgagakAzJNVzjZhYL4GVk\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"type\":\"function\",\"function\":{\"arguments\":\"{\\\"city\\\"\"}}]}}],\"created\":1793466513,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\" }\n\ndata: {\"id\":\"msg_011CgagakAzJNVzjZhYL4GVk\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"type\":\"function\",\"function\":{\"arguments\":\": \\\"Pari\"}}]}}],\"created\":1793466513,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\" }\n\ndata: {\"id\":\"msg_011CgagakAzJNVzjZhYL4GVk\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"type\":\"function\",\"function\":{\"arguments\":\"s\\\"}\"}}]}}],\"created\":1793466513,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\" }\n\ndata: {\"id\":\"msg_011CgagakAzJNVzjZhYL4GVk\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}],\"created\":1793466513,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\",\"usage\":{\"completion_tokens\":54,\"prompt_tokens\":593,\"total_tokens\":647} }\n\ndata: [DONE]\n\n"
}
},
{
"transport": "http",
"request": {
"method": "POST",
"url": "https://api.anthropic.com/v1/chat/completions",
"headers": {
"content-type": "application/json"
},
"body": "{\"model\":\"claude-haiku-4-5\",\"messages\":[{\"role\":\"system\",\"content\":\"Use the get_weather tool exactly once. After the tool result, reply exactly: Paris is sunny.\"},{\"role\":\"user\",\"content\":\"What is the weather in Paris?\"},{\"role\":\"assistant\",\"content\":null,\"tool_calls\":[{\"id\":\"toolu_018jrkS2pzcUKPcYpzZP7JUR\",\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"arguments\":\"{\\\"city\\\":\\\"Paris\\\"}\"}}]},{\"role\":\"tool\",\"tool_call_id\":\"toolu_018jrkS2pzcUKPcYpzZP7JUR\",\"content\":\"{\\\"temperature\\\":22,\\\"condition\\\":\\\"sunny\\\"}\"}],\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"description\":\"Get current weather for a city.\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"],\"additionalProperties\":false},\"strict\":false}}],\"stream\":true,\"stream_options\":{\"include_usage\":true},\"max_completion_tokens\":256}"
},
"response": {
"status": 200,
"headers": {
"content-type": "text/event-stream"
},
"body": "data: {\"id\":\"msg_011CgagaoAotSgrR2nUfMCfv\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\"}}],\"created\":1793466513,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\" }\n\ndata: {\"id\":\"msg_011CgagaoAotSgrR2nUfMCfv\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Paris\"}}],\"created\":1793466513,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\" }\n\ndata: {\"id\":\"msg_011CgagaoAotSgrR2nUfMCfv\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\" is\"}}],\"created\":1793466513,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\" }\n\ndata: {\"id\":\"msg_011CgagaoAotSgrR2nUfMCfv\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\" sunny\"}}],\"created\":1793466513,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\" }\n\ndata: {\"id\":\"msg_011CgagaoAotSgrR2nUfMCfv\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\".\"}}],\"created\":1793466513,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\" }\n\ndata: {\"id\":\"msg_011CgagaoAotSgrR2nUfMCfv\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"created\":1793466513,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\",\"usage\":{\"completion_tokens\":7,\"prompt_tokens\":668,\"total_tokens\":675} }\n\ndata: [DONE]\n\n"
}
}
]
}

View file

@ -0,0 +1,35 @@
{
"version": 1,
"metadata": {
"model": "claude-haiku-4-5",
"tags": [
"prefix:anthropic-chat",
"provider:anthropic",
"protocol:openai-chat",
"text",
"usage"
],
"name": "anthropic-chat/streams-text",
"recordedAt": "2026-10-31T17:08:33.113Z"
},
"interactions": [
{
"transport": "http",
"request": {
"method": "POST",
"url": "https://api.anthropic.com/v1/chat/completions",
"headers": {
"content-type": "application/json"
},
"body": "{\"model\":\"claude-haiku-4-5\",\"messages\":[{\"role\":\"user\",\"content\":\"Reply with exactly one word: hello\"}],\"stream\":true,\"stream_options\":{\"include_usage\":true},\"max_completion_tokens\":256}"
},
"response": {
"status": 200,
"headers": {
"content-type": "text/event-stream"
},
"body": "data: {\"id\":\"msg_011CgagaiS4DzAZ3qffBsD7q\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\"}}],\"created\":1793466512,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\" }\n\ndata: {\"id\":\"msg_011CgagaiS4DzAZ3qffBsD7q\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hello\"}}],\"created\":1793466512,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\" }\n\ndata: {\"id\":\"msg_011CgagaiS4DzAZ3qffBsD7q\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"created\":1793466512,\"model\":\"claude-haiku-4-5-20251001\",\"object\":\"chat.completion.chunk\",\"usage\":{\"completion_tokens\":4,\"prompt_tokens\":14,\"total_tokens\":18} }\n\ndata: [DONE]\n\n"
}
}
]
}

View file

@ -0,0 +1,53 @@
{
"version": 1,
"metadata": {
"model": "gemini-3.5-flash-lite",
"tags": [
"prefix:google-chat",
"provider:google",
"protocol:openai-chat",
"tool",
"tool-loop"
],
"name": "google-chat/continues-a-tool-call",
"recordedAt": "2026-10-31T17:08:35.923Z"
},
"interactions": [
{
"transport": "http",
"request": {
"method": "POST",
"url": "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
"headers": {
"content-type": "application/json"
},
"body": "{\"model\":\"gemini-3.5-flash-lite\",\"messages\":[{\"role\":\"system\",\"content\":\"Use the get_weather tool exactly once. After the tool result, reply exactly: Paris is sunny.\"},{\"role\":\"user\",\"content\":\"What is the weather in Paris?\"}],\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"description\":\"Get current weather for a city.\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"],\"additionalProperties\":false},\"strict\":false}}],\"stream\":true,\"stream_options\":{\"include_usage\":true},\"max_completion_tokens\":1024}"
},
"response": {
"status": 200,
"headers": {
"content-type": "text/event-stream"
},
"body": "data: {\"choices\":[{\"delta\":{\"role\":\"assistant\",\"tool_calls\":[{\"extra_content\":{\"google\":{\"thought_signature\":\"EmAKXgFpFH0T593JIvdTiFGZ623F1xhKKp/+yoTwRiS0OIsNOR48wTGLw6+gdjIPxBAWODNJldznsdGY2rs5jsJBgrw/sQwMnlrSMMU66sLYImfvOVCfwj9/acKmHsRdZGY=\"}},\"function\":{\"arguments\":\"{\\\"city\\\":\\\"Paris\\\"}\",\"name\":\"get_weather\"},\"id\":\"call_621013\",\"type\":\"function\"}]},\"index\":0}],\"created\":1793466515,\"id\":\"kyDmaub9CufVz7IP4OaE8Qg\",\"model\":\"gemini-3.5-flash-lite\",\"object\":\"chat.completion.chunk\",\"usage\":{\"completion_tokens\":16,\"prompt_tokens\":74,\"total_tokens\":90}}\n\ndata: {\"choices\":[{\"delta\":{\"role\":\"assistant\"},\"finish_reason\":\"stop\",\"index\":0}],\"created\":1793466515,\"id\":\"kyDmaub9CufVz7IP4OaE8Qg\",\"model\":\"gemini-3.5-flash-lite\",\"object\":\"chat.completion.chunk\",\"usage\":{\"completion_tokens\":16,\"prompt_tokens\":74,\"total_tokens\":90}}\n\ndata: [DONE]\n\n"
}
},
{
"transport": "http",
"request": {
"method": "POST",
"url": "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
"headers": {
"content-type": "application/json"
},
"body": "{\"model\":\"gemini-3.5-flash-lite\",\"messages\":[{\"role\":\"system\",\"content\":\"Use the get_weather tool exactly once. After the tool result, reply exactly: Paris is sunny.\"},{\"role\":\"user\",\"content\":\"What is the weather in Paris?\"},{\"role\":\"assistant\",\"content\":null,\"tool_calls\":[{\"id\":\"call_621013\",\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"arguments\":\"{\\\"city\\\":\\\"Paris\\\"}\"},\"extra_content\":{\"google\":{\"thought_signature\":\"EmAKXgFpFH0T593JIvdTiFGZ623F1xhKKp/+yoTwRiS0OIsNOR48wTGLw6+gdjIPxBAWODNJldznsdGY2rs5jsJBgrw/sQwMnlrSMMU66sLYImfvOVCfwj9/acKmHsRdZGY=\"}}}]},{\"role\":\"tool\",\"tool_call_id\":\"call_621013\",\"content\":\"{\\\"temperature\\\":22,\\\"condition\\\":\\\"sunny\\\"}\"}],\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"description\":\"Get current weather for a city.\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"],\"additionalProperties\":false},\"strict\":false}}],\"stream\":true,\"stream_options\":{\"include_usage\":true},\"max_completion_tokens\":1024}"
},
"response": {
"status": 200,
"headers": {
"content-type": "text/event-stream"
},
"body": "data: {\"choices\":[{\"delta\":{\"content\":\"Paris is\",\"role\":\"assistant\"},\"index\":0}],\"created\":1793466515,\"id\":\"kyDmavytI7yez7IP4anQiA0\",\"model\":\"gemini-3.5-flash-lite\",\"object\":\"chat.completion.chunk\",\"usage\":{\"completion_tokens\":2,\"prompt_tokens\":113,\"total_tokens\":115}}\n\ndata: {\"choices\":[{\"delta\":{\"content\":\" sunny.\",\"role\":\"assistant\"},\"index\":0}],\"created\":1793466515,\"id\":\"kyDmavytI7yez7IP4anQiA0\",\"model\":\"gemini-3.5-flash-lite\",\"object\":\"chat.completion.chunk\",\"usage\":{\"completion_tokens\":4,\"prompt_tokens\":113,\"total_tokens\":117}}\n\ndata: {\"choices\":[{\"delta\":{\"extra_content\":{\"google\":{\"thought_signature\":\"EmAKXgFpFH0TLwqo+Wlrf8GoZFHNU+lYObcJ1Dsd/iT1H0zejL+Z4R6FtQUewnCTeOm7yFlG2LU/xp7/+aNmMsS7z7dJt/U8/ZN1JsrdIFUwSWp2JDNZLUX6lCZWHEez/kU=\"}},\"role\":\"assistant\"},\"finish_reason\":\"stop\",\"index\":0}],\"created\":1793466515,\"id\":\"kyDmavytI7yez7IP4anQiA0\",\"model\":\"gemini-3.5-flash-lite\",\"object\":\"chat.completion.chunk\",\"usage\":{\"completion_tokens\":4,\"prompt_tokens\":113,\"total_tokens\":117}}\n\ndata: [DONE]\n\n"
}
}
]
}

View file

@ -0,0 +1,35 @@
{
"version": 1,
"metadata": {
"model": "gemini-3.5-flash-lite",
"tags": [
"prefix:google-chat",
"provider:google",
"protocol:openai-chat",
"text",
"usage"
],
"name": "google-chat/streams-text",
"recordedAt": "2026-10-31T17:08:35.032Z"
},
"interactions": [
{
"transport": "http",
"request": {
"method": "POST",
"url": "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
"headers": {
"content-type": "application/json"
},
"body": "{\"model\":\"gemini-3.5-flash-lite\",\"messages\":[{\"role\":\"user\",\"content\":\"Reply with exactly one word: hello\"}],\"stream\":true,\"stream_options\":{\"include_usage\":true},\"max_completion_tokens\":1024}"
},
"response": {
"status": 200,
"headers": {
"content-type": "text/event-stream"
},
"body": "data: {\"choices\":[{\"delta\":{\"content\":\"Hello\",\"role\":\"assistant\"},\"index\":0}],\"created\":1793466515,\"id\":\"kiDmapqHHsPXz7IP9ZD0mQ0\",\"model\":\"gemini-3.5-flash-lite\",\"object\":\"chat.completion.chunk\",\"usage\":{\"completion_tokens\":1,\"prompt_tokens\":8,\"total_tokens\":9}}\n\ndata: {\"choices\":[{\"delta\":{\"extra_content\":{\"google\":{\"thought_signature\":\"EmAKXgFpFH0T4TX8eJQ87yo8sqhTvDTWFsYyVZubRZJbAJ4b/fqWjp9Rjj9LJ3MRjlQvkkVvLe+BKpULTfKMD9aP1hHnGye0at4tt7LxxbQLSbooS1l/clXfASb4hkm/41c=\"}},\"role\":\"assistant\"},\"finish_reason\":\"stop\",\"index\":0}],\"created\":1793466515,\"id\":\"kiDmapqHHsPXz7IP9ZD0mQ0\",\"model\":\"gemini-3.5-flash-lite\",\"object\":\"chat.completion.chunk\",\"usage\":{\"completion_tokens\":1,\"prompt_tokens\":8,\"total_tokens\":9}}\n\ndata: [DONE]\n\n"
}
}
]
}

View file

@ -0,0 +1,53 @@
{
"version": 1,
"metadata": {
"model": "grok-4.20-0309-non-reasoning",
"tags": [
"prefix:xai-chat",
"provider:xai",
"protocol:openai-chat",
"tool",
"tool-loop"
],
"name": "xai-chat/continues-a-tool-call",
"recordedAt": "2026-10-31T17:08:37.317Z"
},
"interactions": [
{
"transport": "http",
"request": {
"method": "POST",
"url": "https://api.x.ai/v1/chat/completions",
"headers": {
"content-type": "application/json"
},
"body": "{\"model\":\"grok-4.20-0309-non-reasoning\",\"messages\":[{\"role\":\"system\",\"content\":\"Use the get_weather tool exactly once. After the tool result, reply exactly: Paris is sunny.\"},{\"role\":\"user\",\"content\":\"What is the weather in Paris?\"}],\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"description\":\"Get current weather for a city.\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"],\"additionalProperties\":false},\"strict\":false}}],\"stream\":true,\"stream_options\":{\"include_usage\":true},\"max_completion_tokens\":256}"
},
"response": {
"status": 200,
"headers": {
"content-type": "text/event-stream"
},
"body": "data: {\"id\":\"54851786-6328-9c56-be7f-318562eee856\",\"object\":\"chat.completion.chunk\",\"created\":1793466516,\"model\":\"grok-4.20-0309-non-reasoning\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"tool_calls\":[{\"id\":\"call-9667d575-fe99-4680-b117-691a3659bd04-0\",\"function\":{\"name\":\"get_weather\",\"arguments\":\"{\\\"city\\\":\\\"Paris\\\"}\"},\"index\":0,\"type\":\"function\"}]}}],\"system_fingerprint\":\"fp_8d6266e762\",\"service_tier\":\"default\"}\n\ndata: {\"id\":\"54851786-6328-9c56-be7f-318562eee856\",\"object\":\"chat.completion.chunk\",\"created\":1793466516,\"model\":\"grok-4.20-0309-non-reasoning\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}],\"system_fingerprint\":\"fp_8d6266e762\",\"service_tier\":\"default\"}\n\ndata: {\"id\":\"54851786-6328-9c56-be7f-318562eee856\",\"object\":\"chat.completion.chunk\",\"created\":1793466516,\"model\":\"grok-4.20-0309-non-reasoning\",\"choices\":[],\"usage\":{\"prompt_tokens\":296,\"completion_tokens\":10,\"total_tokens\":306,\"prompt_tokens_details\":{\"text_tokens\":296,\"audio_tokens\":0,\"image_tokens\":0,\"cached_tokens\":128},\"completion_tokens_details\":{\"reasoning_tokens\":0,\"audio_tokens\":0,\"accepted_prediction_tokens\":0,\"rejected_prediction_tokens\":0},\"num_sources_used\":0,\"cost_in_usd_ticks\":2606000},\"system_fingerprint\":\"fp_8d6266e762\",\"service_tier\":\"default\"}\n\ndata: [DONE]\n\n"
}
},
{
"transport": "http",
"request": {
"method": "POST",
"url": "https://api.x.ai/v1/chat/completions",
"headers": {
"content-type": "application/json"
},
"body": "{\"model\":\"grok-4.20-0309-non-reasoning\",\"messages\":[{\"role\":\"system\",\"content\":\"Use the get_weather tool exactly once. After the tool result, reply exactly: Paris is sunny.\"},{\"role\":\"user\",\"content\":\"What is the weather in Paris?\"},{\"role\":\"assistant\",\"content\":null,\"tool_calls\":[{\"id\":\"call-9667d575-fe99-4680-b117-691a3659bd04-0\",\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"arguments\":\"{\\\"city\\\":\\\"Paris\\\"}\"}}]},{\"role\":\"tool\",\"tool_call_id\":\"call-9667d575-fe99-4680-b117-691a3659bd04-0\",\"content\":\"{\\\"temperature\\\":22,\\\"condition\\\":\\\"sunny\\\"}\"}],\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"description\":\"Get current weather for a city.\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"],\"additionalProperties\":false},\"strict\":false}}],\"stream\":true,\"stream_options\":{\"include_usage\":true},\"max_completion_tokens\":256}"
},
"response": {
"status": 200,
"headers": {
"content-type": "text/event-stream"
},
"body": "data: {\"id\":\"21228b3a-d8ee-9d40-98e5-28541fb2cb0c\",\"object\":\"chat.completion.chunk\",\"created\":1793466517,\"model\":\"grok-4.20-0309-non-reasoning\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Paris\",\"role\":\"assistant\"}}],\"system_fingerprint\":\"fp_8d6266e762\",\"service_tier\":\"default\"}\n\ndata: {\"id\":\"21228b3a-d8ee-9d40-98e5-28541fb2cb0c\",\"object\":\"chat.completion.chunk\",\"created\":1793466517,\"model\":\"grok-4.20-0309-non-reasoning\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\" is\"}}],\"system_fingerprint\":\"fp_8d6266e762\",\"service_tier\":\"default\"}\n\ndata: {\"id\":\"21228b3a-d8ee-9d40-98e5-28541fb2cb0c\",\"object\":\"chat.completion.chunk\",\"created\":1793466517,\"model\":\"grok-4.20-0309-non-reasoning\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\" sunny\"}}],\"system_fingerprint\":\"fp_8d6266e762\",\"service_tier\":\"default\"}\n\ndata: {\"id\":\"21228b3a-d8ee-9d40-98e5-28541fb2cb0c\",\"object\":\"chat.completion.chunk\",\"created\":1793466517,\"model\":\"grok-4.20-0309-non-reasoning\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\".\"}}],\"system_fingerprint\":\"fp_8d6266e762\",\"service_tier\":\"default\"}\n\ndata: {\"id\":\"21228b3a-d8ee-9d40-98e5-28541fb2cb0c\",\"object\":\"chat.completion.chunk\",\"created\":1793466517,\"model\":\"grok-4.20-0309-non-reasoning\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"system_fingerprint\":\"fp_8d6266e762\",\"service_tier\":\"default\"}\n\ndata: {\"id\":\"21228b3a-d8ee-9d40-98e5-28541fb2cb0c\",\"object\":\"chat.completion.chunk\",\"created\":1793466517,\"model\":\"grok-4.20-0309-non-reasoning\",\"choices\":[],\"usage\":{\"prompt_tokens\":321,\"completion_tokens\":4,\"total_tokens\":325,\"prompt_tokens_details\":{\"text_tokens\":321,\"audio_tokens\":0,\"image_tokens\":0,\"cached_tokens\":256},\"completion_tokens_details\":{\"reasoning_tokens\":0,\"audio_tokens\":0,\"accepted_prediction_tokens\":0,\"rejected_prediction_tokens\":0},\"num_sources_used\":0,\"cost_in_usd_ticks\":1424500},\"system_fingerprint\":\"fp_8d6266e762\",\"service_tier\":\"default\"}\n\ndata: [DONE]\n\n"
}
}
]
}

View file

@ -0,0 +1,35 @@
{
"version": 1,
"metadata": {
"model": "grok-4.20-0309-non-reasoning",
"tags": [
"prefix:xai-chat",
"provider:xai",
"protocol:openai-chat",
"text",
"usage"
],
"name": "xai-chat/streams-text",
"recordedAt": "2026-10-31T17:08:36.469Z"
},
"interactions": [
{
"transport": "http",
"request": {
"method": "POST",
"url": "https://api.x.ai/v1/chat/completions",
"headers": {
"content-type": "application/json"
},
"body": "{\"model\":\"grok-4.20-0309-non-reasoning\",\"messages\":[{\"role\":\"user\",\"content\":\"Reply with exactly one word: hello\"}],\"stream\":true,\"stream_options\":{\"include_usage\":true},\"max_completion_tokens\":256}"
},
"response": {
"status": 200,
"headers": {
"content-type": "text/event-stream"
},
"body": "data: {\"id\":\"c49dcb74-ce08-900d-a735-e936a9122b0f\",\"object\":\"chat.completion.chunk\",\"created\":1793466516,\"model\":\"grok-4.20-0309-non-reasoning\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"hello\",\"role\":\"assistant\"}}],\"system_fingerprint\":\"fp_8d6266e762\",\"service_tier\":\"default\"}\n\ndata: {\"id\":\"c49dcb74-ce08-900d-a735-e936a9122b0f\",\"object\":\"chat.completion.chunk\",\"created\":1793466516,\"model\":\"grok-4.20-0309-non-reasoning\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"system_fingerprint\":\"fp_8d6266e762\",\"service_tier\":\"default\"}\n\ndata: {\"id\":\"c49dcb74-ce08-900d-a735-e936a9122b0f\",\"object\":\"chat.completion.chunk\",\"created\":1793466516,\"model\":\"grok-4.20-0309-non-reasoning\",\"choices\":[],\"usage\":{\"prompt_tokens\":191,\"completion_tokens\":1,\"total_tokens\":192,\"prompt_tokens_details\":{\"text_tokens\":191,\"audio_tokens\":0,\"image_tokens\":0,\"cached_tokens\":128},\"completion_tokens_details\":{\"reasoning_tokens\":0,\"audio_tokens\":0,\"accepted_prediction_tokens\":0,\"rejected_prediction_tokens\":0},\"num_sources_used\":0,\"cost_in_usd_ticks\":1068500},\"system_fingerprint\":\"fp_8d6266e762\",\"service_tier\":\"default\"}\n\ndata: [DONE]\n\n"
}
}
]
}

View file

@ -0,0 +1,75 @@
import { model as anthropicChat } from "@opencode/ai/providers/anthropic/chat"
import { model as googleChat } from "@opencode/ai/providers/google/chat"
import { model as xaiChat } from "@opencode/ai/providers/xai/chat"
import { describe, expect } from "bun:test"
import { Effect } from "effect"
import { ai, LLMEvent } from "../../src/effect.js"
import { LLMClient } from "../../src/route.js"
import { expectWeatherToolLoop, goldenWeatherToolLoopRequest, runWeatherToolLoop } from "../recorded-scenarios.js"
import { recordedTests } from "../recorded-test.js"
for (const item of [
{
name: "Anthropic",
provider: "anthropic",
env: "ANTHROPIC_API_KEY",
model: anthropicChat("claude-haiku-4-5", { apiKey: process.env.ANTHROPIC_API_KEY ?? "fixture" }),
maxTokens: 256,
},
{
name: "Google",
provider: "google",
env: "GEMINI_API_KEY",
model: googleChat("gemini-3.5-flash-lite", { apiKey: process.env.GEMINI_API_KEY ?? "fixture" }),
maxTokens: 1024,
},
{
name: "xAI",
provider: "xai",
env: "XAI_API_KEY",
model: xaiChat("grok-4.20-0309-non-reasoning", { apiKey: process.env.XAI_API_KEY ?? "fixture" }),
maxTokens: 256,
},
] as const) {
const recorded = recordedTests({
prefix: `${item.provider}-chat`,
provider: item.provider,
protocol: "openai-chat",
requires: [item.env],
})
describe(`${item.name} Chat recorded`, () => {
recorded.effect.with("streams text", { tags: ["text", "usage"], metadata: { model: item.model.id } }, () =>
Effect.gen(function* () {
const response = yield* LLMClient.generate(
ai.request({
model: item.model,
prompt: "Reply with exactly one word: hello",
generation: { maxTokens: item.maxTokens },
}),
)
expect(response.text.toLowerCase()).toContain("hello")
expect(response.events.some(LLMEvent.is.textDelta)).toBe(true)
expect(response.usage?.outputTokens).toBeGreaterThan(0)
}),
)
recorded.effect.with(
"continues a tool call",
{ tags: ["tool", "tool-loop"], metadata: { model: item.model.id } },
() =>
Effect.gen(function* () {
const events = yield* runWeatherToolLoop(
goldenWeatherToolLoopRequest({
id: `${item.provider}-chat-tool-loop`,
model: item.model,
maxTokens: item.maxTokens,
temperature: false,
}),
)
expectWeatherToolLoop(events)
}),
60_000,
)
})
}

View file

@ -71,6 +71,8 @@ describe("native OpenAI-compatible providers", () => {
[CloudflareWorkersAI.configure({ accountId: "account" }).model("model"), "cloudflare-workers-ai"],
[OpenRouter.configure({ apiKey: "test" }).model("model"), "openrouter"],
[XAI.configure({ apiKey: "test" }).chat("model"), "xai"],
[Anthropic.configure({ apiKey: "test" }).chat("model"), "anthropic"],
[Google.configure({ apiKey: "test" }).chat("model"), "google"],
[XAI.configure({ apiKey: "test" }).responses("model"), "xai"],
] as const
@ -269,6 +271,24 @@ describe("native OpenAI-compatible providers", () => {
token: "groq-secret",
url: "https://api.groq.com/openai/v1/chat/completions",
},
{
model: Anthropic.configure().chat("claude-haiku-4-5"),
env: { ANTHROPIC_API_KEY: "anthropic-secret" },
token: "anthropic-secret",
url: "https://api.anthropic.com/v1/chat/completions",
},
{
model: Google.configure().chat("gemini-3.5-flash"),
env: { GOOGLE_GENERATIVE_AI_API_KEY: "google-secret" },
token: "google-secret",
url: "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
},
{
model: Google.configure({ baseURL: "https://proxy.test/v1beta" }).chat("gemini-3.5-flash"),
env: { GOOGLE_GENERATIVE_AI_API_KEY: "google-secret" },
token: "google-secret",
url: "https://proxy.test/v1beta/openai/chat/completions",
},
]
yield* Effect.forEach(scenarios, (scenario) =>