| 1 | import { ModelRole } from "@continuedev/config-yaml"; |
| 2 | import { fetchwithRequestOptions } from "@continuedev/fetch"; |
| 3 | import { findLlmInfo } from "@continuedev/llm-info"; |
| 4 | import { |
| 5 | BaseLlmApi, |
| 6 | ChatCompletionCreateParams, |
| 7 | constructLlmApi, |
| 8 | } from "@continuedev/openai-adapters"; |
| 9 | import Handlebars from "handlebars"; |
| 10 | |
| 11 | import { DevDataSqliteDb } from "../data/devdataSqlite.js"; |
| 12 | import { DataLogger } from "../data/log.js"; |
| 13 | import { |
| 14 | CacheBehavior, |
| 15 | ChatMessage, |
| 16 | Chunk, |
| 17 | CompletionOptions, |
| 18 | ILLM, |
| 19 | ILLMInteractionLog, |
| 20 | ILLMLogger, |
| 21 | LLMFullCompletionOptions, |
| 22 | LLMOptions, |
| 23 | MessageOption, |
| 24 | ModelCapability, |
| 25 | ModelInstaller, |
| 26 | PromptLog, |
| 27 | PromptTemplate, |
| 28 | RequestOptions, |
| 29 | TabAutocompleteOptions, |
| 30 | TemplateType, |
| 31 | Usage, |
| 32 | } from "../index.js"; |
| 33 | import { isLemonadeInstalled } from "../util/lemonadeHelper.js"; |
| 34 | import { Logger } from "../util/Logger.js"; |
| 35 | import mergeJson from "../util/merge.js"; |
| 36 | import { renderChatMessage } from "../util/messageContent.js"; |
| 37 | import { isOllamaInstalled } from "../util/ollamaHelper.js"; |
| 38 | import { TokensBatchingService } from "../util/TokensBatchingService.js"; |
| 39 | import { withExponentialBackoff } from "../util/withExponentialBackoff.js"; |
| 40 | |
| 41 | import { |
| 42 | autodetectPromptTemplates, |
| 43 | autodetectTemplateFunction, |
| 44 | autodetectTemplateType, |
| 45 | modelSupportsImages, |
| 46 | } from "./autodetect.js"; |
| 47 | import { |
| 48 | DEFAULT_ARGS, |
| 49 | DEFAULT_CONTEXT_LENGTH, |
| 50 | DEFAULT_MAX_BATCH_SIZE, |
| 51 | DEFAULT_MAX_CHUNK_SIZE, |
| 52 | DEFAULT_MAX_TOKENS, |
| 53 | LLMConfigurationStatuses, |
| 54 | } from "./constants.js"; |
| 55 | import { |
| 56 | compileChatMessages, |
| 57 | countTokens, |
| 58 | pruneRawPromptFromTop, |
| 59 | } from "./countTokens.js"; |
| 60 | import { |
| 61 | fromChatCompletionChunk, |
| 62 | fromChatResponse, |
| 63 | LlmApiRequestType, |
| 64 | toChatBody, |
| 65 | toCompleteBody, |
| 66 | toFimBody, |
| 67 | } from "./openaiTypeConverters.js"; |
| 68 | export class LLMError extends Error { |
| 69 | constructor( |
| 70 | message: string, |
| 71 | public llm: ILLM, |
| 72 | ) { |
| 73 | super(message); |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | export function isModelInstaller(provider: any): provider is ModelInstaller { |
| 78 | return ( |
| 79 | provider && |
| 80 | typeof provider.installModel === "function" && |
| 81 | typeof provider.isInstallingModel === "function" |
| 82 | ); |
| 83 | } |
| 84 | |
| 85 | type InteractionStatus = "in_progress" | "success" | "error" | "cancelled"; |
| 86 | |
| 87 | export abstract class BaseLLM implements ILLM { |
| 88 | static providerName: string; |
| 89 | static defaultOptions: Partial<LLMOptions> | undefined = undefined; |
| 90 | |
| 91 | get providerName(): string { |
| 92 | return (this.constructor as typeof BaseLLM).providerName; |
| 93 | } |
| 94 | |
| 95 | /** |
| 96 | * This exists because for the continue-proxy, sometimes we want to get the value of the underlying provider that is used on the server |
| 97 | * For example, the underlying provider should always be sent with dev data |
| 98 | */ |
| 99 | get underlyingProviderName(): string { |
| 100 | return this.providerName; |
| 101 | } |
| 102 | |
| 103 | autocompleteOptions?: Partial<TabAutocompleteOptions>; |
| 104 | |
| 105 | supportsFim(): boolean { |
| 106 | return false; |
| 107 | } |
| 108 | |
| 109 | supportsImages(): boolean { |
| 110 | return modelSupportsImages( |
| 111 | this.providerName, |
| 112 | this.model, |
| 113 | this.title, |
| 114 | this.capabilities, |
| 115 | ); |
| 116 | } |
| 117 | |
| 118 | supportsCompletions(): boolean { |
| 119 | if (["openai", "azure"].includes(this.providerName)) { |
| 120 | if ( |
| 121 | this.apiBase?.includes("api.groq.com") || |
| 122 | this.apiBase?.includes("api.mistral.ai") || |
| 123 | this.apiBase?.includes(":1337") || |
| 124 | this.apiBase?.includes("integrate.api.nvidia.com") || |
| 125 | this._llmOptions.useLegacyCompletionsEndpoint?.valueOf() === false |
| 126 | ) { |
| 127 | // Jan + Groq + Mistral don't support completions : ( |
| 128 | // Seems to be going out of style... |
| 129 | return false; |
| 130 | } |
| 131 | } |
| 132 | if (["groq", "mistral", "deepseek"].includes(this.providerName)) { |
| 133 | return false; |
| 134 | } |
| 135 | return true; |
| 136 | } |
| 137 | |
| 138 | supportsPrefill(): boolean { |
| 139 | return ["ollama", "anthropic", "mistral"].includes(this.providerName); |
| 140 | } |
| 141 | |
| 142 | uniqueId: string; |
| 143 | model: string; |
| 144 | |
| 145 | title?: string; |
| 146 | baseChatSystemMessage?: string; |
| 147 | basePlanSystemMessage?: string; |
| 148 | baseAgentSystemMessage?: string; |
| 149 | _contextLength: number | undefined; |
| 150 | maxStopWords?: number | undefined; |
| 151 | completionOptions: CompletionOptions; |
| 152 | requestOptions?: RequestOptions; |
| 153 | template?: TemplateType; |
| 154 | promptTemplates?: Record<string, PromptTemplate>; |
| 155 | templateMessages?: (messages: ChatMessage[]) => string; |
| 156 | logger?: ILLMLogger; |
| 157 | llmRequestHook?: (model: string, prompt: string) => any; |
| 158 | apiKey?: string; |
| 159 | |
| 160 | // continueProperties |
| 161 | apiKeyLocation?: string; |
| 162 | envSecretLocations?: Record<string, string>; |
| 163 | apiBase?: string; |
| 164 | orgScopeId?: string | null; |
| 165 | |
| 166 | onPremProxyUrl?: string | null; |
| 167 | |
| 168 | cacheBehavior?: CacheBehavior; |
| 169 | capabilities?: ModelCapability; |
| 170 | roles?: ModelRole[]; |
| 171 | |
| 172 | deployment?: string; |
| 173 | apiVersion?: string; |
| 174 | apiType?: string; |
| 175 | region?: string; |
| 176 | projectId?: string; |
| 177 | accountId?: string; |
| 178 | aiGatewaySlug?: string; |
| 179 | profile?: string | undefined; |
| 180 | accessKeyId?: string; |
| 181 | secretAccessKey?: string; |
| 182 | |
| 183 | // For IBM watsonx |
| 184 | deploymentId?: string; |
| 185 | |
| 186 | // Embedding options |
| 187 | embeddingId: string; |
| 188 | maxEmbeddingChunkSize: number; |
| 189 | maxEmbeddingBatchSize: number; |
| 190 | |
| 191 | //URI to local block defining this LLM |
| 192 | sourceFile?: string; |
| 193 | |
| 194 | isFromAutoDetect?: boolean; |
| 195 | |
| 196 | private _llmOptions: LLMOptions; |
| 197 | |
| 198 | protected openaiAdapter?: BaseLlmApi; |
| 199 | |
| 200 | constructor(_options: LLMOptions) { |
| 201 | this._llmOptions = _options; |
| 202 | |
| 203 | // Set default options |
| 204 | const options = { |
| 205 | title: (this.constructor as typeof BaseLLM).providerName, |
| 206 | ...(this.constructor as typeof BaseLLM).defaultOptions, |
| 207 | ..._options, |
| 208 | }; |
| 209 | |
| 210 | this.model = options.model; |
| 211 | // Use @continuedev/llm-info package to autodetect certain parameters |
| 212 | const modelSearchString = |
| 213 | this.providerName === "continue-proxy" |
| 214 | ? this.model?.split("/").pop() || this.model |
| 215 | : this.model; |
| 216 | const llmInfo = findLlmInfo(modelSearchString, this.underlyingProviderName); |
| 217 | |
| 218 | const templateType = |
| 219 | options.template ?? autodetectTemplateType(options.model); |
| 220 | |
| 221 | this.title = options.title; |
| 222 | this.uniqueId = options.uniqueId ?? "None"; |
| 223 | this.baseAgentSystemMessage = options.baseAgentSystemMessage; |
| 224 | this.basePlanSystemMessage = options.basePlanSystemMessage; |
| 225 | this.baseChatSystemMessage = options.baseChatSystemMessage; |
| 226 | this._contextLength = options.contextLength ?? llmInfo?.contextLength; |
| 227 | this.maxStopWords = options.maxStopWords ?? this.maxStopWords; |
| 228 | this.completionOptions = { |
| 229 | ...options.completionOptions, |
| 230 | model: options.model || "gpt-4", |
| 231 | maxTokens: |
| 232 | options.completionOptions?.maxTokens ?? |
| 233 | (llmInfo?.maxCompletionTokens |
| 234 | ? Math.min( |
| 235 | llmInfo.maxCompletionTokens, |
| 236 | // Even if the model has a large maxTokens, we don't want to use that every time, |
| 237 | // because it takes away from the context length |
| 238 | this.contextLength / 4, |
| 239 | ) |
| 240 | : DEFAULT_MAX_TOKENS), |
| 241 | }; |
| 242 | this.requestOptions = options.requestOptions; |
| 243 | this.promptTemplates = { |
| 244 | ...autodetectPromptTemplates(options.model, templateType), |
| 245 | ...options.promptTemplates, |
| 246 | }; |
| 247 | this.templateMessages = |
| 248 | options.templateMessages ?? |
| 249 | autodetectTemplateFunction( |
| 250 | options.model, |
| 251 | this.providerName, |
| 252 | options.template, |
| 253 | ) ?? |
| 254 | undefined; |
| 255 | this.logger = options.logger; |
| 256 | this.llmRequestHook = options.llmRequestHook; |
| 257 | this.apiKey = options.apiKey; |
| 258 | |
| 259 | // continueProperties |
| 260 | this.apiKeyLocation = options.apiKeyLocation; |
| 261 | this.envSecretLocations = options.envSecretLocations; |
| 262 | this.orgScopeId = options.orgScopeId; |
| 263 | this.apiBase = options.apiBase; |
| 264 | |
| 265 | this.onPremProxyUrl = options.onPremProxyUrl; |
| 266 | |
| 267 | this.aiGatewaySlug = options.aiGatewaySlug; |
| 268 | this.cacheBehavior = options.cacheBehavior; |
| 269 | |
| 270 | // watsonx deploymentId |
| 271 | this.deploymentId = options.deploymentId; |
| 272 | |
| 273 | if (this.apiBase && !this.apiBase.endsWith("/")) { |
| 274 | this.apiBase = `${this.apiBase}/`; |
| 275 | } |
| 276 | this.accountId = options.accountId; |
| 277 | this.capabilities = options.capabilities; |
| 278 | this.roles = options.roles; |
| 279 | |
| 280 | this.deployment = options.deployment; |
| 281 | this.apiVersion = options.apiVersion; |
| 282 | this.apiType = options.apiType; |
| 283 | this.region = options.region; |
| 284 | this.projectId = options.projectId; |
| 285 | this.profile = options.profile; |
| 286 | this.accessKeyId = options.accessKeyId; |
| 287 | this.secretAccessKey = options.secretAccessKey; |
| 288 | |
| 289 | this.openaiAdapter = this.createOpenAiAdapter(); |
| 290 | |
| 291 | this.maxEmbeddingBatchSize = |
| 292 | options.maxEmbeddingBatchSize ?? DEFAULT_MAX_BATCH_SIZE; |
| 293 | this.maxEmbeddingChunkSize = |
| 294 | options.maxEmbeddingChunkSize ?? DEFAULT_MAX_CHUNK_SIZE; |
| 295 | this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`; |
| 296 | |
| 297 | this.autocompleteOptions = options.autocompleteOptions; |
| 298 | this.sourceFile = options.sourceFile; |
| 299 | this.isFromAutoDetect = options.isFromAutoDetect; |
| 300 | } |
| 301 | |
| 302 | get contextLength() { |
| 303 | return this._contextLength ?? DEFAULT_CONTEXT_LENGTH; |
| 304 | } |
| 305 | |
| 306 | getConfigurationStatus() { |
| 307 | return LLMConfigurationStatuses.VALID; |
| 308 | } |
| 309 | |
| 310 | protected createOpenAiAdapter() { |
| 311 | return constructLlmApi({ |
| 312 | provider: this.providerName as any, |
| 313 | apiKey: this.apiKey ?? "", |
| 314 | apiBase: this.apiBase, |
| 315 | requestOptions: this.requestOptions, |
| 316 | env: this._llmOptions.env, |
| 317 | }); |
| 318 | } |
| 319 | |
| 320 | listModels(): Promise<string[]> { |
| 321 | return Promise.resolve([]); |
| 322 | } |
| 323 | |
| 324 | private _templatePromptLikeMessages(prompt: string): string { |
| 325 | if (!this.templateMessages) { |
| 326 | return prompt; |
| 327 | } |
| 328 | |
| 329 | // NOTE system message no longer supported here |
| 330 | |
| 331 | const msgs: ChatMessage[] = [{ role: "user", content: prompt }]; |
| 332 | |
| 333 | return this.templateMessages(msgs); |
| 334 | } |
| 335 | |
| 336 | private _logEnd( |
| 337 | model: string, |
| 338 | prompt: string, |
| 339 | completion: string, |
| 340 | thinking: string | undefined, |
| 341 | interaction: ILLMInteractionLog | undefined, |
| 342 | usage: Usage | undefined, |
| 343 | error?: any, |
| 344 | ): InteractionStatus { |
| 345 | let promptTokens = this.countTokens(prompt); |
| 346 | let generatedTokens = this.countTokens(completion); |
| 347 | let thinkingTokens = thinking ? this.countTokens(thinking) : 0; |
| 348 | |
| 349 | TokensBatchingService.getInstance().addTokens( |
| 350 | model, |
| 351 | this.providerName, |
| 352 | promptTokens, |
| 353 | generatedTokens, |
| 354 | ); |
| 355 | |
| 356 | void DevDataSqliteDb.logTokensGenerated( |
| 357 | model, |
| 358 | this.providerName, |
| 359 | promptTokens, |
| 360 | generatedTokens, |
| 361 | ); |
| 362 | |
| 363 | void DataLogger.getInstance().logDevData({ |
| 364 | name: "tokensGenerated", |
| 365 | data: { |
| 366 | model: model, |
| 367 | provider: this.underlyingProviderName, |
| 368 | promptTokens: promptTokens, |
| 369 | generatedTokens: generatedTokens, |
| 370 | }, |
| 371 | }); |
| 372 | |
| 373 | if (typeof error === "undefined") { |
| 374 | interaction?.logItem({ |
| 375 | kind: "success", |
| 376 | promptTokens, |
| 377 | generatedTokens, |
| 378 | thinkingTokens, |
| 379 | usage, |
| 380 | }); |
| 381 | return "success"; |
| 382 | } else { |
| 383 | if (error === "cancel" || error?.name?.includes("AbortError")) { |
| 384 | interaction?.logItem({ |
| 385 | kind: "cancel", |
| 386 | promptTokens, |
| 387 | generatedTokens, |
| 388 | thinkingTokens, |
| 389 | usage, |
| 390 | }); |
| 391 | return "cancelled"; |
| 392 | } else { |
| 393 | console.log(error); |
| 394 | interaction?.logItem({ |
| 395 | kind: "error", |
| 396 | name: error.name, |
| 397 | message: error.message, |
| 398 | promptTokens, |
| 399 | generatedTokens, |
| 400 | thinkingTokens, |
| 401 | usage, |
| 402 | }); |
| 403 | return "error"; |
| 404 | } |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | private async parseError(resp: any): Promise<Error> { |
| 409 | let text = await resp.text(); |
| 410 | |
| 411 | if (resp.status === 404 && !resp.url.includes("/v1")) { |
| 412 | const parsedError = JSON.parse(text); |
| 413 | const errorMessageRaw = parsedError?.error ?? parsedError?.message; |
| 414 | const error = |
| 415 | typeof errorMessageRaw === "string" |
| 416 | ? errorMessageRaw.replace(/"/g, "'") |
| 417 | : undefined; |
| 418 | let model = error?.match(/model '(.*)' not found/)?.[1]; |
| 419 | if (model && resp.url.match("127.0.0.1:11434")) { |
| 420 | text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`; |
| 421 | return new LLMError(text, this); // No need to add HTTP status details |
| 422 | } else if (text.includes("/api/chat")) { |
| 423 | text = |
| 424 | "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue."; |
| 425 | } else { |
| 426 | text = |
| 427 | "This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json."; |
| 428 | } |
| 429 | } else if (resp.status === 404 && resp.url.includes("api.openai.com")) { |
| 430 | text = |
| 431 | "You may need to add pre-paid credits before using the OpenAI API."; |
| 432 | } else if ( |
| 433 | resp.status === 401 && |
| 434 | (resp.url.includes("api.mistral.ai") || |
| 435 | resp.url.includes("codestral.mistral.ai")) |
| 436 | ) { |
| 437 | if (resp.url.includes("codestral.mistral.ai")) { |
| 438 | return new Error( |
| 439 | "You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting 'apiBase' to 'https://api.mistral.ai/v1' in config.json.", |
| 440 | ); |
| 441 | } else { |
| 442 | return new Error( |
| 443 | "You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting 'apiBase' to 'https://codestral.mistral.ai/v1' in config.json.", |
| 444 | ); |
| 445 | } |
| 446 | } |
| 447 | return new Error( |
| 448 | `HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`, |
| 449 | ); |
| 450 | } |
| 451 | |
| 452 | fetch(url: RequestInfo | URL, init?: RequestInit): Promise<Response> { |
| 453 | // Custom Node.js fetch |
| 454 | const customFetch = async (input: URL | RequestInfo, init: any) => { |
| 455 | try { |
| 456 | const resp = await fetchwithRequestOptions( |
| 457 | new URL(input as any), |
| 458 | { ...init }, |
| 459 | { ...this.requestOptions }, |
| 460 | ); |
| 461 | |
| 462 | // Error mapping to be more helpful |
| 463 | if (!resp.ok) { |
| 464 | if (resp.status === 499) { |
| 465 | return resp; // client side cancellation |
| 466 | } |
| 467 | |
| 468 | const error = await this.parseError(resp); |
| 469 | throw error; |
| 470 | } |
| 471 | |
| 472 | return resp; |
| 473 | } catch (e: any) { |
| 474 | // Capture all fetch errors to Sentry for monitoring |
| 475 | Logger.error(e, { |
| 476 | context: "llm_fetch", |
| 477 | url: String(input), |
| 478 | method: init?.method || "GET", |
| 479 | model: this.model, |
| 480 | provider: this.providerName, |
| 481 | }); |
| 482 | |
| 483 | // Errors to ignore |
| 484 | if (e.message.includes("/api/tags")) { |
| 485 | throw new Error(`Error fetching tags: ${e.message}`); |
| 486 | } else if (e.message.includes("/api/show")) { |
| 487 | throw new Error( |
| 488 | `HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`, |
| 489 | ); |
| 490 | } else { |
| 491 | if (e.name !== "AbortError") { |
| 492 | // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here |
| 493 | console.debug( |
| 494 | `${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`, |
| 495 | ); |
| 496 | } |
| 497 | if ( |
| 498 | e.code === "ECONNREFUSED" && |
| 499 | e.message.includes("http://127.0.0.1:11434") |
| 500 | ) { |
| 501 | const message = (await isOllamaInstalled()) |
| 502 | ? "Unable to connect to local Ollama instance. Ollama may not be running." |
| 503 | : "Unable to connect to local Ollama instance. Ollama may not be installed or may not running."; |
| 504 | throw new Error(message); |
| 505 | } |
| 506 | if ( |
| 507 | e.code === "ECONNREFUSED" && |
| 508 | e.message.includes("http://localhost:8000") |
| 509 | ) { |
| 510 | const isInstalled = await isLemonadeInstalled(); |
| 511 | let message: string; |
| 512 | if (process.platform === "linux") { |
| 513 | // On Linux, isLemonadeInstalled checks if it's running (via health endpoint) |
| 514 | message = |
| 515 | "Unable to connect to local Lemonade instance. Please ensure Lemonade is running. Visit http://lemonade-server.ai for setup instructions."; |
| 516 | } else { |
| 517 | // On Windows, we can check if it's installed |
| 518 | message = isInstalled |
| 519 | ? "Unable to connect to local Lemonade instance. Lemonade server may not be running." |
| 520 | : "Unable to connect to local Lemonade instance. Lemonade may not be installed or may not be running."; |
| 521 | } |
| 522 | throw new Error(message); |
| 523 | } |
| 524 | } |
| 525 | throw e; |
| 526 | } |
| 527 | }; |
| 528 | return withExponentialBackoff<Response>( |
| 529 | () => customFetch(url, init) as any, |
| 530 | 5, |
| 531 | 0.5, |
| 532 | ); |
| 533 | } |
| 534 | |
| 535 | private _parseCompletionOptions(options: LLMFullCompletionOptions) { |
| 536 | const log = options.log ?? true; |
| 537 | const raw = options.raw ?? false; |
| 538 | options.log = undefined; |
| 539 | |
| 540 | const completionOptions: CompletionOptions = mergeJson( |
| 541 | this.completionOptions, |
| 542 | options, |
| 543 | ); |
| 544 | |
| 545 | return { completionOptions, logEnabled: log, raw }; |
| 546 | } |
| 547 | |
| 548 | private _formatChatMessages(messages: ChatMessage[]): string { |
| 549 | const msgsCopy = messages ? messages.map((msg) => ({ ...msg })) : []; |
| 550 | let formatted = ""; |
| 551 | for (const msg of msgsCopy) { |
| 552 | formatted += this._formatChatMessage(msg); |
| 553 | } |
| 554 | return formatted; |
| 555 | } |
| 556 | |
| 557 | private _formatChatMessage(msg: ChatMessage): string { |
| 558 | let contentToShow = renderChatMessage(msg); |
| 559 | if (msg.role === "assistant" && msg.toolCalls?.length) { |
| 560 | contentToShow += |
| 561 | "\n" + |
| 562 | msg.toolCalls |
| 563 | ?.map( |
| 564 | (toolCall) => |
| 565 | `${toolCall.function?.name}(${toolCall.function?.arguments})`, |
| 566 | ) |
| 567 | .join("\n"); |
| 568 | } |
| 569 | |
| 570 | return `<${msg.role}>\n${contentToShow}\n\n`; |
| 571 | } |
| 572 | |
| 573 | protected async *_streamFim( |
| 574 | prefix: string, |
| 575 | suffix: string, |
| 576 | signal: AbortSignal, |
| 577 | options: CompletionOptions, |
| 578 | ): AsyncGenerator<string, PromptLog> { |
| 579 | throw new Error("Not implemented"); |
| 580 | } |
| 581 | |
| 582 | protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = []; |
| 583 | |
| 584 | private shouldUseOpenAIAdapter(requestType: LlmApiRequestType) { |
| 585 | return ( |
| 586 | this.useOpenAIAdapterFor.includes(requestType) || |
| 587 | this.useOpenAIAdapterFor.includes("*") |
| 588 | ); |
| 589 | } |
| 590 | |
| 591 | async *streamFim( |
| 592 | prefix: string, |
| 593 | suffix: string, |
| 594 | signal: AbortSignal, |
| 595 | options: LLMFullCompletionOptions = {}, |
| 596 | ): AsyncGenerator<string> { |
| 597 | const { completionOptions, logEnabled } = |
| 598 | this._parseCompletionOptions(options); |
| 599 | const interaction = logEnabled |
| 600 | ? this.logger?.createInteractionLog() |
| 601 | : undefined; |
| 602 | let status: InteractionStatus = "in_progress"; |
| 603 | |
| 604 | const fimLog = `Prefix: ${prefix}\nSuffix: ${suffix}`; |
| 605 | if (logEnabled) { |
| 606 | interaction?.logItem({ |
| 607 | kind: "startFim", |
| 608 | prefix, |
| 609 | suffix, |
| 610 | options: completionOptions, |
| 611 | provider: this.providerName, |
| 612 | }); |
| 613 | if (this.llmRequestHook) { |
| 614 | this.llmRequestHook(completionOptions.model, fimLog); |
| 615 | } |
| 616 | } |
| 617 | |
| 618 | let completion = ""; |
| 619 | try { |
| 620 | if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) { |
| 621 | const stream = this.openaiAdapter.fimStream( |
| 622 | toFimBody(prefix, suffix, completionOptions), |
| 623 | signal, |
| 624 | ); |
| 625 | for await (const chunk of stream) { |
| 626 | const result = fromChatCompletionChunk(chunk); |
| 627 | if (result) { |
| 628 | const content = renderChatMessage(result); |
| 629 | const formattedContent = this._formatChatMessage(result); |
| 630 | interaction?.logItem({ |
| 631 | kind: "chunk", |
| 632 | chunk: formattedContent, |
| 633 | }); |
| 634 | |
| 635 | completion += formattedContent; |
| 636 | yield content; |
| 637 | } |
| 638 | } |
| 639 | } else { |
| 640 | for await (const chunk of this._streamFim( |
| 641 | prefix, |
| 642 | suffix, |
| 643 | signal, |
| 644 | completionOptions, |
| 645 | )) { |
| 646 | interaction?.logItem({ |
| 647 | kind: "chunk", |
| 648 | chunk, |
| 649 | }); |
| 650 | |
| 651 | completion += chunk; |
| 652 | yield chunk; |
| 653 | } |
| 654 | } |
| 655 | |
| 656 | status = this._logEnd( |
| 657 | completionOptions.model, |
| 658 | fimLog, |
| 659 | completion, |
| 660 | undefined, |
| 661 | interaction, |
| 662 | undefined, |
| 663 | ); |
| 664 | } catch (e) { |
| 665 | // Capture FIM (Fill-in-the-Middle) completion failures to Sentry |
| 666 | Logger.error(e as Error, { |
| 667 | context: "llm_stream_fim", |
| 668 | model: completionOptions.model, |
| 669 | provider: this.providerName, |
| 670 | useOpenAIAdapter: this.shouldUseOpenAIAdapter("streamFim"), |
| 671 | }); |
| 672 | |
| 673 | status = this._logEnd( |
| 674 | completionOptions.model, |
| 675 | fimLog, |
| 676 | completion, |
| 677 | undefined, |
| 678 | interaction, |
| 679 | undefined, |
| 680 | e, |
| 681 | ); |
| 682 | throw e; |
| 683 | } finally { |
| 684 | if (status === "in_progress") { |
| 685 | this._logEnd( |
| 686 | completionOptions.model, |
| 687 | fimLog, |
| 688 | completion, |
| 689 | undefined, |
| 690 | interaction, |
| 691 | undefined, |
| 692 | "cancel", |
| 693 | ); |
| 694 | } |
| 695 | } |
| 696 | |
| 697 | return { |
| 698 | prompt: fimLog, |
| 699 | completion, |
| 700 | completionOptions, |
| 701 | }; |
| 702 | } |
| 703 | |
| 704 | async *streamComplete( |
| 705 | _prompt: string, |
| 706 | signal: AbortSignal, |
| 707 | options: LLMFullCompletionOptions = {}, |
| 708 | ) { |
| 709 | const { completionOptions, logEnabled, raw } = |
| 710 | this._parseCompletionOptions(options); |
| 711 | const interaction = logEnabled |
| 712 | ? this.logger?.createInteractionLog() |
| 713 | : undefined; |
| 714 | let status: InteractionStatus = "in_progress"; |
| 715 | |
| 716 | let prompt = pruneRawPromptFromTop( |
| 717 | completionOptions.model, |
| 718 | this.contextLength, |
| 719 | _prompt, |
| 720 | completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS, |
| 721 | ); |
| 722 | |
| 723 | if (!raw) { |
| 724 | prompt = this._templatePromptLikeMessages(prompt); |
| 725 | } |
| 726 | |
| 727 | if (logEnabled) { |
| 728 | interaction?.logItem({ |
| 729 | kind: "startComplete", |
| 730 | prompt, |
| 731 | options: completionOptions, |
| 732 | provider: this.providerName, |
| 733 | }); |
| 734 | if (this.llmRequestHook) { |
| 735 | this.llmRequestHook(completionOptions.model, prompt); |
| 736 | } |
| 737 | } |
| 738 | |
| 739 | let completion = ""; |
| 740 | try { |
| 741 | if (this.shouldUseOpenAIAdapter("streamComplete") && this.openaiAdapter) { |
| 742 | if (completionOptions.stream === false) { |
| 743 | // Stream false |
| 744 | const response = await this.openaiAdapter.completionNonStream( |
| 745 | { ...toCompleteBody(prompt, completionOptions), stream: false }, |
| 746 | signal, |
| 747 | ); |
| 748 | completion = response.choices[0]?.text ?? ""; |
| 749 | yield completion; |
| 750 | } else { |
| 751 | // Stream true |
| 752 | for await (const chunk of this.openaiAdapter.completionStream( |
| 753 | { |
| 754 | ...toCompleteBody(prompt, completionOptions), |
| 755 | stream: true, |
| 756 | }, |
| 757 | signal, |
| 758 | )) { |
| 759 | const content = chunk.choices[0]?.text ?? ""; |
| 760 | completion += content; |
| 761 | interaction?.logItem({ |
| 762 | kind: "chunk", |
| 763 | chunk: content, |
| 764 | }); |
| 765 | yield content; |
| 766 | } |
| 767 | } |
| 768 | } else { |
| 769 | for await (const chunk of this._streamComplete( |
| 770 | prompt, |
| 771 | signal, |
| 772 | completionOptions, |
| 773 | )) { |
| 774 | completion += chunk; |
| 775 | interaction?.logItem({ |
| 776 | kind: "chunk", |
| 777 | chunk, |
| 778 | }); |
| 779 | yield chunk; |
| 780 | } |
| 781 | } |
| 782 | status = this._logEnd( |
| 783 | completionOptions.model, |
| 784 | prompt, |
| 785 | completion, |
| 786 | undefined, |
| 787 | interaction, |
| 788 | undefined, |
| 789 | ); |
| 790 | } catch (e) { |
| 791 | // Capture streaming completion failures to Sentry |
| 792 | Logger.error(e as Error, { |
| 793 | context: "llm_stream_complete", |
| 794 | model: completionOptions.model, |
| 795 | provider: this.providerName, |
| 796 | useOpenAIAdapter: this.shouldUseOpenAIAdapter("streamComplete"), |
| 797 | streamEnabled: completionOptions.stream !== false, |
| 798 | }); |
| 799 | |
| 800 | status = this._logEnd( |
| 801 | completionOptions.model, |
| 802 | prompt, |
| 803 | completion, |
| 804 | undefined, |
| 805 | interaction, |
| 806 | undefined, |
| 807 | e, |
| 808 | ); |
| 809 | throw e; |
| 810 | } finally { |
| 811 | if (status === "in_progress") { |
| 812 | this._logEnd( |
| 813 | completionOptions.model, |
| 814 | prompt, |
| 815 | completion, |
| 816 | undefined, |
| 817 | interaction, |
| 818 | undefined, |
| 819 | "cancel", |
| 820 | ); |
| 821 | } |
| 822 | } |
| 823 | |
| 824 | return { |
| 825 | modelTitle: this.title ?? completionOptions.model, |
| 826 | modelProvider: this.underlyingProviderName, |
| 827 | prompt, |
| 828 | completion, |
| 829 | completionOptions, |
| 830 | }; |
| 831 | } |
| 832 | |
| 833 | async complete( |
| 834 | _prompt: string, |
| 835 | signal: AbortSignal, |
| 836 | options: LLMFullCompletionOptions = {}, |
| 837 | ) { |
| 838 | const { completionOptions, logEnabled, raw } = |
| 839 | this._parseCompletionOptions(options); |
| 840 | const interaction = logEnabled |
| 841 | ? this.logger?.createInteractionLog() |
| 842 | : undefined; |
| 843 | let status: InteractionStatus = "in_progress"; |
| 844 | |
| 845 | let prompt = pruneRawPromptFromTop( |
| 846 | completionOptions.model, |
| 847 | this.contextLength, |
| 848 | _prompt, |
| 849 | completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS, |
| 850 | ); |
| 851 | |
| 852 | if (!raw) { |
| 853 | prompt = this._templatePromptLikeMessages(prompt); |
| 854 | } |
| 855 | |
| 856 | if (logEnabled) { |
| 857 | interaction?.logItem({ |
| 858 | kind: "startComplete", |
| 859 | prompt: prompt, |
| 860 | options: completionOptions, |
| 861 | provider: this.providerName, |
| 862 | }); |
| 863 | if (this.llmRequestHook) { |
| 864 | this.llmRequestHook(completionOptions.model, prompt); |
| 865 | } |
| 866 | } |
| 867 | |
| 868 | let completion: string = ""; |
| 869 | |
| 870 | try { |
| 871 | if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) { |
| 872 | const result = await this.openaiAdapter.completionNonStream( |
| 873 | { |
| 874 | ...toCompleteBody(prompt, completionOptions), |
| 875 | stream: false, |
| 876 | }, |
| 877 | signal, |
| 878 | ); |
| 879 | completion = result.choices[0].text; |
| 880 | } else { |
| 881 | completion = await this._complete(prompt, signal, completionOptions); |
| 882 | } |
| 883 | |
| 884 | interaction?.logItem({ |
| 885 | kind: "chunk", |
| 886 | chunk: completion, |
| 887 | }); |
| 888 | |
| 889 | status = this._logEnd( |
| 890 | completionOptions.model, |
| 891 | prompt, |
| 892 | completion, |
| 893 | undefined, |
| 894 | interaction, |
| 895 | undefined, |
| 896 | ); |
| 897 | } catch (e) { |
| 898 | // Capture completion failures to Sentry |
| 899 | Logger.error(e as Error, { |
| 900 | context: "llm_complete", |
| 901 | model: completionOptions.model, |
| 902 | provider: this.providerName, |
| 903 | useOpenAIAdapter: this.shouldUseOpenAIAdapter("complete"), |
| 904 | }); |
| 905 | |
| 906 | status = this._logEnd( |
| 907 | completionOptions.model, |
| 908 | prompt, |
| 909 | completion, |
| 910 | undefined, |
| 911 | interaction, |
| 912 | undefined, |
| 913 | e, |
| 914 | ); |
| 915 | throw e; |
| 916 | } finally { |
| 917 | if (status === "in_progress") { |
| 918 | this._logEnd( |
| 919 | completionOptions.model, |
| 920 | prompt, |
| 921 | completion, |
| 922 | undefined, |
| 923 | interaction, |
| 924 | undefined, |
| 925 | "cancel", |
| 926 | ); |
| 927 | } |
| 928 | } |
| 929 | |
| 930 | return completion; |
| 931 | } |
| 932 | |
| 933 | async chat( |
| 934 | messages: ChatMessage[], |
| 935 | signal: AbortSignal, |
| 936 | options: LLMFullCompletionOptions = {}, |
| 937 | ) { |
| 938 | let completion = ""; |
| 939 | for await (const message of this.streamChat(messages, signal, options)) { |
| 940 | completion += renderChatMessage(message); |
| 941 | } |
| 942 | return { role: "assistant" as const, content: completion }; |
| 943 | } |
| 944 | |
| 945 | compileChatMessages( |
| 946 | message: ChatMessage[], |
| 947 | options: LLMFullCompletionOptions, |
| 948 | ) { |
| 949 | let { completionOptions } = this._parseCompletionOptions(options); |
| 950 | completionOptions = this._modifyCompletionOptions(completionOptions); |
| 951 | |
| 952 | return compileChatMessages({ |
| 953 | modelName: completionOptions.model, |
| 954 | msgs: message, |
| 955 | knownContextLength: this._contextLength, |
| 956 | maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS, |
| 957 | supportsImages: this.supportsImages(), |
| 958 | tools: options.tools, |
| 959 | }); |
| 960 | } |
| 961 | |
| 962 | protected modifyChatBody( |
| 963 | body: ChatCompletionCreateParams, |
| 964 | ): ChatCompletionCreateParams { |
| 965 | return body; |
| 966 | } |
| 967 | |
| 968 | private _modifyCompletionOptions( |
| 969 | completionOptions: CompletionOptions, |
| 970 | ): CompletionOptions { |
| 971 | // As of 01/14/25 streaming is currently not available with o1 |
| 972 | // See these threads: |
| 973 | // - https://github.com/continuedev/continue/issues/3698 |
| 974 | // - https://community.openai.com/t/streaming-support-for-o1-o1-2024-12-17-resulting-in-400-unsupported-value/1085043 |
| 975 | if (completionOptions.model === "o1") { |
| 976 | completionOptions.stream = false; |
| 977 | } |
| 978 | |
| 979 | return completionOptions; |
| 980 | } |
| 981 | |
| 982 | async *streamChat( |
| 983 | _messages: ChatMessage[], |
| 984 | signal: AbortSignal, |
| 985 | options: LLMFullCompletionOptions = {}, |
| 986 | messageOptions?: MessageOption, |
| 987 | ): AsyncGenerator<ChatMessage, PromptLog> { |
| 988 | let { completionOptions, logEnabled } = |
| 989 | this._parseCompletionOptions(options); |
| 990 | const interaction = logEnabled |
| 991 | ? this.logger?.createInteractionLog() |
| 992 | : undefined; |
| 993 | let status: InteractionStatus = "in_progress"; |
| 994 | |
| 995 | completionOptions = this._modifyCompletionOptions(completionOptions); |
| 996 | |
| 997 | let messages = _messages; |
| 998 | |
| 999 | // If not precompiled, compile the chat messages |
| 1000 | if (!messageOptions?.precompiled) { |
| 1001 | const { compiledChatMessages } = compileChatMessages({ |
| 1002 | modelName: completionOptions.model, |
| 1003 | msgs: _messages, |
| 1004 | knownContextLength: this._contextLength, |
| 1005 | maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS, |
| 1006 | supportsImages: this.supportsImages(), |
| 1007 | tools: options.tools, |
| 1008 | }); |
| 1009 | |
| 1010 | messages = compiledChatMessages; |
| 1011 | } |
| 1012 | |
| 1013 | const prompt = this.templateMessages |
| 1014 | ? this.templateMessages(messages) |
| 1015 | : this._formatChatMessages(messages); |
| 1016 | if (logEnabled) { |
| 1017 | interaction?.logItem({ |
| 1018 | kind: "startChat", |
| 1019 | messages, |
| 1020 | options: completionOptions, |
| 1021 | provider: this.providerName, |
| 1022 | }); |
| 1023 | if (this.llmRequestHook) { |
| 1024 | this.llmRequestHook(completionOptions.model, prompt); |
| 1025 | } |
| 1026 | } |
| 1027 | |
| 1028 | let thinking = ""; |
| 1029 | let completion = ""; |
| 1030 | let usage: Usage | undefined = undefined; |
| 1031 | |
| 1032 | try { |
| 1033 | if (this.templateMessages) { |
| 1034 | for await (const chunk of this._streamComplete( |
| 1035 | prompt, |
| 1036 | signal, |
| 1037 | completionOptions, |
| 1038 | )) { |
| 1039 | completion += chunk; |
| 1040 | interaction?.logItem({ |
| 1041 | kind: "chunk", |
| 1042 | chunk: chunk, |
| 1043 | }); |
| 1044 | yield { role: "assistant", content: chunk }; |
| 1045 | } |
| 1046 | } else { |
| 1047 | if (this.shouldUseOpenAIAdapter("streamChat") && this.openaiAdapter) { |
| 1048 | let body = toChatBody(messages, completionOptions); |
| 1049 | body = this.modifyChatBody(body); |
| 1050 | |
| 1051 | if (completionOptions.stream === false) { |
| 1052 | // Stream false |
| 1053 | const response = await this.openaiAdapter.chatCompletionNonStream( |
| 1054 | { ...body, stream: false }, |
| 1055 | signal, |
| 1056 | ); |
| 1057 | const msg = fromChatResponse(response); |
| 1058 | yield msg; |
| 1059 | completion = this._formatChatMessage(msg); |
| 1060 | interaction?.logItem({ |
| 1061 | kind: "message", |
| 1062 | message: msg, |
| 1063 | }); |
| 1064 | } else { |
| 1065 | // Stream true |
| 1066 | const stream = this.openaiAdapter.chatCompletionStream( |
| 1067 | { |
| 1068 | ...body, |
| 1069 | stream: true, |
| 1070 | }, |
| 1071 | signal, |
| 1072 | ); |
| 1073 | for await (const chunk of stream) { |
| 1074 | const result = fromChatCompletionChunk(chunk); |
| 1075 | if (result) { |
| 1076 | completion += this._formatChatMessage(result); |
| 1077 | interaction?.logItem({ |
| 1078 | kind: "message", |
| 1079 | message: result, |
| 1080 | }); |
| 1081 | yield result; |
| 1082 | } |
| 1083 | } |
| 1084 | } |
| 1085 | } else { |
| 1086 | for await (const chunk of this._streamChat( |
| 1087 | messages, |
| 1088 | signal, |
| 1089 | completionOptions, |
| 1090 | )) { |
| 1091 | if (chunk.role === "assistant") { |
| 1092 | completion += this._formatChatMessage(chunk); |
| 1093 | } else if (chunk.role === "thinking") { |
| 1094 | thinking += chunk.content; |
| 1095 | } |
| 1096 | |
| 1097 | interaction?.logItem({ |
| 1098 | kind: "message", |
| 1099 | message: chunk, |
| 1100 | }); |
| 1101 | |
| 1102 | if (chunk.role === "assistant" && chunk.usage) { |
| 1103 | usage = chunk.usage; |
| 1104 | } |
| 1105 | |
| 1106 | yield chunk; |
| 1107 | } |
| 1108 | } |
| 1109 | } |
| 1110 | status = this._logEnd( |
| 1111 | completionOptions.model, |
| 1112 | prompt, |
| 1113 | completion, |
| 1114 | thinking, |
| 1115 | interaction, |
| 1116 | usage, |
| 1117 | ); |
| 1118 | } catch (e) { |
| 1119 | // Capture chat streaming failures to Sentry |
| 1120 | Logger.error(e as Error, { |
| 1121 | context: "llm_stream_chat", |
| 1122 | model: completionOptions.model, |
| 1123 | provider: this.providerName, |
| 1124 | useOpenAIAdapter: this.shouldUseOpenAIAdapter("streamChat"), |
| 1125 | streamEnabled: completionOptions.stream !== false, |
| 1126 | templateMessages: !!this.templateMessages, |
| 1127 | }); |
| 1128 | |
| 1129 | status = this._logEnd( |
| 1130 | completionOptions.model, |
| 1131 | prompt, |
| 1132 | completion, |
| 1133 | thinking, |
| 1134 | interaction, |
| 1135 | usage, |
| 1136 | e, |
| 1137 | ); |
| 1138 | throw e; |
| 1139 | } finally { |
| 1140 | if (status === "in_progress") { |
| 1141 | this._logEnd( |
| 1142 | completionOptions.model, |
| 1143 | prompt, |
| 1144 | completion, |
| 1145 | undefined, |
| 1146 | interaction, |
| 1147 | usage, |
| 1148 | "cancel", |
| 1149 | ); |
| 1150 | } |
| 1151 | } |
| 1152 | /* |
| 1153 | TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking |
| 1154 | During tool use, you must pass thinking and redacted_thinking blocks back to the API, |
| 1155 | and you must include the complete unmodified block back to the API. This is critical |
| 1156 | for maintaining the model's reasoning flow and conversation integrity. |
| 1157 | |
| 1158 | On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent |
| 1159 | requests when not using tools, so it's the simplest option to always add to history. |
| 1160 | */ |
| 1161 | |
| 1162 | return { |
| 1163 | modelTitle: this.title ?? completionOptions.model, |
| 1164 | modelProvider: this.underlyingProviderName, |
| 1165 | prompt, |
| 1166 | completion, |
| 1167 | }; |
| 1168 | } |
| 1169 | |
| 1170 | getBatchedChunks(chunks: string[]): string[][] { |
| 1171 | const batchedChunks = []; |
| 1172 | |
| 1173 | for (let i = 0; i < chunks.length; i += this.maxEmbeddingBatchSize) { |
| 1174 | batchedChunks.push(chunks.slice(i, i + this.maxEmbeddingBatchSize)); |
| 1175 | } |
| 1176 | |
| 1177 | return batchedChunks; |
| 1178 | } |
| 1179 | |
| 1180 | async embed(chunks: string[]): Promise<number[][]> { |
| 1181 | const batches = this.getBatchedChunks(chunks); |
| 1182 | |
| 1183 | return ( |
| 1184 | await Promise.all( |
| 1185 | batches.map(async (batch) => { |
| 1186 | if (batch.length === 0) { |
| 1187 | return []; |
| 1188 | } |
| 1189 | |
| 1190 | const embeddings = await withExponentialBackoff<number[][]>( |
| 1191 | async () => { |
| 1192 | if (this.shouldUseOpenAIAdapter("embed") && this.openaiAdapter) { |
| 1193 | const result = await this.openaiAdapter.embed({ |
| 1194 | model: this.model, |
| 1195 | input: batch, |
| 1196 | }); |
| 1197 | return result.data.map((chunk) => chunk.embedding); |
| 1198 | } |
| 1199 | |
| 1200 | return await this._embed(batch); |
| 1201 | }, |
| 1202 | ); |
| 1203 | |
| 1204 | return embeddings; |
| 1205 | }), |
| 1206 | ) |
| 1207 | ).flat(); |
| 1208 | } |
| 1209 | |
| 1210 | async rerank(query: string, chunks: Chunk[]): Promise<number[]> { |
| 1211 | if (this.shouldUseOpenAIAdapter("rerank") && this.openaiAdapter) { |
| 1212 | const results = await this.openaiAdapter.rerank({ |
| 1213 | model: this.model, |
| 1214 | query, |
| 1215 | documents: chunks.map((chunk) => chunk.content), |
| 1216 | }); |
| 1217 | |
| 1218 | // Standard OpenAI format |
| 1219 | if (results.data && Array.isArray(results.data)) { |
| 1220 | return results.data |
| 1221 | .sort((a, b) => a.index - b.index) |
| 1222 | .map((result) => result.relevance_score); |
| 1223 | } |
| 1224 | |
| 1225 | throw new Error( |
| 1226 | `Unexpected rerank response format from ${this.providerName}. ` + |
| 1227 | `Expected 'data' array but got: ${JSON.stringify(Object.keys(results))}`, |
| 1228 | ); |
| 1229 | } |
| 1230 | |
| 1231 | throw new Error( |
| 1232 | `Reranking is not supported for provider type ${this.providerName}`, |
| 1233 | ); |
| 1234 | } |
| 1235 | |
| 1236 | protected async *_streamComplete( |
| 1237 | prompt: string, |
| 1238 | signal: AbortSignal, |
| 1239 | options: CompletionOptions, |
| 1240 | ): AsyncGenerator<string> { |
| 1241 | throw new Error("Not implemented"); |
| 1242 | } |
| 1243 | |
| 1244 | protected async *_streamChat( |
| 1245 | messages: ChatMessage[], |
| 1246 | signal: AbortSignal, |
| 1247 | options: CompletionOptions, |
| 1248 | ): AsyncGenerator<ChatMessage> { |
| 1249 | if (!this.templateMessages) { |
| 1250 | throw new Error( |
| 1251 | "You must either implement templateMessages or _streamChat", |
| 1252 | ); |
| 1253 | } |
| 1254 | |
| 1255 | for await (const chunk of this._streamComplete( |
| 1256 | this.templateMessages(messages), |
| 1257 | signal, |
| 1258 | options, |
| 1259 | )) { |
| 1260 | yield { role: "assistant", content: chunk }; |
| 1261 | } |
| 1262 | } |
| 1263 | |
| 1264 | protected async _complete( |
| 1265 | prompt: string, |
| 1266 | signal: AbortSignal, |
| 1267 | options: CompletionOptions, |
| 1268 | ) { |
| 1269 | let completion = ""; |
| 1270 | for await (const chunk of this._streamComplete(prompt, signal, options)) { |
| 1271 | completion += chunk; |
| 1272 | } |
| 1273 | return completion; |
| 1274 | } |
| 1275 | |
| 1276 | protected async _embed(chunks: string[]): Promise<number[][]> { |
| 1277 | throw new Error( |
| 1278 | `Embedding is not supported for provider type ${this.providerName}`, |
| 1279 | ); |
| 1280 | } |
| 1281 | |
| 1282 | countTokens(text: string): number { |
| 1283 | return countTokens(text, this.model); |
| 1284 | } |
| 1285 | |
| 1286 | protected collectArgs(options: CompletionOptions): any { |
| 1287 | return { |
| 1288 | ...DEFAULT_ARGS, |
| 1289 | // model: this.model, |
| 1290 | ...options, |
| 1291 | }; |
| 1292 | } |
| 1293 | |
| 1294 | public renderPromptTemplate( |
| 1295 | template: PromptTemplate, |
| 1296 | history: ChatMessage[], |
| 1297 | otherData: Record<string, string>, |
| 1298 | canPutWordsInModelsMouth = false, |
| 1299 | ): string | ChatMessage[] { |
| 1300 | if (typeof template === "string") { |
| 1301 | const data: any = { |
| 1302 | history: history, |
| 1303 | ...otherData, |
| 1304 | }; |
| 1305 | if (history.length > 0 && history[0].role === "system") { |
| 1306 | data.system_message = history.shift()!.content; |
| 1307 | } |
| 1308 | |
| 1309 | const compiledTemplate = Handlebars.compile(template); |
| 1310 | return compiledTemplate(data); |
| 1311 | } |
| 1312 | const rendered = template(history, { |
| 1313 | ...otherData, |
| 1314 | supportsCompletions: this.supportsCompletions() ? "true" : "false", |
| 1315 | supportsPrefill: this.supportsPrefill() ? "true" : "false", |
| 1316 | }); |
| 1317 | if ( |
| 1318 | typeof rendered !== "string" && |
| 1319 | rendered[rendered.length - 1]?.role === "assistant" && |
| 1320 | !canPutWordsInModelsMouth |
| 1321 | ) { |
| 1322 | // Some providers don't allow you to put words in the model's mouth |
| 1323 | // So we have to manually compile the prompt template and use |
| 1324 | // raw /completions, not /chat/completions |
| 1325 | const templateMessages = autodetectTemplateFunction( |
| 1326 | this.model, |
| 1327 | this.providerName, |
| 1328 | autodetectTemplateType(this.model), |
| 1329 | ); |
| 1330 | if (templateMessages) { |
| 1331 | return templateMessages(rendered); |
| 1332 | } |
| 1333 | } |
| 1334 | return rendered; |
| 1335 | } |
| 1336 | } |