Elffuss BraidHub

kikocis/continue public

80ffc97db92a · 5.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 {
28 legacySlashCommandData,
29 completionOptions,
30 messages,
31 messageOptions,
32 } = msg.data;
33
34 const model = config.selectedModelByRole.chat;
35
36 if (!model) {
37 throw new Error("No chat model selected");
38 }
39
40 // Log to return in case of error
41 const errorPromptLog = {
42 modelTitle: model?.title ?? model?.model,
43 completion: "",
44 prompt: "",
45 completionOptions: {
46 ...msg.data.completionOptions,
47 model: model?.model,
48 },
49 };
50
51 try {
52 if (legacySlashCommandData) {
53 const { command, contextItems, historyIndex, input, selectedCode } =
54 legacySlashCommandData;
55 const slashCommand = config.slashCommands?.find(
56 (sc) => sc.name === command.name,
57 );
58 if (!slashCommand) {
59 throw new Error(`Unknown slash command ${command.name}`);
60 }
61 void Telemetry.capture(
62 "useSlashCommand",
63 {
64 name: command.name,
65 },
66 true,
67 );
68 if (!slashCommand.run) {
69 console.error(
70 `Slash command ${command.name} (${command.source}) has no run function`,
71 );
72 throw new Error(`Slash command not found`);
73 }
74
75 const gen = slashCommand.run({
76 input,
77 history: messages,
78 llm: model,
79 contextItems,
80 params: command.params,
81 ide,
82 addContextItem: (item) => {
83 void messenger.request("addContextItem", {
84 item,
85 historyIndex,
86 });
87 },
88 selectedCode,
89 config,
90 fetch: (url, init) =>
91 fetchwithRequestOptions(
92 url,
93 {
94 ...init,
95 signal: abortController.signal,
96 },
97 config.requestOptions,
98 ),
99 completionOptions,
100 abortController,
101 });
102 let next = await gen.next();
103 while (!next.done) {
104 if (abortController.signal.aborted) {
105 next = await gen.return(errorPromptLog);
106 break;
107 }
108 if (next.value) {
109 yield {
110 role: "assistant",
111 content: next.value,
112 };
113 }
114 next = await gen.next();
115 }
116 if (!next.done) {
117 throw new Error("Will never happen");
118 }
119
120 return next.value;
121 } else {
122 const gen = model.streamChat(
123 messages,
124 abortController.signal,
125 completionOptions,
126 messageOptions,
127 );
128 let next = await gen.next();
129 while (!next.done) {
130 if (abortController.signal.aborted) {
131 next = await gen.return(errorPromptLog);
132 break;
133 }
134
135 const chunk = next.value;
136
137 yield chunk;
138 next = await gen.next();
139 }
140 if (config.experimental?.readResponseTTS && "completion" in next.value) {
141 void TTS.read(next.value?.completion);
142 }
143
144 void Telemetry.capture(
145 "chat",
146 {
147 model: model.model,
148 provider: model.providerName,
149 },
150 true,
151 );
152
153 void checkForFreeTrialExceeded(configHandler, messenger);
154
155 if (!next.done) {
156 throw new Error("Will never happen");
157 }
158
159 return next.value;
160 }
161 } catch (error) {
162 if (
163 error instanceof Error &&
164 error.message.toLowerCase().includes("premature close")
165 ) {
166 void Telemetry.capture(
167 "stream_premature_close_error",
168 {
169 model: model.model,
170 provider: model.providerName,
171 errorMessage: error.message,
172 context: legacySlashCommandData ? "slash_command" : "regular_chat",
173 ...(legacySlashCommandData && {
174 command: legacySlashCommandData.command.name,
175 }),
176 },
177 false,
178 );
179 }
180 throw error;
181 }
182}
183
184async function checkForFreeTrialExceeded(
185 configHandler: ConfigHandler,
186 messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
187) {
188 const { config } = await configHandler.getSerializedConfig();
189
190 // Only check if the user is using the free trial
191 if (config && !usesFreeTrialApiKey(config)) {
192 return;
193 }
194
195 try {
196 const freeTrialStatus =
197 await configHandler.controlPlaneClient.getFreeTrialStatus();
198 if (
199 freeTrialStatus &&
200 freeTrialStatus.chatCount &&
201 freeTrialStatus.chatCount > freeTrialStatus.chatLimit
202 ) {
203 void messenger.request("freeTrialExceeded", undefined);
204 }
205 } catch (error) {
206 console.error("Error checking free trial status:", error);
207 }
208}