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