Elffuss BraidHub

kikocis/continue public

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