opencode-plugin-litellm 1.1.0 → 1.3.0
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 +64 -3
- package/package.json +1 -1
- package/src/plugin/index.ts +100 -34
- package/src/utils/index.ts +1 -0
- package/src/utils/litellm-api.ts +2 -8
- package/src/utils/model-cache.ts +57 -0
- package/src/utils/model-capabilities.ts +50 -0
package/README.md
CHANGED
|
@@ -71,13 +71,14 @@ opencode
|
|
|
71
71
|
| 🔍 **Auto-detection** | Probes `localhost:4000`, `:8000`, `:8080` and adopts the first responsive proxy. |
|
|
72
72
|
| 📡 **Dynamic discovery** | Queries `/v1/models` so your OpenCode model picker always reflects your live `model_list`. |
|
|
73
73
|
| ⚡ **Instant startup (SWR)** | Discovered models are cached on disk and loaded synchronously — startup never blocks on the network. A background refresh on new sessions keeps the cache fresh; entries expire after 7 days. |
|
|
74
|
-
| 🏷️ **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`. |
|
|
74
|
+
| 🏷️ **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`. Set `formatModelNames: false` to keep the raw LiteLLM ids instead. |
|
|
75
75
|
| 🧠 **Modality-aware** | Enriches `/v1/models` entries with `/v1/model/info` (`mode`, token limits, capability flags) and hides embedding / image / audio models from the picker. |
|
|
76
76
|
| 💵 **Real pricing** | Maps `input_cost_per_token` / `output_cost_per_token` (and cache read/write costs) 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
77
|
| 🧩 **Reasoning-effort variants** | When LiteLLM reports per-model effort support (`supports_low_reasoning_effort`, …), the plugin surfaces each level as a picker variant automatically. |
|
|
78
78
|
| 🔐 **Auth-aware** | Honours `LITELLM_API_KEY` / `LITELLM_MASTER_KEY` env vars, `provider.litellm.options.apiKey`, or the key you stored via OpenCode's `/connect`. |
|
|
79
79
|
| 🌐 **Gateway-friendly** | Supports `customHeaders` for proxies behind Cloudflare Access or other API gateways requiring extra HTTP headers. |
|
|
80
80
|
| 🧩 **Splittable catalog** | `includeModels` / `excludeModels` (glob patterns) let one LiteLLM proxy be divided into several OpenCode providers — e.g. by naming prefix — without hand-maintaining a model list. |
|
|
81
|
+
| 🎚️ **Capability overrides** | `modelCapabilities` forces or retracts per-model capability flags (`supports_vision`, `supports_function_calling`, …) when `/v1/model/info` is unavailable or disagrees with your deployment. |
|
|
81
82
|
| ⏱️ **Non-blocking startup** | Health checks fail fast (3 s); discovery fetches are capped at **15 s** (configurable via `LITELLM_REQUEST_TIMEOUT_MS`) for slow remote proxies. Repeat config-hook invocations are a no-op. |
|
|
82
83
|
| 📝 **TUI-safe logging** | All plugin logs go through OpenCode's log API (into OpenCode's own log files), never to stdout — the TUI stays intact. |
|
|
83
84
|
| 🤝 **Non-destructive merge** | Only adds models you don't already have configured. Hand-curated entries are preserved verbatim. |
|
|
@@ -280,6 +281,53 @@ If your LiteLLM catalog mixes naming conventions from different teams or environ
|
|
|
280
281
|
- Patterns support only `*` (any run of characters); everything else is matched literally, so dots in ids like `gpt-4.1` need no escaping.
|
|
281
282
|
- Filtering happens before the on-disk cache is written, so each provider's cached view respects its own filters.
|
|
282
283
|
|
|
284
|
+
### Correcting capability flags (`modelCapabilities`)
|
|
285
|
+
|
|
286
|
+
Model classification (tool-call badge, attachments, reasoning, input modalities) leans on the capability flags LiteLLM reports via `/v1/model/info`. If your proxy doesn't expose that endpoint, or reports a flag that doesn't match your deployment, override flags per model id:
|
|
287
|
+
|
|
288
|
+
```jsonc
|
|
289
|
+
{
|
|
290
|
+
"provider": {
|
|
291
|
+
"litellm": {
|
|
292
|
+
"options": {
|
|
293
|
+
"baseURL": "http://localhost:4000/v1",
|
|
294
|
+
"modelCapabilities": {
|
|
295
|
+
"te-gpt-5.4-mini": { "supports_function_calling": true },
|
|
296
|
+
"openai/gpt-4o": { "supports_vision": false }
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
- Overrides apply on top of whatever the proxy reports, with an explicit `false` winning — a flag the proxy never reported can be forced on just the same.
|
|
305
|
+
- Keys are exact model ids as they appear in `/v1/models` (not globs).
|
|
306
|
+
- Overridden flags flow into the picker exactly like natively reported ones, and the adjusted view is what gets persisted to the model cache.
|
|
307
|
+
- Changing `modelCapabilities` (or `includeModels`/`excludeModels`) starts a fresh discovery on the next start — the cache is scoped by that config — so the picker reflects the new flags immediately.
|
|
308
|
+
|
|
309
|
+
### Keeping raw model ids in the picker (`formatModelNames`)
|
|
310
|
+
|
|
311
|
+
By default the plugin prettifies each discovered id into a display name — `anthropic/claude-3-5-sonnet` shows up as `Claude 3.5 Sonnet`. If you'd rather see your LiteLLM `model_list` aliases verbatim (for example because your team refers to models by those exact names, or the formatter mangles an internal naming scheme), turn formatting off:
|
|
312
|
+
|
|
313
|
+
```jsonc
|
|
314
|
+
{
|
|
315
|
+
"provider": {
|
|
316
|
+
"litellm": {
|
|
317
|
+
"options": {
|
|
318
|
+
"baseURL": "http://localhost:4000/v1",
|
|
319
|
+
"formatModelNames": false
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
- The display name becomes the exact model id as returned by `/v1/models` (provider prefix, version suffixes and all). Nothing else changes — ids, capability flags, pricing and filtering behave exactly as before.
|
|
327
|
+
- Only a boolean `false` disables formatting; omitting the option or setting anything else keeps the default.
|
|
328
|
+
- Like the other options above, `formatModelNames` is part of the cache identity, so toggling it triggers a fresh discovery on the next start instead of serving previously cached names.
|
|
329
|
+
- To rename just a handful of models while keeping smart formatting for the rest, use the per-model `name` override described in [Overriding or curating individual models](#overriding-or-curating-individual-models-optional).
|
|
330
|
+
|
|
283
331
|
## 🔧 How it works
|
|
284
332
|
|
|
285
333
|
```mermaid
|
|
@@ -311,7 +359,7 @@ sequenceDiagram
|
|
|
311
359
|
Plugin->>Cache: persist for next startup
|
|
312
360
|
end
|
|
313
361
|
Note over Plugin,Cache: on session.created, revalidate cache in<br/>the background (throttled to 5 min)
|
|
314
|
-
OC->>OC: render model picker with all discovered models
|
|
362
|
+
OC->>OC: render model picker with all discovered models (CLI)
|
|
315
363
|
```
|
|
316
364
|
|
|
317
365
|
1. On OpenCode startup the `config` lifecycle hook fires.
|
|
@@ -322,6 +370,8 @@ sequenceDiagram
|
|
|
322
370
|
6. Discovered models are merged on top of any user-defined ones — never overwriting them — and persisted to the cache.
|
|
323
371
|
7. On every `session.created` event the cache is revalidated in the background (throttled to once per 5 minutes); refreshed entries surface on the next OpenCode start. The whole cold path is capped by a 20 s timeout so a slow proxy never blocks boot.
|
|
324
372
|
|
|
373
|
+
> **OpenCode Desktop:** Dynamic LiteLLM models currently appear in the CLI but may not appear in the Desktop model picker. This is an observed OpenCode Desktop config-hook limitation: plugin mutations are not reflected in the provider state used by the picker. The plugin cannot safely work around this without persisting resolved configuration and credentials. Track [issue #5](https://github.com/yuseferi/opencode-litellm/issues/5) for updates.
|
|
374
|
+
|
|
325
375
|
## 📋 Requirements
|
|
326
376
|
|
|
327
377
|
- [OpenCode](https://opencode.ai) ≥ 0.1.x with plugin support (`@opencode-ai/plugin ^1.14.0`)
|
|
@@ -354,6 +404,15 @@ delete the cache directory (`~/.cache/opencode-litellm/`, or
|
|
|
354
404
|
`$XDG_CACHE_HOME/opencode-litellm/`).
|
|
355
405
|
</details>
|
|
356
406
|
|
|
407
|
+
<details>
|
|
408
|
+
<summary><b>Why do discovered models appear in the CLI but not OpenCode Desktop?</b></summary>
|
|
409
|
+
|
|
410
|
+
OpenCode Desktop currently does not reflect mutations made by a plugin's
|
|
411
|
+
`config` hook in the provider state used by its model picker. The plugin works
|
|
412
|
+
as expected in the CLI, but there is no safe plugin-side workaround yet. This
|
|
413
|
+
is being tracked in [issue #5](https://github.com/yuseferi/opencode-litellm/issues/5).
|
|
414
|
+
</details>
|
|
415
|
+
|
|
357
416
|
<details>
|
|
358
417
|
<summary><b>Can I use this with a remote LiteLLM proxy?</b></summary>
|
|
359
418
|
|
|
@@ -444,9 +503,11 @@ src/
|
|
|
444
503
|
│ ├── litellm-api.ts # health check, discovery (/v1/models + /v1/model/info), auto-detect
|
|
445
504
|
│ ├── format-model-name.ts # name formatting, categorization
|
|
446
505
|
│ ├── model-cache.ts # stale-while-revalidate on-disk model cache
|
|
506
|
+
│ ├── model-filter.ts # includeModels/excludeModels glob filtering
|
|
507
|
+
│ ├── model-capabilities.ts # per-model capability flag overrides
|
|
447
508
|
│ └── opencode-auth.ts # fallback to OpenCode's /connect-stored credentials
|
|
448
509
|
└── plugin/
|
|
449
|
-
└── index.ts # LiteLLMPlugin entry (config hook, enrichment, filtering)
|
|
510
|
+
└── index.ts # LiteLLMPlugin entry (config hook, enrichment, filtering, capability overrides, naming)
|
|
450
511
|
|
|
451
512
|
test/ # vitest suite for the pure logic
|
|
452
513
|
```
|
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": "1.
|
|
4
|
+
"version": "1.3.0",
|
|
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",
|
package/src/plugin/index.ts
CHANGED
|
@@ -13,9 +13,16 @@ import {
|
|
|
13
13
|
} from '../utils/format-model-name'
|
|
14
14
|
import type { LiteLLMModel, LiteLLMModelInfo } from '../types'
|
|
15
15
|
import { getOpenCodeStoredApiKey } from '../utils/opencode-auth'
|
|
16
|
-
import {
|
|
16
|
+
import {
|
|
17
|
+
buildCacheKey,
|
|
18
|
+
readModelCache,
|
|
19
|
+
writeModelCache,
|
|
20
|
+
readModelCacheSavedAt,
|
|
21
|
+
} from '../utils/model-cache'
|
|
17
22
|
import { passesModelFilter } from '../utils/model-filter'
|
|
18
23
|
import type { ModelFilters } from '../utils/model-filter'
|
|
24
|
+
import { applyCapabilityOverrides, parseModelCapabilities } from '../utils/model-capabilities'
|
|
25
|
+
import type { ModelCapabilities } from '../utils/model-capabilities'
|
|
19
26
|
|
|
20
27
|
const CHAT_PROVIDER_ID = 'litellm'
|
|
21
28
|
// Covers the 3 s health check plus the parallel models/model-info fetch
|
|
@@ -73,6 +80,8 @@ interface RefreshContext {
|
|
|
73
80
|
apiKey?: string
|
|
74
81
|
customHeaders?: Record<string, string>
|
|
75
82
|
filters: ModelFilters
|
|
83
|
+
capabilities: ModelCapabilities
|
|
84
|
+
formatModelNames: boolean
|
|
76
85
|
providerId: string
|
|
77
86
|
}
|
|
78
87
|
const refreshContexts = new Map<string, RefreshContext>()
|
|
@@ -148,30 +157,45 @@ function readModelFilters(options: Record<string, unknown>): ModelFilters {
|
|
|
148
157
|
}
|
|
149
158
|
}
|
|
150
159
|
|
|
160
|
+
function readFormatModelNames(options: Record<string, unknown>): boolean {
|
|
161
|
+
return options.formatModelNames !== false
|
|
162
|
+
}
|
|
163
|
+
|
|
151
164
|
/**
|
|
152
|
-
* Overlay metadata
|
|
153
|
-
*
|
|
154
|
-
*
|
|
155
|
-
*
|
|
165
|
+
* Overlay metadata onto a `/v1/models` entry in three tiers: the entry's
|
|
166
|
+
* own fields win, `/v1/model/info` fills gaps (notably `mode`, which
|
|
167
|
+
* `/v1/models` omits for database-defined models), and finally
|
|
168
|
+
* user-configured `modelCapabilities` overrides apply — explicit
|
|
169
|
+
* `false` included — because the user knows their deployment better
|
|
170
|
+
* than either endpoint (issue #25).
|
|
156
171
|
*/
|
|
157
|
-
function enrichModel(
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
model.
|
|
174
|
-
|
|
172
|
+
function enrichModel(
|
|
173
|
+
model: LiteLLMModel,
|
|
174
|
+
info: LiteLLMModelInfo | undefined,
|
|
175
|
+
overrides?: Record<string, boolean>,
|
|
176
|
+
): LiteLLMModel {
|
|
177
|
+
return applyCapabilityOverrides(
|
|
178
|
+
{
|
|
179
|
+
...model,
|
|
180
|
+
mode: model.mode ?? info?.mode,
|
|
181
|
+
max_tokens: model.max_tokens ?? info?.max_tokens,
|
|
182
|
+
max_input_tokens: model.max_input_tokens ?? info?.max_input_tokens,
|
|
183
|
+
max_output_tokens: model.max_output_tokens ?? info?.max_output_tokens,
|
|
184
|
+
supports_function_calling:
|
|
185
|
+
model.supports_function_calling ?? info?.supports_function_calling,
|
|
186
|
+
supports_vision: model.supports_vision ?? info?.supports_vision,
|
|
187
|
+
supports_reasoning: model.supports_reasoning ?? info?.supports_reasoning,
|
|
188
|
+
supports_pdf_input: model.supports_pdf_input ?? info?.supports_pdf_input,
|
|
189
|
+
supports_audio_input: model.supports_audio_input ?? info?.supports_audio_input,
|
|
190
|
+
input_cost_per_token: model.input_cost_per_token ?? info?.input_cost_per_token,
|
|
191
|
+
output_cost_per_token: model.output_cost_per_token ?? info?.output_cost_per_token,
|
|
192
|
+
cache_read_input_token_cost:
|
|
193
|
+
model.cache_read_input_token_cost ?? info?.cache_read_input_token_cost,
|
|
194
|
+
cache_creation_input_token_cost:
|
|
195
|
+
model.cache_creation_input_token_cost ?? info?.cache_creation_input_token_cost,
|
|
196
|
+
},
|
|
197
|
+
overrides,
|
|
198
|
+
)
|
|
175
199
|
}
|
|
176
200
|
|
|
177
201
|
/**
|
|
@@ -188,17 +212,21 @@ const USD_PER_TOKEN_TO_PER_MILLION = 1_000_000
|
|
|
188
212
|
* `opencode.json`). Returns `null` for non-chat models (embedding,
|
|
189
213
|
* image, audio) — they can't be used as primary chat models and would
|
|
190
214
|
* clutter the picker.
|
|
215
|
+
*
|
|
216
|
+
* Exported for tests: `formatModelNames` decides whether the display
|
|
217
|
+
* name is the prettified id or the raw `/v1/models` id verbatim.
|
|
191
218
|
*/
|
|
192
|
-
function toConfigModel(
|
|
219
|
+
export function toConfigModel(
|
|
193
220
|
model: LiteLLMModel,
|
|
194
221
|
info?: LiteLLMModelInfo,
|
|
222
|
+
formatModelNames = true,
|
|
195
223
|
): Record<string, unknown> | null {
|
|
196
224
|
const type = categorizeModel(model)
|
|
197
225
|
if (type === 'embedding' || type === 'image' || type === 'audio') {
|
|
198
226
|
return null
|
|
199
227
|
}
|
|
200
228
|
const entry: Record<string, unknown> = {
|
|
201
|
-
name: formatModelName(model),
|
|
229
|
+
name: formatModelNames ? formatModelName(model) : model.id,
|
|
202
230
|
}
|
|
203
231
|
// Some deployments only report the OpenAI-style `max_tokens` total;
|
|
204
232
|
// use it as the context limit when `max_input_tokens` is absent.
|
|
@@ -258,10 +286,11 @@ function toConfigModel(
|
|
|
258
286
|
*
|
|
259
287
|
* Pure with respect to plugin config: it performs the network calls,
|
|
260
288
|
* classifies + formats each model, and returns a `{ id -> entry }` map.
|
|
261
|
-
* The provider's `includeModels`/`excludeModels` filters
|
|
262
|
-
*
|
|
263
|
-
*
|
|
264
|
-
*
|
|
289
|
+
* The provider's `includeModels`/`excludeModels` filters,
|
|
290
|
+
* `modelCapabilities` overrides and `formatModelNames` choice are
|
|
291
|
+
* applied here (not at merge time) so every path that persists or
|
|
292
|
+
* serves a cache — cold discovery and background refresh — writes the
|
|
293
|
+
* same adjusted view.
|
|
265
294
|
*
|
|
266
295
|
* Returns `null` when the proxy is unreachable/unauthorized or exposes
|
|
267
296
|
* no models, so callers can distinguish "no data" from "empty result".
|
|
@@ -272,6 +301,8 @@ async function discoverModels(
|
|
|
272
301
|
customHeaders: Record<string, string> | undefined,
|
|
273
302
|
providerId: string,
|
|
274
303
|
filters: ModelFilters = {},
|
|
304
|
+
capabilities: ModelCapabilities = {},
|
|
305
|
+
formatModelNames = true,
|
|
275
306
|
): Promise<Record<string, unknown> | null> {
|
|
276
307
|
if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders))) {
|
|
277
308
|
log(
|
|
@@ -343,7 +374,11 @@ async function discoverModels(
|
|
|
343
374
|
}
|
|
344
375
|
const info = infoByName?.get(model.id)
|
|
345
376
|
if (infoByName && !info) unmatched.push(model.id)
|
|
346
|
-
const entry = toConfigModel(
|
|
377
|
+
const entry = toConfigModel(
|
|
378
|
+
enrichModel(model, info, capabilities[model.id]),
|
|
379
|
+
info,
|
|
380
|
+
formatModelNames,
|
|
381
|
+
)
|
|
347
382
|
if (!entry) {
|
|
348
383
|
skipped++
|
|
349
384
|
continue
|
|
@@ -424,7 +459,15 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
|
|
|
424
459
|
refreshInFlight.add(cacheKey)
|
|
425
460
|
try {
|
|
426
461
|
const built = await withTimeout(
|
|
427
|
-
discoverModels(
|
|
462
|
+
discoverModels(
|
|
463
|
+
ctx.baseURL,
|
|
464
|
+
ctx.apiKey,
|
|
465
|
+
ctx.customHeaders,
|
|
466
|
+
ctx.providerId,
|
|
467
|
+
ctx.filters,
|
|
468
|
+
ctx.capabilities,
|
|
469
|
+
ctx.formatModelNames,
|
|
470
|
+
),
|
|
428
471
|
DISCOVERY_TIMEOUT_MS,
|
|
429
472
|
)
|
|
430
473
|
if (built && Object.keys(built).length > 0) {
|
|
@@ -525,6 +568,8 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
525
568
|
const apiKey = configuredKey ?? envKey ?? storedKey
|
|
526
569
|
const customHeaders = readCustomHeaders(options)
|
|
527
570
|
const filters = readModelFilters(options)
|
|
571
|
+
const capabilities = parseModelCapabilities(options.modelCapabilities)
|
|
572
|
+
const formatModelNames = readFormatModelNames(options)
|
|
528
573
|
|
|
529
574
|
// Resolve base URL
|
|
530
575
|
let baseURL: string | null = null
|
|
@@ -580,11 +625,24 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
580
625
|
|
|
581
626
|
const models = actualProvider.models as Record<string, unknown>
|
|
582
627
|
|
|
583
|
-
|
|
628
|
+
// Identity includes the filter/capability/naming config: those
|
|
629
|
+
// are baked into cached entries, so changing them must start a
|
|
630
|
+
// fresh discovery instead of serving the old adjusted view.
|
|
631
|
+
const cacheKey = buildCacheKey(providerId, baseURL, filters, capabilities, {
|
|
632
|
+
formatModelNames,
|
|
633
|
+
})
|
|
584
634
|
|
|
585
635
|
// Remember how to reach this proxy so the `event` hook can
|
|
586
636
|
// revalidate its cache in the background on new sessions.
|
|
587
|
-
refreshContexts.set(cacheKey, {
|
|
637
|
+
refreshContexts.set(cacheKey, {
|
|
638
|
+
baseURL,
|
|
639
|
+
apiKey,
|
|
640
|
+
customHeaders,
|
|
641
|
+
filters,
|
|
642
|
+
capabilities,
|
|
643
|
+
formatModelNames,
|
|
644
|
+
providerId,
|
|
645
|
+
})
|
|
588
646
|
|
|
589
647
|
// Repeat config-hook invocations within a run are a no-op once
|
|
590
648
|
// we've injected this provider's models.
|
|
@@ -616,7 +674,15 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
616
674
|
// persist for subsequent startups. Capped by a timeout so a slow
|
|
617
675
|
// proxy never blocks boot.
|
|
618
676
|
const built = await withTimeout(
|
|
619
|
-
discoverModels(
|
|
677
|
+
discoverModels(
|
|
678
|
+
baseURL,
|
|
679
|
+
apiKey,
|
|
680
|
+
customHeaders,
|
|
681
|
+
providerId,
|
|
682
|
+
filters,
|
|
683
|
+
capabilities,
|
|
684
|
+
formatModelNames,
|
|
685
|
+
),
|
|
620
686
|
DISCOVERY_TIMEOUT_MS,
|
|
621
687
|
)
|
|
622
688
|
if (built && Object.keys(built).length > 0) {
|
package/src/utils/index.ts
CHANGED
package/src/utils/litellm-api.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { LiteLLMModel, LiteLLMModelInfo, LiteLLMModelInfoResponse, LiteLLMModelsResponse } from '../types'
|
|
2
|
+
import { CAPABILITY_FLAGS } from './model-capabilities'
|
|
2
3
|
|
|
3
4
|
export const DEFAULT_LITELLM_URL = 'http://localhost:4000'
|
|
4
5
|
const MODELS_ENDPOINT = '/v1/models'
|
|
@@ -128,14 +129,7 @@ export async function discoverLiteLLMModelInfo(
|
|
|
128
129
|
// Some deployments set capability flags on the params block rather
|
|
129
130
|
// than inside model_info. Fill those gaps so enrichment sees them.
|
|
130
131
|
const info: LiteLLMModelInfo = { ...entry.model_info }
|
|
131
|
-
const
|
|
132
|
-
'supports_vision',
|
|
133
|
-
'supports_function_calling',
|
|
134
|
-
'supports_reasoning',
|
|
135
|
-
'supports_pdf_input',
|
|
136
|
-
'supports_audio_input',
|
|
137
|
-
] as const
|
|
138
|
-
for (const flag of capabilityFlags) {
|
|
132
|
+
for (const flag of CAPABILITY_FLAGS) {
|
|
139
133
|
const paramsValue = entry.litellm_params?.[flag]
|
|
140
134
|
if (info[flag] == null && typeof paramsValue === 'boolean') {
|
|
141
135
|
info[flag] = paramsValue
|
package/src/utils/model-cache.ts
CHANGED
|
@@ -47,6 +47,63 @@ function cacheFile(cacheKey: string): string {
|
|
|
47
47
|
return join(cacheDir(), `models-${hash}.json`)
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
+
/**
|
|
51
|
+
* Canonical JSON serialization (object keys sorted) so semantically
|
|
52
|
+
* identical filter/capability configs fingerprint identically no matter
|
|
53
|
+
* the key order in the user's `opencode.json`.
|
|
54
|
+
*/
|
|
55
|
+
function canonicalize(value: unknown): string {
|
|
56
|
+
if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`
|
|
57
|
+
if (value && typeof value === 'object') {
|
|
58
|
+
const entries = Object.entries(value as Record<string, unknown>)
|
|
59
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
60
|
+
.map(([k, v]) => `${JSON.stringify(k)}:${canonicalize(v)}`)
|
|
61
|
+
return `{${entries.join(',')}}`
|
|
62
|
+
}
|
|
63
|
+
return JSON.stringify(value)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Cache identity for a provider's model view. `providerId@baseURL`
|
|
68
|
+
* alone isn't enough: `includeModels`/`excludeModels`,
|
|
69
|
+
* `modelCapabilities` and `formatModelNames` are baked into cached
|
|
70
|
+
* entries by discovery, so a config change must not reuse the old cache
|
|
71
|
+
* — it would keep serving the previous adjusted view until a second
|
|
72
|
+
* restart. A fingerprint is appended whenever adjustments exist
|
|
73
|
+
* (pattern order ignored); default configs keep the plain key so
|
|
74
|
+
* existing caches stay warm across plugin upgrades.
|
|
75
|
+
*/
|
|
76
|
+
export function buildCacheKey(
|
|
77
|
+
providerId: string,
|
|
78
|
+
baseURL: string,
|
|
79
|
+
filters: { includeModels?: string[]; excludeModels?: string[] },
|
|
80
|
+
capabilities: Record<string, Record<string, boolean>>,
|
|
81
|
+
naming: { formatModelNames?: boolean } = {},
|
|
82
|
+
): string {
|
|
83
|
+
const base = `${providerId}@${baseURL}`
|
|
84
|
+
const rawNames = naming.formatModelNames === false
|
|
85
|
+
const hasAdjustments =
|
|
86
|
+
(filters.includeModels?.length ?? 0) > 0 ||
|
|
87
|
+
(filters.excludeModels?.length ?? 0) > 0 ||
|
|
88
|
+
Object.keys(capabilities).length > 0 ||
|
|
89
|
+
rawNames
|
|
90
|
+
if (!hasAdjustments) return base
|
|
91
|
+
const fingerprint = createHash('sha256')
|
|
92
|
+
.update(
|
|
93
|
+
canonicalize({
|
|
94
|
+
includeModels: filters.includeModels ? [...filters.includeModels].sort() : undefined,
|
|
95
|
+
excludeModels: filters.excludeModels ? [...filters.excludeModels].sort() : undefined,
|
|
96
|
+
capabilities,
|
|
97
|
+
// Omitted (not `true`) when formatting is on, so keys for
|
|
98
|
+
// configs that never touch this option are unchanged.
|
|
99
|
+
formatModelNames: rawNames ? false : undefined,
|
|
100
|
+
}),
|
|
101
|
+
)
|
|
102
|
+
.digest('hex')
|
|
103
|
+
.slice(0, 12)
|
|
104
|
+
return `${base}@${fingerprint}`
|
|
105
|
+
}
|
|
106
|
+
|
|
50
107
|
/**
|
|
51
108
|
* Read cached model entries for a cache key. Returns `null` on any
|
|
52
109
|
* problem (missing file, parse error, version mismatch, or an entry
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export const CAPABILITY_FLAGS = [
|
|
2
|
+
'supports_vision',
|
|
3
|
+
'supports_function_calling',
|
|
4
|
+
'supports_reasoning',
|
|
5
|
+
'supports_pdf_input',
|
|
6
|
+
'supports_audio_input',
|
|
7
|
+
] as const
|
|
8
|
+
|
|
9
|
+
export type CapabilityFlag = (typeof CAPABILITY_FLAGS)[number]
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Per-model boolean capability overrides keyed by exact model id
|
|
13
|
+
* (`provider.litellm.options.modelCapabilities`). Keys of the inner
|
|
14
|
+
* record are not restricted to `CapabilityFlag`: any boolean capability
|
|
15
|
+
* key LiteLLM reports is accepted, so future flags work without a
|
|
16
|
+
* plugin change.
|
|
17
|
+
*/
|
|
18
|
+
export type ModelCapabilities = Record<string, Record<string, boolean>>
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Defensively parse the `modelCapabilities` provider option. Non-object
|
|
22
|
+
* input, non-object per-model values, and non-boolean flag values are
|
|
23
|
+
* dropped; everything else (including explicit `false`) is kept.
|
|
24
|
+
*/
|
|
25
|
+
export function parseModelCapabilities(raw: unknown): ModelCapabilities {
|
|
26
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}
|
|
27
|
+
const out: ModelCapabilities = {}
|
|
28
|
+
for (const [modelId, flags] of Object.entries(raw as Record<string, unknown>)) {
|
|
29
|
+
if (!flags || typeof flags !== 'object' || Array.isArray(flags)) continue
|
|
30
|
+
const parsed: Record<string, boolean> = {}
|
|
31
|
+
for (const [flag, value] of Object.entries(flags as Record<string, unknown>)) {
|
|
32
|
+
if (typeof value === 'boolean') parsed[flag] = value
|
|
33
|
+
}
|
|
34
|
+
if (Object.keys(parsed).length > 0) out[modelId] = parsed
|
|
35
|
+
}
|
|
36
|
+
return out
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Overlay user-configured capability flags onto a (possibly enriched)
|
|
41
|
+
* model entry. Explicit `false` wins over whatever the proxy reported,
|
|
42
|
+
* and unknown-to-the-proxy flags are added outright.
|
|
43
|
+
*/
|
|
44
|
+
export function applyCapabilityOverrides<T extends object>(
|
|
45
|
+
model: T,
|
|
46
|
+
overrides?: Readonly<Record<string, boolean>>,
|
|
47
|
+
): T {
|
|
48
|
+
if (!overrides || Object.keys(overrides).length === 0) return model
|
|
49
|
+
return Object.assign({}, model, overrides)
|
|
50
|
+
}
|