1package provider
2
3// Extra third-party providers.
4//
5// Most are OpenAI Chat Completions–compatible, so they reuse `openaiClient`
6// with a different name + base URL. A handful speak the Anthropic Messages
7// API and reuse `anthropicClient` via NewAnthropicCompat below.
8//
9// Providers with a non-trivial protocol (Bedrock Converse, Vertex SSE, Azure
10// Responses, Mistral Conversations) are stubbed so the host wiring compiles.
11// Filling those in is its own work — Bedrock needs SigV4 + Converse stream
12// parsing, Vertex needs ADC, Azure needs the Responses API shape, Mistral
13// needs its bespoke Conversations API.
14
15import (
16 "context"
17 "fmt"
18 "net/http"
19 "os"
20 "strings"
21)
22
23// ----------------------------------------------------------------------
24// OpenAI Chat Completions–compatible providers. All of these just route
25// Chat Completions to a different base URL with a different name. The
26// default Authorization: Bearer header from openaiClient is correct for
27// every one of them.
28// ----------------------------------------------------------------------
29
30// NewOpenAICompat is the shared constructor for OpenAI-completions clones.
31// Exported so build.go can instantiate clients for user-defined providers.
32func NewOpenAICompat(name, apiKey, baseURL, fallbackBaseURL string) Client {
33 if baseURL == "" {
34 baseURL = fallbackBaseURL
35 }
36 return &openaiClient{
37 apiKey: apiKey,
38 baseURL: strings.TrimRight(baseURL, "/"),
39 name: name,
40 http: &http.Client{Timeout: 0},
41 }
42}
43
44// NewMoonshot is the global Moonshot AI endpoint (Kimi-K2 family by id).
45// Provider id is `moonshotai`.
46func NewMoonshot(apiKey, baseURL string) Client {
47 return NewOpenAICompat("moonshotai", apiKey, baseURL, "https://api.moonshot.ai/v1")
48}
49
50// NewMoonshotCN is the China-region Moonshot endpoint. Same model ids as
51// the global flavor, different base URL.
52func NewMoonshotCN(apiKey, baseURL string) Client {
53 return NewOpenAICompat("moonshotai-cn", apiKey, baseURL, "https://api.moonshot.cn/v1")
54}
55
56// NewCerebras: ultra-fast inference (Llama/Qwen/GPT-OSS/GLM).
57func NewCerebras(apiKey, baseURL string) Client {
58 return NewOpenAICompat("cerebras", apiKey, baseURL, "https://api.cerebras.ai/v1")
59}
60
61// NewGroq: LPU inference (Llama/Kimi/Qwen/GPT-OSS).
62func NewGroq(apiKey, baseURL string) Client {
63 return NewOpenAICompat("groq", apiKey, baseURL, "https://api.groq.com/openai/v1")
64}
65
66// NewXAI: xAI Grok.
67func NewXAI(apiKey, baseURL string) Client {
68 return NewOpenAICompat("xai", apiKey, baseURL, "https://api.x.ai/v1")
69}
70
71// NewTogether: Together.ai aggregator.
72func NewTogether(apiKey, baseURL string) Client {
73 return NewOpenAICompat("together", apiKey, baseURL, "https://api.together.ai/v1")
74}
75
76// NewHuggingFace: HF inference router.
77func NewHuggingFace(apiKey, baseURL string) Client {
78 return NewOpenAICompat("huggingface", apiKey, baseURL, "https://router.huggingface.co/v1")
79}
80
81// NewZAI: Z.AI GLM family.
82func NewZAI(apiKey, baseURL string) Client {
83 return NewOpenAICompat("zai", apiKey, baseURL, "https://api.z.ai/api/coding/paas/v4")
84}
85
86// NewXiaomi: Xiaomi MiMo family (default endpoint).
87func NewXiaomi(apiKey, baseURL string) Client {
88 return NewOpenAICompat("xiaomi", apiKey, baseURL, "https://api.xiaomimimo.com/v1")
89}
90
91// NewXiaomiTokenPlan creates a regional Xiaomi token-plan client.
92// region must be "ams", "cn", or "sgp", matching the three
93// `xiaomi-token-plan-*` provider ids.
94func NewXiaomiTokenPlan(region, apiKey, baseURL string) Client {
95 var fallback string
96 var name string
97 switch region {
98 case "ams":
99 fallback = "https://token-plan-ams.xiaomimimo.com/v1"
100 name = "xiaomi-token-plan-ams"
101 case "cn":
102 fallback = "https://token-plan-cn.xiaomimimo.com/v1"
103 name = "xiaomi-token-plan-cn"
104 case "sgp":
105 fallback = "https://token-plan-sgp.xiaomimimo.com/v1"
106 name = "xiaomi-token-plan-sgp"
107 default:
108 panic(fmt.Sprintf("xiaomi token-plan: unknown region %q", region))
109 }
110 return NewOpenAICompat(name, apiKey, baseURL, fallback)
111}
112
113// NewOpenRouter: OpenRouter aggregator. Unlocks dozens of upstream
114// models with one key.
115func NewOpenRouter(apiKey, baseURL string) Client {
116 return NewOpenAICompat("openrouter", apiKey, baseURL, openrouterDefaultBaseURL)
117}
118
119// NewGondola: Gondola, a USDC-paid marketplace gateway for Venice AI
120// inference. OpenAI Chat Completions-compatible.
121func NewGondola(apiKey, baseURL string) Client {
122 return NewOpenAICompat("gondola", apiKey, baseURL, gondolaDefaultBaseURL)
123}
124
125// NewOpenCode is the opencode.ai Zen endpoint. Mixed APIs upstream; this
126// constructor wires the openai-completions flavor only. Models that need
127// the anthropic-messages flavor under the same provider should be built
128// with NewAnthropicCompat against the same base URL.
129func NewOpenCode(apiKey, baseURL string) Client {
130 return NewOpenAICompat("opencode", apiKey, baseURL, "https://opencode.ai/zen/v1")
131}
132
133// NewOpenCodeGo routes each model through the wire API exposed by OpenCode Go.
134func NewOpenCodeGo(apiKey, baseURL string) Client {
135 const defaultBaseURL = "https://opencode.ai/zen/go/v1"
136 return NewModelRouter("opencode-go",
137 NewOpenAICompat("opencode-go", apiKey, baseURL, defaultBaseURL),
138 map[string]Client{
139 APIResponses: NewOpenAIResponsesNamed(apiKey, firstNonEmptyString(baseURL, defaultBaseURL), "opencode-go"),
140 })
141}
142
143// NewMinimaxOpenAI is the OpenAI-completions flavor of MiniMax, in case
144// downstream models switch from anthropic-messages. The main MiniMax route
145// uses anthropic-messages; see NewMinimaxAnthropic below.
146func NewMinimaxOpenAI(apiKey, baseURL string) Client {
147 return NewOpenAICompat("minimax", apiKey, baseURL, "https://api.minimax.io/v1")
148}
149
150// NewMinimaxCNOpenAI is the CN-region MiniMax (openai-completions).
151func NewMinimaxCNOpenAI(apiKey, baseURL string) Client {
152 return NewOpenAICompat("minimax-cn", apiKey, baseURL, "https://api.minimaxi.com/v1")
153}
154
155// NewFireworksOpenAI is the OpenAI-completions flavor of Fireworks.
156// The main route uses the anthropic-messages variant on
157// api.fireworks.ai/inference; see NewFireworksAnthropic.
158func NewFireworksOpenAI(apiKey, baseURL string) Client {
159 return NewOpenAICompat("fireworks", apiKey, baseURL, "https://api.fireworks.ai/inference/v1")
160}
161
162// NewVercelGatewayOpenAI is Vercel AI Gateway's OpenAI-compat shim. The
163// main route uses anthropic-messages; see NewVercelGatewayAnthropic.
164func NewVercelGatewayOpenAI(apiKey, baseURL string) Client {
165 return NewOpenAICompat("vercel-ai-gateway", apiKey, baseURL, "https://ai-gateway.vercel.sh/v1")
166}
167
168// ----------------------------------------------------------------------
169// Anthropic Messages–compatible providers. These speak Anthropic's wire
170// format but live behind a third party's base URL. They reuse
171// anthropicClient with a custom name.
172// ----------------------------------------------------------------------
173
174// NewAnthropicCompat returns an anthropicClient pinned to a non-default
175// base URL and identifying as `name` for cost / logging purposes. Auth is
176// API key (x-api-key header). For OAuth-fronted compatibles (rare) use
177// NewAnthropicOAuth and rename via NameClient.
178func NewAnthropicCompat(name, apiKey, baseURL string) Client {
179 if baseURL == "" {
180 baseURL = anthropicDefaultBaseURL
181 }
182 return &anthropicClient{
183 apiKey: apiKey,
184 baseURL: strings.TrimRight(baseURL, "/"),
185 name: name,
186 http: &http.Client{Timeout: 0},
187 }
188}
189
190// NewKimiCoding is the Kimi Code client: Kimi behind the Anthropic
191// Messages API at https://api.kimi.com/coding. Replaces the older
192// OpenAI-completions-on-/coding/v1 wiring.
193func NewKimiCoding(apiKey, baseURL string) Client {
194 return NewKimiCodingWithHeaders(apiKey, baseURL, nil)
195}
196
197// NewKimiCodingWithHeaders is the headered variant used by OAuth.
198func NewKimiCodingWithHeaders(apiKey, baseURL string, headers map[string]string) Client {
199 if baseURL == "" {
200 baseURL = "https://api.kimi.com/coding"
201 }
202 return &anthropicClient{
203 apiKey: apiKey,
204 baseURL: strings.TrimRight(baseURL, "/"),
205 name: "kimi",
206 headers: headers,
207 http: &http.Client{Timeout: 0},
208 }
209}
210
211// NewMinimaxAnthropic is the anthropic-messages flavor on
212// api.minimax.io/anthropic, catalogued under provider=minimax.
213func NewMinimaxAnthropic(apiKey, baseURL string) Client {
214 return NewAnthropicCompat("minimax", apiKey, firstNonEmptyString(baseURL, "https://api.minimax.io/anthropic"))
215}
216
217// NewMinimaxCNAnthropic is the CN-region MiniMax (anthropic-messages).
218func NewMinimaxCNAnthropic(apiKey, baseURL string) Client {
219 return NewAnthropicCompat("minimax-cn", apiKey, firstNonEmptyString(baseURL, "https://api.minimaxi.com/anthropic"))
220}
221
222// NewFireworksAnthropic is the main Fireworks route. The
223// anthropic-messages-compatible endpoint at api.fireworks.ai/inference
224// expects Anthropic-style request bodies; use this rather than the
225// OpenAI flavor.
226func NewFireworksAnthropic(apiKey, baseURL string) Client {
227 return NewAnthropicCompat("fireworks", apiKey, firstNonEmptyString(baseURL, "https://api.fireworks.ai/inference"))
228}
229
230// NewVercelGatewayAnthropic — Vercel AI Gateway anthropic-messages route.
231func NewVercelGatewayAnthropic(apiKey, baseURL string) Client {
232 return NewAnthropicCompat("vercel-ai-gateway", apiKey, firstNonEmptyString(baseURL, "https://ai-gateway.vercel.sh"))
233}
234
235// ----------------------------------------------------------------------
236// Stubbed providers — bigger protocol surface, follow-up work.
237// ----------------------------------------------------------------------
238
239type unimplementedClient struct {
240 name string
241 hint string
242}
243
244func (c *unimplementedClient) Name() string { return c.name }
245
246func (c *unimplementedClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
247 return nil, fmt.Errorf("provider %q not yet implemented: %s", c.name, c.hint)
248}
249
250// NewBedrock returns an AWS Bedrock client. See amazon_bedrock.go for the
251// hand-rolled Converse-Stream wire-format parser. Auth is via
252// AWS_BEARER_TOKEN_BEDROCK (the modern Bedrock API key flow); SigV4
253// signing for IAM access-key + secret credentials is not yet wired.
254func NewBedrock(apiKey, baseURL string) Client {
255 return NewBedrockClient(apiKey, baseURL)
256}
257
258// NewGoogleVertex returns a Vertex AI client. See google_vertex.go for
259// the full auth + URL-rewrite implementation. Requires GOOGLE_CLOUD_PROJECT,
260// GOOGLE_CLOUD_LOCATION, and either GOOGLE_CLOUD_API_KEY or a service-
261// account JSON file pointed to by GOOGLE_APPLICATION_CREDENTIALS (or the
262// default ADC location ~/.config/gcloud/application_default_credentials.json).
263func NewGoogleVertex(apiKey, baseURL string) Client {
264 return NewVertex(apiKey, baseURL)
265}
266
267// NewMistral returns a Mistral client using their OpenAI-compatible Chat
268// Completions endpoint at https://api.mistral.ai/v1. Mistral also offers a
269// bespoke "Conversations" API, but the OpenAI-compat endpoint supports
270// the same models with tool calling and streaming, so we use that for
271// simplicity (no extra wire format to maintain).
272func NewMistral(apiKey, baseURL string) Client {
273 return NewOpenAICompat("mistral", apiKey, baseURL, "https://api.mistral.ai/v1")
274}
275
276// Cloudflare endpoints carry `{CLOUDFLARE_ACCOUNT_ID}` and (for the AI
277// Gateway) `{CLOUDFLARE_GATEWAY_ID}` placeholders that we substitute
278// from env vars at client-construction time. Workers AI uses standard
279// `Authorization: Bearer <key>`; AI Gateway uses `cf-aig-authorization`
280// (the upstream Authorization header is passed through to whichever
281// downstream provider the gateway forwards to).
282
283func resolveCloudflareURL(template string) (string, error) {
284 out := template
285 for _, key := range []string{"CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_GATEWAY_ID"} {
286 placeholder := "{" + key + "}"
287 if !strings.Contains(out, placeholder) {
288 continue
289 }
290 v := os.Getenv(key)
291 if v == "" {
292 return "", fmt.Errorf("%s is required but not set in env", key)
293 }
294 out = strings.ReplaceAll(out, placeholder, v)
295 }
296 return out, nil
297}
298
299// NewCloudflareWorkersAI returns an OpenAI-compatible client pinned to
300// the Workers AI base URL with {CLOUDFLARE_ACCOUNT_ID} substituted.
301// Returns an erroring client (deferred error on first Stream call) if
302// the env var is missing, so the constructor signature stays the same.
303func NewCloudflareWorkersAI(apiKey, baseURL string) Client {
304 if baseURL == "" {
305 baseURL = "https://api.cloudflare.com/client/v4/accounts/{CLOUDFLARE_ACCOUNT_ID}/ai/v1"
306 }
307 resolved, err := resolveCloudflareURL(baseURL)
308 if err != nil {
309 return &unimplementedClient{name: "cloudflare-workers-ai", hint: err.Error()}
310 }
311 return NewOpenAICompat("cloudflare-workers-ai", apiKey, resolved, "")
312}
313
314// NewCloudflareAIGateway returns the AI Gateway client (OpenAI compat
315// route). Sends `cf-aig-authorization` instead of `Authorization` so
316// the gateway authenticates the caller (downstream-provider auth is
317// configured per-gateway in the Cloudflare dashboard).
318func NewCloudflareAIGateway(apiKey, baseURL string) Client {
319 if baseURL == "" {
320 baseURL = "https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/compat"
321 }
322 resolved, err := resolveCloudflareURL(baseURL)
323 if err != nil {
324 return &unimplementedClient{name: "cloudflare-ai-gateway", hint: err.Error()}
325 }
326 return &openaiClient{
327 apiKey: apiKey,
328 baseURL: strings.TrimRight(resolved, "/"),
329 name: "cloudflare-ai-gateway",
330 headers: map[string]string{"cf-aig-authorization": "Bearer " + apiKey},
331 http: &http.Client{Timeout: 0},
332 }
333}
334
335// NewGithubCopilot returns a GitHub Copilot client. The provided
336// credential must be a GitHub Personal Access Token (PAT) with Copilot
337// access enabled; zot trades it for a short-lived Copilot token on
338// every inference request (cached in memory until ~5min before expiry).
339//
340// Wire format: OpenAI Chat Completions. Copilot-specific headers
341// (X-Initiator, Openai-Intent, Editor-Version, Editor-Plugin-Version,
342// Copilot-Integration-Id, User-Agent) are added by the refresh
343// transport. The model id passes through unchanged.
344//
345// baseURL is ignored: the canonical host is read from `proxy-ep=...` in
346// the short-lived token's value.
347func NewGithubCopilot(apiKey, _ string) Client {
348 if apiKey == "" {
349 return &unimplementedClient{name: "github-copilot", hint: "set COPILOT_GITHUB_TOKEN"}
350 }
351 return NewGithubCopilotClient(apiKey)
352}
353
354// ----------------------------------------------------------------------
355// helpers
356// ----------------------------------------------------------------------
357
358func firstNonEmptyString(vals ...string) string {
359 for _, v := range vals {
360 if v != "" {
361 return v
362 }
363 }
364 return ""
365}