Elffuss BraidHub

kikocis/continue public

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