| 1 | import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; |
| 2 | import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters"; |
| 3 | |
| 4 | import { |
| 5 | AuthConfig, |
| 6 | getAccessToken, |
| 7 | getModelName, |
| 8 | getOrganizationId, |
| 9 | } from "../auth/workos.js"; |
| 10 | import { getLlmApi } from "../config.js"; |
| 11 | import { logger } from "../util/logger.js"; |
| 12 | |
| 13 | import { BaseService, ServiceWithDependencies } from "./BaseService.js"; |
| 14 | import { ModelServiceState } from "./types.js"; |
| 15 | |
| 16 | /** |
| 17 | * Service for managing LLM and model state |
| 18 | * Depends on auth config and assistant config |
| 19 | */ |
| 20 | export class ModelService |
| 21 | extends BaseService<ModelServiceState> |
| 22 | implements ServiceWithDependencies |
| 23 | { |
| 24 | private availableModels: ModelConfig[] = []; |
| 25 | private assistant: AssistantUnrolled | null = null; |
| 26 | private authConfig: AuthConfig | null = null; |
| 27 | |
| 28 | constructor() { |
| 29 | super("ModelService", { |
| 30 | llmApi: null, |
| 31 | model: null, |
| 32 | assistant: null, |
| 33 | authConfig: null, |
| 34 | }); |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * Declare dependencies on other services |
| 39 | */ |
| 40 | getDependencies(): string[] { |
| 41 | return ["auth", "config"]; |
| 42 | } |
| 43 | |
| 44 | /** |
| 45 | * Initialize the model service |
| 46 | */ |
| 47 | async doInitialize( |
| 48 | assistant: AssistantUnrolled, |
| 49 | authConfig: AuthConfig, |
| 50 | ): Promise<ModelServiceState> { |
| 51 | logger.debug("ModelService.doInitialize called", { |
| 52 | hasAssistant: !!assistant, |
| 53 | hasAuthConfig: !!authConfig, |
| 54 | assistantModelsCount: assistant?.models?.length || 0, |
| 55 | }); |
| 56 | |
| 57 | this.assistant = assistant; |
| 58 | this.authConfig = authConfig; |
| 59 | this.availableModels = (assistant.models?.filter( |
| 60 | (model) => |
| 61 | model && (model.roles?.includes("chat") || model.roles === undefined), |
| 62 | ) || []) as ModelConfig[]; |
| 63 | |
| 64 | // Check if we have a persisted model name and use it if valid |
| 65 | const persistedModelName = getModelName(authConfig); |
| 66 | if (persistedModelName) { |
| 67 | // During initialization, we need to check against availableModels directly |
| 68 | const modelIndex = this.availableModels.findIndex((model) => { |
| 69 | const name = (model as any).name || (model as any).model; |
| 70 | return name === persistedModelName; |
| 71 | }); |
| 72 | if (modelIndex === -1) { |
| 73 | // Model name not found, use default model selection |
| 74 | const [llmApi, model] = getLlmApi(assistant, authConfig); |
| 75 | return { |
| 76 | llmApi, |
| 77 | model, |
| 78 | assistant, |
| 79 | authConfig, |
| 80 | }; |
| 81 | } else { |
| 82 | // Use the persisted model - but we need to handle initialization specially |
| 83 | // During init, currentState isn't set yet, so switchModel would fail |
| 84 | // Instead, we'll manually switch here |
| 85 | const selectedModel = this.availableModels[modelIndex]; |
| 86 | logger.debug("Using persisted model during initialization", { |
| 87 | modelIndex, |
| 88 | provider: selectedModel.provider, |
| 89 | name: (selectedModel as any).name || "unnamed", |
| 90 | }); |
| 91 | |
| 92 | const accessToken = getAccessToken(authConfig); |
| 93 | const organizationId = getOrganizationId(authConfig); |
| 94 | |
| 95 | const config: LLMConfig = |
| 96 | selectedModel.provider === "continue-proxy" |
| 97 | ? { |
| 98 | provider: selectedModel.provider, |
| 99 | requestOptions: selectedModel.requestOptions, |
| 100 | apiBase: selectedModel.apiBase, |
| 101 | apiKey: accessToken ?? undefined, |
| 102 | env: { |
| 103 | apiKeyLocation: (selectedModel as any).apiKeyLocation, |
| 104 | orgScopeId: organizationId, |
| 105 | proxyUrl: (selectedModel as any).onPremProxyUrl ?? undefined, |
| 106 | }, |
| 107 | } |
| 108 | : { |
| 109 | provider: selectedModel.provider as any, |
| 110 | apiKey: selectedModel.apiKey, |
| 111 | apiBase: selectedModel.apiBase, |
| 112 | requestOptions: selectedModel.requestOptions, |
| 113 | env: selectedModel.env, |
| 114 | }; |
| 115 | |
| 116 | const llmApi = constructLlmApi(config); |
| 117 | |
| 118 | if (!llmApi) { |
| 119 | throw new Error("Failed to initialize LLM with persisted model"); |
| 120 | } |
| 121 | |
| 122 | return { |
| 123 | llmApi, |
| 124 | model: selectedModel, |
| 125 | assistant, |
| 126 | authConfig, |
| 127 | }; |
| 128 | } |
| 129 | } else { |
| 130 | // Use default model selection |
| 131 | const [llmApi, model] = getLlmApi(assistant, authConfig); |
| 132 | return { |
| 133 | llmApi, |
| 134 | model, |
| 135 | assistant, |
| 136 | authConfig, |
| 137 | }; |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | /** |
| 142 | * Update the model based on new config or auth changes |
| 143 | */ |
| 144 | async update( |
| 145 | assistant: AssistantUnrolled, |
| 146 | authConfig: AuthConfig, |
| 147 | ): Promise<ModelServiceState> { |
| 148 | logger.debug("Updating ModelService"); |
| 149 | |
| 150 | try { |
| 151 | // Update instance properties for backward compatibility |
| 152 | this.assistant = assistant; |
| 153 | this.authConfig = authConfig; |
| 154 | this.availableModels = (assistant.models?.filter( |
| 155 | (model) => |
| 156 | model && (model.roles?.includes("chat") || model.roles === undefined), |
| 157 | ) || []) as ModelConfig[]; |
| 158 | |
| 159 | const [llmApi, model] = getLlmApi(assistant, authConfig); |
| 160 | |
| 161 | // Ensure state has all necessary data |
| 162 | this.setState({ |
| 163 | llmApi, |
| 164 | model, |
| 165 | assistant, |
| 166 | authConfig, |
| 167 | }); |
| 168 | |
| 169 | logger.debug("ModelService updated successfully", { |
| 170 | modelProvider: model.provider, |
| 171 | modelName: (model as any).name || "unnamed", |
| 172 | availableModels: this.availableModels.length, |
| 173 | }); |
| 174 | |
| 175 | return this.getState(); |
| 176 | } catch (error: any) { |
| 177 | logger.error("Failed to update ModelService:", error); |
| 178 | this.emit("error", error); |
| 179 | throw error; |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | /** |
| 184 | * Override isReady to check for required state |
| 185 | */ |
| 186 | override isReady(): boolean { |
| 187 | return ( |
| 188 | super.isReady() && |
| 189 | this.currentState.llmApi !== null && |
| 190 | this.currentState.model !== null |
| 191 | ); |
| 192 | } |
| 193 | |
| 194 | /** |
| 195 | * Get model information for display |
| 196 | */ |
| 197 | getModelInfo(): { provider: string; name: string } | null { |
| 198 | if (!this.currentState.model) { |
| 199 | return null; |
| 200 | } |
| 201 | |
| 202 | return { |
| 203 | provider: this.currentState.model.provider, |
| 204 | name: (this.currentState.model as any).name || "unnamed", |
| 205 | }; |
| 206 | } |
| 207 | |
| 208 | /** |
| 209 | * Get list of available chat models |
| 210 | */ |
| 211 | getAvailableChatModels(): Array<{ |
| 212 | provider: string; |
| 213 | name: string; |
| 214 | index: number; |
| 215 | }> { |
| 216 | // Get assistant from state to ensure we have the latest data |
| 217 | const { assistant } = this.getState(); |
| 218 | if (!assistant || !assistant.models) { |
| 219 | return []; |
| 220 | } |
| 221 | |
| 222 | // Filter for chat models |
| 223 | const chatModels = (assistant.models.filter( |
| 224 | (model) => |
| 225 | model && (model.roles?.includes("chat") || model.roles === undefined), |
| 226 | ) || []) as ModelConfig[]; |
| 227 | |
| 228 | return chatModels.map((model, index) => ({ |
| 229 | provider: model.provider, |
| 230 | name: (model as any).name || (model as any).model || "unnamed", |
| 231 | index, |
| 232 | })); |
| 233 | } |
| 234 | |
| 235 | /** |
| 236 | * Switch to a different chat model by index |
| 237 | */ |
| 238 | async switchModel(modelIndex: number): Promise<ModelServiceState> { |
| 239 | // Get assistant and authConfig from state, but fall back to instance properties |
| 240 | // This is needed during initialization when state isn't set yet |
| 241 | const stateValues = this.getState(); |
| 242 | const assistant = stateValues.assistant || this.assistant; |
| 243 | const authConfig = stateValues.authConfig || this.authConfig; |
| 244 | |
| 245 | // Debug logging to understand the state |
| 246 | logger.debug("switchModel: Checking state", { |
| 247 | hasStateAssistant: !!stateValues.assistant, |
| 248 | hasStateAuthConfig: !!stateValues.authConfig, |
| 249 | hasInstanceAssistant: !!this.assistant, |
| 250 | hasInstanceAuthConfig: !!this.authConfig, |
| 251 | isInitialized: this.isReady(), |
| 252 | isReady: this.isReady(), |
| 253 | modelIndex, |
| 254 | }); |
| 255 | |
| 256 | if (!assistant) { |
| 257 | logger.error("switchModel: Missing assistant data", { |
| 258 | assistant: !!assistant, |
| 259 | authConfig: !!authConfig, |
| 260 | stateKeys: Object.keys(stateValues), |
| 261 | currentState: { |
| 262 | hasLlmApi: !!stateValues.llmApi, |
| 263 | hasModel: !!stateValues.model, |
| 264 | hasAssistant: !!stateValues.assistant, |
| 265 | hasAuthConfig: !!stateValues.authConfig, |
| 266 | }, |
| 267 | }); |
| 268 | throw new Error("ModelService not initialized - assistant data missing"); |
| 269 | } |
| 270 | |
| 271 | // Get available models from assistant in state |
| 272 | const availableModels = (assistant.models?.filter( |
| 273 | (model) => |
| 274 | model && (model.roles?.includes("chat") || model.roles === undefined), |
| 275 | ) || []) as ModelConfig[]; |
| 276 | |
| 277 | if (modelIndex < 0 || modelIndex >= availableModels.length) { |
| 278 | throw new Error( |
| 279 | `Invalid model index: ${modelIndex}. Available models: 0-${availableModels.length - 1}`, |
| 280 | ); |
| 281 | } |
| 282 | |
| 283 | const selectedModel = availableModels[modelIndex]; |
| 284 | logger.debug("Switching to model", { |
| 285 | modelIndex, |
| 286 | provider: selectedModel.provider, |
| 287 | name: (selectedModel as any).name || "unnamed", |
| 288 | }); |
| 289 | |
| 290 | try { |
| 291 | const accessToken = getAccessToken(authConfig); |
| 292 | const organizationId = getOrganizationId(authConfig); |
| 293 | |
| 294 | const config: LLMConfig = |
| 295 | selectedModel.provider === "continue-proxy" |
| 296 | ? { |
| 297 | provider: selectedModel.provider, |
| 298 | requestOptions: selectedModel.requestOptions, |
| 299 | apiBase: selectedModel.apiBase, |
| 300 | apiKey: accessToken ?? undefined, |
| 301 | env: { |
| 302 | apiKeyLocation: (selectedModel as any).apiKeyLocation, |
| 303 | orgScopeId: organizationId, |
| 304 | proxyUrl: (selectedModel as any).onPremProxyUrl ?? undefined, |
| 305 | }, |
| 306 | } |
| 307 | : { |
| 308 | provider: selectedModel.provider as any, |
| 309 | apiKey: selectedModel.apiKey, |
| 310 | apiBase: selectedModel.apiBase, |
| 311 | requestOptions: selectedModel.requestOptions, |
| 312 | env: selectedModel.env, |
| 313 | }; |
| 314 | |
| 315 | const llmApi = constructLlmApi(config); |
| 316 | |
| 317 | if (!llmApi) { |
| 318 | throw new Error("Failed to initialize LLM with selected model"); |
| 319 | } |
| 320 | |
| 321 | this.setState({ |
| 322 | llmApi, |
| 323 | model: selectedModel, |
| 324 | assistant, |
| 325 | authConfig, |
| 326 | }); |
| 327 | |
| 328 | logger.debug("Model switched successfully", { |
| 329 | modelProvider: selectedModel.provider, |
| 330 | modelName: (selectedModel as any).name || "unnamed", |
| 331 | }); |
| 332 | |
| 333 | return this.getState(); |
| 334 | } catch (error: any) { |
| 335 | logger.error("Failed to switch model:", error); |
| 336 | this.emit("error", error); |
| 337 | throw error; |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | /** |
| 342 | * Get current model index |
| 343 | */ |
| 344 | getCurrentModelIndex(): number { |
| 345 | const state = this.getState(); |
| 346 | if (!state.model || !state.assistant) { |
| 347 | return -1; |
| 348 | } |
| 349 | |
| 350 | // Get available models from state |
| 351 | const availableModels = (state.assistant.models?.filter( |
| 352 | (model) => |
| 353 | model && (model.roles?.includes("chat") || model.roles === undefined), |
| 354 | ) || []) as ModelConfig[]; |
| 355 | |
| 356 | return availableModels.findIndex( |
| 357 | (model) => |
| 358 | model.provider === state.model?.provider && |
| 359 | (model as any).name === (state.model as any).name, |
| 360 | ); |
| 361 | } |
| 362 | |
| 363 | /** |
| 364 | * Get model index by name and provider |
| 365 | */ |
| 366 | getModelIndexByName(modelName: string, provider?: string): number { |
| 367 | const state = this.getState(); |
| 368 | if (!state.assistant) { |
| 369 | return -1; |
| 370 | } |
| 371 | |
| 372 | // Get available models from state |
| 373 | const availableModels = (state.assistant.models?.filter( |
| 374 | (model) => |
| 375 | model && (model.roles?.includes("chat") || model.roles === undefined), |
| 376 | ) || []) as ModelConfig[]; |
| 377 | |
| 378 | return availableModels.findIndex((model) => { |
| 379 | const name = (model as any).name || (model as any).model; |
| 380 | const nameMatches = name === modelName; |
| 381 | |
| 382 | if (provider) { |
| 383 | return nameMatches && model.provider === provider; |
| 384 | } |
| 385 | |
| 386 | return nameMatches; |
| 387 | }); |
| 388 | } |
| 389 | } |