consolidate streaming

This commit is contained in:
Dallin Romney 2025-03-18 19:48:03 -07:00
parent 6a45e67851
commit 688b10bbd5
12 changed files with 297 additions and 397 deletions

4
.vscode/launch.json vendored
View file

@ -12,8 +12,8 @@
"cwd": "${workspaceFolder}/extensions/vscode",
"args": [
// Pass a directory to manually test in
"/Users/dallin/Documents/code/continuedev/continue-extras/dlt-example",
"/Users/dallin/Documents/code/continuedev/continue-extras/dlt-example/start.py",
"${workspaceFolder}/manual-testing-sandbox",
"${workspaceFolder}/manual-testing-sandbox/test.js",
"--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode"
],
"pauseForSourceMap": false,

View file

@ -36,7 +36,6 @@ import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
import {
ChatMessage,
DiffLine,
PromptLog,
type ContextItemId,
@ -47,6 +46,7 @@ import {
import { isLocalAssistantFile } from "./config/loadLocalAssistants";
import { shouldIgnore } from "./indexing/shouldIgnore";
import { walkDirCache } from "./indexing/walkDir";
import { llmStreamChat } from "./llm/streamChat";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";
@ -486,72 +486,14 @@ export class Core {
}
});
async function* llmStreamChat(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
): AsyncGenerator<ChatMessage, PromptLog> {
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
// Stop TTS on new StreamChat
if (config.experimental?.readResponseTTS) {
void TTS.kill();
}
const model = await configHandler.llmFromTitle(msg.data.title);
const gen = model.streamChat(
msg.data.messages,
new AbortController().signal,
msg.data.completionOptions,
);
let next = await gen.next();
while (!next.done) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
next = await gen.return({
modelTitle: model.title ?? model.model,
completion: "",
prompt: "",
completionOptions: {
...msg.data.completionOptions,
model: model.model,
},
});
break;
}
const chunk = next.value;
yield chunk;
next = await gen.next();
}
if (config.experimental?.readResponseTTS && "completion" in next.value) {
void TTS.read(next.value?.completion);
}
void Telemetry.capture(
"chat",
{
model: model.model,
provider: model.providerName,
},
true,
);
if (!next.done) {
throw new Error("Will never happen");
}
return next.value;
}
on("llm/streamChat", (msg) =>
llmStreamChat(this.configHandler, this.abortedMessageIds, msg),
llmStreamChat(
this.configHandler,
this.abortedMessageIds,
msg,
ide,
this.messenger,
),
);
async function* llmStreamComplete(
@ -643,96 +585,6 @@ export class Core {
return await ChatDescriber.describe(currentModel, {}, msg.data.text);
});
async function* runNodeJsSlashCommand(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["command/run"][0]>,
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
): AsyncGenerator<string> {
const {
input,
history,
modelTitle,
slashCommandName,
contextItems,
params,
historyIndex,
selectedCode,
completionOptions,
} = msg.data;
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
const llm = await configHandler.llmFromTitle(modelTitle);
const slashCommand = config.slashCommands?.find(
(sc) => sc.name === slashCommandName,
);
if (!slashCommand) {
throw new Error(`Unknown slash command ${slashCommandName}`);
}
void Telemetry.capture(
"useSlashCommand",
{
name: slashCommandName,
},
true,
);
const checkActiveInterval = setInterval(() => {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
clearInterval(checkActiveInterval);
}
}, 100);
try {
for await (const content of slashCommand.run({
input,
history,
llm,
contextItems,
params,
ide,
addContextItem: (item) => {
void messenger.request("addContextItem", {
item,
historyIndex,
});
},
selectedCode,
config,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
completionOptions,
})) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
clearInterval(checkActiveInterval);
break;
}
if (content) {
yield content;
}
}
} catch (e) {
throw e;
} finally {
clearInterval(checkActiveInterval);
}
}
on("command/run", (msg) =>
runNodeJsSlashCommand(
this.configHandler,
this.abortedMessageIds,
msg,
this.messenger,
),
);
// Autocomplete
on("autocomplete/complete", async (msg) => {
const outcome =

149
core/llm/streamChat.ts Normal file
View file

@ -0,0 +1,149 @@
import { fetchwithRequestOptions } from "@continuedev/fetch";
import { ChatMessage, IDE, PromptLog } from "..";
import { ConfigHandler } from "../config/ConfigHandler";
import { FromCoreProtocol, ToCoreProtocol } from "../protocol";
import { IMessenger, Message } from "../protocol/messenger";
import { Telemetry } from "../util/posthog";
import { TTS } from "../util/tts";
export async function* llmStreamChat(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
ide: IDE,
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
): AsyncGenerator<ChatMessage, PromptLog> {
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
// Stop TTS on new StreamChat
if (config.experimental?.readResponseTTS) {
void TTS.kill();
}
const { title, legacySlashCommandData, completionOptions, messages } =
msg.data;
const model = await configHandler.llmFromTitle(title);
// Log to return in case of error
const errorPromptLog = {
modelTitle: model.title ?? model.model,
completion: "",
prompt: "",
completionOptions: {
...msg.data.completionOptions,
model: model.model,
},
};
if (legacySlashCommandData) {
const { command, contextItems, historyIndex, input, selectedCode } =
legacySlashCommandData;
const slashCommand = config.slashCommands?.find(
(sc) => sc.name === command.name,
);
if (!slashCommand) {
throw new Error(`Unknown slash command ${command.name}`);
}
void Telemetry.capture(
"useSlashCommand",
{
name: command.name,
},
true,
);
const gen = slashCommand.run({
input,
history: messages,
llm: model,
contextItems,
params: command.params,
ide,
addContextItem: (item) => {
void messenger.request("addContextItem", {
item,
historyIndex,
});
},
selectedCode,
config,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
completionOptions,
});
const checkActiveInterval = setInterval(() => {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
clearInterval(checkActiveInterval);
}
}, 100);
try {
let next = await gen.next();
while (!next.done) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
next = await gen.return(errorPromptLog);
clearInterval(checkActiveInterval);
break;
}
if (next.value) {
yield {
role: "assistant",
content: next.value,
};
}
next = await gen.next();
}
if (!next.done) {
throw new Error("Will never happen");
}
return next.value;
} catch (e) {
throw e;
} finally {
clearInterval(checkActiveInterval);
}
} else {
const gen = model.streamChat(
messages,
new AbortController().signal,
completionOptions,
);
let next = await gen.next();
while (!next.done) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
next = await gen.return(errorPromptLog);
break;
}
const chunk = next.value;
yield chunk;
next = await gen.next();
}
if (config.experimental?.readResponseTTS && "completion" in next.value) {
void TTS.read(next.value?.completion);
}
void Telemetry.capture(
"chat",
{
model: model.model,
provider: model.providerName,
},
true,
);
if (!next.done) {
throw new Error("Will never happen");
}
return next.value;
}
}

View file

@ -26,6 +26,7 @@ import type {
Session,
SessionMetadata,
SiteIndexingConfig,
SlashCommandDescription,
ToolCall,
} from "../";
import { GlobalContextModelSelections } from "../util/GlobalContext";
@ -101,20 +102,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"context/indexDocs": [{ reIndex: boolean }, void];
"autocomplete/cancel": [undefined, void];
"autocomplete/accept": [{ completionId: string }, void];
"command/run": [
{
input: string;
history: ChatMessage[];
modelTitle: string;
slashCommandName: string;
contextItems: ContextItemWithId[];
params: any;
historyIndex: number;
selectedCode: RangeInFile[];
completionOptions?: LLMFullCompletionOptions;
},
AsyncGenerator<string>,
];
"llm/complete": [
{
prompt: string;
@ -137,6 +124,13 @@ export type ToCoreFromIdeOrWebviewProtocol = {
messages: ChatMessage[];
completionOptions: LLMFullCompletionOptions;
title: string;
legacySlashCommandData?: {
command: SlashCommandDescription;
input: string;
contextItems: ContextItemWithId[];
historyIndex: number;
selectedCode: RangeInFile[];
};
},
AsyncGenerator<ChatMessage, PromptLog>,
];

View file

@ -35,7 +35,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"autocomplete/complete",
"autocomplete/cancel",
"autocomplete/accept",
"command/run",
"tts/kill",
"llm/complete",
"llm/streamComplete",

View file

@ -103,7 +103,6 @@ class MessageTypes {
"autocomplete/complete",
"autocomplete/cancel",
"autocomplete/accept",
"command/run",
"tts/kill",
"llm/complete",
"llm/streamComplete",

View file

@ -1,15 +1,18 @@
import { ChatMessage, IDE, LLMFullCompletionOptions, PromptLog } from "core";
import type { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol";
import { ChatMessage, IDE, PromptLog } from "core";
import type {
FromWebviewProtocol,
ToCoreProtocol,
ToWebviewProtocol,
} from "core/protocol";
import { Message } from "core/protocol/messenger";
import { MessageIde } from "core/protocol/messenger/messageIde";
import {
GeneratorReturnType,
GeneratorYieldType,
WebviewMessage,
WebviewProtocolGeneratorMessage,
WebviewSingleMessage,
WebviewSingleProtocolMessage,
} from "core/protocol/util";
import { MessageIde } from "core/protocol/messenger/messageIde";
import { Message } from "core/protocol/messenger";
import { createContext } from "react";
import { v4 as uuidv4 } from "uuid";
import "vscode-webview";
@ -50,10 +53,8 @@ export interface IIdeMessenger {
>;
llmStreamChat(
modelTitle: string,
cancelToken: AbortSignal | undefined,
messages: ChatMessage[],
options?: LLMFullCompletionOptions,
msg: ToCoreProtocol["llm/streamChat"][0],
cancelToken: AbortSignal,
): AsyncGenerator<ChatMessage[], PromptLog | undefined>;
ide: IDE;
@ -247,20 +248,10 @@ export class IdeMessenger implements IIdeMessenger {
}
async *llmStreamChat(
modelTitle: string,
cancelToken: AbortSignal | undefined,
messages: ChatMessage[],
options: LLMFullCompletionOptions = {},
msg: ToCoreProtocol["llm/streamChat"][0],
cancelToken: AbortSignal,
): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
const gen = this.streamRequest(
"llm/streamChat",
{
messages,
title: modelTitle,
completionOptions: options,
},
cancelToken,
);
const gen = this.streamRequest("llm/streamChat", msg, cancelToken);
let next = await gen.next();
while (!next.done) {

View file

@ -1,8 +1,7 @@
export { exitEditMode } from "./exitEditMode";
export { gatherContext } from "./gatherContext";
export { streamThunkWrapper } from "./streamThunkWrapper";
export { resetStateForNewMessage } from "./resetStateForNewMessage";
export { streamNormalInput } from "./streamNormalInput";
export { streamResponseThunk } from "./streamResponse";
export { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
export { streamSlashCommand } from "./streamSlashCommand";
export { streamThunkWrapper } from "./streamThunkWrapper";

View file

@ -1,5 +1,7 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ChatMessage, PromptLog } from "core";
import { ChatMessage } from "core";
import { modelSupportsTools } from "core/llm/autodetect";
import { ToCoreProtocol } from "core/protocol";
import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
import { selectDefaultModel } from "../slices/configSlice";
import {
@ -10,98 +12,109 @@ import {
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { callTool } from "./callTool";
import { modelSupportsTools } from "core/llm/autodetect";
export const streamNormalInput = createAsyncThunk<
void,
ChatMessage[],
{
messages: ChatMessage[];
legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"];
},
ThunkApiType
>("chat/streamNormalInput", async (messages, { dispatch, extra, getState }) => {
// Gather state
const state = getState();
const defaultModel = selectDefaultModel(state);
const toolSettings = state.ui.toolSettings;
const streamAborter = state.session.streamAborter;
const useTools = state.ui.useTools;
if (!defaultModel) {
throw new Error("Default model not defined");
}
const includeTools =
useTools &&
modelSupportsTools(defaultModel) &&
state.session.mode === "chat";
// Send request
const gen = extra.ideMessenger.llmStreamChat(
defaultModel.title,
streamAborter.signal,
messages,
includeTools
? {
tools: state.config.config.tools.filter(
(tool) => toolSettings[tool.function.name] !== "disabled",
),
}
: {},
);
// Stream response
let next = await gen.next();
while (!next.done) {
if (!getState().session.isStreaming) {
dispatch(abortStream());
break;
>(
"chat/streamNormalInput",
async (
{ messages, legacySlashCommandData },
{ dispatch, extra, getState },
) => {
// Gather state
const state = getState();
const defaultModel = selectDefaultModel(state);
const toolSettings = state.ui.toolSettings;
const streamAborter = state.session.streamAborter;
const useTools = state.ui.useTools;
if (!defaultModel) {
throw new Error("Default model not defined");
}
dispatch(streamUpdate(next.value));
next = await gen.next();
}
const includeTools =
useTools &&
modelSupportsTools(defaultModel) &&
state.session.mode === "chat";
// Attach prompt log
if (next.done && next.value) {
dispatch(addPromptCompletionPair([next.value]));
// Send request
const gen = extra.ideMessenger.llmStreamChat(
{
completionOptions: includeTools
? {
tools: state.config.config.tools.filter(
(tool) => toolSettings[tool.function.name] !== "disabled",
),
}
: {},
title: defaultModel.title,
messages,
legacySlashCommandData,
},
streamAborter.signal,
);
try {
if (state.session.mode === "chat") {
extra.ideMessenger.post("devdata/log", {
name: "chatInteraction",
data: {
prompt: next.value.prompt,
completion: next.value.completion,
modelProvider: defaultModel.provider,
modelTitle: defaultModel.title,
sessionId: state.session.id,
},
});
// Stream response
let next = await gen.next();
while (!next.done) {
if (!getState().session.isStreaming) {
dispatch(abortStream());
break;
}
// else if (state.session.mode === "edit") {
// extra.ideMessenger.post("devdata/log", {
// name: "editInteraction",
// data: {
// prompt: next.value.prompt,
// completion: next.value.completion,
// modelProvider: defaultModel.provider,
// modelTitle: defaultModel.title,
// },
// });
// }
} catch (e) {
console.error("Failed to send dev data interaction log", e);
}
}
// If it's a tool call that is automatically accepted, we should call it
const toolCallState = selectCurrentToolCall(getState());
if (toolCallState) {
dispatch(setToolGenerated());
if (
toolSettings[toolCallState.toolCall.function.name] ===
"allowedWithoutPermission"
) {
const response = await dispatch(callTool());
unwrapResult(response);
dispatch(streamUpdate(next.value));
next = await gen.next();
}
}
});
// Attach prompt log
if (next.done && next.value) {
dispatch(addPromptCompletionPair([next.value]));
try {
if (state.session.mode === "chat") {
extra.ideMessenger.post("devdata/log", {
name: "chatInteraction",
data: {
prompt: next.value.prompt,
completion: next.value.completion,
modelProvider: defaultModel.provider,
modelTitle: defaultModel.title,
sessionId: state.session.id,
},
});
}
// else if (state.session.mode === "edit") {
// extra.ideMessenger.post("devdata/log", {
// name: "editInteraction",
// data: {
// prompt: next.value.prompt,
// completion: next.value.completion,
// modelProvider: defaultModel.provider,
// modelTitle: defaultModel.title,
// },
// });
// }
} catch (e) {
console.error("Failed to send dev data interaction log", e);
}
}
// If it's a tool call that is automatically accepted, we should call it
const toolCallState = selectCurrentToolCall(getState());
if (toolCallState) {
dispatch(setToolGenerated());
if (
toolSettings[toolCallState.toolCall.function.name] ===
"allowedWithoutPermission"
) {
const response = await dispatch(callTool());
unwrapResult(response);
}
}
},
);

View file

@ -19,7 +19,6 @@ import { ThunkApiType } from "../store";
import { gatherContext } from "./gatherContext";
import { resetStateForNewMessage } from "./resetStateForNewMessage";
import { streamNormalInput } from "./streamNormalInput";
import { streamSlashCommand } from "./streamSlashCommand";
import { streamThunkWrapper } from "./streamThunkWrapper";
import { updateFileSymbolsFromFiles } from "./updateFileSymbols";
@ -136,29 +135,31 @@ export const streamResponseThunk = createAsyncThunk<
let commandAndInput = getSlashCommandForInput(content, slashCommands);
if (!commandAndInput) {
unwrapResult(await dispatch(streamNormalInput(messages)));
unwrapResult(await dispatch(streamNormalInput({ messages })));
} else {
const [slashCommand, commandInput] = commandAndInput;
posthog.capture("step run", {
step_name: slashCommand.name,
params: {},
});
// if (slashCommand.name === "multifile-edit") {
// dispatch(setIsInMultifileEdit(true));
// }
const result = await dispatch(
streamSlashCommand({
messages,
slashCommand,
input: commandInput,
historyIndex: inputIndex,
selectedCode,
contextItems: [],
}),
// TODO - handle non-legacy slash commands, update messages if relevant
// Pass around isFromConfigTs
unwrapResult(
await dispatch(
streamNormalInput({
messages,
legacySlashCommandData: {
command: slashCommand,
contextItems: selectedContextItems,
historyIndex: inputIndex,
input: commandInput,
selectedCode,
},
}),
),
);
unwrapResult(result);
}
}),
);

View file

@ -65,8 +65,7 @@ export const streamResponseAfterToolCall = createAsyncThunk<
defaultModel,
useTools,
);
const output = await dispatch(streamNormalInput(messages));
unwrapResult(output);
unwrapResult(await dispatch(streamNormalInput({ messages })));
}),
);
},

View file

@ -1,96 +0,0 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import {
ChatMessage,
ContextItemWithId,
RangeInFile,
SlashCommandDescription,
} from "core";
import { modelSupportsTools } from "core/llm/autodetect";
import { selectDefaultModel } from "../slices/configSlice";
import { abortStream, streamUpdate } from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
export const streamSlashCommand = createAsyncThunk<
void,
{
messages: ChatMessage[];
slashCommand: SlashCommandDescription;
input: string;
historyIndex: number;
selectedCode: RangeInFile[];
contextItems: ContextItemWithId[];
},
ThunkApiType
>(
"chat/streamSlashCommand",
async (
{ messages, selectedCode, slashCommand, input, historyIndex, contextItems },
{ dispatch, getState, extra },
) => {
const state = getState();
const defaultModel = selectDefaultModel(state);
const isStreaming = state.session.isStreaming;
const streamAborter = state.session.streamAborter;
const toolSettings = state.ui.toolSettings;
if (!defaultModel) {
throw new Error("Default model not defined");
}
const useTools = state.ui.useTools;
const includeTools =
useTools &&
modelSupportsTools(defaultModel) &&
state.session.mode === "chat";
const modelTitle = defaultModel.title;
const checkActiveInterval = setInterval(() => {
if (!isStreaming) {
dispatch(abortStream());
clearInterval(checkActiveInterval);
}
}, 100);
for await (const update of extra.ideMessenger.streamRequest(
"command/run",
{
input,
history: messages,
modelTitle,
slashCommandName: slashCommand.name,
contextItems,
params: slashCommand.params,
historyIndex,
selectedCode,
completionOptions: includeTools
? {
// Temporarily commented out until slash commands are hooked up to the tool use feedback loop
// tools: state.config.config.tools.filter(
// (tool) => toolSettings[tool.function.name] !== "disabled",
// ),
}
: {},
},
streamAborter.signal,
)) {
if (!getState().session.isStreaming) {
dispatch(abortStream());
break;
}
for (const item of update) {
if (typeof item === "string") {
dispatch(
streamUpdate([
{
role: "assistant",
content: item,
},
]),
);
}
}
}
clearInterval(checkActiveInterval);
},
);