Elffuss BraidHub

kikocis/continue public

401f69e2e4c4 · 4.5 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 if (!slashCommand.run) {
63 console.error(
64 `Slash command ${command.name} (${command.source}) has no run function`,
65 );
66 throw new Error(`Slash command not found`);
67 }
68
69 const gen = slashCommand.run({
70 input,
71 history: messages,
72 llm: model,
73 contextItems,
74 params: command.params,
75 ide,
76 addContextItem: (item) => {
77 void messenger.request("addContextItem", {
78 item,
79 historyIndex,
80 });
81 },
82 selectedCode,
83 config,
84 fetch: (url, init) =>
85 fetchwithRequestOptions(
86 url,
87 {
88 ...init,
89 signal: abortController.signal,
90 },
91 config.requestOptions,
92 ),
93 completionOptions,
94 abortController,
95 });
96 let next = await gen.next();
97 while (!next.done) {
98 if (abortController.signal.aborted) {
99 next = await gen.return(errorPromptLog);
100 break;
101 }
102 if (next.value) {
103 yield {
104 role: "assistant",
105 content: next.value,
106 };
107 }
108 next = await gen.next();
109 }
110 if (!next.done) {
111 throw new Error("Will never happen");
112 }
113
114 return next.value;
115 } else {
116 const gen = model.streamChat(
117 messages,
118 abortController.signal,
119 completionOptions,
120 );
121 let next = await gen.next();
122 while (!next.done) {
123 if (abortController.signal.aborted) {
124 next = await gen.return(errorPromptLog);
125 break;
126 }
127
128 const chunk = next.value;
129
130 yield chunk;
131 next = await gen.next();
132 }
133 if (config.experimental?.readResponseTTS && "completion" in next.value) {
134 void TTS.read(next.value?.completion);
135 }
136
137 void Telemetry.capture(
138 "chat",
139 {
140 model: model.model,
141 provider: model.providerName,
142 },
143 true,
144 );
145
146 void checkForFreeTrialExceeded(configHandler, messenger);
147
148 if (!next.done) {
149 throw new Error("Will never happen");
150 }
151
152 return next.value;
153 }
154}
155
156async function checkForFreeTrialExceeded(
157 configHandler: ConfigHandler,
158 messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
159) {
160 const { config } = await configHandler.getSerializedConfig();
161
162 // Only check if the user is using the free trial
163 if (config && !usesFreeTrialApiKey(config)) {
164 return;
165 }
166
167 try {
168 const freeTrialStatus =
169 await configHandler.controlPlaneClient.getFreeTrialStatus();
170 if (
171 freeTrialStatus &&
172 freeTrialStatus.chatCount &&
173 freeTrialStatus.chatCount > freeTrialStatus.chatLimit
174 ) {
175 void messenger.request("freeTrialExceeded", undefined);
176 }
177 } catch (error) {
178 console.error("Error checking free trial status:", error);
179 }
180}