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