|
| 1 | +type OpenAIModule = typeof import('@ai-sdk/openai-compatible'); |
| 2 | +import type { OpenAICompatibleProviderSettings } from '@ai-sdk/openai-compatible'; |
| 3 | +import type { LanguageModelV2 } from '@ai-sdk/provider'; |
| 4 | +import type { ModelConfig, ProviderMetadata, ProviderInstanceParams } from '../types'; |
| 5 | +import { AIProvider, createModelId, createProviderId, isObject } from '../types'; |
| 6 | +import { LmStudioIcon } from '../icons'; |
| 7 | +import { baseUrlField, makeConfiguration, type ConfigAPI } from './configuration'; |
| 8 | + |
| 9 | +type LmStudioModelType = 'llm' | 'embeddings'; |
| 10 | + |
| 11 | +interface LmStudioModel { |
| 12 | + id: string; |
| 13 | + type: LmStudioModelType; |
| 14 | + max_context_length?: number; |
| 15 | + capabilities?: string[]; |
| 16 | +} |
| 17 | + |
| 18 | +interface LmStudioModelListResponse { |
| 19 | + data: LmStudioModel[]; |
| 20 | +} |
| 21 | + |
| 22 | +function isLmStudioModel(value: unknown): value is LmStudioModel { |
| 23 | + if (!isObject(value)) { |
| 24 | + return false; |
| 25 | + } |
| 26 | + |
| 27 | + const candidate = value as { |
| 28 | + id?: unknown; |
| 29 | + type?: unknown; |
| 30 | + max_context_length?: unknown; |
| 31 | + capabilities?: unknown; |
| 32 | + }; |
| 33 | + |
| 34 | + if (typeof candidate.id !== 'string') { |
| 35 | + return false; |
| 36 | + } |
| 37 | + |
| 38 | + if (candidate.type !== 'llm' && candidate.type !== 'embeddings') { |
| 39 | + return false; |
| 40 | + } |
| 41 | + |
| 42 | + if ( |
| 43 | + candidate.max_context_length !== undefined && |
| 44 | + typeof candidate.max_context_length !== 'number' |
| 45 | + ) { |
| 46 | + return false; |
| 47 | + } |
| 48 | + |
| 49 | + if ( |
| 50 | + candidate.capabilities !== undefined && |
| 51 | + (!Array.isArray(candidate.capabilities) || |
| 52 | + candidate.capabilities.some((capability) => typeof capability !== 'string')) |
| 53 | + ) { |
| 54 | + return false; |
| 55 | + } |
| 56 | + |
| 57 | + return true; |
| 58 | +} |
| 59 | + |
| 60 | +function isLmStudioModelListResponse(value: unknown): value is LmStudioModelListResponse { |
| 61 | + if (!isObject(value)) { |
| 62 | + return false; |
| 63 | + } |
| 64 | + |
| 65 | + const candidate = value as { data?: unknown }; |
| 66 | + |
| 67 | + if (!Array.isArray(candidate.data)) { |
| 68 | + return false; |
| 69 | + } |
| 70 | + |
| 71 | + return candidate.data.every((item) => isLmStudioModel(item)); |
| 72 | +} |
| 73 | + |
| 74 | +export class LmStudioProvider extends AIProvider { |
| 75 | + override readonly metadata: ProviderMetadata = { |
| 76 | + id: createProviderId('lmstudio'), |
| 77 | + name: 'LMStudio', |
| 78 | + description: 'Use GPT-4o, GPT-4, or other OpenAI models', |
| 79 | + icon: LmStudioIcon, |
| 80 | + documentationUrl: 'https://lmstudio.ai/docs/app/api/endpoints/openai', |
| 81 | + fetchModelListPath: '/api/v0/models', |
| 82 | + }; |
| 83 | + |
| 84 | + override readonly models: ModelConfig[] = []; |
| 85 | + |
| 86 | + override readonly configuration: ConfigAPI<OpenAICompatibleProviderSettings> = |
| 87 | + makeConfiguration<OpenAICompatibleProviderSettings>()({ |
| 88 | + fields: [baseUrlField('http://localhost:1234/v1')], |
| 89 | + }); |
| 90 | + |
| 91 | + override async fetchModels( |
| 92 | + options: ProviderInstanceParams['options'] | undefined |
| 93 | + ): Promise<ModelConfig[]> { |
| 94 | + if (this.metadata.fetchModelListPath === undefined) { |
| 95 | + return []; |
| 96 | + } |
| 97 | + |
| 98 | + this.configuration.assertValidConfigAndRemoveEmptyKeys(options); |
| 99 | + |
| 100 | + const baseUrl = |
| 101 | + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, sonarjs/different-types-comparison |
| 102 | + options !== undefined && 'baseURL' in options && options.baseURL.trim().length > 0 |
| 103 | + ? options.baseURL |
| 104 | + : 'http://localhost:1234/v1'; |
| 105 | + |
| 106 | + let requestUrl: URL; |
| 107 | + try { |
| 108 | + const base = new URL(baseUrl); |
| 109 | + requestUrl = new URL(this.metadata.fetchModelListPath, base.origin); |
| 110 | + } catch (error) { |
| 111 | + const reason = error instanceof Error ? error.message : String(error); |
| 112 | + throw new Error(`Invalid LM Studio base URL: ${reason}`); |
| 113 | + } |
| 114 | + |
| 115 | + const response = await fetch(requestUrl); |
| 116 | + if (!response.ok) { |
| 117 | + throw new Error( |
| 118 | + `Failed to fetch LM Studio models: ${String(response.status)} ${response.statusText}` |
| 119 | + ); |
| 120 | + } |
| 121 | + |
| 122 | + const payload = (await response.json()) as unknown; |
| 123 | + if (!isLmStudioModelListResponse(payload)) { |
| 124 | + throw new TypeError('Unexpected LM Studio model list response payload'); |
| 125 | + } |
| 126 | + |
| 127 | + return payload.data |
| 128 | + .filter((model) => model.type !== 'embeddings') |
| 129 | + .map((model) => ({ |
| 130 | + id: createModelId(model.id), |
| 131 | + displayName: model.id, |
| 132 | + contextLength: model.max_context_length, |
| 133 | + supportsTools: model.capabilities?.includes('tool_use') ?? false, |
| 134 | + discoveredAt: Date.now(), |
| 135 | + })); |
| 136 | + } |
| 137 | + |
| 138 | + async createInstance(params: ProviderInstanceParams): Promise<LanguageModelV2> { |
| 139 | + // Dynamic import to avoid bundling if not needed |
| 140 | + let openai: OpenAIModule; |
| 141 | + |
| 142 | + try { |
| 143 | + // This will be a peer dependency |
| 144 | + openai = await import('@ai-sdk/openai-compatible'); |
| 145 | + } catch { |
| 146 | + throw new Error( |
| 147 | + 'LmStudio provider requires "@ai-sdk/openai-compatible" to be installed. ' + |
| 148 | + 'Please install it with: npm install @ai-sdk/openai-compatible' |
| 149 | + ); |
| 150 | + } |
| 151 | + |
| 152 | + this.configuration.assertValidConfigAndRemoveEmptyKeys(params.options); |
| 153 | + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
| 154 | + params.options.baseURL ??= 'http://localhost:1234/v1'; |
| 155 | + const client = openai.createOpenAICompatible(params.options); |
| 156 | + return client(params.model); |
| 157 | + } |
| 158 | +} |
0 commit comments