* Switch to a different chat model by index
(modelIndex: number)
| 179 | * Switch to a different chat model by index |
| 180 | */ |
| 181 | async switchModel(modelIndex: number): Promise<ModelServiceState> { |
| 182 | // Get assistant and authConfig from state, but fall back to instance properties |
| 183 | // This is needed during initialization when state isn't set yet |
| 184 | const stateValues = this.getState(); |
| 185 | const assistant = stateValues.assistant || this.assistant; |
| 186 | const authConfig = stateValues.authConfig || this.authConfig; |
| 187 | |
| 188 | // Debug logging to understand the state |
| 189 | logger.debug("switchModel: Checking state", { |
| 190 | hasStateAssistant: !!stateValues.assistant, |
| 191 | hasStateAuthConfig: !!stateValues.authConfig, |
| 192 | hasInstanceAssistant: !!this.assistant, |
| 193 | hasInstanceAuthConfig: !!this.authConfig, |
| 194 | isInitialized: this.isReady(), |
| 195 | isReady: this.isReady(), |
| 196 | modelIndex, |
| 197 | }); |
| 198 | |
| 199 | if (!assistant) { |
| 200 | logger.error("switchModel: Missing assistant data", { |
| 201 | assistant: !!assistant, |
| 202 | authConfig: !!authConfig, |
| 203 | stateKeys: Object.keys(stateValues), |
| 204 | currentState: { |
| 205 | hasLlmApi: !!stateValues.llmApi, |
| 206 | hasModel: !!stateValues.model, |
| 207 | hasAssistant: !!stateValues.assistant, |
| 208 | hasAuthConfig: !!stateValues.authConfig, |
| 209 | }, |
| 210 | }); |
| 211 | throw new Error("ModelService not initialized - assistant data missing"); |
| 212 | } |
| 213 | |
| 214 | // Get available models from assistant in state |
| 215 | const availableModels = (assistant.models?.filter( |
| 216 | (model) => |
| 217 | model && (model.roles?.includes("chat") || model.roles === undefined), |
| 218 | ) || []) as ModelConfig[]; |
| 219 | |
| 220 | if (modelIndex < 0 || modelIndex >= availableModels.length) { |
| 221 | throw new Error( |
| 222 | `Invalid model index: ${modelIndex}. Available models: 0-${availableModels.length - 1}`, |
| 223 | ); |
| 224 | } |
| 225 | |
| 226 | const selectedModel = availableModels[modelIndex]; |
| 227 | logger.debug("Switching to model", { |
| 228 | modelIndex, |
| 229 | provider: selectedModel.provider, |
| 230 | name: (selectedModel as any).name || "unnamed", |
| 231 | }); |
| 232 | |
| 233 | try { |
| 234 | const llmApi = createLlmApi(selectedModel, authConfig); |
| 235 | |
| 236 | if (!llmApi) { |
| 237 | throw new Error("Failed to initialize LLM with selected model"); |
| 238 | } |
no test coverage detected