Elffuss BraidHub

kikocis/continue public

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