Elffuss BraidHub

kikocis/continue public

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