Elffuss BraidHub

kikocis/continue public

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