opencode-plugin-litellm 0.2.3 → 0.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/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.2.3",
4
+ "version": "0.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",
@@ -35,7 +35,8 @@
35
35
  },
36
36
  "homepage": "https://github.com/yuseferi/opencode-litellm#readme",
37
37
  "dependencies": {
38
- "@opencode-ai/plugin": "^1.0.166"
38
+ "@opencode-ai/plugin": "^1.14.0",
39
+ "@opencode-ai/sdk": "^1.2.0"
39
40
  },
40
41
  "devDependencies": {
41
42
  "@types/node": "^25.0.3",
package/src/index.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { LiteLLMPlugin } from './plugin'
1
+ export { LiteLLMPlugin, LiteLLMResponsesPlugin } from './plugin'
2
2
  export * from './types'
@@ -0,0 +1,70 @@
1
+ import type { Model as ModelV2 } from '@opencode-ai/sdk/v2'
2
+ import type { LiteLLMModel } from '../types'
3
+ import {
4
+ categorizeModel,
5
+ formatModelName,
6
+ } from '../utils/format-model-name'
7
+
8
+ /**
9
+ * Build an OpenCode V2 `Model` entry from a discovered LiteLLM model.
10
+ *
11
+ * The V2 schema requires a lot of fields we have no real data for
12
+ * (`cost`, `limit`, `release_date`, …). We fill these with sensible
13
+ * defaults — zero cost / zero limits / today's date — so the entry
14
+ * type-checks and the picker renders something useful. Real values
15
+ * can be added in a future release if LiteLLM exposes them via
16
+ * `/v1/model/info`, which carries `max_tokens`, `input_cost_per_token`,
17
+ * etc.
18
+ */
19
+ export function buildModelV2(
20
+ providerID: string,
21
+ api: { id: string; url: string; npm: string },
22
+ model: LiteLLMModel,
23
+ ): ModelV2 {
24
+ const type = categorizeModel(model)
25
+ const isVision = !!model.supports_vision
26
+ const isAudio = type === 'audio'
27
+ const isImageOut = type === 'image'
28
+
29
+ return {
30
+ id: model.id,
31
+ providerID,
32
+ api,
33
+ name: formatModelName(model),
34
+ capabilities: {
35
+ temperature: true,
36
+ reasoning: false,
37
+ attachment: isVision || isAudio,
38
+ toolcall: !!model.supports_function_calling,
39
+ input: {
40
+ text: true,
41
+ audio: isAudio,
42
+ image: isVision,
43
+ video: false,
44
+ pdf: false,
45
+ },
46
+ output: {
47
+ text: !isImageOut,
48
+ audio: false,
49
+ image: isImageOut,
50
+ video: false,
51
+ pdf: false,
52
+ },
53
+ interleaved: false,
54
+ },
55
+ cost: {
56
+ input: 0,
57
+ output: 0,
58
+ cache: { read: 0, write: 0 },
59
+ },
60
+ limit: {
61
+ context: model.max_input_tokens ?? 0,
62
+ input: model.max_input_tokens,
63
+ output: model.max_output_tokens ?? 0,
64
+ },
65
+ status: 'active',
66
+ options: {},
67
+ headers: {},
68
+ release_date: '',
69
+ }
70
+ }
@@ -0,0 +1,169 @@
1
+ import type { Model as ModelV2, Provider as ProviderV2 } from '@opencode-ai/sdk/v2'
2
+ import {
3
+ autoDetectLiteLLM,
4
+ checkLiteLLMHealth,
5
+ discoverLiteLLMModels,
6
+ normalizeBaseURL,
7
+ } from '../utils/litellm-api'
8
+ import { requiresResponsesAPI } from '../utils/format-model-name'
9
+ import type { LiteLLMModel, Transport, TransportPolicy } from '../types'
10
+ import { buildModelV2 } from './build-model'
11
+
12
+ const DISCOVERY_TIMEOUT_MS = 5000
13
+
14
+ /**
15
+ * Decide which transport bucket a model belongs to. Order of
16
+ * precedence (highest first):
17
+ *
18
+ * 1. Explicit allowlist `responsesApiModels` → 'responses'
19
+ * 2. Explicit denylist `chatApiModels` → 'chat'
20
+ * 3. Global policy `transport: 'chat' | 'responses'`
21
+ * 4. Heuristic via {@link requiresResponsesAPI} → 'responses' or 'chat'
22
+ */
23
+ function pickTransport(
24
+ model: LiteLLMModel,
25
+ policy: TransportPolicy,
26
+ responsesApiModels: ReadonlySet<string>,
27
+ chatApiModels: ReadonlySet<string>,
28
+ ): Transport {
29
+ if (responsesApiModels.has(model.id)) return 'responses'
30
+ if (chatApiModels.has(model.id)) return 'chat'
31
+ if (policy === 'chat') return 'chat'
32
+ if (policy === 'responses') return 'responses'
33
+ return requiresResponsesAPI(model) ? 'responses' : 'chat'
34
+ }
35
+
36
+ /**
37
+ * Resolve the LiteLLM `baseURL` and `apiKey` to use for discovery.
38
+ *
39
+ * Looks at the configured provider options first (so the user's
40
+ * `opencode.json` wins), then falls back to env vars, and finally to
41
+ * auto-detecting a local proxy on the common ports.
42
+ */
43
+ async function resolveEndpoint(
44
+ provider: ProviderV2 | undefined,
45
+ ): Promise<{ baseURL: string; apiKey?: string } | null> {
46
+ const options = (provider?.options ?? {}) as Record<string, unknown>
47
+ const configuredBase = typeof options.baseURL === 'string' ? options.baseURL : undefined
48
+ const configuredKey = typeof options.apiKey === 'string' && options.apiKey ? options.apiKey : undefined
49
+ const envKey = process.env.LITELLM_API_KEY ?? process.env.LITELLM_MASTER_KEY
50
+
51
+ if (configuredBase) {
52
+ return { baseURL: normalizeBaseURL(configuredBase), apiKey: configuredKey ?? envKey }
53
+ }
54
+
55
+ const detected = await autoDetectLiteLLM(configuredKey ?? envKey)
56
+ if (!detected) return null
57
+ return { baseURL: normalizeBaseURL(detected), apiKey: configuredKey ?? envKey }
58
+ }
59
+
60
+ /**
61
+ * Read the routing policy and per-model overrides off the provider's
62
+ * `options` block. Defaults to `'auto'` with empty allow/deny lists.
63
+ */
64
+ function readRoutingOptions(
65
+ provider: ProviderV2 | undefined,
66
+ ): {
67
+ policy: TransportPolicy
68
+ responsesApiModels: Set<string>
69
+ chatApiModels: Set<string>
70
+ } {
71
+ const options = (provider?.options ?? {}) as Record<string, unknown>
72
+ const policy =
73
+ typeof options.transport === 'string' &&
74
+ (options.transport === 'auto' || options.transport === 'chat' || options.transport === 'responses')
75
+ ? (options.transport as TransportPolicy)
76
+ : 'auto'
77
+ const responses = Array.isArray(options.responsesApiModels)
78
+ ? options.responsesApiModels.filter((v): v is string => typeof v === 'string')
79
+ : []
80
+ const chat = Array.isArray(options.chatApiModels)
81
+ ? options.chatApiModels.filter((v): v is string => typeof v === 'string')
82
+ : []
83
+ return {
84
+ policy,
85
+ responsesApiModels: new Set(responses),
86
+ chatApiModels: new Set(chat),
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Discover all models from the LiteLLM proxy and bucket them by the
92
+ * transport (`chat` vs `responses`) they should use. Returns a map of
93
+ * model id → V2 `Model` for the requested bucket only.
94
+ *
95
+ * Pass `bucket: 'all'` to ignore the routing heuristic and return
96
+ * every discovered model. Useful for the default chat-only setup
97
+ * where the user hasn't declared a sibling `litellm-responses`
98
+ * provider — without `'all'`, gpt-5* / o-series models would be
99
+ * silently dropped.
100
+ *
101
+ * Capped at {@link DISCOVERY_TIMEOUT_MS} so a slow / unreachable
102
+ * proxy never stalls OpenCode startup.
103
+ */
104
+ export async function discoverBucket(
105
+ bucket: Transport | 'all',
106
+ provider: ProviderV2 | undefined,
107
+ api: { id: string; url: string; npm: string },
108
+ ): Promise<Record<string, ModelV2>> {
109
+ const out: Record<string, ModelV2> = {}
110
+
111
+ const work = async () => {
112
+ const endpoint = await resolveEndpoint(provider)
113
+ if (!endpoint) return
114
+
115
+ const { baseURL, apiKey } = endpoint
116
+ if (!(await checkLiteLLMHealth(baseURL, apiKey))) {
117
+ console.warn(`[opencode-litellm] LiteLLM appears offline or unauthorized at ${baseURL}`)
118
+ return
119
+ }
120
+
121
+ let models: LiteLLMModel[]
122
+ try {
123
+ models = await discoverLiteLLMModels(baseURL, apiKey)
124
+ } catch (error) {
125
+ console.warn(
126
+ '[opencode-litellm] Model discovery failed:',
127
+ error instanceof Error ? error.message : String(error),
128
+ )
129
+ return
130
+ }
131
+
132
+ if (models.length === 0) {
133
+ console.warn(
134
+ '[opencode-litellm] LiteLLM responded but exposed zero models. Check your `model_list` in litellm config.yaml',
135
+ )
136
+ return
137
+ }
138
+
139
+ const resolvedApi = { ...api, url: `${baseURL}/v1` }
140
+
141
+ const routing = readRoutingOptions(provider)
142
+ for (const model of models) {
143
+ if (bucket !== 'all') {
144
+ const transport = pickTransport(
145
+ model,
146
+ routing.policy,
147
+ routing.responsesApiModels,
148
+ routing.chatApiModels,
149
+ )
150
+ if (transport !== bucket) continue
151
+ }
152
+ // OpenCode's @ai-sdk/openai-compatible adapter uses `api.id` as
153
+ // the wire model name sent to the upstream LiteLLM endpoint
154
+ // (verified empirically — without this override the wire request
155
+ // sends the provider id "litellm" instead, and LiteLLM rejects
156
+ // it with "team not allowed"). Set `api.id` per-model so each
157
+ // entry carries the correct upstream model name.
158
+ const perModelApi = { ...resolvedApi, id: model.id }
159
+ out[model.id] = buildModelV2(resolvedApi.id, perModelApi, model)
160
+ }
161
+ }
162
+
163
+ await Promise.race([
164
+ work(),
165
+ new Promise<void>((resolve) => setTimeout(resolve, DISCOVERY_TIMEOUT_MS)),
166
+ ])
167
+
168
+ return out
169
+ }
@@ -1,24 +1,26 @@
1
1
  import type { Plugin, PluginInput } from '@opencode-ai/plugin'
2
- import { createConfigHook } from './config-hook'
2
+ import { discoverBucket } from './discover'
3
+
4
+ const CHAT_PROVIDER_ID = 'litellm'
5
+ const RESPONSES_PROVIDER_ID = 'litellm-responses'
3
6
 
4
7
  /**
5
- * LiteLLM Plugin for OpenCode
6
- *
7
- * Auto-detects a running LiteLLM proxy (default port 4000) and pulls
8
- * the full `model_list` out of `/v1/models` so you don't have to
9
- * hand-maintain models in `opencode.json`.
10
- *
11
- * Discovered models are split into two providers based on the transport
12
- * required by the upstream model:
8
+ * LiteLLM Plugin for OpenCode.
13
9
  *
14
- * - `litellm` → /v1/chat/completions (most models)
15
- * - `litellm-responses` → /v1/responses (gpt-5*, o-series with reasoning)
10
+ * Implements the `provider.models` hook so OpenCode populates the
11
+ * `litellm` provider's model list from a live LiteLLM proxy at
12
+ * startup. No models need to be hand-defined in `opencode.json`.
16
13
  *
17
- * The split is necessary because reasoning-tier OpenAI models reject
18
- * requests that combine `reasoning_effort` with function tools when sent
19
- * to chat-completions.
14
+ * By default, every discovered model is registered under the
15
+ * `litellm` provider — including OpenAI reasoning-tier models like
16
+ * `gpt-5*`. Most of those models work fine through
17
+ * `/v1/chat/completions` for normal use. If you actually hit the
18
+ * "Function tools with reasoning_effort are not supported" error
19
+ * from OpenAI, declare a sibling `litellm-responses` provider in
20
+ * `opencode.json` (see {@link LiteLLMResponsesPlugin}) and the
21
+ * plugin will route those models through `/v1/responses` instead.
20
22
  *
21
- * Configure (optional):
23
+ * Configure the provider in your `opencode.json`:
22
24
  *
23
25
  * {
24
26
  * "plugin": ["opencode-plugin-litellm@latest"],
@@ -28,21 +30,73 @@ import { createConfigHook } from './config-hook'
28
30
  * "name": "LiteLLM (proxy)",
29
31
  * "options": {
30
32
  * "baseURL": "http://localhost:4000/v1",
31
- * "apiKey": "{env:LITELLM_API_KEY}",
32
- *
33
- * // Optional routing controls (added in 0.2.0):
34
- * "transport": "auto", // "auto" | "chat" | "responses"
35
- * "responsesApiModels": ["gpt-5-4-high"], // force into /v1/responses
36
- * "chatApiModels": ["o1-mini"] // force into /v1/chat/completions
33
+ * "apiKey": "{env:LITELLM_API_KEY}"
37
34
  * }
38
35
  * }
39
36
  * }
40
37
  * }
41
38
  */
42
39
  export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
43
- console.log('[opencode-litellm] LiteLLM plugin initialized')
40
+ return {
41
+ provider: {
42
+ id: CHAT_PROVIDER_ID,
43
+ models: async (provider) => {
44
+ // 'all' (not 'chat') by default so reasoning-tier models like
45
+ // gpt-5* don't silently disappear when the user hasn't opted
46
+ // into the responses-API split. The split only kicks in when
47
+ // the user explicitly declares a `litellm-responses` provider.
48
+ return discoverBucket('all', provider, {
49
+ id: CHAT_PROVIDER_ID,
50
+ url: '',
51
+ npm: '@ai-sdk/openai-compatible',
52
+ })
53
+ },
54
+ },
55
+ }
56
+ }
44
57
 
58
+ /**
59
+ * Optional sibling plugin that registers the `litellm-responses`
60
+ * provider for OpenAI reasoning-tier models.
61
+ *
62
+ * OpenAI's reasoning-tier models (`gpt-5*`, `o1`/`o3`/`o4*`) reject
63
+ * requests that combine `reasoning_effort` with function tools when
64
+ * sent to `/v1/chat/completions`. Routing those models through
65
+ * `/v1/responses` (the OpenAI Responses API) avoids the rejection.
66
+ *
67
+ * This plugin is only active when the `litellm-responses` provider
68
+ * is declared in `opencode.json`. When it is, the chat-only `litellm`
69
+ * provider continues to register every discovered model — set
70
+ * `chatApiModels` / `responsesApiModels` on either provider's options
71
+ * if you want to control which side a particular model lives on.
72
+ *
73
+ * Example `opencode.json` snippet:
74
+ *
75
+ * {
76
+ * "provider": {
77
+ * "litellm-responses": {
78
+ * "npm": "@ai-sdk/openai",
79
+ * "name": "LiteLLM (responses)",
80
+ * "options": {
81
+ * "baseURL": "http://localhost:4000/v1",
82
+ * "apiKey": "{env:LITELLM_API_KEY}",
83
+ * "compatibility": "strict"
84
+ * }
85
+ * }
86
+ * }
87
+ * }
88
+ */
89
+ export const LiteLLMResponsesPlugin: Plugin = async (_input: PluginInput) => {
45
90
  return {
46
- config: createConfigHook(),
91
+ provider: {
92
+ id: RESPONSES_PROVIDER_ID,
93
+ models: async (provider) => {
94
+ return discoverBucket('responses', provider, {
95
+ id: RESPONSES_PROVIDER_ID,
96
+ url: '',
97
+ npm: '@ai-sdk/openai',
98
+ })
99
+ },
100
+ },
47
101
  }
48
102
  }
@@ -1,41 +0,0 @@
1
- import { enhanceConfig } from './enhance-config'
2
-
3
- const ENHANCE_TIMEOUT_MS = 5000
4
-
5
- /**
6
- * Returns the OpenCode `config` lifecycle hook.
7
- *
8
- * The hook is fire-and-merge: we attempt to enrich the user's config
9
- * with models discovered from LiteLLM, but we cap the wall-clock cost
10
- * so a slow / unreachable proxy never blocks OpenCode startup.
11
- */
12
- export function createConfigHook() {
13
- return async (config: any) => {
14
- if (!config) return
15
-
16
- if (Object.isFrozen?.(config) || Object.isSealed?.(config)) {
17
- console.warn('[opencode-litellm] Config object is frozen/sealed - cannot inject discovered models')
18
- return
19
- }
20
-
21
- try {
22
- await Promise.race([
23
- enhanceConfig(config),
24
- new Promise<void>((resolve) => setTimeout(resolve, ENHANCE_TIMEOUT_MS)),
25
- ])
26
- } catch (error) {
27
- console.error('[opencode-litellm] Config enhancement failed:', error)
28
- }
29
-
30
- const chatCount = config?.provider?.litellm?.models
31
- ? Object.keys(config.provider.litellm.models).length
32
- : 0
33
- const responsesCount = config?.provider?.['litellm-responses']?.models
34
- ? Object.keys(config.provider['litellm-responses'].models).length
35
- : 0
36
-
37
- if (chatCount + responsesCount === 0 && config?.provider?.litellm) {
38
- console.warn('[opencode-litellm] No models loaded — is LiteLLM reachable and is your model_list non-empty?')
39
- }
40
- }
41
- }
@@ -1,260 +0,0 @@
1
- import {
2
- autoDetectLiteLLM,
3
- checkLiteLLMHealth,
4
- discoverLiteLLMModels,
5
- normalizeBaseURL,
6
- } from '../utils/litellm-api'
7
- import {
8
- categorizeModel,
9
- extractModelOwner,
10
- formatModelName,
11
- requiresResponsesAPI,
12
- } from '../utils/format-model-name'
13
- import type { LiteLLMModel, Transport, TransportPolicy } from '../types'
14
-
15
- const CHAT_PROVIDER_KEY = 'litellm'
16
- const RESPONSES_PROVIDER_KEY = 'litellm-responses'
17
-
18
- /**
19
- * Build the OpenCode model entry for a single discovered model.
20
- */
21
- function buildModelEntry(model: LiteLLMModel): Record<string, unknown> {
22
- const owner = extractModelOwner(model)
23
- const type = categorizeModel(model)
24
-
25
- const entry: Record<string, unknown> = {
26
- id: model.id,
27
- name: formatModelName(model),
28
- }
29
-
30
- if (owner) entry.organizationOwner = owner
31
-
32
- switch (type) {
33
- case 'embedding':
34
- entry.modalities = { input: ['text'], output: ['embedding'] }
35
- break
36
- case 'image':
37
- entry.modalities = { input: ['text'], output: ['image'] }
38
- break
39
- case 'audio':
40
- entry.modalities = { input: ['audio', 'text'], output: ['text'] }
41
- break
42
- case 'chat':
43
- default:
44
- entry.modalities = {
45
- input: model.supports_vision ? ['text', 'image'] : ['text'],
46
- output: ['text'],
47
- }
48
- break
49
- }
50
-
51
- if (model.supports_function_calling) {
52
- entry.toolCall = true
53
- }
54
-
55
- return entry
56
- }
57
-
58
- /**
59
- * Sanitize an id into a key OpenCode can parse. Most LiteLLM ids are
60
- * already safe (`gpt-4o`, `anthropic/claude-3-5-sonnet`).
61
- */
62
- function safeKey(id: string): string {
63
- return /^[a-zA-Z0-9/_.\-:]+$/.test(id) ? id : id.replace(/[^a-zA-Z0-9_-]/g, '_')
64
- }
65
-
66
- /**
67
- * Decide which transport bucket a model belongs to. Order of
68
- * precedence (highest first):
69
- *
70
- * 1. Explicit allowlist `responsesApiModels` → 'responses'
71
- * 2. Explicit denylist `chatApiModels` → 'chat'
72
- * 3. Global policy `transport: 'chat' | 'responses'`
73
- * 4. Heuristic via {@link requiresResponsesAPI} → 'responses' or 'chat'
74
- */
75
- function pickTransport(
76
- model: LiteLLMModel,
77
- policy: TransportPolicy,
78
- responsesApiModels: ReadonlySet<string>,
79
- chatApiModels: ReadonlySet<string>,
80
- ): Transport {
81
- if (responsesApiModels.has(model.id)) return 'responses'
82
- if (chatApiModels.has(model.id)) return 'chat'
83
- if (policy === 'chat') return 'chat'
84
- if (policy === 'responses') return 'responses'
85
- return requiresResponsesAPI(model) ? 'responses' : 'chat'
86
- }
87
-
88
- /**
89
- * Ensure a provider entry exists on `config.provider[key]` and return
90
- * it. If we created it just now, `created` is true so callers can log
91
- * one-time messages.
92
- */
93
- function ensureProvider(
94
- config: any,
95
- key: string,
96
- defaults: () => Record<string, unknown>,
97
- ): { provider: any; created: boolean } {
98
- if (config.provider[key]) {
99
- return { provider: config.provider[key], created: false }
100
- }
101
- const provider = defaults()
102
- config.provider[key] = provider
103
- return { provider, created: true }
104
- }
105
-
106
- /**
107
- * Mutates `config` in place: ensures the litellm provider(s) exist,
108
- * fetches all models from the LiteLLM proxy, and merges them into the
109
- * appropriate transport bucket (`litellm` for /v1/chat/completions,
110
- * `litellm-responses` for /v1/responses).
111
- */
112
- export async function enhanceConfig(config: any): Promise<void> {
113
- if (!config) return
114
-
115
- if (!config.provider) config.provider = {}
116
- let chatProvider = config.provider[CHAT_PROVIDER_KEY]
117
-
118
- // Resolve baseURL & apiKey, either from the user's primary provider
119
- // config or by auto-detecting a running LiteLLM proxy.
120
- let baseURL: string
121
- let apiKey: string | undefined
122
-
123
- if (chatProvider) {
124
- baseURL = normalizeBaseURL(chatProvider.options?.baseURL ?? 'http://localhost:4000')
125
- apiKey =
126
- chatProvider.options?.apiKey ??
127
- process.env.LITELLM_API_KEY ??
128
- process.env.LITELLM_MASTER_KEY
129
- } else {
130
- // Allow the user to pre-define ONLY the responses provider; in that
131
- // case we still need to know the baseURL/apiKey for discovery.
132
- const preDefinedResponses = config.provider[RESPONSES_PROVIDER_KEY]
133
- if (preDefinedResponses) {
134
- baseURL = normalizeBaseURL(preDefinedResponses.options?.baseURL ?? 'http://localhost:4000')
135
- apiKey =
136
- preDefinedResponses.options?.apiKey ??
137
- process.env.LITELLM_API_KEY ??
138
- process.env.LITELLM_MASTER_KEY
139
- } else {
140
- const detected = await autoDetectLiteLLM()
141
- if (!detected) {
142
- // Nothing to do — LiteLLM doesn't appear to be running anywhere
143
- // we know about. Silently bail; this is the no-op case.
144
- return
145
- }
146
- baseURL = normalizeBaseURL(detected)
147
- apiKey = process.env.LITELLM_API_KEY ?? process.env.LITELLM_MASTER_KEY
148
- }
149
-
150
- chatProvider = {
151
- npm: '@ai-sdk/openai-compatible',
152
- name: 'LiteLLM (proxy)',
153
- options: {
154
- baseURL: `${baseURL}/v1`,
155
- ...(apiKey ? { apiKey } : {}),
156
- },
157
- models: {},
158
- }
159
- config.provider[CHAT_PROVIDER_KEY] = chatProvider
160
- }
161
-
162
- // Verify the server is actually answering before we hammer /v1/models.
163
- if (!(await checkLiteLLMHealth(baseURL, apiKey))) {
164
- console.warn(`[opencode-litellm] LiteLLM appears offline or unauthorized at ${baseURL}`)
165
- return
166
- }
167
-
168
- let models: LiteLLMModel[]
169
- try {
170
- models = await discoverLiteLLMModels(baseURL, apiKey)
171
- } catch (error) {
172
- console.warn(
173
- '[opencode-litellm] Model discovery failed:',
174
- error instanceof Error ? error.message : String(error),
175
- )
176
- return
177
- }
178
-
179
- if (models.length === 0) {
180
- console.warn(
181
- '[opencode-litellm] LiteLLM responded but exposed zero models. Check your `model_list` in litellm config.yaml',
182
- )
183
- return
184
- }
185
-
186
- // Read the routing policy + per-model overrides from the chat provider's options.
187
- const policy: TransportPolicy =
188
- (chatProvider.options?.transport as TransportPolicy | undefined) ?? 'auto'
189
- const responsesApiModels = new Set<string>(
190
- Array.isArray(chatProvider.options?.responsesApiModels)
191
- ? chatProvider.options.responsesApiModels
192
- : [],
193
- )
194
- const chatApiModels = new Set<string>(
195
- Array.isArray(chatProvider.options?.chatApiModels) ? chatProvider.options.chatApiModels : [],
196
- )
197
-
198
- // First pass: bucket every discovered model by transport.
199
- const chatBucket: Record<string, any> = {}
200
- const responsesBucket: Record<string, any> = {}
201
-
202
- for (const model of models) {
203
- const key = safeKey(model.id)
204
- const entry = buildModelEntry(model)
205
- const transport = pickTransport(model, policy, responsesApiModels, chatApiModels)
206
- if (transport === 'responses') {
207
- responsesBucket[key] = entry
208
- } else {
209
- chatBucket[key] = entry
210
- }
211
- }
212
-
213
- // Lazily create the responses provider only when we actually have
214
- // something to put in it (or the user already declared one).
215
- let responsesProvider: any | undefined = config.provider[RESPONSES_PROVIDER_KEY]
216
- if (!responsesProvider && Object.keys(responsesBucket).length > 0) {
217
- responsesProvider = {
218
- npm: '@ai-sdk/openai',
219
- name: 'LiteLLM (responses)',
220
- options: {
221
- baseURL: `${baseURL}/v1`,
222
- ...(apiKey ? { apiKey } : {}),
223
- // Help the AI SDK route to /v1/responses for reasoning models
224
- // when the upstream supports it.
225
- compatibility: 'strict',
226
- },
227
- models: {},
228
- }
229
- config.provider[RESPONSES_PROVIDER_KEY] = responsesProvider
230
- }
231
-
232
- // Non-destructive merge into each provider. A key is considered
233
- // "already present" if it exists under EITHER provider, so the user's
234
- // hand-curated entry wins regardless of which bucket we'd have chosen.
235
- const mergeIntoProvider = (
236
- provider: any,
237
- bucket: Record<string, any>,
238
- bucketLabel: string,
239
- ): number => {
240
- if (!provider) return 0
241
- const existingHere: Record<string, any> = provider.models ?? {}
242
- const existingChat: Record<string, any> = chatProvider.models ?? {}
243
- const existingResp: Record<string, any> = responsesProvider?.models ?? {}
244
- const additions: Record<string, any> = {}
245
- for (const [key, entry] of Object.entries(bucket)) {
246
- if (existingHere[key]) continue
247
- if (existingChat[key] || existingResp[key]) continue
248
- additions[key] = entry
249
- }
250
- if (Object.keys(additions).length === 0) return 0
251
- provider.models = { ...existingHere, ...additions }
252
- console.log(
253
- `[opencode-litellm] Discovered ${Object.keys(additions).length} ${bucketLabel} model(s) from LiteLLM at ${baseURL}`,
254
- )
255
- return Object.keys(additions).length
256
- }
257
-
258
- mergeIntoProvider(chatProvider, chatBucket, 'chat-completions')
259
- mergeIntoProvider(responsesProvider, responsesBucket, 'responses-API')
260
- }