Elffuss BraidHub

kikocis/continue public

91fbf794ce85 · 33.1 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 fetch(url: RequestInfo | URL, init?: RequestInit): Promise<Response> {
388 // Custom Node.js fetch
389 const customFetch = async (input: URL | RequestInfo, init: any) => {
390 try {
391 const resp = await fetchwithRequestOptions(
392 new URL(input as any),
393 { ...init },
394 { ...this.requestOptions },
395 );
396
397 // Error mapping to be more helpful
398 if (!resp.ok) {
399 if (resp.status === 499) {
400 return resp; // client side cancellation
401 }
402 let text = await resp.text();
403 if (resp.status === 404 && !resp.url.includes("/v1")) {
404 const error = JSON.parse(text)?.error?.replace(/"/g, "'");
405 let model = error?.match(/model '(.*)' not found/)?.[1];
406 if (model && resp.url.match("127.0.0.1:11434")) {
407 text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
408 throw new LLMError(text, this); // No need to add HTTP status details
409 } else if (text.includes("/api/chat")) {
410 text =
411 "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
412 } else {
413 text =
414 "This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json.";
415 }
416 } else if (
417 resp.status === 404 &&
418 resp.url.includes("api.openai.com")
419 ) {
420 text =
421 "You may need to add pre-paid credits before using the OpenAI API.";
422 } else if (
423 resp.status === 401 &&
424 (resp.url.includes("api.mistral.ai") ||
425 resp.url.includes("codestral.mistral.ai"))
426 ) {
427 if (resp.url.includes("codestral.mistral.ai")) {
428 throw new Error(
429 "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.",
430 );
431 } else {
432 throw new Error(
433 "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.",
434 );
435 }
436 }
437 throw new Error(
438 `HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`,
439 );
440 }
441
442 return resp;
443 } catch (e: any) {
444 // Errors to ignore
445 if (e.message.includes("/api/tags")) {
446 throw new Error(`Error fetching tags: ${e.message}`);
447 } else if (e.message.includes("/api/show")) {
448 throw new Error(
449 `HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`,
450 );
451 } else {
452 if (e.name !== "AbortError") {
453 // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here
454 console.debug(
455 `${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`,
456 );
457 }
458 if (
459 e.code === "ECONNREFUSED" &&
460 e.message.includes("http://127.0.0.1:11434")
461 ) {
462 const message = (await isOllamaInstalled())
463 ? "Unable to connect to local Ollama instance. Ollama may not be running."
464 : "Unable to connect to local Ollama instance. Ollama may not be installed or may not running.";
465 throw new Error(message);
466 }
467 }
468 throw e;
469 }
470 };
471 return withExponentialBackoff<Response>(
472 () => customFetch(url, init) as any,
473 5,
474 0.5,
475 );
476 }
477
478 private _parseCompletionOptions(options: LLMFullCompletionOptions) {
479 const log = options.log ?? true;
480 const raw = options.raw ?? false;
481 options.log = undefined;
482
483 const completionOptions: CompletionOptions = mergeJson(
484 this.completionOptions,
485 options,
486 );
487
488 return { completionOptions, logEnabled: log, raw };
489 }
490
491 private _formatChatMessages(messages: ChatMessage[]): string {
492 const msgsCopy = messages ? messages.map((msg) => ({ ...msg })) : [];
493 let formatted = "";
494 for (const msg of msgsCopy) {
495 formatted += this._formatChatMessage(msg);
496 }
497 return formatted;
498 }
499
500 private _formatChatMessage(msg: ChatMessage): string {
501 let contentToShow = "";
502 if (msg.role === "tool") {
503 contentToShow = msg.content;
504 } else if (msg.role === "assistant" && msg.toolCalls) {
505 contentToShow = msg.toolCalls
506 ?.map(
507 (toolCall) =>
508 `${toolCall.function?.name}(${toolCall.function?.arguments})`,
509 )
510 .join("\n");
511 } else if ("content" in msg) {
512 if (Array.isArray(msg.content)) {
513 msg.content = renderChatMessage(msg);
514 }
515 contentToShow = msg.content;
516 }
517
518 return `<${msg.role}>\n${contentToShow}\n\n`;
519 }
520
521 protected async *_streamFim(
522 prefix: string,
523 suffix: string,
524 signal: AbortSignal,
525 options: CompletionOptions,
526 ): AsyncGenerator<string, PromptLog> {
527 throw new Error("Not implemented");
528 }
529
530 protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [];
531
532 private shouldUseOpenAIAdapter(requestType: LlmApiRequestType) {
533 return (
534 this.useOpenAIAdapterFor.includes(requestType) ||
535 this.useOpenAIAdapterFor.includes("*")
536 );
537 }
538
539 async *streamFim(
540 prefix: string,
541 suffix: string,
542 signal: AbortSignal,
543 options: LLMFullCompletionOptions = {},
544 ): AsyncGenerator<string> {
545 const { completionOptions, logEnabled } =
546 this._parseCompletionOptions(options);
547 const interaction = logEnabled
548 ? this.logger?.createInteractionLog()
549 : undefined;
550 let status: InteractionStatus = "in_progress";
551
552 const fimLog = `Prefix: ${prefix}\nSuffix: ${suffix}`;
553 if (logEnabled) {
554 interaction?.logItem({
555 kind: "startFim",
556 prefix,
557 suffix,
558 options: completionOptions,
559 });
560 if (this.llmRequestHook) {
561 this.llmRequestHook(completionOptions.model, fimLog);
562 }
563 }
564
565 let completion = "";
566 try {
567 if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) {
568 const stream = this.openaiAdapter.fimStream(
569 toFimBody(prefix, suffix, completionOptions),
570 signal,
571 );
572 for await (const chunk of stream) {
573 const result = fromChatCompletionChunk(chunk);
574 if (result) {
575 const content = renderChatMessage(result);
576 const formattedContent = this._formatChatMessage(result);
577 interaction?.logItem({
578 kind: "chunk",
579 chunk: formattedContent,
580 });
581 completion += formattedContent;
582 yield content;
583 }
584 }
585 } else {
586 for await (const chunk of this._streamFim(
587 prefix,
588 suffix,
589 signal,
590 completionOptions,
591 )) {
592 interaction?.logItem({
593 kind: "chunk",
594 chunk,
595 });
596 completion += chunk;
597 yield chunk;
598 }
599 }
600
601 status = this._logEnd(
602 completionOptions.model,
603 fimLog,
604 completion,
605 undefined,
606 interaction,
607 );
608 } catch (e) {
609 status = this._logEnd(
610 completionOptions.model,
611 fimLog,
612 completion,
613 undefined,
614 interaction,
615 e,
616 );
617 throw e;
618 } finally {
619 if (status === "in_progress") {
620 this._logEnd(
621 completionOptions.model,
622 fimLog,
623 completion,
624 undefined,
625 interaction,
626 "cancel",
627 );
628 }
629 }
630
631 return {
632 prompt: fimLog,
633 completion,
634 completionOptions,
635 };
636 }
637
638 async *streamComplete(
639 _prompt: string,
640 signal: AbortSignal,
641 options: LLMFullCompletionOptions = {},
642 ) {
643 const { completionOptions, logEnabled, raw } =
644 this._parseCompletionOptions(options);
645 const interaction = logEnabled
646 ? this.logger?.createInteractionLog()
647 : undefined;
648 let status: InteractionStatus = "in_progress";
649
650 let prompt = pruneRawPromptFromTop(
651 completionOptions.model,
652 this.contextLength,
653 _prompt,
654 completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
655 );
656
657 if (!raw) {
658 prompt = this._templatePromptLikeMessages(prompt);
659 }
660
661 if (logEnabled) {
662 interaction?.logItem({
663 kind: "startComplete",
664 prompt,
665 options: completionOptions,
666 });
667 if (this.llmRequestHook) {
668 this.llmRequestHook(completionOptions.model, prompt);
669 }
670 }
671
672 let completion = "";
673 try {
674 if (this.shouldUseOpenAIAdapter("streamComplete") && this.openaiAdapter) {
675 if (completionOptions.stream === false) {
676 // Stream false
677 const response = await this.openaiAdapter.completionNonStream(
678 { ...toCompleteBody(prompt, completionOptions), stream: false },
679 signal,
680 );
681 completion = response.choices[0]?.text ?? "";
682 yield completion;
683 } else {
684 // Stream true
685 for await (const chunk of this.openaiAdapter.completionStream(
686 {
687 ...toCompleteBody(prompt, completionOptions),
688 stream: true,
689 },
690 signal,
691 )) {
692 const content = chunk.choices[0]?.text ?? "";
693 completion += content;
694 interaction?.logItem({
695 kind: "chunk",
696 chunk: content,
697 });
698 yield content;
699 }
700 }
701 } else {
702 for await (const chunk of this._streamComplete(
703 prompt,
704 signal,
705 completionOptions,
706 )) {
707 completion += chunk;
708 interaction?.logItem({
709 kind: "chunk",
710 chunk,
711 });
712 yield chunk;
713 }
714 }
715 status = this._logEnd(
716 completionOptions.model,
717 prompt,
718 completion,
719 undefined,
720 interaction,
721 );
722 } catch (e) {
723 status = this._logEnd(
724 completionOptions.model,
725 prompt,
726 completion,
727 undefined,
728 interaction,
729 e,
730 );
731 throw e;
732 } finally {
733 if (status === "in_progress") {
734 this._logEnd(
735 completionOptions.model,
736 prompt,
737 completion,
738 undefined,
739 interaction,
740 "cancel",
741 );
742 }
743 }
744
745 return {
746 modelTitle: this.title ?? completionOptions.model,
747 prompt,
748 completion,
749 completionOptions,
750 };
751 }
752
753 async complete(
754 _prompt: string,
755 signal: AbortSignal,
756 options: LLMFullCompletionOptions = {},
757 ) {
758 const { completionOptions, logEnabled, raw } =
759 this._parseCompletionOptions(options);
760 const interaction = logEnabled
761 ? this.logger?.createInteractionLog()
762 : undefined;
763 let status: InteractionStatus = "in_progress";
764
765 let prompt = pruneRawPromptFromTop(
766 completionOptions.model,
767 this.contextLength,
768 _prompt,
769 completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
770 );
771
772 if (!raw) {
773 prompt = this._templatePromptLikeMessages(prompt);
774 }
775
776 if (logEnabled) {
777 interaction?.logItem({
778 kind: "startComplete",
779 prompt: prompt,
780 options: completionOptions,
781 });
782 if (this.llmRequestHook) {
783 this.llmRequestHook(completionOptions.model, prompt);
784 }
785 }
786
787 let completion: string = "";
788
789 try {
790 if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) {
791 const result = await this.openaiAdapter.completionNonStream(
792 {
793 ...toCompleteBody(prompt, completionOptions),
794 stream: false,
795 },
796 signal,
797 );
798 completion = result.choices[0].text;
799 } else {
800 completion = await this._complete(prompt, signal, completionOptions);
801 }
802
803 interaction?.logItem({
804 kind: "chunk",
805 chunk: completion,
806 });
807
808 status = this._logEnd(
809 completionOptions.model,
810 prompt,
811 completion,
812 undefined,
813 interaction,
814 );
815 } catch (e) {
816 status = this._logEnd(
817 completionOptions.model,
818 prompt,
819 completion,
820 undefined,
821 interaction,
822 e,
823 );
824 throw e;
825 } finally {
826 if (status === "in_progress") {
827 this._logEnd(
828 completionOptions.model,
829 prompt,
830 completion,
831 undefined,
832 interaction,
833 "cancel",
834 );
835 }
836 }
837
838 return completion;
839 }
840
841 async chat(
842 messages: ChatMessage[],
843 signal: AbortSignal,
844 options: LLMFullCompletionOptions = {},
845 ) {
846 let completion = "";
847 for await (const message of this.streamChat(messages, signal, options)) {
848 completion += renderChatMessage(message);
849 }
850 return { role: "assistant" as const, content: completion };
851 }
852
853 protected modifyChatBody(
854 body: ChatCompletionCreateParams,
855 ): ChatCompletionCreateParams {
856 return body;
857 }
858
859 private _modifyCompletionOptions(
860 completionOptions: CompletionOptions,
861 ): CompletionOptions {
862 // As of 01/14/25 streaming is currently not available with o1
863 // See these threads:
864 // - https://github.com/continuedev/continue/issues/3698
865 // - https://community.openai.com/t/streaming-support-for-o1-o1-2024-12-17-resulting-in-400-unsupported-value/1085043
866 if (completionOptions.model === "o1") {
867 completionOptions.stream = false;
868 }
869
870 return completionOptions;
871 }
872
873 async *streamChat(
874 _messages: ChatMessage[],
875 signal: AbortSignal,
876 options: LLMFullCompletionOptions = {},
877 ): AsyncGenerator<ChatMessage, PromptLog> {
878 let { completionOptions, logEnabled } =
879 this._parseCompletionOptions(options);
880 const interaction = logEnabled
881 ? this.logger?.createInteractionLog()
882 : undefined;
883 let status: InteractionStatus = "in_progress";
884
885 completionOptions = this._modifyCompletionOptions(completionOptions);
886
887 const messages = compileChatMessages({
888 modelName: completionOptions.model,
889 msgs: _messages,
890 contextLength: this.contextLength,
891 maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
892 supportsImages: this.supportsImages(),
893 tools: options.tools,
894 });
895
896 const prompt = this.templateMessages
897 ? this.templateMessages(messages)
898 : this._formatChatMessages(messages);
899 if (logEnabled) {
900 interaction?.logItem({
901 kind: "startChat",
902 messages,
903 options: completionOptions,
904 });
905 if (this.llmRequestHook) {
906 this.llmRequestHook(completionOptions.model, prompt);
907 }
908 }
909
910 let thinking = "";
911 let completion = "";
912
913 try {
914 if (this.templateMessages) {
915 for await (const chunk of this._streamComplete(
916 prompt,
917 signal,
918 completionOptions,
919 )) {
920 completion += chunk;
921 interaction?.logItem({
922 kind: "chunk",
923 chunk: chunk,
924 });
925 yield { role: "assistant", content: chunk };
926 }
927 } else {
928 if (this.shouldUseOpenAIAdapter("streamChat") && this.openaiAdapter) {
929 let body = toChatBody(messages, completionOptions);
930 body = this.modifyChatBody(body);
931
932 if (completionOptions.stream === false) {
933 // Stream false
934 const response = await this.openaiAdapter.chatCompletionNonStream(
935 { ...body, stream: false },
936 signal,
937 );
938 const msg = fromChatResponse(response);
939 yield msg;
940 completion = this._formatChatMessage(msg);
941 } else {
942 // Stream true
943 const stream = this.openaiAdapter.chatCompletionStream(
944 {
945 ...body,
946 stream: true,
947 },
948 signal,
949 );
950 for await (const chunk of stream) {
951 const result = fromChatCompletionChunk(chunk);
952 if (result) {
953 completion += this._formatChatMessage(result);
954 interaction?.logItem({
955 kind: "message",
956 message: result,
957 });
958 yield result;
959 }
960 }
961 }
962 } else {
963 for await (const chunk of this._streamChat(
964 messages,
965 signal,
966 completionOptions,
967 )) {
968 if (chunk.role === "assistant") {
969 completion += this._formatChatMessage(chunk);
970 } else if (chunk.role === "thinking") {
971 thinking += chunk.content;
972 }
973
974 interaction?.logItem({
975 kind: "message",
976 message: chunk,
977 });
978 yield chunk;
979 }
980 }
981 }
982 status = this._logEnd(
983 completionOptions.model,
984 prompt,
985 completion,
986 thinking,
987 interaction,
988 );
989 } catch (e) {
990 status = this._logEnd(
991 completionOptions.model,
992 prompt,
993 completion,
994 thinking,
995 interaction,
996 e,
997 );
998 throw e;
999 } finally {
1000 if (status === "in_progress") {
1001 this._logEnd(
1002 completionOptions.model,
1003 prompt,
1004 completion,
1005 undefined,
1006 interaction,
1007 "cancel",
1008 );
1009 }
1010 }
1011 /*
1012 TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
1013 During tool use, you must pass thinking and redacted_thinking blocks back to the API,
1014 and you must include the complete unmodified block back to the API. This is critical
1015 for maintaining the model's reasoning flow and conversation integrity.
1016
1017 On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent
1018 requests when not using tools, so it's the simplest option to always add to history.
1019 */
1020
1021 return {
1022 modelTitle: this.title ?? completionOptions.model,
1023 prompt,
1024 completion,
1025 completionOptions,
1026 };
1027 }
1028
1029 getBatchedChunks(chunks: string[]): string[][] {
1030 const batchedChunks = [];
1031
1032 for (let i = 0; i < chunks.length; i += this.maxEmbeddingBatchSize) {
1033 batchedChunks.push(chunks.slice(i, i + this.maxEmbeddingBatchSize));
1034 }
1035
1036 return batchedChunks;
1037 }
1038
1039 async embed(chunks: string[]): Promise<number[][]> {
1040 const batches = this.getBatchedChunks(chunks);
1041
1042 return (
1043 await Promise.all(
1044 batches.map(async (batch) => {
1045 if (batch.length === 0) {
1046 return [];
1047 }
1048
1049 const embeddings = await withExponentialBackoff<number[][]>(
1050 async () => {
1051 if (this.shouldUseOpenAIAdapter("embed") && this.openaiAdapter) {
1052 const result = await this.openaiAdapter.embed({
1053 model: this.model,
1054 input: batch,
1055 });
1056 return result.data.map((chunk) => chunk.embedding);
1057 }
1058
1059 return await this._embed(batch);
1060 },
1061 );
1062
1063 return embeddings;
1064 }),
1065 )
1066 ).flat();
1067 }
1068
1069 async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
1070 if (this.shouldUseOpenAIAdapter("rerank") && this.openaiAdapter) {
1071 const results = await this.openaiAdapter.rerank({
1072 model: this.model,
1073 query,
1074 documents: chunks.map((chunk) => chunk.content),
1075 });
1076
1077 // Standard OpenAI format
1078 if (results.data && Array.isArray(results.data)) {
1079 return results.data
1080 .sort((a, b) => a.index - b.index)
1081 .map((result) => result.relevance_score);
1082 }
1083
1084 throw new Error(
1085 `Unexpected rerank response format from ${this.providerName}. ` +
1086 `Expected 'data' array but got: ${JSON.stringify(Object.keys(results))}`,
1087 );
1088 }
1089
1090 throw new Error(
1091 `Reranking is not supported for provider type ${this.providerName}`,
1092 );
1093 }
1094
1095 protected async *_streamComplete(
1096 prompt: string,
1097 signal: AbortSignal,
1098 options: CompletionOptions,
1099 ): AsyncGenerator<string> {
1100 throw new Error("Not implemented");
1101 }
1102
1103 protected async *_streamChat(
1104 messages: ChatMessage[],
1105 signal: AbortSignal,
1106 options: CompletionOptions,
1107 ): AsyncGenerator<ChatMessage> {
1108 if (!this.templateMessages) {
1109 throw new Error(
1110 "You must either implement templateMessages or _streamChat",
1111 );
1112 }
1113
1114 for await (const chunk of this._streamComplete(
1115 this.templateMessages(messages),
1116 signal,
1117 options,
1118 )) {
1119 yield { role: "assistant", content: chunk };
1120 }
1121 }
1122
1123 protected async _complete(
1124 prompt: string,
1125 signal: AbortSignal,
1126 options: CompletionOptions,
1127 ) {
1128 let completion = "";
1129 for await (const chunk of this._streamComplete(prompt, signal, options)) {
1130 completion += chunk;
1131 }
1132 return completion;
1133 }
1134
1135 protected async _embed(chunks: string[]): Promise<number[][]> {
1136 throw new Error(
1137 `Embedding is not supported for provider type ${this.providerName}`,
1138 );
1139 }
1140
1141 countTokens(text: string): number {
1142 return countTokens(text, this.model);
1143 }
1144
1145 protected collectArgs(options: CompletionOptions): any {
1146 return {
1147 ...DEFAULT_ARGS,
1148 // model: this.model,
1149 ...options,
1150 };
1151 }
1152
1153 public renderPromptTemplate(
1154 template: PromptTemplate,
1155 history: ChatMessage[],
1156 otherData: Record<string, string>,
1157 canPutWordsInModelsMouth = false,
1158 ): string | ChatMessage[] {
1159 if (typeof template === "string") {
1160 const data: any = {
1161 history: history,
1162 ...otherData,
1163 };
1164 if (history.length > 0 && history[0].role === "system") {
1165 data.system_message = history.shift()!.content;
1166 }
1167
1168 const compiledTemplate = Handlebars.compile(template);
1169 return compiledTemplate(data);
1170 }
1171 const rendered = template(history, {
1172 ...otherData,
1173 supportsCompletions: this.supportsCompletions() ? "true" : "false",
1174 supportsPrefill: this.supportsPrefill() ? "true" : "false",
1175 });
1176 if (
1177 typeof rendered !== "string" &&
1178 rendered[rendered.length - 1]?.role === "assistant" &&
1179 !canPutWordsInModelsMouth
1180 ) {
1181 // Some providers don't allow you to put words in the model's mouth
1182 // So we have to manually compile the prompt template and use
1183 // raw /completions, not /chat/completions
1184 const templateMessages = autodetectTemplateFunction(
1185 this.model,
1186 this.providerName,
1187 autodetectTemplateType(this.model),
1188 );
1189 if (templateMessages) {
1190 return templateMessages(rendered);
1191 }
1192 }
1193 return rendered;
1194 }
1195}