opencode-plugin-litellm 0.1.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/LICENSE +21 -0
- package/README.md +95 -0
- package/package.json +44 -0
- package/src/index.ts +2 -0
- package/src/plugin/config-hook.ts +38 -0
- package/src/plugin/enhance-config.ts +130 -0
- package/src/plugin/index.ts +33 -0
- package/src/types/index.ts +40 -0
- package/src/utils/format-model-name.ts +85 -0
- package/src/utils/index.ts +2 -0
- package/src/utils/litellm-api.ts +89 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yusef Mohamadi (@yuseferi)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# opencode-litellm
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/opencode-plugin-litellm)
|
|
4
|
+
[](https://github.com/yuseferi/opencode-litellm/actions/workflows/ci.yml)
|
|
5
|
+
[](./LICENSE)
|
|
6
|
+
|
|
7
|
+
OpenCode plugin for [LiteLLM](https://github.com/BerriAI/litellm) proxy support
|
|
8
|
+
with **auto-detection** and **dynamic model discovery**.
|
|
9
|
+
|
|
10
|
+
Inspired by [`opencode-lmstudio`](https://github.com/agustif/opencode-lmstudio).
|
|
11
|
+
|
|
12
|
+
> **npm package name:** `opencode-plugin-litellm` (the unscoped `opencode-litellm`
|
|
13
|
+
> name was taken on npm). Repo name and plugin export remain `opencode-litellm`.
|
|
14
|
+
|
|
15
|
+
## Features
|
|
16
|
+
|
|
17
|
+
- **Auto-detection** — finds a LiteLLM proxy running on common ports (`4000`, `8000`, `8080`)
|
|
18
|
+
- **Dynamic model discovery** — queries `/v1/models` so you never hand-maintain a model list
|
|
19
|
+
- **OpenAI-compatible** — registers under OpenCode as `@ai-sdk/openai-compatible`
|
|
20
|
+
- **Vendor-aware** — extracts `litellm_provider` (or the `provider/model` prefix) into `organizationOwner`
|
|
21
|
+
- **Smart formatting** — turns `anthropic/claude-3-5-sonnet` into `Claude 3 5 Sonnet` in the picker
|
|
22
|
+
- **Categorization** — chat / embedding / image / audio modalities are inferred from the model `mode` or id
|
|
23
|
+
- **Non-blocking** — discovery is capped at 5s so a slow proxy never blocks OpenCode startup
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
npm install opencode-plugin-litellm
|
|
29
|
+
# or
|
|
30
|
+
bun add opencode-plugin-litellm
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Usage
|
|
34
|
+
|
|
35
|
+
### Zero-config (recommended)
|
|
36
|
+
|
|
37
|
+
If a LiteLLM proxy is already running on `localhost:4000`, just add the plugin:
|
|
38
|
+
|
|
39
|
+
```json
|
|
40
|
+
{
|
|
41
|
+
"$schema": "https://opencode.ai/config.json",
|
|
42
|
+
"plugin": ["opencode-plugin-litellm@latest"]
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The plugin will detect the proxy, query `/v1/models`, and inject every model into
|
|
47
|
+
your provider list automatically.
|
|
48
|
+
|
|
49
|
+
### Manual configuration
|
|
50
|
+
|
|
51
|
+
```json
|
|
52
|
+
{
|
|
53
|
+
"$schema": "https://opencode.ai/config.json",
|
|
54
|
+
"plugin": ["opencode-plugin-litellm@latest"],
|
|
55
|
+
"provider": {
|
|
56
|
+
"litellm": {
|
|
57
|
+
"npm": "@ai-sdk/openai-compatible",
|
|
58
|
+
"name": "LiteLLM (proxy)",
|
|
59
|
+
"options": {
|
|
60
|
+
"baseURL": "http://localhost:4000/v1",
|
|
61
|
+
"apiKey": "{env:LITELLM_API_KEY}"
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Any models you predefine under `provider.litellm.models` are kept as-is; the
|
|
69
|
+
plugin only adds models it discovers that aren't already configured.
|
|
70
|
+
|
|
71
|
+
### Authentication
|
|
72
|
+
|
|
73
|
+
If your LiteLLM proxy requires a master key, expose it via either:
|
|
74
|
+
|
|
75
|
+
- `apiKey` field inside `provider.litellm.options`, or
|
|
76
|
+
- the `LITELLM_API_KEY` (or `LITELLM_MASTER_KEY`) environment variable.
|
|
77
|
+
|
|
78
|
+
## How it works
|
|
79
|
+
|
|
80
|
+
1. On OpenCode startup the `config` hook fires.
|
|
81
|
+
2. If a `litellm` provider is configured, its `baseURL` is used. Otherwise the
|
|
82
|
+
plugin probes `localhost:4000`, `:8000`, `:8080`.
|
|
83
|
+
3. Health check via `GET /v1/models`. If unreachable, the hook is a no-op.
|
|
84
|
+
4. Models from `/v1/models` are turned into OpenCode model entries with
|
|
85
|
+
sensible `name`, `organizationOwner`, and `modalities` fields.
|
|
86
|
+
5. Discovered models are merged on top of any user-configured ones.
|
|
87
|
+
|
|
88
|
+
## Requirements
|
|
89
|
+
|
|
90
|
+
- OpenCode with plugin support (`@opencode-ai/plugin ^1.0.166`)
|
|
91
|
+
- A running LiteLLM proxy (`pip install 'litellm[proxy]' && litellm --config config.yaml`)
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
MIT
|
package/package.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json.schemastore.org/package.json",
|
|
3
|
+
"name": "opencode-plugin-litellm",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"description": "OpenCode plugin for LiteLLM proxy support with auto-detection and dynamic model discovery",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./src/index.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/index.ts"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"src"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"typecheck": "tsc --noEmit",
|
|
16
|
+
"build": "npm run typecheck",
|
|
17
|
+
"prepublishOnly": "npm run build"
|
|
18
|
+
},
|
|
19
|
+
"keywords": [
|
|
20
|
+
"opencode",
|
|
21
|
+
"litellm",
|
|
22
|
+
"lite-llm",
|
|
23
|
+
"plugin",
|
|
24
|
+
"llm-proxy",
|
|
25
|
+
"openai-compatible"
|
|
26
|
+
],
|
|
27
|
+
"author": "Yusef Mohamadi (https://github.com/yuseferi)",
|
|
28
|
+
"license": "MIT",
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/yuseferi/opencode-litellm.git"
|
|
32
|
+
},
|
|
33
|
+
"bugs": {
|
|
34
|
+
"url": "https://github.com/yuseferi/opencode-litellm/issues"
|
|
35
|
+
},
|
|
36
|
+
"homepage": "https://github.com/yuseferi/opencode-litellm#readme",
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"@opencode-ai/plugin": "^1.0.166"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@types/node": "^25.0.3",
|
|
42
|
+
"typescript": "^5.9.3"
|
|
43
|
+
}
|
|
44
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
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 count = config?.provider?.litellm?.models
|
|
31
|
+
? Object.keys(config.provider.litellm.models).length
|
|
32
|
+
: 0
|
|
33
|
+
|
|
34
|
+
if (count === 0 && config?.provider?.litellm) {
|
|
35
|
+
console.warn('[opencode-litellm] No models loaded — is LiteLLM reachable and is your model_list non-empty?')
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import {
|
|
2
|
+
autoDetectLiteLLM,
|
|
3
|
+
checkLiteLLMHealth,
|
|
4
|
+
discoverLiteLLMModels,
|
|
5
|
+
normalizeBaseURL,
|
|
6
|
+
} from '../utils/litellm-api'
|
|
7
|
+
import { categorizeModel, extractModelOwner, formatModelName } from '../utils/format-model-name'
|
|
8
|
+
import type { LiteLLMModel } from '../types'
|
|
9
|
+
|
|
10
|
+
const PROVIDER_KEY = 'litellm'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Build the OpenCode model entry for a single discovered model.
|
|
14
|
+
*/
|
|
15
|
+
function buildModelEntry(model: LiteLLMModel): Record<string, unknown> {
|
|
16
|
+
const owner = extractModelOwner(model)
|
|
17
|
+
const type = categorizeModel(model)
|
|
18
|
+
|
|
19
|
+
const entry: Record<string, unknown> = {
|
|
20
|
+
id: model.id,
|
|
21
|
+
name: formatModelName(model),
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if (owner) entry.organizationOwner = owner
|
|
25
|
+
|
|
26
|
+
switch (type) {
|
|
27
|
+
case 'embedding':
|
|
28
|
+
entry.modalities = { input: ['text'], output: ['embedding'] }
|
|
29
|
+
break
|
|
30
|
+
case 'image':
|
|
31
|
+
entry.modalities = { input: ['text'], output: ['image'] }
|
|
32
|
+
break
|
|
33
|
+
case 'audio':
|
|
34
|
+
entry.modalities = { input: ['audio', 'text'], output: ['text'] }
|
|
35
|
+
break
|
|
36
|
+
case 'chat':
|
|
37
|
+
default:
|
|
38
|
+
entry.modalities = {
|
|
39
|
+
input: model.supports_vision ? ['text', 'image'] : ['text'],
|
|
40
|
+
output: ['text'],
|
|
41
|
+
}
|
|
42
|
+
break
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (model.supports_function_calling) {
|
|
46
|
+
entry.toolCall = true
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return entry
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Mutates `config` in place: ensures the litellm provider exists,
|
|
54
|
+
* fetches all models from the LiteLLM proxy and merges them in.
|
|
55
|
+
*/
|
|
56
|
+
export async function enhanceConfig(config: any): Promise<void> {
|
|
57
|
+
if (!config) return
|
|
58
|
+
|
|
59
|
+
if (!config.provider) config.provider = {}
|
|
60
|
+
let provider = config.provider[PROVIDER_KEY]
|
|
61
|
+
|
|
62
|
+
// Resolve baseURL & apiKey, either from the user's provider config
|
|
63
|
+
// or by auto-detecting a running LiteLLM proxy.
|
|
64
|
+
let baseURL: string
|
|
65
|
+
let apiKey: string | undefined
|
|
66
|
+
|
|
67
|
+
if (provider) {
|
|
68
|
+
baseURL = normalizeBaseURL(provider.options?.baseURL ?? 'http://localhost:4000')
|
|
69
|
+
apiKey = provider.options?.apiKey ?? process.env.LITELLM_API_KEY ?? process.env.LITELLM_MASTER_KEY
|
|
70
|
+
} else {
|
|
71
|
+
const detected = await autoDetectLiteLLM()
|
|
72
|
+
if (!detected) {
|
|
73
|
+
// Nothing to do — LiteLLM doesn't appear to be running anywhere
|
|
74
|
+
// we know about. Silently bail; this is the no-op case.
|
|
75
|
+
return
|
|
76
|
+
}
|
|
77
|
+
baseURL = normalizeBaseURL(detected)
|
|
78
|
+
apiKey = process.env.LITELLM_API_KEY ?? process.env.LITELLM_MASTER_KEY
|
|
79
|
+
|
|
80
|
+
provider = {
|
|
81
|
+
npm: '@ai-sdk/openai-compatible',
|
|
82
|
+
name: 'LiteLLM (proxy)',
|
|
83
|
+
options: {
|
|
84
|
+
baseURL: `${baseURL}/v1`,
|
|
85
|
+
...(apiKey ? { apiKey } : {}),
|
|
86
|
+
},
|
|
87
|
+
models: {},
|
|
88
|
+
}
|
|
89
|
+
config.provider[PROVIDER_KEY] = provider
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Verify the server is actually answering before we hammer /v1/models.
|
|
93
|
+
if (!(await checkLiteLLMHealth(baseURL, apiKey))) {
|
|
94
|
+
console.warn(`[opencode-litellm] LiteLLM appears offline or unauthorized at ${baseURL}`)
|
|
95
|
+
return
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
let models: LiteLLMModel[]
|
|
99
|
+
try {
|
|
100
|
+
models = await discoverLiteLLMModels(baseURL, apiKey)
|
|
101
|
+
} catch (error) {
|
|
102
|
+
console.warn('[opencode-litellm] Model discovery failed:', error instanceof Error ? error.message : String(error))
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (models.length === 0) {
|
|
107
|
+
console.warn('[opencode-litellm] LiteLLM responded but exposed zero models. Check your `model_list` in litellm config.yaml')
|
|
108
|
+
return
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const existing: Record<string, any> = provider.models ?? {}
|
|
112
|
+
const discovered: Record<string, any> = {}
|
|
113
|
+
|
|
114
|
+
for (const model of models) {
|
|
115
|
+
// Use the raw id as the key when it's safe (most LiteLLM ids are
|
|
116
|
+
// safe — e.g. "gpt-4o" or "anthropic/claude-3-5-sonnet"), otherwise
|
|
117
|
+
// sanitize it so OpenCode can parse it.
|
|
118
|
+
const key = /^[a-zA-Z0-9/_.\-:]+$/.test(model.id)
|
|
119
|
+
? model.id
|
|
120
|
+
: model.id.replace(/[^a-zA-Z0-9_-]/g, '_')
|
|
121
|
+
|
|
122
|
+
if (existing[key] || existing[model.id]) continue
|
|
123
|
+
discovered[key] = buildModelEntry(model)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (Object.keys(discovered).length === 0) return
|
|
127
|
+
|
|
128
|
+
provider.models = { ...existing, ...discovered }
|
|
129
|
+
console.log(`[opencode-litellm] Discovered ${Object.keys(discovered).length} model(s) from LiteLLM at ${baseURL}`)
|
|
130
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Plugin, PluginInput } from '@opencode-ai/plugin'
|
|
2
|
+
import { createConfigHook } from './config-hook'
|
|
3
|
+
|
|
4
|
+
/**
|
|
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
|
+
* Configure (optional):
|
|
12
|
+
*
|
|
13
|
+
* {
|
|
14
|
+
* "plugin": ["opencode-plugin-litellm@latest"],
|
|
15
|
+
* "provider": {
|
|
16
|
+
* "litellm": {
|
|
17
|
+
* "npm": "@ai-sdk/openai-compatible",
|
|
18
|
+
* "name": "LiteLLM (proxy)",
|
|
19
|
+
* "options": {
|
|
20
|
+
* "baseURL": "http://localhost:4000/v1",
|
|
21
|
+
* "apiKey": "{env:LITELLM_API_KEY}"
|
|
22
|
+
* }
|
|
23
|
+
* }
|
|
24
|
+
* }
|
|
25
|
+
* }
|
|
26
|
+
*/
|
|
27
|
+
export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
|
|
28
|
+
console.log('[opencode-litellm] LiteLLM plugin initialized')
|
|
29
|
+
|
|
30
|
+
return {
|
|
31
|
+
config: createConfigHook(),
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Core types for the LiteLLM OpenCode plugin
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A single model entry returned by LiteLLM's `/v1/models` endpoint.
|
|
5
|
+
* LiteLLM follows the OpenAI-compatible schema.
|
|
6
|
+
*/
|
|
7
|
+
export interface LiteLLMModel {
|
|
8
|
+
id: string
|
|
9
|
+
object: string
|
|
10
|
+
created?: number
|
|
11
|
+
owned_by?: string
|
|
12
|
+
/**
|
|
13
|
+
* LiteLLM-specific extension. Some deployments include the underlying
|
|
14
|
+
* provider (e.g. "openai", "anthropic", "bedrock") here.
|
|
15
|
+
*/
|
|
16
|
+
litellm_provider?: string
|
|
17
|
+
/**
|
|
18
|
+
* Optional capability metadata exposed by some LiteLLM versions
|
|
19
|
+
* via `/model/info` (we ignore it for the lean discovery endpoint
|
|
20
|
+
* but keep the type around for forward-compat).
|
|
21
|
+
*/
|
|
22
|
+
mode?: string
|
|
23
|
+
max_tokens?: number
|
|
24
|
+
max_input_tokens?: number
|
|
25
|
+
max_output_tokens?: number
|
|
26
|
+
supports_function_calling?: boolean
|
|
27
|
+
supports_vision?: boolean
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface LiteLLMModelsResponse {
|
|
31
|
+
object: string
|
|
32
|
+
data: LiteLLMModel[]
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export type ModelType = 'chat' | 'embedding' | 'image' | 'audio' | 'unknown'
|
|
36
|
+
|
|
37
|
+
export interface LiteLLMOptions {
|
|
38
|
+
baseURL?: string
|
|
39
|
+
apiKey?: string
|
|
40
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { LiteLLMModel } from '../types'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Extract owner / provider from a LiteLLM model ID.
|
|
5
|
+
*
|
|
6
|
+
* LiteLLM model IDs commonly take the shape `<provider>/<model>` (e.g.
|
|
7
|
+
* `openai/gpt-4o`, `anthropic/claude-3-5-sonnet`, `bedrock/...`). When
|
|
8
|
+
* available we prefer the `litellm_provider` field returned by the API.
|
|
9
|
+
*/
|
|
10
|
+
export function extractModelOwner(model: LiteLLMModel): string | undefined {
|
|
11
|
+
if (model.litellm_provider) return model.litellm_provider
|
|
12
|
+
const parts = model.id.split('/')
|
|
13
|
+
if (parts.length > 1) return parts[0]
|
|
14
|
+
return undefined
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Categorize the model so we can attach sensible `modalities` metadata
|
|
19
|
+
* in the OpenCode provider config.
|
|
20
|
+
*/
|
|
21
|
+
export function categorizeModel(model: LiteLLMModel): 'chat' | 'embedding' | 'image' | 'audio' | 'unknown' {
|
|
22
|
+
if (model.mode) {
|
|
23
|
+
const m = model.mode.toLowerCase()
|
|
24
|
+
if (m.includes('embedding')) return 'embedding'
|
|
25
|
+
if (m.includes('image')) return 'image'
|
|
26
|
+
if (m.includes('audio') || m.includes('speech') || m.includes('transcription')) return 'audio'
|
|
27
|
+
if (m.includes('chat') || m.includes('completion')) return 'chat'
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const id = model.id.toLowerCase()
|
|
31
|
+
if (id.includes('embed') || id.includes('embedding')) return 'embedding'
|
|
32
|
+
if (id.includes('whisper') || id.includes('tts')) return 'audio'
|
|
33
|
+
if (id.includes('dall-e') || id.includes('stable-diffusion') || id.includes('flux')) return 'image'
|
|
34
|
+
return 'chat'
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Format a LiteLLM model ID into a human readable display name.
|
|
39
|
+
*
|
|
40
|
+
* Examples:
|
|
41
|
+
* "openai/gpt-4o-mini" -> "GPT 4o Mini"
|
|
42
|
+
* "anthropic/claude-3-5-sonnet" -> "Claude 3 5 Sonnet"
|
|
43
|
+
* "bedrock/amazon.nova-pro-v1" -> "Amazon Nova Pro V1"
|
|
44
|
+
* "qwen/qwen3-30b-a3b" -> "Qwen3 30B A3B"
|
|
45
|
+
*/
|
|
46
|
+
export function formatModelName(model: LiteLLMModel): string {
|
|
47
|
+
const { id } = model
|
|
48
|
+
|
|
49
|
+
// Drop provider prefix when present, but only the FIRST segment, so
|
|
50
|
+
// ids like `bedrock/amazon.nova-pro-v1` still carry the vendor name
|
|
51
|
+
// through to the display.
|
|
52
|
+
const slashIdx = id.indexOf('/')
|
|
53
|
+
const modelPart = slashIdx >= 0 ? id.slice(slashIdx + 1) : id
|
|
54
|
+
|
|
55
|
+
const acronyms = new Set([
|
|
56
|
+
'gpt', 'oss', 'api', 'gguf', 'ggml', 'nomic', 'vl', 'it', 'mlx',
|
|
57
|
+
'llm', 'ai', 'sdk', 'aws', 'gcp', 'tts', 'stt', 'mm',
|
|
58
|
+
])
|
|
59
|
+
|
|
60
|
+
const tokens = modelPart
|
|
61
|
+
.split(/[-_.]/) // split on -, _ and .
|
|
62
|
+
.filter(Boolean)
|
|
63
|
+
.map((token) => {
|
|
64
|
+
const lower = token.toLowerCase()
|
|
65
|
+
if (acronyms.has(lower)) return token.toUpperCase()
|
|
66
|
+
// sizes (30b, 7b, 4k...)
|
|
67
|
+
if (/^\d+[bkmg]$/i.test(token)) return token.toUpperCase()
|
|
68
|
+
// quantizations (q4, q8...)
|
|
69
|
+
if (/^q\d+$/i.test(token)) return token.toUpperCase()
|
|
70
|
+
// semantic versions like 3.5
|
|
71
|
+
if (/^\d+\.\d+/.test(token)) return token
|
|
72
|
+
// shapes like a3b, e4b, 3n -> uppercase
|
|
73
|
+
if (/^[a-z]\d+[a-z]?$/i.test(token)) {
|
|
74
|
+
return token.toUpperCase()
|
|
75
|
+
}
|
|
76
|
+
// shapes like "4o" (OpenAI branding) — keep digit + lowercase letter
|
|
77
|
+
if (/^\d+[a-z]$/i.test(token)) {
|
|
78
|
+
return token.toLowerCase()
|
|
79
|
+
}
|
|
80
|
+
return token.charAt(0).toUpperCase() + token.slice(1).toLowerCase()
|
|
81
|
+
})
|
|
82
|
+
.join(' ')
|
|
83
|
+
|
|
84
|
+
return tokens || id
|
|
85
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { LiteLLMModel, LiteLLMModelsResponse } from '../types'
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_LITELLM_URL = 'http://localhost:4000'
|
|
4
|
+
const MODELS_ENDPOINT = '/v1/models'
|
|
5
|
+
const REQUEST_TIMEOUT_MS = 3000
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Normalise a base URL so the rest of the plugin can rely on a
|
|
9
|
+
* predictable shape (no trailing slash, no `/v1` suffix).
|
|
10
|
+
*/
|
|
11
|
+
export function normalizeBaseURL(baseURL: string = DEFAULT_LITELLM_URL): string {
|
|
12
|
+
let normalized = baseURL.replace(/\/+$/, '')
|
|
13
|
+
if (normalized.endsWith('/v1')) {
|
|
14
|
+
normalized = normalized.slice(0, -3)
|
|
15
|
+
}
|
|
16
|
+
return normalized
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Build a full URL for a given API endpoint. */
|
|
20
|
+
export function buildAPIURL(baseURL: string, endpoint: string = MODELS_ENDPOINT): string {
|
|
21
|
+
return `${normalizeBaseURL(baseURL)}${endpoint}`
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function buildHeaders(apiKey?: string): Record<string, string> {
|
|
25
|
+
const headers: Record<string, string> = {
|
|
26
|
+
'Content-Type': 'application/json',
|
|
27
|
+
}
|
|
28
|
+
const key = apiKey ?? process.env.LITELLM_API_KEY ?? process.env.LITELLM_MASTER_KEY
|
|
29
|
+
if (key) {
|
|
30
|
+
headers['Authorization'] = `Bearer ${key}`
|
|
31
|
+
}
|
|
32
|
+
return headers
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Lightweight ping to see whether a LiteLLM server is reachable. */
|
|
36
|
+
export async function checkLiteLLMHealth(
|
|
37
|
+
baseURL: string = DEFAULT_LITELLM_URL,
|
|
38
|
+
apiKey?: string,
|
|
39
|
+
): Promise<boolean> {
|
|
40
|
+
try {
|
|
41
|
+
const response = await fetch(buildAPIURL(baseURL), {
|
|
42
|
+
method: 'GET',
|
|
43
|
+
headers: buildHeaders(apiKey),
|
|
44
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
45
|
+
})
|
|
46
|
+
// 401 still means a server is alive — we just don't have the right
|
|
47
|
+
// credentials. Surface that as "unhealthy" so the user is prompted
|
|
48
|
+
// to set LITELLM_API_KEY.
|
|
49
|
+
return response.ok
|
|
50
|
+
} catch {
|
|
51
|
+
return false
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Discover all models exposed by a LiteLLM proxy. */
|
|
56
|
+
export async function discoverLiteLLMModels(
|
|
57
|
+
baseURL: string = DEFAULT_LITELLM_URL,
|
|
58
|
+
apiKey?: string,
|
|
59
|
+
): Promise<LiteLLMModel[]> {
|
|
60
|
+
const url = buildAPIURL(baseURL)
|
|
61
|
+
const response = await fetch(url, {
|
|
62
|
+
method: 'GET',
|
|
63
|
+
headers: buildHeaders(apiKey),
|
|
64
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
if (!response.ok) {
|
|
68
|
+
throw new Error(`LiteLLM responded with HTTP ${response.status} ${response.statusText}`)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const data = (await response.json()) as LiteLLMModelsResponse
|
|
72
|
+
return data.data ?? []
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Try the most common ports a LiteLLM proxy is started on.
|
|
77
|
+
* The default `litellm --port` is 4000, but 8000 is also widely used
|
|
78
|
+
* and 8080 is a common reverse-proxy default.
|
|
79
|
+
*/
|
|
80
|
+
export async function autoDetectLiteLLM(apiKey?: string): Promise<string | null> {
|
|
81
|
+
const commonPorts = [4000, 8000, 8080]
|
|
82
|
+
for (const port of commonPorts) {
|
|
83
|
+
const baseURL = `http://localhost:${port}`
|
|
84
|
+
if (await checkLiteLLMHealth(baseURL, apiKey)) {
|
|
85
|
+
return baseURL
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return null
|
|
89
|
+
}
|