Elffuss BraidHub

kikocis/continue public

f53b8f6ce186 · 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 abortController,
89 });
90 let next = await gen.next();
91 while (!next.done) {
92 if (abortController.signal.aborted) {
93 next = await gen.return(errorPromptLog);
94 break;
95 }
96 if (next.value) {
97 yield {
98 role: "assistant",
99 content: next.value,
100 };
101 }
102 next = await gen.next();
103 }
104 if (!next.done) {
105 throw new Error("Will never happen");
106 }
107
108 return next.value;
109 } else {
110 const gen = model.streamChat(
111 messages,
112 abortController.signal,
113 completionOptions,
114 );
115 let next = await gen.next();
116 while (!next.done) {
117 if (abortController.signal.aborted) {
118 next = await gen.return(errorPromptLog);
119 break;
120 }
121
122 const chunk = next.value;
123
124 yield chunk;
125 next = await gen.next();
126 }
127 if (config.experimental?.readResponseTTS && "completion" in next.value) {
128 void TTS.read(next.value?.completion);
129 }
130
131 void Telemetry.capture(
132 "chat",
133 {
134 model: model.model,
135 provider: model.providerName,
136 },
137 true,
138 );
139
140 void checkForFreeTrialExceeded(configHandler, messenger);
141
142 if (!next.done) {
143 throw new Error("Will never happen");
144 }
145
146 return next.value;
147 }
148}
149
150async function checkForFreeTrialExceeded(
151 configHandler: ConfigHandler,
152 messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
153) {
154 const { config } = await configHandler.getSerializedConfig();
155
156 // Only check if the user is using the free trial
157 if (config && !usesFreeTrialApiKey(config)) {
158 return;
159 }
160
161 try {
162 const freeTrialStatus =
163 await configHandler.controlPlaneClient.getFreeTrialStatus();
164 if (
165 freeTrialStatus &&
166 freeTrialStatus.chatCount &&
167 freeTrialStatus.chatCount > freeTrialStatus.chatLimit
168 ) {
169 void messenger.request("freeTrialExceeded", undefined);
170 }
171 } catch (error) {
172 console.error("Error checking free trial status:", error);
173 }
174}