Elffuss BraidHub

kikocis/continue public

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