Elffuss BraidHub

kikocis/continue public

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