Elffuss BraidHub

kikocis/continue public

05a393b2fd55 · 4.3 KiBRawPermalink
1import { fetchwithRequestOptions } from "@continuedev/fetch";
2import { ChatMessage, IDE, PromptLog } from "..";
3import { ConfigHandler } from "../config/ConfigHandler";
4import { usesFreeTrialApiKey } from "../config/usesFreeTrialApiKey";
5import { FromCoreProtocol, ToCoreProtocol } from "../protocol";
6import { IMessenger, Message } from "../protocol/messenger";
7import { Telemetry } from "../util/posthog";
8import { TTS } from "../util/tts";
9
10export async function* llmStreamChat(
11 configHandler: ConfigHandler,
12 abortController: AbortController,
13 msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
14 ide: IDE,
15 messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
16): AsyncGenerator<ChatMessage, PromptLog> {
17 const { config } = await configHandler.loadConfig();
18 if (!config) {
19 throw new Error("Config not loaded");
20 }
21
22 // Stop TTS on new StreamChat
23 if (config.experimental?.readResponseTTS) {
24 void TTS.kill();
25 }
26
27 const { legacySlashCommandData, completionOptions, messages } = msg.data;
28
29 const model = config.selectedModelByRole.chat;
30
31 if (!model) {
32 throw new Error("No chat model selected");
33 }
34
35 // Log to return in case of error
36 const errorPromptLog = {
37 modelTitle: model?.title ?? model?.model,
38 completion: "",
39 prompt: "",
40 completionOptions: {
41 ...msg.data.completionOptions,
42 model: model?.model,
43 },
44 };
45
46 if (legacySlashCommandData) {
47 const { command, contextItems, historyIndex, input, selectedCode } =
48 legacySlashCommandData;
49 const slashCommand = config.slashCommands?.find(
50 (sc) => sc.name === command.name,
51 );
52 if (!slashCommand) {
53 throw new Error(`Unknown slash command ${command.name}`);
54 }
55 void Telemetry.capture(
56 "useSlashCommand",
57 {
58 name: command.name,
59 },
60 true,
61 );
62
63 const gen = slashCommand.run({
64 input,
65 history: messages,
66 llm: model,
67 contextItems,
68 params: command.params,
69 ide,
70 addContextItem: (item) => {
71 void messenger.request("addContextItem", {
72 item,
73 historyIndex,
74 });
75 },
76 selectedCode,
77 config,
78 fetch: (url, init) =>
79 fetchwithRequestOptions(
80 url,
81 {
82 ...init,
83 signal: abortController.signal,
84 },
85 config.requestOptions,
86 ),
87 completionOptions,
88 });
89 let next = await gen.next();
90 while (!next.done) {
91 if (abortController.signal.aborted) {
92 next = await gen.return(errorPromptLog);
93 break;
94 }
95 if (next.value) {
96 yield {
97 role: "assistant",
98 content: next.value,
99 };
100 }
101 next = await gen.next();
102 }
103 if (!next.done) {
104 throw new Error("Will never happen");
105 }
106
107 return next.value;
108 } else {
109 const gen = model.streamChat(
110 messages,
111 abortController.signal,
112 completionOptions,
113 );
114 let next = await gen.next();
115 while (!next.done) {
116 if (abortController.signal.aborted) {
117 next = await gen.return(errorPromptLog);
118 break;
119 }
120
121 const chunk = next.value;
122
123 yield chunk;
124 next = await gen.next();
125 }
126 if (config.experimental?.readResponseTTS && "completion" in next.value) {
127 void TTS.read(next.value?.completion);
128 }
129
130 void Telemetry.capture(
131 "chat",
132 {
133 model: model.model,
134 provider: model.providerName,
135 },
136 true,
137 );
138
139 void checkForFreeTrialExceeded(configHandler, messenger);
140
141 if (!next.done) {
142 throw new Error("Will never happen");
143 }
144
145 return next.value;
146 }
147}
148
149async function checkForFreeTrialExceeded(
150 configHandler: ConfigHandler,
151 messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
152) {
153 const { config } = await configHandler.getSerializedConfig();
154
155 // Only check if the user is using the free trial
156 if (config && !usesFreeTrialApiKey(config)) {
157 return;
158 }
159
160 try {
161 const freeTrialStatus =
162 await configHandler.controlPlaneClient.getFreeTrialStatus();
163 if (
164 freeTrialStatus &&
165 freeTrialStatus.chatCount &&
166 freeTrialStatus.chatCount > freeTrialStatus.chatLimit
167 ) {
168 void messenger.request("freeTrialExceeded", undefined);
169 }
170 } catch (error) {
171 console.error("Error checking free trial status:", error);
172 }
173}