| 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 | }); |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * Declare dependencies on other services |
| 37 | */ |
| 38 | getDependencies(): string[] { |
| 39 | return ["auth", "config"]; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Initialize the model service |
| 44 | */ |
| 45 | async doInitialize( |
| 46 | assistant: AssistantUnrolled, |
| 47 | authConfig: AuthConfig, |
| 48 | ): Promise<ModelServiceState> { |
| 49 | this.assistant = assistant; |
| 50 | this.authConfig = authConfig; |
| 51 | this.availableModels = (assistant.models?.filter( |
| 52 | (model) => |
| 53 | model && (model.roles?.includes("chat") || model.roles === undefined), |
| 54 | ) || []) as ModelConfig[]; |
| 55 | |
| 56 | // Check if we have a persisted model name and use it if valid |
| 57 | const persistedModelName = getModelName(authConfig); |
| 58 | if (persistedModelName) { |
| 59 | const modelIndex = this.getModelIndexByName(persistedModelName); |
| 60 | if (modelIndex === -1) { |
| 61 | // Model name not found, use default model selection |
| 62 | const [llmApi, model] = getLlmApi(assistant, authConfig); |
| 63 | return { |
| 64 | llmApi, |
| 65 | model, |
| 66 | }; |
| 67 | } else { |
| 68 | // Use the persisted model |
| 69 | const state = await this.switchModel(modelIndex); |
| 70 | return state; |
| 71 | } |
| 72 | } else { |
| 73 | // Use default model selection |
| 74 | const [llmApi, model] = getLlmApi(assistant, authConfig); |
| 75 | return { |
| 76 | llmApi, |
| 77 | model, |
| 78 | }; |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * Update the model based on new config or auth changes |
| 84 | */ |
| 85 | async update( |
| 86 | assistant: AssistantUnrolled, |
| 87 | authConfig: AuthConfig, |
| 88 | ): Promise<ModelServiceState> { |
| 89 | logger.debug("Updating ModelService"); |
| 90 | |
| 91 | try { |
| 92 | this.assistant = assistant; |
| 93 | this.authConfig = authConfig; |
| 94 | this.availableModels = (assistant.models?.filter( |
| 95 | (model) => |
| 96 | model && (model.roles?.includes("chat") || model.roles === undefined), |
| 97 | ) || []) as ModelConfig[]; |
| 98 | |
| 99 | const [llmApi, model] = getLlmApi(assistant, authConfig); |
| 100 | |
| 101 | this.setState({ |
| 102 | llmApi, |
| 103 | model, |
| 104 | }); |
| 105 | |
| 106 | logger.debug("ModelService updated successfully", { |
| 107 | modelProvider: model.provider, |
| 108 | modelName: (model as any).name || "unnamed", |
| 109 | availableModels: this.availableModels.length, |
| 110 | }); |
| 111 | |
| 112 | return this.getState(); |
| 113 | } catch (error: any) { |
| 114 | logger.error("Failed to update ModelService:", error); |
| 115 | this.emit("error", error); |
| 116 | throw error; |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | /** |
| 121 | * Override isReady to check for required state |
| 122 | */ |
| 123 | override isReady(): boolean { |
| 124 | return ( |
| 125 | super.isReady() && |
| 126 | this.currentState.llmApi !== null && |
| 127 | this.currentState.model !== null |
| 128 | ); |
| 129 | } |
| 130 | |
| 131 | /** |
| 132 | * Get model information for display |
| 133 | */ |
| 134 | getModelInfo(): { provider: string; name: string } | null { |
| 135 | if (!this.currentState.model) { |
| 136 | return null; |
| 137 | } |
| 138 | |
| 139 | return { |
| 140 | provider: this.currentState.model.provider, |
| 141 | name: (this.currentState.model as any).name || "unnamed", |
| 142 | }; |
| 143 | } |
| 144 | |
| 145 | /** |
| 146 | * Get list of available chat models |
| 147 | */ |
| 148 | getAvailableChatModels(): Array<{ |
| 149 | provider: string; |
| 150 | name: string; |
| 151 | index: number; |
| 152 | }> { |
| 153 | return this.availableModels.map((model, index) => ({ |
| 154 | provider: model.provider, |
| 155 | name: (model as any).name || (model as any).model || "unnamed", |
| 156 | index, |
| 157 | })); |
| 158 | } |
| 159 | |
| 160 | /** |
| 161 | * Switch to a different chat model by index |
| 162 | */ |
| 163 | async switchModel(modelIndex: number): Promise<ModelServiceState> { |
| 164 | if (!this.assistant || !this.authConfig) { |
| 165 | throw new Error("ModelService not initialized"); |
| 166 | } |
| 167 | |
| 168 | if (modelIndex < 0 || modelIndex >= this.availableModels.length) { |
| 169 | throw new Error( |
| 170 | `Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`, |
| 171 | ); |
| 172 | } |
| 173 | |
| 174 | const selectedModel = this.availableModels[modelIndex]; |
| 175 | logger.debug("Switching to model", { |
| 176 | modelIndex, |
| 177 | provider: selectedModel.provider, |
| 178 | name: (selectedModel as any).name || "unnamed", |
| 179 | }); |
| 180 | |
| 181 | try { |
| 182 | const accessToken = getAccessToken(this.authConfig); |
| 183 | const organizationId = getOrganizationId(this.authConfig); |
| 184 | |
| 185 | const config: LLMConfig = |
| 186 | selectedModel.provider === "continue-proxy" |
| 187 | ? { |
| 188 | provider: selectedModel.provider, |
| 189 | requestOptions: selectedModel.requestOptions, |
| 190 | apiBase: selectedModel.apiBase, |
| 191 | apiKey: accessToken ?? undefined, |
| 192 | env: { |
| 193 | apiKeyLocation: (selectedModel as any).apiKeyLocation, |
| 194 | orgScopeId: organizationId, |
| 195 | proxyUrl: undefined, |
| 196 | }, |
| 197 | } |
| 198 | : { |
| 199 | provider: selectedModel.provider as any, |
| 200 | apiKey: selectedModel.apiKey, |
| 201 | apiBase: selectedModel.apiBase, |
| 202 | requestOptions: selectedModel.requestOptions, |
| 203 | env: selectedModel.env, |
| 204 | }; |
| 205 | |
| 206 | const llmApi = constructLlmApi(config); |
| 207 | |
| 208 | if (!llmApi) { |
| 209 | throw new Error("Failed to initialize LLM with selected model"); |
| 210 | } |
| 211 | |
| 212 | this.setState({ |
| 213 | llmApi, |
| 214 | model: selectedModel, |
| 215 | }); |
| 216 | |
| 217 | logger.debug("Model switched successfully", { |
| 218 | modelProvider: selectedModel.provider, |
| 219 | modelName: (selectedModel as any).name || "unnamed", |
| 220 | }); |
| 221 | |
| 222 | return this.getState(); |
| 223 | } catch (error: any) { |
| 224 | logger.error("Failed to switch model:", error); |
| 225 | this.emit("error", error); |
| 226 | throw error; |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | /** |
| 231 | * Get current model index |
| 232 | */ |
| 233 | getCurrentModelIndex(): number { |
| 234 | if (!this.currentState.model) { |
| 235 | return -1; |
| 236 | } |
| 237 | |
| 238 | return this.availableModels.findIndex( |
| 239 | (model) => |
| 240 | model.provider === this.currentState.model?.provider && |
| 241 | (model as any).name === (this.currentState.model as any).name, |
| 242 | ); |
| 243 | } |
| 244 | |
| 245 | /** |
| 246 | * Get model index by name and provider |
| 247 | */ |
| 248 | getModelIndexByName(modelName: string, provider?: string): number { |
| 249 | return this.availableModels.findIndex((model) => { |
| 250 | const name = (model as any).name || (model as any).model; |
| 251 | const nameMatches = name === modelName; |
| 252 | |
| 253 | if (provider) { |
| 254 | return nameMatches && model.provider === provider; |
| 255 | } |
| 256 | |
| 257 | return nameMatches; |
| 258 | }); |
| 259 | } |
| 260 | } |