Elffuss BraidHub

kikocis/continue public

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