Elffuss BraidHub

kikocis/continue public

b0a27770390e · 36.7 KiBRawPermalink
1import { ModelRole } from "@continuedev/config-yaml";
2import { fetchwithRequestOptions } from "@continuedev/fetch";
3import { findLlmInfo } from "@continuedev/llm-info";
4import {
5 BaseLlmApi,
6 ChatCompletionCreateParams,
7 constructLlmApi,
8} from "@continuedev/openai-adapters";
9import Handlebars from "handlebars";
10
11import { DevDataSqliteDb } from "../data/devdataSqlite.js";
12import { DataLogger } from "../data/log.js";
13import {
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";
33import { Logger } from "../util/Logger.js";
34import mergeJson from "../util/merge.js";
35import { renderChatMessage } from "../util/messageContent.js";
36import { isOllamaInstalled } from "../util/ollamaHelper.js";
37import { TokensBatchingService } from "../util/TokensBatchingService.js";
38import { withExponentialBackoff } from "../util/withExponentialBackoff.js";
39
40import {
41 autodetectPromptTemplates,
42 autodetectTemplateFunction,
43 autodetectTemplateType,
44 modelSupportsImages,
45} from "./autodetect.js";
46import {
47 DEFAULT_ARGS,
48 DEFAULT_CONTEXT_LENGTH,
49 DEFAULT_MAX_BATCH_SIZE,
50 DEFAULT_MAX_CHUNK_SIZE,
51 DEFAULT_MAX_TOKENS,
52 LLMConfigurationStatuses,
53} from "./constants.js";
54import {
55 compileChatMessages,
56 countTokens,
57 pruneRawPromptFromTop,
58} from "./countTokens.js";
59import {
60 fromChatCompletionChunk,
61 fromChatResponse,
62 LlmApiRequestType,
63 toChatBody,
64 toCompleteBody,
65 toFimBody,
66} from "./openaiTypeConverters.js";
67
68export class LLMError extends Error {
69 constructor(
70 message: string,
71 public llm: ILLM,
72 ) {
73 super(message);
74 }
75}
76
77export function isModelInstaller(provider: any): provider is ModelInstaller {
78 return (
79 provider &&
80 typeof provider.installModel === "function" &&
81 typeof provider.isInstallingModel === "function"
82 );
83}
84
85type InteractionStatus = "in_progress" | "success" | "error" | "cancelled";
86
87export 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);
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 }
507 throw e;
508 }
509 };
510 return withExponentialBackoff<Response>(
511 () => customFetch(url, init) as any,
512 5,
513 0.5,
514 );
515 }
516
517 private _parseCompletionOptions(options: LLMFullCompletionOptions) {
518 const log = options.log ?? true;
519 const raw = options.raw ?? false;
520 options.log = undefined;
521
522 const completionOptions: CompletionOptions = mergeJson(
523 this.completionOptions,
524 options,
525 );
526
527 return { completionOptions, logEnabled: log, raw };
528 }
529
530 private _formatChatMessages(messages: ChatMessage[]): string {
531 const msgsCopy = messages ? messages.map((msg) => ({ ...msg })) : [];
532 let formatted = "";
533 for (const msg of msgsCopy) {
534 formatted += this._formatChatMessage(msg);
535 }
536 return formatted;
537 }
538
539 private _formatChatMessage(msg: ChatMessage): string {
540 let contentToShow = "";
541 if (msg.role === "tool") {
542 contentToShow = msg.content;
543 } else if (msg.role === "assistant" && msg.toolCalls?.length) {
544 contentToShow = msg.toolCalls
545 ?.map(
546 (toolCall) =>
547 `${toolCall.function?.name}(${toolCall.function?.arguments})`,
548 )
549 .join("\n");
550 } else if ("content" in msg) {
551 contentToShow = renderChatMessage(msg);
552 }
553
554 return `<${msg.role}>\n${contentToShow}\n\n`;
555 }
556
557 protected async *_streamFim(
558 prefix: string,
559 suffix: string,
560 signal: AbortSignal,
561 options: CompletionOptions,
562 ): AsyncGenerator<string, PromptLog> {
563 throw new Error("Not implemented");
564 }
565
566 protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [];
567
568 private shouldUseOpenAIAdapter(requestType: LlmApiRequestType) {
569 return (
570 this.useOpenAIAdapterFor.includes(requestType) ||
571 this.useOpenAIAdapterFor.includes("*")
572 );
573 }
574
575 async *streamFim(
576 prefix: string,
577 suffix: string,
578 signal: AbortSignal,
579 options: LLMFullCompletionOptions = {},
580 ): AsyncGenerator<string> {
581 const { completionOptions, logEnabled } =
582 this._parseCompletionOptions(options);
583 const interaction = logEnabled
584 ? this.logger?.createInteractionLog()
585 : undefined;
586 let status: InteractionStatus = "in_progress";
587
588 const fimLog = `Prefix: ${prefix}\nSuffix: ${suffix}`;
589 if (logEnabled) {
590 interaction?.logItem({
591 kind: "startFim",
592 prefix,
593 suffix,
594 options: completionOptions,
595 provider: this.providerName,
596 });
597 if (this.llmRequestHook) {
598 this.llmRequestHook(completionOptions.model, fimLog);
599 }
600 }
601
602 let completion = "";
603 try {
604 if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) {
605 const stream = this.openaiAdapter.fimStream(
606 toFimBody(prefix, suffix, completionOptions),
607 signal,
608 );
609 for await (const chunk of stream) {
610 const result = fromChatCompletionChunk(chunk);
611 if (result) {
612 const content = renderChatMessage(result);
613 const formattedContent = this._formatChatMessage(result);
614 interaction?.logItem({
615 kind: "chunk",
616 chunk: formattedContent,
617 });
618
619 completion += formattedContent;
620 yield content;
621 }
622 }
623 } else {
624 for await (const chunk of this._streamFim(
625 prefix,
626 suffix,
627 signal,
628 completionOptions,
629 )) {
630 interaction?.logItem({
631 kind: "chunk",
632 chunk,
633 });
634
635 completion += chunk;
636 yield chunk;
637 }
638 }
639
640 status = this._logEnd(
641 completionOptions.model,
642 fimLog,
643 completion,
644 undefined,
645 interaction,
646 undefined,
647 );
648 } catch (e) {
649 // Capture FIM (Fill-in-the-Middle) completion failures to Sentry
650 Logger.error(e as Error, {
651 context: "llm_stream_fim",
652 model: completionOptions.model,
653 provider: this.providerName,
654 useOpenAIAdapter: this.shouldUseOpenAIAdapter("streamFim"),
655 });
656
657 status = this._logEnd(
658 completionOptions.model,
659 fimLog,
660 completion,
661 undefined,
662 interaction,
663 undefined,
664 e,
665 );
666 throw e;
667 } finally {
668 if (status === "in_progress") {
669 this._logEnd(
670 completionOptions.model,
671 fimLog,
672 completion,
673 undefined,
674 interaction,
675 undefined,
676 "cancel",
677 );
678 }
679 }
680
681 return {
682 prompt: fimLog,
683 completion,
684 completionOptions,
685 };
686 }
687
688 async *streamComplete(
689 _prompt: string,
690 signal: AbortSignal,
691 options: LLMFullCompletionOptions = {},
692 ) {
693 const { completionOptions, logEnabled, raw } =
694 this._parseCompletionOptions(options);
695 const interaction = logEnabled
696 ? this.logger?.createInteractionLog()
697 : undefined;
698 let status: InteractionStatus = "in_progress";
699
700 let prompt = pruneRawPromptFromTop(
701 completionOptions.model,
702 this.contextLength,
703 _prompt,
704 completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
705 );
706
707 if (!raw) {
708 prompt = this._templatePromptLikeMessages(prompt);
709 }
710
711 if (logEnabled) {
712 interaction?.logItem({
713 kind: "startComplete",
714 prompt,
715 options: completionOptions,
716 provider: this.providerName,
717 });
718 if (this.llmRequestHook) {
719 this.llmRequestHook(completionOptions.model, prompt);
720 }
721 }
722
723 let completion = "";
724 try {
725 if (this.shouldUseOpenAIAdapter("streamComplete") && this.openaiAdapter) {
726 if (completionOptions.stream === false) {
727 // Stream false
728 const response = await this.openaiAdapter.completionNonStream(
729 { ...toCompleteBody(prompt, completionOptions), stream: false },
730 signal,
731 );
732 completion = response.choices[0]?.text ?? "";
733 yield completion;
734 } else {
735 // Stream true
736 for await (const chunk of this.openaiAdapter.completionStream(
737 {
738 ...toCompleteBody(prompt, completionOptions),
739 stream: true,
740 },
741 signal,
742 )) {
743 const content = chunk.choices[0]?.text ?? "";
744 completion += content;
745 interaction?.logItem({
746 kind: "chunk",
747 chunk: content,
748 });
749 yield content;
750 }
751 }
752 } else {
753 for await (const chunk of this._streamComplete(
754 prompt,
755 signal,
756 completionOptions,
757 )) {
758 completion += chunk;
759 interaction?.logItem({
760 kind: "chunk",
761 chunk,
762 });
763 yield chunk;
764 }
765 }
766 status = this._logEnd(
767 completionOptions.model,
768 prompt,
769 completion,
770 undefined,
771 interaction,
772 undefined,
773 );
774 } catch (e) {
775 // Capture streaming completion failures to Sentry
776 Logger.error(e as Error, {
777 context: "llm_stream_complete",
778 model: completionOptions.model,
779 provider: this.providerName,
780 useOpenAIAdapter: this.shouldUseOpenAIAdapter("streamComplete"),
781 streamEnabled: completionOptions.stream !== false,
782 });
783
784 status = this._logEnd(
785 completionOptions.model,
786 prompt,
787 completion,
788 undefined,
789 interaction,
790 undefined,
791 e,
792 );
793 throw e;
794 } finally {
795 if (status === "in_progress") {
796 this._logEnd(
797 completionOptions.model,
798 prompt,
799 completion,
800 undefined,
801 interaction,
802 undefined,
803 "cancel",
804 );
805 }
806 }
807
808 return {
809 modelTitle: this.title ?? completionOptions.model,
810 modelProvider: this.underlyingProviderName,
811 prompt,
812 completion,
813 completionOptions,
814 };
815 }
816
817 async complete(
818 _prompt: string,
819 signal: AbortSignal,
820 options: LLMFullCompletionOptions = {},
821 ) {
822 const { completionOptions, logEnabled, raw } =
823 this._parseCompletionOptions(options);
824 const interaction = logEnabled
825 ? this.logger?.createInteractionLog()
826 : undefined;
827 let status: InteractionStatus = "in_progress";
828
829 let prompt = pruneRawPromptFromTop(
830 completionOptions.model,
831 this.contextLength,
832 _prompt,
833 completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
834 );
835
836 if (!raw) {
837 prompt = this._templatePromptLikeMessages(prompt);
838 }
839
840 if (logEnabled) {
841 interaction?.logItem({
842 kind: "startComplete",
843 prompt: prompt,
844 options: completionOptions,
845 provider: this.providerName,
846 });
847 if (this.llmRequestHook) {
848 this.llmRequestHook(completionOptions.model, prompt);
849 }
850 }
851
852 let completion: string = "";
853
854 try {
855 if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) {
856 const result = await this.openaiAdapter.completionNonStream(
857 {
858 ...toCompleteBody(prompt, completionOptions),
859 stream: false,
860 },
861 signal,
862 );
863 completion = result.choices[0].text;
864 } else {
865 completion = await this._complete(prompt, signal, completionOptions);
866 }
867
868 interaction?.logItem({
869 kind: "chunk",
870 chunk: completion,
871 });
872
873 status = this._logEnd(
874 completionOptions.model,
875 prompt,
876 completion,
877 undefined,
878 interaction,
879 undefined,
880 );
881 } catch (e) {
882 // Capture completion failures to Sentry
883 Logger.error(e as Error, {
884 context: "llm_complete",
885 model: completionOptions.model,
886 provider: this.providerName,
887 useOpenAIAdapter: this.shouldUseOpenAIAdapter("complete"),
888 });
889
890 status = this._logEnd(
891 completionOptions.model,
892 prompt,
893 completion,
894 undefined,
895 interaction,
896 undefined,
897 e,
898 );
899 throw e;
900 } finally {
901 if (status === "in_progress") {
902 this._logEnd(
903 completionOptions.model,
904 prompt,
905 completion,
906 undefined,
907 interaction,
908 undefined,
909 "cancel",
910 );
911 }
912 }
913
914 return completion;
915 }
916
917 async chat(
918 messages: ChatMessage[],
919 signal: AbortSignal,
920 options: LLMFullCompletionOptions = {},
921 ) {
922 let completion = "";
923 for await (const message of this.streamChat(messages, signal, options)) {
924 completion += renderChatMessage(message);
925 }
926 return { role: "assistant" as const, content: completion };
927 }
928
929 compileChatMessages(
930 message: ChatMessage[],
931 options: LLMFullCompletionOptions,
932 ) {
933 let { completionOptions } = this._parseCompletionOptions(options);
934 completionOptions = this._modifyCompletionOptions(completionOptions);
935
936 return compileChatMessages({
937 modelName: completionOptions.model,
938 msgs: message,
939 knownContextLength: this._contextLength,
940 maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
941 supportsImages: this.supportsImages(),
942 tools: options.tools,
943 });
944 }
945
946 protected modifyChatBody(
947 body: ChatCompletionCreateParams,
948 ): ChatCompletionCreateParams {
949 return body;
950 }
951
952 private _modifyCompletionOptions(
953 completionOptions: CompletionOptions,
954 ): CompletionOptions {
955 // As of 01/14/25 streaming is currently not available with o1
956 // See these threads:
957 // - https://github.com/continuedev/continue/issues/3698
958 // - https://community.openai.com/t/streaming-support-for-o1-o1-2024-12-17-resulting-in-400-unsupported-value/1085043
959 if (completionOptions.model === "o1") {
960 completionOptions.stream = false;
961 }
962
963 return completionOptions;
964 }
965
966 async *streamChat(
967 _messages: ChatMessage[],
968 signal: AbortSignal,
969 options: LLMFullCompletionOptions = {},
970 messageOptions?: MessageOption,
971 ): AsyncGenerator<ChatMessage, PromptLog> {
972 let { completionOptions, logEnabled } =
973 this._parseCompletionOptions(options);
974 const interaction = logEnabled
975 ? this.logger?.createInteractionLog()
976 : undefined;
977 let status: InteractionStatus = "in_progress";
978
979 completionOptions = this._modifyCompletionOptions(completionOptions);
980
981 let messages = _messages;
982
983 // If not precompiled, compile the chat messages
984 if (!messageOptions?.precompiled) {
985 const { compiledChatMessages } = compileChatMessages({
986 modelName: completionOptions.model,
987 msgs: _messages,
988 knownContextLength: this._contextLength,
989 maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
990 supportsImages: this.supportsImages(),
991 tools: options.tools,
992 });
993
994 messages = compiledChatMessages;
995 }
996
997 const prompt = this.templateMessages
998 ? this.templateMessages(messages)
999 : this._formatChatMessages(messages);
1000 if (logEnabled) {
1001 interaction?.logItem({
1002 kind: "startChat",
1003 messages,
1004 options: completionOptions,
1005 provider: this.providerName,
1006 });
1007 if (this.llmRequestHook) {
1008 this.llmRequestHook(completionOptions.model, prompt);
1009 }
1010 }
1011
1012 let thinking = "";
1013 let completion = "";
1014 let usage: Usage | undefined = undefined;
1015
1016 try {
1017 if (this.templateMessages) {
1018 for await (const chunk of this._streamComplete(
1019 prompt,
1020 signal,
1021 completionOptions,
1022 )) {
1023 completion += chunk;
1024 interaction?.logItem({
1025 kind: "chunk",
1026 chunk: chunk,
1027 });
1028 yield { role: "assistant", content: chunk };
1029 }
1030 } else {
1031 if (this.shouldUseOpenAIAdapter("streamChat") && this.openaiAdapter) {
1032 let body = toChatBody(messages, completionOptions);
1033 body = this.modifyChatBody(body);
1034
1035 if (completionOptions.stream === false) {
1036 // Stream false
1037 const response = await this.openaiAdapter.chatCompletionNonStream(
1038 { ...body, stream: false },
1039 signal,
1040 );
1041 const msg = fromChatResponse(response);
1042 yield msg;
1043 completion = this._formatChatMessage(msg);
1044 } else {
1045 // Stream true
1046 const stream = this.openaiAdapter.chatCompletionStream(
1047 {
1048 ...body,
1049 stream: true,
1050 },
1051 signal,
1052 );
1053 for await (const chunk of stream) {
1054 const result = fromChatCompletionChunk(chunk);
1055 if (result) {
1056 completion += this._formatChatMessage(result);
1057 interaction?.logItem({
1058 kind: "message",
1059 message: result,
1060 });
1061 yield result;
1062 }
1063 }
1064 }
1065 } else {
1066 for await (const chunk of this._streamChat(
1067 messages,
1068 signal,
1069 completionOptions,
1070 )) {
1071 if (chunk.role === "assistant") {
1072 completion += this._formatChatMessage(chunk);
1073 } else if (chunk.role === "thinking") {
1074 thinking += chunk.content;
1075 }
1076
1077 interaction?.logItem({
1078 kind: "message",
1079 message: chunk,
1080 });
1081
1082 if (chunk.role === "assistant" && chunk.usage) {
1083 usage = chunk.usage;
1084 }
1085
1086 yield chunk;
1087 }
1088 }
1089 }
1090 status = this._logEnd(
1091 completionOptions.model,
1092 prompt,
1093 completion,
1094 thinking,
1095 interaction,
1096 usage,
1097 );
1098 } catch (e) {
1099 // Capture chat streaming failures to Sentry
1100 Logger.error(e as Error, {
1101 context: "llm_stream_chat",
1102 model: completionOptions.model,
1103 provider: this.providerName,
1104 useOpenAIAdapter: this.shouldUseOpenAIAdapter("streamChat"),
1105 streamEnabled: completionOptions.stream !== false,
1106 templateMessages: !!this.templateMessages,
1107 });
1108
1109 status = this._logEnd(
1110 completionOptions.model,
1111 prompt,
1112 completion,
1113 thinking,
1114 interaction,
1115 usage,
1116 e,
1117 );
1118 throw e;
1119 } finally {
1120 if (status === "in_progress") {
1121 this._logEnd(
1122 completionOptions.model,
1123 prompt,
1124 completion,
1125 undefined,
1126 interaction,
1127 usage,
1128 "cancel",
1129 );
1130 }
1131 }
1132 /*
1133 TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
1134 During tool use, you must pass thinking and redacted_thinking blocks back to the API,
1135 and you must include the complete unmodified block back to the API. This is critical
1136 for maintaining the model's reasoning flow and conversation integrity.
1137
1138 On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent
1139 requests when not using tools, so it's the simplest option to always add to history.
1140 */
1141
1142 return {
1143 modelTitle: this.title ?? completionOptions.model,
1144 modelProvider: this.underlyingProviderName,
1145 prompt,
1146 completion,
1147 };
1148 }
1149
1150 getBatchedChunks(chunks: string[]): string[][] {
1151 const batchedChunks = [];
1152
1153 for (let i = 0; i < chunks.length; i += this.maxEmbeddingBatchSize) {
1154 batchedChunks.push(chunks.slice(i, i + this.maxEmbeddingBatchSize));
1155 }
1156
1157 return batchedChunks;
1158 }
1159
1160 async embed(chunks: string[]): Promise<number[][]> {
1161 const batches = this.getBatchedChunks(chunks);
1162
1163 return (
1164 await Promise.all(
1165 batches.map(async (batch) => {
1166 if (batch.length === 0) {
1167 return [];
1168 }
1169
1170 const embeddings = await withExponentialBackoff<number[][]>(
1171 async () => {
1172 if (this.shouldUseOpenAIAdapter("embed") && this.openaiAdapter) {
1173 const result = await this.openaiAdapter.embed({
1174 model: this.model,
1175 input: batch,
1176 });
1177 return result.data.map((chunk) => chunk.embedding);
1178 }
1179
1180 return await this._embed(batch);
1181 },
1182 );
1183
1184 return embeddings;
1185 }),
1186 )
1187 ).flat();
1188 }
1189
1190 async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
1191 if (this.shouldUseOpenAIAdapter("rerank") && this.openaiAdapter) {
1192 const results = await this.openaiAdapter.rerank({
1193 model: this.model,
1194 query,
1195 documents: chunks.map((chunk) => chunk.content),
1196 });
1197
1198 // Standard OpenAI format
1199 if (results.data && Array.isArray(results.data)) {
1200 return results.data
1201 .sort((a, b) => a.index - b.index)
1202 .map((result) => result.relevance_score);
1203 }
1204
1205 throw new Error(
1206 `Unexpected rerank response format from ${this.providerName}. ` +
1207 `Expected 'data' array but got: ${JSON.stringify(Object.keys(results))}`,
1208 );
1209 }
1210
1211 throw new Error(
1212 `Reranking is not supported for provider type ${this.providerName}`,
1213 );
1214 }
1215
1216 protected async *_streamComplete(
1217 prompt: string,
1218 signal: AbortSignal,
1219 options: CompletionOptions,
1220 ): AsyncGenerator<string> {
1221 throw new Error("Not implemented");
1222 }
1223
1224 protected async *_streamChat(
1225 messages: ChatMessage[],
1226 signal: AbortSignal,
1227 options: CompletionOptions,
1228 ): AsyncGenerator<ChatMessage> {
1229 if (!this.templateMessages) {
1230 throw new Error(
1231 "You must either implement templateMessages or _streamChat",
1232 );
1233 }
1234
1235 for await (const chunk of this._streamComplete(
1236 this.templateMessages(messages),
1237 signal,
1238 options,
1239 )) {
1240 yield { role: "assistant", content: chunk };
1241 }
1242 }
1243
1244 protected async _complete(
1245 prompt: string,
1246 signal: AbortSignal,
1247 options: CompletionOptions,
1248 ) {
1249 let completion = "";
1250 for await (const chunk of this._streamComplete(prompt, signal, options)) {
1251 completion += chunk;
1252 }
1253 return completion;
1254 }
1255
1256 protected async _embed(chunks: string[]): Promise<number[][]> {
1257 throw new Error(
1258 `Embedding is not supported for provider type ${this.providerName}`,
1259 );
1260 }
1261
1262 countTokens(text: string): number {
1263 return countTokens(text, this.model);
1264 }
1265
1266 protected collectArgs(options: CompletionOptions): any {
1267 return {
1268 ...DEFAULT_ARGS,
1269 // model: this.model,
1270 ...options,
1271 };
1272 }
1273
1274 public renderPromptTemplate(
1275 template: PromptTemplate,
1276 history: ChatMessage[],
1277 otherData: Record<string, string>,
1278 canPutWordsInModelsMouth = false,
1279 ): string | ChatMessage[] {
1280 if (typeof template === "string") {
1281 const data: any = {
1282 history: history,
1283 ...otherData,
1284 };
1285 if (history.length > 0 && history[0].role === "system") {
1286 data.system_message = history.shift()!.content;
1287 }
1288
1289 const compiledTemplate = Handlebars.compile(template);
1290 return compiledTemplate(data);
1291 }
1292 const rendered = template(history, {
1293 ...otherData,
1294 supportsCompletions: this.supportsCompletions() ? "true" : "false",
1295 supportsPrefill: this.supportsPrefill() ? "true" : "false",
1296 });
1297 if (
1298 typeof rendered !== "string" &&
1299 rendered[rendered.length - 1]?.role === "assistant" &&
1300 !canPutWordsInModelsMouth
1301 ) {
1302 // Some providers don't allow you to put words in the model's mouth
1303 // So we have to manually compile the prompt template and use
1304 // raw /completions, not /chat/completions
1305 const templateMessages = autodetectTemplateFunction(
1306 this.model,
1307 this.providerName,
1308 autodetectTemplateType(this.model),
1309 );
1310 if (templateMessages) {
1311 return templateMessages(rendered);
1312 }
1313 }
1314 return rendered;
1315 }
1316}