Elffuss BraidHub

kikocis/continue public

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