Elffuss BraidHub

kikocis/continue public

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