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