Elffuss BraidHub

kikocis/continue public

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