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