opencode-plugin-litellm 0.6.0 โ†’ 0.7.1

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 CHANGED
@@ -74,6 +74,7 @@ opencode
74
74
  | ๐Ÿ“ก **Dynamic discovery** | Queries `/v1/models` so your OpenCode model picker always reflects your live `model_list`. |
75
75
  | ๐Ÿท๏ธ **Smart formatting** | Turns `anthropic/claude-3-5-sonnet` into `Claude 3 5 Sonnet` in the picker โ€” handles versions, sizes, quantizations, and brand-cased names like `gpt-4o`. |
76
76
  | ๐Ÿง  **Modality-aware** | Enriches `/v1/models` entries with `/v1/model/info` (`mode`, token limits, capability flags) and hides embedding / image / audio models from the picker. |
77
+ | ๐Ÿ’ต **Real pricing** | Maps `input_cost_per_token` / `output_cost_per_token` from `/v1/model/info` into OpenCode's `cost` field, so the picker and `/cost` show what the proxy actually bills instead of `$0.00`. Models LiteLLM has no price for are left unpriced, not falsely marked free. |
77
78
  | ๐Ÿงช **Reasoning-aware routing** | Auto-routes `gpt-5*` / `o1`/`o3`/`o4*` models through a sibling `litellm-responses` provider that uses `/v1/responses`, so tools + `reasoning_effort` actually work. Override per model via `responsesApiModels` / `chatApiModels`. |
78
79
  | ๐Ÿข **Provider extraction** | Pulls `litellm_provider` (or the `provider/model` prefix) into `organizationOwner` so models group correctly in the UI. |
79
80
  | ๐Ÿ” **Auth-aware** | Honours `LITELLM_API_KEY` / `LITELLM_MASTER_KEY` env vars or `provider.litellm.options.apiKey`. |
@@ -292,7 +293,7 @@ sequenceDiagram
292
293
  1. On OpenCode startup the `config` lifecycle hook fires.
293
294
  2. If `provider.litellm` exists, its `baseURL` is used. Otherwise common ports are probed.
294
295
  3. A health check (`GET /v1/models`) verifies the proxy is reachable and authorized.
295
- 4. Models from the response are enriched with `/v1/model/info` metadata (`mode`, token limits, capability flags โ€” `/v1/models` omits these for database-defined models) and converted into OpenCode model entries keyed by `id`, with formatted `name`, `organizationOwner`, and inferred `modalities`. Non-chat models (embedding / image / audio) are excluded from the picker.
296
+ 4. Models from the response are enriched with `/v1/model/info` metadata (`mode`, token limits, capability flags, and per-token pricing โ€” `/v1/models` omits these for database-defined models) and converted into OpenCode model entries keyed by `id`, with formatted `name`, `organizationOwner`, inferred `modalities`, and `cost` (USD/1M tokens, converted from LiteLLM's USD/token). Non-chat models (embedding / image / audio) are excluded from the picker.
296
297
  5. Each model is bucketed by transport โ€” reasoning-tier models (`gpt-5*`, `o1`/`o3`/`o4*`, or anything with `mode === 'responses'`) go into the `litellm-responses` provider; everything else goes into `litellm`. Per-model overrides via `responsesApiModels` / `chatApiModels` win.
297
298
  6. Discovered models are merged on top of any user-defined ones โ€” never overwriting them. A model is skipped if its key already exists under **either** provider.
298
299
  7. The whole flow is wrapped in a `Promise.race` against a 20 s timeout so a slow proxy never blocks boot.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "opencode-plugin-litellm",
4
- "version": "0.6.0",
4
+ "version": "0.7.1",
5
5
  "description": "OpenCode plugin for LiteLLM proxy support with auto-detection and dynamic model discovery",
6
6
  "type": "module",
7
7
  "main": "./src/index.ts",
@@ -25,6 +25,23 @@ const DISCOVERY_TIMEOUT_MS = 20000
25
25
  */
26
26
  const injectedModelIds = new Map<string, Set<string>>()
27
27
 
28
+ /**
29
+ * Helper to determine if a provider ID or its configured options indicate
30
+ * compatibility with LiteLLM.
31
+ */
32
+ function isLiteLLMProvider(
33
+ providerId: string,
34
+ options: Record<string, unknown>,
35
+ ): boolean {
36
+ if (providerId === CHAT_PROVIDER_ID) return true
37
+ if (providerId.startsWith('litellm-') || providerId.startsWith('litellm_')) return true
38
+ if (options.litellm === true) return true
39
+ if (options.litellmCompatible === true) return true
40
+ if (options['litellm-compatible'] === true) return true
41
+ if (options.litellm_compatible === true) return true
42
+ return false
43
+ }
44
+
28
45
  /**
29
46
  * Read `customHeaders` from a provider options block.
30
47
  */
@@ -60,9 +77,19 @@ function enrichModel(model: LiteLLMModel, info: LiteLLMModelInfo): LiteLLMModel
60
77
  supports_reasoning: model.supports_reasoning ?? info.supports_reasoning,
61
78
  supports_pdf_input: model.supports_pdf_input ?? info.supports_pdf_input,
62
79
  supports_audio_input: model.supports_audio_input ?? info.supports_audio_input,
80
+ input_cost_per_token: model.input_cost_per_token ?? info.input_cost_per_token,
81
+ output_cost_per_token: model.output_cost_per_token ?? info.output_cost_per_token,
63
82
  }
64
83
  }
65
84
 
85
+ /**
86
+ * OpenCode's `cost` config field is USD per **million** tokens (the
87
+ * models.dev convention); LiteLLM's `/v1/model/info` reports USD per
88
+ * single token. `1e6` bridges the two โ€” verified against a live
89
+ * `x-litellm-response-cost` header, not just the unit names.
90
+ */
91
+ const USD_PER_TOKEN_TO_PER_MILLION = 1_000_000
92
+
66
93
  /**
67
94
  * Convert a discovered LiteLLM model into an OpenCode config-level
68
95
  * model entry (the shape used in `provider.*.models` inside
@@ -93,6 +120,16 @@ function toConfigModel(model: LiteLLMModel): Record<string, unknown> | null {
93
120
  if (model.supports_vision) {
94
121
  entry.attachment = true
95
122
  }
123
+ // Only emit `cost` when LiteLLM actually reported a price. Omitting
124
+ // it (rather than defaulting to 0) lets OpenCode/models.dev fall back
125
+ // to their own default instead of us asserting "this model is free"
126
+ // for something LiteLLM simply has no price anchor for (e.g. rerank).
127
+ if (model.input_cost_per_token != null || model.output_cost_per_token != null) {
128
+ entry.cost = {
129
+ input: (model.input_cost_per_token ?? 0) * USD_PER_TOKEN_TO_PER_MILLION,
130
+ output: (model.output_cost_per_token ?? 0) * USD_PER_TOKEN_TO_PER_MILLION,
131
+ }
132
+ }
96
133
  const input: Array<'text' | 'image' | 'pdf' | 'audio'> = ['text']
97
134
  if (model.supports_vision) input.push('image')
98
135
  if (model.supports_pdf_input) input.push('pdf')
@@ -133,178 +170,199 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
133
170
  // Ensure the provider entry exists
134
171
  if (!config.provider) config.provider = {}
135
172
 
136
- const existing = config.provider[CHAT_PROVIDER_ID] as
137
- | Record<string, unknown>
138
- | undefined
139
- const options = (existing?.options ?? {}) as Record<string, unknown>
140
- const configuredBase =
141
- typeof options.baseURL === 'string' ? options.baseURL : undefined
142
- const configuredKey =
143
- typeof options.apiKey === 'string' && options.apiKey
144
- ? options.apiKey
145
- : undefined
146
- const envKey =
147
- process.env.LITELLM_API_KEY ?? process.env.LITELLM_MASTER_KEY
148
- const apiKey = configuredKey ?? envKey
149
- const customHeaders = readCustomHeaders(options)
150
-
151
- // Resolve base URL
152
- let baseURL: string | null = null
153
- if (configuredBase) {
154
- baseURL = normalizeBaseURL(configuredBase)
155
- } else {
156
- baseURL = await autoDetectLiteLLM(apiKey, customHeaders)
157
- }
173
+ // Find all matching LiteLLM providers
174
+ const providerIds = Object.keys(config.provider)
175
+ const liteLLMProviders: Array<{ id: string; provider: Record<string, unknown> }> = []
158
176
 
159
- if (!baseURL) {
160
- console.warn(
161
- '[opencode-litellm] No LiteLLM proxy found. Configure provider.litellm.options.baseURL or start LiteLLM on port 4000/8000/8080.',
162
- )
163
- return
164
- }
165
-
166
- // Create provider entry if it doesn't exist
167
- if (!existing) {
168
- config.provider[CHAT_PROVIDER_ID] = {
169
- npm: '@ai-sdk/openai-compatible',
170
- name: 'LiteLLM (proxy)',
171
- options: {
172
- baseURL: `${baseURL}/v1`,
173
- },
174
- models: {},
177
+ for (const id of providerIds) {
178
+ const provider = config.provider[id]
179
+ if (provider && typeof provider === 'object') {
180
+ const options = (provider.options ?? {}) as Record<string, unknown>
181
+ if (isLiteLLMProvider(id, options)) {
182
+ liteLLMProviders.push({ id, provider })
183
+ }
175
184
  }
176
185
  }
177
186
 
178
- const provider = config.provider[CHAT_PROVIDER_ID] as Record<
179
- string,
180
- unknown
181
- >
182
-
183
- // Ensure npm is set
184
- if (!provider.npm) {
185
- provider.npm = '@ai-sdk/openai-compatible'
186
- }
187
-
188
- // Ensure options.baseURL is set
189
- if (!provider.options) {
190
- provider.options = { baseURL: `${baseURL}/v1` }
191
- }
192
-
193
- // Ensure models map exists
194
- if (!provider.models) {
195
- provider.models = {}
187
+ // If no providers are matched (e.g., zero-config auto-detection),
188
+ // fall back to default 'litellm' provider to ensure backwards compatibility.
189
+ if (liteLLMProviders.length === 0) {
190
+ const id = CHAT_PROVIDER_ID
191
+ let provider = config.provider[id] as Record<string, unknown> | undefined
192
+ if (!provider) {
193
+ provider = {
194
+ npm: '@ai-sdk/openai-compatible',
195
+ name: 'LiteLLM (proxy)',
196
+ options: {},
197
+ models: {},
198
+ }
199
+ }
200
+ liteLLMProviders.push({ id, provider })
196
201
  }
197
202
 
198
- const models = provider.models as Record<string, unknown>
203
+ // Process each matched provider
204
+ for (const { id: providerId, provider } of liteLLMProviders) {
205
+ const options = (provider.options ?? {}) as Record<string, unknown>
206
+ const configuredBase =
207
+ typeof options.baseURL === 'string' ? options.baseURL : undefined
208
+ const configuredKey =
209
+ typeof options.apiKey === 'string' && options.apiKey
210
+ ? options.apiKey
211
+ : undefined
212
+ const envKey =
213
+ process.env.LITELLM_API_KEY ?? process.env.LITELLM_MASTER_KEY
214
+ const apiKey = configuredKey ?? envKey
215
+ const customHeaders = readCustomHeaders(options)
199
216
 
200
- // Discover models with timeout
201
- const work = async () => {
202
- const alreadyInjected = injectedModelIds.get(baseURL!)
203
- if (
204
- alreadyInjected &&
205
- [...alreadyInjected].every((id) => models[id])
206
- ) {
207
- return
217
+ // Resolve base URL
218
+ let baseURL: string | null = null
219
+ if (configuredBase) {
220
+ baseURL = normalizeBaseURL(configuredBase)
221
+ } else {
222
+ baseURL = await autoDetectLiteLLM(apiKey, customHeaders)
208
223
  }
209
224
 
210
- if (!(await checkLiteLLMHealth(baseURL!, apiKey, customHeaders))) {
225
+ if (!baseURL) {
211
226
  console.warn(
212
- `[opencode-litellm] LiteLLM appears offline or unauthorized at ${baseURL}`,
227
+ `[opencode-litellm] No LiteLLM proxy found for provider "${providerId}". Configure options.baseURL or start LiteLLM on port 4000/8000/8080.`,
213
228
  )
214
- return
229
+ continue
215
230
  }
216
231
 
217
- // `/v1/models` omits `mode` and capability metadata for
218
- // database-defined models, so fetch `/v1/model/info` alongside
219
- // it. The info call is best-effort: without it, classification
220
- // falls back to id heuristics.
221
- const [modelsResult, infoResult] = await Promise.allSettled([
222
- discoverLiteLLMModels(baseURL!, apiKey, customHeaders),
223
- discoverLiteLLMModelInfo(baseURL!, apiKey, customHeaders),
224
- ])
232
+ // Initialize/Update the provider entry in config
233
+ if (!config.provider[providerId]) {
234
+ config.provider[providerId] = provider
235
+ }
236
+ const actualProvider = config.provider[providerId] as Record<string, unknown>
225
237
 
226
- if (modelsResult.status === 'rejected') {
227
- const error = modelsResult.reason
228
- console.warn(
229
- '[opencode-litellm] Model discovery failed:',
230
- error instanceof Error ? error.message : String(error),
231
- )
232
- return
238
+ if (!actualProvider.npm) {
239
+ actualProvider.npm = '@ai-sdk/openai-compatible'
233
240
  }
234
241
 
235
- const discovered = modelsResult.value
236
- let infoByName: Map<string, LiteLLMModelInfo> | null = null
237
- if (infoResult.status === 'fulfilled') {
238
- infoByName = infoResult.value
242
+ if (!actualProvider.options) {
243
+ actualProvider.options = { baseURL: `${baseURL}/v1` }
239
244
  } else {
240
- const reason = infoResult.reason
241
- console.warn(
242
- '[opencode-litellm] /v1/model/info unavailable; non-chat model filtering will use id heuristics only:',
243
- reason instanceof Error ? reason.message : String(reason),
244
- )
245
+ const actualOptions = actualProvider.options as Record<string, unknown>
246
+ if (!actualOptions.baseURL) {
247
+ actualOptions.baseURL = `${baseURL}/v1`
248
+ }
245
249
  }
246
250
 
247
- if (discovered.length === 0) {
248
- console.warn(
249
- '[opencode-litellm] LiteLLM responded but exposed zero models.',
250
- )
251
- return
251
+ if (!actualProvider.models) {
252
+ actualProvider.models = {}
252
253
  }
253
254
 
254
- let added = 0
255
- let skipped = 0
256
- let wildcards = 0
257
- const unmatched: string[] = []
258
- for (const model of discovered) {
259
- // Wildcard entries (`deepseek/*`) are access rules, not
260
- // callable models โ€” invoking one sends a literal `*` upstream.
261
- if (model.id.includes('*')) {
262
- wildcards++
263
- continue
255
+ const models = actualProvider.models as Record<string, unknown>
256
+
257
+ // Discover models with timeout
258
+ const work = async () => {
259
+ const alreadyInjected = injectedModelIds.get(baseURL!)
260
+ if (
261
+ alreadyInjected &&
262
+ [...alreadyInjected].every((id) => models[id])
263
+ ) {
264
+ return
264
265
  }
265
- // Don't overwrite user-curated entries
266
- if (models[model.id]) continue
267
- const info = infoByName?.get(model.id)
268
- if (infoByName && !info) unmatched.push(model.id)
269
- const entry = toConfigModel(info ? enrichModel(model, info) : model)
270
- if (!entry) {
271
- skipped++
272
- continue
266
+
267
+ if (!(await checkLiteLLMHealth(baseURL!, apiKey, customHeaders))) {
268
+ console.warn(
269
+ `[opencode-litellm] LiteLLM appears offline or unauthorized for provider "${providerId}" at ${baseURL}`,
270
+ )
271
+ return
273
272
  }
274
- models[model.id] = entry
275
- added++
276
- }
277
273
 
278
- if (unmatched.length > 0) {
279
- console.warn(
280
- `[opencode-litellm] /v1/model/info has no entry for ${unmatched.length} model(s); ` +
281
- `classification uses id heuristics for: ${unmatched.slice(0, 5).join(', ')}` +
282
- (unmatched.length > 5 ? `, +${unmatched.length - 5} more` : ''),
283
- )
284
- }
274
+ // `/v1/models` omits `mode` and capability metadata for
275
+ // database-defined models, so fetch `/v1/model/info` alongside
276
+ // it. The info call is best-effort: without it, classification
277
+ // falls back to id heuristics.
278
+ const [modelsResult, infoResult] = await Promise.allSettled([
279
+ discoverLiteLLMModels(baseURL!, apiKey, customHeaders),
280
+ discoverLiteLLMModelInfo(baseURL!, apiKey, customHeaders),
281
+ ])
285
282
 
286
- // Remove the seed placeholder if real models were discovered
287
- if (models['_'] && Object.keys(models).length > 1) {
288
- delete models['_']
289
- }
283
+ if (modelsResult.status === 'rejected') {
284
+ const error = modelsResult.reason
285
+ console.warn(
286
+ `[opencode-litellm] Model discovery failed for provider "${providerId}":`,
287
+ error instanceof Error ? error.message : String(error),
288
+ )
289
+ return
290
+ }
290
291
 
291
- injectedModelIds.set(baseURL!, new Set(Object.keys(models)))
292
+ const discovered = modelsResult.value
293
+ let infoByName: Map<string, LiteLLMModelInfo> | null = null
294
+ if (infoResult.status === 'fulfilled') {
295
+ infoByName = infoResult.value
296
+ } else {
297
+ const reason = infoResult.reason
298
+ console.warn(
299
+ `[opencode-litellm] /v1/model/info unavailable for provider "${providerId}"; non-chat model filtering will use id heuristics only:`,
300
+ reason instanceof Error ? reason.message : String(reason),
301
+ )
302
+ }
292
303
 
293
- console.log(
294
- `[opencode-litellm] Discovered ${discovered.length} models from ${baseURL} ` +
295
- `(${added} added` +
296
- (skipped > 0 ? `, ${skipped} non-chat hidden` : '') +
297
- (wildcards > 0 ? `, ${wildcards} wildcard ignored` : '') +
298
- ')',
299
- )
300
- }
304
+ if (discovered.length === 0) {
305
+ console.warn(
306
+ `[opencode-litellm] LiteLLM responded for provider "${providerId}" but exposed zero models.`,
307
+ )
308
+ return
309
+ }
310
+
311
+ let added = 0
312
+ let skipped = 0
313
+ let wildcards = 0
314
+ const unmatched: string[] = []
315
+ for (const model of discovered) {
316
+ // Wildcard entries (`deepseek/*`) are access rules, not
317
+ // callable models โ€” invoking one sends a literal `*` upstream.
318
+ if (model.id.includes('*')) {
319
+ wildcards++
320
+ continue
321
+ }
322
+ // Don't overwrite user-curated entries
323
+ if (models[model.id]) continue
324
+ const info = infoByName?.get(model.id)
325
+ if (infoByName && !info) unmatched.push(model.id)
326
+ const entry = toConfigModel(info ? enrichModel(model, info) : model)
327
+ if (!entry) {
328
+ skipped++
329
+ continue
330
+ }
331
+ models[model.id] = entry
332
+ added++
333
+ }
334
+
335
+ if (unmatched.length > 0) {
336
+ console.warn(
337
+ `[opencode-litellm] /v1/model/info has no entry for ${unmatched.length} model(s) on provider "${providerId}"; ` +
338
+ `classification uses id heuristics for: ${unmatched.slice(0, 5).join(', ')}` +
339
+ (unmatched.length > 5 ? `, +${unmatched.length - 5} more` : ''),
340
+ )
341
+ }
342
+
343
+ // Remove the seed placeholder if real models were discovered
344
+ if (models['_'] && Object.keys(models).length > 1) {
345
+ delete models['_']
346
+ }
301
347
 
302
- await Promise.race([
303
- work(),
304
- new Promise<void>((resolve) =>
305
- setTimeout(resolve, DISCOVERY_TIMEOUT_MS),
306
- ),
307
- ])
348
+ injectedModelIds.set(baseURL!, new Set(Object.keys(models)))
349
+
350
+ console.log(
351
+ `[opencode-litellm] Discovered ${discovered.length} models for provider "${providerId}" from ${baseURL} ` +
352
+ `(${added} added` +
353
+ (skipped > 0 ? `, ${skipped} non-chat hidden` : '') +
354
+ (wildcards > 0 ? `, ${wildcards} wildcard ignored` : '') +
355
+ ')',
356
+ )
357
+ }
358
+
359
+ await Promise.race([
360
+ work(),
361
+ new Promise<void>((resolve) =>
362
+ setTimeout(resolve, DISCOVERY_TIMEOUT_MS),
363
+ ),
364
+ ])
365
+ }
308
366
  },
309
367
  }
310
368
  }
@@ -32,6 +32,14 @@ export interface LiteLLMModel {
32
32
  supports_reasoning?: boolean
33
33
  supports_pdf_input?: boolean
34
34
  supports_audio_input?: boolean
35
+ /**
36
+ * USD price per input/output token, reliably available via
37
+ * `/v1/model/info` (`/v1/models` omits pricing). Absent for models
38
+ * LiteLLM has no price anchor for (e.g. rerank) โ€” treat as "unknown",
39
+ * not "free".
40
+ */
41
+ input_cost_per_token?: number
42
+ output_cost_per_token?: number
35
43
  }
36
44
 
37
45
  export interface LiteLLMModelsResponse {
@@ -58,6 +66,8 @@ export interface LiteLLMModelInfo {
58
66
  supports_reasoning?: boolean
59
67
  supports_pdf_input?: boolean
60
68
  supports_audio_input?: boolean
69
+ input_cost_per_token?: number
70
+ output_cost_per_token?: number
61
71
  }
62
72
 
63
73
  /** A single entry returned by LiteLLM's `/v1/model/info` endpoint. */