Elffuss BraidHub

kikocis/continue public

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