xonecas.io
64875
Mc

mini-coder / commit 57bd6e2

refactor(llm-api): simplify model provider resolution

xonecas2026-03-14 57bd6e2f121248c23d641e22701a1c8de0a1e5ae parent 1928410

1 file changed

src/llm-api/providers.ts+94−99
@@ -14,7 +14,9 @@ import { getZenBackend } from "./model-routing.ts";
1414 export { getContextWindow } from "./model-info.ts";
1515 export type { ThinkingEffort } from "./provider-options.ts";
1616
17-// ─── Zen endpoint constants ────────────────────────────────────────────────────
17+type ProviderName = "zen" | "anthropic" | "openai" | "google" | "ollama";
18+
19+const ZEN_BASE = "https://opencode.ai/zen/v1";
1820
1921 function getFetchWithLogging(): typeof fetch {
2022 const customFetch = async (
@@ -45,42 +47,32 @@ function getFetchWithLogging(): typeof fetch {
4547 return customFetch as unknown as typeof fetch;
4648 }
4749
48-const ZEN_BASE = "https://opencode.ai/zen/v1";
50+const fetchWithLogging = getFetchWithLogging();
4951
50-// Zen endpoint routing — matched in order, fallthrough to OpenAI-compatible
51-function zenEndpointFor(modelId: string) {
52- switch (getZenBackend(modelId)) {
53- case "anthropic":
54- return zenAnthropic()(modelId);
55- case "openai":
56- return zenOpenAI().responses(modelId);
57- case "google":
58- return zenGoogle()(modelId);
59- case "compat":
60- return zenCompat()(modelId);
61- }
52+function requireEnv(name: string): string {
53+ const value = process.env[name];
54+ if (!value) throw new Error(`${name} is not set`);
55+ return value;
6256 }
6357
64-// ─── Lazy provider factories (created on first use) ───────────────────────────
58+function requireAnyEnv(names: string[]): string {
59+ for (const name of names) {
60+ const value = process.env[name];
61+ if (value) return value;
62+ }
63+ throw new Error(`${names.join(" or ")} is not set`);
64+}
6565
6666 let _zenAnthropic: ReturnType<typeof createAnthropic> | null = null;
6767 let _zenOpenAI: ReturnType<typeof createOpenAI> | null = null;
6868 let _zenGoogle: ReturnType<typeof createGoogleGenerativeAI> | null = null;
69-
7069 let _zenCompat: ReturnType<typeof createOpenAICompatible> | null = null;
7170
72-function getZenApiKey(): string {
73- const key = process.env.OPENCODE_API_KEY;
74- if (!key) throw new Error("OPENCODE_API_KEY is not set");
75- return key;
76-}
77-
7871 function zenAnthropic() {
7972 if (!_zenAnthropic) {
80- // @ai-sdk/anthropic appends /messages automatically — baseURL is the v1 root
8173 _zenAnthropic = createAnthropic({
82- fetch: getFetchWithLogging(),
83- apiKey: getZenApiKey(),
74+ fetch: fetchWithLogging,
75+ apiKey: requireEnv("OPENCODE_API_KEY"),
8476 baseURL: ZEN_BASE,
8577 });
8678 }
@@ -89,10 +81,9 @@ function zenAnthropic() {
8981
9082 function zenOpenAI() {
9183 if (!_zenOpenAI) {
92- // @ai-sdk/openai appends /responses automatically — baseURL is the v1 root
9384 _zenOpenAI = createOpenAI({
94- fetch: getFetchWithLogging(),
95- apiKey: getZenApiKey(),
85+ fetch: fetchWithLogging,
86+ apiKey: requireEnv("OPENCODE_API_KEY"),
9687 baseURL: ZEN_BASE,
9788 });
9889 }
@@ -101,10 +92,9 @@ function zenOpenAI() {
10192
10293 function zenGoogle() {
10394 if (!_zenGoogle) {
104- // @ai-sdk/google constructs its own path; we pass the base up to /models
10595 _zenGoogle = createGoogleGenerativeAI({
106- fetch: getFetchWithLogging(),
107- apiKey: getZenApiKey(),
96+ fetch: fetchWithLogging,
97+ apiKey: requireEnv("OPENCODE_API_KEY"),
10898 baseURL: ZEN_BASE,
10999 });
110100 }
@@ -113,30 +103,26 @@ function zenGoogle() {
113103
114104 function zenCompat() {
115105 if (!_zenCompat) {
116- // @ai-sdk/openai-compatible appends /chat/completions — baseURL is the v1 root
117106 _zenCompat = createOpenAICompatible({
118- fetch: getFetchWithLogging(),
107+ fetch: fetchWithLogging,
119108 name: "zen-compat",
120- apiKey: getZenApiKey(),
109+ apiKey: requireEnv("OPENCODE_API_KEY"),
121110 baseURL: ZEN_BASE,
122111 });
123112 }
124113 return _zenCompat;
125114 }
126115
127-// ─── Direct provider factories ────────────────────────────────────────────────
128-
129116 let _directAnthropic: ReturnType<typeof createAnthropic> | null = null;
130117 let _directOpenAI: ReturnType<typeof createOpenAI> | null = null;
131118 let _directGoogle: ReturnType<typeof createGoogleGenerativeAI> | null = null;
119+let _ollama: ReturnType<typeof createOpenAICompatible> | null = null;
132120
133121 function directAnthropic() {
134122 if (!_directAnthropic) {
135- const key = process.env.ANTHROPIC_API_KEY;
136- if (!key) throw new Error("ANTHROPIC_API_KEY is not set");
137123 _directAnthropic = createAnthropic({
138- fetch: getFetchWithLogging(),
139- apiKey: key,
124+ fetch: fetchWithLogging,
125+ apiKey: requireEnv("ANTHROPIC_API_KEY"),
140126 });
141127 }
142128 return _directAnthropic;
@@ -144,88 +130,100 @@ function directAnthropic() {
144130
145131 function directOpenAI() {
146132 if (!_directOpenAI) {
147- const key = process.env.OPENAI_API_KEY;
148- if (!key) throw new Error("OPENAI_API_KEY is not set");
149- _directOpenAI = createOpenAI({ fetch: getFetchWithLogging(), apiKey: key });
133+ _directOpenAI = createOpenAI({
134+ fetch: fetchWithLogging,
135+ apiKey: requireEnv("OPENAI_API_KEY"),
136+ });
150137 }
151138 return _directOpenAI;
152139 }
153140
154141 function directGoogle() {
155142 if (!_directGoogle) {
156- const key = process.env.GOOGLE_API_KEY ?? process.env.GEMINI_API_KEY;
157- if (!key) throw new Error("GOOGLE_API_KEY or GEMINI_API_KEY is not set");
158143 _directGoogle = createGoogleGenerativeAI({
159- fetch: getFetchWithLogging(),
160- apiKey: key,
144+ fetch: fetchWithLogging,
145+ apiKey: requireAnyEnv(["GOOGLE_API_KEY", "GEMINI_API_KEY"]),
161146 });
162147 }
163148 return _directGoogle;
164149 }
165150
166-// ─── Public API ───────────────────────────────────────────────────────────────
167-
168-/**
169- * Resolve a model string to a LanguageModel.
170- *
171- * Format: "<provider>/<model-id>"
172- *
173- * Providers:
174- * zen/<model-id> – OpenCode Zen (requires OPENCODE_API_KEY)
175- * anthropic/<model> – Direct Anthropic (requires ANTHROPIC_API_KEY)
176- * openai/<model> – Direct OpenAI (requires OPENAI_API_KEY)
177- * google/<model> – Direct Google (requires GOOGLE_API_KEY or GEMINI_API_KEY)
178- * ollama/<model> – Local Ollama
179- */
180-export function resolveModel(modelString: string): LanguageModel {
181- const slashIdx = modelString.indexOf("/");
182- if (slashIdx === -1) {
183- throw new Error(
184- `Invalid model string "${modelString}". Expected format: "<provider>/<model-id>"`,
185- );
151+function ollamaProvider() {
152+ if (!_ollama) {
153+ const baseURL = process.env.OLLAMA_BASE_URL ?? "http://localhost:11434";
154+ _ollama = createOpenAICompatible({
155+ name: "ollama",
156+ baseURL: `${baseURL}/v1`,
157+ apiKey: "ollama",
158+ fetch: fetchWithLogging,
159+ });
186160 }
161+ return _ollama;
162+}
187163
188- const provider = modelString.slice(0, slashIdx);
189- const modelId = modelString.slice(slashIdx + 1);
164+function resolveZenModel(modelId: string): LanguageModel {
165+ switch (getZenBackend(modelId)) {
166+ case "anthropic":
167+ return zenAnthropic()(modelId);
168+ case "openai":
169+ return zenOpenAI().responses(modelId);
170+ case "google":
171+ return zenGoogle()(modelId);
172+ case "compat":
173+ return zenCompat()(modelId);
174+ }
175+}
190176
191- switch (provider) {
192- case "zen": {
193- return zenEndpointFor(modelId);
194- }
177+function resolveOpenAIModel(modelId: string): LanguageModel {
178+ return modelId.startsWith("gpt-")
179+ ? directOpenAI().responses(modelId)
180+ : directOpenAI()(modelId);
181+}
195182
183+function resolveProviderModel(
184+ provider: ProviderName,
185+ modelId: string,
186+): LanguageModel {
187+ switch (provider) {
188+ case "zen":
189+ return resolveZenModel(modelId);
196190 case "anthropic":
197191 return directAnthropic()(modelId);
198-
199192 case "openai":
200- return modelId.startsWith("gpt-")
201- ? directOpenAI().responses(modelId)
202- : directOpenAI()(modelId);
203-
193+ return resolveOpenAIModel(modelId);
204194 case "google":
205195 return directGoogle()(modelId);
196+ case "ollama":
197+ return ollamaProvider().chatModel(modelId);
198+ }
199+}
206200
207- case "ollama": {
208- const baseURL = process.env.OLLAMA_BASE_URL ?? "http://localhost:11434";
209- const ollamaProvider = createOpenAICompatible({
210- name: "ollama",
211- baseURL: `${baseURL}/v1`,
212- apiKey: "ollama",
213- fetch: getFetchWithLogging(),
214- });
215- return ollamaProvider.chatModel(modelId);
216- }
201+export function resolveModel(modelString: string): LanguageModel {
202+ const slashIdx = modelString.indexOf("/");
203+ if (slashIdx === -1) {
204+ throw new Error(
205+ `Invalid model string "${modelString}". Expected format: "<provider>/<model-id>"`,
206+ );
207+ }
208+
209+ const provider = modelString.slice(0, slashIdx);
210+ const modelId = modelString.slice(slashIdx + 1);
217211
218- default:
219- throw new Error(
220- `Unknown provider "${provider}". Supported: zen, anthropic, openai, google, ollama`,
221- );
212+ if (
213+ provider !== "zen" &&
214+ provider !== "anthropic" &&
215+ provider !== "openai" &&
216+ provider !== "google" &&
217+ provider !== "ollama"
218+ ) {
219+ throw new Error(
220+ `Unknown provider "${provider}". Supported: zen, anthropic, openai, google, ollama`,
221+ );
222222 }
223+
224+ return resolveProviderModel(provider, modelId);
223225 }
224226
225-/**
226- * Auto-discover a usable provider from the environment.
227- * Returns the first available (provider, defaultModel) pair.
228- */
229227 export function autoDiscoverModel(): string {
230228 if (process.env.OPENCODE_API_KEY) return "zen/claude-sonnet-4-6";
231229 if (process.env.ANTHROPIC_API_KEY)
@@ -233,12 +231,9 @@ export function autoDiscoverModel(): string {
233231 if (process.env.OPENAI_API_KEY) return "openai/gpt-4o";
234232 if (process.env.GOOGLE_API_KEY ?? process.env.GEMINI_API_KEY)
235233 return "google/gemini-2.0-flash";
236- // Always fall back to Ollama (may fail at request time if not running)
237234 return "ollama/llama3.2";
238235 }
239236
240-// ─── Cached model listing ─────────────────────────────────────────────────────
241-
242237 export async function fetchAvailableModels(): Promise<AvailableModelsSnapshot> {
243238 return fetchAvailableModelsSnapshot();
244239 }