Elffuss BraidHub

kikocis/continue public

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