Elffuss BraidHub

kikocis/continue public

c657d7bd6e88 · 8.7 KiBRawPermalink
1import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
2import { LLMFullCompletionOptions, ModelDescription, Tool } from "core";
3import { modelSupportsTools } from "core/llm/autodetect";
4import { getRuleId } from "core/llm/rules/getSystemMessageWithRules";
5import { ToCoreProtocol } from "core/protocol";
6import { BuiltInToolNames } from "core/tools/builtIn";
7import { selectActiveTools } from "../selectors/selectActiveTools";
8import { selectSelectedChatModel } from "../slices/configSlice";
9import {
10 abortStream,
11 addPromptCompletionPair,
12 setActive,
13 setAppliedRulesAtIndex,
14 setInactive,
15 setToolGenerated,
16 setWarningMessage,
17 streamUpdate,
18} from "../slices/sessionSlice";
19import { AppThunkDispatch, RootState, ThunkApiType } from "../store";
20import {
21 constructMessages,
22 getBaseSystemMessage,
23} from "../util/constructMessages";
24
25import { selectCurrentToolCalls } from "../selectors/selectToolCalls";
26import { callToolById } from "./callToolById";
27
28/**
29 * Handles the execution of tool calls that may be automatically accepted.
30 * Sets all tools as generated first, then executes auto-approved tool calls.
31 */
32async function handleToolCallExecution(
33 dispatch: AppThunkDispatch,
34 getState: () => RootState,
35): Promise<void> {
36 const newState = getState();
37 const toolSettings = newState.ui.toolSettings;
38 const allToolCallStates = selectCurrentToolCalls(newState);
39
40 // Only process tool calls that are in "generating" status (newly created during this streaming session)
41 const toolCallStates = allToolCallStates.filter(
42 (toolCallState) => toolCallState.status === "generating",
43 );
44
45 // If no generating tool calls, nothing to process
46 if (toolCallStates.length === 0) {
47 return;
48 }
49
50 // Check if ALL tool calls are auto-approved - if not, wait for user approval
51 const allAutoApproved = toolCallStates.every(
52 (toolCallState) =>
53 toolSettings[toolCallState.toolCall.function.name] ===
54 "allowedWithoutPermission",
55 );
56
57 // Set all tools as generated first
58 toolCallStates.forEach((toolCallState) => {
59 dispatch(
60 setToolGenerated({
61 toolCallId: toolCallState.toolCallId,
62 tools: newState.config.config.tools,
63 }),
64 );
65 });
66
67 // Only run if we have auto-approve for all
68 if (allAutoApproved && toolCallStates.length > 0) {
69 const toolCallPromises = toolCallStates.map(async (toolCallState) => {
70 const response = await dispatch(
71 callToolById({ toolCallId: toolCallState.toolCallId }),
72 );
73 unwrapResult(response);
74 });
75
76 await Promise.all(toolCallPromises);
77 }
78}
79
80/**
81 * Filters tools based on the selected model's capabilities.
82 * Returns either the edit file tool or search and replace tool, but not both.
83 */
84function filterToolsForModel(
85 tools: Tool[],
86 selectedModel: ModelDescription,
87): Tool[] {
88 const editFileTool = tools.find(
89 (tool) => tool.function.name === BuiltInToolNames.EditExistingFile,
90 );
91 const searchAndReplaceTool = tools.find(
92 (tool) => tool.function.name === BuiltInToolNames.SearchAndReplaceInFile,
93 );
94
95 // If we don't have both tools, return tools as-is
96 if (!editFileTool || !searchAndReplaceTool) {
97 return tools;
98 }
99
100 // Determine which tool to use based on the model
101 const shouldUseFindReplace = shouldUseFindReplaceEdits(selectedModel);
102
103 // Filter out the unwanted tool
104 return tools.filter((tool) => {
105 if (tool.function.name === BuiltInToolNames.EditExistingFile) {
106 return !shouldUseFindReplace;
107 }
108 if (tool.function.name === BuiltInToolNames.SearchAndReplaceInFile) {
109 return shouldUseFindReplace;
110 }
111 return true;
112 });
113}
114
115/**
116 * Determines whether to use search and replace tool instead of edit file
117 * Right now we only know that this is reliable with Claude models
118 */
119function shouldUseFindReplaceEdits(model: ModelDescription): boolean {
120 return model.model.includes("claude");
121}
122
123export const streamNormalInput = createAsyncThunk<
124 void,
125 {
126 legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"];
127 },
128 ThunkApiType
129>(
130 "chat/streamNormalInput",
131 async ({ legacySlashCommandData }, { dispatch, extra, getState }) => {
132 const state = getState();
133 const selectedChatModel = selectSelectedChatModel(state);
134
135 if (!selectedChatModel) {
136 throw new Error("No chat model selected");
137 }
138
139 // Get tools and filter them based on the selected model
140 const allActiveTools = selectActiveTools(state);
141 const activeTools = filterToolsForModel(allActiveTools, selectedChatModel);
142 const toolsSupported = modelSupportsTools(selectedChatModel);
143
144 // Construct completion options
145 let completionOptions: LLMFullCompletionOptions = {};
146 if (toolsSupported && activeTools.length > 0) {
147 completionOptions = {
148 tools: activeTools,
149 };
150 }
151
152 if (state.session.hasReasoningEnabled) {
153 completionOptions = {
154 ...completionOptions,
155 reasoning: true,
156 reasoningBudgetTokens: completionOptions.reasoningBudgetTokens ?? 2048,
157 };
158 }
159
160 // Construct messages (excluding system message)
161 const baseSystemMessage = getBaseSystemMessage(
162 state.session.mode,
163 selectedChatModel,
164 );
165
166 const withoutMessageIds = state.session.history.map((item) => {
167 const { id, ...messageWithoutId } = item.message;
168 return { ...item, message: messageWithoutId };
169 });
170 const { messages, appliedRules, appliedRuleIndex } = constructMessages(
171 withoutMessageIds,
172 baseSystemMessage,
173 state.config.config.rules,
174 state.ui.ruleSettings,
175 );
176
177 // TODO parallel tool calls will cause issues with this
178 // because there will be multiple tool messages, so which one should have applied rules?
179 dispatch(
180 setAppliedRulesAtIndex({
181 index: appliedRuleIndex,
182 appliedRules: appliedRules,
183 }),
184 );
185
186 dispatch(setActive());
187 // Remove the warning message before each compileChat call
188 dispatch(setWarningMessage(undefined));
189 const precompiledRes = await extra.ideMessenger.request("llm/compileChat", {
190 messages,
191 options: completionOptions,
192 });
193
194 if (precompiledRes.status === "error") {
195 throw new Error(precompiledRes.error);
196 }
197
198 const { compiledChatMessages, pruningStatus } = precompiledRes.content;
199
200 switch (pruningStatus) {
201 case "pruned":
202 dispatch(
203 setWarningMessage({
204 message: `Chat history exceeds model's context length (${state.config.config.selectedModelByRole.chat?.contextLength} tokens). Old messages will not be included.`,
205 level: "warning",
206 category: "exceeded-context-length",
207 }),
208 );
209 break;
210 case "deleted-last-input":
211 dispatch(
212 setWarningMessage({
213 message:
214 "The provided context items are too large. Please trim the context item to fit the model's context length or increase the model's context length by editing the configuration.",
215 level: "fatal",
216 category: "deleted-last-input",
217 }),
218 );
219 dispatch(setInactive());
220 return;
221 }
222
223 // Send request and stream response
224 const streamAborter = state.session.streamAborter;
225 const gen = extra.ideMessenger.llmStreamChat(
226 {
227 completionOptions,
228 title: selectedChatModel.title,
229 messages: compiledChatMessages,
230 legacySlashCommandData,
231 messageOptions: { precompiled: true },
232 },
233 streamAborter.signal,
234 );
235
236 let next = await gen.next();
237 while (!next.done) {
238 if (!getState().session.isStreaming) {
239 dispatch(abortStream());
240 break;
241 }
242
243 dispatch(streamUpdate(next.value));
244 next = await gen.next();
245 }
246
247 // Attach prompt log and end thinking for reasoning models
248 if (next.done && next.value) {
249 dispatch(addPromptCompletionPair([next.value]));
250
251 try {
252 extra.ideMessenger.post("devdata/log", {
253 name: "chatInteraction",
254 data: {
255 prompt: next.value.prompt,
256 completion: next.value.completion,
257 modelProvider: selectedChatModel.underlyingProviderName,
258 modelTitle: selectedChatModel.title,
259 sessionId: state.session.id,
260 ...(!!activeTools.length && {
261 tools: activeTools.map((tool) => tool.function.name),
262 }),
263 ...(appliedRules.length > 0 && {
264 rules: appliedRules.map((rule) => ({
265 id: getRuleId(rule),
266 rule: rule.rule,
267 })),
268 }),
269 },
270 });
271 } catch (e) {
272 console.error("Failed to send dev data interaction log", e);
273 }
274 }
275 dispatch(setInactive());
276 await handleToolCallExecution(dispatch, getState);
277 },
278);