From e2bd9cc2b7236a3959fa42baa73d303a9622c4b6 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 15 Nov 2024 09:43:40 -0800 Subject: [PATCH 001/105] WIP on tools --- core/config/load.ts | 2 ++ core/core.ts | 29 +++++++++++++++++++--- core/index.d.ts | 24 +++++++++++++++++- core/llm/llms/OpenAI.ts | 38 ++++++++++++++++++++++------- core/protocol/core.ts | 3 +-- core/tools/index.ts | 26 ++++++++++++++++++++ extensions/vscode/package-lock.json | 4 +-- gui/src/context/IdeMessenger.ts | 2 +- gui/src/hooks/useChatHandler.ts | 5 ++-- gui/src/pages/gui/Chat.tsx | 9 +++++++ gui/src/pages/gui/ToolCallDiv.tsx | 8 ++++++ gui/src/redux/slices/stateSlice.ts | 35 +++++++++++++++++++++++--- 12 files changed, 160 insertions(+), 25 deletions(-) create mode 100644 core/tools/index.ts create mode 100644 gui/src/pages/gui/ToolCallDiv.tsx diff --git a/core/config/load.ts b/core/config/load.ts index b692b36bf..25a9b510d 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -58,6 +58,7 @@ import { readAllGlobalPromptFiles, } from "../util/paths"; +import { makeCreateNewFileTool } from "../tools"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -335,6 +336,7 @@ async function intermediateToFinalConfig( ...model.requestOptions, ...config.requestOptions, }; + model.completionOptions.tools = [makeCreateNewFileTool(ide)]; } if (allowFreeTrial) { diff --git a/core/core.ts b/core/core.ts index 6df1482ef..464f8a5e3 100644 --- a/core/core.ts +++ b/core/core.ts @@ -83,7 +83,7 @@ export class Core { constructor( private readonly messenger: IMessenger, private readonly ide: IDE, - private readonly onWrite: (text: string) => Promise = async () => { }, + private readonly onWrite: (text: string) => Promise = async () => {}, ) { // Ensure .continue directory is created setupInitialDotContinueDirectory(); @@ -174,7 +174,7 @@ export class Core { this.configHandler, ide, getLlm, - (e) => { }, + (e) => {}, (..._) => Promise.resolve([]), ); @@ -404,8 +404,29 @@ export class Core { }); break; } + + const chunk = next.value; + + // if (chunk.toolCalls?.length) { + // for (const toolCall of chunk.toolCalls) { + // const tool = model.completionOptions.tools?.find( + // (tool) => tool.function.name === toolCall.function.name, + // ); + // if (!tool) { + // continue; + // } + // const response = await tool?.action(toolCall.function.arguments); + + // yield { + // role: "assistant", + // content: response, + // toolCalls: [toolCall], + // }; + // } + // } + // @ts-ignore - yield { content: next.value.content }; + yield { content: chunk }; next = await gen.next(); } @@ -684,7 +705,7 @@ export class Core { await codebaseIndexer.clearIndexes(); } - const dirs = data?.dirs ?? await this.ide.getWorkspaceDirs(); + const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs()); await this.refreshCodebaseIndex(dirs); }); on("index/setPaused", (msg) => { diff --git a/core/index.d.ts b/core/index.d.ts index 1bad9fd74..039455521 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -252,7 +252,7 @@ export interface CompletionOptions extends BaseCompletionOptions { model: string; } -export type ChatMessageRole = "user" | "assistant" | "system"; +export type ChatMessageRole = "user" | "assistant" | "system" | "tool"; export interface MessagePart { type: "text" | "imageUrl"; @@ -262,9 +262,19 @@ export interface MessagePart { export type MessageContent = string | MessagePart[]; +export interface ToolCall { + id: string; + type: "function"; + function: { + name: string; + arguments: string; + }; +} + export interface ChatMessage { role: ChatMessageRole; content: MessageContent; + toolCalls?: ToolCall[]; } export interface ContextItemId { @@ -805,6 +815,17 @@ interface Prediction { }[]; } +export interface Tool { + type: "function"; + function: { + name: string; + description?: string; + parameters?: Record; + strict?: boolean | null; + }; + action: (parameters: any) => Promise; +} + interface BaseCompletionOptions { temperature?: number; topP?: number; @@ -821,6 +842,7 @@ interface BaseCompletionOptions { raw?: boolean; stream?: boolean; prediction?: Prediction; + tools?: Tool[]; } export interface ModelCapability { diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 168e0afff..5a524c1ad 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -96,14 +96,16 @@ class OpenAI extends BaseLLM { } private supportsPrediction(model: string): boolean { - return [ - "gpt-4o-mini", - "gpt-4o" - ].includes(model); + return ["gpt-4o-mini", "gpt-4o"].includes(model); } protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) { const url = new URL(this.apiBase!); + const tools = options.tools?.map((tool) => { + const { action, ...restOfTool } = tool; + return restOfTool; + }); + const finalOptions: any = { messages: messages.map(this._convertMessage), model: this._convertModelName(options.model), @@ -120,11 +122,12 @@ class OpenAI extends BaseLLM { : url.host === "api.deepseek.com" ? options.stop?.slice(0, 16) : url.port === "1337" || - url.host === "api.openai.com" || - url.host === "api.groq.com" || - this.apiType === "azure" + url.host === "api.openai.com" || + url.host === "api.groq.com" || + this.apiType === "azure" ? options.stop?.slice(0, 4) : options.stop, + tools, }; // OpenAI o1-preview and o1-mini: @@ -143,10 +146,12 @@ class OpenAI extends BaseLLM { } if (options.prediction && this.supportsPrediction(options.model)) { - if (finalOptions.presence_penalty) { // prediction doesn't support > 0 + if (finalOptions.presence_penalty) { + // prediction doesn't support > 0 finalOptions.presence_penalty = undefined; } - if (finalOptions.frequency_penalty) { // prediction doesn't support > 0 + if (finalOptions.frequency_penalty) { + // prediction doesn't support > 0 finalOptions.frequency_penalty = undefined; } finalOptions.max_completion_tokens = undefined; @@ -279,6 +284,21 @@ class OpenAI extends BaseLLM { for await (const value of streamSse(response)) { if (value.choices?.[0]?.delta?.content) { yield value.choices[0].delta; + } else if (value.choices?.[0]?.delta?.tool_calls) { + yield { + role: "assistant", + content: "", + toolCalls: value.choices?.[0]?.delta?.tool_calls.map( + (tool_call: any) => ({ + id: tool_call.id, + type: tool_call.type, + function: { + name: tool_call.name, + arguments: tool_call.arguments, + }, + }), + ), + }; } } } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 2c9af1433..196192a38 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -9,7 +9,6 @@ import type { DiffLine, IdeSettings, LLMFullCompletionOptions, - MessageContent, ModelDescription, ModelRoles, PersistedSessionInfo, @@ -119,7 +118,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { completionOptions: LLMFullCompletionOptions; title: string; }, - ProtocolGeneratorType, + ProtocolGeneratorType, ]; streamDiffLines: [ { diff --git a/core/tools/index.ts b/core/tools/index.ts new file mode 100644 index 000000000..d7119acaa --- /dev/null +++ b/core/tools/index.ts @@ -0,0 +1,26 @@ +import { IDE, Tool } from ".."; + +export const makeCreateNewFileTool = (ide: IDE): Tool => ({ + type: "function", + action: async (...args: any) => { + await ide.writeFile(args[0], args[1]); + }, + function: { + name: "create_new_file", + description: "Create a new file", + parameters: { + type: "object", + required: ["filePath", "contents"], + properties: { + filePath: { + type: "string", + description: "The path where the new file should be created", + }, + contents: { + type: "string", + description: "The contents to write to the new file", + }, + }, + }, + }, +}); diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 24930d980..29ac4731f 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.229", + "version": "0.9.230", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.229", + "version": "0.9.230", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.ts index 0b5329c61..fcdcaea91 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.ts @@ -215,7 +215,7 @@ export class IdeMessenger implements IIdeMessenger { let next = await gen.next(); while (!next.done) { - yield { role: "user", content: next.value }; + yield next.value; next = await gen.next(); } diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 2e35acc53..a66debf80 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -89,9 +89,8 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { abortController.abort(); break; } - dispatch( - streamUpdate(stripImages((next.value as ChatMessage).content)), - ); + console.log(".......", (next.value as any).role); + dispatch(streamUpdate(next.value as ChatMessage)); next = await gen.next(); } diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 78bbcd262..1b8a1990d 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -62,6 +62,7 @@ import { } from "../../util"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; +import { ToolCallDiv } from "./ToolCallDiv"; const StopButton = styled.div` background-color: ${vscBackground}; @@ -331,6 +332,7 @@ export function Chat() { dispatch(newSession()); }} > + {item.message.role}-{JSON.stringify(item.message)} {item.message.role === "user" ? ( { @@ -341,6 +343,13 @@ export function Chat() { editorState={item.editorState} contextItems={item.contextItems} /> + ) : item.message.role === "assistant" && + item.message.toolCalls ? ( +
+ {item.message.toolCalls?.map((toolCall) => { + return ; + })} +
) : (
{props.toolCall.function.name}...
; +} diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index e3ce22eb6..c2d314008 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -188,6 +188,7 @@ export const stateSlice = createSlice({ editorState: JSONContent; }>, ) => { + console.log("OAEJFOIJOJOJAJ"); state.history.push({ message: { role: "user", content: "", id: uuidv4() }, contextItems: state.contextItems, @@ -215,6 +216,7 @@ export const stateSlice = createSlice({ contextItems?: ContextItemWithId[]; }>, ) => { + console.log("aoiujnnnnnnn"); if (payload.index >= state.history.length) { state.history.push({ message: { ...payload.message, id: uuidv4() }, @@ -256,10 +258,37 @@ export const stateSlice = createSlice({ state.isGatheringContext = false; state.active = false; }, - streamUpdate: (state, action: PayloadAction) => { + streamUpdate: (state, action: PayloadAction) => { if (state.history.length) { - state.history[state.history.length - 1].message.content += - action.payload; + const lastMessage = state.history[state.history.length - 1]; + + if ( + action.payload.role && + lastMessage.message.role !== action.payload.role + ) { + console.log("NEW: ", action.payload); + // Create a new message + state.history.push({ + contextItems: [], + message: { id: "NONE", ...action.payload }, + }); + } else { + console.log("ABC: ", action.payload); + // Add to the existing message + const msg = state.history[state.history.length - 1].message; + if (action.payload.content) { + msg.content += stripImages(action.payload.content); + } else if (action.payload.toolCalls) { + action.payload.toolCalls.forEach((toolCall, i) => { + if (msg.toolCalls.length < i) { + msg.toolCalls.push(toolCall); + } else { + msg.toolCalls[i].function.arguments += + toolCall.function.arguments; + } + }); + } + } } }, newSession: ( From a0ce651bc7407d597772591da44f38dc9a83cb00 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 17 Nov 2024 16:30:09 -0800 Subject: [PATCH 002/105] fix openai function call streaming --- core/llm/llms/OpenAI.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 5a524c1ad..99df30f32 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -293,8 +293,8 @@ class OpenAI extends BaseLLM { id: tool_call.id, type: tool_call.type, function: { - name: tool_call.name, - arguments: tool_call.arguments, + name: tool_call.function.name, + arguments: tool_call.function.arguments, }, }), ), From 5b09955701495235ffe439af1f265a96a199263c Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 17 Nov 2024 16:30:40 -0800 Subject: [PATCH 003/105] update ChatMessage type with ToolCallDelta (should have an entirely separate ChatMessageDelta) --- core/index.d.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/core/index.d.ts b/core/index.d.ts index 039455521..76e68702c 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -271,10 +271,19 @@ export interface ToolCall { }; } +export interface ToolCallDelta { + id?: string; + type?: "function"; + function?: { + name?: string; + arguments?: string[]; + }; +} + export interface ChatMessage { role: ChatMessageRole; content: MessageContent; - toolCalls?: ToolCall[]; + toolCalls?: ToolCallDelta[]; } export interface ContextItemId { From ac62fed5e8593747ca2e3f44588f164a28dff4db Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 17 Nov 2024 16:30:54 -0800 Subject: [PATCH 004/105] don't assume streams to GUI are always strings --- gui/src/context/IdeMessenger.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.ts index fcdcaea91..43fc7ef56 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.ts @@ -156,7 +156,7 @@ export class IdeMessenger implements IIdeMessenger { this.post(messageType, data, messageId); - let buffer = ""; + const buffer: any[] = []; let index = 0; let done = false; let returnVal = undefined; @@ -169,7 +169,7 @@ export class IdeMessenger implements IIdeMessenger { done = true; returnVal = responseData; } else { - buffer += responseData.content; + buffer.push(responseData.content); } } }; @@ -181,16 +181,16 @@ export class IdeMessenger implements IIdeMessenger { while (!done) { if (buffer.length > index) { - const chunk = buffer.slice(index); - index = buffer.length; + const chunk = buffer[index]; + index++; yield chunk; } await new Promise((resolve) => setTimeout(resolve, 50)); } - if (buffer.length > index) { - const chunk = buffer.slice(index); - index = buffer.length; + while (buffer.length > index) { + const chunk = buffer[index]; + index++; yield chunk; } From e25eceaceeca149055b35d87ae46aa5f1ca62315 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 17 Nov 2024 16:39:30 -0800 Subject: [PATCH 005/105] fix state updates --- core/index.d.ts | 2 +- gui/src/redux/slices/stateSlice.ts | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 76e68702c..8c3f44f5e 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -276,7 +276,7 @@ export interface ToolCallDelta { type?: "function"; function?: { name?: string; - arguments?: string[]; + arguments?: string; }; } diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index c2d314008..db6dbf859 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -273,14 +273,16 @@ export const stateSlice = createSlice({ message: { id: "NONE", ...action.payload }, }); } else { - console.log("ABC: ", action.payload); // Add to the existing message const msg = state.history[state.history.length - 1].message; if (action.payload.content) { msg.content += stripImages(action.payload.content); } else if (action.payload.toolCalls) { + if (!msg.toolCalls) { + msg.toolCalls = []; + } action.payload.toolCalls.forEach((toolCall, i) => { - if (msg.toolCalls.length < i) { + if (msg.toolCalls.length <= i) { msg.toolCalls.push(toolCall); } else { msg.toolCalls[i].function.arguments += From 59bb5f8246a22974ad0637fce84aa6856fe49d25 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 17 Nov 2024 17:21:45 -0800 Subject: [PATCH 006/105] UI for create_new_file tool --- core/tools/index.ts | 4 +- .../StepContainerPreToolbar.tsx | 21 +++-- .../markdown/SyntaxHighlightedPre.tsx | 2 +- gui/src/pages/gui/Chat.tsx | 3 +- gui/src/pages/gui/ToolCallDiv.tsx | 8 -- gui/src/pages/gui/ToolCallDiv/CreateFile.tsx | 29 ++++++ gui/src/pages/gui/ToolCallDiv/index.tsx | 93 +++++++++++++++++++ 7 files changed, 139 insertions(+), 21 deletions(-) delete mode 100644 gui/src/pages/gui/ToolCallDiv.tsx create mode 100644 gui/src/pages/gui/ToolCallDiv/CreateFile.tsx create mode 100644 gui/src/pages/gui/ToolCallDiv/index.tsx diff --git a/core/tools/index.ts b/core/tools/index.ts index d7119acaa..ad6767d9b 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -10,9 +10,9 @@ export const makeCreateNewFileTool = (ide: IDE): Tool => ({ description: "Create a new file", parameters: { type: "object", - required: ["filePath", "contents"], + required: ["filepath", "contents"], properties: { - filePath: { + filepath: { type: "string", description: "The path where the new file should be created", }, diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index ac13c6d54..6f8bf9224 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -55,6 +55,8 @@ export interface StepContainerPreToolbarProps { codeBlockIndex: number; // To track which codeblock we are applying range?: string; children: any; + expanded?: boolean; + hideApply?: boolean; } export default function StepContainerPreToolbar( @@ -67,7 +69,9 @@ export default function StepContainerPreToolbar( const isMultifileEdit = useSelector( (state: RootState) => state.state.isInMultifileEdit, ); - const [isExpanded, setIsExpanded] = useState(isMultifileEdit ? false : true); + const [isExpanded, setIsExpanded] = useState( + props.expanded ?? (isMultifileEdit ? false : true), + ); const [codeBlockContent, setCodeBlockContent] = useState(""); const isChatActive = useSelector((state: RootState) => state.state.active); const onClickApply = useApplyCodeBlock({ @@ -179,7 +183,6 @@ export default function StepContainerPreToolbar( /> -
{isGeneratingCodeBlock && ( - + {props.hideApply || ( + + )} )}
diff --git a/gui/src/components/markdown/SyntaxHighlightedPre.tsx b/gui/src/components/markdown/SyntaxHighlightedPre.tsx index a3caba685..6e2be08f2 100644 --- a/gui/src/components/markdown/SyntaxHighlightedPre.tsx +++ b/gui/src/components/markdown/SyntaxHighlightedPre.tsx @@ -1,6 +1,6 @@ import { useContext } from "react"; import styled from "styled-components"; -import { vscForeground, defaultBorderRadius } from ".."; +import { defaultBorderRadius, vscForeground } from ".."; import { VscThemeContext } from "../../context/VscTheme"; const generateThemeStyles = (theme: any) => { diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 1b8a1990d..0b1b1756c 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -332,7 +332,6 @@ export function Chat() { dispatch(newSession()); }} > - {item.message.role}-{JSON.stringify(item.message)} {item.message.role === "user" ? ( { @@ -347,7 +346,7 @@ export function Chat() { item.message.toolCalls ? (
{item.message.toolCalls?.map((toolCall) => { - return ; + return ; })}
) : ( diff --git a/gui/src/pages/gui/ToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv.tsx deleted file mode 100644 index dc1790c14..000000000 --- a/gui/src/pages/gui/ToolCallDiv.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { ToolCall } from "core"; - -interface ToolCallDivProps { - toolCall: ToolCall; -} -export function ToolCallDiv(props: ToolCallDivProps) { - return
{props.toolCall.function.name}...
; -} diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx new file mode 100644 index 000000000..e1e65981e --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -0,0 +1,29 @@ +import StepContainerPreToolbar from "../../../components/markdown/StepContainerPreToolbar"; +import { SyntaxHighlightedPre } from "../../../components/markdown/SyntaxHighlightedPre"; + +interface CreateFileToolCallProps { + filepath: string; + fileContents: string; +} + +export function CreateFile(props: CreateFileToolCallProps) { + return ( + <> +

Continue wants to create a file:

+ + + + {props.fileContents} + + + + ); +} diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx new file mode 100644 index 000000000..a505137d8 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -0,0 +1,93 @@ +import { ToolCall } from "core"; +import styled from "styled-components"; +import { + defaultBorderRadius, + lightGray, + vscButtonBackground, + vscButtonForeground, +} from "../../../components"; +import { CreateFile } from "./CreateFile"; + +const Container = styled.div` + margin: 8px; + overflow: hidden; +`; + +const ButtonContainer = styled.div` + display: flex; + gap: 8px; + margin-top: 12px; +`; + +const Button = styled.button` + color: ${vscButtonForeground}; + padding: 6px; + border-radius: ${defaultBorderRadius}; + flex: 1; + + &:hover { + cursor: pointer; + opacity: 0.8; + } +`; + +const AcceptButton = styled(Button)` + border: none; + background-color: ${vscButtonBackground}; + color: ${vscButtonForeground}; + + &:hover { + cursor: pointer; + } +`; + +const RejectButton = styled(Button)` + border: 1px solid ${lightGray}; + background-color: transparent; +`; + +interface ToolCallDivProps { + toolCall: ToolCall; +} + +function incrementalParseJson(raw: string): any { + try { + return JSON.parse(raw); + } catch (e) { + return {}; + } +} + +function FunctionSpecificToolCallDiv(toolCall: ToolCall) { + const args = incrementalParseJson(toolCall.function.arguments); + + switch (toolCall.function.name) { + case "create_new_file": + return ( + + ); + default: + return ( + <> +
{toolCall.function.name}
+ {Object.entries(args)?.map(([key, value]) => ( +
+ {key}: {JSON.stringify(value)} +
+ ))} + + ); + } +} + +export function ToolCallDiv(props: ToolCallDivProps) { + return ( + + + + Cancel + Continue + + + ); +} From 0c4f80bca864f126ee3283b8faa4556ee2da8b11 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 17 Nov 2024 17:58:18 -0800 Subject: [PATCH 007/105] run terminal command tool --- core/config/load.ts | 7 +++-- core/tools/index.ts | 22 ++++++++++++++ gui/src/hooks/useChatHandler.ts | 1 - gui/src/pages/gui/ToolCallDiv/CreateFile.tsx | 4 +-- .../gui/ToolCallDiv/RunTerminalCommand.tsx | 29 +++++++++++++++++++ gui/src/pages/gui/ToolCallDiv/index.tsx | 3 ++ 6 files changed, 61 insertions(+), 5 deletions(-) create mode 100644 gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx diff --git a/core/config/load.ts b/core/config/load.ts index 25a9b510d..b199e0e58 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -58,7 +58,7 @@ import { readAllGlobalPromptFiles, } from "../util/paths"; -import { makeCreateNewFileTool } from "../tools"; +import { makeCreateNewFileTool, runTerminalCommandTool } from "../tools"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -336,7 +336,10 @@ async function intermediateToFinalConfig( ...model.requestOptions, ...config.requestOptions, }; - model.completionOptions.tools = [makeCreateNewFileTool(ide)]; + model.completionOptions.tools = [ + makeCreateNewFileTool(ide), + runTerminalCommandTool(ide), + ]; } if (allowFreeTrial) { diff --git a/core/tools/index.ts b/core/tools/index.ts index ad6767d9b..aec23de36 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -24,3 +24,25 @@ export const makeCreateNewFileTool = (ide: IDE): Tool => ({ }, }, }); + +export const runTerminalCommandTool = (ide: IDE): Tool => ({ + type: "function", + action: async (...args) => { + await ide.runCommand(args[0]); + }, + function: { + name: "run_terminal_command", + description: "Run a terminal command in the current directory", + parameters: { + type: "object", + required: ["command"], + properties: { + command: { + type: "string", + description: + "The command to run. This will be passed directly into the shell.", + }, + }, + }, + }, +}); diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index a66debf80..baf2310c6 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -89,7 +89,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { abortController.abort(); break; } - console.log(".......", (next.value as any).role); dispatch(streamUpdate(next.value as ChatMessage)); next = await gen.next(); } diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index e1e65981e..5dbdaf340 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -11,10 +11,10 @@ export function CreateFile(props: CreateFileToolCallProps) { <>

Continue wants to create a file:

+

Continue wants to run a terminal command:

+ + + + + {props.command} + + + + ); +} diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index a505137d8..dbe7c3bed 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -7,6 +7,7 @@ import { vscButtonForeground, } from "../../../components"; import { CreateFile } from "./CreateFile"; +import { RunTerminalCommand } from "./RunTerminalCommand"; const Container = styled.div` margin: 8px; @@ -66,6 +67,8 @@ function FunctionSpecificToolCallDiv(toolCall: ToolCall) { return ( ); + case "run_terminal_command": + return ; default: return ( <> From 47dd44da557ca30ea17e46f0e7ca6a6e60786e5c Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 17 Nov 2024 18:36:45 -0800 Subject: [PATCH 008/105] run tools --- core/core.ts | 7 +++++++ core/protocol/core.ts | 2 ++ core/protocol/passThrough.ts | 3 ++- core/tools/index.ts | 27 +++++++++++++++++++------ extensions/vscode/package.json | 6 ++++++ gui/src/pages/gui/Chat.tsx | 3 +++ gui/src/pages/gui/ToolCallDiv/index.tsx | 25 +++++++++++++++++++++-- gui/src/redux/slices/stateSlice.ts | 1 - 8 files changed, 64 insertions(+), 10 deletions(-) diff --git a/core/core.ts b/core/core.ts index 464f8a5e3..f2dc9387c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -34,6 +34,7 @@ import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; +import { instantiateTool } from "./tools"; import type { IMessenger, Message } from "./util/messenger"; export class Core { @@ -740,6 +741,12 @@ export class Core { recentlyEditedFilesCache.set(filepath, filepath); } }); + + on("tools/call", async ({ data: { toolCall } }) => { + const tool = instantiateTool(toolCall.function.name, { ide: this.ide }); + const result = await tool.action(toolCall.function.arguments); + return { result }; + }); } private indexingCancellationController: AbortController | undefined; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 196192a38..27cd3fcdd 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -16,6 +16,7 @@ import type { SerializedContinueConfig, SessionInfo, SiteIndexingConfig, + ToolCall, } from "../"; export type ProtocolGeneratorType = AsyncGenerator<{ @@ -158,4 +159,5 @@ export type ToCoreFromIdeOrWebviewProtocol = { "profiles/switch": [{ id: string }, undefined]; "auth/getAuthUrl": [undefined, { url: string }]; + "tools/call": [{ toolCall: ToolCall }, { result: any }]; }; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 1c0f5e962..f2b1af96e 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -47,6 +47,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/listProfiles", "profiles/switch", "didChangeSelectedProfile", + "tools/call", ]; // Message types to pass through from core to webview @@ -60,5 +61,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "isContinueInputFocused", "didChangeAvailableProfiles", "setTTSActive", - "getWebviewHistoryLength" + "getWebviewHistoryLength", ]; diff --git a/core/tools/index.ts b/core/tools/index.ts index aec23de36..ab592b757 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,9 +1,13 @@ import { IDE, Tool } from ".."; -export const makeCreateNewFileTool = (ide: IDE): Tool => ({ +export interface ToolParams { + ide: IDE; +} + +export const makeCreateNewFileTool = ({ ide }: ToolParams): Tool => ({ type: "function", - action: async (...args: any) => { - await ide.writeFile(args[0], args[1]); + action: async (args: any) => { + await ide.writeFile(args.filepath, args.contents); }, function: { name: "create_new_file", @@ -25,10 +29,10 @@ export const makeCreateNewFileTool = (ide: IDE): Tool => ({ }, }); -export const runTerminalCommandTool = (ide: IDE): Tool => ({ +export const runTerminalCommandTool = ({ ide }: ToolParams): Tool => ({ type: "function", - action: async (...args) => { - await ide.runCommand(args[0]); + action: async (args) => { + await ide.runCommand(args.command); }, function: { name: "run_terminal_command", @@ -46,3 +50,14 @@ export const runTerminalCommandTool = (ide: IDE): Tool => ({ }, }, }); + +export function instantiateTool(name: string, { ide }: ToolParams): Tool { + switch (name) { + case "create_new_file": + return makeCreateNewFileTool({ ide }); + case "run_terminal_command": + return runTerminalCommandTool({ ide }); + default: + throw new Error(`Unknown tool ${name}`); + } +} diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index e7b6c8271..abcf80fb4 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -57,6 +57,12 @@ ], "main": "./out/extension.js", "contributes": { + "authentication": [ + { + "id": "continue", + "label": "Continue" + } + ], "languages": [ { "filenames": [ diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 0b1b1756c..6f642d9ea 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -6,6 +6,7 @@ import { } from "@heroicons/react/24/outline"; import { JSONContent } from "@tiptap/react"; import { InputModifiers } from "core"; +import { stripImages } from "core/llm/images"; import { usePostHog } from "posthog-js/react"; import { Fragment, @@ -342,6 +343,8 @@ export function Chat() { editorState={item.editorState} contextItems={item.contextItems} /> + ) : item.message.role === "tool" ? ( +
{stripImages(item.message.content)}
) : item.message.role === "assistant" && item.message.toolCalls ? (
diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index dbe7c3bed..de89fbb9a 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -1,4 +1,6 @@ import { ToolCall } from "core"; +import { useContext } from "react"; +import { useDispatch } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, @@ -6,6 +8,8 @@ import { vscButtonBackground, vscButtonForeground, } from "../../../components"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { streamUpdate } from "../../../redux/slices/stateSlice"; import { CreateFile } from "./CreateFile"; import { RunTerminalCommand } from "./RunTerminalCommand"; @@ -84,12 +88,29 @@ function FunctionSpecificToolCallDiv(toolCall: ToolCall) { } export function ToolCallDiv(props: ToolCallDivProps) { + const ideMessenger = useContext(IdeMessengerContext); + const dispatch = useDispatch(); + + async function callTool() { + const result = await ideMessenger.request("tools/call", { + toolCall: props.toolCall, + }); + if (result.status === "success") { + dispatch( + streamUpdate({ + role: "tool", + content: JSON.stringify(result.content.result), + }), + ); + } + } + return ( - Cancel - Continue + {}}>Cancel + Continue ); diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index db6dbf859..647c18188 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -266,7 +266,6 @@ export const stateSlice = createSlice({ action.payload.role && lastMessage.message.role !== action.payload.role ) { - console.log("NEW: ", action.payload); // Create a new message state.history.push({ contextItems: [], From 445716c1ccdc642a261e8aaaa6ecda945ef1f169 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 17 Nov 2024 18:54:23 -0800 Subject: [PATCH 009/105] run tools --- core/core.ts | 2 +- core/tools/index.ts | 12 ++++++- gui/src/pages/gui/ToolCallDiv/CreateFile.tsx | 4 +-- gui/src/pages/gui/ToolCallDiv/index.tsx | 37 ++++++++++++++++---- 4 files changed, 44 insertions(+), 11 deletions(-) diff --git a/core/core.ts b/core/core.ts index f2dc9387c..babecfec8 100644 --- a/core/core.ts +++ b/core/core.ts @@ -744,7 +744,7 @@ export class Core { on("tools/call", async ({ data: { toolCall } }) => { const tool = instantiateTool(toolCall.function.name, { ide: this.ide }); - const result = await tool.action(toolCall.function.arguments); + const result = await tool.action(JSON.parse(toolCall.function.arguments)); return { result }; }); } diff --git a/core/tools/index.ts b/core/tools/index.ts index ab592b757..862f7dd6b 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,4 +1,5 @@ import { IDE, Tool } from ".."; +import { getPathModuleForIde } from "../util/pathModule"; export interface ToolParams { ide: IDE; @@ -7,7 +8,16 @@ export interface ToolParams { export const makeCreateNewFileTool = ({ ide }: ToolParams): Tool => ({ type: "function", action: async (args: any) => { - await ide.writeFile(args.filepath, args.contents); + const pathSep = await ide.pathSep(); + let filepath = args.filepath; + if (!args.filepath.startsWith(pathSep)) { + const pathModule = await getPathModuleForIde(ide); + const workspaceDirs = await ide.getWorkspaceDirs(); + const cwd = workspaceDirs[0]; + filepath = pathModule.join(cwd, filepath); + } + await ide.writeFile(filepath, args.contents); + await ide.openFile(filepath); }, function: { name: "create_new_file", diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index 5dbdaf340..0eee17b96 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -11,10 +11,10 @@ export function CreateFile(props: CreateFileToolCallProps) { <>

Continue wants to create a file:

(true); + + useEffect(() => { + if (props.toolCall.function.arguments.length === 0) { + return; + } + + const [done, _] = incrementalParseJson(props.toolCall.function.arguments); + if (done) { + setLoading(false); + } + }, [props.toolCall.function.arguments]); + async function callTool() { const result = await ideMessenger.request("tools/call", { toolCall: props.toolCall, @@ -109,8 +123,17 @@ export function ToolCallDiv(props: ToolCallDivProps) { - {}}>Cancel - Continue + {loading ? ( +
+ Loading... + +
+ ) : ( + <> + {}}>Cancel + Continue + + )}
); From ec98aa51b9e35d26454fb2aee5b7c549354a5e14 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 17 Nov 2024 19:32:31 -0800 Subject: [PATCH 010/105] continue conversation after tool calls --- core/index.d.ts | 1 + core/llm/constructMessages.ts | 4 +- core/llm/llms/OpenAI.ts | 3 ++ gui/src/pages/gui/ToolCallDiv/CreateFile.tsx | 2 + .../gui/ToolCallDiv/RunTerminalCommand.tsx | 2 + gui/src/pages/gui/ToolCallDiv/index.tsx | 40 +++++++++++++++---- gui/src/pages/gui/ToolCallDiv/types.ts | 1 + 7 files changed, 43 insertions(+), 10 deletions(-) create mode 100644 gui/src/pages/gui/ToolCallDiv/types.ts diff --git a/core/index.d.ts b/core/index.d.ts index 8c3f44f5e..281a91dba 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -284,6 +284,7 @@ export interface ChatMessage { role: ChatMessageRole; content: MessageContent; toolCalls?: ToolCallDelta[]; + toolCallId?: string; } export interface ContextItemId { diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 13d538be8..f36f362ef 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -73,7 +73,7 @@ export function constructMessages( history: ChatHistory, model: string, ): ChatMessage[] { - const msgs = []; + const msgs: ChatMessage[] = []; // Only using this system message with Sonnet right now if ( @@ -100,7 +100,7 @@ export function constructMessages( content = [...ctxItems, ...content]; msgs.push({ - role: historyItem.message.role, + ...historyItem.message, content, }); } diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 99df30f32..6c8bded39 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -267,6 +267,9 @@ class OpenAI extends BaseLLM { body.messages = body.messages.map((m: any) => ({ ...m, content: m.content === "" ? " " : m.content, + // We call it toolCalls, they call it tool_calls + tool_calls: m.toolCalls, + tool_call_id: m.toolCallId, })) as any; const response = await this.fetch(this._getEndpoint("chat/completions"), { method: "POST", diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index 0eee17b96..5cfeef4de 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -1,9 +1,11 @@ import StepContainerPreToolbar from "../../../components/markdown/StepContainerPreToolbar"; import { SyntaxHighlightedPre } from "../../../components/markdown/SyntaxHighlightedPre"; +import { ToolState } from "./types"; interface CreateFileToolCallProps { filepath: string; fileContents: string; + state: ToolState; } export function CreateFile(props: CreateFileToolCallProps) { diff --git a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx index 0dff88046..62186ddec 100644 --- a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx +++ b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx @@ -1,8 +1,10 @@ import StepContainerPreToolbar from "../../../components/markdown/StepContainerPreToolbar"; import { SyntaxHighlightedPre } from "../../../components/markdown/SyntaxHighlightedPre"; +import { ToolState } from "./types"; interface RunTerminalCommandToolCallProps { command: string; + state: ToolState; } export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 844ed765c..b5df62ad6 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -13,6 +13,7 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { streamUpdate } from "../../../redux/slices/stateSlice"; import { CreateFile } from "./CreateFile"; import { RunTerminalCommand } from "./RunTerminalCommand"; +import { ToolState } from "./types"; const Container = styled.div` margin: 8px; @@ -64,16 +65,20 @@ function incrementalParseJson(raw: string): [boolean, any] { } } -function FunctionSpecificToolCallDiv(toolCall: ToolCall) { +function FunctionSpecificToolCallDiv(toolCall: ToolCall, state: ToolState) { const [_, args] = incrementalParseJson(toolCall.function.arguments); switch (toolCall.function.name) { case "create_new_file": return ( - + ); case "run_terminal_command": - return ; + return ; default: return ( <> @@ -92,7 +97,7 @@ export function ToolCallDiv(props: ToolCallDivProps) { const ideMessenger = useContext(IdeMessengerContext); const dispatch = useDispatch(); - const [loading, setLoading] = useState(true); + const [state, setState] = useState("generating"); useEffect(() => { if (props.toolCall.function.arguments.length === 0) { @@ -101,21 +106,35 @@ export function ToolCallDiv(props: ToolCallDivProps) { const [done, _] = incrementalParseJson(props.toolCall.function.arguments); if (done) { - setLoading(false); + setState("generated"); } }, [props.toolCall.function.arguments]); async function callTool() { + let setCallingState = true; + + const timer = setTimeout(() => { + if (setCallingState) { + setState("calling"); + } + }, 800); + const result = await ideMessenger.request("tools/call", { toolCall: props.toolCall, }); + + setCallingState = false; + clearTimeout(timer); + if (result.status === "success") { dispatch( streamUpdate({ role: "tool", content: JSON.stringify(result.content.result), + toolCallId: props.toolCall.id, }), ); + setState("done"); } } @@ -123,17 +142,22 @@ export function ToolCallDiv(props: ToolCallDivProps) { - {loading ? ( + {state === "generating" ? (
Loading...
- ) : ( + ) : state === "generated" ? ( <> {}}>Cancel Continue - )} + ) : state === "calling" ? ( +
+ Loading... + +
+ ) : null}
); diff --git a/gui/src/pages/gui/ToolCallDiv/types.ts b/gui/src/pages/gui/ToolCallDiv/types.ts new file mode 100644 index 000000000..fa041be64 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/types.ts @@ -0,0 +1 @@ +export type ToolState = "generating" | "generated" | "calling" | "done"; From a73e0b53c9933d2d4f1e34bae5428fa48fb9b894 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 17 Nov 2024 21:21:47 -0800 Subject: [PATCH 011/105] anthropic tool use support --- core/config/load.ts | 4 ++-- core/llm/llms/Anthropic.ts | 49 +++++++++++++++++++++++++++++++++++--- 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/core/config/load.ts b/core/config/load.ts index b199e0e58..603d38e01 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -337,8 +337,8 @@ async function intermediateToFinalConfig( ...config.requestOptions, }; model.completionOptions.tools = [ - makeCreateNewFileTool(ide), - runTerminalCommandTool(ide), + makeCreateNewFileTool({ ide }), + runTerminalCommandTool({ ide }), ]; } diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 8db42eefa..a3303f179 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -30,6 +30,11 @@ class Anthropic extends BaseLLM { model: options.model === "claude-2" ? "claude-2.1" : options.model, stop_sequences: options.stop?.filter((x) => x.trim() !== ""), stream: options.stream ?? true, + tools: options.tools?.map((tool) => ({ + name: tool.function.name, + description: tool.function.description, + input_schema: tool.function.parameters, + })), }; return finalOptions; @@ -145,10 +150,48 @@ class Anthropic extends BaseLLM { return; } + let lastToolUseId: string | undefined; + let lastToolUseName: string | undefined; for await (const value of streamSse(response)) { - if (value.type == "message_start") {console.log(value);} - if (value.delta?.text) { - yield { role: "assistant", content: value.delta.text }; + // https://docs.anthropic.com/en/api/messages-streaming#event-types + switch (value.type) { + case "content_block_start": + if (value.content_block.type === "tool_use") { + lastToolUseId = value.content_block.id; + lastToolUseName = value.content_block.name; + } + break; + case "content_block_delta": + // https://docs.anthropic.com/en/api/messages-streaming#delta-types + switch (value.delta.type) { + case "text_delta": + yield { role: "assistant", content: value.delta.text }; + break; + case "input_json_delta": + if (!lastToolUseId || !lastToolUseName) { + throw new Error("No tool use found"); + } + yield { + role: "assistant", + content: "", + toolCalls: [ + { + id: lastToolUseId, + type: "function", + function: { + name: lastToolUseName, + arguments: value.delta.partial_json, + }, + }, + ], + }; + break; + } + break; + case "content_block_stop": + break; + default: + break; } } } From 95e1414a2e092c754a91a3b1686a3d6da17cd56c Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 17 Nov 2024 21:25:29 -0800 Subject: [PATCH 012/105] fix anthropic tool use stateSlice update --- gui/src/redux/slices/stateSlice.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 647c18188..62387e66b 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -264,7 +264,10 @@ export const stateSlice = createSlice({ if ( action.payload.role && - lastMessage.message.role !== action.payload.role + (lastMessage.message.role !== action.payload.role || + // This is when a tool call comes after assistant text + (lastMessage.message.content !== "" && + action.payload.toolCalls?.length)) ) { // Create a new message state.history.push({ From 6117d789757ec330cb1661e300c0f27edc9b6e1a Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 18 Nov 2024 14:20:50 -0800 Subject: [PATCH 013/105] nicer loader --- core/llm/llms/Anthropic.ts | 2 ++ gui/src/pages/gui/ToolCallDiv/CreateFile.tsx | 1 - gui/src/pages/gui/ToolCallDiv/index.tsx | 19 +++++++++++++++---- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index a3303f179..13e359ead 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -189,6 +189,8 @@ class Anthropic extends BaseLLM { } break; case "content_block_stop": + lastToolUseId = undefined; + lastToolUseName = undefined; break; default: break; diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index 5cfeef4de..7fe43deec 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -11,7 +11,6 @@ interface CreateFileToolCallProps { export function CreateFile(props: CreateFileToolCallProps) { return ( <> -

Continue wants to create a file:

- + {state === "generating" ? ( -
- Loading... +
+ Thinking...
) : state === "generated" ? ( From b5edb31c76a5fbf73c5b5544de2529aa803cca10 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 18 Nov 2024 14:25:02 -0800 Subject: [PATCH 014/105] styling --- gui/src/pages/gui/ToolCallDiv/index.tsx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 5b23d75a0..f234f2640 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -18,6 +18,9 @@ import { ToolState } from "./types"; const Container = styled.div` margin: 8px; overflow: hidden; + border-left: 1px solid ${lightGray}; + margin-left: 16px; + padding-left: 16px; `; const ButtonContainer = styled.div` @@ -27,8 +30,7 @@ const ButtonContainer = styled.div` `; const Button = styled.button` - color: ${vscButtonForeground}; - padding: 6px; + padding: 5px; border-radius: ${defaultBorderRadius}; flex: 1; @@ -39,6 +41,7 @@ const Button = styled.button` `; const AcceptButton = styled(Button)` + color: ${vscButtonForeground}; border: none; background-color: ${vscButtonBackground}; color: ${vscButtonForeground}; @@ -49,6 +52,7 @@ const AcceptButton = styled(Button)` `; const RejectButton = styled(Button)` + color: ${lightGray}; border: 1px solid ${lightGray}; background-color: transparent; `; From eb1cddaf9026be6237165bbeea93f0d86a466504 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 18 Nov 2024 19:24:57 -0800 Subject: [PATCH 015/105] tab and cmd+backspace for continue and cancel buttons --- gui/src/pages/gui/ToolCallDiv/index.tsx | 29 +++++++++++++++++++++++-- gui/src/pages/gui/ToolCallDiv/types.ts | 7 +++++- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index f234f2640..092468f06 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -16,6 +16,10 @@ import { RunTerminalCommand } from "./RunTerminalCommand"; import { ToolState } from "./types"; const Container = styled.div` + display: flex; + flex-direction: column; + justify-content: center; + margin: 8px; overflow: hidden; border-left: 1px solid ${lightGray}; @@ -120,6 +124,26 @@ export function ToolCallDiv(props: ToolCallDivProps) { } }, [props.toolCall.function.arguments]); + useEffect(() => { + function handleKeyDown(e: KeyboardEvent) { + if (e.key === "Tab") { + e.preventDefault(); + callTool(); + } + if (e.key === "Backspace" && e.metaKey) { + e.preventDefault(); + cancelTool(); + } + } + + window.addEventListener("keydown", handleKeyDown); + return () => window.removeEventListener("keydown", handleKeyDown); + }, []); + + async function cancelTool() { + setState("canceled"); + } + async function callTool() { let setCallingState = true; @@ -157,14 +181,15 @@ export function ToolCallDiv(props: ToolCallDivProps) { className="flex w-full items-center justify-center gap-4" style={{ color: lightGray, + minHeight: "40px", }} > Thinking... - + {/* */}
) : state === "generated" ? ( <> - {}}>Cancel + Cancel Continue ) : state === "calling" ? ( diff --git a/gui/src/pages/gui/ToolCallDiv/types.ts b/gui/src/pages/gui/ToolCallDiv/types.ts index fa041be64..2a21a7bb9 100644 --- a/gui/src/pages/gui/ToolCallDiv/types.ts +++ b/gui/src/pages/gui/ToolCallDiv/types.ts @@ -1 +1,6 @@ -export type ToolState = "generating" | "generated" | "calling" | "done"; +export type ToolState = + | "generating" + | "generated" + | "calling" + | "done" + | "canceled"; From b23d36e18994898540690927558a5420aa120450 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 11:14:49 -0800 Subject: [PATCH 016/105] thread UI --- gui/src/pages/gui/Chat.tsx | 10 ++++ gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx | 52 +++++++++++++++++++++ gui/src/pages/gui/ToolCallDiv/index.tsx | 33 +++++++------ 3 files changed, 81 insertions(+), 14 deletions(-) create mode 100644 gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index d2af2bc00..575b3d6a1 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -90,6 +90,16 @@ const StepsDiv = styled.div` position: relative; background-color: transparent; + // &::before { + // content: ""; + // position: absolute; + // top: 0; + // left: 16px; + // bottom: 0; + // width: 1px; + // background-color: ${lightGray}; + // } + & > * { position: relative; } diff --git a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx new file mode 100644 index 000000000..0a43670d2 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx @@ -0,0 +1,52 @@ +import styled from "styled-components"; +import { lightGray, vscBackground } from "../../../components"; + +interface ThreadDivProps { + children: React.ReactNode; + icon: React.ReactNode; +} + +const Container = styled.div` + display: flex; + flex-direction: column; + justify-content: center; + position: relative; + border-left: 1px solid ${lightGray}; + padding-left: 16px; + margin-left: 16px; +`; + +const ChildrenDiv = styled.div` + margin: 8px; + margin-left: 0; +`; + +const W = 12; + +const IconWrapper = styled.div` + position: absolute; + left: -${W / 2 + W / 4}px; + width: ${W}px; + height: ${W}px; + top: 50%; + overflow: hidden; + transform: translateY(-50%); + + background-color: ${vscBackground}; + border-radius: 50%; + // outline: 1px solid ${lightGray}; + + display: flex; + align-items: center; + justify-content: center; + padding: ${W / 4}px; +`; + +export function ThreadDiv(props: ThreadDivProps) { + return ( + + {props.icon} + {props.children} + + ); +} diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 092468f06..c9c242b9d 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -1,3 +1,4 @@ +import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ToolCall } from "core"; import { useContext, useEffect, useState } from "react"; import { useDispatch } from "react-redux"; @@ -13,20 +14,9 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { streamUpdate } from "../../../redux/slices/stateSlice"; import { CreateFile } from "./CreateFile"; import { RunTerminalCommand } from "./RunTerminalCommand"; +import { ThreadDiv } from "./ThreadDiv"; import { ToolState } from "./types"; -const Container = styled.div` - display: flex; - flex-direction: column; - justify-content: center; - - margin: 8px; - overflow: hidden; - border-left: 1px solid ${lightGray}; - margin-left: 16px; - padding-left: 16px; -`; - const ButtonContainer = styled.div` display: flex; gap: 8px; @@ -172,8 +162,23 @@ export function ToolCallDiv(props: ToolCallDivProps) { } } + function getIcon(state: ToolState) { + switch (state) { + case "generating": + return ; + case "done": + return ; + case "calling": + return ; + case "canceled": + return ; + case "generated": + return ; + } + } + return ( - + {state === "generating" ? ( @@ -199,6 +204,6 @@ export function ToolCallDiv(props: ToolCallDivProps) {
) : null} - + ); } From 54e25d6d885757aa01cbba1ae250a8d2adb524a9 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 13:32:54 -0800 Subject: [PATCH 017/105] update anthropic tool use --- core/llm/constructMessages.ts | 7 ++ core/llm/countTokens.ts | 6 +- core/llm/flattenMessages.test.ts | 104 +++++++++++++++++ core/llm/llms/Anthropic.ts | 105 +++++++++++------- .../StepContainer/ResponseActions.tsx | 6 +- .../StepContainer/StepContainer.tsx | 4 +- .../markdown/StyledMarkdownPreview.tsx | 8 +- gui/src/hooks/useChatHandler.ts | 2 +- 8 files changed, 192 insertions(+), 50 deletions(-) create mode 100644 core/llm/flattenMessages.test.ts diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index f36f362ef..8b381f5fb 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -103,6 +103,13 @@ export function constructMessages( ...historyItem.message, content, }); + + // Remove the "id" from all of the messages + msgs.forEach((msg: any) => { + if (msg.id !== undefined) { + delete msg.id; + } + }); } return msgs; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 9b30ad4bc..871e5ee84 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -115,13 +115,15 @@ function countTokens( } } -function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { +export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { const flattened: ChatMessage[] = []; for (let i = 0; i < msgs.length; i++) { const msg = msgs[i]; if ( flattened.length > 0 && - flattened[flattened.length - 1].role === msg.role + flattened[flattened.length - 1].role === msg.role && + !msg.toolCalls && + !flattened[flattened.length - 1].toolCalls ) { flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`; } else { diff --git a/core/llm/flattenMessages.test.ts b/core/llm/flattenMessages.test.ts new file mode 100644 index 000000000..6f5ba0a4c --- /dev/null +++ b/core/llm/flattenMessages.test.ts @@ -0,0 +1,104 @@ +import { ChatMessage } from ".."; +import { flattenMessages } from "./countTokens"; + +describe("flattenMessages", () => { + it("should return an empty array when given an empty array", () => { + expect(flattenMessages([])).toEqual([]); + }); + + it("should return the same array when there is only one message", () => { + const messages: ChatMessage[] = [{ role: "user", content: "Hello" }]; + expect(flattenMessages(messages)).toEqual(messages); + }); + + it("should return the same array when messages have different roles", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there!" }, + { role: "user", content: "How are you?" }, + ]; + expect(flattenMessages(messages)).toEqual(messages); + }); + + it("should combine consecutive messages with the same role", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Hello" }, + { role: "user", content: "How are you?" }, + { role: "assistant", content: "I am an AI assistant." }, + { role: "assistant", content: "How can I help you?" }, + ]; + const expected: ChatMessage[] = [ + { role: "user", content: "Hello\n\nHow are you?" }, + { + role: "assistant", + content: "I am an AI assistant.\n\nHow can I help you?", + }, + ]; + expect(flattenMessages(messages)).toEqual(expected); + }); + + it("should handle messages with undefined or empty content", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Hello" }, + { role: "user", content: "" }, + { role: "assistant", content: "" }, + { role: "assistant", content: "Sure, I can help with that." }, + ]; + const expected: ChatMessage[] = [ + { role: "user", content: "Hello\n\n" }, + { role: "assistant", content: "\n\nSure, I can help with that." }, + ]; + expect(flattenMessages(messages)).toEqual(expected); + }); + + it("should not combine non-consecutive messages with the same role", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "First message" }, + { role: "assistant", content: "Reply to first message" }, + { role: "user", content: "Second message" }, + ]; + expect(flattenMessages(messages)).toEqual(messages); + }); + + it("should handle a mix of message roles and contents correctly", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Message one" }, + { role: "user", content: "Message two" }, + { role: "assistant", content: "Reply one" }, + { role: "user", content: "Message three" }, + { role: "user", content: "Message four" }, + { role: "assistant", content: "Reply two" }, + ]; + const expected: ChatMessage[] = [ + { role: "user", content: "Message one\n\nMessage two" }, + { role: "assistant", content: "Reply one" }, + { role: "user", content: "Message three\n\nMessage four" }, + { role: "assistant", content: "Reply two" }, + ]; + expect(flattenMessages(messages)).toEqual(expected); + }); + + it("should not combine adjacent assistant messages when one of them is a tool call", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "What's the capital of France?" }, + { role: "assistant", content: "Paris" }, + { + role: "assistant", + content: " ", + toolCalls: [ + { + id: "test", + type: "function", + function: { + name: "getCapital", + arguments: JSON.stringify({ + country: "France", + }), + }, + }, + ], + }, + ]; + expect(flattenMessages(messages).length).toBe(3); + }); +}); diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 13e359ead..aa0b55f1c 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -40,6 +40,69 @@ class Anthropic extends BaseLLM { return finalOptions; } + private convertMessage(message: ChatMessage, addCaching: boolean): any { + if (message.role === "tool") { + return { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: message.toolCallId, + content: stripImages(message.content) || undefined, + }, + ], + }; + } else if (message.role === "assistant" && message.toolCalls) { + return { + role: "assistant", + content: message.toolCalls.map((toolCall) => ({ + type: "tool_use", + id: toolCall.id, + name: toolCall.function?.name, + input: JSON.parse(toolCall.function?.arguments ?? "{}"), + })), + }; + } + + if (typeof message.content === "string") { + var chatMessage = { + role: message.role, + content: [ + { + type: "text", + text: message.content, + ...(addCaching ? { cache_control: { type: "ephemeral" } } : {}), + }, + ], + }; + return chatMessage; + } + + return { + role: message.role, + content: message.content.map((part, contentIdx) => { + if (part.type === "text") { + const newpart = { + ...part, + // If multiple text parts, only add cache_control to the last one + ...(addCaching && contentIdx == message.content.length - 1 + ? { cache_control: { type: "ephemeral" } } + : {}), + }; + return newpart; + } + return { + type: "image", + source: { + type: "base64", + media_type: "image/jpeg", + data: part.imageUrl?.url.split(",")[1], + }, + }; + }), + }; + } + public convertMessages(msgs: ChatMessage[]): any[] { // should be public for use within VertexAI const filteredmessages = msgs.filter((m) => m.role !== "system"); @@ -57,43 +120,8 @@ class Anthropic extends BaseLLM { this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx); - if (typeof message.content === "string") { - var chatMessage = { - ...message, - content: [ - { - type: "text", - text: message.content, - ...(addCaching ? { cache_control: { type: "ephemeral" } } : {}), - }, - ], - }; - return chatMessage; - } - - return { - ...message, - content: message.content.map((part, contentIdx) => { - if (part.type === "text") { - const newpart = { - ...part, - // If multiple text parts, only add cache_control to the last one - ...(addCaching && contentIdx == message.content.length - 1 - ? { cache_control: { type: "ephemeral" } } - : {}), - }; - return newpart; - } - return { - type: "image", - source: { - type: "base64", - media_type: "image/jpeg", - data: part.imageUrl?.url.split(",")[1], - }, - }; - }), - }; + const chatMessage = this.convertMessage(message, !!addCaching); + return chatMessage; }); return messages; } @@ -118,6 +146,7 @@ class Anthropic extends BaseLLM { messages.filter((m) => m.role === "system")[0]?.content, ); + const msgs = this.convertMessages(messages); const response = await this.fetch(new URL("messages", this.apiBase), { method: "POST", headers: { @@ -131,7 +160,7 @@ class Anthropic extends BaseLLM { }, body: JSON.stringify({ ...this.convertArgs(options), - messages: this.convertMessages(messages), + messages: msgs, system: shouldCacheSystemMessage ? [ { diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index 66d62575c..24ba98aaa 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -1,10 +1,10 @@ import { BarsArrowDownIcon, TrashIcon } from "@heroicons/react/24/outline"; +import { ChatHistoryItem } from "core"; import { stripImages } from "core/llm/images"; -import { CopyIconButton } from "../gui/CopyIconButton"; -import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import { useSelector } from "react-redux"; import { RootState } from "../../redux/store"; -import { ChatHistoryItem } from "core"; +import { CopyIconButton } from "../gui/CopyIconButton"; +import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import FeedbackButtons from "./FeedbackButtons"; import MultifileEditActions from "./MultifileEditActions"; diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index f5673e4e8..3d60c841b 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -5,11 +5,11 @@ import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; import { vscBackground } from ".."; import useUIConfig from "../../hooks/useUIConfig"; +import { deleteMessage } from "../../redux/slices/stateSlice"; import { RootState } from "../../redux/store"; import { getFontSize } from "../../util"; import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; import ResponseActions from "./ResponseActions"; -import { deleteMessage } from "../../redux/slices/stateSlice"; interface StepContainerProps { item: ChatHistoryItem; @@ -42,7 +42,7 @@ export default function StepContainer(props: StepContainerProps) { useEffect(() => { if (!active) { const content = stripImages(props.item.message.content).trim(); - const endingPunctuation = [".", "?", "!", "```"]; + const endingPunctuation = [".", "?", "!", "```", ":"]; // If not ending in punctuation or emoji, we assume the response got truncated if ( diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index e783f8499..b06bdc6be 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,3 +1,5 @@ +import { ContextItemWithId } from "core"; +import { ctxItemToRifWithContents } from "core/commands/util"; import { memo, useEffect } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; @@ -12,15 +14,13 @@ import { vscForeground, } from ".."; import { getFontSize, isJetBrains } from "../../util"; +import FilenameLink from "./FilenameLink"; import "./katex.css"; import "./markdown.css"; -import { ctxItemToRifWithContents } from "core/commands/util"; -import FilenameLink from "./FilenameLink"; +import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; import StepContainerPreToolbar from "./StepContainerPreToolbar"; import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; -import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; import { patchNestedMarkdown } from "./utils/patchNestedMarkdown"; -import { ContextItemWithId } from "core"; const StyledMarkdown = styled.div<{ fontSize?: number; diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index e0a552c7a..455484474 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -26,6 +26,7 @@ import { addPromptCompletionPair, clearLastResponse, initNewActiveMessage, + resetNextCodeBlockToApplyIndex, resubmitAtIndex, setCurCheckpointIndex, setInactive, @@ -34,7 +35,6 @@ import { setMessageAtIndex, streamUpdate, } from "../redux/slices/stateSlice"; -import { resetNextCodeBlockToApplyIndex } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import useHistory from "./useHistory"; From 8d2a0081a52b7b4b5c8c850cef5f2379c7fc3efe Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 13:45:27 -0800 Subject: [PATCH 018/105] left thread line --- .../StepContainer/ResponseActions.tsx | 2 +- .../components/mainInput/ContextItemsPeek.tsx | 11 ++++++++--- gui/src/pages/gui/Chat.tsx | 18 +++++++++--------- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index 24ba98aaa..138e93c6a 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -35,7 +35,7 @@ export default function ResponseActions({ } return ( -
+
{isTruncated && ( +
setOpen((prev) => !prev)} diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 575b3d6a1..3ac790ff9 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -90,15 +90,15 @@ const StepsDiv = styled.div` position: relative; background-color: transparent; - // &::before { - // content: ""; - // position: absolute; - // top: 0; - // left: 16px; - // bottom: 0; - // width: 1px; - // background-color: ${lightGray}; - // } + &::before { + content: ""; + position: absolute; + top: 0; + left: 16px; + bottom: 0; + width: 1px; + background-color: ${lightGray}; + } & > * { position: relative; From ba4598d25b536bc796c17f8569ab2866bfe894ba Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 14:04:55 -0800 Subject: [PATCH 019/105] padding stuff --- gui/src/components/ChatScrollAnchor.tsx | 11 ++++++++++- gui/src/components/StepContainer/StepContainer.tsx | 1 + gui/src/components/mainInput/ContinueInputBox.tsx | 2 +- gui/src/pages/gui/Chat.tsx | 4 ++-- 4 files changed, 14 insertions(+), 4 deletions(-) diff --git a/gui/src/components/ChatScrollAnchor.tsx b/gui/src/components/ChatScrollAnchor.tsx index 40c0f9d19..9b32e7283 100644 --- a/gui/src/components/ChatScrollAnchor.tsx +++ b/gui/src/components/ChatScrollAnchor.tsx @@ -1,5 +1,6 @@ import { useEffect } from "react"; import { useInView } from "react-intersection-observer"; +import { vscBackground } from "."; interface ChatScrollAnchorProps { trackVisibility: boolean; @@ -25,5 +26,13 @@ export function ChatScrollAnchor({ } }, [inView, entry, isAtBottom, trackVisibility]); - return
; + return ( +
+ ); } diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index 3d60c841b..610cfd0f9 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -19,6 +19,7 @@ interface StepContainerProps { const ContentDiv = styled.div<{ fontSize?: number }>` padding-top: 4px; + padding-bottom: 4px; background-color: ${vscBackground}; font-size: ${getFontSize()}px; overflow: hidden; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 4a9ea0dfd..bdf4b36ca 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -109,7 +109,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) { }, [isGatheringContextStore]); return ( -
+
0 ? "h-full" : ""}`} + className={`mt-[8px] overflow-y-scroll ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${state.history.length > 0 ? "h-full" : ""}`} onScroll={handleScroll} > {highlights} From 21e93814bf86da953680a9d8b10635a438aa8518 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 14:33:05 -0800 Subject: [PATCH 020/105] remove listener --- gui/src/pages/gui/ToolCallDiv/index.tsx | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index c9c242b9d..73b615fbc 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -114,22 +114,6 @@ export function ToolCallDiv(props: ToolCallDivProps) { } }, [props.toolCall.function.arguments]); - useEffect(() => { - function handleKeyDown(e: KeyboardEvent) { - if (e.key === "Tab") { - e.preventDefault(); - callTool(); - } - if (e.key === "Backspace" && e.metaKey) { - e.preventDefault(); - cancelTool(); - } - } - - window.addEventListener("keydown", handleKeyDown); - return () => window.removeEventListener("keydown", handleKeyDown); - }, []); - async function cancelTool() { setState("canceled"); } From c1f3204f96c92eaa25efa848b8cfa9f3b046275d Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 15:11:30 -0800 Subject: [PATCH 021/105] update llm-info --- packages/llm-info/package.json | 2 +- packages/llm-info/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/llm-info/package.json b/packages/llm-info/package.json index 4ba97f6b8..af8303938 100644 --- a/packages/llm-info/package.json +++ b/packages/llm-info/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/llm-info", - "version": "1.0.6", + "version": "1.0.7", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/llm-info/src/index.ts b/packages/llm-info/src/index.ts index 84d88e031..fe71f419d 100644 --- a/packages/llm-info/src/index.ts +++ b/packages/llm-info/src/index.ts @@ -22,7 +22,7 @@ export const allModelProviders: ModelProvider[] = [ Vllm, Bedrock, Cohere, - xAI + xAI, ]; export const allLlms: LlmInfo[] = allModelProviders.flatMap((provider) => From 3021c1e27cc7dff2e9c29105992438a29ec17cf4 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 15:43:09 -0800 Subject: [PATCH 022/105] styling and state for tool calling --- core/util/incrementalParseJson.ts | 7 + gui/src/pages/gui/Chat.tsx | 12 +- .../FunctionSpecificToolCallDiv.tsx | 41 +++++ gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx | 32 ++-- .../gui/ToolCallDiv/ToolCallButtonsDiv.tsx | 126 +++++++++++++ gui/src/pages/gui/ToolCallDiv/index.tsx | 173 +++--------------- gui/src/redux/slices/toolCallSlice.ts | 45 +++++ gui/src/redux/store.ts | 2 + 8 files changed, 256 insertions(+), 182 deletions(-) create mode 100644 core/util/incrementalParseJson.ts create mode 100644 gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx create mode 100644 gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx create mode 100644 gui/src/redux/slices/toolCallSlice.ts diff --git a/core/util/incrementalParseJson.ts b/core/util/incrementalParseJson.ts new file mode 100644 index 000000000..c72809035 --- /dev/null +++ b/core/util/incrementalParseJson.ts @@ -0,0 +1,7 @@ +export function incrementalParseJson(raw: string): [boolean, any] { + try { + return [true, JSON.parse(raw)]; + } catch (e) { + return [false, {}]; + } +} diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index f09a081d6..759c1e834 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -62,6 +62,7 @@ import { import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import { ToolCallDiv } from "./ToolCallDiv"; +import { ToolCallButtons } from "./ToolCallDiv/ToolCallButtonsDiv"; const StopButton = styled.div` background-color: ${vscBackground}; @@ -90,16 +91,6 @@ const StepsDiv = styled.div` position: relative; background-color: transparent; - &::before { - content: ""; - position: absolute; - top: 0; - left: 16px; - bottom: 0; - width: 1px; - background-color: ${lightGray}; - } - & > * { position: relative; } @@ -432,6 +423,7 @@ export function Chat() { )}
+ + ); + case "run_terminal_command": + return ; + default: + return ( + <> +
{toolCall.function.name}
+ {Object.entries(args)?.map(([key, value]) => ( +
+ {key}: {JSON.stringify(value)} +
+ ))} + + ); + } +} + +export default FunctionSpecificToolCallDiv; diff --git a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx index 0a43670d2..65efb7678 100644 --- a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx @@ -1,5 +1,4 @@ import styled from "styled-components"; -import { lightGray, vscBackground } from "../../../components"; interface ThreadDivProps { children: React.ReactNode; @@ -11,9 +10,7 @@ const Container = styled.div` flex-direction: column; justify-content: center; position: relative; - border-left: 1px solid ${lightGray}; - padding-left: 16px; - margin-left: 16px; + padding: 8px; `; const ChildrenDiv = styled.div` @@ -21,31 +18,24 @@ const ChildrenDiv = styled.div` margin-left: 0; `; -const W = 12; - -const IconWrapper = styled.div` - position: absolute; - left: -${W / 2 + W / 4}px; - width: ${W}px; - height: ${W}px; - top: 50%; - overflow: hidden; - transform: translateY(-50%); - - background-color: ${vscBackground}; - border-radius: 50%; - // outline: 1px solid ${lightGray}; +const W = 16; +const HeaderDiv = styled.div` display: flex; align-items: center; - justify-content: center; - padding: ${W / 4}px; + gap: 6px; + margin-bottom: 8px; `; export function ThreadDiv(props: ThreadDivProps) { return ( - {props.icon} + +
+ {props.icon} +
+ Continue wants to create a new file +
{props.children}
); diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx new file mode 100644 index 000000000..2449c0ab5 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx @@ -0,0 +1,126 @@ +import { useContext } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import styled from "styled-components"; +import { + defaultBorderRadius, + lightGray, + vscButtonBackground, + vscButtonForeground, +} from "../../../components"; +import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { streamUpdate } from "../../../redux/slices/stateSlice"; +import { + acceptToolCall, + cancelToolCall, + setCalling, +} from "../../../redux/slices/toolCallSlice"; +import { RootState } from "../../../redux/store"; + +const ButtonContainer = styled.div` + display: flex; + gap: 8px; + margin-top: 12px; + margin: 8px; +`; + +const Button = styled.button` + padding: 5px; + border-radius: ${defaultBorderRadius}; + flex: 1; + + &:hover { + cursor: pointer; + opacity: 0.8; + } +`; + +const AcceptButton = styled(Button)` + color: ${vscButtonForeground}; + border: none; + background-color: ${vscButtonBackground}; + color: ${vscButtonForeground}; + + &:hover { + cursor: pointer; + } +`; + +const RejectButton = styled(Button)` + color: ${lightGray}; + border: 1px solid ${lightGray}; + background-color: transparent; +`; + +interface ToolCallButtonsProps {} + +export function ToolCallButtons(props: ToolCallButtonsProps) { + const dispatch = useDispatch(); + const toolCallState = useSelector((store: RootState) => store.toolCallState); + const ideMessenger = useContext(IdeMessengerContext); + + async function callTool() { + // If it goes "generated" -> "calling" -> "done" really quickly + // we don't want an abrupt flash so just skip "calling" + let setCallingState = true; + + const timer = setTimeout(() => { + if (setCallingState) { + dispatch(setCalling()); + } + }, 800); + + if (toolCallState.currentToolCallState !== "generated") { + return; + } + + const result = await ideMessenger.request("tools/call", { + toolCall: toolCallState.toolCall, + }); + + setCallingState = false; + clearTimeout(timer); + + if (result.status === "success") { + dispatch( + streamUpdate({ + role: "tool", + content: JSON.stringify(result.content.result), + toolCallId: toolCallState.toolCall.id, + }), + ); + + dispatch(acceptToolCall()); + } + } + + return ( + <> + + {toolCallState.currentToolCallState === "generating" ? ( +
+ Thinking... +
+ ) : toolCallState.currentToolCallState === "generated" ? ( + <> + dispatch(cancelToolCall())}> + Cancel + + Continue + + ) : toolCallState.currentToolCallState === "calling" ? ( +
+ Loading... + +
+ ) : null} +
+ + ); +} diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 73b615fbc..6580c205e 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -1,151 +1,43 @@ import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ToolCall } from "core"; -import { useContext, useEffect, useState } from "react"; -import { useDispatch } from "react-redux"; -import styled from "styled-components"; -import { - defaultBorderRadius, - lightGray, - vscButtonBackground, - vscButtonForeground, -} from "../../../components"; +import { incrementalParseJson } from "core/util/incrementalParseJson"; +import { useEffect } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { lightGray } from "../../../components"; import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { streamUpdate } from "../../../redux/slices/stateSlice"; -import { CreateFile } from "./CreateFile"; -import { RunTerminalCommand } from "./RunTerminalCommand"; +import { + registerCurrentToolCall, + setGeneratedOutput, +} from "../../../redux/slices/toolCallSlice"; +import { RootState } from "../../../redux/store"; +import FunctionSpecificToolCallDiv from "./FunctionSpecificToolCallDiv"; import { ThreadDiv } from "./ThreadDiv"; import { ToolState } from "./types"; -const ButtonContainer = styled.div` - display: flex; - gap: 8px; - margin-top: 12px; -`; - -const Button = styled.button` - padding: 5px; - border-radius: ${defaultBorderRadius}; - flex: 1; - - &:hover { - cursor: pointer; - opacity: 0.8; - } -`; - -const AcceptButton = styled(Button)` - color: ${vscButtonForeground}; - border: none; - background-color: ${vscButtonBackground}; - color: ${vscButtonForeground}; - - &:hover { - cursor: pointer; - } -`; - -const RejectButton = styled(Button)` - color: ${lightGray}; - border: 1px solid ${lightGray}; - background-color: transparent; -`; - interface ToolCallDivProps { toolCall: ToolCall; } -function incrementalParseJson(raw: string): [boolean, any] { - try { - return [true, JSON.parse(raw)]; - } catch (e) { - return [false, {}]; - } -} - -function FunctionSpecificToolCallDiv({ - toolCall, - state, -}: { - toolCall: ToolCall; - state: ToolState; -}) { - const [_, args] = incrementalParseJson(toolCall.function.arguments); - - switch (toolCall.function.name) { - case "create_new_file": - return ( - - ); - case "run_terminal_command": - return ; - default: - return ( - <> -
{toolCall.function.name}
- {Object.entries(args)?.map(([key, value]) => ( -
- {key}: {JSON.stringify(value)} -
- ))} - - ); - } -} - export function ToolCallDiv(props: ToolCallDivProps) { - const ideMessenger = useContext(IdeMessengerContext); const dispatch = useDispatch(); - - const [state, setState] = useState("generating"); + const toolCallState = useSelector((store: RootState) => store.toolCallState); useEffect(() => { + dispatch(registerCurrentToolCall()); + }, []); + + useEffect(() => { + // Once the JSON can successfully parse, then set state to "generated" if (props.toolCall.function.arguments.length === 0) { return; } const [done, _] = incrementalParseJson(props.toolCall.function.arguments); if (done) { - setState("generated"); + dispatch(setGeneratedOutput(props.toolCall)); } }, [props.toolCall.function.arguments]); - async function cancelTool() { - setState("canceled"); - } - - async function callTool() { - let setCallingState = true; - - const timer = setTimeout(() => { - if (setCallingState) { - setState("calling"); - } - }, 800); - - const result = await ideMessenger.request("tools/call", { - toolCall: props.toolCall, - }); - - setCallingState = false; - clearTimeout(timer); - - if (result.status === "success") { - dispatch( - streamUpdate({ - role: "tool", - content: JSON.stringify(result.content.result), - toolCallId: props.toolCall.id, - }), - ); - setState("done"); - } - } - function getIcon(state: ToolState) { switch (state) { case "generating": @@ -162,32 +54,11 @@ export function ToolCallDiv(props: ToolCallDivProps) { } return ( - - - - {state === "generating" ? ( -
- Thinking... - {/* */} -
- ) : state === "generated" ? ( - <> - Cancel - Continue - - ) : state === "calling" ? ( -
- Loading... - -
- ) : null} -
+ + ); } diff --git a/gui/src/redux/slices/toolCallSlice.ts b/gui/src/redux/slices/toolCallSlice.ts new file mode 100644 index 000000000..2b18e898a --- /dev/null +++ b/gui/src/redux/slices/toolCallSlice.ts @@ -0,0 +1,45 @@ +import { createSlice, PayloadAction } from "@reduxjs/toolkit"; +import { ToolCall } from "core"; +import { ToolState } from "../../pages/gui/ToolCallDiv/types"; + +interface CurrentToolCallState { + currentToolCallId?: string; + currentToolCallState?: ToolState; + toolCall?: ToolCall; +} + +const initialState: CurrentToolCallState = {}; +export const toolCallStateSlice = createSlice({ + name: "editModeState", + initialState, + reducers: { + registerCurrentToolCall: (state, { payload }: PayloadAction) => { + state.currentToolCallId = payload; + state.currentToolCallState = "generating"; + }, + cancelToolCall: (state) => { + state.currentToolCallId = undefined; + state.currentToolCallState = undefined; + }, + acceptToolCall: (state) => { + state.currentToolCallId = undefined; + state.currentToolCallState = undefined; + }, + setGeneratedOutput: (state, { payload }: PayloadAction) => { + state.currentToolCallState = "generated"; + state.toolCall = payload; + }, + setCalling: (state) => { + state.currentToolCallState = "calling"; + }, + }, +}); + +export const { + registerCurrentToolCall, + setGeneratedOutput, + cancelToolCall, + acceptToolCall, + setCalling, +} = toolCallStateSlice.actions; +export default toolCallStateSlice.reducer; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 725d88c01..e1accc497 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -10,6 +10,7 @@ import { createFilter } from "redux-persist-transform-filter"; import autoMergeLevel2 from "redux-persist/lib/stateReconciler/autoMergeLevel2"; import storage from "redux-persist/lib/storage"; import editModeStateReducer from "./slices/editModeState"; +import toolCallStateSliceReducer from "./slices/toolCallSlice"; export interface ChatMessage { role: "system" | "user" | "assistant"; content: string; @@ -22,6 +23,7 @@ const rootReducer = combineReducers({ uiState: uiStateReducer, serverState: serverStateReducer, editModeState: editModeStateReducer, + toolCallState: toolCallStateSliceReducer, }); export type RootState = ReturnType; From 492f53bf46c7a556ce131cf2b1c4fe075a205bda Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 22:19:43 -0800 Subject: [PATCH 023/105] more tools --- core/index.d.ts | 1 + core/package-lock.json | 6 ++ core/package.json | 1 + core/tools/createNewFile.ts | 37 +++++++++++ core/tools/index.ts | 66 ++----------------- core/tools/runTerminalCommand.ts | 24 +++++++ core/tools/types.ts | 5 ++ core/util/incrementalParseJson.ts | 8 ++- extensions/vscode/package-lock.json | 1 + gui/package-lock.json | 1 + gui/src/pages/gui/Chat.tsx | 17 ++++- .../gui/ToolCallDiv/ToolCallButtonsDiv.tsx | 8 ++- gui/src/pages/gui/ToolCallDiv/index.tsx | 15 ++++- gui/src/redux/slices/stateSlice.ts | 51 ++++++++++++-- gui/src/redux/slices/toolCallSlice.ts | 45 ------------- gui/src/redux/store.ts | 2 - 16 files changed, 163 insertions(+), 125 deletions(-) create mode 100644 core/tools/createNewFile.ts create mode 100644 core/tools/runTerminalCommand.ts create mode 100644 core/tools/types.ts delete mode 100644 gui/src/redux/slices/toolCallSlice.ts diff --git a/core/index.d.ts b/core/index.d.ts index 780ded914..65fed30a0 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -336,6 +336,7 @@ export interface ChatHistoryItem { modifiers?: InputModifiers; contextItems: ContextItemWithId[]; promptLogs?: PromptLog[]; + acceptedToolCall?: boolean; } export type ChatHistory = ChatHistoryItem[]; diff --git a/core/package-lock.json b/core/package-lock.json index 09e22ce96..2c1361364 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -47,6 +47,7 @@ "onnxruntime-node": "1.14.0", "openai": "^4.20.1", "p-limit": "^6.1.0", + "partial-json": "^0.1.7", "pg": "^8.11.3", "posthog-node": "^3.6.3", "puppeteer": "^22.4.0", @@ -12077,6 +12078,11 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, + "node_modules/partial-json": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz", + "integrity": "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==" + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", diff --git a/core/package.json b/core/package.json index e95c66509..38d2aea0d 100644 --- a/core/package.json +++ b/core/package.json @@ -78,6 +78,7 @@ "onnxruntime-node": "1.14.0", "openai": "^4.20.1", "p-limit": "^6.1.0", + "partial-json": "^0.1.7", "pg": "^8.11.3", "posthog-node": "^3.6.3", "puppeteer": "^22.4.0", diff --git a/core/tools/createNewFile.ts b/core/tools/createNewFile.ts new file mode 100644 index 000000000..caadfc152 --- /dev/null +++ b/core/tools/createNewFile.ts @@ -0,0 +1,37 @@ +import { Tool } from ".."; +import { getPathModuleForIde } from "../util/pathModule"; +import { ToolParams } from "./types"; + +export const makeCreateNewFileTool = ({ ide }: ToolParams): Tool => ({ + type: "function", + action: async (args: any) => { + const pathSep = await ide.pathSep(); + let filepath = args.filepath; + if (!args.filepath.startsWith(pathSep)) { + const pathModule = await getPathModuleForIde(ide); + const workspaceDirs = await ide.getWorkspaceDirs(); + const cwd = workspaceDirs[0]; + filepath = pathModule.join(cwd, filepath); + } + await ide.writeFile(filepath, args.contents); + await ide.openFile(filepath); + }, + function: { + name: "create_new_file", + description: "Create a new file", + parameters: { + type: "object", + required: ["filepath", "contents"], + properties: { + filepath: { + type: "string", + description: "The path where the new file should be created", + }, + contents: { + type: "string", + description: "The contents to write to the new file", + }, + }, + }, + }, +}); diff --git a/core/tools/index.ts b/core/tools/index.ts index 862f7dd6b..5073562d5 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,65 +1,7 @@ -import { IDE, Tool } from ".."; -import { getPathModuleForIde } from "../util/pathModule"; - -export interface ToolParams { - ide: IDE; -} - -export const makeCreateNewFileTool = ({ ide }: ToolParams): Tool => ({ - type: "function", - action: async (args: any) => { - const pathSep = await ide.pathSep(); - let filepath = args.filepath; - if (!args.filepath.startsWith(pathSep)) { - const pathModule = await getPathModuleForIde(ide); - const workspaceDirs = await ide.getWorkspaceDirs(); - const cwd = workspaceDirs[0]; - filepath = pathModule.join(cwd, filepath); - } - await ide.writeFile(filepath, args.contents); - await ide.openFile(filepath); - }, - function: { - name: "create_new_file", - description: "Create a new file", - parameters: { - type: "object", - required: ["filepath", "contents"], - properties: { - filepath: { - type: "string", - description: "The path where the new file should be created", - }, - contents: { - type: "string", - description: "The contents to write to the new file", - }, - }, - }, - }, -}); - -export const runTerminalCommandTool = ({ ide }: ToolParams): Tool => ({ - type: "function", - action: async (args) => { - await ide.runCommand(args.command); - }, - function: { - name: "run_terminal_command", - description: "Run a terminal command in the current directory", - parameters: { - type: "object", - required: ["command"], - properties: { - command: { - type: "string", - description: - "The command to run. This will be passed directly into the shell.", - }, - }, - }, - }, -}); +import { Tool } from ".."; +import { makeCreateNewFileTool } from "./createNewFile"; +import { runTerminalCommandTool } from "./runTerminalCommand"; +import { ToolParams } from "./types"; export function instantiateTool(name: string, { ide }: ToolParams): Tool { switch (name) { diff --git a/core/tools/runTerminalCommand.ts b/core/tools/runTerminalCommand.ts new file mode 100644 index 000000000..15ce4c84b --- /dev/null +++ b/core/tools/runTerminalCommand.ts @@ -0,0 +1,24 @@ +import { Tool } from ".."; +import { ToolParams } from "./types"; + +export const runTerminalCommandTool = ({ ide }: ToolParams): Tool => ({ + type: "function", + action: async (args) => { + await ide.runCommand(args.command); + }, + function: { + name: "run_terminal_command", + description: "Run a terminal command in the current directory", + parameters: { + type: "object", + required: ["command"], + properties: { + command: { + type: "string", + description: + "The command to run. This will be passed directly into the shell.", + }, + }, + }, + }, +}); diff --git a/core/tools/types.ts b/core/tools/types.ts new file mode 100644 index 000000000..616f8ea5d --- /dev/null +++ b/core/tools/types.ts @@ -0,0 +1,5 @@ +import { IDE } from ".."; + +export interface ToolParams { + ide: IDE; +} diff --git a/core/util/incrementalParseJson.ts b/core/util/incrementalParseJson.ts index c72809035..21385ad6a 100644 --- a/core/util/incrementalParseJson.ts +++ b/core/util/incrementalParseJson.ts @@ -1,7 +1,13 @@ +import { parse } from "partial-json"; + export function incrementalParseJson(raw: string): [boolean, any] { try { return [true, JSON.parse(raw)]; } catch (e) { - return [false, {}]; + try { + return [false, parse(raw)]; + } catch (e2) { + return [false, {}]; + } } } diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 3dc6757e7..fb1219880 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -132,6 +132,7 @@ "onnxruntime-node": "1.14.0", "openai": "^4.20.1", "p-limit": "^6.1.0", + "partial-json": "^0.1.7", "pg": "^8.11.3", "posthog-node": "^3.6.3", "puppeteer": "^22.4.0", diff --git a/gui/package-lock.json b/gui/package-lock.json index 7d5bf06c9..1f857451c 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -134,6 +134,7 @@ "onnxruntime-node": "1.14.0", "openai": "^4.20.1", "p-limit": "^6.1.0", + "partial-json": "^0.1.7", "pg": "^8.11.3", "posthog-node": "^3.6.3", "puppeteer": "^22.4.0", diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 759c1e834..ef64de6dc 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -111,6 +111,7 @@ function fallbackRender({ error, resetErrorBoundary }: any) { >

Something went wrong:

{error.message}
+
{error.stack}
@@ -137,6 +138,10 @@ export function Chat() { const { saveSession, getLastSessionId, loadLastSession } = useHistory(dispatch); + const toolCallState = useSelector( + (store: RootState) => store.state.currentToolCallState, + ); + const snapToBottom = useCallback(() => { if (!stepsDivRef.current) return; const elem = stepsDivRef.current; @@ -348,7 +353,12 @@ export function Chat() { item.message.toolCalls ? (
{item.message.toolCalls?.map((toolCall) => { - return ; + return ( + + ); })}
) : ( @@ -423,7 +433,10 @@ export function Chat() { )}
- + + {toolCallState.currentToolCallState === "generated" && ( + + )} store.toolCallState); + const toolCallState = useSelector( + (store: RootState) => store.state.currentToolCallState, + ); const ideMessenger = useContext(IdeMessengerContext); async function callTool() { diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 6580c205e..1aa8c4a05 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -8,7 +8,7 @@ import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinne import { registerCurrentToolCall, setGeneratedOutput, -} from "../../../redux/slices/toolCallSlice"; +} from "../../../redux/slices/stateSlice"; import { RootState } from "../../../redux/store"; import FunctionSpecificToolCallDiv from "./FunctionSpecificToolCallDiv"; import { ThreadDiv } from "./ThreadDiv"; @@ -16,11 +16,14 @@ import { ToolState } from "./types"; interface ToolCallDivProps { toolCall: ToolCall; + acceptedToolCall?: boolean; } export function ToolCallDiv(props: ToolCallDivProps) { const dispatch = useDispatch(); - const toolCallState = useSelector((store: RootState) => store.toolCallState); + const toolCallState = useSelector( + (store: RootState) => store.state.currentToolCallState, + ); useEffect(() => { dispatch(registerCurrentToolCall()); @@ -39,11 +42,17 @@ export function ToolCallDiv(props: ToolCallDivProps) { }, [props.toolCall.function.arguments]); function getIcon(state: ToolState) { + if (props.acceptedToolCall === true) { + return ; + } else if (props.acceptedToolCall === false) { + return ; + } + switch (state) { case "generating": return ; case "done": - return ; + return ; case "calling": return ; case "canceled": diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 5855d0e54..aea7cbd7a 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -4,18 +4,23 @@ import { ChatHistoryItem, ChatMessage, Checkpoint, - ContextItemId, ContextItemWithId, PersistedSessionInfo, PromptLog, + ToolCall, } from "core"; import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { stripImages } from "core/llm/images"; -import { createSelector } from "reselect"; -import { v4 as uuidv4, v4 } from "uuid"; -import { RootState } from "../store"; import { ApplyState } from "core/protocol/ideWebview"; +import { v4 as uuidv4, v4 } from "uuid"; +import { ToolState } from "../../pages/gui/ToolCallDiv/types"; + +interface CurrentToolCallState { + currentToolCallId?: string; + currentToolCallState?: ToolState; + toolCall?: ToolCall; +} // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -23,6 +28,7 @@ type ChatHistoryItemWithMessageId = ChatHistoryItem & { message: ChatMessage & { id: string }; }; type State = { + currentToolCallState: CurrentToolCallState; history: ChatHistoryItemWithMessageId[]; ttsActive: boolean; active: boolean; @@ -42,6 +48,10 @@ type State = { }; const initialState: State = { + currentToolCallState: { + currentToolCallId: undefined, + currentToolCallState: undefined, + }, history: [], ttsActive: false, active: false, @@ -181,7 +191,6 @@ export const stateSlice = createSlice({ editorState: JSONContent; }>, ) => { - console.log("OAEJFOIJOJOJAJ"); state.history.push({ message: { role: "user", content: "", id: uuidv4() }, contextItems: [], @@ -209,7 +218,6 @@ export const stateSlice = createSlice({ contextItems?: ContextItemWithId[]; }>, ) => { - console.log("aoiujnnnnnnn"); if (payload.index >= state.history.length) { state.history.push({ message: { ...payload.message, id: uuidv4() }, @@ -387,13 +395,36 @@ export const stateSlice = createSlice({ curApplyState.numDiffs = payload.numDiffs ?? curApplyState.numDiffs; curApplyState.filepath = payload.filepath ?? curApplyState.filepath; } - if(payload.status === "done"){ + if (payload.status === "done") { state.nextCodeBlockToApplyIndex++; } }, resetNextCodeBlockToApplyIndex: (state) => { state.nextCodeBlockToApplyIndex = 0; }, + + // Related to currentToolCallState + registerCurrentToolCall: (state, { payload }: PayloadAction) => { + state.currentToolCallState.currentToolCallId = payload; + state.currentToolCallState.currentToolCallState = "generating"; + }, + cancelToolCall: (state) => { + state.currentToolCallState.currentToolCallId = undefined; + state.currentToolCallState.currentToolCallState = undefined; + state.history[state.history.length - 1].acceptedToolCall = false; + }, + acceptToolCall: (state) => { + state.currentToolCallState.currentToolCallId = undefined; + state.currentToolCallState.currentToolCallState = undefined; + state.history[state.history.length - 1].acceptedToolCall = true; + }, + setGeneratedOutput: (state, { payload }: PayloadAction) => { + state.currentToolCallState.currentToolCallState = "generated"; + state.currentToolCallState.toolCall = payload; + }, + setCalling: (state) => { + state.currentToolCallState.currentToolCallState = "calling"; + }, }, }); @@ -423,6 +454,12 @@ export const { setCurCheckpointIndex, resetNextCodeBlockToApplyIndex, updateApplyState, + // toolCallState + registerCurrentToolCall, + setGeneratedOutput, + cancelToolCall, + acceptToolCall, + setCalling, } = stateSlice.actions; export default stateSlice.reducer; diff --git a/gui/src/redux/slices/toolCallSlice.ts b/gui/src/redux/slices/toolCallSlice.ts deleted file mode 100644 index 2b18e898a..000000000 --- a/gui/src/redux/slices/toolCallSlice.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { createSlice, PayloadAction } from "@reduxjs/toolkit"; -import { ToolCall } from "core"; -import { ToolState } from "../../pages/gui/ToolCallDiv/types"; - -interface CurrentToolCallState { - currentToolCallId?: string; - currentToolCallState?: ToolState; - toolCall?: ToolCall; -} - -const initialState: CurrentToolCallState = {}; -export const toolCallStateSlice = createSlice({ - name: "editModeState", - initialState, - reducers: { - registerCurrentToolCall: (state, { payload }: PayloadAction) => { - state.currentToolCallId = payload; - state.currentToolCallState = "generating"; - }, - cancelToolCall: (state) => { - state.currentToolCallId = undefined; - state.currentToolCallState = undefined; - }, - acceptToolCall: (state) => { - state.currentToolCallId = undefined; - state.currentToolCallState = undefined; - }, - setGeneratedOutput: (state, { payload }: PayloadAction) => { - state.currentToolCallState = "generated"; - state.toolCall = payload; - }, - setCalling: (state) => { - state.currentToolCallState = "calling"; - }, - }, -}); - -export const { - registerCurrentToolCall, - setGeneratedOutput, - cancelToolCall, - acceptToolCall, - setCalling, -} = toolCallStateSlice.actions; -export default toolCallStateSlice.reducer; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index e1accc497..725d88c01 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -10,7 +10,6 @@ import { createFilter } from "redux-persist-transform-filter"; import autoMergeLevel2 from "redux-persist/lib/stateReconciler/autoMergeLevel2"; import storage from "redux-persist/lib/storage"; import editModeStateReducer from "./slices/editModeState"; -import toolCallStateSliceReducer from "./slices/toolCallSlice"; export interface ChatMessage { role: "system" | "user" | "assistant"; content: string; @@ -23,7 +22,6 @@ const rootReducer = combineReducers({ uiState: uiStateReducer, serverState: serverStateReducer, editModeState: editModeStateReducer, - toolCallState: toolCallStateSliceReducer, }); export type RootState = ReturnType; From 71680480d4027ba88c2903c3d588ef0442427258 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 20 Nov 2024 12:04:59 -0800 Subject: [PATCH 024/105] more tools --- .../generation/ListenableGenerator.test.ts | 37 +++++++++++--- core/config/load.ts | 10 ++-- core/context/providers/WebContextProvider.ts | 49 ++++++++++++------- core/core.ts | 24 +++++++-- core/index.d.ts | 10 +++- core/test/llm.test.ts | 14 ++++-- core/tools/createNewFile.ts | 17 +++---- core/tools/exactSearch.ts | 23 +++++++++ core/tools/index.ts | 29 ++++++----- core/tools/runTerminalCommand.ts | 9 ++-- core/tools/searchWeb.ts | 24 +++++++++ core/tools/types.ts | 5 -- core/tools/viewDiff.ts | 14 ++++++ core/tools/viewFileTree.ts | 24 +++++++++ core/tools/viewSubdirectory.ts | 27 ++++++++++ extensions/vscode/package-lock.json | 4 +- 16 files changed, 246 insertions(+), 74 deletions(-) create mode 100644 core/tools/exactSearch.ts create mode 100644 core/tools/searchWeb.ts delete mode 100644 core/tools/types.ts create mode 100644 core/tools/viewDiff.ts create mode 100644 core/tools/viewFileTree.ts create mode 100644 core/tools/viewSubdirectory.ts diff --git a/core/autocomplete/generation/ListenableGenerator.test.ts b/core/autocomplete/generation/ListenableGenerator.test.ts index 69797959e..916d8dbef 100644 --- a/core/autocomplete/generation/ListenableGenerator.test.ts +++ b/core/autocomplete/generation/ListenableGenerator.test.ts @@ -1,4 +1,5 @@ import { jest } from "@jest/globals"; + import { ListenableGenerator } from "./ListenableGenerator"; describe("ListenableGenerator", () => { @@ -17,7 +18,11 @@ describe("ListenableGenerator", () => { const source = asyncGenerator(values); const onError = jest.fn(); - const lg = new ListenableGenerator(source, onError); + const lg = new ListenableGenerator( + source, + onError, + new AbortController(), + ); const result: number[] = []; for await (const value of lg.tee()) { @@ -33,7 +38,11 @@ describe("ListenableGenerator", () => { const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior const onError = jest.fn(); - const lg = new ListenableGenerator(source, onError); + const lg = new ListenableGenerator( + source, + onError, + new AbortController(), + ); const listener = jest.fn(); @@ -57,7 +66,11 @@ describe("ListenableGenerator", () => { const source = asyncGenerator(values, 10); const onError = jest.fn(); - const lg = new ListenableGenerator(source, onError); + const lg = new ListenableGenerator( + source, + onError, + new AbortController(), + ); const initialListener = jest.fn(); @@ -87,7 +100,11 @@ describe("ListenableGenerator", () => { const source = asyncGenerator(values, 10); const onError = jest.fn(); - const lg = new ListenableGenerator(source, onError); + const lg = new ListenableGenerator( + source, + onError, + new AbortController(), + ); const result: number[] = []; const teeIterator = lg.tee(); @@ -116,7 +133,11 @@ describe("ListenableGenerator", () => { const source = errorGenerator(); const onError = jest.fn(); - const lg = new ListenableGenerator(source, onError); + const lg = new ListenableGenerator( + source, + onError, + new AbortController(), + ); const result: number[] = []; for await (const value of lg.tee()) { @@ -133,7 +154,11 @@ describe("ListenableGenerator", () => { const source = asyncGenerator(values); const onError = jest.fn(); - const lg = new ListenableGenerator(source, onError); + const lg = new ListenableGenerator( + source, + onError, + new AbortController(), + ); const listener = jest.fn(); lg.listen(listener); diff --git a/core/config/load.ts b/core/config/load.ts index 603d38e01..627d59b67 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -1,10 +1,11 @@ import { execSync } from "child_process"; -import * as JSONC from "comment-json"; import * as fs from "fs"; import os from "os"; import path from "path"; +import * as JSONC from "comment-json"; import * as tar from "tar"; + import { BrowserSerializedContinueConfig, Config, @@ -58,7 +59,7 @@ import { readAllGlobalPromptFiles, } from "../util/paths"; -import { makeCreateNewFileTool, runTerminalCommandTool } from "../tools"; +import { allTools } from "../tools"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -336,10 +337,7 @@ async function intermediateToFinalConfig( ...model.requestOptions, ...config.requestOptions, }; - model.completionOptions.tools = [ - makeCreateNewFileTool({ ide }), - runTerminalCommandTool({ ide }), - ]; + model.completionOptions.tools = allTools; } if (allowFreeTrial) { diff --git a/core/context/providers/WebContextProvider.ts b/core/context/providers/WebContextProvider.ts index 2c8cb8928..9ea4bac41 100644 --- a/core/context/providers/WebContextProvider.ts +++ b/core/context/providers/WebContextProvider.ts @@ -3,12 +3,37 @@ import { ContextItem, ContextProviderDescription, ContextProviderExtras, + FetchFunction, } from "../.."; import { getHeaders } from "../../continueServer/stubs/headers"; import { TRIAL_PROXY_URL } from "../../control-plane/client"; +export const fetchSearchResults = async ( + query: string, + n: number, + fetchFn: FetchFunction, +): Promise => { + const resp = await fetchFn(WebContextProvider.ENDPOINT, { + method: "POST", + headers: { + "Content-Type": "application/json", + ...(await getHeaders()), + }, + body: JSON.stringify({ + query, + n, + }), + }); + + if (!resp.ok) { + const text = await resp.text(); + throw new Error(`Failed to fetch web context: ${text}`); + } + return await resp.json(); +}; + export default class WebContextProvider extends BaseContextProvider { - private static ENDPOINT = new URL("web", TRIAL_PROXY_URL); + public static ENDPOINT = new URL("web", TRIAL_PROXY_URL); private static DEFAULT_N = 6; static description: ContextProviderDescription = { @@ -23,22 +48,10 @@ export default class WebContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { - const resp = await extras.fetch(WebContextProvider.ENDPOINT, { - method: "POST", - headers: { - "Content-Type": "application/json", - ...(await getHeaders()), - }, - body: JSON.stringify({ - query: extras.fullInput, - n: this.options.n ?? WebContextProvider.DEFAULT_N, - }), - }); - if (!resp.ok) { - const text = await resp.text(); - throw new Error(`Failed to fetch web context: ${text}`); - } - const json = await resp.json(); - return json; + return await fetchSearchResults( + extras.fullInput, + this.options.n ?? WebContextProvider.DEFAULT_N, + extras.fetch, + ); } } diff --git a/core/core.ts b/core/core.ts index 76edfdd42..6541ddd92 100644 --- a/core/core.ts +++ b/core/core.ts @@ -34,7 +34,7 @@ import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; -import { instantiateTool } from "./tools"; +import { allTools } from "./tools"; import type { IMessenger, Message } from "./util/messenger"; export class Core { @@ -751,8 +751,26 @@ export class Core { }); on("tools/call", async ({ data: { toolCall } }) => { - const tool = instantiateTool(toolCall.function.name, { ide: this.ide }); - const result = await tool.action(JSON.parse(toolCall.function.arguments)); + const tool = allTools.find( + (t) => t.function.name === toolCall.function.name, + ); + + if (!tool) { + return { error: "Tool not found", result: undefined }; + } + + const config = await this.configHandler.loadConfig(); + const llm = await this.getSelectedModel(); + + const result = await tool.action( + JSON.parse(toolCall.function.arguments), + { + ide: this.ide, + llm, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), + }, + ); return { result }; }); } diff --git a/core/index.d.ts b/core/index.d.ts index 2d24cc1ca..e025ccdb6 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -81,7 +81,7 @@ export interface ILLM extends LLMOptions { complete( prompt: string, signal: AbortSignal, - options?: LLMFullCompletionOptions + options?: LLMFullCompletionOptions, ): Promise; streamComplete( @@ -846,6 +846,12 @@ interface Prediction { }[]; } +export interface ToolExtras { + ide: IDE; + llm: ILLM; + fetch: FetchFunction; +} + export interface Tool { type: "function"; function: { @@ -854,7 +860,7 @@ export interface Tool { parameters?: Record; strict?: boolean | null; }; - action: (parameters: any) => Promise; + action: (parameters: any, extras: ToolExtras) => Promise; } interface BaseCompletionOptions { diff --git a/core/test/llm.test.ts b/core/test/llm.test.ts index 2cb81da72..cf42e128a 100644 --- a/core/test/llm.test.ts +++ b/core/test/llm.test.ts @@ -26,9 +26,10 @@ function testLLM(llm: BaseLLM) { describe(llm.providerName, () => { test("Stream Chat works", async () => { let total = ""; - for await (const chunk of llm.streamChat([ - { role: "user", content: "Hi" }, - ])) { + for await (const chunk of llm.streamChat( + [{ role: "user", content: "Hi" }], + new AbortController().signal, + )) { total += chunk.content; } @@ -38,7 +39,10 @@ function testLLM(llm: BaseLLM) { test("Stream Complete works", async () => { let total = ""; - for await (const chunk of llm.streamComplete("Hi")) { + for await (const chunk of llm.streamComplete( + "Hi", + new AbortController().signal, + )) { total += chunk; } @@ -47,7 +51,7 @@ function testLLM(llm: BaseLLM) { }); test("Complete works", async () => { - const completion = await llm.complete("Hi"); + const completion = await llm.complete("Hi", new AbortController().signal); expect(completion.length).toBeGreaterThan(0); return; diff --git a/core/tools/createNewFile.ts b/core/tools/createNewFile.ts index caadfc152..4d0b1c7a1 100644 --- a/core/tools/createNewFile.ts +++ b/core/tools/createNewFile.ts @@ -1,20 +1,19 @@ import { Tool } from ".."; import { getPathModuleForIde } from "../util/pathModule"; -import { ToolParams } from "./types"; -export const makeCreateNewFileTool = ({ ide }: ToolParams): Tool => ({ +export const createNewFileTool: Tool = { type: "function", - action: async (args: any) => { - const pathSep = await ide.pathSep(); + action: async (args, extras) => { + const pathSep = await extras.ide.pathSep(); let filepath = args.filepath; if (!args.filepath.startsWith(pathSep)) { - const pathModule = await getPathModuleForIde(ide); - const workspaceDirs = await ide.getWorkspaceDirs(); + const pathModule = await getPathModuleForIde(extras.ide); + const workspaceDirs = await extras.ide.getWorkspaceDirs(); const cwd = workspaceDirs[0]; filepath = pathModule.join(cwd, filepath); } - await ide.writeFile(filepath, args.contents); - await ide.openFile(filepath); + await extras.ide.writeFile(filepath, args.contents); + await extras.ide.openFile(filepath); }, function: { name: "create_new_file", @@ -34,4 +33,4 @@ export const makeCreateNewFileTool = ({ ide }: ToolParams): Tool => ({ }, }, }, -}); +}; diff --git a/core/tools/exactSearch.ts b/core/tools/exactSearch.ts new file mode 100644 index 000000000..2735b24a0 --- /dev/null +++ b/core/tools/exactSearch.ts @@ -0,0 +1,23 @@ +import { Tool } from ".."; + +export const exactSearchTool: Tool = { + type: "function", + action: async (args, extras) => { + const results = await extras.ide.getSearchResults(args.query); + return results; + }, + function: { + name: "exact_search", + description: "Perform an exact search over the repository using ripgrep", + parameters: { + type: "object", + required: ["query"], + properties: { + query: { + type: "string", + description: "The search query to use", + }, + }, + }, + }, +}; diff --git a/core/tools/index.ts b/core/tools/index.ts index 5073562d5..892b27ce2 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,15 +1,18 @@ -import { Tool } from ".."; -import { makeCreateNewFileTool } from "./createNewFile"; +import { createNewFileTool } from "./createNewFile"; +import { exactSearchTool } from "./exactSearch"; import { runTerminalCommandTool } from "./runTerminalCommand"; -import { ToolParams } from "./types"; +import { searchWebTool } from "./searchWeb"; +import { viewDiffTool } from "./viewDiff"; +import { viewFileTreeTool } from "./viewFileTree"; +import { viewSubdirectoryTool } from "./viewSubdirectory"; -export function instantiateTool(name: string, { ide }: ToolParams): Tool { - switch (name) { - case "create_new_file": - return makeCreateNewFileTool({ ide }); - case "run_terminal_command": - return runTerminalCommandTool({ ide }); - default: - throw new Error(`Unknown tool ${name}`); - } -} +export const allTools = [ + createNewFileTool, + runTerminalCommandTool, + runTerminalCommandTool, + viewSubdirectoryTool, + viewFileTreeTool, + exactSearchTool, + searchWebTool, + viewDiffTool, +]; diff --git a/core/tools/runTerminalCommand.ts b/core/tools/runTerminalCommand.ts index 15ce4c84b..4982ec972 100644 --- a/core/tools/runTerminalCommand.ts +++ b/core/tools/runTerminalCommand.ts @@ -1,10 +1,9 @@ import { Tool } from ".."; -import { ToolParams } from "./types"; -export const runTerminalCommandTool = ({ ide }: ToolParams): Tool => ({ +export const runTerminalCommandTool: Tool = { type: "function", - action: async (args) => { - await ide.runCommand(args.command); + action: async (args, extras) => { + await extras.ide.runCommand(args.command); }, function: { name: "run_terminal_command", @@ -21,4 +20,4 @@ export const runTerminalCommandTool = ({ ide }: ToolParams): Tool => ({ }, }, }, -}); +}; diff --git a/core/tools/searchWeb.ts b/core/tools/searchWeb.ts new file mode 100644 index 000000000..8f438ce2f --- /dev/null +++ b/core/tools/searchWeb.ts @@ -0,0 +1,24 @@ +import { Tool } from ".."; +import { fetchSearchResults } from "../context/providers/WebContextProvider"; + +export const searchWebTool: Tool = { + type: "function", + action: async (args, extras) => { + const webResults = await fetchSearchResults(args.query, 5, extras.fetch); + return webResults.map((result) => result.content).join("\n\n"); + }, + function: { + name: "search_web", + description: "Perform a web search and get back top results", + parameters: { + type: "object", + required: ["query"], + properties: { + repo_url: { + type: "string", + description: "The natural language search query", + }, + }, + }, + }, +}; diff --git a/core/tools/types.ts b/core/tools/types.ts deleted file mode 100644 index 616f8ea5d..000000000 --- a/core/tools/types.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { IDE } from ".."; - -export interface ToolParams { - ide: IDE; -} diff --git a/core/tools/viewDiff.ts b/core/tools/viewDiff.ts new file mode 100644 index 000000000..ed03d832f --- /dev/null +++ b/core/tools/viewDiff.ts @@ -0,0 +1,14 @@ +import { Tool } from ".."; + +export const viewDiffTool: Tool = { + type: "function", + action: async (args, extras) => { + const diff = await extras.ide.getDiff(true); + return diff; + }, + function: { + name: "view_diff", + description: "View the current diff of working changes", + parameters: {}, + }, +}; diff --git a/core/tools/viewFileTree.ts b/core/tools/viewFileTree.ts new file mode 100644 index 000000000..9fb8ff368 --- /dev/null +++ b/core/tools/viewFileTree.ts @@ -0,0 +1,24 @@ +import { Tool } from ".."; +import generateRepoMap from "../util/generateRepoMap"; + +export const viewFileTreeTool: Tool = { + type: "function", + action: async (args, extras) => { + const repoMap = await generateRepoMap(extras.llm, extras.ide, {}); + return repoMap; + }, + function: { + name: "view_repo_map", + description: "View the repository map", + parameters: { + type: "object", + required: ["repo_url"], + properties: { + repo_url: { + type: "string", + description: "The URL of the repository to view", + }, + }, + }, + }, +}; diff --git a/core/tools/viewSubdirectory.ts b/core/tools/viewSubdirectory.ts new file mode 100644 index 000000000..c3e83a39a --- /dev/null +++ b/core/tools/viewSubdirectory.ts @@ -0,0 +1,27 @@ +import { Tool } from ".."; +import generateRepoMap from "../util/generateRepoMap"; + +export const viewSubdirectoryTool: Tool = { + type: "function", + action: async (args: any, extras) => { + const { directory_path } = args; + const repoMap = await generateRepoMap(extras.llm, extras.ide, { + dirs: [directory_path], + }); + return repoMap; + }, + function: { + name: "view_subdirectory", + description: "View the contents of a subdirectory", + parameters: { + type: "object", + required: ["directory_path"], + properties: { + directory_path: { + type: "string", + description: "The path of the subdirectory to view", + }, + }, + }, + }, +}; diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index fb1219880..31c9a041c 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.231", + "version": "0.9.232", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.231", + "version": "0.9.232", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", From 2ccf532b09c4b184043d72ebb9659bab140b6fe5 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 20 Nov 2024 14:00:57 -0800 Subject: [PATCH 025/105] fixes --- core/tools/index.ts | 1 - core/tools/viewDiff.ts | 5 ++++- extensions/vscode/src/autocomplete/completionProvider.ts | 4 ++-- gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx | 9 ++++++++- 4 files changed, 14 insertions(+), 5 deletions(-) diff --git a/core/tools/index.ts b/core/tools/index.ts index 892b27ce2..3eda0ce49 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -9,7 +9,6 @@ import { viewSubdirectoryTool } from "./viewSubdirectory"; export const allTools = [ createNewFileTool, runTerminalCommandTool, - runTerminalCommandTool, viewSubdirectoryTool, viewFileTreeTool, exactSearchTool, diff --git a/core/tools/viewDiff.ts b/core/tools/viewDiff.ts index ed03d832f..82439c54c 100644 --- a/core/tools/viewDiff.ts +++ b/core/tools/viewDiff.ts @@ -9,6 +9,9 @@ export const viewDiffTool: Tool = { function: { name: "view_diff", description: "View the current diff of working changes", - parameters: {}, + parameters: { + type: "object", + properties: {}, + }, }, }; diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 0df8e58b1..c7d0553a0 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -19,8 +19,8 @@ import { stopStatusBarLoading, } from "./statusBar"; -import type { TabAutocompleteModel } from "../util/loadAutocompleteModel"; import type { IDE } from "core"; +import type { TabAutocompleteModel } from "../util/loadAutocompleteModel"; interface VsCodeCompletionInput { document: vscode.TextDocument; @@ -42,7 +42,7 @@ export class ContinueCompletionProvider e.message, this.configHandler.reloadConfig.bind(this.configHandler), () => { - void this.webviewProtocol.request("openOnboardingCard", undefined) + void this.webviewProtocol.request("openOnboardingCard", undefined); }, ); return; diff --git a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx index 65efb7678..fdb7bc721 100644 --- a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx @@ -31,7 +31,14 @@ export function ThreadDiv(props: ThreadDivProps) { return ( -
+
{props.icon}
Continue wants to create a new file From e0b08489c829eb7d401919649c76a4768a1e988e Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 20 Nov 2024 14:18:12 -0800 Subject: [PATCH 026/105] request messages --- core/tools/index.ts | 4 +-- .../tools/{viewFileTree.ts => viewRepoMap.ts} | 2 +- .../ToolCallDiv/FunctionSpecificHeader.tsx | 31 +++++++++++++++++++ gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx | 5 ++- gui/src/pages/gui/ToolCallDiv/index.tsx | 5 ++- 5 files changed, 42 insertions(+), 5 deletions(-) rename core/tools/{viewFileTree.ts => viewRepoMap.ts} (93%) create mode 100644 gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx diff --git a/core/tools/index.ts b/core/tools/index.ts index 3eda0ce49..12667259b 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -3,14 +3,14 @@ import { exactSearchTool } from "./exactSearch"; import { runTerminalCommandTool } from "./runTerminalCommand"; import { searchWebTool } from "./searchWeb"; import { viewDiffTool } from "./viewDiff"; -import { viewFileTreeTool } from "./viewFileTree"; +import { viewRepoMapTool } from "./viewRepoMap"; import { viewSubdirectoryTool } from "./viewSubdirectory"; export const allTools = [ createNewFileTool, runTerminalCommandTool, viewSubdirectoryTool, - viewFileTreeTool, + viewRepoMapTool, exactSearchTool, searchWebTool, viewDiffTool, diff --git a/core/tools/viewFileTree.ts b/core/tools/viewRepoMap.ts similarity index 93% rename from core/tools/viewFileTree.ts rename to core/tools/viewRepoMap.ts index 9fb8ff368..5f8e09146 100644 --- a/core/tools/viewFileTree.ts +++ b/core/tools/viewRepoMap.ts @@ -1,7 +1,7 @@ import { Tool } from ".."; import generateRepoMap from "../util/generateRepoMap"; -export const viewFileTreeTool: Tool = { +export const viewRepoMapTool: Tool = { type: "function", action: async (args, extras) => { const repoMap = await generateRepoMap(extras.llm, extras.ide, {}); diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx new file mode 100644 index 000000000..858c2e46c --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx @@ -0,0 +1,31 @@ +import { ToolCall } from "core"; +import { incrementalParseJson } from "core/util/incrementalParseJson"; + +interface FunctionSpecificHeaderProps { + toolCall: ToolCall; +} + +export function FunctionSpecificHeader(props: FunctionSpecificHeaderProps) { + const [done, incrementalJson] = incrementalParseJson( + props.toolCall.function.arguments, + ); + + switch (props.toolCall.function.name) { + case "create_new_file": + return "Continue wants to create a new file"; + case "run_terminal_command": + return "Continue wantsto run a terminal command."; + case "exact_search": + return "Continue wants to search your codebase"; + case "search_web": + return "Continue wants to search the internet"; + case "view_diff": + return "Continue wants to view the current git diff"; + case "view_repo_map": + return "Continue wants to view a map of your repository"; + case "view_subdirectory": + return `Continue wants to view the contents of ${incrementalJson.directory_path ?? "a subdirectory"}`; + default: + return `Continue wants to use the ${props.toolCall.function.name} function.`; + } +} diff --git a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx index fdb7bc721..351d7e466 100644 --- a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx @@ -1,8 +1,11 @@ +import { ToolCall } from "core"; import styled from "styled-components"; +import { FunctionSpecificHeader } from "./FunctionSpecificHeader"; interface ThreadDivProps { children: React.ReactNode; icon: React.ReactNode; + toolCall: ToolCall; } const Container = styled.div` @@ -41,7 +44,7 @@ export function ThreadDiv(props: ThreadDivProps) { > {props.icon}
- Continue wants to create a new file +
{props.children}
diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 1aa8c4a05..330c6fdcd 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -63,7 +63,10 @@ export function ToolCallDiv(props: ToolCallDivProps) { } return ( - + Date: Wed, 20 Nov 2024 14:47:31 -0800 Subject: [PATCH 027/105] WIP --- core/core.ts | 2 +- core/tools/viewRepoMap.ts | 8 +---- gui/src/pages/gui/Chat.tsx | 6 +++- .../FunctionSpecificToolCallDiv.tsx | 11 +----- gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx | 1 - gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx | 36 +++++++++++++++++++ gui/src/pages/gui/ToolCallDiv/index.tsx | 3 +- 7 files changed, 46 insertions(+), 21 deletions(-) create mode 100644 gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx diff --git a/core/core.ts b/core/core.ts index 6541ddd92..ad1ed3be7 100644 --- a/core/core.ts +++ b/core/core.ts @@ -763,7 +763,7 @@ export class Core { const llm = await this.getSelectedModel(); const result = await tool.action( - JSON.parse(toolCall.function.arguments), + JSON.parse(toolCall.function.arguments || "{}"), { ide: this.ide, llm, diff --git a/core/tools/viewRepoMap.ts b/core/tools/viewRepoMap.ts index 5f8e09146..c96f5ed27 100644 --- a/core/tools/viewRepoMap.ts +++ b/core/tools/viewRepoMap.ts @@ -12,13 +12,7 @@ export const viewRepoMapTool: Tool = { description: "View the repository map", parameters: { type: "object", - required: ["repo_url"], - properties: { - repo_url: { - type: "string", - description: "The URL of the repository to view", - }, - }, + properties: {}, }, }, }; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index ef64de6dc..ec4b320b2 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -63,6 +63,7 @@ import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import { ToolCallDiv } from "./ToolCallDiv"; import { ToolCallButtons } from "./ToolCallDiv/ToolCallButtonsDiv"; +import ToolOutput from "./ToolCallDiv/ToolOutput"; const StopButton = styled.div` background-color: ${vscBackground}; @@ -348,7 +349,10 @@ export function Chat() { contextItems={item.contextItems} /> ) : item.message.role === "tool" ? ( -
{stripImages(item.message.content)}
+ ) : item.message.role === "assistant" && item.message.toolCalls ? (
diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 151f3e5f9..27bd820a8 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -25,16 +25,7 @@ function FunctionSpecificToolCallDiv({ case "run_terminal_command": return ; default: - return ( - <> -
{toolCall.function.name}
- {Object.entries(args)?.map(([key, value]) => ( -
- {key}: {JSON.stringify(value)} -
- ))} - - ); + return null; } } diff --git a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx index 351d7e466..ef42c4a44 100644 --- a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx @@ -18,7 +18,6 @@ const Container = styled.div` const ChildrenDiv = styled.div` margin: 8px; - margin-left: 0; `; const W = 16; diff --git a/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx b/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx new file mode 100644 index 000000000..0e6c6b245 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx @@ -0,0 +1,36 @@ +import ContextItemsPeek from "../../../components/mainInput/ContextItemsPeek"; + +interface ToolOutputProps { + output: string; + toolCallId: string; +} + +function ToolOutput(props: ToolOutputProps) { + if ( + props.output === undefined || + props.output === null || + props.output.trim() === "" + ) { + return null; + } + return ( +
+ +
+ ); +} + +export default ToolOutput; diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 330c6fdcd..3235dd2d7 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -32,10 +32,11 @@ export function ToolCallDiv(props: ToolCallDivProps) { useEffect(() => { // Once the JSON can successfully parse, then set state to "generated" if (props.toolCall.function.arguments.length === 0) { + dispatch(setGeneratedOutput(props.toolCall)); return; } - const [done, _] = incrementalParseJson(props.toolCall.function.arguments); + const [done, j] = incrementalParseJson(props.toolCall.function.arguments); if (done) { dispatch(setGeneratedOutput(props.toolCall)); } From b54b4feb78187fa99507eaf4b45fa55001dc704b Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 20 Nov 2024 15:16:22 -0800 Subject: [PATCH 028/105] remove unecessary if statement --- gui/src/hooks/useChatHandler.ts | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index c332be793..28b1add9a 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -191,13 +191,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { dispatch(setCurCheckpointIndex(Math.floor(index / 2))); } - const shouldGatherContext = - modifiers.useCodebase || hasSlashCommandOrContextProvider(editorState); - - if (shouldGatherContext) { - dispatch(setIsGatheringContext(true)); - } - + dispatch(setIsGatheringContext(true)); // Resolve context providers and construct new history const [selectedContextItems, selectedCode, content] = await resolveEditorContent( @@ -212,7 +206,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { // Automatically use currently open file if (!modifiers.noContext) { const usingFreeTrial = defaultModel?.provider === "free-trial"; - const currentFile = await ideMessenger.ide.getCurrentFile(); if (currentFile) { let currentFileContents = currentFile.contents; From 28952ba9acc2594e0720dc2f1b89906226d119e0 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 20 Nov 2024 16:02:31 -0800 Subject: [PATCH 029/105] streaming after tools --- gui/src/hooks/useChatHandler.ts | 318 +++++++++++------- .../gui/ToolCallDiv/ToolCallButtonsDiv.tsx | 25 +- 2 files changed, 206 insertions(+), 137 deletions(-) diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 28b1add9a..21face2a7 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -17,18 +17,18 @@ import { getBasename, getRelativePath } from "core/util"; import { usePostHog } from "posthog-js/react"; import { useEffect, useRef, useState } from "react"; import { useSelector } from "react-redux"; -import resolveEditorContent, { - hasSlashCommandOrContextProvider, -} from "../components/mainInput/resolveInput"; +import resolveEditorContent from "../components/mainInput/resolveInput"; import { IIdeMessenger } from "../context/IdeMessenger"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { abortStream, + acceptToolCall, addPromptCompletionPair, clearLastResponse, initNewActiveMessage, resetNextCodeBlockToApplyIndex, resubmitAtIndex, + setActive, setCurCheckpointIndex, setInactive, setIsGatheringContext, @@ -171,136 +171,73 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { clearInterval(checkActiveInterval); } - async function streamResponse( + function resetStateForNewMessage() { + // Reset current code block index + dispatch(resetNextCodeBlockToApplyIndex()); + } + + async function gatherContext( editorState: JSONContent, modifiers: InputModifiers, ideMessenger: IIdeMessenger, - index?: number, ) { - try { - if (typeof index === "number") { - dispatch(resubmitAtIndex({ index, editorState })); - } else { - dispatch(initNewActiveMessage({ editorState })); - } - - // Reset current code block index - dispatch(resetNextCodeBlockToApplyIndex()); - - if (index) { - dispatch(setCurCheckpointIndex(Math.floor(index / 2))); - } - - dispatch(setIsGatheringContext(true)); - // Resolve context providers and construct new history - const [selectedContextItems, selectedCode, content] = - await resolveEditorContent( - editorState, - modifiers, - ideMessenger, - defaultContextProviders, - ); - - dispatch(setIsGatheringContext(false)); - - // Automatically use currently open file - if (!modifiers.noContext) { - const usingFreeTrial = defaultModel?.provider === "free-trial"; - const currentFile = await ideMessenger.ide.getCurrentFile(); - if (currentFile) { - let currentFileContents = currentFile.contents; - if (usingFreeTrial) { - currentFileContents = currentFile.contents - .split("\n") - .slice(0, 1000) - .join("\n"); - } - if ( - !selectedContextItems.find( - (item) => item.uri?.value === currentFile.path, - ) - ) { - // don't add the file if it's already in the context items - selectedContextItems.unshift({ - content: `The following file is currently open. Don't reference it if it's not relevant to the user's message.\n\n\`\`\`${getRelativePath( - currentFile.path, - await ideMessenger.ide.getWorkspaceDirs(), - )}\n${currentFileContents}\n\`\`\``, - name: `Active file: ${getBasename(currentFile.path)}`, - description: currentFile.path, - id: { - itemId: currentFile.path, - providerTitle: "file", - }, - uri: { - type: "file", - value: currentFile.path, - }, - }); - } - } - } - - // dispatch(addContextItems(contextItems)); - - const message: ChatMessage = { - role: "user", - content, - }; - - const historyItem: ChatHistoryItem = { - message, - contextItems: selectedContextItems, + // Resolve context providers and construct new history + dispatch(setIsGatheringContext(true)); + const [selectedContextItems, selectedCode, content] = + await resolveEditorContent( editorState, - }; - - let newHistory: ChatHistory = [...history.slice(0, index), historyItem]; - const historyIndex = index || newHistory.length - 1; - dispatch( - setMessageAtIndex({ - message, - index: historyIndex, - contextItems: selectedContextItems, - }), + modifiers, + ideMessenger, + defaultContextProviders, ); + dispatch(setIsGatheringContext(false)); - // TODO: hacky way to allow rerender - await new Promise((resolve) => setTimeout(resolve, 0)); + // Automatically use currently open file + if (!modifiers.noContext) { + const usingFreeTrial = defaultModel?.provider === "free-trial"; - posthog.capture("step run", { - step_name: "User Input", - params: {}, - }); - posthog.capture("userInput", {}); - - const messages = constructMessages(newHistory, defaultModel.model); - - // Determine if the input is a slash command - let commandAndInput = getSlashCommandForInput(content); - - if (!commandAndInput) { - await _streamNormalInput(messages); - } else { - const [slashCommand, commandInput] = commandAndInput; - let updatedContextItems = []; - posthog.capture("step run", { - step_name: slashCommand.name, - params: {}, - }); - - if (slashCommand.name === "multifile-edit") { - dispatch(setIsInMultifileEdit(true)); + const currentFile = await ideMessenger.ide.getCurrentFile(); + if (currentFile) { + let currentFileContents = currentFile.contents; + if (usingFreeTrial) { + currentFileContents = currentFile.contents + .split("\n") + .slice(0, 1000) + .join("\n"); + } + if ( + !selectedContextItems.find( + (item) => item.uri?.value === currentFile.path, + ) + ) { + // don't add the file if it's already in the context items + selectedContextItems.unshift({ + content: `The following file is currently open. Don't reference it if it's not relevant to the user's message.\n\n\`\`\`${getRelativePath( + currentFile.path, + await ideMessenger.ide.getWorkspaceDirs(), + )}\n${currentFileContents}\n\`\`\``, + name: `Active file: ${getBasename(currentFile.path)}`, + description: currentFile.path, + id: { + itemId: currentFile.path, + providerTitle: "file", + }, + uri: { + type: "file", + value: currentFile.path, + }, + }); } - - await _streamSlashCommand( - messages, - slashCommand, - commandInput, - historyIndex, - selectedCode, - updatedContextItems, - ); } + } + + // dispatch(addContextItems(contextItems)); + return { selectedContextItems, selectedCode, content }; + } + + async function handleErrors(runStream: () => any): Promise { + try { + await runStream(); } catch (e: any) { console.debug("Error streaming response: ", e); ideMessenger.post("showToast", [ @@ -313,8 +250,143 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } } + async function streamResponseWithoutErrorHandling( + editorState: JSONContent, + modifiers: InputModifiers, + ideMessenger: IIdeMessenger, + index?: number, + ) { + if (typeof index === "number") { + dispatch(resubmitAtIndex({ index, editorState })); + } else { + dispatch(initNewActiveMessage({ editorState })); + } + + resetStateForNewMessage(); + + if (index) { + dispatch(setCurCheckpointIndex(Math.floor(index / 2))); + } + + const { selectedContextItems, selectedCode, content } = await gatherContext( + editorState, + modifiers, + ideMessenger, + ); + + const message: ChatMessage = { + role: "user", + content, + }; + + const historyItem: ChatHistoryItem = { + message, + contextItems: selectedContextItems, + editorState, + }; + + let newHistory: ChatHistory = [...history.slice(0, index), historyItem]; + const historyIndex = index || newHistory.length - 1; + dispatch( + setMessageAtIndex({ + message, + index: historyIndex, + contextItems: selectedContextItems, + }), + ); + + // TODO: hacky way to allow rerender + await new Promise((resolve) => setTimeout(resolve, 0)); + + posthog.capture("step run", { + step_name: "User Input", + params: {}, + }); + posthog.capture("userInput", {}); + + const messages = constructMessages(newHistory, defaultModel.model); + + // Determine if the input is a slash command + let commandAndInput = getSlashCommandForInput(content); + + if (!commandAndInput) { + await _streamNormalInput(messages); + } else { + const [slashCommand, commandInput] = commandAndInput; + let updatedContextItems = []; + posthog.capture("step run", { + step_name: slashCommand.name, + params: {}, + }); + + if (slashCommand.name === "multifile-edit") { + dispatch(setIsInMultifileEdit(true)); + } + + await _streamSlashCommand( + messages, + slashCommand, + commandInput, + historyIndex, + selectedCode, + updatedContextItems, + ); + } + } + + async function streamResponse( + editorState: JSONContent, + modifiers: InputModifiers, + ideMessenger: IIdeMessenger, + index?: number, + ) { + await handleErrors(() => + streamResponseWithoutErrorHandling( + editorState, + modifiers, + ideMessenger, + index, + ), + ); + } + + async function streamResponseAfterToolCall( + toolCallId: string, + toolOutput: string, + ) { + await handleErrors(async () => { + resetStateForNewMessage(); + + const newMessage: ChatMessage = { + role: "tool", + content: toolOutput, + toolCallId, + }; + + dispatch(streamUpdate(newMessage)); + dispatch(acceptToolCall()); + activeRef.current = true; + dispatch(setActive()); + + await new Promise((resolve) => setTimeout(resolve, 0)); + + const messages = constructMessages( + [ + ...history, + { + message: newMessage, + contextItems: [], + }, + ], + defaultModel.model, + ); + await _streamNormalInput(messages); + }); + } + return { streamResponse, + streamResponseAfterToolCall, }; } diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx index abc1018f6..3ea14c8bf 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx @@ -9,12 +9,8 @@ import { } from "../../../components"; import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { - acceptToolCall, - cancelToolCall, - setCalling, - streamUpdate, -} from "../../../redux/slices/stateSlice"; +import useChatHandler from "../../../hooks/useChatHandler"; +import { cancelToolCall, setCalling } from "../../../redux/slices/stateSlice"; import { RootState } from "../../../redux/store"; const ButtonContainer = styled.div` @@ -61,6 +57,11 @@ export function ToolCallButtons(props: ToolCallButtonsProps) { ); const ideMessenger = useContext(IdeMessengerContext); + const { streamResponseAfterToolCall } = useChatHandler( + dispatch, + ideMessenger, + ); + async function callTool() { // If it goes "generated" -> "calling" -> "done" really quickly // we don't want an abrupt flash so just skip "calling" @@ -84,15 +85,11 @@ export function ToolCallButtons(props: ToolCallButtonsProps) { clearTimeout(timer); if (result.status === "success") { - dispatch( - streamUpdate({ - role: "tool", - content: JSON.stringify(result.content.result), - toolCallId: toolCallState.toolCall.id, - }), + // Send to the LLM to continue the conversation + streamResponseAfterToolCall( + toolCallState.toolCall.id, + result.content.result, ); - - dispatch(acceptToolCall()); } } From d9911a60e48438effda65c0e94092091e54d0e27 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 20 Nov 2024 23:58:38 -0800 Subject: [PATCH 030/105] fixes --- core/llm/llms/Anthropic.ts | 4 ++-- gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx | 7 +++---- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 366174cfe..a5068e49b 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -59,7 +59,7 @@ class Anthropic extends BaseLLM { type: "tool_use", id: toolCall.id, name: toolCall.function?.name, - input: JSON.parse(toolCall.function?.arguments ?? "{}"), + input: JSON.parse(toolCall.function?.arguments || "{}"), })), }; } @@ -173,7 +173,7 @@ class Anthropic extends BaseLLM { ] : systemMessage, }), - signal + signal, }); if (options.stream === false) { diff --git a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx index ef42c4a44..de20f6437 100644 --- a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx @@ -14,11 +14,10 @@ const Container = styled.div` justify-content: center; position: relative; padding: 8px; + padding-bottom: 0; `; -const ChildrenDiv = styled.div` - margin: 8px; -`; +const ChildrenDiv = styled.div``; const W = 16; @@ -37,7 +36,7 @@ export function ThreadDiv(props: ThreadDivProps) { style={{ width: `${W}px`, height: `${W}px`, - fontWeight: "bold", + fontWeight: "bolder", marginTop: "1px", }} > From e93ae594825d71471438adc11c99eeb306b4e392 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 21 Nov 2024 08:38:00 -0800 Subject: [PATCH 031/105] adjust prompting --- core/llm/constructMessages.ts | 5 ++++- core/tools/searchWeb.ts | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 8b381f5fb..836d6c442 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -56,7 +56,10 @@ function helloWorld() { } \`\`\` -Always follow these guidelines when generating code responses.`; +Always follow these guidelines when generating code responses. + +Other rules: +- Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.`; function hasCodeBlockWithFilename(content: ChatMessage["content"]): boolean { const contentStr = typeof content === "string" ? content : content[0].text; diff --git a/core/tools/searchWeb.ts b/core/tools/searchWeb.ts index 8f438ce2f..4a7c32788 100644 --- a/core/tools/searchWeb.ts +++ b/core/tools/searchWeb.ts @@ -9,7 +9,8 @@ export const searchWebTool: Tool = { }, function: { name: "search_web", - description: "Perform a web search and get back top results", + description: + "Performs a web search, returning top results. This tool should only be called for questions that require external knowledge. Common programming questions do not require web search.", parameters: { type: "object", required: ["query"], From b8992b35603dff26dc19655a4740abca3cce3993 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 21 Nov 2024 08:38:31 -0800 Subject: [PATCH 032/105] update state management --- gui/src/pages/gui/Chat.tsx | 5 ++++- gui/src/redux/slices/stateSlice.ts | 8 ++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index ec4b320b2..d7e41bfde 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -180,7 +180,7 @@ export function Chat() { isMetaEquivalentKeyPressed(e) && !e.shiftKey ) { - dispatch(setInactive()); + dispatch(cancelGeneration()); } }; window.addEventListener("keydown", listener); @@ -502,3 +502,6 @@ export function Chat() { ); } +function cancelGeneration(): any { + throw new Error("Function not implemented."); +} diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 9adac23fd..ff5db6c02 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -178,6 +178,8 @@ export const stateSlice = createSlice({ contextItems: [], }); + state.currentToolCallState = {}; + // https://github.com/continuedev/continue/pull/1021 state.active = true; }, @@ -261,6 +263,11 @@ export const stateSlice = createSlice({ state.isGatheringContext = false; state.active = false; }, + cancelGeneration: (state) => { + state.isGatheringContext = false; + state.active = false; + state.currentToolCallState = {}; + }, abortStream: (state) => { state.streamAborter.abort(); state.streamAborter = new AbortController(); @@ -312,6 +319,7 @@ export const stateSlice = createSlice({ state.active = false; state.isGatheringContext = false; state.isMultifileEdit = false; + state.currentToolCallState = {}; if (payload) { state.history = payload.history as any; state.title = payload.title; From 2daef34b8ae1365888cf5f89d1d5dbec93ecbb84 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 21 Nov 2024 09:20:15 -0800 Subject: [PATCH 033/105] fix rendering of code blocks --- gui/src/pages/gui/ToolCallDiv/CreateFile.tsx | 22 +++++------------- .../ToolCallDiv/FunctionSpecificHeader.tsx | 2 +- .../gui/ToolCallDiv/RunTerminalCommand.tsx | 23 ++++--------------- 3 files changed, 12 insertions(+), 35 deletions(-) diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index 7fe43deec..4b6e5bbc1 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -1,5 +1,5 @@ -import StepContainerPreToolbar from "../../../components/markdown/StepContainerPreToolbar"; -import { SyntaxHighlightedPre } from "../../../components/markdown/SyntaxHighlightedPre"; +import { getMarkdownLanguageTagForFile } from "core/util"; +import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; import { ToolState } from "./types"; interface CreateFileToolCallProps { @@ -11,20 +11,10 @@ interface CreateFileToolCallProps { export function CreateFile(props: CreateFileToolCallProps) { return ( <> - - - - {props.fileContents} - - + ); } diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx index 858c2e46c..207945a8e 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx @@ -14,7 +14,7 @@ export function FunctionSpecificHeader(props: FunctionSpecificHeaderProps) { case "create_new_file": return "Continue wants to create a new file"; case "run_terminal_command": - return "Continue wantsto run a terminal command."; + return "Continue wants to run a terminal command."; case "exact_search": return "Continue wants to search your codebase"; case "search_web": diff --git a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx index 62186ddec..799d65126 100644 --- a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx +++ b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx @@ -1,5 +1,4 @@ -import StepContainerPreToolbar from "../../../components/markdown/StepContainerPreToolbar"; -import { SyntaxHighlightedPre } from "../../../components/markdown/SyntaxHighlightedPre"; +import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; import { ToolState } from "./types"; interface RunTerminalCommandToolCallProps { @@ -10,22 +9,10 @@ interface RunTerminalCommandToolCallProps { export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { return ( <> -

Continue wants to run a terminal command:

- - - - - {props.command} - - + ); } From a7cd760c3d8e4ccada4567605a970e4f7f0e9ccb Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 21 Nov 2024 09:49:23 -0800 Subject: [PATCH 034/105] remove edit slash command --- core/commands/slash/edit.ts | 620 ------------------------------------ 1 file changed, 620 deletions(-) delete mode 100644 core/commands/slash/edit.ts diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts deleted file mode 100644 index 78d86beee..000000000 --- a/core/commands/slash/edit.ts +++ /dev/null @@ -1,620 +0,0 @@ -import { ContextItemWithId, ILLM, SlashCommand } from "../../"; -import { - filterCodeBlockLines, - filterEnglishLinesAtEnd, - filterEnglishLinesAtStart, - fixCodeLlamaFirstLineIndentation, - stopAtLines, - streamWithNewLines, -} from "../../autocomplete/filtering/streamTransforms/lineStream"; -import { streamLines } from "../../diff/util"; -import { stripImages } from "../../llm/images"; -import { - dedentAndGetCommonWhitespace, - getMarkdownLanguageTagForFile, -} from "../../util/"; -import { - ctxItemToRifWithContents, - type RangeInFileWithContents, -} from "../util"; - -const PROMPT = `Take the file prefix and suffix into account, but only rewrite the code_to_edit as specified in the user_request. The code you write in modified_code_to_edit will replace the code between the code_to_edit tags. Do NOT preface your answer or write anything other than code. The tag should be written to indicate the end of the modified code section. Do not ever use nested tags. - -Example: - - -class Database: - def __init__(self): - self._data = {{}} - - def get(self, key): - return self._data[key] - - - - def set(self, key, value): - self._data[key] = value - - - - def clear_all(): - self._data = {{}} - - -Raise an error if the key already exists. - - - def set(self, key, value): - if key in self._data: - raise KeyError(f"Key {{key}} already exists") - self._data[key] = value - - -Main task: -`; - -export async function getPromptParts( - rif: RangeInFileWithContents, - fullFileContents: string, - model: ILLM, - input: string, - tokenLimit: number | undefined, -) { - const maxTokens = Math.floor(model.contextLength / 2); - - const BUFFER_FOR_FUNCTIONS = 400; - let totalTokens = - model.countTokens(fullFileContents + PROMPT + input) + - BUFFER_FOR_FUNCTIONS + - maxTokens; - - const fullFileContentsList = fullFileContents.split("\n"); - const maxStartLine = rif.range.start.line; - const minEndLine = rif.range.end.line; - let curStartLine = 0; - let curEndLine = fullFileContentsList.length - 1; - - if (totalTokens > model.contextLength) { - while (curEndLine > minEndLine) { - totalTokens -= model.countTokens(fullFileContentsList[curEndLine]); - curEndLine--; - if (totalTokens < model.contextLength) { - break; - } - } - } - - if (totalTokens > model.contextLength) { - while (curStartLine < maxStartLine) { - curStartLine++; - totalTokens -= model.countTokens(fullFileContentsList[curStartLine]); - if (totalTokens < model.contextLength) { - break; - } - } - } - - let filePrefix = fullFileContentsList - .slice(curStartLine, maxStartLine - 1) - .join("\n"); - let fileSuffix = fullFileContentsList - .slice(minEndLine, curEndLine + 1) - .join("\n"); - - if (rif.contents.length > 0) { - let lines = rif.contents.split(/\r?\n/); - let firstLine = lines[0] || null; - while (firstLine && firstLine.trim() === "") { - filePrefix += firstLine; - rif.contents = rif.contents.substring(firstLine.length); - lines = rif.contents.split(/\r?\n/); - firstLine = lines[0] || null; - } - - let lastLine = lines[lines.length - 1] || null; - while (lastLine && lastLine.trim() === "") { - fileSuffix = lastLine + fileSuffix; - rif.contents = rif.contents.substring( - 0, - rif.contents.length - lastLine.length, - ); - lines = rif.contents.split(/\r?\n/); - lastLine = lines[lines.length - 1] || null; - } - - while (rif.contents.startsWith("\n")) { - filePrefix += "\n"; - rif.contents = rif.contents.substring(1); - } - while (rif.contents.endsWith("\n")) { - fileSuffix = `\n${fileSuffix}`; - rif.contents = rif.contents.substring(0, rif.contents.length - 1); - } - } - return { filePrefix, fileSuffix, contents: rif.contents, maxTokens }; -} - -function compilePrompt( - filePrefix: string, - contents: string, - fileSuffix: string, - input: string, -): string { - if (contents.trim() === "") { - // Separate prompt for insertion at the cursor, the other tends to cause it to repeat whole file - return `\ - -${filePrefix} - - - -${fileSuffix} - - -${input} - - -Please output the code to be inserted at the cursor in order to fulfill the user_request. Do NOT preface your answer or write anything other than code. You should not write any tags, just the code. Make sure to correctly indent the code:`; - } - - let prompt = PROMPT; - if (filePrefix.trim() !== "") { - prompt += ` - -${filePrefix} -`; - } - prompt += ` - -${contents} -`; - - if (fileSuffix.trim() !== "") { - prompt += ` - -${fileSuffix} -`; - } - prompt += ` - -${input} - - -`; - - return prompt; -} - -function isEndLine(line: string) { - return ( - line.includes("") || - line.includes("") || - line.includes("[/CODE]") - ); -} - -function lineToBeIgnored(line: string, isFirstLine = false): boolean { - return ( - line.includes("```") || - line.includes("") || - line.includes("") || - line.includes("") || - line.includes("") || - line.includes("") || - line.includes("") || - line.includes("") || - line.includes("") - ); -} - -const EditSlashCommand: SlashCommand = { - name: "edit", - description: "Edit selected code", - run: async function* ({ ide, llm, input, history, contextItems, params }) { - let contextItemToEdit = contextItems.find( - (item: ContextItemWithId) => - item.editing && item.id.providerTitle === "code", - ); - if (!contextItemToEdit) { - contextItemToEdit = contextItems.find( - (item: ContextItemWithId) => item.id.providerTitle === "code", - ); - } - - if (!contextItemToEdit) { - yield "Please highlight the code you want to edit, then press `cmd/ctrl+shift+L` to add it to chat"; - return; - } - - // Strip unecessary parts of the input (the fact that you have to do this is suboptimal, should be refactored away) - let content = history[history.length - 1].content; - if (typeof content !== "string") { - content.forEach((part) => { - if (part.text?.startsWith("/edit")) { - part.text = part.text.replace("/edit", "").trimStart(); - } - }); - } else if (input?.startsWith("/edit")) { - content = input.replace("/edit", "").trimStart(); - } else if (input?.startsWith("/comment")) { - content = input.replace("/comment", "").trimStart(); - } - let userInput = stripImages(content).replace( - `\`\`\`${contextItemToEdit.name}\n${contextItemToEdit.content}\n\`\`\`\n`, - "", - ); - // if the above replace fails to find a match, the code will still be present - // in the userInput. Replace it with input if available. - if (userInput.includes("```") && (input !== "" || !input)) { - userInput = input; - } - - const rif: RangeInFileWithContents = - ctxItemToRifWithContents(contextItemToEdit); - - await ide.saveFile(rif.filepath); - const fullFileContents = await ide.readFile(rif.filepath); - - let { filePrefix, contents, fileSuffix, maxTokens } = await getPromptParts( - rif, - fullFileContents, - llm, - userInput, - params?.tokenLimit, - ); - const [dedentedContents, commonWhitespace] = - dedentAndGetCommonWhitespace(contents); - contents = dedentedContents; - - const prompt = compilePrompt(filePrefix, contents, fileSuffix, userInput); - const fullFileContentsLines = fullFileContents.split("\n"); - const fullPrefixLines = fullFileContentsLines.slice( - 0, - Math.max(0, rif.range.start.line - 1), - ); - const fullSuffixLines = fullFileContentsLines.slice(rif.range.end.line); - - let linesToDisplay: string[] = []; - - async function sendDiffUpdate(lines: string[], final = false) { - const completion = lines.join("\n"); - - // Don't do this at the very end, just show the inserted code - if (final) { - linesToDisplay = []; - } - - // Only recalculate at every new-line, because this is sort of expensive - else if (completion.endsWith("\n")) { - const contentsLines = rif.contents.split("\n"); - let rewrittenLines = 0; - for (const line of lines) { - for (let i = rewrittenLines; i < contentsLines.length; i++) { - if ( - // difflib.SequenceMatcher( - // null, line, contentsLines[i] - // ).ratio() - // > 0.7 - line.trim() === contentsLines[i].trim() && // Temp replacement for difflib (TODO) - contentsLines[i].trim() !== "" - ) { - rewrittenLines = i + 1; - break; - } - } - } - linesToDisplay = contentsLines.slice(rewrittenLines); - } - - const newFileContents = `${fullPrefixLines.join("\n")}\n${completion}\n${ - linesToDisplay.length > 0 ? `${linesToDisplay.join("\n")}\n` : "" - }${fullSuffixLines.join("\n")}`; - - const stepIndex = history.length - 1; - - await ide.showDiff(rif.filepath, newFileContents, stepIndex); - } - - // Important state variables - // ------------------------- - const originalLines = rif.contents === "" ? [] : rif.contents.split("\n"); - // In the actual file, taking into account block offset - let currentLineInFile = rif.range.start.line; - let currentBlockLines: string[] = []; - let originalLinesBelowPreviousBlocks = originalLines; - // The start of the current block in file, taking into account block offset - let currentBlockStart = -1; - let offsetFromBlocks = 0; - - // Don't end the block until you've matched N simultaneous lines - // This helps avoid many tiny blocks - const LINES_TO_MATCH_BEFORE_ENDING_BLOCK = 2; - // If a line has been matched at the end of the block, this is its index within originalLinesBelowPreviousBlocks - // Except we are keeping track of multiple potentialities, so it's a list - // We always check the lines following each of these leads, but if multiple make it out at the end, we use the first one - // This is a tuple of (index_of_last_matched_line, number_of_lines_matched) - let indicesOfLastMatchedLines: [number, number][] = []; - - async function handleGeneratedLine(line: string) { - if (currentBlockLines.length === 0) { - // Set this as the start of the next block - currentBlockStart = - rif.range.start.line + - originalLines.length - - originalLinesBelowPreviousBlocks.length + - offsetFromBlocks; - if ( - originalLinesBelowPreviousBlocks.length > 0 && - line === originalLinesBelowPreviousBlocks[0] - ) { - // Line is equal to the next line in file, move past this line - originalLinesBelowPreviousBlocks = - originalLinesBelowPreviousBlocks.slice(1); - return; - } - } - - // In a block, and have already matched at least one line - // Check if the next line matches, for each of the candidates - const matchesFound: any[] = []; - let firstValidMatch: any = null; - for (const [ - index_of_last_matched_line, - num_lines_matched, - ] of indicesOfLastMatchedLines) { - if ( - index_of_last_matched_line + 1 < - originalLinesBelowPreviousBlocks.length && - line === - originalLinesBelowPreviousBlocks[index_of_last_matched_line + 1] - ) { - matchesFound.push([ - index_of_last_matched_line + 1, - num_lines_matched + 1, - ]); - if ( - firstValidMatch === null && - num_lines_matched + 1 >= LINES_TO_MATCH_BEFORE_ENDING_BLOCK - ) { - firstValidMatch = [ - index_of_last_matched_line + 1, - num_lines_matched + 1, - ]; - } - } - } - indicesOfLastMatchedLines = matchesFound; - - if (firstValidMatch !== null) { - // We've matched the required number of lines, insert suggestion! - - // We added some lines to the block that were matched (including maybe some blank lines) - // So here we will strip all matching lines from the end of currentBlockLines - const linesStripped: string[] = []; - let indexOfLastLineInBlock: number = firstValidMatch[0]; - while ( - currentBlockLines.length > 0 && - currentBlockLines[currentBlockLines.length - 1] === - originalLinesBelowPreviousBlocks[indexOfLastLineInBlock - 1] - ) { - linesStripped.push(currentBlockLines.pop() as string); - indexOfLastLineInBlock -= 1; - } - - // Reset current block / update variables - currentLineInFile += 1; - offsetFromBlocks += currentBlockLines.length; - originalLinesBelowPreviousBlocks = - originalLinesBelowPreviousBlocks.slice(indexOfLastLineInBlock + 1); - currentBlockLines = []; - currentBlockStart = -1; - indicesOfLastMatchedLines = []; - - return; - } - - // Always look for new matching candidates - const newMatches: any[] = []; - for (let i = 0; i < originalLinesBelowPreviousBlocks.length; i++) { - const ogLine = originalLinesBelowPreviousBlocks[i]; - // TODO: It's a bit sus to be disqualifying empty lines. - // What you ideally do is find ALL matches, and then throw them out as you check the following lines - if (ogLine === line) { - // and og_line.trim() !== "": - newMatches.push([i, 1]); - } - } - indicesOfLastMatchedLines = indicesOfLastMatchedLines.concat(newMatches); - - // Make sure they are sorted by index - indicesOfLastMatchedLines = indicesOfLastMatchedLines.sort( - (a, b) => a[0] - b[0], - ); - - currentBlockLines.push(line); - } - - let messages = history; - messages[messages.length - 1] = { role: "user", content: prompt }; - - let linesOfPrefixCopied = 0; - const lines = []; - let unfinishedLine = ""; - let completionLinesCovered = 0; - let repeatingFileSuffix = false; - const lineBelowHighlightedRange = fileSuffix.trim().split("\n")[0]; - - // Use custom templates defined by the model - const template = llm.promptTemplates?.edit; - let generator: AsyncGenerator; - if (template) { - const rendered = llm.renderPromptTemplate( - template, - // typeof template === 'string' ? template : template.prompt, - messages.slice(0, messages.length - 1), - { - codeToEdit: rif.contents, - userInput, - filePrefix: filePrefix, - fileSuffix: fileSuffix, - - // Some built-in templates use these instead of the above - prefix: filePrefix, - suffix: fileSuffix, - - language: getMarkdownLanguageTagForFile(rif.filepath), - systemMessage: llm.systemMessage ?? "", - // "contextItems": (await sdk.getContextItemChatMessages()).map(x => x.content || "").join("\n\n"), - }, - ); - if (typeof rendered === "string") { - messages = [ - { - role: "user", - content: rendered, - }, - ]; - } else { - messages = rendered; - } - - const completion = llm.streamComplete(rendered as string, new AbortController().signal, { - maxTokens: Math.min(maxTokens, Math.floor(llm.contextLength / 2), 4096), - raw: true, - }); - let lineStream = streamLines(completion); - - lineStream = filterEnglishLinesAtStart(lineStream); - - lineStream = filterEnglishLinesAtEnd(filterCodeBlockLines(lineStream)); - lineStream = stopAtLines(lineStream, () => {}); - - generator = streamWithNewLines( - fixCodeLlamaFirstLineIndentation(lineStream), - ); - } else { - async function* gen() { - for await (const chunk of llm.streamChat(messages, new AbortController().signal,{ - temperature: 0.5, // TODO - maxTokens: Math.min( - maxTokens, - Math.floor(llm.contextLength / 2), - 4096, - ), - })) { - yield stripImages(chunk.content); - } - } - - generator = gen(); - } - - for await (const chunk of generator) { - // Stop early if it is repeating the fileSuffix or the step was deleted - if (repeatingFileSuffix) { - break; - } - - // Allow stopping breakpoints - yield undefined; - - // Accumulate lines - const chunkLines = chunk.split("\n"); - chunkLines[0] = unfinishedLine + chunkLines[0]; - if (chunk.endsWith("\n")) { - unfinishedLine = ""; - chunkLines.pop(); // because this will be an empty string - } else { - unfinishedLine = chunkLines.pop() ?? ""; - } - - // Deal with newly accumulated lines - for (let i = 0; i < chunkLines.length; i++) { - // Trailing whitespace doesn't matter - chunkLines[i] = chunkLines[i].trimEnd(); - chunkLines[i] = commonWhitespace + chunkLines[i]; - - // Lines that should signify the end of generation - if (isEndLine(chunkLines[i])) { - break; - } - // Lines that should be ignored, like the <> tags - if (lineToBeIgnored(chunkLines[i], completionLinesCovered === 0)) { - continue; // noice - } - // Check if we are currently just copying the prefix - if ( - (linesOfPrefixCopied > 0 || completionLinesCovered === 0) && - linesOfPrefixCopied < filePrefix.split("\n").length && - chunkLines[i] === fullPrefixLines[linesOfPrefixCopied] - ) { - // This is a sketchy way of stopping it from repeating the filePrefix. Is a bug if output happens to have a matching line - linesOfPrefixCopied += 1; - continue; // also nice - } - // Because really short lines might be expected to be repeated, this is only a !heuristic! - // Stop when it starts copying the fileSuffix - if ( - chunkLines[i].trim() === lineBelowHighlightedRange.trim() && - chunkLines[i].trim().length > 4 && - !( - originalLinesBelowPreviousBlocks.length > 0 && - chunkLines[i].trim() === originalLinesBelowPreviousBlocks[0].trim() - ) - ) { - repeatingFileSuffix = true; - break; - } - - lines.push(chunkLines[i]); - completionLinesCovered += 1; - currentLineInFile += 1; - } - - await sendDiffUpdate( - lines.concat([ - unfinishedLine?.startsWith("<") - ? commonWhitespace - : commonWhitespace + unfinishedLine, - ]), - ); - } - - // Add the unfinished line - if ( - unfinishedLine !== "" && - !lineToBeIgnored(unfinishedLine, completionLinesCovered === 0) && - !isEndLine(unfinishedLine) - ) { - unfinishedLine = commonWhitespace + unfinishedLine; - lines.push(unfinishedLine); - await handleGeneratedLine(unfinishedLine); - completionLinesCovered += 1; - currentLineInFile += 1; - } - - await sendDiffUpdate(lines, true); - - if (params?.recap) { - const prompt = `This is the code before editing: -\`\`\` -${contents} -\`\`\` - -This is the code after editing: - -\`\`\` -${lines.join("\n")} -\`\`\` - -Please briefly explain the changes made to the code above. Give no more than 2-3 sentences, and use markdown bullet points:`; - - for await (const update of llm.streamComplete(prompt, new AbortController().signal)) { - yield update; - } - } - yield `Edited ${contextItemToEdit.name}`; - }, -}; - -export default EditSlashCommand; From ee7bea7c19e3f52a50a8c9a0d26f242757dfd8a5 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 21 Nov 2024 18:31:50 -0800 Subject: [PATCH 035/105] renderChatMessage, return ContextItem[] from tools, and other refactoring --- core/commands/index.ts | 16 ++-- core/commands/slash/comment.ts | 19 ----- core/commands/slash/commit.ts | 11 +-- core/commands/slash/draftIssue.ts | 12 ++- core/commands/slash/multifileEdit.ts | 9 ++- core/commands/slash/onboard.ts | 11 +-- core/commands/slash/review.ts | 11 +-- core/commands/slash/share.ts | 4 +- core/config/promptFile.ts | 14 ++-- core/context/retrieval/repoMapRequest.ts | 15 ++-- core/core.ts | 6 +- core/diff/util.ts | 4 +- core/index.d.ts | 31 +++++-- core/llm/constructMessages.ts | 51 +++++------- core/llm/countTokens.ts | 36 +++++---- core/llm/images.ts | 11 --- core/llm/index.ts | 25 ++++-- core/llm/llms/Anthropic.ts | 11 ++- core/llm/llms/Bedrock.ts | 12 +-- core/llm/llms/Cloudflare.ts | 6 +- core/llm/llms/Cohere.ts | 6 +- core/llm/llms/Flowise.ts | 6 +- core/llm/llms/FreeTrial.ts | 16 +++- core/llm/llms/Gemini.ts | 18 +++-- core/llm/llms/Ollama.ts | 57 +++++++------ core/llm/llms/OpenAI.ts | 14 +++- core/llm/llms/VertexAI.ts | 80 +++++++++---------- core/llm/llms/WatsonX.ts | 40 +++++----- core/llm/templates/chat.ts | 8 +- .../v1/slashCommandFromPromptFile.ts | 9 ++- core/protocol/core.ts | 3 +- core/tools/createNewFile.ts | 1 + core/tools/exactSearch.ts | 10 ++- core/tools/runTerminalCommand.ts | 11 ++- core/tools/searchWeb.ts | 2 +- core/tools/viewDiff.ts | 8 +- core/tools/viewRepoMap.ts | 8 +- core/tools/viewSubdirectory.ts | 8 +- core/util/chatDescriber.ts | 2 - core/util/messageContent.ts | 45 +++++++++++ .../vscode/src/extension/VsCodeMessenger.ts | 2 +- .../StepContainer/MultifileEditActions.tsx | 7 +- .../StepContainer/ResponseActions.tsx | 4 +- .../StepContainer/StepContainer.tsx | 8 +- gui/src/components/mainInput/resolveInput.ts | 2 +- gui/src/hooks/useChatHandler.ts | 12 ++- gui/src/hooks/useHistory.tsx | 4 +- gui/src/pages/edit/index.tsx | 7 +- gui/src/pages/gui/Chat.tsx | 4 +- .../ToolCallDiv/FunctionSpecificHeader.tsx | 27 +++++-- .../gui/ToolCallDiv/ToolCallButtonsDiv.tsx | 6 +- gui/src/redux/slices/stateSlice.ts | 26 +++--- manual-testing-sandbox/test.ts | 41 ++++++++++ 53 files changed, 498 insertions(+), 319 deletions(-) delete mode 100644 core/commands/slash/comment.ts delete mode 100644 core/llm/images.ts create mode 100644 core/util/messageContent.ts create mode 100644 manual-testing-sandbox/test.ts diff --git a/core/commands/index.ts b/core/commands/index.ts index cb5e162f7..492b7f90a 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -1,6 +1,6 @@ import { CustomCommand, SlashCommand, SlashCommandDescription } from "../"; -import { stripImages } from "../llm/images"; import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; +import { renderChatMessage } from "../util/messageContent"; import SlashCommands from "./slash"; @@ -29,7 +29,8 @@ export function slashFromCustomCommand( const messages = [...history]; // Find the last chat message with this slash command and replace it with the user input for (let i = messages.length - 1; i >= 0; i--) { - const { role, content } = messages[i]; + const message = messages[i]; + const { role, content } = message; if (role !== "user") { continue; } @@ -41,7 +42,7 @@ export function slashFromCustomCommand( ) ) { messages[i] = { - ...messages[i], + ...message, content: content.map((part) => { return part.text?.startsWith(`/${customCommand.name}`) ? { ...part, text: promptUserInput } @@ -53,13 +54,16 @@ export function slashFromCustomCommand( typeof content === "string" && content.startsWith(`/${customCommand.name}`) ) { - messages[i] = { ...messages[i], content: promptUserInput }; + messages[i] = { ...message, content: promptUserInput }; break; } } - for await (const chunk of llm.streamChat(messages, new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of llm.streamChat( + messages, + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/commands/slash/comment.ts b/core/commands/slash/comment.ts deleted file mode 100644 index adadb026c..000000000 --- a/core/commands/slash/comment.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { SlashCommand } from "../../"; - -import EditSlashCommand from "./edit"; - -const CommentSlashCommand: SlashCommand = { - name: "comment", - description: "Write comments for highlighted code", - run: async function* (sdk) { - for await (const update of EditSlashCommand.run({ - ...sdk, - input: - "Write comments for this code. Do not change anything about the code itself.", - })) { - yield update; - } - }, -}; - -export default CommentSlashCommand; diff --git a/core/commands/slash/commit.ts b/core/commands/slash/commit.ts index 7d5f22a90..d6f9bef1f 100644 --- a/core/commands/slash/commit.ts +++ b/core/commands/slash/commit.ts @@ -1,5 +1,5 @@ import { SlashCommand } from "../../index.js"; -import { stripImages } from "../../llm/images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; const CommitMessageCommand: SlashCommand = { name: "commit", @@ -14,10 +14,11 @@ const CommitMessageCommand: SlashCommand = { } const prompt = `${diff}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`; - for await (const chunk of llm.streamChat([ - { role: "user", content: prompt }, - ], new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of llm.streamChat( + [{ role: "user", content: prompt }], + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/commands/slash/draftIssue.ts b/core/commands/slash/draftIssue.ts index 268c68384..a640dbd25 100644 --- a/core/commands/slash/draftIssue.ts +++ b/core/commands/slash/draftIssue.ts @@ -1,6 +1,6 @@ import { ChatMessage, SlashCommand } from "../../index.js"; -import { stripImages } from "../../llm/images.js"; import { removeQuotesAndEscapes } from "../../util/index.js"; +import { renderChatMessage } from "../../util/messageContent.js"; const PROMPT = ( input: string, @@ -30,7 +30,8 @@ const DraftIssueCommand: SlashCommand = { return; } let title = await llm.complete( - `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, new AbortController().signal, + `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, + new AbortController().signal, { maxTokens: 20 }, ); @@ -43,9 +44,12 @@ const DraftIssueCommand: SlashCommand = { { role: "user", content: PROMPT(input, title) }, ]; - for await (const chunk of llm.streamChat(messages, new AbortController().signal)) { + for await (const chunk of llm.streamChat( + messages, + new AbortController().signal, + )) { body += chunk.content; - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent( diff --git a/core/commands/slash/multifileEdit.ts b/core/commands/slash/multifileEdit.ts index c8cf64679..d7b3edcb5 100644 --- a/core/commands/slash/multifileEdit.ts +++ b/core/commands/slash/multifileEdit.ts @@ -1,5 +1,5 @@ import { SlashCommand } from "../.."; -import { stripImages } from "../../llm/images"; +import { renderChatMessage } from "../../util/messageContent"; const MultiFileEditSlashCommand: SlashCommand = { name: "multifile-edit", @@ -39,8 +39,11 @@ const MultiFileEditSlashCommand: SlashCommand = { const content = createPrompt(filesToEditStr, additionalContextStr, input); - for await (const chunk of llm.streamChat([{ role: "user", content }], new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of llm.streamChat( + [{ role: "user", content }], + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index 4d8aa3a38..b9a39aa0b 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -9,7 +9,7 @@ import { defaultIgnoreFile, gitIgArrayFromFile, } from "../../indexing/ignore"; -import { stripImages } from "../../llm/images"; +import { renderChatMessage } from "../../util/messageContent"; const LANGUAGE_DEP_MGMT_FILENAMES = [ "package.json", // JavaScript (Node.js) @@ -45,10 +45,11 @@ const OnboardSlashCommand: SlashCommand = { const context = await gatherProjectContext(workspaceDir, ide); const prompt = createOnboardingPrompt(context); - for await (const chunk of llm.streamChat([ - { role: "user", content: prompt }, - ], new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of llm.streamChat( + [{ role: "user", content: prompt }], + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/commands/slash/review.ts b/core/commands/slash/review.ts index 77357647a..a3a2be6a7 100644 --- a/core/commands/slash/review.ts +++ b/core/commands/slash/review.ts @@ -1,5 +1,5 @@ import { ChatMessage, SlashCommand } from "../../index.js"; -import { stripImages } from "../../llm/images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; const prompt = ` Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines: @@ -43,10 +43,11 @@ const ReviewMessageCommand: SlashCommand = { const content = `${prompt} \r\n ${reviewText}`; - for await (const chunk of llm.streamChat([ - { role: "user", content: content }, - ], new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of llm.streamChat( + [{ role: "user", content: content }], + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/commands/slash/share.ts b/core/commands/slash/share.ts index 5ee1fd938..4b69f4c62 100644 --- a/core/commands/slash/share.ts +++ b/core/commands/slash/share.ts @@ -4,7 +4,7 @@ import path from "path"; import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js"; import { SlashCommand } from "../../index.js"; -import { stripImages } from "../../llm/images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; // If useful elsewhere, helper funcs should move to core/util/index.ts or similar function getOffsetDatetime(date: Date): Date { @@ -48,7 +48,7 @@ const ShareSlashCommand: SlashCommand = { // message in the chat history, this will omit it for (const msg of history.slice(0, history.length - 1)) { let msgText = msg.content; - msgText = stripImages(msg.content); + msgText = renderChatMessage(msg); if (msg.role === "user" && msgText.search("```") > -1) { msgText = reformatCodeBlocks(msgText); diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index 1ec963513..b369e6338 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -4,9 +4,9 @@ import Handlebars from "handlebars"; import * as YAML from "yaml"; import { walkDir } from "../indexing/walkDir"; -import { stripImages } from "../llm/images"; import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; import { getBasename } from "../util/index"; +import { renderChatMessage } from "../util/messageContent"; import type { ChatMessage, @@ -125,8 +125,11 @@ export function slashCommandFromPromptFile( systemMessage, ); - for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of context.llm.streamChat( + messages, + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } context.llm.systemMessage = originalSystemMessage; @@ -233,7 +236,8 @@ function updateChatHistory( const messages = [...history]; for (let i = messages.length - 1; i >= 0; i--) { - const { role, content } = messages[i]; + const message = messages[i]; + const { role, content } = message; if (role !== "user") { continue; } @@ -251,7 +255,7 @@ function updateChatHistory( typeof content === "string" && content.startsWith(`/${commandName}`) ) { - messages[i] = { ...messages[i], content: renderedPrompt }; + messages[i] = { ...message, content: renderedPrompt }; break; } } diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 8dc55df9d..57f2b339e 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -1,7 +1,7 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../.."; import { getModelByRole } from "../../config/util"; -import { stripImages } from "../../llm/images"; import generateRepoMap from "../../util/generateRepoMap"; +import { renderChatMessage } from "../../util/messageContent"; const SUPPORTED_MODEL_TITLE_FAMILIES = [ "claude-3", @@ -58,11 +58,14 @@ After this, your response should begin with a tag, followed by a list This is the question that you should select relevant files for: "${input}"`; - const response = await llm.chat([ - { role: "user", content: prompt }, - { role: "assistant", content: "" }, - ], new AbortController().signal); - const content = stripImages(response.content); + const response = await llm.chat( + [ + { role: "user", content: prompt }, + { role: "assistant", content: "" }, + ], + new AbortController().signal, + ); + const content = renderChatMessage(response); console.debug("Repo map retrieval response: ", content); if (!content.includes("\n")) { diff --git a/core/core.ts b/core/core.ts index ad1ed3be7..e844146f9 100644 --- a/core/core.ts +++ b/core/core.ts @@ -756,13 +756,13 @@ export class Core { ); if (!tool) { - return { error: "Tool not found", result: undefined }; + throw new Error(`Tool ${toolCall.function.name} not found`); } const config = await this.configHandler.loadConfig(); const llm = await this.getSelectedModel(); - const result = await tool.action( + const contextItems = await tool.action( JSON.parse(toolCall.function.arguments || "{}"), { ide: this.ide, @@ -771,7 +771,7 @@ export class Core { fetchwithRequestOptions(url, init, config.requestOptions), }, ); - return { result }; + return { contextItems }; }); } diff --git a/core/diff/util.ts b/core/diff/util.ts index 839ab15b1..c56e88504 100644 --- a/core/diff/util.ts +++ b/core/diff/util.ts @@ -1,7 +1,7 @@ import { distance } from "fastest-levenshtein"; import { ChatMessage } from "../index.js"; -import { stripImages } from "../llm/images.js"; +import { renderChatMessage } from "../util/messageContent.js"; export type LineStream = AsyncGenerator; @@ -103,7 +103,7 @@ export async function* streamLines( try { for await (const update of streamCompletion) { const chunk = - typeof update === "string" ? update : stripImages(update.content); + typeof update === "string" ? update : renderChatMessage(update); buffer += chunk; const lines = buffer.split("\n"); buffer = lines.pop() ?? ""; diff --git a/core/index.d.ts b/core/index.d.ts index e025ccdb6..dcd375643 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -293,13 +293,34 @@ export interface ToolCallDelta { }; } -export interface ChatMessage { - role: ChatMessageRole; - content: MessageContent; - toolCalls?: ToolCallDelta[]; +export interface ToolResultChatMessage { + role: "tool"; + content: string; toolCallId?: string; } +export interface UserChatMessage { + role: "user"; + content: MessageContent; +} + +export interface AssistantChatMessage { + role: "assistant"; + content: MessageContent; + toolCalls?: ToolCallDelta[]; +} + +export interface SystemChatMessage { + role: "system"; + content: string; +} + +export type ChatMessage = + | UserChatMessage + | AssistantChatMessage + | SystemChatMessage + | ToolResultChatMessage; + export interface ContextItemId { providerTitle: string; itemId: string; @@ -860,7 +881,7 @@ export interface Tool { parameters?: Record; strict?: boolean | null; }; - action: (parameters: any, extras: ToolExtras) => Promise; + action: (parameters: any, extras: ToolExtras) => Promise; } interface BaseCompletionOptions { diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 836d6c442..823fd97f2 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,4 +1,5 @@ import { ChatHistory, ChatMessage, MessagePart } from "../index.js"; +import { normalizeToMessageParts } from "../util/messageContent.js"; const SYSTEM_MESSAGE = `When generating new code: @@ -61,17 +62,6 @@ Always follow these guidelines when generating code responses. Other rules: - Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.`; -function hasCodeBlockWithFilename(content: ChatMessage["content"]): boolean { - const contentStr = typeof content === "string" ? content : content[0].text; - - if (!contentStr) { - return false; - } - - const codeBlockRegex = /```[\w\W]*?\.[\w\W]*/; - return codeBlockRegex.test(contentStr); -} - export function constructMessages( history: ChatHistory, model: string, @@ -92,28 +82,27 @@ export function constructMessages( for (let i = 0; i < history.length; i++) { const historyItem = history[i]; - let content = Array.isArray(historyItem.message.content) - ? historyItem.message.content - : [{ type: "text", text: historyItem.message.content } as MessagePart]; + if (historyItem.message.role === "user") { + // Gather context items for user messages + let content = normalizeToMessageParts(historyItem.message); - const ctxItems = historyItem.contextItems.map((ctxItem) => { - return { type: "text", text: `${ctxItem.content}\n` } as MessagePart; - }); + const ctxItems = historyItem.contextItems.map((ctxItem) => { + return { type: "text", text: `${ctxItem.content}\n` } as MessagePart; + }); - content = [...ctxItems, ...content]; - - msgs.push({ - ...historyItem.message, - content, - }); - - // Remove the "id" from all of the messages - msgs.forEach((msg: any) => { - if (msg.id !== undefined) { - delete msg.id; - } - }); + content = [...ctxItems, ...content]; + msgs.push({ + ...historyItem.message, + content, + }); + } else { + msgs.push(historyItem.message); + } } - return msgs; + // Remove the "id" from all of the messages + return msgs.map((msg) => { + const { id, ...rest } = msg as any; + return rest; + }); } diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 871e5ee84..896cfe337 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -2,6 +2,7 @@ import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; import { ChatMessage, MessageContent, MessagePart } from "../index.js"; +import { renderChatMessage } from "../util/messageContent.js"; import { AsyncEncoder, GPTAsyncEncoder, @@ -9,7 +10,6 @@ import { } from "./asyncEncoder.js"; import { autodetectTemplateType } from "./autodetect.js"; import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js"; -import { stripImages } from "./images.js"; import llamaTokenizer from "./llamaTokenizer.js"; interface Encoding { encode: Tiktoken["encode"]; @@ -115,21 +115,28 @@ function countTokens( } } +function messageHasToolCalls(msg: ChatMessage): boolean { + return msg.role === "assistant" && !!msg.toolCalls; +} + export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { const flattened: ChatMessage[] = []; + for (let i = 0; i < msgs.length; i++) { const msg = msgs[i]; + if ( flattened.length > 0 && flattened[flattened.length - 1].role === msg.role && - !msg.toolCalls && - !flattened[flattened.length - 1].toolCalls + !messageHasToolCalls(msg) && + !messageHasToolCalls(flattened[flattened.length - 1]) ) { flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`; } else { flattened.push(msg); } } + return flattened; } @@ -224,11 +231,8 @@ function pruneRawPromptFromBottom( return pruneStringFromBottom(modelName, maxTokens, prompt); } -function summarize(message: MessageContent): string { - if (Array.isArray(message)) { - return `${stripImages(message).substring(0, 100)}...`; - } - return `${message.substring(0, 100)}...`; +function summarize(message: ChatMessage): string { + return `${renderChatMessage(message).substring(0, 100)}...`; } function pruneChatHistory( @@ -259,7 +263,7 @@ function pruneChatHistory( for (let i = 0; i < longerThanOneThird.length; i++) { // Prune line-by-line from the top const message = longerThanOneThird[i]; - const content = stripImages(message.content); + const content = renderChatMessage(message); const deltaNeeded = totalTokens - contextLength; const delta = Math.min(deltaNeeded, distanceFromThird[i]); message.content = pruneStringFromTop( @@ -275,8 +279,8 @@ function pruneChatHistory( while (totalTokens > contextLength && i < chatHistory.length - 5) { const message = chatHistory[0]; totalTokens -= countTokens(message.content, modelName); - totalTokens += countTokens(summarize(message.content), modelName); - message.content = summarize(message.content); + totalTokens += countTokens(summarize(message), modelName); + message.content = summarize(message); i++; } @@ -299,8 +303,8 @@ function pruneChatHistory( ) { const message = chatHistory[i]; totalTokens -= countTokens(message.content, modelName); - totalTokens += countTokens(summarize(message.content), modelName); - message.content = summarize(message.content); + totalTokens += countTokens(summarize(message), modelName); + message.content = summarize(message); i++; } @@ -316,7 +320,7 @@ function pruneChatHistory( message.content = pruneRawPromptFromTop( modelName, contextLength, - stripImages(message.content), + renderChatMessage(message), tokensForCompletion, ); totalTokens = contextLength; @@ -378,7 +382,7 @@ function compileChatMessages( ) { let content = ""; if (msgs?.[0].role === "system") { - content = stripImages(msgs?.[0].content); + content = renderChatMessage(msgs?.[0]); } if (systemMessage && systemMessage.trim() !== "") { const shouldAddNewLines = content !== ""; @@ -413,7 +417,7 @@ function compileChatMessages( if (!supportsImages) { for (const msg of msgsCopy) { if ("content" in msg && Array.isArray(msg.content)) { - const content = stripImages(msg.content); + const content = renderChatMessage(msg); msg.content = content; } } diff --git a/core/llm/images.ts b/core/llm/images.ts deleted file mode 100644 index 912ae48ca..000000000 --- a/core/llm/images.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { MessageContent } from "../index.js"; - -export function stripImages(content: MessageContent): string { - if (Array.isArray(content)) { - return content - .filter((part) => part.type === "text") - .map((part) => part.text) - .join("\n"); - } - return content; - } \ No newline at end of file diff --git a/core/llm/index.ts b/core/llm/index.ts index 1156120a6..e46231ec4 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -24,6 +24,7 @@ import mergeJson from "../util/merge.js"; import { Telemetry } from "../util/posthog.js"; import { withExponentialBackoff } from "../util/withExponentialBackoff.js"; +import { renderChatMessage } from "../util/messageContent.js"; import { autodetectPromptTemplates, autodetectTemplateFunction, @@ -41,7 +42,6 @@ import { countTokens, pruneRawPromptFromTop, } from "./countTokens.js"; -import { stripImages } from "./images.js"; import CompletionOptionsForModels from "./templates/options.js"; export abstract class BaseLLM implements ILLM { @@ -372,7 +372,8 @@ export abstract class BaseLLM implements ILLM { `HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`, ); } else { - if (e.name !== "AbortError") { // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here + if (e.name !== "AbortError") { + // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here console.debug( `${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`, ); @@ -414,7 +415,7 @@ export abstract class BaseLLM implements ILLM { let formatted = ""; for (const msg of msgsCopy) { if ("content" in msg && Array.isArray(msg.content)) { - const content = stripImages(msg.content); + const content = renderChatMessage(msg); msg.content = content; } formatted += `<${msg.role}>\n${msg.content || ""}\n\n`; @@ -533,7 +534,11 @@ export abstract class BaseLLM implements ILLM { }; } - async complete(_prompt: string, signal: AbortSignal, options: LLMFullCompletionOptions = {}) { + async complete( + _prompt: string, + signal: AbortSignal, + options: LLMFullCompletionOptions = {}, + ) { const { completionOptions, log, raw } = this._parseCompletionOptions(options); @@ -568,7 +573,11 @@ export abstract class BaseLLM implements ILLM { return completion; } - async chat(messages: ChatMessage[], signal: AbortSignal, options: LLMFullCompletionOptions = {}) { + async chat( + messages: ChatMessage[], + signal: AbortSignal, + options: LLMFullCompletionOptions = {}, + ) { let completion = ""; for await (const chunk of this.streamChat(messages, signal, options)) { completion += chunk.content; @@ -668,7 +677,11 @@ export abstract class BaseLLM implements ILLM { } } - protected async _complete(prompt: string, signal: AbortSignal, options: CompletionOptions) { + protected async _complete( + prompt: string, + signal: AbortSignal, + options: CompletionOptions, + ) { let completion = ""; for await (const chunk of this._streamComplete(prompt, signal, options)) { completion += chunk; diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index a5068e49b..c6fcc9bdf 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -4,7 +4,7 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; @@ -48,7 +48,7 @@ class Anthropic extends BaseLLM { { type: "tool_result", tool_use_id: message.toolCallId, - content: stripImages(message.content) || undefined, + content: renderChatMessage(message) || undefined, }, ], }; @@ -133,7 +133,7 @@ class Anthropic extends BaseLLM { ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; for await (const update of this._streamChat(messages, signal, options)) { - yield stripImages(update.content); + yield renderChatMessage(update); } } @@ -144,9 +144,8 @@ class Anthropic extends BaseLLM { ): AsyncGenerator { const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; - const systemMessage: string = stripImages( - messages.filter((m) => m.role === "system")[0]?.content, - ); + const systemMessage: string = + messages.filter((m) => m.role === "system")[0]?.content ?? ""; const msgs = this.convertMessages(messages); const response = await this.fetch(new URL("messages", this.apiBase), { diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 01a0201eb..7ca2783fa 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -11,7 +11,7 @@ import { MessageContent, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; class Bedrock extends BaseLLM { @@ -42,7 +42,7 @@ class Bedrock extends BaseLLM { ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; for await (const update of this._streamChat(messages, signal, options)) { - yield stripImages(update.content); + yield renderChatMessage(update); } } @@ -86,7 +86,7 @@ class Bedrock extends BaseLLM { const input = this._generateConverseInput(messages, options); const command = new ConverseStreamCommand(input); - const response = await client.send(command, { abortSignal: signal}); + const response = await client.send(command, { abortSignal: signal }); if (response.stream) { for await (const chunk of response.stream) { @@ -122,7 +122,9 @@ class Bedrock extends BaseLLM { // TODO: Additionally, consider implementing a global exception handler for the providers to give users clearer feedback. // For example, differentiate between client-side errors (4XX status codes) and server-side issues (5XX status codes), // providing meaningful error messages to improve the user experience. - stopSequences: options.stop?.filter((stop) => stop.trim() !== "").slice(0, 4), + stopSequences: options.stop + ?.filter((stop) => stop.trim() !== "") + .slice(0, 4), }, }; } @@ -164,7 +166,7 @@ class Bedrock extends BaseLLM { try { return await fromIni({ profile: this.profile, - ignoreCache: true + ignoreCache: true, })(); } catch (e) { console.warn( diff --git a/core/llm/llms/Cloudflare.ts b/core/llm/llms/Cloudflare.ts index 07e2e427c..215e97b37 100644 --- a/core/llm/llms/Cloudflare.ts +++ b/core/llm/llms/Cloudflare.ts @@ -1,5 +1,5 @@ import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; @@ -36,7 +36,7 @@ export default class Cloudflare extends BaseLLM { model: this.model, ...this._convertArgs(options), }), - signal + signal, }); for await (const value of streamSse(resp)) { @@ -56,7 +56,7 @@ export default class Cloudflare extends BaseLLM { signal, options, )) { - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } } } diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index 98135c7cc..a43df7a62 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -4,7 +4,7 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamJSON } from "../stream.js"; @@ -51,7 +51,7 @@ class Cohere extends BaseLLM { ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; for await (const update of this._streamChat(messages, signal, options)) { - yield stripImages(update.content); + yield renderChatMessage(update); } } @@ -75,7 +75,7 @@ class Cohere extends BaseLLM { chat_history: this._convertMessages(messages), preamble: this.systemMessage, }), - signal + signal, }); if (options.stream === false) { diff --git a/core/llm/llms/Flowise.ts b/core/llm/llms/Flowise.ts index ecca89d16..8c5b0f459 100644 --- a/core/llm/llms/Flowise.ts +++ b/core/llm/llms/Flowise.ts @@ -6,7 +6,7 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; interface IFlowiseApiOptions { @@ -126,7 +126,7 @@ class Flowise extends BaseLLM { ): AsyncGenerator { const message: ChatMessage = { role: "user", content: prompt }; for await (const chunk of this._streamChat([message], signal, options)) { - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } } @@ -141,7 +141,7 @@ class Flowise extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }), - signal + signal, }).then((res) => res.json()); while (await socketInfo.hasNextToken()) { diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index 8f80c7418..895d6c42f 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -74,7 +74,7 @@ class FreeTrial extends BaseLLM { prompt, ...args, }), - signal + signal, }); let completion = ""; @@ -82,10 +82,18 @@ class FreeTrial extends BaseLLM { yield value; completion += value; } - this._countTokens(completion, args.model, false); + void this._countTokens(completion, args.model, false); } protected _convertMessage(message: ChatMessage) { + if (message.role === "tool") { + return { + role: "tool", + content: message.content, + tool_call_id: message.toolCallId, + }; + } + if (typeof message.content === "string") { return message; } @@ -123,7 +131,7 @@ class FreeTrial extends BaseLLM { messages: messages.map(this._convertMessage), ...args, }), - signal + signal, }); let completion = ""; @@ -158,7 +166,7 @@ class FreeTrial extends BaseLLM { suffix, ...args, }), - signal + signal, }); let completion = ""; diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index ada603240..e9cc484c8 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -5,7 +5,7 @@ import { MessagePart, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -19,7 +19,8 @@ class Gemini extends BaseLLM { }; // Function to convert completion options to Gemini format - public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI + public convertArgs(options: CompletionOptions) { + // should be public for use within VertexAI const finalOptions: any = {}; // Initialize an empty object // Map known options @@ -54,17 +55,19 @@ class Gemini extends BaseLLM { signal, options, )) { - yield stripImages(message.content); + yield renderChatMessage(message); } } - public removeSystemMessage(messages: ChatMessage[]) { // should be public for use within VertexAI + public removeSystemMessage(messages: ChatMessage[]) { + // should be public for use within VertexAI const msgs = [...messages]; if (msgs[0]?.role === "system") { const sysMsg = msgs.shift()?.content; // @ts-ignore if (msgs[0]?.role === "user") { + // @ts-ignore msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`; } } @@ -143,6 +146,9 @@ class Gemini extends BaseLLM { if (msg.role === "system" && !isV1API) { return null; // Don't include system message in contents } + if (msg.role === "tool") { + return null; + } return { role: msg.role === "assistant" ? "model" : "user", parts: @@ -165,7 +171,7 @@ class Gemini extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), - signal + signal, }); let buffer = ""; @@ -234,7 +240,7 @@ class Gemini extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), - signal + signal, }); const data = await response.json(); yield { role: "assistant", content: data.candidates[0].content }; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index dcaa078ba..69de3f1d9 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -4,13 +4,11 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; -interface OllamaChatMessage extends ChatMessage { - images?: string[]; -} +type OllamaChatMessage = ChatMessage & { images?: string[] }; // See https://github.com/ollama/ollama/blob/main/docs/modelfile.md for details on each parameter interface ModelFileParams { @@ -37,31 +35,29 @@ interface ModelFileParams { // See https://github.com/ollama/ollama/blob/main/docs/api.md interface BaseOptions { - model: string; // the model name + model: string; // the model name options?: ModelFileParams; // additional model parameters listed in the documentation for the Modelfile such as temperature - format?: "json"; // the format to return a response in. Currently, the only accepted value is json - stream?: boolean; // if false the response will be returned as a single response object, rather than a stream of objects - keep_alive?: number; // controls how long the model will stay loaded into memory following the request (default: 5m) + format?: "json"; // the format to return a response in. Currently, the only accepted value is json + stream?: boolean; // if false the response will be returned as a single response object, rather than a stream of objects + keep_alive?: number; // controls how long the model will stay loaded into memory following the request (default: 5m) } interface GenerateOptions extends BaseOptions { - prompt: string; // the prompt to generate a response for - suffix?: string; // the text after the model response - images?: string[]; // a list of base64-encoded images (for multimodal models such as llava) - system?: string; // system message to (overrides what is defined in the Modelfile) - template?: string; // the prompt template to use (overrides what is defined in the Modelfile) - context?: string; // the context parameter returned from a previous request to /generate, this can be used to keep a short conversational memory - raw?: boolean; // if true no formatting will be applied to the prompt. You may choose to use the raw parameter if you are specifying a full templated prompt in your request to the API + prompt: string; // the prompt to generate a response for + suffix?: string; // the text after the model response + images?: string[]; // a list of base64-encoded images (for multimodal models such as llava) + system?: string; // system message to (overrides what is defined in the Modelfile) + template?: string; // the prompt template to use (overrides what is defined in the Modelfile) + context?: string; // the context parameter returned from a previous request to /generate, this can be used to keep a short conversational memory + raw?: boolean; // if true no formatting will be applied to the prompt. You may choose to use the raw parameter if you are specifying a full templated prompt in your request to the API } interface ChatOptions extends BaseOptions { - messages: OllamaChatMessage[]; // the messages of the chat, this can be used to keep a chat memory + messages: OllamaChatMessage[]; // the messages of the chat, this can be used to keep a chat memory // Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false // And correspondingly, tool calls in OllamaChatMessage } - - class Ollama extends BaseLLM { static providerName: ModelProvider = "ollama"; static defaultOptions: Partial = { @@ -196,9 +192,11 @@ class Ollama extends BaseLLM { }; } - private _convertMessage( - message: ChatMessage - ) { + private _convertMessage(message: ChatMessage) { + if (message.role === "tool") { + return null; + } + if (typeof message.content === "string") { return message; } @@ -214,18 +212,18 @@ class Ollama extends BaseLLM { return { role: message.role, - content: stripImages(message.content), - images + content: renderChatMessage(message), + images, }; } private _getChatOptions( options: CompletionOptions, - messages: ChatMessage[] + messages: ChatMessage[], ): ChatOptions { return { model: this._getModel(), - messages: messages.map(this._convertMessage), + messages: messages.map(this._convertMessage).filter(Boolean) as any, options: this._getModelFileParams(options), keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes stream: options.stream, @@ -236,7 +234,7 @@ class Ollama extends BaseLLM { private _getGenerateOptions( options: CompletionOptions, prompt: string, - suffix?: string + suffix?: string, ): GenerateOptions { return { model: this._getModel(), @@ -271,7 +269,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getGenerateOptions(options, prompt)), - signal + signal, }); let buffer = ""; @@ -312,7 +310,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getChatOptions(options, messages)), - signal + signal, }); let buffer = ""; @@ -354,7 +352,6 @@ class Ollama extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - const response = await this.fetch(this.getEndpoint("api/generate"), { method: "POST", headers: { @@ -362,7 +359,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)), - signal + signal, }); let buffer = ""; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index eb9c3d7c9..10683c8a8 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -4,7 +4,7 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; @@ -56,6 +56,14 @@ class OpenAI extends BaseLLM { }; protected _convertMessage(message: ChatMessage) { + if (message.role === "tool") { + return { + role: "tool", + content: message.content, + tool_call_id: message.toolCallId, + }; + } + if (typeof message.content === "string") { return message; } else if (!message.content.some((item) => item.type !== "text")) { @@ -215,7 +223,7 @@ class OpenAI extends BaseLLM { signal, options, )) { - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } } @@ -258,7 +266,7 @@ class OpenAI extends BaseLLM { options.raw) ) { for await (const content of this._legacystreamComplete( - stripImages(messages[messages.length - 1]?.content || ""), + renderChatMessage(messages[messages.length - 1]), signal, options, )) { diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index c17aac90d..c9254eacc 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -4,13 +4,11 @@ import { ChatMessage, CompletionOptions, LLMOptions, - MessagePart, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; -import { streamSse } from "../stream.js"; -import { streamResponse } from "../stream.js"; +import { streamResponse, streamSse } from "../stream.js"; import Anthropic from "./Anthropic.js"; import Gemini from "./Gemini.js"; @@ -40,16 +38,17 @@ class VertexAI extends BaseLLM { super(_options); this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options); this.vertexProvider = - _options.model.includes("mistral") || _options.model.includes("codestral") || _options.model.includes("mixtral") + _options.model.includes("mistral") || + _options.model.includes("codestral") || + _options.model.includes("mixtral") ? "mistral" : _options.model.includes("claude") ? "anthropic" : _options.model.includes("gemini") - ? "gemini" : - "unknown"; + ? "gemini" + : "unknown"; this.anthropicInstance = new Anthropic(_options); this.geminiInstance = new Gemini(_options); - } async fetch(url: RequestInfo | URL, init?: RequestInit) { @@ -82,18 +81,18 @@ class VertexAI extends BaseLLM { }; } - protected async *StreamChatAnthropic( messages: ChatMessage[], options: CompletionOptions, ): AsyncGenerator { - const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; - const systemMessage: string = stripImages( - messages.filter((m) => m.role === "system")[0]?.content, + const shouldCacheSystemMessage = + !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; + const systemMessage: string = renderChatMessage( + messages.filter((m) => m.role === "system")[0], ); const apiURL = new URL( `publishers/anthropic/models/${options.model}:streamRawPredict`, - this.apiBase + this.apiBase, ); const response = await this.fetch(apiURL, { @@ -108,12 +107,12 @@ class VertexAI extends BaseLLM { messages: this.anthropicInstance.convertMessages(messages), system: shouldCacheSystemMessage ? [ - { - type: "text", - text: this.systemMessage, - cache_control: { type: "ephemeral" }, - }, - ] + { + type: "text", + text: this.systemMessage, + cache_control: { type: "ephemeral" }, + }, + ] : systemMessage, }), }); @@ -125,14 +124,15 @@ class VertexAI extends BaseLLM { } for await (const value of streamSse(response)) { - if (value.type == "message_start") {console.log(value);} + if (value.type == "message_start") { + console.log(value); + } if (value.delta?.text) { yield { role: "assistant", content: value.delta.text }; } } } - //Gemini private async *streamChatGemini( @@ -152,6 +152,10 @@ class VertexAI extends BaseLLM { if (msg.role === "system" && !isV1API) { return null; // Don't include system message in contents } + if (msg.role === "tool") { + return null; + } + return { role: msg.role === "assistant" ? "model" : "user", parts: @@ -168,8 +172,8 @@ class VertexAI extends BaseLLM { // if this.systemMessage is defined, reformat it for Gemini API ...(this.systemMessage && !isV1API && { - systemInstruction: { parts: [{ text: this.systemMessage }] }, - }), + systemInstruction: { parts: [{ text: this.systemMessage }] }, + }), }; const response = await this.fetch(apiURL, { method: "POST", @@ -265,7 +269,6 @@ class VertexAI extends BaseLLM { //Mistral - protected async *StreamChatMistral( messages: ChatMessage[], options: CompletionOptions, @@ -330,7 +333,7 @@ class VertexAI extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), - signal + signal, }); for await (const chunk of streamSse(response)) { @@ -338,8 +341,6 @@ class VertexAI extends BaseLLM { } } - - //gecko protected async *streamFimGecko( prefix: string, @@ -347,15 +348,18 @@ class VertexAI extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - const endpoint = new URL("publishers/google/models/code-gecko:predict", this.apiBase); + const endpoint = new URL( + "publishers/google/models/code-gecko:predict", + this.apiBase, + ); const resp = await this.fetch(endpoint, { method: "POST", body: JSON.stringify({ instances: [ { prefix: prefix, - suffix: suffix - } + suffix: suffix, + }, ], parameters: { temperature: options.temperature, @@ -363,10 +367,9 @@ class VertexAI extends BaseLLM { stopSequences: options.stop?.splice(0, 5), frequencyPenalty: options.frequencyPenalty, presencePenalty: options.frequencyPenalty, - } - + }, }), - signal + signal, }); // Streaming is not supported by code-gecko // TODO: convert to non-streaming fim method when one exist in continue. @@ -409,7 +412,7 @@ class VertexAI extends BaseLLM { signal, options, )) { - yield stripImages(message.content); + yield renderChatMessage(message); } } @@ -419,9 +422,6 @@ class VertexAI extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - - - if (this.model === "code-gecko") { yield* this.streamFimGecko(prefix, suffix, signal, options); } else if (this.model.includes("codestral")) { @@ -429,21 +429,15 @@ class VertexAI extends BaseLLM { } else { throw new Error(`Unsupported model: ${this.model}`); } - - } supportsFim(): boolean { return ["code-gecko", "codestral-latest"].includes(this.model); } - - } async function delay(seconds: number) { return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); } - - export default VertexAI; diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 808557692..fb82dacf9 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -4,25 +4,22 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; let watsonxToken = { - expiration: 0, - token: "" + expiration: 0, + token: "", }; class WatsonX extends BaseLLM { - constructor(options: LLMOptions) { super(options); } async getBearerToken(): Promise<{ token: string; expiration: number }> { - if ( - this.apiBase?.includes("cloud.ibm.com") - ) { + if (this.apiBase?.includes("cloud.ibm.com")) { // watsonx SaaS const wxToken = await ( await fetch( @@ -82,11 +79,9 @@ class WatsonX extends BaseLLM { } getWatsonxEndpoint(): string { - return ( - this.deploymentId ? - `${this.apiBase}/ml/v1/deployments/${this.deploymentId}/text/generation_stream?version=${this.apiVersion}`: - `${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}` - ); + return this.deploymentId + ? `${this.apiBase}/ml/v1/deployments/${this.deploymentId}/text/generation_stream?version=${this.apiVersion}` + : `${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}`; } static providerName: ModelProvider = "watsonx"; @@ -96,6 +91,10 @@ class WatsonX extends BaseLLM { return message; } + if (message.role === "tool") { + return null; + } + const parts = message.content.map((part) => { const msg: any = { type: part.type, @@ -119,7 +118,7 @@ class WatsonX extends BaseLLM { protected _convertArgs(options: any, messages: ChatMessage[]) { const finalOptions = { - messages: messages.map(this._convertMessage), + messages: messages.map(this._convertMessage).filter(Boolean), model: this._convertModelName(options.model), max_tokens: options.maxTokens, temperature: options.temperature, @@ -133,8 +132,9 @@ class WatsonX extends BaseLLM { protected _getHeaders() { return { "Content-Type": "application/json", - Authorization: `${watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" - } ${watsonxToken.token}`, + Authorization: `${ + watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxToken.token}`, }; } @@ -165,7 +165,7 @@ class WatsonX extends BaseLLM { signal, options, )) { - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } } @@ -183,7 +183,8 @@ class WatsonX extends BaseLLM { watsonxToken = await this.getBearerToken(); } else { console.log( - `Reusing token (expires in ${(watsonxToken.expiration - now) / 60 + `Reusing token (expires in ${ + (watsonxToken.expiration - now) / 60 } mins)`, ); } @@ -191,7 +192,8 @@ class WatsonX extends BaseLLM { throw new Error("Something went wrong. Check your credentials, please."); } const stopSequences = - options.stop?.slice(0,6) ?? (options.model?.includes("granite") ? ["Question:"] : []); + options.stop?.slice(0, 6) ?? + (options.model?.includes("granite") ? ["Question:"] : []); const url = this.getWatsonxEndpoint(); const headers = this._getHeaders(); @@ -224,7 +226,7 @@ class WatsonX extends BaseLLM { method: "POST", headers: headers, body: JSON.stringify(payload), - signal + signal, }); if (!response.ok || response.body === null) { diff --git a/core/llm/templates/chat.ts b/core/llm/templates/chat.ts index 9d26620f4..a4b999b05 100644 --- a/core/llm/templates/chat.ts +++ b/core/llm/templates/chat.ts @@ -1,5 +1,5 @@ import { ChatMessage } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; function templateFactory( systemMessage: (msg: ChatMessage) => string, @@ -64,7 +64,7 @@ function llama2TemplateMessages(msgs: ChatMessage[]): string { let prompt = ""; let hasSystem = msgs[0].role === "system"; - if (hasSystem && stripImages(msgs[0].content).trim() === "") { + if (hasSystem && renderChatMessage(msgs[0]).trim() === "") { hasSystem = false; msgs = msgs.slice(1); } @@ -158,7 +158,7 @@ function deepseekTemplateMessages(msgs: ChatMessage[]): string { prompt += "You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n"; if (msgs[0].role === "system") { - system = stripImages(msgs.shift()!.content); + system = renderChatMessage(msgs.shift()!); } for (let i = 0; i < msgs.length; i++) { @@ -245,7 +245,7 @@ function codeLlama70bTemplateMessages(msgs: ChatMessage[]): string { let prompt = ""; for (const msg of msgs) { - prompt += `Source: ${msg.role}\n\n ${stripImages(msg.content).trim()}`; + prompt += `Source: ${msg.role}\n\n ${renderChatMessage(msg).trim()}`; prompt += " "; } diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index 9e4f0c194..7d3750ad4 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -1,8 +1,8 @@ import * as YAML from "yaml"; import { ContinueSDK, SlashCommand } from "../.."; -import { stripImages } from "../../llm/images"; import { getBasename } from "../../util/index"; +import { renderChatMessage } from "../../util/messageContent"; import { getContextProviderHelpers } from "./getContextProviderHelpers"; import { renderTemplatedString } from "./renderTemplatedString"; @@ -90,8 +90,11 @@ export function slashCommandFromPromptFile( systemMessage, ); - for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of context.llm.streamChat( + messages, + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index f49fde837..a3f11f4ea 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -4,6 +4,7 @@ import { ProfileDescription } from "../config/ConfigHandler"; import type { BrowserSerializedContinueConfig, ChatMessage, + ContextItem, ContextItemWithId, ContextSubmenuItem, DiffLine, @@ -160,5 +161,5 @@ export type ToCoreFromIdeOrWebviewProtocol = { "profiles/switch": [{ id: string }, undefined]; "auth/getAuthUrl": [undefined, { url: string }]; - "tools/call": [{ toolCall: ToolCall }, { result: any }]; + "tools/call": [{ toolCall: ToolCall }, { contextItems: ContextItem[] }]; }; diff --git a/core/tools/createNewFile.ts b/core/tools/createNewFile.ts index 4d0b1c7a1..50a067f5e 100644 --- a/core/tools/createNewFile.ts +++ b/core/tools/createNewFile.ts @@ -14,6 +14,7 @@ export const createNewFileTool: Tool = { } await extras.ide.writeFile(filepath, args.contents); await extras.ide.openFile(filepath); + return []; }, function: { name: "create_new_file", diff --git a/core/tools/exactSearch.ts b/core/tools/exactSearch.ts index 2735b24a0..81bd061a4 100644 --- a/core/tools/exactSearch.ts +++ b/core/tools/exactSearch.ts @@ -3,8 +3,14 @@ import { Tool } from ".."; export const exactSearchTool: Tool = { type: "function", action: async (args, extras) => { - const results = await extras.ide.getSearchResults(args.query); - return results; + const content = await extras.ide.getSearchResults(args.query); + return [ + { + name: "Search results", + description: "Results from exact search", + content, + }, + ]; }, function: { name: "exact_search", diff --git a/core/tools/runTerminalCommand.ts b/core/tools/runTerminalCommand.ts index 4982ec972..6788c46d5 100644 --- a/core/tools/runTerminalCommand.ts +++ b/core/tools/runTerminalCommand.ts @@ -3,7 +3,16 @@ import { Tool } from ".."; export const runTerminalCommandTool: Tool = { type: "function", action: async (args, extras) => { - await extras.ide.runCommand(args.command); + const output = await extras.ide.runCommand(args.command); + + return []; + // return [ + // { + // description: "The contents of the terminal", + // content: output, + // name: "Terminal", + // }, + // ]; }, function: { name: "run_terminal_command", diff --git a/core/tools/searchWeb.ts b/core/tools/searchWeb.ts index 4a7c32788..3f5ded0b7 100644 --- a/core/tools/searchWeb.ts +++ b/core/tools/searchWeb.ts @@ -5,7 +5,7 @@ export const searchWebTool: Tool = { type: "function", action: async (args, extras) => { const webResults = await fetchSearchResults(args.query, 5, extras.fetch); - return webResults.map((result) => result.content).join("\n\n"); + return webResults; }, function: { name: "search_web", diff --git a/core/tools/viewDiff.ts b/core/tools/viewDiff.ts index 82439c54c..6bb327e2c 100644 --- a/core/tools/viewDiff.ts +++ b/core/tools/viewDiff.ts @@ -4,7 +4,13 @@ export const viewDiffTool: Tool = { type: "function", action: async (args, extras) => { const diff = await extras.ide.getDiff(true); - return diff; + return [ + { + name: "Diff", + description: "The current git diff", + content: diff, + }, + ]; }, function: { name: "view_diff", diff --git a/core/tools/viewRepoMap.ts b/core/tools/viewRepoMap.ts index c96f5ed27..9466c6be6 100644 --- a/core/tools/viewRepoMap.ts +++ b/core/tools/viewRepoMap.ts @@ -5,7 +5,13 @@ export const viewRepoMapTool: Tool = { type: "function", action: async (args, extras) => { const repoMap = await generateRepoMap(extras.llm, extras.ide, {}); - return repoMap; + return [ + { + name: "Repo map", + description: "Overview of the repository structure", + content: repoMap, + }, + ]; }, function: { name: "view_repo_map", diff --git a/core/tools/viewSubdirectory.ts b/core/tools/viewSubdirectory.ts index c3e83a39a..583266c52 100644 --- a/core/tools/viewSubdirectory.ts +++ b/core/tools/viewSubdirectory.ts @@ -8,7 +8,13 @@ export const viewSubdirectoryTool: Tool = { const repoMap = await generateRepoMap(extras.llm, extras.ide, { dirs: [directory_path], }); - return repoMap; + return [ + { + name: "Repo map", + description: `Map of ${directory_path}`, + content: repoMap, + }, + ]; }, function: { name: "view_subdirectory", diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index b8ca609a2..b52fd7696 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -1,5 +1,4 @@ import { ILLM, LLMFullCompletionOptions } from ".."; -import { stripImages } from "../llm/images"; import { removeQuotesAndEscapes } from "."; @@ -35,7 +34,6 @@ export class ChatDescriber { } // Clean up and distill the message we want to send to the LLM - message = stripImages(message); message = removeCodeBlocksAndTrim(message); if (!message) { diff --git a/core/util/messageContent.ts b/core/util/messageContent.ts new file mode 100644 index 000000000..b42bb082a --- /dev/null +++ b/core/util/messageContent.ts @@ -0,0 +1,45 @@ +import { + ChatMessage, + ContextItem, + MessageContent, + MessagePart, +} from "../index.js"; + +export function stripImages(messageContent: MessageContent): string { + if (typeof messageContent === "string") { + return messageContent; + } + + return messageContent + .filter((part) => part.type === "text") + .map((part) => part.text) + .join("\n"); +} + +export function renderChatMessage(message: ChatMessage): string { + switch (message.role) { + case "user": + case "assistant": + case "system": + return stripImages(message.content); + case "tool": + return message.content; + } +} + +export function renderContextItems(contextItems: ContextItem[]): string { + return contextItems.map((item) => item.content).join("\n\n"); +} + +export function normalizeToMessageParts(message: ChatMessage): MessagePart[] { + switch (message.role) { + case "user": + case "assistant": + case "system": + return Array.isArray(message.content) + ? message.content + : [{ type: "text", text: message.content }]; + case "tool": + return [{ type: "text", text: message.content }]; + } +} diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 3b5baad5f..28bce52b9 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -4,7 +4,6 @@ import * as path from "node:path"; import { ConfigHandler } from "core/config/ConfigHandler"; import { getModelByRole } from "core/config/util"; import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock"; -import { stripImages } from "core/llm/images"; import { FromCoreProtocol, FromWebviewProtocol, @@ -22,6 +21,7 @@ import { InProcessMessenger, Message } from "core/util/messenger"; import { getConfigJsonPath } from "core/util/paths"; import * as vscode from "vscode"; +import { stripImages } from "core/util/messageContent"; import { VerticalDiffManager } from "../diff/vertical/manager"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { diff --git a/gui/src/components/StepContainer/MultifileEditActions.tsx b/gui/src/components/StepContainer/MultifileEditActions.tsx index 5fb7122df..d3c292ce4 100644 --- a/gui/src/components/StepContainer/MultifileEditActions.tsx +++ b/gui/src/components/StepContainer/MultifileEditActions.tsx @@ -1,10 +1,11 @@ +import { ChatHistoryItem } from "core"; import { useSelector } from "react-redux"; import { RootState } from "../../redux/store"; import AcceptRejectAllButtons from "./AcceptRejectAllButtons"; import FeedbackButtons from "./FeedbackButtons"; import UndoAndRedoButtons from "./UndoAndRedoButtons"; -import { ChatHistoryItem } from "core"; -import { stripImages } from "core/llm/images"; + +import { renderChatMessage } from "core/util/messageContent"; import { CopyIconButton } from "../gui/CopyIconButton"; export interface MultifileEditActionsProps { @@ -53,7 +54,7 @@ export default function MultifileEditActions({
diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index 138e93c6a..7f61e2241 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -1,6 +1,6 @@ import { BarsArrowDownIcon, TrashIcon } from "@heroicons/react/24/outline"; import { ChatHistoryItem } from "core"; -import { stripImages } from "core/llm/images"; +import { renderChatMessage } from "core/util/messageContent"; import { useSelector } from "react-redux"; import { RootState } from "../../redux/store"; import { CopyIconButton } from "../gui/CopyIconButton"; @@ -54,7 +54,7 @@ export default function ResponseActions({ diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index 610cfd0f9..6aeaee32e 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -1,5 +1,5 @@ import { ChatHistoryItem } from "core"; -import { stripImages } from "core/llm/images"; +import { renderChatMessage } from "core/util/messageContent"; import { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; @@ -42,7 +42,7 @@ export default function StepContainer(props: StepContainerProps) { useEffect(() => { if (!active) { - const content = stripImages(props.item.message.content).trim(); + const content = renderChatMessage(props.item.message).trim(); const endingPunctuation = [".", "?", "!", "```", ":"]; // If not ending in punctuation or emoji, we assume the response got truncated @@ -88,12 +88,12 @@ export default function StepContainer(props: StepContainerProps) { className="max-w-full overflow-x-auto whitespace-pre-wrap break-words p-4" style={{ fontSize: getFontSize() - 2 }} > - {stripImages(props.item.message.content)} + {renderChatMessage(props.item.message)} ) : ( )} diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 64acba85a..09f38869c 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -7,7 +7,7 @@ import { MessagePart, RangeInFile, } from "core"; -import { stripImages } from "core/llm/images"; +import { stripImages } from "core/util/messageContent"; import { IIdeMessenger } from "../../context/IdeMessenger"; interface MentionAttrs { diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 21face2a7..a6de4883d 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -4,6 +4,7 @@ import { ChatHistory, ChatHistoryItem, ChatMessage, + ContextItem, ContextItemWithId, InputModifiers, MessageContent, @@ -12,8 +13,11 @@ import { SlashCommandDescription, } from "core"; import { constructMessages } from "core/llm/constructMessages"; -import { stripImages } from "core/llm/images"; import { getBasename, getRelativePath } from "core/util"; +import { + renderChatMessage, + renderContextItems, +} from "core/util/messageContent"; import { usePostHog } from "posthog-js/react"; import { useEffect, useRef, useState } from "react"; import { useSelector } from "react-redux"; @@ -122,7 +126,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } // Convert to actual slash command object with runnable function - return [slashCommand, stripImages(input)]; + return [slashCommand, renderChatMessage({ role: "user", content: input })]; }; async function _streamSlashCommand( @@ -352,14 +356,14 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { async function streamResponseAfterToolCall( toolCallId: string, - toolOutput: string, + toolOutput: ContextItem[], ) { await handleErrors(async () => { resetStateForNewMessage(); const newMessage: ChatMessage = { role: "tool", - content: toolOutput, + content: renderContextItems(toolOutput), toolCallId, }; diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index bb5935653..d4a09421e 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -1,7 +1,6 @@ import { Dispatch } from "@reduxjs/toolkit"; import { PersistedSessionInfo, SessionInfo } from "core"; -import { stripImages } from "core/llm/images"; import { useCallback, useContext } from "react"; import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; @@ -10,6 +9,7 @@ import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { newSession } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; +import { renderChatMessage } from "core/util/messageContent"; const MAX_TITLE_LENGTH = 100; @@ -79,7 +79,7 @@ function useHistory(dispatch: Dispatch) { let title = stateCopy.title === "New Session" ? truncateText( - stripImages(stateCopy.history[0].message.content) + renderChatMessage(stateCopy.history[0].message) .split("\n") .filter((l) => l.trim() !== "") .slice(-1)[0] || "", diff --git a/gui/src/pages/edit/index.tsx b/gui/src/pages/edit/index.tsx index c601c9650..602b2c0f1 100644 --- a/gui/src/pages/edit/index.tsx +++ b/gui/src/pages/edit/index.tsx @@ -1,7 +1,7 @@ import { ArrowLeftIcon } from "@heroicons/react/24/outline"; import { Editor, JSONContent } from "@tiptap/core"; import { InputModifiers } from "core"; -import { stripImages } from "core/llm/images"; +import { renderChatMessage } from "core/util/messageContent"; import { useContext, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; @@ -178,7 +178,10 @@ function Edit() { const prompt = [ ...contextItems.map((item) => item.content), - stripImages(userInstructions), + renderChatMessage({ + role: "user", + content: userInstructions, + }), ].join("\n\n"); ideMessenger.post("edit/sendPrompt", { prompt, diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index d7e41bfde..b1ffbf25c 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -6,7 +6,7 @@ import { } from "@heroicons/react/24/outline"; import { JSONContent } from "@tiptap/react"; import { InputModifiers } from "core"; -import { stripImages } from "core/llm/images"; +import { renderChatMessage } from "core/util/messageContent"; import { usePostHog } from "posthog-js/react"; import { Fragment, @@ -350,7 +350,7 @@ export function Chat() { /> ) : item.message.role === "tool" ? ( ) : item.message.role === "assistant" && diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx index 207945a8e..fea85ca9f 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx @@ -10,22 +10,33 @@ export function FunctionSpecificHeader(props: FunctionSpecificHeaderProps) { props.toolCall.function.arguments, ); + let message; + switch (props.toolCall.function.name) { case "create_new_file": - return "Continue wants to create a new file"; + message = "Continue wants to create a new file"; + break; case "run_terminal_command": - return "Continue wants to run a terminal command."; + message = "Continue wants to run a terminal command."; + break; case "exact_search": - return "Continue wants to search your codebase"; + message = "Continue wants to search your codebase"; + break; case "search_web": - return "Continue wants to search the internet"; + message = "Continue wants to search the internet"; + break; case "view_diff": - return "Continue wants to view the current git diff"; + message = "Continue wants to view the current git diff"; + break; case "view_repo_map": - return "Continue wants to view a map of your repository"; + message = "Continue wants to view a map of your repository"; + break; case "view_subdirectory": - return `Continue wants to view the contents of ${incrementalJson.directory_path ?? "a subdirectory"}`; + message = `Continue wants to view the contents of ${incrementalJson.directory_path ?? "a subdirectory"}`; + break; default: - return `Continue wants to use the ${props.toolCall.function.name} function.`; + message = `Continue wants to use the ${props.toolCall.function.name} function.`; } + + return
{message}
; } diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx index 3ea14c8bf..7143769ac 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx @@ -85,11 +85,9 @@ export function ToolCallButtons(props: ToolCallButtonsProps) { clearTimeout(timer); if (result.status === "success") { + const contextItems = result.content.contextItems; // Send to the LLM to continue the conversation - streamResponseAfterToolCall( - toolCallState.toolCall.id, - result.content.result, - ); + streamResponseAfterToolCall(toolCallState.toolCall.id, contextItems); } } diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index ff5db6c02..cf2e6fa96 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -11,8 +11,8 @@ import { } from "core"; import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; -import { stripImages } from "core/llm/images"; import { ApplyState } from "core/protocol/ideWebview"; +import { renderChatMessage } from "core/util/messageContent"; import { v4 as uuidv4, v4 } from "uuid"; import { ToolState } from "../../pages/gui/ToolCallDiv/types"; @@ -30,9 +30,15 @@ type ChatHistoryItemWithMessageId = ChatHistoryItem & { type State = { currentToolCallState: CurrentToolCallState; history: ChatHistoryItemWithMessageId[]; - ttsActive: boolean; active: boolean; isGatheringContext: boolean; + checkpoints: Checkpoint[]; + applyStates: ApplyState[]; + nextCodeBlockToApplyIndex: number; + streamAborter: AbortController; + curCheckpointIndex: number; + + ttsActive: boolean; config: BrowserSerializedContinueConfig; title: string; sessionId: string; @@ -40,11 +46,6 @@ type State = { mainEditorContent?: JSONContent; selectedProfileId: string; configError: ConfigValidationError[] | undefined; - checkpoints: Checkpoint[]; - curCheckpointIndex: number; - applyStates: ApplyState[]; - nextCodeBlockToApplyIndex: number; - streamAborter: AbortController; isMultifileEdit: boolean; }; @@ -227,7 +228,7 @@ export const stateSlice = createSlice({ message: { ...payload.message, id: uuidv4() }, editorState: { type: "doc", - content: stripImages(payload.message.content) + content: renderChatMessage(payload.message) .split("\n") .map((line) => ({ type: "paragraph", @@ -281,6 +282,7 @@ export const stateSlice = createSlice({ (lastMessage.message.role !== action.payload.role || // This is when a tool call comes after assistant text (lastMessage.message.content !== "" && + action.payload.role === "assistant" && action.payload.toolCalls?.length)) ) { // Create a new message @@ -292,8 +294,12 @@ export const stateSlice = createSlice({ // Add to the existing message const msg = state.history[state.history.length - 1].message; if (action.payload.content) { - msg.content += stripImages(action.payload.content); - } else if (action.payload.toolCalls) { + msg.content += renderChatMessage(action.payload); + } else if ( + action.payload.role === "assistant" && + action.payload.toolCalls && + msg.role === "assistant" + ) { if (!msg.toolCalls) { msg.toolCalls = []; } diff --git a/manual-testing-sandbox/test.ts b/manual-testing-sandbox/test.ts new file mode 100644 index 000000000..9cf524421 --- /dev/null +++ b/manual-testing-sandbox/test.ts @@ -0,0 +1,41 @@ +class Calculator { + private result: number; + + constructor() { + this.result = 0; + } + + add(number: number): Calculator { + this.result += number; + return this; + } + + subtract(number: number): Calculator { + this.result -= number; + return this; + } + + multiply(number: number): Calculator { + this.result *= number; + return this; + } + + divide(number: number): Calculator { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult(): number { + return this.result; + } + + reset(): Calculator { + this.result = 0; + return this; + } +} + +export default Calculator; \ No newline at end of file From f3ba421ca4da5a5baf27d2f51a81b11f6e469319 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 21 Nov 2024 22:03:32 -0800 Subject: [PATCH 036/105] stop CompileChatMessages from removing tool messages --- core/llm/countTokens.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 896cfe337..49aed0e8d 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -350,6 +350,24 @@ function addSpaceToAnyEmptyMessages(messages: ChatMessage[]): ChatMessage[] { }); } +function chatMessageIsEmpty(message: ChatMessage): boolean { + switch (message.role) { + case "system": + case "user": + return ( + typeof message.content === "string" && message.content.trim() === "" + ); + case "assistant": + return ( + typeof message.content === "string" && + message.content.trim() === "" && + !message.toolCalls + ); + case "tool": + return false; + } +} + function compileChatMessages( modelName: string, msgs: ChatMessage[] | undefined, @@ -363,7 +381,7 @@ function compileChatMessages( let msgsCopy = msgs ? msgs .map((msg) => ({ ...msg })) - .filter((msg) => msg.content !== "" && msg.role !== "system") + .filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system") : []; msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); From c49faa9c87af7f40ad45f489c0f8fc1d827320c7 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 21 Nov 2024 22:03:44 -0800 Subject: [PATCH 037/105] get terminal output with tool unless ssh --- core/tools/runTerminalCommand.ts | 33 ++++++++++++++----- .../gui/ToolCallDiv/RunTerminalCommand.tsx | 2 +- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/core/tools/runTerminalCommand.ts b/core/tools/runTerminalCommand.ts index 6788c46d5..91e3f9edc 100644 --- a/core/tools/runTerminalCommand.ts +++ b/core/tools/runTerminalCommand.ts @@ -1,18 +1,33 @@ import { Tool } from ".."; +const util = require("node:util"); +const asyncExec = util.promisify(require("node:child_process").exec); + export const runTerminalCommandTool: Tool = { type: "function", action: async (args, extras) => { - const output = await extras.ide.runCommand(args.command); + const ideInfo = await extras.ide.getIdeInfo(); + if (ideInfo.remoteName === "local" || ideInfo.remoteName === "") { + // If we're local, can just run the terminal command with child_process + const output = asyncExec(args.command); + return [ + { + name: "Terminal", + description: "Terminal command output", + content: output.stdout, + }, + ]; + } - return []; - // return [ - // { - // description: "The contents of the terminal", - // content: output, - // name: "Terminal", - // }, - // ]; + await extras.ide.runCommand(args.command); + return [ + { + name: "Terminal", + description: "Terminal command output", + content: + "[Terminal output not available. This is only available in local development environments and not in SSH environments for example.]", + }, + ]; }, function: { name: "run_terminal_command", diff --git a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx index 799d65126..d9c44a2b0 100644 --- a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx +++ b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx @@ -11,7 +11,7 @@ export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { <> ); From 5a07fed30c8545774346b8e388aa609200166abb Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 21 Nov 2024 22:47:53 -0800 Subject: [PATCH 038/105] fix type errs --- core/llm/llms/Anthropic.ts | 7 ++++--- extensions/vscode/package-lock.json | 6 +++--- gui/package-lock.json | 8 +------- gui/src/App.tsx | 5 ----- gui/src/hooks/useChatHandler.ts | 13 ++++++------- gui/src/pages/Edit/Edit.tsx | 10 +++++----- gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx | 2 +- gui/src/redux/slices/stateSlice.ts | 5 +++++ 8 files changed, 25 insertions(+), 31 deletions(-) diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index d6569af8f..b3a099a81 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -4,7 +4,7 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { renderChatMessage } from "../../util/messageContent.js"; +import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; @@ -146,8 +146,9 @@ class Anthropic extends BaseLLM { ): AsyncGenerator { const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; - const systemMessage: string = - messages.filter((m) => m.role === "system")[0]?.content ?? ""; + const systemMessage: string = stripImages( + messages.filter((m) => m.role === "system")[0]?.content ?? "", + ); const msgs = this.convertMessages(messages); const response = await this.fetch(new URL("messages", this.apiBase), { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 31c9a041c..046b4f398 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.232", + "version": "0.9.233", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.232", + "version": "0.9.233", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -109,7 +109,7 @@ "cheerio": "^1.0.0-rc.12", "commander": "^12.0.0", "comment-json": "^4.2.3", - "dbinfoz": "^0.11.0", + "dbinfoz": "^0.14.0", "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", diff --git a/gui/package-lock.json b/gui/package-lock.json index 2f64dad52..107360d04 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -56,7 +56,6 @@ "socket.io-client": "^4.7.2", "styled-components": "^5.3.6", "table": "^6.8.1", - "tailwind-scrollbar-hide": "^1.1.7", "tippy.js": "^6.3.7", "unist-util-visit": "^5.0.0", "uuid": "^9.0.1", @@ -112,7 +111,7 @@ "cheerio": "^1.0.0-rc.12", "commander": "^12.0.0", "comment-json": "^4.2.3", - "dbinfoz": "^0.11.0", + "dbinfoz": "^0.14.0", "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", @@ -8985,11 +8984,6 @@ "node": ">=10.0.0" } }, - "node_modules/tailwind-scrollbar-hide": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/tailwind-scrollbar-hide/-/tailwind-scrollbar-hide-1.1.7.tgz", - "integrity": "sha512-X324n9OtpTmOMqEgDUEA/RgLrNfBF/jwJdctaPZDzB3mppxJk7TLIDmOreEDm1Bq4R9LSPu4Epf8VSdovNU+iA==" - }, "node_modules/tailwindcss": { "version": "3.4.12", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.12.tgz", diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 1e34e6e15..0c3f81ada 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -8,7 +8,6 @@ import useSubmenuContextProviders from "./hooks/useSubmenuContextProviders"; import { useVscTheme } from "./hooks/useVscTheme"; import { AddNewModel, ConfigureProvider } from "./pages/AddNewModel"; import ConfigErrorPage from "./pages/config-error"; -import Edit from "./pages/Edit"; import ErrorPage from "./pages/error"; import Chat from "./pages/gui"; import History from "./pages/history"; @@ -33,10 +32,6 @@ const router = createMemoryRouter([ path: "/", element: , }, - { - path: "/edit", - element: , - }, { path: "/history", element: , diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index cf5aa39a2..45b391233 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -30,7 +30,7 @@ import { abortStream, acceptToolCall, addPromptCompletionPair, - clearLastResponse, + clearLastEmptyResponse, initNewActiveMessage, resetNextCodeBlockToApplyIndex, resubmitAtIndex, @@ -38,13 +38,12 @@ import { setCurCheckpointIndex, setInactive, setIsGatheringContext, - setIsInMultifileEdit, setMessageAtIndex, streamUpdate, } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; -import useHistory from "./useHistory"; import { updateFileSymbolsFromContextItems } from "../util/symbols"; +import useHistory from "./useHistory"; function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const posthog = usePostHog(); @@ -103,7 +102,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } } catch (e) { // If there's an error, we should clear the response so there aren't two input boxes - dispatch(clearLastResponse()); + dispatch(clearLastEmptyResponse()); } } @@ -352,9 +351,9 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { params: {}, }); - if (slashCommand.name === "multifile-edit") { - dispatch(setIsInMultifileEdit(true)); - } + // if (slashCommand.name === "multifile-edit") { + // dispatch(setIsInMultifileEdit(true)); + // } await _streamSlashCommand( messages, diff --git a/gui/src/pages/Edit/Edit.tsx b/gui/src/pages/Edit/Edit.tsx index c69200bc1..c5ef23731 100644 --- a/gui/src/pages/Edit/Edit.tsx +++ b/gui/src/pages/Edit/Edit.tsx @@ -1,14 +1,18 @@ import { ArrowLeftIcon } from "@heroicons/react/24/outline"; import { Editor, JSONContent } from "@tiptap/core"; import { InputModifiers, RangeInFileWithContents } from "core"; -import { stripImages } from "core/llm/images"; +import { stripImages } from "core/util/messageContent"; import { useCallback, useContext, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; +import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; import resolveEditorContent from "../../components/mainInput/resolveInput"; import TipTapEditor from "../../components/mainInput/TipTapEditor"; +import StepContainer from "../../components/StepContainer"; +import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons"; import { IdeMessengerContext } from "../../context/IdeMessenger"; +import useChatHandler from "../../hooks/useChatHandler"; import { clearCodeToEdit, setEditDone, @@ -16,10 +20,6 @@ import { } from "../../redux/slices/editModeState"; import { RootState } from "../../redux/store"; import CodeToEdit from "./CodeToEdit"; -import useChatHandler from "../../hooks/useChatHandler"; -import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons"; -import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; -import StepContainer from "../../components/StepContainer"; import getMultifileEditPrompt from "./getMultifileEditPrompt"; const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [ diff --git a/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx b/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx index 0e6c6b245..44a3d4d08 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx @@ -16,7 +16,7 @@ function ToolOutput(props: ToolOutputProps) { return (
Date: Thu, 21 Nov 2024 23:07:01 -0800 Subject: [PATCH 039/105] tool use ui improvements --- .continueignore | 3 ++- .../StepContainer/StepContainer.tsx | 5 +--- gui/src/hooks/useChatHandler.ts | 13 ++++++++++ gui/src/pages/gui/Chat.tsx | 25 ++++++++----------- .../ToolCallDiv/FunctionSpecificHeader.tsx | 2 +- gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx | 22 ++++------------ 6 files changed, 33 insertions(+), 37 deletions(-) diff --git a/.continueignore b/.continueignore index 7e0d0c115..79e924012 100644 --- a/.continueignore +++ b/.continueignore @@ -4,4 +4,5 @@ docs/docs/languages .idea/ .vscode/ .archive/ -**/*.scm \ No newline at end of file +**/*.scm +**/*.diff \ No newline at end of file diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index d3adcb388..593fef732 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -77,10 +77,7 @@ export default function StepContainer(props: StepContainerProps) { return (
{uiConfig?.displayRawMarkdown ? ( diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 45b391233..8fcbb2749 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -29,6 +29,7 @@ import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { abortStream, acceptToolCall, + addContextItemsAtIndex, addPromptCompletionPair, clearLastEmptyResponse, initNewActiveMessage, @@ -398,6 +399,18 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { }; dispatch(streamUpdate(newMessage)); + dispatch( + addContextItemsAtIndex({ + index: history.length, + contextItems: toolOutput.map((contextItem) => ({ + ...contextItem, + id: { + providerTitle: "toolCall", + itemId: toolCallId, + }, + })), + }), + ); dispatch(acceptToolCall()); activeRef.current = true; dispatch(setActive()); diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 47135f7d5..a858c09a8 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -6,16 +6,8 @@ import { } from "@heroicons/react/24/outline"; import { JSONContent } from "@tiptap/react"; import { InputModifiers } from "core"; -import { renderChatMessage } from "core/util/messageContent"; import { usePostHog } from "posthog-js/react"; -import { - Fragment, - useCallback, - useContext, - useEffect, - useRef, - useState, -} from "react"; +import { useCallback, useContext, useEffect, useRef, useState } from "react"; import { ErrorBoundary } from "react-error-boundary"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; @@ -28,6 +20,7 @@ import { import { ChatScrollAnchor } from "../../components/ChatScrollAnchor"; import { useFindWidget } from "../../components/find/FindWidget"; import TimelineItem from "../../components/gui/TimelineItem"; +import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks"; import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; import { TutorialCard } from "../../components/mainInput/TutorialCard"; @@ -60,11 +53,10 @@ import { } from "../../util"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; +import ConfigErrorIndicator from "./ConfigError"; import { ToolCallDiv } from "./ToolCallDiv"; import { ToolCallButtons } from "./ToolCallDiv/ToolCallButtonsDiv"; import ToolOutput from "./ToolCallDiv/ToolOutput"; -import ConfigErrorIndicator from "./ConfigError"; -import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks"; const StopButton = styled.div` background-color: ${vscBackground}; @@ -332,7 +324,12 @@ export function Chat() { > {highlights} {state.history.map((item, index: number) => ( - +
{ @@ -351,7 +348,7 @@ export function Chat() { /> ) : item.message.role === "tool" ? ( ) : item.message.role === "assistant" && @@ -401,7 +398,7 @@ export function Chat() {
)} -
+
))}
); From 3c42902266eca7a224336408631b7148d059c2ec Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Nov 2024 08:04:57 -0800 Subject: [PATCH 040/105] ui improvement --- .../StepContainer/ResponseActions.tsx | 58 +++++++++++-------- .../StepContainer/StepContainer.tsx | 21 +++---- .../gui/ToolCallDiv/RunTerminalCommand.tsx | 2 +- .../gui/ToolCallDiv/ToolCallButtonsDiv.tsx | 16 ++++- 4 files changed, 57 insertions(+), 40 deletions(-) diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index a6c66e9d5..3769907ef 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -5,8 +5,8 @@ import { useSelector } from "react-redux"; import { RootState } from "../../redux/store"; import { CopyIconButton } from "../gui/CopyIconButton"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import FeedbackButtons from "./FeedbackButtons"; import EditActions from "./EditActions"; +import FeedbackButtons from "./FeedbackButtons"; export interface ResponseActionsProps { isTruncated: boolean; @@ -14,6 +14,7 @@ export interface ResponseActionsProps { index: number; onDelete: () => void; item: ChatHistoryItem; + shouldHideActions: boolean; } export default function ResponseActions({ @@ -22,6 +23,7 @@ export default function ResponseActions({ item, isTruncated, onDelete, + shouldHideActions, }: ResponseActionsProps) { const isInEditMode = useSelector( (store: RootState) => store.editModeState.isInEditMode, @@ -36,30 +38,38 @@ export default function ResponseActions({ return (
- {isTruncated && ( - - - + {shouldHideActions || ( + <> + {isTruncated && ( + + + + )} + + {shouldRenderDelete && ( + + + + )} + + + + + )} - - {shouldRenderDelete && ( - - - - )} - - - -
); } diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index 593fef732..8c28d5ddd 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -96,18 +96,15 @@ export default function StepContainer(props: StepContainerProps) { )} {/* We want to occupy space in the DOM regardless of whether the actions are visible to avoid jank on */} -
- {!shouldHideActions && ( - - )} +
+
); diff --git a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx index d9c44a2b0..c217bd07b 100644 --- a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx +++ b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx @@ -11,7 +11,7 @@ export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { <> ); diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx index 7143769ac..a2c69cbed 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx @@ -91,6 +91,18 @@ export function ToolCallButtons(props: ToolCallButtonsProps) { } } + async function cancelTool() { + dispatch(cancelToolCall()); + streamResponseAfterToolCall(toolCallState.toolCall.id, [ + { + name: "Cancelled", + description: "Cancelled", + content: + "This tool call was cancelled by the user. You should try something else, likely just chatting instead of using another tool.", + }, + ]); + } + return ( <> @@ -106,9 +118,7 @@ export function ToolCallButtons(props: ToolCallButtonsProps) {
) : toolCallState.currentToolCallState === "generated" ? ( <> - dispatch(cancelToolCall())}> - Cancel - + Cancel Continue ) : toolCallState.currentToolCallState === "calling" ? ( From 587ad3de6ae75dfe4059cd4b9940cd44b4efdf17 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Nov 2024 08:05:18 -0800 Subject: [PATCH 041/105] return terminal output --- core/tools/runTerminalCommand.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/tools/runTerminalCommand.ts b/core/tools/runTerminalCommand.ts index 91e3f9edc..dc7cd4bd7 100644 --- a/core/tools/runTerminalCommand.ts +++ b/core/tools/runTerminalCommand.ts @@ -9,12 +9,14 @@ export const runTerminalCommandTool: Tool = { const ideInfo = await extras.ide.getIdeInfo(); if (ideInfo.remoteName === "local" || ideInfo.remoteName === "") { // If we're local, can just run the terminal command with child_process - const output = asyncExec(args.command); + const output = await asyncExec(args.command, { + cwd: (await extras.ide.getWorkspaceDirs())[0], + }); return [ { name: "Terminal", description: "Terminal command output", - content: output.stdout, + content: output.stdout ?? "", }, ]; } From 045c450e4d4d786c3540d48f0e2096d61ab9cca3 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Nov 2024 09:49:10 -0800 Subject: [PATCH 042/105] tools button --- core/config/load.ts | 2 -- core/core.ts | 12 ++++--- core/protocol/core.ts | 2 +- .../components/mainInput/ContinueInputBox.tsx | 3 ++ gui/src/components/mainInput/InputToolbar.tsx | 31 +++++++++++++++++-- gui/src/components/mainInput/TipTapEditor.tsx | 14 +++------ gui/src/pages/gui/ToolCallDiv/index.tsx | 2 ++ gui/src/redux/slices/uiStateSlice.ts | 6 ++++ 8 files changed, 53 insertions(+), 19 deletions(-) diff --git a/core/config/load.ts b/core/config/load.ts index 627d59b67..3aa9ffc8d 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -59,7 +59,6 @@ import { readAllGlobalPromptFiles, } from "../util/paths"; -import { allTools } from "../tools"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -337,7 +336,6 @@ async function intermediateToFinalConfig( ...model.requestOptions, ...config.requestOptions, }; - model.completionOptions.tools = allTools; } if (allowFreeTrial) { diff --git a/core/core.ts b/core/core.ts index 6ba78faaf..897ba50cf 100644 --- a/core/core.ts +++ b/core/core.ts @@ -28,11 +28,7 @@ import { DevDataSqliteDb } from "./util/devdataSqlite"; import { fetchwithRequestOptions } from "./util/fetchWithOptions"; import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; -import { - editConfigJson, - getConfigJsonPath, - setupInitialDotContinueDirectory, -} from "./util/paths"; +import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; @@ -386,6 +382,12 @@ export class Core { } const model = await configHandler.llmFromTitle(msg.data.title); + + if (msg.data.useTools) { + // Array.isArray(config.experimental?.allowTools)) { + msg.data.completionOptions.tools = allTools; + } + const gen = model.streamChat( msg.data.messages, new AbortController().signal, diff --git a/core/protocol/core.ts b/core/protocol/core.ts index a4d928e49..bebfc1b6e 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -10,7 +10,6 @@ import type { DiffLine, FileSymbolMap, IdeSettings, - IndexingStatusMap, LLMFullCompletionOptions, ModelDescription, ModelRoles, @@ -123,6 +122,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { messages: ChatMessage[]; completionOptions: LLMFullCompletionOptions; title: string; + useTools?: boolean; }, ProtocolGeneratorType, ]; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 78e2a5710..89ecab411 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -107,6 +107,9 @@ function ContinueInputBox(props: ContinueInputBoxProps) { availableContextProviders={availableContextProviders ?? []} availableSlashCommands={availableSlashCommands} historyKey="chat" + toolbarOptions={{ + hideTools: true, + }} />
diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index c335ce978..fae6f9a09 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -1,8 +1,12 @@ -import { AtSymbolIcon, PhotoIcon } from "@heroicons/react/24/outline"; +import { + AtSymbolIcon, + PhotoIcon, + WrenchScrewdriverIcon, +} from "@heroicons/react/24/outline"; import { InputModifiers } from "core"; import { modelSupportsImages } from "core/llm/autodetect"; import { useRef } from "react"; -import { useSelector } from "react-redux"; +import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, @@ -12,6 +16,8 @@ import { } from ".."; import { selectUseActiveFile } from "../../redux/selectors"; import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; +import { toggleUseTools } from "../../redux/slices/uiStateSlice"; +import { RootState } from "../../redux/store"; import { getAltKeyLabel, getFontSize, @@ -69,6 +75,7 @@ export interface ToolbarOptions { hideAddContext?: boolean; enterText?: string; hideSelectModel?: boolean; + hideTools?: boolean; } interface InputToolbarProps { @@ -87,6 +94,9 @@ function InputToolbar(props: InputToolbarProps) { const fileInputRef = useRef(null); const defaultModel = useSelector(defaultModelSelector); const useActiveFile = useSelector(selectUseActiveFile); + const dispatch = useDispatch(); + + const useTools = useSelector((store: RootState) => store.uiState.useTools); const supportsImages = defaultModel && @@ -144,6 +154,23 @@ function InputToolbar(props: InputToolbarProps) { )} + + {props.toolbarOptions?.hideTools || ( + dispatch(toggleUseTools())}> + + + Tools + + + )}
diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index bde052274..aa0b70487 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -40,16 +40,16 @@ import { IdeMessengerContext } from "../../context/IdeMessenger"; import { SubmenuContextProvidersContext } from "../../context/SubmenuContextProviders"; import useHistory from "../../hooks/useHistory"; import { useInputHistory } from "../../hooks/useInputHistory"; +import useIsOSREnabled from "../../hooks/useIsOSREnabled"; import useUpdatingRef from "../../hooks/useUpdatingRef"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { selectUseActiveFile } from "../../redux/selectors"; import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; +import { addCodeToEdit } from "../../redux/slices/editModeState"; +import { setShouldAddFileForEditing } from "../../redux/slices/uiStateSlice"; import { RootState } from "../../redux/store"; -import { - getFontSize, - isJetBrains, - isMetaEquivalentKeyPressed, -} from "../../util"; +import { getFontSize, isMetaEquivalentKeyPressed } from "../../util"; +import { AddCodeToEdit } from "./AddCodeToEditExtension"; import { CodeBlockExtension } from "./CodeBlockExtension"; import { SlashCommand } from "./CommandsExtension"; import InputToolbar, { ToolbarOptions } from "./InputToolbar"; @@ -64,10 +64,6 @@ import { handleVSCMetaKeyIssues, } from "./handleMetaKeyIssues"; import { ComboBoxItem } from "./types"; -import useIsOSREnabled from "../../hooks/useIsOSREnabled"; -import { setShouldAddFileForEditing } from "../../redux/slices/uiStateSlice"; -import { AddCodeToEdit } from "./AddCodeToEditExtension"; -import { addCodeToEdit } from "../../redux/slices/editModeState"; const InputBoxDiv = styled.div<{ border?: string }>` resize: none; diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 3235dd2d7..fa0a96a6a 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -43,6 +43,7 @@ export function ToolCallDiv(props: ToolCallDivProps) { }, [props.toolCall.function.arguments]); function getIcon(state: ToolState) { + console.log("State: ", state); if (props.acceptedToolCall === true) { return ; } else if (props.acceptedToolCall === false) { @@ -68,6 +69,7 @@ export function ToolCallDiv(props: ToolCallDivProps) { icon={getIcon(toolCallState.currentToolCallState)} toolCall={props.toolCall} > + {toolCallState.currentToolCallState} { state.shouldAddFileForEditing = action.payload; }, + toggleUseTools: (state) => { + state.useTools = !state.useTools; + }, }, }); @@ -58,6 +63,7 @@ export const { setDialogEntryOn, setShowDialog, setShouldAddFileForEditing, + toggleUseTools, } = uiStateSlice.actions; export default uiStateSlice.reducer; From 13181dc32c17f29b1c438e80d6ffc4c1a4a372ec Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Nov 2024 10:58:29 -0800 Subject: [PATCH 043/105] useTools option --- core/core.ts | 1 - core/index.d.ts | 1 + extensions/vscode/config_schema.json | 5 +++++ gui/src/components/mainInput/ContinueInputBox.tsx | 5 ++++- gui/src/context/IdeMessenger.ts | 3 +++ gui/src/hooks/useChatHandler.ts | 4 ++++ 6 files changed, 17 insertions(+), 2 deletions(-) diff --git a/core/core.ts b/core/core.ts index 897ba50cf..edb064afb 100644 --- a/core/core.ts +++ b/core/core.ts @@ -384,7 +384,6 @@ export class Core { const model = await configHandler.llmFromTitle(msg.data.title); if (msg.data.useTools) { - // Array.isArray(config.experimental?.allowTools)) { msg.data.completionOptions.tools = allTools; } diff --git a/core/index.d.ts b/core/index.d.ts index 647712f6a..8905e5646 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1158,6 +1158,7 @@ interface ExperimentalConfig { * This is needed to crawl a large number of documentation sites that are dynamically rendered. */ useChromiumForDocsCrawling?: boolean; + useTools?: boolean; } interface AnalyticsConfig { diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 7edceced4..d5c9223a4 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -3023,6 +3023,11 @@ "type": "boolean", "description": "Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`.", "default": false + }, + "useTools": { + "type": "boolean", + "description": "Allow tool use. Currently only supported with Claude 3.5 Sonnet", + "default": true } } } diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 89ecab411..ce1ebd424 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -68,6 +68,9 @@ function ContinueInputBox(props: ContinueInputBoxProps) { const availableContextProviders = useSelector( (store: RootState) => store.state.config.contextProviders, ); + const useTools = useSelector( + (store: RootState) => store.state.config.experimental?.useTools, + ); useWebviewListener( "newSessionWithPrompt", @@ -108,7 +111,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) { availableSlashCommands={availableSlashCommands} historyKey="chat" toolbarOptions={{ - hideTools: true, + hideTools: !useTools, }} /> diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.ts index 43fc7ef56..aea398feb 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.ts @@ -44,6 +44,7 @@ export interface IIdeMessenger { cancelToken: AbortSignal | undefined, messages: ChatMessage[], options?: LLMFullCompletionOptions, + useTools?: boolean, ): AsyncGenerator; ide: IDE; @@ -202,6 +203,7 @@ export class IdeMessenger implements IIdeMessenger { cancelToken: AbortSignal | undefined, messages: ChatMessage[], options: LLMFullCompletionOptions = {}, + useTools?: boolean, ): AsyncGenerator { const gen = this.streamRequest( "llm/streamChat", @@ -209,6 +211,7 @@ export class IdeMessenger implements IIdeMessenger { messages, title: modelTitle, completionOptions: options, + useTools, }, cancelToken, ); diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 8fcbb2749..e3d557f61 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -63,6 +63,8 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const streamAborter = useSelector( (store: RootState) => store.state.streamAborter, ); + const useTools = useSelector((store: RootState) => store.uiState.useTools); + const activeRef = useRef(active); const { saveSession } = useHistory(dispatch); @@ -85,6 +87,8 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { defaultModel.title, streamAborter.signal, messages, + {}, + useTools, ); let next = await gen.next(); From aee314b6bd73fe65cb6c5e4a378d165d506d6ec3 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Nov 2024 18:14:33 -0800 Subject: [PATCH 044/105] tools toggle button --- gui/src/components/mainInput/InputToolbar.tsx | 43 ++---------- .../mainInput/InputToolbar/HoverItem.tsx | 14 ++++ .../InputToolbar/ToggleToolsButton.tsx | 69 +++++++++++++++++++ 3 files changed, 88 insertions(+), 38 deletions(-) create mode 100644 gui/src/components/mainInput/InputToolbar/HoverItem.tsx create mode 100644 gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index fae6f9a09..a5bbd50b1 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -1,12 +1,8 @@ -import { - AtSymbolIcon, - PhotoIcon, - WrenchScrewdriverIcon, -} from "@heroicons/react/24/outline"; +import { AtSymbolIcon, PhotoIcon } from "@heroicons/react/24/outline"; import { InputModifiers } from "core"; import { modelSupportsImages } from "core/llm/autodetect"; import { useRef } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useSelector } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, @@ -16,8 +12,6 @@ import { } from ".."; import { selectUseActiveFile } from "../../redux/selectors"; import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; -import { toggleUseTools } from "../../redux/slices/uiStateSlice"; -import { RootState } from "../../redux/store"; import { getAltKeyLabel, getFontSize, @@ -26,6 +20,8 @@ import { } from "../../util"; import { ToolTip } from "../gui/Tooltip"; import ModelSelect from "../modelSelection/ModelSelect"; +import HoverItem from "./InputToolbar/HoverItem"; +import ToggleToolsButton from "./InputToolbar/ToggleToolsButton"; const StyledDiv = styled.div<{ isHidden: boolean }>` padding-top: 4px; @@ -44,17 +40,6 @@ const StyledDiv = styled.div<{ isHidden: boolean }>` } `; -const HoverItem = styled.span<{ isActive?: boolean }>` - padding: 0 4px; - padding-top: 2px; - padding-bottom: 2px; - cursor: pointer; - transition: - color 200ms, - background-color 200ms, - box-shadow 200ms; -`; - const EnterButton = styled.button` all: unset; padding: 2px 4px; @@ -94,9 +79,6 @@ function InputToolbar(props: InputToolbarProps) { const fileInputRef = useRef(null); const defaultModel = useSelector(defaultModelSelector); const useActiveFile = useSelector(selectUseActiveFile); - const dispatch = useDispatch(); - - const useTools = useSelector((store: RootState) => store.uiState.useTools); const supportsImages = defaultModel && @@ -155,22 +137,7 @@ function InputToolbar(props: InputToolbarProps) { )} - {props.toolbarOptions?.hideTools || ( - dispatch(toggleUseTools())}> - - - Tools - - - )} + {props.toolbarOptions?.hideTools || }
diff --git a/gui/src/components/mainInput/InputToolbar/HoverItem.tsx b/gui/src/components/mainInput/InputToolbar/HoverItem.tsx new file mode 100644 index 000000000..e668a69f2 --- /dev/null +++ b/gui/src/components/mainInput/InputToolbar/HoverItem.tsx @@ -0,0 +1,14 @@ +import styled from "styled-components"; + +const HoverItem = styled.span<{ isActive?: boolean }>` + padding: 0 4px; + padding-top: 2px; + padding-bottom: 2px; + cursor: pointer; + transition: + color 200ms, + background-color 200ms, + box-shadow 200ms; +`; + +export default HoverItem; diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx new file mode 100644 index 000000000..d1c093754 --- /dev/null +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -0,0 +1,69 @@ +import { + ChevronDownIcon, + WrenchScrewdriverIcon, +} from "@heroicons/react/24/outline"; +import { useDispatch, useSelector } from "react-redux"; +import styled from "styled-components"; +import { + defaultBorderRadius, + vscForeground, + vscListActiveBackground, +} from "../.."; +import { toggleUseTools } from "../../../redux/slices/uiStateSlice"; +import { RootState } from "../../../redux/store"; +import { getFontSize } from "../../../util"; +import { ToolTip } from "../../gui/Tooltip"; +import HoverItem from "./HoverItem"; + +const BackgroundDiv = styled.div<{ useTools: boolean }>` + background-color: ${(props) => + props.useTools ? vscListActiveBackground : "transparent"}; + border-radius: ${defaultBorderRadius}; + padding: 1px; + + font-size: ${getFontSize() - 4}px; + + display: flex; + flex-direction: row; + align-items: center; + gap: 4px; + + transition: background-color 200ms; +`; + +interface ToggleToolsButtonProps {} + +function ToggleToolsButton(props: ToggleToolsButtonProps) { + const dispatch = useDispatch(); + + const useTools = useSelector((store: RootState) => store.uiState.useTools); + return ( + dispatch(toggleUseTools())}> + + + {useTools && ( + <> + Tools + + + )} + + Tools + + + + ); +} + +export default ToggleToolsButton; From 9fbd4cc045de04694ef770921e338e3dd9e74db3 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Nov 2024 18:23:12 -0800 Subject: [PATCH 045/105] only allow tool use for claude 3.5 models --- .../InputToolbar/ToggleToolsButton.tsx | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index d1c093754..d94f58257 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -4,11 +4,8 @@ import { } from "@heroicons/react/24/outline"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; -import { - defaultBorderRadius, - vscForeground, - vscListActiveBackground, -} from "../.."; +import { defaultBorderRadius, lightGray, vscForeground } from "../.."; +import { defaultModelSelector } from "../../../redux/selectors/modelSelectors"; import { toggleUseTools } from "../../../redux/slices/uiStateSlice"; import { RootState } from "../../../redux/store"; import { getFontSize } from "../../../util"; @@ -17,7 +14,7 @@ import HoverItem from "./HoverItem"; const BackgroundDiv = styled.div<{ useTools: boolean }>` background-color: ${(props) => - props.useTools ? vscListActiveBackground : "transparent"}; + props.useTools ? `${lightGray}33` : "transparent"}; border-radius: ${defaultBorderRadius}; padding: 1px; @@ -37,6 +34,19 @@ function ToggleToolsButton(props: ToggleToolsButtonProps) { const dispatch = useDispatch(); const useTools = useSelector((store: RootState) => store.uiState.useTools); + const defaultModel = useSelector(defaultModelSelector); + + function toolUseAllowed() { + return ( + defaultModel.model.includes("claude") && + (defaultModel.model.includes("3-5") || defaultModel.model.includes("3.5")) + ); + } + + if (!toolUseAllowed()) { + return null; + } + return ( dispatch(toggleUseTools())}> From ee47711bdd55b146ec4be38b7c95e03f60098a88 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Nov 2024 20:51:42 -0800 Subject: [PATCH 046/105] system message for tools --- core/llm/autodetect.ts | 12 +++++++-- core/llm/constructMessages.ts | 25 +++++++++++++------ .../InputToolbar/ToggleToolsButton.tsx | 10 ++------ 3 files changed, 29 insertions(+), 18 deletions(-) diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 8e475d01e..09929de33 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -84,6 +84,13 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ "llama3.2", ]; +function modelSupportsTools(modelName: string) { + return ( + modelName.includes("claude") && + (modelName.includes("3-5") || modelName.includes("3.5")) + ); +} + function modelSupportsImages( provider: ModelProvider, model: string, @@ -150,10 +157,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined { lower.includes("chat-bison") || lower.includes("pplx") || lower.includes("gemini") || - lower.includes("grok")|| + lower.includes("grok") || lower.includes("moonshot") ) { - return undefined; + return undefined; } if (lower.includes("llama3")) { @@ -354,4 +361,5 @@ export { autodetectTemplateType, llmCanGenerateInParallel, modelSupportsImages, + modelSupportsTools, }; diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 823fd97f2..3af1b1a4f 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,5 +1,6 @@ import { ChatHistory, ChatMessage, MessagePart } from "../index.js"; import { normalizeToMessageParts } from "../util/messageContent.js"; +import { modelSupportsTools } from "./autodetect.js"; const SYSTEM_MESSAGE = `When generating new code: @@ -57,25 +58,33 @@ function helloWorld() { } \`\`\` -Always follow these guidelines when generating code responses. +Always follow these guidelines when generating code responses.`; -Other rules: +const TOOL_USE_RULES = `When using tools, follow the following guidelines: - Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.`; +function constructSystemPrompt(model: string): string | null { + if (model.includes("sonnet")) { + return SYSTEM_MESSAGE + "\n\n" + TOOL_USE_RULES; + } + if (modelSupportsTools(model)) { + return TOOL_USE_RULES; + } + + return null; +} + export function constructMessages( history: ChatHistory, model: string, ): ChatMessage[] { const msgs: ChatMessage[] = []; - // Only using this system message with Sonnet right now - if ( - // hasCodeBlockWithFilename(history[0].message.content) && - model.includes("sonnet") - ) { + const systemMessage = constructSystemPrompt(model); + if (systemMessage) { msgs.push({ role: "system" as const, - content: SYSTEM_MESSAGE, + content: systemMessage, }); } diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index d94f58257..0f9d32440 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -2,6 +2,7 @@ import { ChevronDownIcon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; +import { modelSupportsTools } from "core/llm/autodetect"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, vscForeground } from "../.."; @@ -36,14 +37,7 @@ function ToggleToolsButton(props: ToggleToolsButtonProps) { const useTools = useSelector((store: RootState) => store.uiState.useTools); const defaultModel = useSelector(defaultModelSelector); - function toolUseAllowed() { - return ( - defaultModel.model.includes("claude") && - (defaultModel.model.includes("3-5") || defaultModel.model.includes("3.5")) - ); - } - - if (!toolUseAllowed()) { + if (!modelSupportsTools(defaultModel.model)) { return null; } From 9dc8ff675bd42eaa37fd1ad78080a7f0f9e60038 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Nov 2024 21:01:17 -0800 Subject: [PATCH 047/105] remove tooltip --- .../components/mainInput/InputToolbar/ToggleToolsButton.tsx | 4 ---- 1 file changed, 4 deletions(-) diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index 0f9d32440..4d3c13fee 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -10,7 +10,6 @@ import { defaultModelSelector } from "../../../redux/selectors/modelSelectors"; import { toggleUseTools } from "../../../redux/slices/uiStateSlice"; import { RootState } from "../../../redux/store"; import { getFontSize } from "../../../util"; -import { ToolTip } from "../../gui/Tooltip"; import HoverItem from "./HoverItem"; const BackgroundDiv = styled.div<{ useTools: boolean }>` @@ -62,9 +61,6 @@ function ToggleToolsButton(props: ToggleToolsButtonProps) { /> )} - - Tools - ); From 3757a03226e171ac37d619292d182a9a1490edc2 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Nov 2024 21:25:45 -0800 Subject: [PATCH 048/105] basic listbox for tools toggle --- .../InputToolbar/ToggleToolsButton.tsx | 36 +++++++++++++------ 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index 4d3c13fee..03f2b8b15 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -1,8 +1,10 @@ +import { Listbox } from "@headlessui/react"; import { ChevronDownIcon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { modelSupportsTools } from "core/llm/autodetect"; +import { useRef } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, vscForeground } from "../.."; @@ -28,9 +30,8 @@ const BackgroundDiv = styled.div<{ useTools: boolean }>` transition: background-color 200ms; `; -interface ToggleToolsButtonProps {} - -function ToggleToolsButton(props: ToggleToolsButtonProps) { +export default function ToolDropdown() { + const buttonRef = useRef(null); const dispatch = useDispatch(); const useTools = useSelector((store: RootState) => store.uiState.useTools); @@ -44,7 +45,6 @@ function ToggleToolsButton(props: ToggleToolsButtonProps) { dispatch(toggleUseTools())}> Tools - + +
+ {}}> + { + e.stopPropagation(); + }} + className="text-lightgray flex cursor-pointer items-center border-none bg-transparent outline-none" + > + + + + + Add all open files + + + +
)}
); } - -export default ToggleToolsButton; From 025dc0840d9d35f502962f4bd2348c0438aaca43 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Nov 2024 22:08:58 -0800 Subject: [PATCH 049/105] fix type errors --- core/core.ts | 5 +- core/index.d.ts | 1 - core/llm/llms/OpenAI.ts | 18 ++++-- core/tools/builtIn.ts | 9 +++ core/tools/callTool.ts | 62 +++++++++++++++++++ core/tools/createNewFile.ts | 37 ----------- core/tools/definitions/createNewFile.ts | 24 +++++++ core/tools/{ => definitions}/exactSearch.ts | 15 +---- core/tools/definitions/runTerminalCommand.ts | 22 +++++++ core/tools/{ => definitions}/searchWeb.ts | 11 ++-- core/tools/definitions/viewDiff.ts | 15 +++++ core/tools/definitions/viewRepoMap.ts | 15 +++++ core/tools/definitions/viewSubdirectory.ts | 21 +++++++ core/tools/implementations/createNewFile.ts | 17 +++++ core/tools/implementations/exactSearch.ts | 12 ++++ core/tools/implementations/index.ts | 6 ++ .../implementations/runTerminalCommand.ts | 31 ++++++++++ core/tools/implementations/searchWeb.ts | 8 +++ core/tools/implementations/viewDiff.ts | 12 ++++ core/tools/implementations/viewRepoMap.ts | 14 +++++ .../tools/implementations/viewSubdirectory.ts | 17 +++++ core/tools/index.ts | 14 ++--- core/tools/runTerminalCommand.ts | 49 --------------- core/tools/viewDiff.ts | 23 ------- core/tools/viewRepoMap.ts | 24 ------- core/tools/viewSubdirectory.ts | 33 ---------- .../InputToolbar/ToggleToolsButton.tsx | 15 +++-- 27 files changed, 326 insertions(+), 204 deletions(-) create mode 100644 core/tools/builtIn.ts create mode 100644 core/tools/callTool.ts delete mode 100644 core/tools/createNewFile.ts create mode 100644 core/tools/definitions/createNewFile.ts rename core/tools/{ => definitions}/exactSearch.ts (55%) create mode 100644 core/tools/definitions/runTerminalCommand.ts rename core/tools/{ => definitions}/searchWeb.ts (65%) create mode 100644 core/tools/definitions/viewDiff.ts create mode 100644 core/tools/definitions/viewRepoMap.ts create mode 100644 core/tools/definitions/viewSubdirectory.ts create mode 100644 core/tools/implementations/createNewFile.ts create mode 100644 core/tools/implementations/exactSearch.ts create mode 100644 core/tools/implementations/index.ts create mode 100644 core/tools/implementations/runTerminalCommand.ts create mode 100644 core/tools/implementations/searchWeb.ts create mode 100644 core/tools/implementations/viewDiff.ts create mode 100644 core/tools/implementations/viewRepoMap.ts create mode 100644 core/tools/implementations/viewSubdirectory.ts delete mode 100644 core/tools/runTerminalCommand.ts delete mode 100644 core/tools/viewDiff.ts delete mode 100644 core/tools/viewRepoMap.ts delete mode 100644 core/tools/viewSubdirectory.ts diff --git a/core/core.ts b/core/core.ts index edb064afb..9e1738740 100644 --- a/core/core.ts +++ b/core/core.ts @@ -36,6 +36,7 @@ import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { allTools } from "./tools"; +import { callTool } from "./tools/callTool"; import type { IMessenger, Message } from "./util/messenger"; export class Core { @@ -795,7 +796,8 @@ export class Core { const config = await this.configHandler.loadConfig(); const llm = await this.getSelectedModel(); - const contextItems = await tool.action( + const contextItems = await callTool( + tool.function.name, JSON.parse(toolCall.function.arguments || "{}"), { ide: this.ide, @@ -804,6 +806,7 @@ export class Core { fetchwithRequestOptions(url, init, config.requestOptions), }, ); + return { contextItems }; }); } diff --git a/core/index.d.ts b/core/index.d.ts index 8905e5646..1dfcbb1fd 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -914,7 +914,6 @@ export interface Tool { parameters?: Record; strict?: boolean | null; }; - action: (parameters: any, extras: ToolExtras) => Promise; } interface BaseCompletionOptions { diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 10683c8a8..f99eff0e1 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -3,6 +3,7 @@ import { CompletionOptions, LLMOptions, ModelProvider, + Tool, } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; @@ -107,12 +108,21 @@ class OpenAI extends BaseLLM { return ["gpt-4o-mini", "gpt-4o"].includes(model); } + private convertTool(tool: Tool): any { + return { + type: tool.type, + function: { + name: tool.function.name, + description: tool.function.description, + parameters: tool.function.parameters, + strict: tool.function.strict, + }, + }; + } + protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) { const url = new URL(this.apiBase!); - const tools = options.tools?.map((tool) => { - const { action, ...restOfTool } = tool; - return restOfTool; - }); + const tools = options.tools?.map(this.convertTool); const finalOptions: any = { messages: messages.map(this._convertMessage), diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts new file mode 100644 index 000000000..421319c14 --- /dev/null +++ b/core/tools/builtIn.ts @@ -0,0 +1,9 @@ +export enum BuiltInToolNames { + CreateNewFile = "create_new_file", + RunTerminalCommand = "run_terminal_command", + ViewSubdirectory = "view_subdirectory", + ViewRepoMap = "view_repo_map", + ExactSearch = "exact_search", + SearchWeb = "search_web", + ViewDiff = "view_diff", +} diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts new file mode 100644 index 000000000..dbe4a8a9f --- /dev/null +++ b/core/tools/callTool.ts @@ -0,0 +1,62 @@ +import { ContextItem, ToolExtras } from ".."; +import { BuiltInToolNames } from "./builtIn"; +import { createNewFileImpl } from "./implementations/createNewFile"; +import { exactSearchImpl } from "./implementations/exactSearch"; +import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; +import { searchWebImpl } from "./implementations/searchWeb"; +import { viewDiffImpl } from "./implementations/viewDiff"; +import { viewRepoMapImpl } from "./implementations/viewRepoMap"; +import { viewSubdirectoryImpl } from "./implementations/viewSubdirectory"; + +async function callToolFromUri( + uri: string, + args: any, + extras: ToolExtras, +): Promise { + const canParse = URL.canParse(uri); + if (!canParse) { + throw new Error(`Invalid URI: ${uri}`); + } + + const response = await extras.fetch(uri, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + arguments: args, + }), + }); + + if (!response.ok) { + throw new Error(`Failed to call tool: ${uri}`); + } + + const data = await response.json(); + return data.output; +} + +export async function callTool( + uri: string, + args: any, + extras: ToolExtras, +): Promise { + switch (uri) { + case BuiltInToolNames.CreateNewFile: + return await createNewFileImpl(args, extras); + case BuiltInToolNames.ExactSearch: + return await exactSearchImpl(args, extras); + case BuiltInToolNames.RunTerminalCommand: + return await runTerminalCommandImpl(args, extras); + case BuiltInToolNames.SearchWeb: + return await searchWebImpl(args, extras); + case BuiltInToolNames.ViewDiff: + return await viewDiffImpl(args, extras); + case BuiltInToolNames.ViewRepoMap: + return await viewRepoMapImpl(args, extras); + case BuiltInToolNames.ViewSubdirectory: + return await viewSubdirectoryImpl(args, extras); + default: + return await callToolFromUri(uri, args, extras); + } +} diff --git a/core/tools/createNewFile.ts b/core/tools/createNewFile.ts deleted file mode 100644 index 50a067f5e..000000000 --- a/core/tools/createNewFile.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { Tool } from ".."; -import { getPathModuleForIde } from "../util/pathModule"; - -export const createNewFileTool: Tool = { - type: "function", - action: async (args, extras) => { - const pathSep = await extras.ide.pathSep(); - let filepath = args.filepath; - if (!args.filepath.startsWith(pathSep)) { - const pathModule = await getPathModuleForIde(extras.ide); - const workspaceDirs = await extras.ide.getWorkspaceDirs(); - const cwd = workspaceDirs[0]; - filepath = pathModule.join(cwd, filepath); - } - await extras.ide.writeFile(filepath, args.contents); - await extras.ide.openFile(filepath); - return []; - }, - function: { - name: "create_new_file", - description: "Create a new file", - parameters: { - type: "object", - required: ["filepath", "contents"], - properties: { - filepath: { - type: "string", - description: "The path where the new file should be created", - }, - contents: { - type: "string", - description: "The contents to write to the new file", - }, - }, - }, - }, -}; diff --git a/core/tools/definitions/createNewFile.ts b/core/tools/definitions/createNewFile.ts new file mode 100644 index 000000000..2a113865f --- /dev/null +++ b/core/tools/definitions/createNewFile.ts @@ -0,0 +1,24 @@ +import { Tool } from "../.."; +import { BuiltInToolNames } from "../builtIn"; + +export const createNewFileTool: Tool = { + type: "function", + function: { + name: BuiltInToolNames.CreateNewFile, + description: "Create a new file", + parameters: { + type: "object", + required: ["filepath", "contents"], + properties: { + filepath: { + type: "string", + description: "The path where the new file should be created", + }, + contents: { + type: "string", + description: "The contents to write to the new file", + }, + }, + }, + }, +}; diff --git a/core/tools/exactSearch.ts b/core/tools/definitions/exactSearch.ts similarity index 55% rename from core/tools/exactSearch.ts rename to core/tools/definitions/exactSearch.ts index 81bd061a4..14986eb90 100644 --- a/core/tools/exactSearch.ts +++ b/core/tools/definitions/exactSearch.ts @@ -1,19 +1,10 @@ -import { Tool } from ".."; +import { Tool } from "../.."; +import { BuiltInToolNames } from "../builtIn"; export const exactSearchTool: Tool = { type: "function", - action: async (args, extras) => { - const content = await extras.ide.getSearchResults(args.query); - return [ - { - name: "Search results", - description: "Results from exact search", - content, - }, - ]; - }, function: { - name: "exact_search", + name: BuiltInToolNames.ExactSearch, description: "Perform an exact search over the repository using ripgrep", parameters: { type: "object", diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts new file mode 100644 index 000000000..4af56955a --- /dev/null +++ b/core/tools/definitions/runTerminalCommand.ts @@ -0,0 +1,22 @@ +import { Tool } from "../.."; + +import { BuiltInToolNames } from "../builtIn"; + +export const runTerminalCommandTool: Tool = { + type: "function", + function: { + name: BuiltInToolNames.RunTerminalCommand, + description: "Run a terminal command in the current directory", + parameters: { + type: "object", + required: ["command"], + properties: { + command: { + type: "string", + description: + "The command to run. This will be passed directly into the shell.", + }, + }, + }, + }, +}; diff --git a/core/tools/searchWeb.ts b/core/tools/definitions/searchWeb.ts similarity index 65% rename from core/tools/searchWeb.ts rename to core/tools/definitions/searchWeb.ts index 3f5ded0b7..12aeaefa9 100644 --- a/core/tools/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -1,14 +1,11 @@ -import { Tool } from ".."; -import { fetchSearchResults } from "../context/providers/WebContextProvider"; +import { Tool } from "../.."; + +import { BuiltInToolNames } from "../builtIn"; export const searchWebTool: Tool = { type: "function", - action: async (args, extras) => { - const webResults = await fetchSearchResults(args.query, 5, extras.fetch); - return webResults; - }, function: { - name: "search_web", + name: BuiltInToolNames.SearchWeb, description: "Performs a web search, returning top results. This tool should only be called for questions that require external knowledge. Common programming questions do not require web search.", parameters: { diff --git a/core/tools/definitions/viewDiff.ts b/core/tools/definitions/viewDiff.ts new file mode 100644 index 000000000..4e88bcb9e --- /dev/null +++ b/core/tools/definitions/viewDiff.ts @@ -0,0 +1,15 @@ +import { Tool } from "../.."; + +import { BuiltInToolNames } from "../builtIn"; + +export const viewDiffTool: Tool = { + type: "function", + function: { + name: BuiltInToolNames.ViewDiff, + description: "View the current diff of working changes", + parameters: { + type: "object", + properties: {}, + }, + }, +}; diff --git a/core/tools/definitions/viewRepoMap.ts b/core/tools/definitions/viewRepoMap.ts new file mode 100644 index 000000000..bb009486a --- /dev/null +++ b/core/tools/definitions/viewRepoMap.ts @@ -0,0 +1,15 @@ +import { Tool } from "../.."; + +import { BuiltInToolNames } from "../builtIn"; + +export const viewRepoMapTool: Tool = { + type: "function", + function: { + name: BuiltInToolNames.ViewRepoMap, + description: "View the repository map", + parameters: { + type: "object", + properties: {}, + }, + }, +}; diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts new file mode 100644 index 000000000..40bce4850 --- /dev/null +++ b/core/tools/definitions/viewSubdirectory.ts @@ -0,0 +1,21 @@ +import { Tool } from "../.."; + +import { BuiltInToolNames } from "../builtIn"; + +export const viewSubdirectoryTool: Tool = { + type: "function", + function: { + name: BuiltInToolNames.ViewSubdirectory, + description: "View the contents of a subdirectory", + parameters: { + type: "object", + required: ["directory_path"], + properties: { + directory_path: { + type: "string", + description: "The path of the subdirectory to view", + }, + }, + }, + }, +}; diff --git a/core/tools/implementations/createNewFile.ts b/core/tools/implementations/createNewFile.ts new file mode 100644 index 000000000..0be187b19 --- /dev/null +++ b/core/tools/implementations/createNewFile.ts @@ -0,0 +1,17 @@ +import { getPathModuleForIde } from "../../util/pathModule"; + +import { ToolImpl } from "."; + +export const createNewFileImpl: ToolImpl = async (args, extras) => { + const pathSep = await extras.ide.pathSep(); + let filepath = args.filepath; + if (!args.filepath.startsWith(pathSep)) { + const pathModule = await getPathModuleForIde(extras.ide); + const workspaceDirs = await extras.ide.getWorkspaceDirs(); + const cwd = workspaceDirs[0]; + filepath = pathModule.join(cwd, filepath); + } + await extras.ide.writeFile(filepath, args.contents); + await extras.ide.openFile(filepath); + return []; +}; diff --git a/core/tools/implementations/exactSearch.ts b/core/tools/implementations/exactSearch.ts new file mode 100644 index 000000000..ae8f6fd02 --- /dev/null +++ b/core/tools/implementations/exactSearch.ts @@ -0,0 +1,12 @@ +import { ToolImpl } from "."; + +export const exactSearchImpl: ToolImpl = async (args, extras) => { + const content = await extras.ide.getSearchResults(args.query); + return [ + { + name: "Search results", + description: "Results from exact search", + content, + }, + ]; +}; diff --git a/core/tools/implementations/index.ts b/core/tools/implementations/index.ts new file mode 100644 index 000000000..c0ef15be9 --- /dev/null +++ b/core/tools/implementations/index.ts @@ -0,0 +1,6 @@ +import { ContextItem, ToolExtras } from "../.."; + +export type ToolImpl = ( + parameters: any, + extras: ToolExtras, +) => Promise; diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts new file mode 100644 index 000000000..fb4770cee --- /dev/null +++ b/core/tools/implementations/runTerminalCommand.ts @@ -0,0 +1,31 @@ +import { ToolImpl } from "."; + +const util = require("node:util"); +const asyncExec = util.promisify(require("node:child_process").exec); + +export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { + const ideInfo = await extras.ide.getIdeInfo(); + if (ideInfo.remoteName === "local" || ideInfo.remoteName === "") { + // If we're local, can just run the terminal command with child_process + const output = await asyncExec(args.command, { + cwd: (await extras.ide.getWorkspaceDirs())[0], + }); + return [ + { + name: "Terminal", + description: "Terminal command output", + content: output.stdout ?? "", + }, + ]; + } + + await extras.ide.runCommand(args.command); + return [ + { + name: "Terminal", + description: "Terminal command output", + content: + "[Terminal output not available. This is only available in local development environments and not in SSH environments for example.]", + }, + ]; +}; diff --git a/core/tools/implementations/searchWeb.ts b/core/tools/implementations/searchWeb.ts new file mode 100644 index 000000000..a01212659 --- /dev/null +++ b/core/tools/implementations/searchWeb.ts @@ -0,0 +1,8 @@ +import { fetchSearchResults } from "../../context/providers/WebContextProvider"; + +import { ToolImpl } from "."; + +export const searchWebImpl: ToolImpl = async (args, extras) => { + const webResults = await fetchSearchResults(args.query, 5, extras.fetch); + return webResults; +}; diff --git a/core/tools/implementations/viewDiff.ts b/core/tools/implementations/viewDiff.ts new file mode 100644 index 000000000..f7c05849f --- /dev/null +++ b/core/tools/implementations/viewDiff.ts @@ -0,0 +1,12 @@ +import { ToolImpl } from "."; + +export const viewDiffImpl: ToolImpl = async (args, extras) => { + const diff = await extras.ide.getDiff(true); + return [ + { + name: "Diff", + description: "The current git diff", + content: diff, + }, + ]; +}; diff --git a/core/tools/implementations/viewRepoMap.ts b/core/tools/implementations/viewRepoMap.ts new file mode 100644 index 000000000..56c265416 --- /dev/null +++ b/core/tools/implementations/viewRepoMap.ts @@ -0,0 +1,14 @@ +import generateRepoMap from "../../util/generateRepoMap"; + +import { ToolImpl } from "."; + +export const viewRepoMapImpl: ToolImpl = async (args, extras) => { + const repoMap = await generateRepoMap(extras.llm, extras.ide, {}); + return [ + { + name: "Repo map", + description: "Overview of the repository structure", + content: repoMap, + }, + ]; +}; diff --git a/core/tools/implementations/viewSubdirectory.ts b/core/tools/implementations/viewSubdirectory.ts new file mode 100644 index 000000000..8ac126a58 --- /dev/null +++ b/core/tools/implementations/viewSubdirectory.ts @@ -0,0 +1,17 @@ +import generateRepoMap from "../../util/generateRepoMap"; + +import { ToolImpl } from "."; + +export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => { + const { directory_path } = args; + const repoMap = await generateRepoMap(extras.llm, extras.ide, { + dirs: [directory_path], + }); + return [ + { + name: "Repo map", + description: `Map of ${directory_path}`, + content: repoMap, + }, + ]; +}; diff --git a/core/tools/index.ts b/core/tools/index.ts index 12667259b..7f8eb32fb 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,10 +1,10 @@ -import { createNewFileTool } from "./createNewFile"; -import { exactSearchTool } from "./exactSearch"; -import { runTerminalCommandTool } from "./runTerminalCommand"; -import { searchWebTool } from "./searchWeb"; -import { viewDiffTool } from "./viewDiff"; -import { viewRepoMapTool } from "./viewRepoMap"; -import { viewSubdirectoryTool } from "./viewSubdirectory"; +import { createNewFileTool } from "./definitions/createNewFile"; +import { exactSearchTool } from "./definitions/exactSearch"; +import { runTerminalCommandTool } from "./definitions/runTerminalCommand"; +import { searchWebTool } from "./definitions/searchWeb"; +import { viewDiffTool } from "./definitions/viewDiff"; +import { viewRepoMapTool } from "./definitions/viewRepoMap"; +import { viewSubdirectoryTool } from "./definitions/viewSubdirectory"; export const allTools = [ createNewFileTool, diff --git a/core/tools/runTerminalCommand.ts b/core/tools/runTerminalCommand.ts deleted file mode 100644 index dc7cd4bd7..000000000 --- a/core/tools/runTerminalCommand.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Tool } from ".."; - -const util = require("node:util"); -const asyncExec = util.promisify(require("node:child_process").exec); - -export const runTerminalCommandTool: Tool = { - type: "function", - action: async (args, extras) => { - const ideInfo = await extras.ide.getIdeInfo(); - if (ideInfo.remoteName === "local" || ideInfo.remoteName === "") { - // If we're local, can just run the terminal command with child_process - const output = await asyncExec(args.command, { - cwd: (await extras.ide.getWorkspaceDirs())[0], - }); - return [ - { - name: "Terminal", - description: "Terminal command output", - content: output.stdout ?? "", - }, - ]; - } - - await extras.ide.runCommand(args.command); - return [ - { - name: "Terminal", - description: "Terminal command output", - content: - "[Terminal output not available. This is only available in local development environments and not in SSH environments for example.]", - }, - ]; - }, - function: { - name: "run_terminal_command", - description: "Run a terminal command in the current directory", - parameters: { - type: "object", - required: ["command"], - properties: { - command: { - type: "string", - description: - "The command to run. This will be passed directly into the shell.", - }, - }, - }, - }, -}; diff --git a/core/tools/viewDiff.ts b/core/tools/viewDiff.ts deleted file mode 100644 index 6bb327e2c..000000000 --- a/core/tools/viewDiff.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { Tool } from ".."; - -export const viewDiffTool: Tool = { - type: "function", - action: async (args, extras) => { - const diff = await extras.ide.getDiff(true); - return [ - { - name: "Diff", - description: "The current git diff", - content: diff, - }, - ]; - }, - function: { - name: "view_diff", - description: "View the current diff of working changes", - parameters: { - type: "object", - properties: {}, - }, - }, -}; diff --git a/core/tools/viewRepoMap.ts b/core/tools/viewRepoMap.ts deleted file mode 100644 index 9466c6be6..000000000 --- a/core/tools/viewRepoMap.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { Tool } from ".."; -import generateRepoMap from "../util/generateRepoMap"; - -export const viewRepoMapTool: Tool = { - type: "function", - action: async (args, extras) => { - const repoMap = await generateRepoMap(extras.llm, extras.ide, {}); - return [ - { - name: "Repo map", - description: "Overview of the repository structure", - content: repoMap, - }, - ]; - }, - function: { - name: "view_repo_map", - description: "View the repository map", - parameters: { - type: "object", - properties: {}, - }, - }, -}; diff --git a/core/tools/viewSubdirectory.ts b/core/tools/viewSubdirectory.ts deleted file mode 100644 index 583266c52..000000000 --- a/core/tools/viewSubdirectory.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { Tool } from ".."; -import generateRepoMap from "../util/generateRepoMap"; - -export const viewSubdirectoryTool: Tool = { - type: "function", - action: async (args: any, extras) => { - const { directory_path } = args; - const repoMap = await generateRepoMap(extras.llm, extras.ide, { - dirs: [directory_path], - }); - return [ - { - name: "Repo map", - description: `Map of ${directory_path}`, - content: repoMap, - }, - ]; - }, - function: { - name: "view_subdirectory", - description: "View the contents of a subdirectory", - parameters: { - type: "object", - required: ["directory_path"], - properties: { - directory_path: { - type: "string", - description: "The path of the subdirectory to view", - }, - }, - }, - }, -}; diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index 03f2b8b15..d91642216 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -4,6 +4,7 @@ import { WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { modelSupportsTools } from "core/llm/autodetect"; +import { allTools } from "core/tools/index"; import { useRef } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; @@ -68,12 +69,14 @@ export default function ToolDropdown() { - - Add all open files - + {allTools.map((tool) => ( + + {tool.function.name} + + ))}
From e6d7f5b511a41fe887a229481c9f914b56ef3aea Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Nov 2024 23:00:14 -0800 Subject: [PATCH 050/105] tool settings ui --- core/index.d.ts | 3 ++ core/tools/definitions/createNewFile.ts | 2 + core/tools/definitions/exactSearch.ts | 2 + core/tools/definitions/runTerminalCommand.ts | 2 + core/tools/definitions/searchWeb.ts | 2 + core/tools/definitions/viewDiff.ts | 2 + core/tools/definitions/viewRepoMap.ts | 2 + core/tools/definitions/viewSubdirectory.ts | 2 + .../InputToolbar/ToggleToolsButton.tsx | 17 +++++-- .../InputToolbar/ToolDropdownItem.tsx | 46 +++++++++++++++++++ .../ToolCallDiv/FunctionSpecificHeader.tsx | 42 ----------------- gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx | 9 +++- gui/src/redux/slices/uiStateSlice.ts | 31 +++++++++++++ 13 files changed, 114 insertions(+), 48 deletions(-) create mode 100644 gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx delete mode 100644 gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx diff --git a/core/index.d.ts b/core/index.d.ts index 1dfcbb1fd..26421368c 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -914,6 +914,9 @@ export interface Tool { parameters?: Record; strict?: boolean | null; }; + + displayTitle: string; + wouldLikeTo: string; } interface BaseCompletionOptions { diff --git a/core/tools/definitions/createNewFile.ts b/core/tools/definitions/createNewFile.ts index 2a113865f..1123de217 100644 --- a/core/tools/definitions/createNewFile.ts +++ b/core/tools/definitions/createNewFile.ts @@ -3,6 +3,8 @@ import { BuiltInToolNames } from "../builtIn"; export const createNewFileTool: Tool = { type: "function", + displayTitle: "Create New File", + wouldLikeTo: "create a new file", function: { name: BuiltInToolNames.CreateNewFile, description: "Create a new file", diff --git a/core/tools/definitions/exactSearch.ts b/core/tools/definitions/exactSearch.ts index 14986eb90..5e55c8667 100644 --- a/core/tools/definitions/exactSearch.ts +++ b/core/tools/definitions/exactSearch.ts @@ -3,6 +3,8 @@ import { BuiltInToolNames } from "../builtIn"; export const exactSearchTool: Tool = { type: "function", + displayTitle: "Exact Search", + wouldLikeTo: "search for a specific term within the repository", function: { name: BuiltInToolNames.ExactSearch, description: "Perform an exact search over the repository using ripgrep", diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index 4af56955a..b3c40ca32 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -4,6 +4,8 @@ import { BuiltInToolNames } from "../builtIn"; export const runTerminalCommandTool: Tool = { type: "function", + displayTitle: "Run Terminal Command", + wouldLikeTo: "run a terminal command", function: { name: BuiltInToolNames.RunTerminalCommand, description: "Run a terminal command in the current directory", diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index 12aeaefa9..c8ead3c28 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -4,6 +4,8 @@ import { BuiltInToolNames } from "../builtIn"; export const searchWebTool: Tool = { type: "function", + displayTitle: "Search Web", + wouldLikeTo: "search the web", function: { name: BuiltInToolNames.SearchWeb, description: diff --git a/core/tools/definitions/viewDiff.ts b/core/tools/definitions/viewDiff.ts index 4e88bcb9e..554f49878 100644 --- a/core/tools/definitions/viewDiff.ts +++ b/core/tools/definitions/viewDiff.ts @@ -4,6 +4,8 @@ import { BuiltInToolNames } from "../builtIn"; export const viewDiffTool: Tool = { type: "function", + displayTitle: "View Diff", + wouldLikeTo: "view a diff", function: { name: BuiltInToolNames.ViewDiff, description: "View the current diff of working changes", diff --git a/core/tools/definitions/viewRepoMap.ts b/core/tools/definitions/viewRepoMap.ts index bb009486a..aca91a78b 100644 --- a/core/tools/definitions/viewRepoMap.ts +++ b/core/tools/definitions/viewRepoMap.ts @@ -4,6 +4,8 @@ import { BuiltInToolNames } from "../builtIn"; export const viewRepoMapTool: Tool = { type: "function", + displayTitle: "View Repo Map", + wouldLikeTo: "view the repository map", function: { name: BuiltInToolNames.ViewRepoMap, description: "View the repository map", diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts index 40bce4850..4ac1b5c40 100644 --- a/core/tools/definitions/viewSubdirectory.ts +++ b/core/tools/definitions/viewSubdirectory.ts @@ -4,6 +4,8 @@ import { BuiltInToolNames } from "../builtIn"; export const viewSubdirectoryTool: Tool = { type: "function", + displayTitle: "View Subdirectory", + wouldLikeTo: "view the contents of a subdirectory", function: { name: BuiltInToolNames.ViewSubdirectory, description: "View the contents of a subdirectory", diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index d91642216..6433959b8 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -1,11 +1,12 @@ import { Listbox } from "@headlessui/react"; import { ChevronDownIcon, + ChevronUpIcon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { modelSupportsTools } from "core/llm/autodetect"; import { allTools } from "core/tools/index"; -import { useRef } from "react"; +import { useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, vscForeground } from "../.."; @@ -14,6 +15,7 @@ import { toggleUseTools } from "../../../redux/slices/uiStateSlice"; import { RootState } from "../../../redux/store"; import { getFontSize } from "../../../util"; import HoverItem from "./HoverItem"; +import ToolDropdownItem from "./ToolDropdownItem"; const BackgroundDiv = styled.div<{ useTools: boolean }>` background-color: ${(props) => @@ -34,6 +36,7 @@ const BackgroundDiv = styled.div<{ useTools: boolean }>` export default function ToolDropdown() { const buttonRef = useRef(null); const dispatch = useDispatch(); + const [isDropdownOpen, setDropdownOpen] = useState(false); const useTools = useSelector((store: RootState) => store.uiState.useTools); const defaultModel = useSelector(defaultModelSelector); @@ -63,18 +66,24 @@ export default function ToolDropdown() { ref={buttonRef} onClick={(e) => { e.stopPropagation(); + setDropdownOpen((prev) => !prev); }} className="text-lightgray flex cursor-pointer items-center border-none bg-transparent outline-none" > - + {isDropdownOpen ? ( + + ) : ( + + )} {allTools.map((tool) => ( - {tool.function.name} + ))} diff --git a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx new file mode 100644 index 000000000..e137c18dc --- /dev/null +++ b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx @@ -0,0 +1,46 @@ +import { Tool } from "core"; +import { useDispatch, useSelector } from "react-redux"; +import { + DEFAULT_TOOL_SETTING, + toggleToolSetting, +} from "../../../redux/slices/uiStateSlice"; +import { RootState } from "../../../redux/store"; + +interface ToolDropdownItemProps { + tool: Tool; +} + +function ToolDropdownItem(props: ToolDropdownItemProps) { + const dispatch = useDispatch(); + const settings = useSelector( + (state: RootState) => + state.uiState.toolSettings[props.tool.function.name] ?? + DEFAULT_TOOL_SETTING, + ); + + return ( +
{ + dispatch(toggleToolSetting(props.tool.function.name)); + e.stopPropagation(); + e.preventDefault(); + }} + > + {props.tool.displayTitle} +
+ {(settings === "allowedWithPermission" || settings === undefined) && ( + Allowed + )} + {settings === "allowedWithoutPermission" && ( + Automatic + )} + {settings === "disabled" && ( + Disabled + )} +
+
+ ); +} + +export default ToolDropdownItem; diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx deleted file mode 100644 index 896e9f81a..000000000 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { ToolCall } from "core"; -import { incrementalParseJson } from "core/util/incrementalParseJson"; - -interface FunctionSpecificHeaderProps { - toolCall: ToolCall; -} - -export function FunctionSpecificHeader(props: FunctionSpecificHeaderProps) { - const [done, incrementalJson] = incrementalParseJson( - props.toolCall.function.arguments, - ); - - let message; - - switch (props.toolCall.function.name) { - case "create_new_file": - message = "Continue wants to write to a file"; - break; - case "run_terminal_command": - message = "Continue wants to run a terminal command."; - break; - case "exact_search": - message = "Continue wants to search your codebase"; - break; - case "search_web": - message = "Continue wants to search the internet"; - break; - case "view_diff": - message = "Continue wants to view the current git diff"; - break; - case "view_repo_map": - message = "Continue wants to view a map of your repository"; - break; - case "view_subdirectory": - message = `Continue wants to view the contents of ${incrementalJson.directory_path ?? "a subdirectory"}`; - break; - default: - message = `Continue wants to use the ${props.toolCall.function.name} function.`; - } - - return
{message}
; -} diff --git a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx index de20f6437..12f28eea8 100644 --- a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx @@ -1,6 +1,6 @@ import { ToolCall } from "core"; +import { allTools } from "core/tools"; import styled from "styled-components"; -import { FunctionSpecificHeader } from "./FunctionSpecificHeader"; interface ThreadDivProps { children: React.ReactNode; @@ -42,7 +42,12 @@ export function ThreadDiv(props: ThreadDivProps) { > {props.icon}
- + Continue wants to{" "} + { + allTools.find( + (tool) => props.toolCall.function.name === tool.function.name, + )?.wouldLikeTo + } {props.children} diff --git a/gui/src/redux/slices/uiStateSlice.ts b/gui/src/redux/slices/uiStateSlice.ts index a31f36d66..3d88c5435 100644 --- a/gui/src/redux/slices/uiStateSlice.ts +++ b/gui/src/redux/slices/uiStateSlice.ts @@ -4,6 +4,11 @@ import { OnboardingCardState, } from "../../components/OnboardingCard"; +type ToolSetting = + | "allowedWithPermission" + | "allowedWithoutPermission" + | "disabled"; + type UiState = { showDialog: boolean; dialogMessage: string | JSX.Element | undefined; @@ -11,8 +16,11 @@ type UiState = { onboardingCard: OnboardingCardState; shouldAddFileForEditing: boolean; useTools: boolean; + toolSettings: { [toolName: string]: ToolSetting }; }; +export const DEFAULT_TOOL_SETTING: ToolSetting = "allowedWithPermission"; + export const uiStateSlice = createSlice({ name: "uiState", initialState: { @@ -21,7 +29,9 @@ export const uiStateSlice = createSlice({ dialogEntryOn: false, onboardingCard: defaultOnboardingCardState, shouldAddFileForEditing: false, + useTools: false, + toolSettings: {}, } as UiState, reducers: { setOnboardingCard: ( @@ -51,9 +61,29 @@ export const uiStateSlice = createSlice({ ) => { state.shouldAddFileForEditing = action.payload; }, + + // Tools toggleUseTools: (state) => { state.useTools = !state.useTools; }, + toggleToolSetting: (state, action: PayloadAction) => { + const setting = state.toolSettings[action.payload]; + + switch (setting) { + case "allowedWithPermission": + state.toolSettings[action.payload] = "allowedWithoutPermission"; + break; + case "allowedWithoutPermission": + state.toolSettings[action.payload] = "disabled"; + break; + case "disabled": + state.toolSettings[action.payload] = "allowedWithPermission"; + break; + default: + state.toolSettings[action.payload] = DEFAULT_TOOL_SETTING; + break; + } + }, }, }); @@ -64,6 +94,7 @@ export const { setShowDialog, setShouldAddFileForEditing, toggleUseTools, + toggleToolSetting, } = uiStateSlice.actions; export default uiStateSlice.reducer; From ae784b9ed01e625ccd2bbaf994a514c30cc6396b Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Nov 2024 23:07:29 -0800 Subject: [PATCH 051/105] auto call tool --- .../pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx | 16 +++++++++++++++- gui/src/redux/slices/uiStateSlice.ts | 11 ++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx index a2c69cbed..42f9d9204 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx @@ -1,4 +1,4 @@ -import { useContext } from "react"; +import { useContext, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; import { @@ -55,8 +55,22 @@ export function ToolCallButtons(props: ToolCallButtonsProps) { const toolCallState = useSelector( (store: RootState) => store.state.currentToolCallState, ); + const toolSetting = useSelector( + (store: RootState) => + store.uiState.toolSettings[toolCallState.toolCall.function.name], + ); + const ideMessenger = useContext(IdeMessengerContext); + useEffect(() => { + if ( + toolCallState.currentToolCallState === "generated" && + toolSetting === "allowedWithoutPermission" + ) { + callTool(); + } + }, [toolCallState.currentToolCallState, toolSetting]); + const { streamResponseAfterToolCall } = useChatHandler( dispatch, ideMessenger, diff --git a/gui/src/redux/slices/uiStateSlice.ts b/gui/src/redux/slices/uiStateSlice.ts index 3d88c5435..268815ae4 100644 --- a/gui/src/redux/slices/uiStateSlice.ts +++ b/gui/src/redux/slices/uiStateSlice.ts @@ -1,4 +1,5 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; +import { BuiltInToolNames } from "core/tools/builtIn"; import { defaultOnboardingCardState, OnboardingCardState, @@ -31,7 +32,15 @@ export const uiStateSlice = createSlice({ shouldAddFileForEditing: false, useTools: false, - toolSettings: {}, + toolSettings: { + [BuiltInToolNames.CreateNewFile]: "allowedWithPermission", + [BuiltInToolNames.RunTerminalCommand]: "allowedWithPermission", + [BuiltInToolNames.ViewSubdirectory]: "allowedWithoutPermission", + [BuiltInToolNames.ViewRepoMap]: "allowedWithoutPermission", + [BuiltInToolNames.ExactSearch]: "allowedWithoutPermission", + [BuiltInToolNames.SearchWeb]: "allowedWithoutPermission", + [BuiltInToolNames.ViewDiff]: "allowedWithoutPermission", + }, } as UiState, reducers: { setOnboardingCard: ( From 215f03da1b8a6f1a3f5924dc7d32c1d468029076 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Nov 2024 23:22:20 -0800 Subject: [PATCH 052/105] turn tools on/off --- core/core.ts | 4 ---- core/protocol/core.ts | 1 - gui/src/components/InfoHover.tsx | 6 ++++-- .../mainInput/InputToolbar/ToggleToolsButton.tsx | 16 ++++++++++++++++ gui/src/context/IdeMessenger.ts | 3 --- gui/src/hooks/useChatHandler.ts | 15 +++++++++++++-- 6 files changed, 33 insertions(+), 12 deletions(-) diff --git a/core/core.ts b/core/core.ts index 9e1738740..a0a571698 100644 --- a/core/core.ts +++ b/core/core.ts @@ -384,10 +384,6 @@ export class Core { const model = await configHandler.llmFromTitle(msg.data.title); - if (msg.data.useTools) { - msg.data.completionOptions.tools = allTools; - } - const gen = model.streamChat( msg.data.messages, new AbortController().signal, diff --git a/core/protocol/core.ts b/core/protocol/core.ts index bebfc1b6e..bad13a359 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -122,7 +122,6 @@ export type ToCoreFromIdeOrWebviewProtocol = { messages: ChatMessage[]; completionOptions: LLMFullCompletionOptions; title: string; - useTools?: boolean; }, ProtocolGeneratorType, ]; diff --git a/gui/src/components/InfoHover.tsx b/gui/src/components/InfoHover.tsx index aa6541c5b..d3f256e70 100644 --- a/gui/src/components/InfoHover.tsx +++ b/gui/src/components/InfoHover.tsx @@ -1,14 +1,16 @@ import { InformationCircleIcon } from "@heroicons/react/24/outline"; import { ToolTip } from "./gui/Tooltip"; -const InfoHover = ({ msg }: { msg: string }) => { +const DEFAULT_SIZE = "5"; + +const InfoHover = ({ msg, size }: { msg: string; size?: string }) => { const id = `info-hover-${encodeURIComponent(msg)}`; return ( <> diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index 6433959b8..9b5ea6664 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -14,6 +14,7 @@ import { defaultModelSelector } from "../../../redux/selectors/modelSelectors"; import { toggleUseTools } from "../../../redux/slices/uiStateSlice"; import { RootState } from "../../../redux/store"; import { getFontSize } from "../../../util"; +import InfoHover from "../../InfoHover"; import HoverItem from "./HoverItem"; import ToolDropdownItem from "./ToolDropdownItem"; @@ -77,6 +78,21 @@ export default function ToolDropdown() { )} +
+ Tool policies{" "} + +
{allTools.map((tool) => ( ; ide: IDE; @@ -203,7 +202,6 @@ export class IdeMessenger implements IIdeMessenger { cancelToken: AbortSignal | undefined, messages: ChatMessage[], options: LLMFullCompletionOptions = {}, - useTools?: boolean, ): AsyncGenerator { const gen = this.streamRequest( "llm/streamChat", @@ -211,7 +209,6 @@ export class IdeMessenger implements IIdeMessenger { messages, title: modelTitle, completionOptions: options, - useTools, }, cancelToken, ); diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index e3d557f61..6cd262a4a 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -13,6 +13,7 @@ import { SlashCommandDescription, } from "core"; import { constructMessages } from "core/llm/constructMessages"; +import { allTools } from "core/tools"; import { getBasename, getRelativePath } from "core/util"; import { renderChatMessage, @@ -64,6 +65,9 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { (store: RootState) => store.state.streamAborter, ); const useTools = useSelector((store: RootState) => store.uiState.useTools); + const toolSettings = useSelector( + (store: RootState) => store.uiState.toolSettings, + ); const activeRef = useRef(active); @@ -87,8 +91,15 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { defaultModel.title, streamAborter.signal, messages, - {}, - useTools, + { + tools: useTools + ? Object.keys(toolSettings) + .filter((tool) => toolSettings[tool] !== "disabled") + .map((toolName) => + allTools.find((tool) => tool.function.name === toolName), + ) + : undefined, + }, ); let next = await gen.next(); From 5004123054434608e1aae30a57fe60520a5f8fa4 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 23 Nov 2024 10:21:31 -0800 Subject: [PATCH 053/105] nicer tooltip --- gui/src/components/InfoHover.tsx | 17 +++++++++++++---- .../InputToolbar/ToggleToolsButton.tsx | 19 ++++++++++++++++++- .../components/modelSelection/ModelCard.tsx | 6 +++++- gui/src/pages/settings.tsx | 2 ++ 4 files changed, 38 insertions(+), 6 deletions(-) diff --git a/gui/src/components/InfoHover.tsx b/gui/src/components/InfoHover.tsx index d3f256e70..4b0774efe 100644 --- a/gui/src/components/InfoHover.tsx +++ b/gui/src/components/InfoHover.tsx @@ -1,19 +1,28 @@ import { InformationCircleIcon } from "@heroicons/react/24/outline"; +import { ReactNode } from "react"; import { ToolTip } from "./gui/Tooltip"; const DEFAULT_SIZE = "5"; -const InfoHover = ({ msg, size }: { msg: string; size?: string }) => { - const id = `info-hover-${encodeURIComponent(msg)}`; +const InfoHover = ({ + msg, + size, + id, +}: { + id: string; + msg: ReactNode; + size?: string; +}) => { + const dataTooltipId = `info-hover-${encodeURIComponent(id)}`; return ( <> - + {msg} diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index 9b5ea6664..232a0cd8e 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -87,9 +87,26 @@ export default function ToolDropdown() { > Tool policies{" "} +

+ Automatic:{" "} + Can be used without asking +

+

+ Allowed:{" "} + Will ask before using +

+

+ Disabled:{" "} + Cannot be used +

+
} />
diff --git a/gui/src/components/modelSelection/ModelCard.tsx b/gui/src/components/modelSelection/ModelCard.tsx index 35891df79..97650ce8e 100644 --- a/gui/src/components/modelSelection/ModelCard.tsx +++ b/gui/src/components/modelSelection/ModelCard.tsx @@ -176,7 +176,10 @@ function ModelCard(props: ModelCardProps) { <>
- +

{dimension.name}

@@ -205,6 +208,7 @@ function ModelCard(props: ModelCardProps) {
System Message Temperature Date: Sat, 23 Nov 2024 21:13:47 -0800 Subject: [PATCH 054/105] update state --- core/index.d.ts | 19 +++++- core/llm/index.ts | 3 +- gui/src/hooks/useChatHandler.ts | 43 +++++++++++++ gui/src/pages/gui/Chat.tsx | 16 ++--- gui/src/pages/gui/ToolCallDiv/CreateFile.tsx | 10 +-- .../FunctionSpecificToolCallDiv.tsx | 17 +---- .../gui/ToolCallDiv/RunTerminalCommand.tsx | 2 - .../gui/ToolCallDiv/ToolCallButtonsDiv.tsx | 62 +++--------------- gui/src/pages/gui/ToolCallDiv/index.tsx | 39 +++--------- gui/src/pages/gui/ToolCallDiv/types.ts | 6 -- gui/src/redux/selectors/selectLastToolCall.ts | 10 +++ gui/src/redux/slices/stateSlice.ts | 63 +++++++++---------- gui/src/redux/util/index.ts | 20 ++++++ 13 files changed, 153 insertions(+), 157 deletions(-) delete mode 100644 gui/src/pages/gui/ToolCallDiv/types.ts create mode 100644 gui/src/redux/selectors/selectLastToolCall.ts create mode 100644 gui/src/redux/util/index.ts diff --git a/core/index.d.ts b/core/index.d.ts index 26421368c..a4f76ead0 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -321,7 +321,7 @@ export interface ToolCallDelta { export interface ToolResultChatMessage { role: "tool"; content: string; - toolCallId?: string; + toolCallId: string; } export interface UserChatMessage { @@ -390,13 +390,28 @@ export interface PromptLog { prompt: string; completion: string; } + +export type ToolStatus = + | "generating" + | "generated" + | "calling" + | "done" + | "canceled"; + +// Will exist only on "assistant" messages with tool calls +interface ToolCallState { + toolCallId: string; + toolCall: ToolCall; + status: ToolStatus; +} + export interface ChatHistoryItem { message: ChatMessage; editorState?: any; modifiers?: InputModifiers; contextItems: ContextItemWithId[]; promptLogs?: PromptLog[]; - acceptedToolCall?: boolean; + toolCallState?: ToolCallState; } export type ChatHistory = ChatHistoryItem[]; diff --git a/core/llm/index.ts b/core/llm/index.ts index fd3e9b7ac..144df72d2 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -4,7 +4,6 @@ import Handlebars from "handlebars"; import { CacheBehavior, ChatMessage, - ChatMessageRole, CompletionOptions, ILLM, LLMFullCompletionOptions, @@ -582,7 +581,7 @@ export abstract class BaseLLM implements ILLM { for await (const chunk of this.streamChat(messages, signal, options)) { completion += chunk.content; } - return { role: "assistant" as ChatMessageRole, content: completion }; + return { role: "assistant" as const, content: completion }; } async *streamChat( diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 6cd262a4a..2d0281bd4 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -27,6 +27,7 @@ import resolveEditorContent, { } from "../components/mainInput/resolveInput"; import { IIdeMessenger } from "../context/IdeMessenger"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; +import { selectLastToolCall } from "../redux/selectors/selectLastToolCall"; import { abortStream, acceptToolCall, @@ -37,6 +38,7 @@ import { resetNextCodeBlockToApplyIndex, resubmitAtIndex, setActive, + setCalling, setCurCheckpointIndex, setInactive, setIsGatheringContext, @@ -68,6 +70,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const toolSettings = useSelector( (store: RootState) => store.uiState.toolSettings, ); + const toolCallState = useSelector(selectLastToolCall); const activeRef = useRef(active); @@ -116,7 +119,16 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { if (returnVal) { dispatch(addPromptCompletionPair([returnVal])); } + + // If it's a tool call that is automatically accepted, we should call it + if ( + toolSettings[toolCallState?.toolCall.function.name] === + "allowedWithoutPermission" + ) { + await callTool(); + } } catch (e) { + debugger; // If there's an error, we should clear the response so there aren't two input boxes dispatch(clearLastEmptyResponse()); } @@ -446,9 +458,40 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { }); } + async function callTool() { + console.log("calling tool", toolCallState.toolCall); + // If it goes "generated" -> "calling" -> "done" really quickly + // we don't want an abrupt flash so just skip "calling" + let setCallingState = true; + + const timer = setTimeout(() => { + if (setCallingState) { + dispatch(setCalling()); + } + }, 800); + + if (toolCallState.status !== "generated") { + return; + } + + const result = await ideMessenger.request("tools/call", { + toolCall: toolCallState.toolCall, + }); + + setCallingState = false; + clearTimeout(timer); + + if (result.status === "success") { + const contextItems = result.content.contextItems; + // Send to the LLM to continue the conversation + streamResponseAfterToolCall(toolCallState.toolCall.id, contextItems); + } + } + return { streamResponse, streamResponseAfterToolCall, + callTool, }; } diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index a858c09a8..26c68f04d 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -5,7 +5,7 @@ import { ExclamationTriangleIcon, } from "@heroicons/react/24/outline"; import { JSONContent } from "@tiptap/react"; -import { InputModifiers } from "core"; +import { InputModifiers, ToolCallState } from "core"; import { usePostHog } from "posthog-js/react"; import { useCallback, useContext, useEffect, useRef, useState } from "react"; import { ErrorBoundary } from "react-error-boundary"; @@ -35,6 +35,7 @@ import useHistory from "../../hooks/useHistory"; import { useTutorialCard } from "../../hooks/useTutorialCard"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; +import { selectLastToolCall } from "../../redux/selectors/selectLastToolCall"; import { clearLastEmptyResponse, newSession, @@ -132,8 +133,8 @@ export function Chat() { const { saveSession, getLastSessionId, loadLastSession } = useHistory(dispatch); - const toolCallState = useSelector( - (store: RootState) => store.state.currentToolCallState, + const toolCallState = useSelector( + selectLastToolCall, ); const snapToBottom = useCallback(() => { @@ -352,13 +353,14 @@ export function Chat() { toolCallId={item.message.toolCallId} /> ) : item.message.role === "assistant" && - item.message.toolCalls ? ( + item.message.toolCalls && + item.toolCallState ? (
{item.message.toolCalls?.map((toolCall) => { return ( ); })} @@ -431,9 +433,7 @@ export function Chat() { )}
- {toolCallState.currentToolCallState === "generated" && ( - - )} + {toolCallState?.status === "generated" && } - + /> */} ); } diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 27bd820a8..db72817c9 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -2,28 +2,17 @@ import { ToolCall } from "core"; import { incrementalParseJson } from "core/util/incrementalParseJson"; import { CreateFile } from "./CreateFile"; import { RunTerminalCommand } from "./RunTerminalCommand"; -import { ToolState } from "./types"; -function FunctionSpecificToolCallDiv({ - toolCall, - state, -}: { - toolCall: ToolCall; - state: ToolState; -}) { +function FunctionSpecificToolCallDiv({ toolCall }: { toolCall: ToolCall }) { const [_, args] = incrementalParseJson(toolCall.function.arguments); switch (toolCall.function.name) { case "create_new_file": return ( - + ); case "run_terminal_command": - return ; + return ; default: return null; } diff --git a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx index c217bd07b..08c00c0bd 100644 --- a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx +++ b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx @@ -1,9 +1,7 @@ import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; -import { ToolState } from "./types"; interface RunTerminalCommandToolCallProps { command: string; - state: ToolState; } export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx index 42f9d9204..068394086 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx @@ -1,4 +1,4 @@ -import { useContext, useEffect } from "react"; +import { useContext } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; import { @@ -10,8 +10,8 @@ import { import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import useChatHandler from "../../../hooks/useChatHandler"; -import { cancelToolCall, setCalling } from "../../../redux/slices/stateSlice"; -import { RootState } from "../../../redux/store"; +import { selectLastToolCall } from "../../../redux/selectors/selectLastToolCall"; +import { cancelToolCall } from "../../../redux/slices/stateSlice"; const ButtonContainer = styled.div` display: flex; @@ -52,62 +52,18 @@ interface ToolCallButtonsProps {} export function ToolCallButtons(props: ToolCallButtonsProps) { const dispatch = useDispatch(); - const toolCallState = useSelector( - (store: RootState) => store.state.currentToolCallState, - ); - const toolSetting = useSelector( - (store: RootState) => - store.uiState.toolSettings[toolCallState.toolCall.function.name], - ); + const toolCallState = useSelector(selectLastToolCall); const ideMessenger = useContext(IdeMessengerContext); - useEffect(() => { - if ( - toolCallState.currentToolCallState === "generated" && - toolSetting === "allowedWithoutPermission" - ) { - callTool(); - } - }, [toolCallState.currentToolCallState, toolSetting]); - - const { streamResponseAfterToolCall } = useChatHandler( + const { streamResponseAfterToolCall, callTool } = useChatHandler( dispatch, ideMessenger, ); - async function callTool() { - // If it goes "generated" -> "calling" -> "done" really quickly - // we don't want an abrupt flash so just skip "calling" - let setCallingState = true; - - const timer = setTimeout(() => { - if (setCallingState) { - dispatch(setCalling()); - } - }, 800); - - if (toolCallState.currentToolCallState !== "generated") { - return; - } - - const result = await ideMessenger.request("tools/call", { - toolCall: toolCallState.toolCall, - }); - - setCallingState = false; - clearTimeout(timer); - - if (result.status === "success") { - const contextItems = result.content.contextItems; - // Send to the LLM to continue the conversation - streamResponseAfterToolCall(toolCallState.toolCall.id, contextItems); - } - } - async function cancelTool() { dispatch(cancelToolCall()); - streamResponseAfterToolCall(toolCallState.toolCall.id, [ + streamResponseAfterToolCall(toolCallState.toolCallId, [ { name: "Cancelled", description: "Cancelled", @@ -120,7 +76,7 @@ export function ToolCallButtons(props: ToolCallButtonsProps) { return ( <> - {toolCallState.currentToolCallState === "generating" ? ( + {toolCallState.status === "generating" ? (
Thinking...
- ) : toolCallState.currentToolCallState === "generated" ? ( + ) : toolCallState.status === "generated" ? ( <> Cancel Continue - ) : toolCallState.currentToolCallState === "calling" ? ( + ) : toolCallState.status === "calling" ? (
Loading... diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index fa0a96a6a..656d2b248 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -1,33 +1,21 @@ import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import { ToolCall } from "core"; +import { ToolCall, ToolStatus } from "core"; import { incrementalParseJson } from "core/util/incrementalParseJson"; import { useEffect } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { lightGray } from "../../../components"; import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner"; -import { - registerCurrentToolCall, - setGeneratedOutput, -} from "../../../redux/slices/stateSlice"; -import { RootState } from "../../../redux/store"; +import { setGeneratedOutput } from "../../../redux/slices/stateSlice"; import FunctionSpecificToolCallDiv from "./FunctionSpecificToolCallDiv"; import { ThreadDiv } from "./ThreadDiv"; -import { ToolState } from "./types"; interface ToolCallDivProps { toolCall: ToolCall; - acceptedToolCall?: boolean; + status: ToolStatus; } export function ToolCallDiv(props: ToolCallDivProps) { const dispatch = useDispatch(); - const toolCallState = useSelector( - (store: RootState) => store.state.currentToolCallState, - ); - - useEffect(() => { - dispatch(registerCurrentToolCall()); - }, []); useEffect(() => { // Once the JSON can successfully parse, then set state to "generated" @@ -42,13 +30,8 @@ export function ToolCallDiv(props: ToolCallDivProps) { } }, [props.toolCall.function.arguments]); - function getIcon(state: ToolState) { + function getIcon(state: ToolStatus) { console.log("State: ", state); - if (props.acceptedToolCall === true) { - return ; - } else if (props.acceptedToolCall === false) { - return ; - } switch (state) { case "generating": @@ -65,15 +48,9 @@ export function ToolCallDiv(props: ToolCallDivProps) { } return ( - - {toolCallState.currentToolCallState} - + + {props.status} + ); } diff --git a/gui/src/pages/gui/ToolCallDiv/types.ts b/gui/src/pages/gui/ToolCallDiv/types.ts deleted file mode 100644 index 2a21a7bb9..000000000 --- a/gui/src/pages/gui/ToolCallDiv/types.ts +++ /dev/null @@ -1,6 +0,0 @@ -export type ToolState = - | "generating" - | "generated" - | "calling" - | "done" - | "canceled"; diff --git a/gui/src/redux/selectors/selectLastToolCall.ts b/gui/src/redux/selectors/selectLastToolCall.ts new file mode 100644 index 000000000..3625cf8de --- /dev/null +++ b/gui/src/redux/selectors/selectLastToolCall.ts @@ -0,0 +1,10 @@ +import { createSelector } from "@reduxjs/toolkit"; +import { RootState } from "../store"; +import { findLastToolCall } from "../util"; + +export const selectLastToolCall = createSelector( + (store: RootState) => store.state.history, + (history) => { + return findLastToolCall(history); + }, +); diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index fecd98176..cbed186c8 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -16,13 +16,7 @@ import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { renderChatMessage } from "core/util/messageContent"; import { v4 as uuidv4, v4 } from "uuid"; -import { ToolState } from "../../pages/gui/ToolCallDiv/types"; - -interface CurrentToolCallState { - currentToolCallId?: string; - currentToolCallState?: ToolState; - toolCall?: ToolCall; -} +import { findLastToolCall } from "../util"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -31,7 +25,6 @@ type ChatHistoryItemWithMessageId = ChatHistoryItem & { }; type State = { - currentToolCallState: CurrentToolCallState; history: ChatHistoryItemWithMessageId[]; symbols: FileSymbolMap; context: { @@ -59,10 +52,6 @@ type State = { }; const initialState: State = { - currentToolCallState: { - currentToolCallId: undefined, - currentToolCallState: undefined, - }, history: [], symbols: {}, context: { @@ -215,8 +204,6 @@ export const stateSlice = createSlice({ contextItems: [], }); - state.currentToolCallState = {}; - // https://github.com/continuedev/continue/pull/1021 state.active = true; }, @@ -320,10 +307,20 @@ export const stateSlice = createSlice({ action.payload.toolCalls?.length)) ) { // Create a new message - state.history.push({ + const historyItem: ChatHistoryItemWithMessageId = { contextItems: [], - message: { id: "NONE", ...action.payload }, - }); + message: { id: uuidv4(), ...action.payload }, + }; + + if (action.payload.role === "assistant" && action.payload.toolCalls) { + historyItem.toolCallState = { + status: "generating", + toolCall: action.payload.toolCalls[0] as ToolCall, + toolCallId: action.payload.toolCalls[0].id, + }; + } + + state.history.push(historyItem); } else { // Add to the existing message const msg = state.history[state.history.length - 1].message; @@ -359,7 +356,6 @@ export const stateSlice = createSlice({ state.active = false; state.context.isGathering = false; state.symbols = {}; - state.currentToolCallState = {}; if (payload) { state.history = payload.history as any; @@ -460,26 +456,30 @@ export const stateSlice = createSlice({ }, // Related to currentToolCallState - registerCurrentToolCall: (state, { payload }: PayloadAction) => { - state.currentToolCallState.currentToolCallId = payload; - state.currentToolCallState.currentToolCallState = "generating"; - }, cancelToolCall: (state) => { - state.currentToolCallState.currentToolCallId = undefined; - state.currentToolCallState.currentToolCallState = undefined; - state.history[state.history.length - 1].acceptedToolCall = false; + const toolCallState = findLastToolCall(state.history); + if (!toolCallState) return; + + toolCallState.status = "canceled"; }, acceptToolCall: (state) => { - state.currentToolCallState.currentToolCallId = undefined; - state.currentToolCallState.currentToolCallState = undefined; - state.history[state.history.length - 1].acceptedToolCall = true; + const toolCallState = findLastToolCall(state.history); + if (!toolCallState) return; + + toolCallState.status = "done"; }, setGeneratedOutput: (state, { payload }: PayloadAction) => { - state.currentToolCallState.currentToolCallState = "generated"; - state.currentToolCallState.toolCall = payload; + const toolCallState = findLastToolCall(state.history); + if (!toolCallState) return; + + toolCallState.toolCall = payload; + toolCallState.status = "generated"; }, setCalling: (state) => { - state.currentToolCallState.currentToolCallState = "calling"; + const toolCallState = findLastToolCall(state.history); + if (!toolCallState) return; + + toolCallState.status = "calling"; }, updateIndexingStatus: ( state, @@ -551,7 +551,6 @@ export const { setIndexingChatPeekHidden, setCalling, cancelToolCall, - registerCurrentToolCall, setGeneratedOutput, acceptToolCall, } = stateSlice.actions; diff --git a/gui/src/redux/util/index.ts b/gui/src/redux/util/index.ts new file mode 100644 index 000000000..debf6b329 --- /dev/null +++ b/gui/src/redux/util/index.ts @@ -0,0 +1,20 @@ +import { ToolCallState } from "core"; +import { RootState } from "../store"; + +function findLast( + array: T[], + predicate: (value: T, index: number, array: T[]) => boolean, +): T | undefined { + for (let i = array.length - 1; i >= 0; i--) { + if (predicate(array[i], i, array)) { + return array[i]; + } + } + return undefined; +} + +export function findLastToolCall( + state: RootState["state"]["history"], +): ToolCallState | undefined { + return findLast(state, (item) => !!item.toolCallState)?.toolCallState; +} From 942fd9fa4e4378c709db092e6a672940a99715fb Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 23 Nov 2024 23:29:08 -0800 Subject: [PATCH 055/105] some logic adjustments, but not entirely fixed yet --- gui/src/hooks/useChatHandler.ts | 23 +++++++++++++------ gui/src/pages/gui/Chat.tsx | 4 ++-- .../gui/ToolCallDiv/ToolCallButtonsDiv.tsx | 8 +++++-- gui/src/pages/gui/ToolCallDiv/index.tsx | 3 --- ...stToolCall.ts => selectCurrentToolCall.ts} | 6 ++--- gui/src/redux/slices/stateSlice.ts | 10 ++++---- gui/src/redux/util/index.ts | 16 ++----------- 7 files changed, 34 insertions(+), 36 deletions(-) rename gui/src/redux/selectors/{selectLastToolCall.ts => selectCurrentToolCall.ts} (53%) diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 2d0281bd4..09b1f8333 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -27,7 +27,7 @@ import resolveEditorContent, { } from "../components/mainInput/resolveInput"; import { IIdeMessenger } from "../context/IdeMessenger"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { selectLastToolCall } from "../redux/selectors/selectLastToolCall"; +import { selectCurrentToolCall } from "../redux/selectors/selectCurrentToolCall"; import { abortStream, acceptToolCall, @@ -70,7 +70,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const toolSettings = useSelector( (store: RootState) => store.uiState.toolSettings, ); - const toolCallState = useSelector(selectLastToolCall); + const toolCallState = useSelector(selectCurrentToolCall); const activeRef = useRef(active); @@ -121,14 +121,18 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } // If it's a tool call that is automatically accepted, we should call it + + await new Promise((resolve) => setTimeout(resolve, 0)); + if ( - toolSettings[toolCallState?.toolCall.function.name] === - "allowedWithoutPermission" + toolCallState && + toolCallState.status === "generated" && + toolSettings[toolCallState.toolCall.function.name] === + "allowedWithoutPermission" ) { await callTool(); } } catch (e) { - debugger; // If there's an error, we should clear the response so there aren't two input boxes dispatch(clearLastEmptyResponse()); } @@ -419,6 +423,9 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { await handleErrors(async () => { resetStateForNewMessage(); + dispatch(acceptToolCall()); + await new Promise((resolve) => setTimeout(resolve, 0)); + const newMessage: ChatMessage = { role: "tool", content: renderContextItems(toolOutput), @@ -438,10 +445,8 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { })), }), ); - dispatch(acceptToolCall()); activeRef.current = true; dispatch(setActive()); - await new Promise((resolve) => setTimeout(resolve, 0)); const messages = constructMessages( @@ -460,6 +465,10 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { async function callTool() { console.log("calling tool", toolCallState.toolCall); + if (!toolCallState) { + return; + } + // If it goes "generated" -> "calling" -> "done" really quickly // we don't want an abrupt flash so just skip "calling" let setCallingState = true; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 26c68f04d..00901f1ae 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -35,7 +35,7 @@ import useHistory from "../../hooks/useHistory"; import { useTutorialCard } from "../../hooks/useTutorialCard"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; -import { selectLastToolCall } from "../../redux/selectors/selectLastToolCall"; +import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall"; import { clearLastEmptyResponse, newSession, @@ -134,7 +134,7 @@ export function Chat() { useHistory(dispatch); const toolCallState = useSelector( - selectLastToolCall, + selectCurrentToolCall, ); const snapToBottom = useCallback(() => { diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx index 068394086..8b371bf11 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx @@ -10,7 +10,7 @@ import { import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import useChatHandler from "../../../hooks/useChatHandler"; -import { selectLastToolCall } from "../../../redux/selectors/selectLastToolCall"; +import { selectCurrentToolCall } from "../../../redux/selectors/selectCurrentToolCall"; import { cancelToolCall } from "../../../redux/slices/stateSlice"; const ButtonContainer = styled.div` @@ -52,7 +52,7 @@ interface ToolCallButtonsProps {} export function ToolCallButtons(props: ToolCallButtonsProps) { const dispatch = useDispatch(); - const toolCallState = useSelector(selectLastToolCall); + const toolCallState = useSelector(selectCurrentToolCall); const ideMessenger = useContext(IdeMessengerContext); @@ -73,6 +73,10 @@ export function ToolCallButtons(props: ToolCallButtonsProps) { ]); } + if (!toolCallState) { + return null; + } + return ( <> diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 656d2b248..b53bfa45a 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -31,8 +31,6 @@ export function ToolCallDiv(props: ToolCallDivProps) { }, [props.toolCall.function.arguments]); function getIcon(state: ToolStatus) { - console.log("State: ", state); - switch (state) { case "generating": return ; @@ -49,7 +47,6 @@ export function ToolCallDiv(props: ToolCallDivProps) { return ( - {props.status} ); diff --git a/gui/src/redux/selectors/selectLastToolCall.ts b/gui/src/redux/selectors/selectCurrentToolCall.ts similarity index 53% rename from gui/src/redux/selectors/selectLastToolCall.ts rename to gui/src/redux/selectors/selectCurrentToolCall.ts index 3625cf8de..cd0b47f50 100644 --- a/gui/src/redux/selectors/selectLastToolCall.ts +++ b/gui/src/redux/selectors/selectCurrentToolCall.ts @@ -1,10 +1,10 @@ import { createSelector } from "@reduxjs/toolkit"; import { RootState } from "../store"; -import { findLastToolCall } from "../util"; +import { findCurrentToolCall } from "../util"; -export const selectLastToolCall = createSelector( +export const selectCurrentToolCall = createSelector( (store: RootState) => store.state.history, (history) => { - return findLastToolCall(history); + return findCurrentToolCall(history); }, ); diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index cbed186c8..9aa05d02a 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -16,7 +16,7 @@ import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { renderChatMessage } from "core/util/messageContent"; import { v4 as uuidv4, v4 } from "uuid"; -import { findLastToolCall } from "../util"; +import { findCurrentToolCall } from "../util"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -457,26 +457,26 @@ export const stateSlice = createSlice({ // Related to currentToolCallState cancelToolCall: (state) => { - const toolCallState = findLastToolCall(state.history); + const toolCallState = findCurrentToolCall(state.history); if (!toolCallState) return; toolCallState.status = "canceled"; }, acceptToolCall: (state) => { - const toolCallState = findLastToolCall(state.history); + const toolCallState = findCurrentToolCall(state.history); if (!toolCallState) return; toolCallState.status = "done"; }, setGeneratedOutput: (state, { payload }: PayloadAction) => { - const toolCallState = findLastToolCall(state.history); + const toolCallState = findCurrentToolCall(state.history); if (!toolCallState) return; toolCallState.toolCall = payload; toolCallState.status = "generated"; }, setCalling: (state) => { - const toolCallState = findLastToolCall(state.history); + const toolCallState = findCurrentToolCall(state.history); if (!toolCallState) return; toolCallState.status = "calling"; diff --git a/gui/src/redux/util/index.ts b/gui/src/redux/util/index.ts index debf6b329..06ceebb4a 100644 --- a/gui/src/redux/util/index.ts +++ b/gui/src/redux/util/index.ts @@ -1,20 +1,8 @@ import { ToolCallState } from "core"; import { RootState } from "../store"; -function findLast( - array: T[], - predicate: (value: T, index: number, array: T[]) => boolean, -): T | undefined { - for (let i = array.length - 1; i >= 0; i--) { - if (predicate(array[i], i, array)) { - return array[i]; - } - } - return undefined; -} - -export function findLastToolCall( +export function findCurrentToolCall( state: RootState["state"]["history"], ): ToolCallState | undefined { - return findLast(state, (item) => !!item.toolCallState)?.toolCallState; + return state[state.length - 1]?.toolCallState; } From 79d9148322697f65fb08330a935ef1315decf30e Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 24 Nov 2024 13:19:42 -0800 Subject: [PATCH 056/105] migrate useChatHandler to async thunks --- gui/package-lock.json | 35 +- gui/package.json | 1 + gui/src/hooks/useChatHandler.ts | 507 ------------------ gui/src/hooks/useSetup.ts | 27 +- gui/src/pages/Edit/Edit.tsx | 32 +- gui/src/pages/gui/Chat.tsx | 17 +- .../gui/ToolCallDiv/ToolCallButtonsDiv.tsx | 38 +- gui/src/redux/slices/stateSlice.ts | 23 +- gui/src/redux/store.ts | 23 +- gui/src/redux/thunks/callTool.ts | 50 ++ gui/src/redux/thunks/gatherContext.ts | 117 ++++ gui/src/redux/thunks/handleErrors.ts | 22 + .../redux/thunks/resetStateForNewMessage.ts | 11 + gui/src/redux/thunks/streamNormalInput.ts | 79 +++ gui/src/redux/thunks/streamResponse.ts | 157 ++++++ .../thunks/streamResponseAfterToolCall.ts | 75 +++ gui/src/redux/thunks/streamSlashCommand.ts | 71 +++ 17 files changed, 707 insertions(+), 578 deletions(-) delete mode 100644 gui/src/hooks/useChatHandler.ts create mode 100644 gui/src/redux/thunks/callTool.ts create mode 100644 gui/src/redux/thunks/gatherContext.ts create mode 100644 gui/src/redux/thunks/handleErrors.ts create mode 100644 gui/src/redux/thunks/resetStateForNewMessage.ts create mode 100644 gui/src/redux/thunks/streamNormalInput.ts create mode 100644 gui/src/redux/thunks/streamResponse.ts create mode 100644 gui/src/redux/thunks/streamResponseAfterToolCall.ts create mode 100644 gui/src/redux/thunks/streamSlashCommand.ts diff --git a/gui/package-lock.json b/gui/package-lock.json index 107360d04..55f1e5b73 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -47,6 +47,7 @@ "react-tooltip": "^5.18.0", "redux-persist": "^6.0.0", "redux-persist-transform-filter": "^0.0.22", + "redux-thunk": "^3.1.0", "rehype-highlight": "^7.0.0", "rehype-katex": "^7.0.0", "rehype-wrap-all": "^1.1.0", @@ -1536,6 +1537,22 @@ } } }, + "node_modules/@reduxjs/toolkit/node_modules/redux": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/redux/-/redux-4.2.1.tgz", + "integrity": "sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w==", + "dependencies": { + "@babel/runtime": "^7.9.2" + } + }, + "node_modules/@reduxjs/toolkit/node_modules/redux-thunk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-2.4.2.tgz", + "integrity": "sha512-+P3TjtnP0k/FEjcBL5FZpoovtvrTNT/UXd4/sluaSyrURlSlhLSzEdfsTBW7WsKB6yPvgd7q/iZPICFjW4o57Q==", + "peerDependencies": { + "redux": "^4" + } + }, "node_modules/@reduxjs/toolkit/node_modules/reselect": { "version": "4.1.8", "resolved": "https://registry.npmjs.org/reselect/-/reselect-4.1.8.tgz", @@ -8025,12 +8042,10 @@ } }, "node_modules/redux": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/redux/-/redux-4.2.1.tgz", - "integrity": "sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w==", - "dependencies": { - "@babel/runtime": "^7.9.2" - } + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", + "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==", + "peer": true }, "node_modules/redux-persist": { "version": "6.0.0", @@ -8053,11 +8068,11 @@ } }, "node_modules/redux-thunk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-2.4.2.tgz", - "integrity": "sha512-+P3TjtnP0k/FEjcBL5FZpoovtvrTNT/UXd4/sluaSyrURlSlhLSzEdfsTBW7WsKB6yPvgd7q/iZPICFjW4o57Q==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz", + "integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==", "peerDependencies": { - "redux": "^4" + "redux": "^5.0.0" } }, "node_modules/refractor": { diff --git a/gui/package.json b/gui/package.json index ef77ac910..1aa3abcf6 100644 --- a/gui/package.json +++ b/gui/package.json @@ -55,6 +55,7 @@ "react-tooltip": "^5.18.0", "redux-persist": "^6.0.0", "redux-persist-transform-filter": "^0.0.22", + "redux-thunk": "^3.1.0", "rehype-highlight": "^7.0.0", "rehype-katex": "^7.0.0", "rehype-wrap-all": "^1.1.0", diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts deleted file mode 100644 index 09b1f8333..000000000 --- a/gui/src/hooks/useChatHandler.ts +++ /dev/null @@ -1,507 +0,0 @@ -import { Dispatch } from "@reduxjs/toolkit"; -import { JSONContent } from "@tiptap/react"; -import { - ChatHistory, - ChatHistoryItem, - ChatMessage, - ContextItem, - ContextItemWithId, - InputModifiers, - MessageContent, - PromptLog, - RangeInFile, - SlashCommandDescription, -} from "core"; -import { constructMessages } from "core/llm/constructMessages"; -import { allTools } from "core/tools"; -import { getBasename, getRelativePath } from "core/util"; -import { - renderChatMessage, - renderContextItems, -} from "core/util/messageContent"; -import { usePostHog } from "posthog-js/react"; -import { useEffect, useRef, useState } from "react"; -import { useSelector } from "react-redux"; -import resolveEditorContent, { - hasSlashCommandOrContextProvider, -} from "../components/mainInput/resolveInput"; -import { IIdeMessenger } from "../context/IdeMessenger"; -import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { selectCurrentToolCall } from "../redux/selectors/selectCurrentToolCall"; -import { - abortStream, - acceptToolCall, - addContextItemsAtIndex, - addPromptCompletionPair, - clearLastEmptyResponse, - initNewActiveMessage, - resetNextCodeBlockToApplyIndex, - resubmitAtIndex, - setActive, - setCalling, - setCurCheckpointIndex, - setInactive, - setIsGatheringContext, - setMessageAtIndex, - streamUpdate, -} from "../redux/slices/stateSlice"; -import { RootState } from "../redux/store"; -import { updateFileSymbolsFromContextItems } from "../util/symbols"; -import useHistory from "./useHistory"; - -function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { - const posthog = usePostHog(); - - const defaultModel = useSelector(defaultModelSelector); - const defaultContextProviders = useSelector( - (store: RootState) => store.state.config.experimental?.defaultContext ?? [], - ); - - const slashCommands = useSelector( - (store: RootState) => store.state.config.slashCommands || [], - ); - - const history = useSelector((store: RootState) => store.state.history); - const active = useSelector((store: RootState) => store.state.active); - const streamAborter = useSelector( - (store: RootState) => store.state.streamAborter, - ); - const useTools = useSelector((store: RootState) => store.uiState.useTools); - const toolSettings = useSelector( - (store: RootState) => store.uiState.toolSettings, - ); - const toolCallState = useSelector(selectCurrentToolCall); - - const activeRef = useRef(active); - - const { saveSession } = useHistory(dispatch); - const [save, triggerSave] = useState(false); - - useEffect(() => { - saveSession(false); - }, [save]); - - useEffect(() => { - activeRef.current = active; - }, [active]); - - async function _streamNormalInput(messages: ChatMessage[]) { - try { - if (!defaultModel) { - throw new Error("Default model not defined"); - } - const gen = ideMessenger.llmStreamChat( - defaultModel.title, - streamAborter.signal, - messages, - { - tools: useTools - ? Object.keys(toolSettings) - .filter((tool) => toolSettings[tool] !== "disabled") - .map((toolName) => - allTools.find((tool) => tool.function.name === toolName), - ) - : undefined, - }, - ); - let next = await gen.next(); - - while (!next.done) { - if (!activeRef.current) { - dispatch(abortStream()); - break; - } - dispatch(streamUpdate(next.value as ChatMessage)); - next = await gen.next(); - } - - let returnVal = next.value as PromptLog; - if (returnVal) { - dispatch(addPromptCompletionPair([returnVal])); - } - - // If it's a tool call that is automatically accepted, we should call it - - await new Promise((resolve) => setTimeout(resolve, 0)); - - if ( - toolCallState && - toolCallState.status === "generated" && - toolSettings[toolCallState.toolCall.function.name] === - "allowedWithoutPermission" - ) { - await callTool(); - } - } catch (e) { - // If there's an error, we should clear the response so there aren't two input boxes - dispatch(clearLastEmptyResponse()); - } - } - - const getSlashCommandForInput = ( - input: MessageContent, - ): [SlashCommandDescription, string] | undefined => { - let slashCommand: SlashCommandDescription | undefined; - let slashCommandName: string | undefined; - - let lastText = - typeof input === "string" - ? input - : input.filter((part) => part.type === "text").slice(-1)[0]?.text || ""; - - if (lastText.startsWith("/")) { - slashCommandName = lastText.split(" ")[0].substring(1); - slashCommand = slashCommands.find( - (command) => command.name === slashCommandName, - ); - } - if (!slashCommand || !slashCommandName) { - return undefined; - } - - // Convert to actual slash command object with runnable function - return [slashCommand, renderChatMessage({ role: "user", content: input })]; - }; - - async function _streamSlashCommand( - messages: ChatMessage[], - slashCommand: SlashCommandDescription, - input: string, - historyIndex: number, - selectedCode: RangeInFile[], - contextItems: ContextItemWithId[], - ) { - if (!defaultModel) { - throw new Error("Default model not defined"); - } - - const modelTitle = defaultModel.title; - - const checkActiveInterval = setInterval(() => { - if (!activeRef.current) { - dispatch(abortStream()); - clearInterval(checkActiveInterval); - } - }, 100); - - for await (const update of ideMessenger.streamRequest( - "command/run", - { - input, - history: messages, - modelTitle, - slashCommandName: slashCommand.name, - contextItems, - params: slashCommand.params, - historyIndex, - selectedCode, - }, - streamAborter.signal, - )) { - if (!activeRef.current) { - dispatch(abortStream()); - break; - } - if (typeof update === "string") { - dispatch(streamUpdate(update)); - } - } - clearInterval(checkActiveInterval); - } - - function resetStateForNewMessage() { - // Reset current code block index - dispatch(resetNextCodeBlockToApplyIndex()); - } - - async function gatherContext( - editorState: JSONContent, - modifiers: InputModifiers, - ideMessenger: IIdeMessenger, - promptPreamble?: string, - ) { - // Resolve context providers and construct new history - const shouldGatherContext = - modifiers.useCodebase || hasSlashCommandOrContextProvider(editorState); - - if (shouldGatherContext) { - dispatch( - setIsGatheringContext({ - isGathering: true, - gatheringMessage: "Gathering Context", - }), - ); - } - - let [selectedContextItems, selectedCode, content] = - await resolveEditorContent( - editorState, - modifiers, - ideMessenger, - defaultContextProviders, - dispatch, - ); - - // Automatically use currently open file - if (!modifiers.noContext) { - const usingFreeTrial = defaultModel?.provider === "free-trial"; - - const currentFile = await ideMessenger.ide.getCurrentFile(); - if (currentFile) { - let currentFileContents = currentFile.contents; - if (usingFreeTrial) { - currentFileContents = currentFile.contents - .split("\n") - .slice(0, 1000) - .join("\n"); - } - if ( - !selectedContextItems.find( - (item) => item.uri?.value === currentFile.path, - ) - ) { - // don't add the file if it's already in the context items - selectedContextItems.unshift({ - content: `The following file is currently open. Don't reference it if it's not relevant to the user's message.\n\n\`\`\`${getRelativePath( - currentFile.path, - await ideMessenger.ide.getWorkspaceDirs(), - )}\n${currentFileContents}\n\`\`\``, - name: `Active file: ${getBasename(currentFile.path)}`, - description: currentFile.path, - id: { - itemId: currentFile.path, - providerTitle: "file", - }, - uri: { - type: "file", - value: currentFile.path, - }, - }); - } - } - } - - await updateFileSymbolsFromContextItems( - selectedContextItems, - ideMessenger, - dispatch, - ); - - if (promptPreamble) { - typeof content === "string" - ? (content += promptPreamble) - : (content.at(-1).text += promptPreamble); - } - - // dispatch(addContextItems(contextItems)); - return { selectedContextItems, selectedCode, content }; - } - - async function handleErrors(runStream: () => any): Promise { - try { - await runStream(); - } catch (e: any) { - console.debug("Error streaming response: ", e); - ideMessenger.post("showToast", [ - "error", - `Error streaming response: ${e.message}`, - ]); - } finally { - dispatch(setInactive()); - triggerSave(!save); - } - } - - async function streamResponseWithoutErrorHandling( - editorState: JSONContent, - modifiers: InputModifiers, - ideMessenger: IIdeMessenger, - index?: number, - promptPreamble?: string, - ) { - if (typeof index === "number") { - dispatch(resubmitAtIndex({ index, editorState })); - } else { - dispatch(initNewActiveMessage({ editorState })); - } - - resetStateForNewMessage(); - - if (index) { - dispatch(setCurCheckpointIndex(Math.floor(index / 2))); - } - - const { selectedContextItems, selectedCode, content } = await gatherContext( - editorState, - modifiers, - ideMessenger, - promptPreamble, - ); - - const message: ChatMessage = { - role: "user", - content, - }; - - const historyItem: ChatHistoryItem = { - message, - contextItems: selectedContextItems, - editorState, - }; - - let newHistory: ChatHistory = [...history.slice(0, index), historyItem]; - const historyIndex = index || newHistory.length - 1; - dispatch( - setMessageAtIndex({ - message, - index: historyIndex, - contextItems: selectedContextItems, - }), - ); - - // TODO: hacky way to allow rerender - await new Promise((resolve) => setTimeout(resolve, 0)); - - posthog.capture("step run", { - step_name: "User Input", - params: {}, - }); - posthog.capture("userInput", {}); - - const messages = constructMessages(newHistory, defaultModel.model); - - // Determine if the input is a slash command - let commandAndInput = getSlashCommandForInput(content); - - if (!commandAndInput) { - await _streamNormalInput(messages); - } else { - const [slashCommand, commandInput] = commandAndInput; - let updatedContextItems = []; - posthog.capture("step run", { - step_name: slashCommand.name, - params: {}, - }); - - // if (slashCommand.name === "multifile-edit") { - // dispatch(setIsInMultifileEdit(true)); - // } - - await _streamSlashCommand( - messages, - slashCommand, - commandInput, - historyIndex, - selectedCode, - updatedContextItems, - ); - } - } - - async function streamResponse( - editorState: JSONContent, - modifiers: InputModifiers, - ideMessenger: IIdeMessenger, - index?: number, - promptPreamble?: string, - ) { - await handleErrors(() => - streamResponseWithoutErrorHandling( - editorState, - modifiers, - ideMessenger, - index, - promptPreamble, - ), - ); - } - - async function streamResponseAfterToolCall( - toolCallId: string, - toolOutput: ContextItem[], - ) { - await handleErrors(async () => { - resetStateForNewMessage(); - - dispatch(acceptToolCall()); - await new Promise((resolve) => setTimeout(resolve, 0)); - - const newMessage: ChatMessage = { - role: "tool", - content: renderContextItems(toolOutput), - toolCallId, - }; - - dispatch(streamUpdate(newMessage)); - dispatch( - addContextItemsAtIndex({ - index: history.length, - contextItems: toolOutput.map((contextItem) => ({ - ...contextItem, - id: { - providerTitle: "toolCall", - itemId: toolCallId, - }, - })), - }), - ); - activeRef.current = true; - dispatch(setActive()); - await new Promise((resolve) => setTimeout(resolve, 0)); - - const messages = constructMessages( - [ - ...history, - { - message: newMessage, - contextItems: [], - }, - ], - defaultModel.model, - ); - await _streamNormalInput(messages); - }); - } - - async function callTool() { - console.log("calling tool", toolCallState.toolCall); - if (!toolCallState) { - return; - } - - // If it goes "generated" -> "calling" -> "done" really quickly - // we don't want an abrupt flash so just skip "calling" - let setCallingState = true; - - const timer = setTimeout(() => { - if (setCallingState) { - dispatch(setCalling()); - } - }, 800); - - if (toolCallState.status !== "generated") { - return; - } - - const result = await ideMessenger.request("tools/call", { - toolCall: toolCallState.toolCall, - }); - - setCallingState = false; - clearTimeout(timer); - - if (result.status === "success") { - const contextItems = result.content.contextItems; - // Send to the LLM to continue the conversation - streamResponseAfterToolCall(toolCallState.toolCall.id, contextItems); - } - } - - return { - streamResponse, - streamResponseAfterToolCall, - callTool, - }; -} - -export default useChatHandler; diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 4bef9da9c..19588c94e 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -1,5 +1,4 @@ -import { Dispatch } from "@reduxjs/toolkit"; -import { useCallback, useContext, useEffect, useRef, useState } from "react"; +import { useCallback, useContext, useEffect, useRef } from "react"; import { useSelector } from "react-redux"; import { VSC_THEME_COLOR_VARS } from "../components"; import { IdeMessengerContext } from "../context/IdeMessenger"; @@ -13,16 +12,15 @@ import { setTTSActive, updateIndexingStatus, } from "../redux/slices/stateSlice"; -import { RootState } from "../redux/store"; +import { AppDispatch, RootState } from "../redux/store"; -import { debounce } from "lodash"; +import { streamResponseThunk } from "../redux/thunks/streamResponse"; import { isJetBrains } from "../util"; -import { getLocalStorage, setLocalStorage } from "../util/localStorage"; -import useChatHandler from "./useChatHandler"; -import { useWebviewListener } from "./useWebviewListener"; +import { setLocalStorage } from "../util/localStorage"; import { updateFileSymbolsFromContextItems } from "../util/symbols"; +import { useWebviewListener } from "./useWebviewListener"; -function useSetup(dispatch: Dispatch) { +function useSetup(dispatch: AppDispatch) { const ideMessenger = useContext(IdeMessengerContext); const history = useSelector((store: RootState) => store.state.history); @@ -115,8 +113,6 @@ function useSetup(dispatch: Dispatch) { } }, []); - const { streamResponse } = useChatHandler(dispatch, ideMessenger); - const defaultModelTitle = useSelector( (store: RootState) => store.state.defaultModelTitle, ); @@ -151,10 +147,11 @@ function useSetup(dispatch: Dispatch) { // TODO - remove? useWebviewListener("submitMessage", async (data) => { - streamResponse( - data.message, - { useCodebase: false, noContext: true }, - ideMessenger, + dispatch( + streamResponseThunk({ + editorState: data.message, + modifiers: { useCodebase: false, noContext: true }, + }), ); }); @@ -178,8 +175,6 @@ function useSetup(dispatch: Dispatch) { }, [defaultModelTitle], ); - - } export default useSetup; diff --git a/gui/src/pages/Edit/Edit.tsx b/gui/src/pages/Edit/Edit.tsx index c5ef23731..0b5ab505a 100644 --- a/gui/src/pages/Edit/Edit.tsx +++ b/gui/src/pages/Edit/Edit.tsx @@ -3,7 +3,7 @@ import { Editor, JSONContent } from "@tiptap/core"; import { InputModifiers, RangeInFileWithContents } from "core"; import { stripImages } from "core/util/messageContent"; import { useCallback, useContext, useEffect } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; @@ -12,13 +12,13 @@ import TipTapEditor from "../../components/mainInput/TipTapEditor"; import StepContainer from "../../components/StepContainer"; import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import useChatHandler from "../../hooks/useChatHandler"; import { clearCodeToEdit, setEditDone, submitEdit, } from "../../redux/slices/editModeState"; -import { RootState } from "../../redux/store"; +import { RootState, useAppDispatch } from "../../redux/store"; +import { streamResponseThunk } from "../../redux/thunks/streamResponse"; import CodeToEdit from "./CodeToEdit"; import getMultifileEditPrompt from "./getMultifileEditPrompt"; @@ -35,10 +35,9 @@ const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [ ]; export default function Edit() { - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); const navigate = useNavigate(); const ideMessenger = useContext(IdeMessengerContext); - const { streamResponse } = useChatHandler(dispatch, ideMessenger); const editModeState = useSelector((state: RootState) => state.editModeState); const availableContextProviders = useSelector( (store: RootState) => store.state.config.contextProviders, @@ -138,12 +137,12 @@ export default function Edit() { } else { const promptPreamble = getMultifileEditPrompt(editModeState.codeToEdit); - streamResponse( - editorState, - modifiers, - ideMessenger, - undefined, - promptPreamble, + dispatch( + streamResponseThunk({ + editorState, + modifiers, + promptPreamble, + }), ); } } @@ -184,11 +183,12 @@ export default function Edit() { {item.message.role === "user" ? ( { - streamResponse( - editorState, - modifiers, - ideMessenger, - index, + dispatch( + streamResponseThunk({ + editorState, + modifiers, + index, + }), ); }} isLastUserInput={isLastUserInput(index)} diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 00901f1ae..208cdf4ec 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -9,7 +9,7 @@ import { InputModifiers, ToolCallState } from "core"; import { usePostHog } from "posthog-js/react"; import { useCallback, useContext, useEffect, useRef, useState } from "react"; import { ErrorBoundary } from "react-error-boundary"; -import { useDispatch, useSelector } from "react-redux"; +import { useSelector } from "react-redux"; import styled from "styled-components"; import { Button, @@ -30,7 +30,6 @@ import { } from "../../components/OnboardingCard"; import StepContainer from "../../components/StepContainer"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import useChatHandler from "../../hooks/useChatHandler"; import useHistory from "../../hooks/useHistory"; import { useTutorialCard } from "../../hooks/useTutorialCard"; import { useWebviewListener } from "../../hooks/useWebviewListener"; @@ -46,7 +45,8 @@ import { setDialogMessage, setShowDialog, } from "../../redux/slices/uiStateSlice"; -import { RootState } from "../../redux/store"; +import { RootState, useAppDispatch } from "../../redux/store"; +import { streamResponseThunk } from "../../redux/thunks/streamResponse"; import { getFontSize, getMetaKeyLabel, @@ -117,9 +117,8 @@ function fallbackRender({ error, resetErrorBoundary }: any) { export function Chat() { const posthog = usePostHog(); - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); - const { streamResponse } = useChatHandler(dispatch, ideMessenger); const onboardingCard = useOnboardingCard(); const { showTutorialCard, closeTutorialCard } = useTutorialCard(); const defaultModel = useSelector(defaultModelSelector); @@ -219,7 +218,7 @@ export function Chat() { } } - streamResponse(editorState, modifiers, ideMessenger); + dispatch(streamResponseThunk({ editorState, modifiers })); // Increment localstorage counter for popup const currentCount = getLocalStorage("mainTextEntryCounter"); @@ -291,7 +290,7 @@ export function Chat() { setLocalStorage("mainTextEntryCounter", 1); } }, - [state.history, defaultModel, state, streamResponse], + [state.history, defaultModel, state], ); useWebviewListener( @@ -340,7 +339,9 @@ export function Chat() { {item.message.role === "user" ? ( { - streamResponse(editorState, modifiers, ideMessenger, index); + dispatch( + streamResponseThunk({ editorState, modifiers, index }), + ); }} isLastUserInput={isLastUserInput(index)} isMainInput={false} diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx index 8b371bf11..d447b7fef 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx @@ -1,5 +1,5 @@ import { useContext } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useSelector } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, @@ -9,9 +9,11 @@ import { } from "../../../components"; import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import useChatHandler from "../../../hooks/useChatHandler"; import { selectCurrentToolCall } from "../../../redux/selectors/selectCurrentToolCall"; import { cancelToolCall } from "../../../redux/slices/stateSlice"; +import { useAppDispatch } from "../../../redux/store"; +import { callTool } from "../../../redux/thunks/callTool"; +import { streamResponseAfterToolCall } from "../../../redux/thunks/streamResponseAfterToolCall"; const ButtonContainer = styled.div` display: flex; @@ -51,26 +53,26 @@ const RejectButton = styled(Button)` interface ToolCallButtonsProps {} export function ToolCallButtons(props: ToolCallButtonsProps) { - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); const toolCallState = useSelector(selectCurrentToolCall); const ideMessenger = useContext(IdeMessengerContext); - const { streamResponseAfterToolCall, callTool } = useChatHandler( - dispatch, - ideMessenger, - ); - async function cancelTool() { dispatch(cancelToolCall()); - streamResponseAfterToolCall(toolCallState.toolCallId, [ - { - name: "Cancelled", - description: "Cancelled", - content: - "This tool call was cancelled by the user. You should try something else, likely just chatting instead of using another tool.", - }, - ]); + dispatch( + streamResponseAfterToolCall({ + toolCallId: toolCallState.toolCallId, + toolOutput: [ + { + name: "Cancelled", + description: "Cancelled", + content: + "This tool call was cancelled by the user. You should try something else, likely just chatting instead of using another tool.", + }, + ], + }), + ); } if (!toolCallState) { @@ -93,7 +95,9 @@ export function ToolCallButtons(props: ToolCallButtonsProps) { ) : toolCallState.status === "generated" ? ( <> Cancel - Continue + dispatch(callTool())}> + Continue + ) : toolCallState.status === "calling" ? (
diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 9aa05d02a..e8dcfdb63 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -1,4 +1,9 @@ -import { PayloadAction, createSlice } from "@reduxjs/toolkit"; +import { + ActionReducerMapBuilder, + AsyncThunk, + PayloadAction, + createSlice, +} from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/react"; import { ApplyState, @@ -16,6 +21,7 @@ import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { renderChatMessage } from "core/util/messageContent"; import { v4 as uuidv4, v4 } from "uuid"; +import { streamResponseThunk } from "../thunks/streamResponse"; import { findCurrentToolCall } from "../util"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. @@ -518,8 +524,23 @@ export const stateSlice = createSlice({ }; }, }, + + extraReducers: (builder) => { + addPassthroughCases(builder, [streamResponseThunk]); + }, }); +function addPassthroughCases( + builder: ActionReducerMapBuilder, + thunks: AsyncThunk[], +) { + thunks.forEach((thunk) => { + builder + .addCase(thunk.fulfilled, (state, action) => {}) + .addCase(thunk.rejected, (state, action) => {}) + .addCase(thunk.pending, (state, action) => {}); + }); +} export const { updateFileSymbols, setContextItemsAtIndex, diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 725d88c01..e0a6bfc4f 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -5,10 +5,12 @@ import serverStateReducer from "./slices/serverStateReducer"; import stateReducer from "./slices/stateSlice"; import uiStateReducer from "./slices/uiStateSlice"; +import { useDispatch } from "react-redux"; import { createTransform, persistReducer, persistStore } from "redux-persist"; import { createFilter } from "redux-persist-transform-filter"; import autoMergeLevel2 from "redux-persist/lib/stateReconciler/autoMergeLevel2"; import storage from "redux-persist/lib/storage"; +import { IdeMessenger, IIdeMessenger } from "../context/IdeMessenger"; import editModeStateReducer from "./slices/editModeState"; export interface ChatMessage { role: "system" | "user" | "assistant"; @@ -24,8 +26,6 @@ const rootReducer = combineReducers({ editModeState: editModeStateReducer, }); -export type RootState = ReturnType; - const windowIDTransform = (windowID: string) => createTransform( // transform state on its way to being serialized and persisted. @@ -56,15 +56,32 @@ const persistedReducer = persistReducer(persistConfig, rootReducer); export function setupStore() { return configureStore({ - reducer: persistedReducer, + // persistedReducer causes type errors with async thunks + reducer: persistedReducer as unknown as typeof rootReducer, // reducer: rootReducer, middleware: (getDefaultMiddleware) => getDefaultMiddleware({ serializableCheck: false, + thunk: { + extraArgument: { + ideMessenger: new IdeMessenger(), + }, + }, }), }); } +export type ThunkApiType = { + state: RootState; + extra: { ideMessenger: IIdeMessenger }; +}; + export const store = setupStore(); +export type RootState = ReturnType; + +export type AppDispatch = typeof store.dispatch; + +export const useAppDispatch = () => useDispatch(); + export const persistor = persistStore(store); diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts new file mode 100644 index 000000000..936b57cf4 --- /dev/null +++ b/gui/src/redux/thunks/callTool.ts @@ -0,0 +1,50 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; +import { setCalling } from "../slices/stateSlice"; +import { ThunkApiType } from "../store"; +import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; + +export const callTool = createAsyncThunk( + "chat/callTool", + async (_, { dispatch, extra, getState }) => { + const state = getState(); + const toolCallState = selectCurrentToolCall(state); + + console.log("calling tool", toolCallState.toolCall); + if (!toolCallState) { + return; + } + + // If it goes "generated" -> "calling" -> "done" really quickly + // we don't want an abrupt flash so just skip "calling" + let setCallingState = true; + + const timer = setTimeout(() => { + if (setCallingState) { + dispatch(setCalling()); + } + }, 800); + + if (toolCallState.status !== "generated") { + return; + } + + const result = await extra.ideMessenger.request("tools/call", { + toolCall: toolCallState.toolCall, + }); + + setCallingState = false; + clearTimeout(timer); + + if (result.status === "success") { + const contextItems = result.content.contextItems; + // Send to the LLM to continue the conversation + dispatch( + streamResponseAfterToolCall({ + toolCallId: toolCallState.toolCall.id, + toolOutput: contextItems, + }), + ); + } + }, +); diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts new file mode 100644 index 000000000..df3f2b218 --- /dev/null +++ b/gui/src/redux/thunks/gatherContext.ts @@ -0,0 +1,117 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { JSONContent } from "@tiptap/core"; +import { + ContextItemWithId, + InputModifiers, + MessageContent, + RangeInFile, +} from "core"; +import { getBasename, getRelativePath } from "core/util"; +import resolveEditorContent, { + hasSlashCommandOrContextProvider, +} from "../../components/mainInput/resolveInput"; +import { updateFileSymbolsFromContextItems } from "../../util/symbols"; +import { defaultModelSelector } from "../selectors/modelSelectors"; +import { setIsGatheringContext } from "../slices/stateSlice"; +import { ThunkApiType } from "../store"; + +export const gatherContext = createAsyncThunk< + { + selectedContextItems: ContextItemWithId[]; + selectedCode: RangeInFile[]; + content: MessageContent; + }, + { + editorState: JSONContent; + modifiers: InputModifiers; + promptPreamble?: string; + }, + ThunkApiType +>( + "chat/gatherContext", + async ( + { modifiers, editorState, promptPreamble }, + { dispatch, extra, getState }, + ) => { + const state = getState(); + const defaultModel = defaultModelSelector(state); + const defaultContextProviders = + state.state.config.experimental?.defaultContext ?? []; + + // Resolve context providers and construct new history + const shouldGatherContext = + modifiers.useCodebase || hasSlashCommandOrContextProvider(editorState); + + if (shouldGatherContext) { + dispatch( + setIsGatheringContext({ + isGathering: true, + gatheringMessage: "Gathering Context", + }), + ); + } + + let [selectedContextItems, selectedCode, content] = + await resolveEditorContent( + editorState, + modifiers, + extra.ideMessenger, + defaultContextProviders, + dispatch, + ); + + // Automatically use currently open file + if (!modifiers.noContext) { + const usingFreeTrial = defaultModel?.provider === "free-trial"; + + const currentFile = await extra.ideMessenger.ide.getCurrentFile(); + if (currentFile) { + let currentFileContents = currentFile.contents; + if (usingFreeTrial) { + currentFileContents = currentFile.contents + .split("\n") + .slice(0, 1000) + .join("\n"); + } + if ( + !selectedContextItems.find( + (item) => item.uri?.value === currentFile.path, + ) + ) { + // don't add the file if it's already in the context items + selectedContextItems.unshift({ + content: `The following file is currently open. Don't reference it if it's not relevant to the user's message.\n\n\`\`\`${getRelativePath( + currentFile.path, + await extra.ideMessenger.ide.getWorkspaceDirs(), + )}\n${currentFileContents}\n\`\`\``, + name: `Active file: ${getBasename(currentFile.path)}`, + description: currentFile.path, + id: { + itemId: currentFile.path, + providerTitle: "file", + }, + uri: { + type: "file", + value: currentFile.path, + }, + }); + } + } + } + + await updateFileSymbolsFromContextItems( + selectedContextItems, + extra.ideMessenger, + dispatch, + ); + + if (promptPreamble) { + typeof content === "string" + ? (content += promptPreamble) + : (content.at(-1).text += promptPreamble); + } + + // dispatch(addContextItems(contextItems)); + return { selectedContextItems, selectedCode, content }; + }, +); diff --git a/gui/src/redux/thunks/handleErrors.ts b/gui/src/redux/thunks/handleErrors.ts new file mode 100644 index 000000000..25f3066e7 --- /dev/null +++ b/gui/src/redux/thunks/handleErrors.ts @@ -0,0 +1,22 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { setInactive } from "../slices/stateSlice"; +import { ThunkApiType } from "../store"; + +export const handleErrors = createAsyncThunk< + void, + () => Promise, + ThunkApiType +>("chat/handleErrors", async (runStream, { dispatch, extra }) => { + try { + await runStream(); + } catch (e: any) { + console.debug("Error streaming response: ", e); + extra.ideMessenger.post("showToast", [ + "error", + `Error streaming response: ${e.message}`, + ]); + } finally { + dispatch(setInactive()); + // triggerSave(!save); TODO + } +}); diff --git a/gui/src/redux/thunks/resetStateForNewMessage.ts b/gui/src/redux/thunks/resetStateForNewMessage.ts new file mode 100644 index 000000000..e7f534e42 --- /dev/null +++ b/gui/src/redux/thunks/resetStateForNewMessage.ts @@ -0,0 +1,11 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { resetNextCodeBlockToApplyIndex } from "../slices/stateSlice"; +import { ThunkApiType } from "../store"; + +export const resetStateForNewMessage = createAsyncThunk< + void, + undefined, + ThunkApiType +>("chat/resetStateForNewMessage", async (_, { dispatch }) => { + dispatch(resetNextCodeBlockToApplyIndex()); +}); diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts new file mode 100644 index 000000000..e793fe96b --- /dev/null +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -0,0 +1,79 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { ChatMessage, PromptLog } from "core"; +import { allTools } from "core/tools"; +import { defaultModelSelector } from "../selectors/modelSelectors"; +import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; +import { + abortStream, + addPromptCompletionPair, + clearLastEmptyResponse, + streamUpdate, +} from "../slices/stateSlice"; +import { ThunkApiType } from "../store"; +import { callTool } from "./callTool"; + +export const streamNormalInput = createAsyncThunk< + void, + ChatMessage[], + ThunkApiType +>("chat/streamNormalInput", async (messages, { dispatch, extra, getState }) => { + try { + // Gather state + const state = getState(); + const defaultModel = defaultModelSelector(state); + const toolSettings = state.uiState.toolSettings; + const streamAborter = state.state.streamAborter; + const useTools = state.uiState.useTools; + + if (!defaultModel) { + throw new Error("Default model not defined"); + } + + // Send request + const gen = extra.ideMessenger.llmStreamChat( + defaultModel.title, + streamAborter.signal, + messages, + { + tools: useTools + ? Object.keys(toolSettings) + .filter((tool) => toolSettings[tool] !== "disabled") + .map((toolName) => + allTools.find((tool) => tool.function.name === toolName), + ) + : undefined, + }, + ); + + // Stream response + let next = await gen.next(); + while (!next.done) { + if (!getState().state.active) { + dispatch(abortStream()); + break; + } + dispatch(streamUpdate(next.value as ChatMessage)); + next = await gen.next(); + } + + // Attach prompt log + let returnVal = next.value as PromptLog; + if (returnVal) { + dispatch(addPromptCompletionPair([returnVal])); + } + + // If it's a tool call that is automatically accepted, we should call it + const toolCallState = selectCurrentToolCall(getState()); + if ( + toolCallState && + toolCallState.status === "generated" && + toolSettings[toolCallState.toolCall.function.name] === + "allowedWithoutPermission" + ) { + await dispatch(callTool()); + } + } catch (e) { + // If there's an error, we should clear the response so there aren't two input boxes + dispatch(clearLastEmptyResponse()); + } +}); diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts new file mode 100644 index 000000000..c1f6ba4d8 --- /dev/null +++ b/gui/src/redux/thunks/streamResponse.ts @@ -0,0 +1,157 @@ +import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; +import { JSONContent } from "@tiptap/core"; +import { + ChatHistoryItem, + ChatMessage, + InputModifiers, + MessageContent, + SlashCommandDescription, +} from "core"; +import { constructMessages } from "core/llm/constructMessages"; +import { renderChatMessage } from "core/util/messageContent"; +import posthog from "posthog-js"; +import { defaultModelSelector } from "../selectors/modelSelectors"; +import { + initNewActiveMessage, + resubmitAtIndex, + setCurCheckpointIndex, + setMessageAtIndex, +} from "../slices/stateSlice"; +import { ThunkApiType } from "../store"; +import { gatherContext } from "./gatherContext"; +import { handleErrors } from "./handleErrors"; +import { resetStateForNewMessage } from "./resetStateForNewMessage"; +import { streamNormalInput } from "./streamNormalInput"; +import { streamSlashCommand } from "./streamSlashCommand"; + +const getSlashCommandForInput = ( + input: MessageContent, + slashCommands: SlashCommandDescription[], +): [SlashCommandDescription, string] | undefined => { + let slashCommand: SlashCommandDescription | undefined; + let slashCommandName: string | undefined; + + let lastText = + typeof input === "string" + ? input + : input.filter((part) => part.type === "text").slice(-1)[0]?.text || ""; + + if (lastText.startsWith("/")) { + slashCommandName = lastText.split(" ")[0].substring(1); + slashCommand = slashCommands.find( + (command) => command.name === slashCommandName, + ); + } + if (!slashCommand || !slashCommandName) { + return undefined; + } + + // Convert to actual slash command object with runnable function + return [slashCommand, renderChatMessage({ role: "user", content: input })]; +}; + +export const streamResponseThunk = createAsyncThunk< + void, + { + editorState: JSONContent; + modifiers: InputModifiers; + index?: number; + promptPreamble?: string; + }, + ThunkApiType +>( + "chat/streamResponse", + async ( + { editorState, modifiers, index, promptPreamble }, + { dispatch, extra, getState }, + ) => { + await dispatch( + handleErrors(async () => { + const state = getState(); + const defaultModel = defaultModelSelector(state); + const slashCommands = state.state.config.slashCommands || []; + const inputIndex = index ?? state.state.history.length; + + if (typeof index === "number") { + dispatch(resubmitAtIndex({ index, editorState })); + } else { + dispatch(initNewActiveMessage({ editorState })); + } + + resetStateForNewMessage(); + + if (index) { + dispatch(setCurCheckpointIndex(Math.floor(index / 2))); + } + + const result = await dispatch( + gatherContext({ + editorState, + modifiers, + promptPreamble, + }), + ); + const unwrapped = unwrapResult(result); + const { selectedContextItems, selectedCode, content } = unwrapped; + + // Add the message to the history + const message: ChatMessage = { + role: "user", + content, + }; + const historyItem: ChatHistoryItem = { + message, + contextItems: selectedContextItems, + editorState, + }; + + dispatch( + setMessageAtIndex({ + message, + index: inputIndex, + contextItems: selectedContextItems, + }), + ); + + // Construct messages from updated history + const updatedHistory = getState().state.history; + const messages = constructMessages(updatedHistory, defaultModel.model); + + posthog.capture("step run", { + step_name: "User Input", + params: {}, + }); + posthog.capture("userInput", {}); + + // Determine if the input is a slash command + let commandAndInput = getSlashCommandForInput(content, slashCommands); + + if (!commandAndInput) { + await dispatch(streamNormalInput(messages)); + } else { + const [slashCommand, commandInput] = commandAndInput; + let updatedContextItems = []; + posthog.capture("step run", { + step_name: slashCommand.name, + params: {}, + }); + + // if (slashCommand.name === "multifile-edit") { + // dispatch(setIsInMultifileEdit(true)); + // } + + await dispatch( + streamSlashCommand({ + messages, + slashCommand, + input: commandInput, + historyIndex: inputIndex, + selectedCode, + contextItems: updatedContextItems, + }), + ); + } + }), + ); + }, +); diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts new file mode 100644 index 000000000..a14e97d68 --- /dev/null +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -0,0 +1,75 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { ChatMessage, ContextItem } from "core"; +import { constructMessages } from "core/llm/constructMessages"; +import { renderContextItems } from "core/util/messageContent"; +import { defaultModelSelector } from "../selectors/modelSelectors"; +import { + acceptToolCall, + addContextItemsAtIndex, + setActive, + streamUpdate, +} from "../slices/stateSlice"; +import { ThunkApiType } from "../store"; +import { handleErrors } from "./handleErrors"; +import { resetStateForNewMessage } from "./resetStateForNewMessage"; +import { streamNormalInput } from "./streamNormalInput"; + +export const streamResponseAfterToolCall = createAsyncThunk< + void, + { + toolCallId: string; + toolOutput: ContextItem[]; + }, + ThunkApiType +>( + "chat/streamAfterToolCall", + async ({ toolCallId, toolOutput }, { dispatch, getState, extra }) => { + await dispatch( + handleErrors(async () => { + const state = getState(); + const initialHistory = state.state.history; + const defaultModel = defaultModelSelector(state); + + resetStateForNewMessage(); + + dispatch(acceptToolCall()); + await new Promise((resolve) => setTimeout(resolve, 0)); + + const newMessage: ChatMessage = { + role: "tool", + content: renderContextItems(toolOutput), + toolCallId, + }; + + dispatch(streamUpdate(newMessage)); + dispatch( + addContextItemsAtIndex({ + index: initialHistory.length, + contextItems: toolOutput.map((contextItem) => ({ + ...contextItem, + id: { + providerTitle: "toolCall", + itemId: toolCallId, + }, + })), + }), + ); + + dispatch(setActive()); + + const updatedHistory = getState().state.history; + const messages = constructMessages( + [ + ...updatedHistory, + { + message: newMessage, + contextItems: [], + }, + ], + defaultModel.model, + ); + await dispatch(streamNormalInput(messages)); + }), + ); + }, +); diff --git a/gui/src/redux/thunks/streamSlashCommand.ts b/gui/src/redux/thunks/streamSlashCommand.ts new file mode 100644 index 000000000..4b6c71791 --- /dev/null +++ b/gui/src/redux/thunks/streamSlashCommand.ts @@ -0,0 +1,71 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { + ChatMessage, + ContextItemWithId, + RangeInFile, + SlashCommandDescription, +} from "core"; +import { defaultModelSelector } from "../selectors/modelSelectors"; +import { abortStream, streamUpdate } from "../slices/stateSlice"; +import { ThunkApiType } from "../store"; + +export const streamSlashCommand = createAsyncThunk< + void, + { + messages: ChatMessage[]; + slashCommand: SlashCommandDescription; + input: string; + historyIndex: number; + selectedCode: RangeInFile[]; + contextItems: ContextItemWithId[]; + }, + ThunkApiType +>( + "chat/streamSlashCommand", + async ( + { messages, selectedCode, slashCommand, input, historyIndex, contextItems }, + { dispatch, getState, extra }, + ) => { + const state = getState(); + const defaultModel = defaultModelSelector(state); + const active = state.state.active; + const streamAborter = state.state.streamAborter; + + if (!defaultModel) { + throw new Error("Default model not defined"); + } + + const modelTitle = defaultModel.title; + + const checkActiveInterval = setInterval(() => { + if (!active) { + dispatch(abortStream()); + clearInterval(checkActiveInterval); + } + }, 100); + + for await (const update of extra.ideMessenger.streamRequest( + "command/run", + { + input, + history: messages, + modelTitle, + slashCommandName: slashCommand.name, + contextItems, + params: slashCommand.params, + historyIndex, + selectedCode, + }, + streamAborter.signal, + )) { + if (!getState().state.active) { + dispatch(abortStream()); + break; + } + if (typeof update === "string") { + dispatch(streamUpdate(update)); + } + } + clearInterval(checkActiveInterval); + }, +); From 6ff5279b02f0eb34aa36d087383183c607adb09f Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 24 Nov 2024 17:59:31 -0800 Subject: [PATCH 057/105] WIP --- core/index.d.ts | 1 + core/llm/constructMessages.ts | 9 ++++ .../StepContainer/ResponseActions.tsx | 2 +- .../StepContainer/StepContainer.tsx | 30 ++++++++----- .../markdown/StyledMarkdownPreview.tsx | 10 ++--- gui/src/pages/gui/Chat.tsx | 2 +- gui/src/pages/gui/ToolCallDiv/CreateFile.tsx | 11 ++--- .../FunctionSpecificToolCallDiv.tsx | 13 ++++-- .../gui/ToolCallDiv/ToolCallButtonsDiv.tsx | 13 +----- gui/src/pages/gui/ToolCallDiv/index.tsx | 42 ++++++------------- gui/src/redux/slices/stateSlice.ts | 28 +++++++++---- gui/src/redux/thunks/callTool.ts | 14 ------- gui/src/redux/thunks/streamNormalInput.ts | 15 ++++--- .../thunks/streamResponseAfterToolCall.ts | 8 +--- 14 files changed, 96 insertions(+), 102 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index a4f76ead0..46454c603 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -403,6 +403,7 @@ interface ToolCallState { toolCallId: string; toolCall: ToolCall; status: ToolStatus; + parsedArgs: any; } export interface ChatHistoryItem { diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 3af1b1a4f..b9e196b02 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -74,6 +74,9 @@ function constructSystemPrompt(model: string): string | null { return null; } +const CANCELED_TOOL_CALL_MESSAGE = + "This tool call was cancelled by the user. You should clarify next steps, as they don't wish for you to use this tool."; + export function constructMessages( history: ChatHistory, model: string, @@ -104,6 +107,12 @@ export function constructMessages( ...historyItem.message, content, }); + } else if (historyItem.toolCallState?.status === "canceled") { + // Canceled tool call + msgs.push({ + ...historyItem.message, + content: CANCELED_TOOL_CALL_MESSAGE, + }); } else { msgs.push(historyItem.message); } diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index 3769907ef..af8623939 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -37,7 +37,7 @@ export default function ResponseActions({ } return ( -
+
{shouldHideActions || ( <> {isTruncated && ( diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index 8c28d5ddd..4ee912901 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -35,8 +35,16 @@ export default function StepContainer(props: StepContainerProps) { const isInEditMode = useSelector( (store: RootState) => store.editModeState.isInEditMode, ); + + const historyItemAfterThis = useSelector( + (store: RootState) => store.state.history[props.index + 1], + ); + const uiConfig = useUIConfig(); - const shouldHideActions = active && props.isLast; + const shouldHideActions = + (active && props.isLast) || + historyItemAfterThis?.message.role === "assistant"; + // const isStepAheadOfCurCheckpoint = // isInEditMode && Math.floor(props.index / 2) > curCheckpointIndex; @@ -96,15 +104,17 @@ export default function StepContainer(props: StepContainerProps) { )} {/* We want to occupy space in the DOM regardless of whether the actions are visible to avoid jank on */} -
- +
+ {shouldHideActions ? null : ( + + )}
); diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 640f80a1d..3d794d4ce 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,4 +1,7 @@ +import { ContextItemWithId, SymbolWithRange } from "core"; +import { ctxItemToRifWithContents } from "core/commands/util"; import { memo, useEffect, useRef } from "react"; +import { useSelector } from "react-redux"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; @@ -11,19 +14,16 @@ import { vscEditorBackground, vscForeground, } from ".."; +import { RootState } from "../../redux/store"; import { getFontSize, isJetBrains } from "../../util"; import FilenameLink from "./FilenameLink"; import "./katex.css"; import "./markdown.css"; import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; import StepContainerPreToolbar from "./StepContainerPreToolbar"; +import SymbolLink from "./SymbolLink"; import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; import { patchNestedMarkdown } from "./utils/patchNestedMarkdown"; -import { RootState } from "../../redux/store"; -import { ContextItemWithId, SymbolWithRange } from "core"; -import SymbolLink from "./SymbolLink"; -import { useSelector } from "react-redux"; -import { ctxItemToRifWithContents } from "core/commands/util"; const StyledMarkdown = styled.div<{ fontSize?: number; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 208cdf4ec..cbef496e2 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -360,8 +360,8 @@ export function Chat() { {item.message.toolCalls?.map((toolCall) => { return ( ); })} diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index 260266c5f..59eec0c97 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -1,16 +1,17 @@ +import { getMarkdownLanguageTagForFile } from "core/util"; +import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; + interface CreateFileToolCallProps { filepath: string; fileContents: string; } export function CreateFile(props: CreateFileToolCallProps) { + const src = `\`\`\`${getMarkdownLanguageTagForFile(props.filepath ?? "javascript")} ${props.filepath}\n${props.fileContents ?? ""}\n\`\`\``; + return ( <> - {props.fileContents} - {/* */} + ); } diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index db72817c9..68fdeb682 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -1,10 +1,15 @@ -import { ToolCall } from "core"; -import { incrementalParseJson } from "core/util/incrementalParseJson"; +import { ToolCall, ToolCallState } from "core"; import { CreateFile } from "./CreateFile"; import { RunTerminalCommand } from "./RunTerminalCommand"; -function FunctionSpecificToolCallDiv({ toolCall }: { toolCall: ToolCall }) { - const [_, args] = incrementalParseJson(toolCall.function.arguments); +function FunctionSpecificToolCallDiv({ + toolCall, + toolCallState, +}: { + toolCall: ToolCall; + toolCallState: ToolCallState; +}) { + const args = toolCallState.parsedArgs; switch (toolCall.function.name) { case "create_new_file": diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx index d447b7fef..2b6a7fc4f 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx @@ -1,4 +1,3 @@ -import { useContext } from "react"; import { useSelector } from "react-redux"; import styled from "styled-components"; import { @@ -8,7 +7,6 @@ import { vscButtonForeground, } from "../../../components"; import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { selectCurrentToolCall } from "../../../redux/selectors/selectCurrentToolCall"; import { cancelToolCall } from "../../../redux/slices/stateSlice"; import { useAppDispatch } from "../../../redux/store"; @@ -56,21 +54,12 @@ export function ToolCallButtons(props: ToolCallButtonsProps) { const dispatch = useAppDispatch(); const toolCallState = useSelector(selectCurrentToolCall); - const ideMessenger = useContext(IdeMessengerContext); - async function cancelTool() { dispatch(cancelToolCall()); dispatch( streamResponseAfterToolCall({ toolCallId: toolCallState.toolCallId, - toolOutput: [ - { - name: "Cancelled", - description: "Cancelled", - content: - "This tool call was cancelled by the user. You should try something else, likely just chatting instead of using another tool.", - }, - ], + toolOutput: [], }), ); } diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index b53bfa45a..4d6838f26 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -1,53 +1,37 @@ -import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import { ToolCall, ToolStatus } from "core"; -import { incrementalParseJson } from "core/util/incrementalParseJson"; -import { useEffect } from "react"; -import { useDispatch } from "react-redux"; -import { lightGray } from "../../../components"; +import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import { ToolCall, ToolCallState, ToolStatus } from "core"; import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner"; -import { setGeneratedOutput } from "../../../redux/slices/stateSlice"; import FunctionSpecificToolCallDiv from "./FunctionSpecificToolCallDiv"; import { ThreadDiv } from "./ThreadDiv"; interface ToolCallDivProps { toolCall: ToolCall; - status: ToolStatus; + toolCallState: ToolCallState; } export function ToolCallDiv(props: ToolCallDivProps) { - const dispatch = useDispatch(); - - useEffect(() => { - // Once the JSON can successfully parse, then set state to "generated" - if (props.toolCall.function.arguments.length === 0) { - dispatch(setGeneratedOutput(props.toolCall)); - return; - } - - const [done, j] = incrementalParseJson(props.toolCall.function.arguments); - if (done) { - dispatch(setGeneratedOutput(props.toolCall)); - } - }, [props.toolCall.function.arguments]); - function getIcon(state: ToolStatus) { switch (state) { case "generating": + case "calling": + case "generated": return ; case "done": return ; - case "calling": - return ; case "canceled": return ; - case "generated": - return ; } } return ( - - + + ); } diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index e8dcfdb63..d0f3e0790 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -19,6 +19,7 @@ import { } from "core"; import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; +import { incrementalParseJson } from "core/util/incrementalParseJson"; import { renderChatMessage } from "core/util/messageContent"; import { v4 as uuidv4, v4 } from "uuid"; import { streamResponseThunk } from "../thunks/streamResponse"; @@ -319,10 +320,14 @@ export const stateSlice = createSlice({ }; if (action.payload.role === "assistant" && action.payload.toolCalls) { + const [_, parsedArgs] = incrementalParseJson( + action.payload.toolCalls[0].function.arguments, + ); historyItem.toolCallState = { status: "generating", toolCall: action.payload.toolCalls[0] as ToolCall, toolCallId: action.payload.toolCalls[0].id, + parsedArgs, }; } @@ -346,6 +351,14 @@ export const stateSlice = createSlice({ } else { msg.toolCalls[i].function.arguments += toolCall.function.arguments; + + const [_, parsedArgs] = incrementalParseJson( + msg.toolCalls[i].function.arguments, + ); + + state.history[ + state.history.length - 1 + ].toolCallState.parsedArgs = parsedArgs; } }); } @@ -462,6 +475,12 @@ export const stateSlice = createSlice({ }, // Related to currentToolCallState + setToolGenerated: (state) => { + const toolCallState = findCurrentToolCall(state.history); + if (!toolCallState) return; + + toolCallState.status = "generated"; + }, cancelToolCall: (state) => { const toolCallState = findCurrentToolCall(state.history); if (!toolCallState) return; @@ -474,13 +493,6 @@ export const stateSlice = createSlice({ toolCallState.status = "done"; }, - setGeneratedOutput: (state, { payload }: PayloadAction) => { - const toolCallState = findCurrentToolCall(state.history); - if (!toolCallState) return; - - toolCallState.toolCall = payload; - toolCallState.status = "generated"; - }, setCalling: (state) => { const toolCallState = findCurrentToolCall(state.history); if (!toolCallState) return; @@ -572,8 +584,8 @@ export const { setIndexingChatPeekHidden, setCalling, cancelToolCall, - setGeneratedOutput, acceptToolCall, + setToolGenerated, } = stateSlice.actions; export default stateSlice.reducer; diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 936b57cf4..f326423aa 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -1,6 +1,5 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; -import { setCalling } from "../slices/stateSlice"; import { ThunkApiType } from "../store"; import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; @@ -15,16 +14,6 @@ export const callTool = createAsyncThunk( return; } - // If it goes "generated" -> "calling" -> "done" really quickly - // we don't want an abrupt flash so just skip "calling" - let setCallingState = true; - - const timer = setTimeout(() => { - if (setCallingState) { - dispatch(setCalling()); - } - }, 800); - if (toolCallState.status !== "generated") { return; } @@ -33,9 +22,6 @@ export const callTool = createAsyncThunk( toolCall: toolCallState.toolCall, }); - setCallingState = false; - clearTimeout(timer); - if (result.status === "success") { const contextItems = result.content.contextItems; // Send to the LLM to continue the conversation diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index e793fe96b..2bb5a160f 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -7,6 +7,7 @@ import { abortStream, addPromptCompletionPair, clearLastEmptyResponse, + setToolGenerated, streamUpdate, } from "../slices/stateSlice"; import { ThunkApiType } from "../store"; @@ -64,13 +65,15 @@ export const streamNormalInput = createAsyncThunk< // If it's a tool call that is automatically accepted, we should call it const toolCallState = selectCurrentToolCall(getState()); - if ( - toolCallState && - toolCallState.status === "generated" && - toolSettings[toolCallState.toolCall.function.name] === + if (toolCallState) { + dispatch(setToolGenerated()); + + if ( + toolSettings[toolCallState.toolCall.function.name] === "allowedWithoutPermission" - ) { - await dispatch(callTool()); + ) { + await dispatch(callTool()); + } } } catch (e) { // If there's an error, we should clear the response so there aren't two input boxes diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index a14e97d68..97f7c15d9 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -59,13 +59,7 @@ export const streamResponseAfterToolCall = createAsyncThunk< const updatedHistory = getState().state.history; const messages = constructMessages( - [ - ...updatedHistory, - { - message: newMessage, - contextItems: [], - }, - ], + [...updatedHistory], defaultModel.model, ); await dispatch(streamNormalInput(messages)); From 73d92d34e81f281652ed0a34ab2c5c8218767192 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 25 Nov 2024 15:08:19 -0800 Subject: [PATCH 058/105] MCP context provider --- .github/workflows/ts-check.yaml | 100 ------------- core/context/providers/MCPContextProvider.ts | 145 +++++++++++++++++++ core/context/providers/index.ts | 2 + core/package-lock.json | 93 ++++++++++++ core/package.json | 1 + docs/docs/customize/context-providers.md | 21 +++ extensions/vscode/package-lock.json | 5 +- gui/package-lock.json | 1 + 8 files changed, 266 insertions(+), 102 deletions(-) delete mode 100644 .github/workflows/ts-check.yaml create mode 100644 core/context/providers/MCPContextProvider.ts diff --git a/.github/workflows/ts-check.yaml b/.github/workflows/ts-check.yaml deleted file mode 100644 index 5f16c406c..000000000 --- a/.github/workflows/ts-check.yaml +++ /dev/null @@ -1,100 +0,0 @@ -name: TypeScript Check - -on: - pull_request: - branches: - - main - -jobs: - tsc-check: - runs-on: ubuntu-latest - - steps: - # 1. Check-out repository - - name: Check-out repository - uses: actions/checkout@v4 - - # 2. Install npm dependencies - - name: Use Node.js from .nvmrc - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - name: Cache root node_modules - uses: actions/cache@v3 - with: - path: node_modules - key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }} - - - name: Cache extension node_modules - uses: actions/cache@v3 - with: - path: extensions/vscode/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }} - - - name: Cache core node_modules - uses: actions/cache@v3 - with: - path: core/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }} - - - name: Cache gui node_modules - uses: actions/cache@v3 - with: - path: gui/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} - - - name: Cache binary node_modules - uses: actions/cache@v3 - with: - path: binary/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} - - - name: Install Root Dependencies - run: | - npm ci - - - name: Install extension Dependencies - run: | - cd extensions/vscode - npm ci - env: - # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 - GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - - - name: Install gui Dependencies - run: | - cd gui - npm ci - - - name: Install Core Dependencies - run: | - cd core - npm ci - - - name: Install Binary Dependencies - run: | - cd binary - npm ci - - - name: tsc core - run: | - cd core - npx tsc --noEmit - npm run lint - - - name: tsc extensions/vscode - run: | - cd extensions/vscode - npx tsc --noEmit - npm run lint - - - name: tsc binary - run: | - cd binary - npx tsc --noEmit - - - name: tsc gui - run: | - cd gui - npx tsc --noEmit diff --git a/core/context/providers/MCPContextProvider.ts b/core/context/providers/MCPContextProvider.ts new file mode 100644 index 000000000..09ef2cfe1 --- /dev/null +++ b/core/context/providers/MCPContextProvider.ts @@ -0,0 +1,145 @@ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; +import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; +import { + ListResourcesResultSchema, + ReadResourceResultSchema, +} from "@modelcontextprotocol/sdk/types.js"; + +import { BaseContextProvider } from "../"; +import { + ContextItem, + ContextProviderDescription, + ContextProviderExtras, + ContextSubmenuItem, + LoadSubmenuItemsArgs, +} from "../../"; + +interface StdioOptions { + type: "stdio"; + command: string; + args: string[]; +} + +interface WebSocketOptions { + type: "websocket"; + url: string; +} + +interface SSEOptions { + type: "sse"; + url: string; +} + +type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions; + +interface MCPContextProviderOptions { + transport: TransportOptions; +} + +class MCPContextProvider extends BaseContextProvider { + static description: ContextProviderDescription = { + title: "mcp", + displayTitle: "MCP", + description: "Model Context Protocol", + type: "submenu", + }; + + private client: Client; + + private constructTransport(options: MCPContextProviderOptions): Transport { + switch (options.transport.type) { + case "stdio": + return new StdioClientTransport({ + command: options.transport.command, + args: options.transport.args, + }); + case "websocket": + return new WebSocketClientTransport(new URL(options.transport.url)); + case "sse": + return new SSEClientTransport(new URL(options.transport.url)); + default: + throw new Error( + `Unsupported transport type: ${(options.transport as any).type}`, + ); + } + } + + private resourcesPromise: Promise; + + constructor(options: MCPContextProviderOptions) { + super(options); + + const transport = this.constructTransport(options); + + this.client = new Client( + { + name: "continue-client", + version: "1.0.0", + }, + { + capabilities: {}, + }, + ); + + let resourcesResolve: (resources: any) => void; + this.resourcesPromise = new Promise((resolve) => { + resourcesResolve = resolve; + }); + + void this.client + .connect(transport) + .then(async () => { + const resources = await this.client.request( + { method: "resources/list" }, + ListResourcesResultSchema, + ); + resourcesResolve(resources.resources); + }) + .catch((error) => { + console.error( + "Error connecting to Model Context Protocol server", + error, + ); + }); + } + + async getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise { + const resourceContent = await this.client.request( + { + method: "resources/read", + params: { + uri: query, + }, + }, + ReadResourceResultSchema, + ); + + return [ + { + name: "1", + description: "text", + content: "resourceContent", + }, + ]; + } + + async loadSubmenuItems( + args: LoadSubmenuItemsArgs, + ): Promise { + const resources = await this.resourcesPromise; + + return resources.map((resource: any) => ({ + title: resource.name, + description: resource.description, + id: resource.uri, + })); + } +} + +export default MCPContextProvider; diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index 316e4936b..f5656832c 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -17,6 +17,7 @@ import GoogleContextProvider from "./GoogleContextProvider"; import GreptileContextProvider from "./GreptileContextProvider"; import HttpContextProvider from "./HttpContextProvider"; import JiraIssuesContextProvider from "./JiraIssuesContextProvider/"; +import MCPContextProvider from "./MCPContextProvider"; import OpenFilesContextProvider from "./OpenFilesContextProvider"; import OSContextProvider from "./OSContextProvider"; import PostgresContextProvider from "./PostgresContextProvider"; @@ -60,6 +61,7 @@ export const Providers: (typeof BaseContextProvider)[] = [ DiscordContextProvider, GreptileContextProvider, WebContextProvider, + MCPContextProvider, ]; export function contextProviderClassFromName( diff --git a/core/package-lock.json b/core/package-lock.json index a53a1a49c..4fa95a1a4 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -14,6 +14,7 @@ "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", "@continuedev/llm-info": "^1.0.2", + "@modelcontextprotocol/sdk": "^1.0.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -4155,6 +4156,16 @@ "win32" ] }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.0.0.tgz", + "integrity": "sha512-mbe0otw8vTtZoL5pVucXAmx6oEC7YjdXBgVeFkJXASu4OAnLkrIeNw9zwzU5CwEp19M54bjOUGcna90Dl/H5Bw==", + "dependencies": { + "content-type": "^1.0.5", + "raw-body": "^3.0.0", + "zod": "^3.23.8" + } + }, "node_modules/@mozilla/readability": { "version": "0.5.0", "resolved": "https://registry.npmjs.org/@mozilla/readability/-/readability-0.5.0.tgz", @@ -6557,6 +6568,14 @@ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/cacache": { "version": "15.3.0", "resolved": "https://registry.npmjs.org/cacache/-/cacache-15.3.0.tgz", @@ -6996,6 +7015,14 @@ "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==" }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -7379,6 +7406,14 @@ "node": ">=0.10" } }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/deprecation": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", @@ -9343,6 +9378,21 @@ "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==", "optional": true }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/http-proxy-agent": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", @@ -13262,6 +13312,20 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/raw-body": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.0.tgz", + "integrity": "sha512-RmkhL8CAyCRPXCE28MMH0z2PNWQBNk2Q09ZdxM9IOOXwxwZbN+qbWaatPkdkWIKL2ZVDImrN/pK5HTRz2PcS4g==", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.6.3", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/rc": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", @@ -13740,6 +13804,11 @@ "node": ">= 0.4" } }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, "node_modules/sharp": { "version": "0.32.6", "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.32.6.tgz", @@ -14134,6 +14203,14 @@ "node": ">=8" } }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/stoppable": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/stoppable/-/stoppable-1.1.0.tgz", @@ -14626,6 +14703,14 @@ "node": ">=8.0" } }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, "node_modules/tough-cookie": { "version": "4.1.4", "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", @@ -15042,6 +15127,14 @@ "node": ">= 4.0.0" } }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/update-browserslist-db": { "version": "1.0.16", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.16.tgz", diff --git a/core/package.json b/core/package.json index 91652280a..cc3ead1a2 100644 --- a/core/package.json +++ b/core/package.json @@ -45,6 +45,7 @@ "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", "@continuedev/llm-info": "^1.0.2", + "@modelcontextprotocol/sdk": "^1.0.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index a423ff4dc..b7ecea320 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -495,6 +495,27 @@ Reference the architecture and platform of your current operating system. } ``` +### `@Model Context Protocol` + +The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the `"mcp"` context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure the context provider in `config.json` like this: + +```json +{ + "contextProviders": [ + { + "name": "mcp", + "params": { + "transport": { + "type": "stdio", + "command": "uvx", + "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] + } + } + } + ] +} +``` + ### `@HTTP` The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems. diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 8d680fb94..ab512a42b 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.233", + "version": "0.9.234", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.233", + "version": "0.9.234", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -99,6 +99,7 @@ "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", "@continuedev/llm-info": "^1.0.2", + "@modelcontextprotocol/sdk": "^1.0.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", diff --git a/gui/package-lock.json b/gui/package-lock.json index 1a9e4fe3f..ef807f807 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -101,6 +101,7 @@ "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", "@continuedev/llm-info": "^1.0.2", + "@modelcontextprotocol/sdk": "^1.0.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", From d9b55400ba08c5ca3fc8d4c4ea445eee22017124 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 26 Nov 2024 13:40:21 -0800 Subject: [PATCH 059/105] merge stash --- gui/src/redux/selectors/selectLastToolCall.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 gui/src/redux/selectors/selectLastToolCall.ts diff --git a/gui/src/redux/selectors/selectLastToolCall.ts b/gui/src/redux/selectors/selectLastToolCall.ts new file mode 100644 index 000000000..610a03b4d --- /dev/null +++ b/gui/src/redux/selectors/selectLastToolCall.ts @@ -0,0 +1,15 @@ +import { createSelector } from "@reduxjs/toolkit"; +import { ToolCallState } from "core"; +import { RootState } from "../store"; + +export const selectLastToolCall = createSelector( + [(store: RootState) => store.state.history], + (history): ToolCallState | null => { + const lastToolCallHistoryItem = history.findLast( + (item) => + item.message.role === "assistant" && item.message.toolCalls?.length, + ); + if (!lastToolCallHistoryItem) return null; + return lastToolCallHistoryItem.toolCallState; + }, +); From 47c6233a226746758b9d91a57ae3343da3763568 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 26 Nov 2024 13:57:58 -0800 Subject: [PATCH 060/105] don't persist editModeState --- gui/src/redux/store.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index e0a6bfc4f..a594b30d5 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -40,6 +40,8 @@ const windowIDTransform = (windowID: string) => const saveSubsetFilters = [ createFilter("state", ["history", "sessionId", "defaultModelTitle"]), + // Don't persist any of the edit state for now + createFilter("editModeState", []), ]; const persistConfig = { From e6e682cbeb72c32c06d477fcecf8c6a3a72ef25b Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 27 Nov 2024 15:03:44 -0800 Subject: [PATCH 061/105] improv: set up experiments --- core/autocomplete/CompletionProvider.ts | 7 ++++- core/util/posthog.ts | 37 +++++++++++++++++++++++-- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index f77efae6e..a6e1e551b 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -3,6 +3,7 @@ import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import { IDE, ILLM } from "../index.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; +import { EXPERIMENTS, PosthogFeatureFlag, Telemetry } from "../util/posthog.js"; import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; @@ -66,7 +67,11 @@ export class CompletionProvider { // Set temperature (but don't override) if (llm.completionOptions.temperature === undefined) { - llm.completionOptions.temperature = 0.01; + const value = await Telemetry.getValueForFeatureFlag( + PosthogFeatureFlag.AutocompleteTemperature, + ); + + llm.completionOptions.temperature = value ?? 0.01; } if (llm instanceof OpenAI) { diff --git a/core/util/posthog.ts b/core/util/posthog.ts index 615f77b82..a3f5200c2 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -2,10 +2,28 @@ import os from "node:os"; import { TeamAnalytics } from "../control-plane/TeamAnalytics.js"; import { IdeInfo } from "../index.js"; +import { PostHog } from "posthog-node"; + +export enum PosthogFeatureFlag { + AutocompleteTemperature = "autocomplete-temperature", +} + +export const EXPERIMENTS: { + [key in PosthogFeatureFlag]: { + [key: string]: { value: number }; + }; +} = { + [PosthogFeatureFlag.AutocompleteTemperature]: { + control: { value: 0.01 }, + "0_33": { value: 0.33 }, + "0_66": { value: 0.66 }, + "0_99": { value: 0.99 }, + }, +}; export class Telemetry { // Set to undefined whenever telemetry is disabled - static client: any = undefined; + static client: PostHog | undefined = undefined; static uniqueId = "NOT_UNIQUE"; static os: string | undefined = undefined; static ideInfo: IdeInfo | undefined = undefined; @@ -55,9 +73,9 @@ export class Telemetry { Telemetry.client?.shutdown(); } - static async getTelemetryClient() { + static async getTelemetryClient(): Promise { try { - const { PostHog } = await import("posthog-node"); + // const { PostHog } = await import("posthog-node"); return new PostHog("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", { host: "https://app.posthog.com", }); @@ -77,4 +95,17 @@ export class Telemetry { Telemetry.client = await Telemetry.getTelemetryClient(); } } + + static async getFeatureFlag(flag: PosthogFeatureFlag) { + return Telemetry.client?.getFeatureFlag(flag, Telemetry.uniqueId); + } + + static async getValueForFeatureFlag(flag: PosthogFeatureFlag) { + const userGroup = await Telemetry.getFeatureFlag(flag); + if (typeof userGroup === "string") { + return EXPERIMENTS[flag][userGroup].value; + } + + return undefined; + } } From db03a08e261087cb202db72d2a7d17aece889ced Mon Sep 17 00:00:00 2001 From: kongkong Date: Thu, 28 Nov 2024 12:58:46 +0800 Subject: [PATCH 062/105] refresh opened files when changed --- gui/src/context/SubmenuContextProviders.tsx | 27 +++++++++++++++------ 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx index f080792f5..e6c115446 100644 --- a/gui/src/context/SubmenuContextProviders.tsx +++ b/gui/src/context/SubmenuContextProviders.tsx @@ -41,6 +41,16 @@ const initialContextProviders: SubtextContextProvidersContextType = { const SubmenuContextProvidersContext = createContext(initialContextProviders); +function hasNewOpenFiles(a: { id: string; }[], b: { id: string; }[]) { + if (a.length > b.length) { + return true; + } + for (let i = 0; i < a.length; ++i) { + if (a[i].id !== b[i].id) return true; + } + return false; +} + export const SubmenuContextProvidersProvider = ({ children, }: { @@ -122,18 +132,21 @@ export const SubmenuContextProvidersProvider = ({ [minisearches], ); + const lastOpenFilesRef = useRef([]); useEffect(() => { let isMounted = true; const refreshOpenFiles = async () => { if (!isMounted) return; const openFiles = await getOpenFilesItems(); - setFallbackResults((prev) => ({ - ...prev, - file: deduplicateArray( - [...openFiles, ...(Array.isArray(prev.file) ? prev.file : [])], - (a, b) => a.id === b.id, - ), - })); + if (hasNewOpenFiles(openFiles, lastOpenFilesRef.current)) { + setFallbackResults((prev) => ({ + ...prev, + file: deduplicateArray( + [...openFiles, ...(Array.isArray(prev.file) ? prev.file : [])], + (a, b) => a.id === b.id, + ), + })); + } }; const interval = setInterval(refreshOpenFiles, 2000); From 9c5efe1be0f7ec68d6f4c50915aff9a13672b173 Mon Sep 17 00:00:00 2001 From: kongkong Date: Thu, 28 Nov 2024 13:07:49 +0800 Subject: [PATCH 063/105] fix --- gui/src/context/SubmenuContextProviders.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx index e6c115446..ae34c3adf 100644 --- a/gui/src/context/SubmenuContextProviders.tsx +++ b/gui/src/context/SubmenuContextProviders.tsx @@ -146,6 +146,7 @@ export const SubmenuContextProvidersProvider = ({ (a, b) => a.id === b.id, ), })); + lastOpenFilesRef.current = newOpenFiles; } }; From 7e9902d8b3a31d5a5e0ef47ed81db25fecbc8972 Mon Sep 17 00:00:00 2001 From: kongkong Date: Thu, 28 Nov 2024 13:08:33 +0800 Subject: [PATCH 064/105] Update SubmenuContextProviders.tsx --- gui/src/context/SubmenuContextProviders.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx index ae34c3adf..0e8cb606e 100644 --- a/gui/src/context/SubmenuContextProviders.tsx +++ b/gui/src/context/SubmenuContextProviders.tsx @@ -7,7 +7,7 @@ import { groupByLastNPathParts, } from "core/util"; import MiniSearch, { SearchResult } from "minisearch"; -import { useCallback, useContext, useEffect, useMemo, useState } from "react"; +import { useCallback, useContext, useEffect, useMemo, userRef, useState } from "react"; import { useSelector } from "react-redux"; import { IdeMessengerContext } from "./IdeMessenger"; import { selectContextProviderDescriptions } from "../redux/selectors"; From f25a6355f3fcd1eef72bacb4959d9db525e53dce Mon Sep 17 00:00:00 2001 From: kongkong Date: Thu, 28 Nov 2024 13:09:01 +0800 Subject: [PATCH 065/105] Update SubmenuContextProviders.tsx --- gui/src/context/SubmenuContextProviders.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx index 0e8cb606e..bf9c02376 100644 --- a/gui/src/context/SubmenuContextProviders.tsx +++ b/gui/src/context/SubmenuContextProviders.tsx @@ -7,7 +7,7 @@ import { groupByLastNPathParts, } from "core/util"; import MiniSearch, { SearchResult } from "minisearch"; -import { useCallback, useContext, useEffect, useMemo, userRef, useState } from "react"; +import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; import { useSelector } from "react-redux"; import { IdeMessengerContext } from "./IdeMessenger"; import { selectContextProviderDescriptions } from "../redux/selectors"; From acc283794f5192c54118825e592f1871da47bbe1 Mon Sep 17 00:00:00 2001 From: kongkong Date: Thu, 28 Nov 2024 13:13:23 +0800 Subject: [PATCH 066/105] Update SubmenuContextProviders.tsx --- gui/src/context/SubmenuContextProviders.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx index bf9c02376..d85bd8b0c 100644 --- a/gui/src/context/SubmenuContextProviders.tsx +++ b/gui/src/context/SubmenuContextProviders.tsx @@ -146,7 +146,7 @@ export const SubmenuContextProvidersProvider = ({ (a, b) => a.id === b.id, ), })); - lastOpenFilesRef.current = newOpenFiles; + lastOpenFilesRef.current = openFiles; } }; From 663fc3b354c37b4cebc3bc92d7992f297e2786d9 Mon Sep 17 00:00:00 2001 From: kongkong Date: Thu, 28 Nov 2024 14:23:21 +0800 Subject: [PATCH 067/105] Update SubmenuContextProviders.tsx --- gui/src/context/SubmenuContextProviders.tsx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx index d85bd8b0c..046cec528 100644 --- a/gui/src/context/SubmenuContextProviders.tsx +++ b/gui/src/context/SubmenuContextProviders.tsx @@ -41,12 +41,12 @@ const initialContextProviders: SubtextContextProvidersContextType = { const SubmenuContextProvidersContext = createContext(initialContextProviders); -function hasNewOpenFiles(a: { id: string; }[], b: { id: string; }[]) { - if (a.length > b.length) { +function IsOpenFilesChanged(newFiles: { id: string; }[], oldFiles: { id: string; }[]) { + if (newFiles.length > oldFiles.length) { return true; } - for (let i = 0; i < a.length; ++i) { - if (a[i].id !== b[i].id) return true; + for (let i = 0; i < newFiles.length; ++i) { + if (newFiles[i].id !== oldFiles[i].id) return true; } return false; } @@ -138,7 +138,7 @@ export const SubmenuContextProvidersProvider = ({ const refreshOpenFiles = async () => { if (!isMounted) return; const openFiles = await getOpenFilesItems(); - if (hasNewOpenFiles(openFiles, lastOpenFilesRef.current)) { + if (IsOpenFilesChanged(openFiles, lastOpenFilesRef.current)) { setFallbackResults((prev) => ({ ...prev, file: deduplicateArray( From 4b5c262dd68cae861f3c128ecb25e90f8f783585 Mon Sep 17 00:00:00 2001 From: kongkong Date: Thu, 28 Nov 2024 14:26:36 +0800 Subject: [PATCH 068/105] Update SubmenuContextProviders.tsx --- gui/src/context/SubmenuContextProviders.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx index 046cec528..6334b2d95 100644 --- a/gui/src/context/SubmenuContextProviders.tsx +++ b/gui/src/context/SubmenuContextProviders.tsx @@ -41,7 +41,7 @@ const initialContextProviders: SubtextContextProvidersContextType = { const SubmenuContextProvidersContext = createContext(initialContextProviders); -function IsOpenFilesChanged(newFiles: { id: string; }[], oldFiles: { id: string; }[]) { +function isOpenFilesChanged(newFiles: { id: string; }[], oldFiles: { id: string; }[]) { if (newFiles.length > oldFiles.length) { return true; } @@ -138,7 +138,7 @@ export const SubmenuContextProvidersProvider = ({ const refreshOpenFiles = async () => { if (!isMounted) return; const openFiles = await getOpenFilesItems(); - if (IsOpenFilesChanged(openFiles, lastOpenFilesRef.current)) { + if (isOpenFilesChanged(openFiles, lastOpenFilesRef.current)) { setFallbackResults((prev) => ({ ...prev, file: deduplicateArray( From 57a84dcfe16e3cdebea54f7a0b0fe354f0d8ad2b Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 28 Nov 2024 18:06:31 -0800 Subject: [PATCH 069/105] fix: import posthog as type, use inline import --- core/util/posthog.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core/util/posthog.ts b/core/util/posthog.ts index a3f5200c2..4376021d5 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -2,7 +2,7 @@ import os from "node:os"; import { TeamAnalytics } from "../control-plane/TeamAnalytics.js"; import { IdeInfo } from "../index.js"; -import { PostHog } from "posthog-node"; +import type { PostHog as PostHogType } from "posthog-node"; export enum PosthogFeatureFlag { AutocompleteTemperature = "autocomplete-temperature", @@ -23,7 +23,7 @@ export const EXPERIMENTS: { export class Telemetry { // Set to undefined whenever telemetry is disabled - static client: PostHog | undefined = undefined; + static client: PostHogType | undefined = undefined; static uniqueId = "NOT_UNIQUE"; static os: string | undefined = undefined; static ideInfo: IdeInfo | undefined = undefined; @@ -73,9 +73,9 @@ export class Telemetry { Telemetry.client?.shutdown(); } - static async getTelemetryClient(): Promise { + static async getTelemetryClient(): Promise { try { - // const { PostHog } = await import("posthog-node"); + const { PostHog } = await import("posthog-node"); return new PostHog("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", { host: "https://app.posthog.com", }); From 2e3fdb34e2e2358232cc12fcf0a0c2d16a3ef0cc Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 28 Nov 2024 18:12:29 -0800 Subject: [PATCH 070/105] fix: send feature flags --- core/util/posthog.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/util/posthog.ts b/core/util/posthog.ts index 4376021d5..d4a31b46d 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -46,6 +46,7 @@ export class Telemetry { distinctId: Telemetry.uniqueId, event, properties: augmentedProperties, + sendFeatureFlags: true, }; // In cases where an extremely early fatal error occurs, we may not have initialized yet From 308ff51874a80aa13a9f54985e856c38277e7ae8 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 28 Nov 2024 18:13:18 -0800 Subject: [PATCH 071/105] mcp slash command --- core/commands/slash/mcp.ts | 47 ++++++ core/config/load.ts | 25 +++- core/context/mcp/index.ts | 146 +++++++++++++++++++ core/context/providers/MCPContextProvider.ts | 131 ++++------------- core/index.d.ts | 23 +++ extensions/vscode/config_schema.json | 57 ++++++++ 6 files changed, 322 insertions(+), 107 deletions(-) create mode 100644 core/commands/slash/mcp.ts create mode 100644 core/context/mcp/index.ts diff --git a/core/commands/slash/mcp.ts b/core/commands/slash/mcp.ts new file mode 100644 index 000000000..22eec07f5 --- /dev/null +++ b/core/commands/slash/mcp.ts @@ -0,0 +1,47 @@ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; + +import { ChatMessage, SlashCommand } from "../../index.js"; +import { stripImages } from "../../llm/images.js"; + +export function constructMcpSlashCommand( + client: Client, + name: string, + description?: string, + args?: string[], +): SlashCommand { + return { + name, + description: description ?? "MCP Prompt", + params: {}, + run: async function* (context) { + const argsObject: { [key: string]: string } = {}; + const userInput = context.input.split(" ").slice(1).join(" "); + if (args) { + args.forEach((arg, i) => { + argsObject[arg] = userInput; + }); + } + + const result = await client.getPrompt({ name, arguments: argsObject }); + + const messages: ChatMessage[] = result.messages.map((msg) => { + if (msg.content.type !== "text") { + throw new Error( + "Continue currently only supports text prompts through MCP", + ); + } + return { + content: msg.content.text, + role: msg.role, + }; + }); + + for await (const chunk of context.llm.streamChat( + messages, + new AbortController().signal, + )) { + yield stripImages(chunk.content); + } + }, + }; +} diff --git a/core/config/load.ts b/core/config/load.ts index b692b36bf..1d28a71a6 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -28,6 +28,7 @@ import { slashCommandFromDescription, slashFromCustomCommand, } from "../commands/index.js"; +import MCPConnectionSingleton from "../context/mcp"; import CodebaseContextProvider from "../context/providers/CodebaseContextProvider"; import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider"; import CustomContextProviderClass from "../context/providers/CustomContextProvider"; @@ -57,7 +58,6 @@ import { getEsbuildBinaryPath, readAllGlobalPromptFiles, } from "../util/paths"; - import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -484,7 +484,7 @@ async function intermediateToFinalConfig( } } - return { + let continueConfig: ContinueConfig = { ...config, contextProviders, models, @@ -492,6 +492,27 @@ async function intermediateToFinalConfig( tabAutocompleteModels, reranker: config.reranker as any, }; + + // Apply MCP if specified + if (config.experimental?.modelContextProtocolServer) { + const mcpConnection = await MCPConnectionSingleton.getInstance( + config.experimental.modelContextProtocolServer, + ); + continueConfig = await Promise.race([ + mcpConnection.modifyConfig(continueConfig), + new Promise((_, reject) => + setTimeout( + () => reject(new Error("MCP connection timed out after 1000ms")), + 1000, + ), + ), + ]).catch((error) => { + console.warn("MCP connection error:", error); + return continueConfig; // Return original config if timeout occurs + }); + } + + return continueConfig; } function finalToBrowserConfig( diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts new file mode 100644 index 000000000..262db9b19 --- /dev/null +++ b/core/context/mcp/index.ts @@ -0,0 +1,146 @@ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; +import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; + +import { ContinueConfig, MCPOptions, SlashCommand } from "../.."; +import { constructMcpSlashCommand } from "../../commands/slash/mcp"; +import MCPContextProvider from "../providers/MCPContextProvider"; + +class MCPConnectionSingleton { + private static instance: MCPConnectionSingleton; + private client: Client; + private transport: Transport; + + private constructor(private readonly options: MCPOptions) { + this.transport = this.constructTransport(options); + + this.client = new Client( + { + name: "continue-client", + version: "1.0.0", + }, + { + capabilities: {}, + }, + ); + } + + public static getInstance(options: MCPOptions): MCPConnectionSingleton { + if (!MCPConnectionSingleton.instance) { + MCPConnectionSingleton.instance = new MCPConnectionSingleton(options); + } + return MCPConnectionSingleton.instance; + } + + private constructTransport(options: MCPOptions): Transport { + switch (options.transport.type) { + case "stdio": + return new StdioClientTransport({ + command: options.transport.command, + args: options.transport.args, + }); + case "websocket": + return new WebSocketClientTransport(new URL(options.transport.url)); + case "sse": + return new SSEClientTransport(new URL(options.transport.url)); + default: + throw new Error( + `Unsupported transport type: ${(options.transport as any).type}`, + ); + } + } + + private isConnected: boolean = false; + private connectPromise: Promise | null = null; + + private async connectClient() { + if (this.isConnected) { + // Already connected + return; + } + + if (this.connectPromise) { + // Connection is already in progress; wait for it to complete + await this.connectPromise; + return; + } + + this.connectPromise = (async () => { + await this.client.connect(this.transport); + this.isConnected = true; + })(); + + try { + await this.connectPromise; + } catch (error) { + // Handle connection error if needed + throw error; + } finally { + // Reset the promise so future attempts can try again if necessary + this.connectPromise = null; + } + } + + async modifyConfig(config: ContinueConfig): Promise { + try { + await this.connectClient(); + } catch (error: any) { + if (!error.message.startsWith("StdioClientTransport already started")) { + console.error("Failed to connect client:", error); + return config; + } + } + + // Resources <—> Context Provider + const { resources } = await this.client.listResources(); + + const submenuItems = resources.map((resource: any) => ({ + title: resource.name, + description: resource.description, + id: resource.uri, + })); + + if (!config.contextProviders) { + config.contextProviders = []; + } + + config.contextProviders!.push( + new MCPContextProvider({ + submenuItems, + client: this.client, + }), + ); + + // Tools <—> Tools + // const { tools } = await this.client.listTools(); + // const continueTools: Tool = tools.map((tool) => ({ + + // })) + // if (!config.tools) { + // config.tools = [] + // } + // config.tools!.push(...continueTools); + + // Prompts <—> Slash commands + const { prompts } = await this.client.listPrompts(); + if (!config.slashCommands) { + config.slashCommands = []; + } + + const slashCommands: SlashCommand[] = prompts.map((prompt) => { + return constructMcpSlashCommand( + this.client, + prompt.name, + prompt.description, + prompt.arguments?.map((a) => a.name), + ); + }); + config.slashCommands!.push(...slashCommands); + + return config; + } +} + +export default MCPConnectionSingleton; diff --git a/core/context/providers/MCPContextProvider.ts b/core/context/providers/MCPContextProvider.ts index 09ef2cfe1..0c0a6939d 100644 --- a/core/context/providers/MCPContextProvider.ts +++ b/core/context/providers/MCPContextProvider.ts @@ -1,12 +1,4 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; -import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; -import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; -import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; -import { - ListResourcesResultSchema, - ReadResourceResultSchema, -} from "@modelcontextprotocol/sdk/types.js"; import { BaseContextProvider } from "../"; import { @@ -17,26 +9,9 @@ import { LoadSubmenuItemsArgs, } from "../../"; -interface StdioOptions { - type: "stdio"; - command: string; - args: string[]; -} - -interface WebSocketOptions { - type: "websocket"; - url: string; -} - -interface SSEOptions { - type: "sse"; - url: string; -} - -type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions; - interface MCPContextProviderOptions { - transport: TransportOptions; + submenuItems: ContextSubmenuItem[]; + client: Client; } class MCPContextProvider extends BaseContextProvider { @@ -47,98 +22,44 @@ class MCPContextProvider extends BaseContextProvider { type: "submenu", }; - private client: Client; - - private constructTransport(options: MCPContextProviderOptions): Transport { - switch (options.transport.type) { - case "stdio": - return new StdioClientTransport({ - command: options.transport.command, - args: options.transport.args, - }); - case "websocket": - return new WebSocketClientTransport(new URL(options.transport.url)); - case "sse": - return new SSEClientTransport(new URL(options.transport.url)); - default: - throw new Error( - `Unsupported transport type: ${(options.transport as any).type}`, - ); - } - } - - private resourcesPromise: Promise; - constructor(options: MCPContextProviderOptions) { super(options); - - const transport = this.constructTransport(options); - - this.client = new Client( - { - name: "continue-client", - version: "1.0.0", - }, - { - capabilities: {}, - }, - ); - - let resourcesResolve: (resources: any) => void; - this.resourcesPromise = new Promise((resolve) => { - resourcesResolve = resolve; - }); - - void this.client - .connect(transport) - .then(async () => { - const resources = await this.client.request( - { method: "resources/list" }, - ListResourcesResultSchema, - ); - resourcesResolve(resources.resources); - }) - .catch((error) => { - console.error( - "Error connecting to Model Context Protocol server", - error, - ); - }); } async getContextItems( query: string, extras: ContextProviderExtras, ): Promise { - const resourceContent = await this.client.request( - { - method: "resources/read", - params: { - uri: query, - }, - }, - ReadResourceResultSchema, - ); + const { contents } = await ( + this.options as MCPContextProviderOptions + ).client.readResource({ uri: query }); - return [ - { - name: "1", - description: "text", - content: "resourceContent", - }, - ]; + return await Promise.all( + contents.map(async (resource) => { + const content = resource.text; + if (typeof content !== "string") { + throw new Error( + "Continue currently only supports text resources from MCP", + ); + } + + return { + name: resource.uri, + description: resource.uri, + content, + uri: { + type: "url", + value: resource.uri, + }, + }; + }), + ); } async loadSubmenuItems( args: LoadSubmenuItemsArgs, ): Promise { - const resources = await this.resourcesPromise; - - return resources.map((resource: any) => ({ - title: resource.name, - description: resource.description, - id: resource.uri, - })); + return (this.options as MCPContextProviderOptions).submenuItems; } } diff --git a/core/index.d.ts b/core/index.d.ts index a71e69425..f34cfa94d 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -993,6 +993,28 @@ export interface TabAutocompleteOptions { showWhateverWeHaveAtXMs?: number; } +interface StdioOptions { + type: "stdio"; + command: string; + args: string[]; +} + +interface WebSocketOptions { + type: "websocket"; + url: string; +} + +interface SSEOptions { + type: "sse"; + url: string; +} + +type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions; + +export interface MCPOptions { + transport: TransportOptions; +} + export interface ContinueUIConfig { codeBlockToolbarPosition?: "top" | "bottom"; fontSize?: number; @@ -1098,6 +1120,7 @@ interface ExperimentalConfig { * This is needed to crawl a large number of documentation sites that are dynamically rendered. */ useChromiumForDocsCrawling?: boolean; + modelContextProtocolServer?: MCPOptions; } interface AnalyticsConfig { diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 7edceced4..1cda82a65 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -3023,6 +3023,63 @@ "type": "boolean", "description": "Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`.", "default": false + }, + "modelContextProtocolServer": { + "type": "object", + "properties": { + "transport": { + "oneOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["stdio"] + }, + "command": { + "type": "string" + }, + "args": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["type", "command", "args"] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["websocket"] + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "required": ["type", "url"] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["sse"] + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "required": ["type", "url"] + } + ] + } + }, + "required": ["transport"] } } } From c031bdfced3028402da8fa099ad57ee9a1b9772c Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 28 Nov 2024 18:16:39 -0800 Subject: [PATCH 072/105] improv: add error handling --- core/util/posthog.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/core/util/posthog.ts b/core/util/posthog.ts index d4a31b46d..dea92ec85 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -102,11 +102,15 @@ export class Telemetry { } static async getValueForFeatureFlag(flag: PosthogFeatureFlag) { - const userGroup = await Telemetry.getFeatureFlag(flag); - if (typeof userGroup === "string") { - return EXPERIMENTS[flag][userGroup].value; - } + try { + const userGroup = await Telemetry.getFeatureFlag(flag); + if (typeof userGroup === "string") { + return EXPERIMENTS[flag][userGroup].value; + } - return undefined; + return undefined; + } catch { + return undefined; + } } } From 98503572516b199e8646101bc7ccc71ad23fcfb4 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 28 Nov 2024 18:17:22 -0800 Subject: [PATCH 073/105] docs --- docs/docs/customize/context-providers.md | 23 +++++++++++------------ docs/docs/customize/slash-commands.md | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index b7ecea320..2c7708cac 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -495,27 +495,26 @@ Reference the architecture and platform of your current operating system. } ``` -### `@Model Context Protocol` +### Model Context Protocol -The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the `"mcp"` context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure the context provider in `config.json` like this: +The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this: ```json { - "contextProviders": [ - { - "name": "mcp", - "params": { - "transport": { - "type": "stdio", - "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] - } + "experimental": { + "modelContextProtocolServer": { + "transport": { + "type": "stdio", + "command": "uvx", + "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] } } - ] + } } ``` +You'll then be able to type "@" and see "MCP" in the context providers dropdown. + ### `@HTTP` The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems. diff --git a/docs/docs/customize/slash-commands.md b/docs/docs/customize/slash-commands.md index 96988e858..20283ae89 100644 --- a/docs/docs/customize/slash-commands.md +++ b/docs/docs/customize/slash-commands.md @@ -106,3 +106,21 @@ The onboard slash command helps to familiarize yourself with a new project by an ] } ``` + +### Model Context Protocol + +The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports MCP "prompts" by creating slash commands. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this: + +```json +{ + "experimental": { + "modelContextProtocolServer": { + "transport": { + "type": "stdio", + "command": "uvx", + "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] + } + } + } +} +``` From 5659afc96f5dbff5fae44c133525f1f0ce2d8408 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 28 Nov 2024 20:08:34 -0800 Subject: [PATCH 074/105] reduce lag when streaming tools calls --- core/core.ts | 18 ------------------ extensions/vscode/package-lock.json | 5 +++-- gui/src/redux/thunks/streamNormalInput.ts | 9 ++++++++- 3 files changed, 11 insertions(+), 21 deletions(-) diff --git a/core/core.ts b/core/core.ts index 3b6b28016..c528f3aec 100644 --- a/core/core.ts +++ b/core/core.ts @@ -408,24 +408,6 @@ export class Core { const chunk = next.value; - // if (chunk.toolCalls?.length) { - // for (const toolCall of chunk.toolCalls) { - // const tool = model.completionOptions.tools?.find( - // (tool) => tool.function.name === toolCall.function.name, - // ); - // if (!tool) { - // continue; - // } - // const response = await tool?.action(toolCall.function.arguments); - - // yield { - // role: "assistant", - // content: response, - // toolCalls: [toolCall], - // }; - // } - // } - // @ts-ignore yield { content: chunk }; next = await gen.next(); diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index d7316c47f..e902921a9 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.235", + "version": "0.9.236", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.235", + "version": "0.9.236", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -109,6 +109,7 @@ "cheerio": "^1.0.0-rc.12", "commander": "^12.0.0", "comment-json": "^4.2.3", + "dbinfoz": "^0.14.0", "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 2bb5a160f..cda38911b 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -53,8 +53,15 @@ export const streamNormalInput = createAsyncThunk< dispatch(abortStream()); break; } - dispatch(streamUpdate(next.value as ChatMessage)); + + const update = next.value as ChatMessage; + dispatch(streamUpdate(update)); next = await gen.next(); + + // There has been lag when streaming tool calls. This is a temporary solution + if (update.role === "assistant" && update.toolCalls) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } } // Attach prompt log From 54b7b22e3fd2b1bebb9441e1e7179aed770d6720 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 28 Nov 2024 20:24:18 -0800 Subject: [PATCH 075/105] better createFile --- gui/src/pages/gui/ToolCallDiv/CreateFile.tsx | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index 59eec0c97..dd0380066 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -7,11 +7,9 @@ interface CreateFileToolCallProps { } export function CreateFile(props: CreateFileToolCallProps) { - const src = `\`\`\`${getMarkdownLanguageTagForFile(props.filepath ?? "javascript")} ${props.filepath}\n${props.fileContents ?? ""}\n\`\`\``; + const src = `\`\`\`${getMarkdownLanguageTagForFile(props.filepath ?? "test.txt")} ${props.filepath}\n${props.fileContents ?? ""}\n\`\`\``; - return ( - <> - - - ); + return props.filepath ? ( + + ) : null; } From 7d248060560b949c85307d9191ca8a2568453e9b Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 28 Nov 2024 22:55:23 -0800 Subject: [PATCH 076/105] fixes for tool use --- core/tools/implementations/viewDiff.ts | 2 +- extensions/vscode/package-lock.json | 4 ++-- extensions/vscode/src/VsCodeIde.ts | 4 +++- gui/src/redux/slices/stateSlice.ts | 4 ++++ 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/core/tools/implementations/viewDiff.ts b/core/tools/implementations/viewDiff.ts index f7c05849f..11003b61a 100644 --- a/core/tools/implementations/viewDiff.ts +++ b/core/tools/implementations/viewDiff.ts @@ -6,7 +6,7 @@ export const viewDiffImpl: ToolImpl = async (args, extras) => { { name: "Diff", description: "The current git diff", - content: diff, + content: diff.join("\n"), }, ]; }; diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index e902921a9..d82208880 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.236", + "version": "0.9.237", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.236", + "version": "0.9.237", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index cc0d8c343..aff491e0c 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -531,7 +531,7 @@ class VsCodeIde implements IDE { "bin", "rg", ), - ["-i", "-C", "2", "--", `${query}`, "."], //no regex + ["-i", "-C", "2", "-F", "--", `"${query}"`, "."], //no regex //["-i", "-C", "2", "-e", `${query}`, "."], //use regex { cwd: dir }, ); @@ -546,6 +546,8 @@ class VsCodeIde implements IDE { p.on("close", (code) => { if (code === 0) { resolve(output); + } else if (code === 1) { + resolve(""); } else { reject(new Error(`Process exited with code ${code}`)); } diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 097132693..0a1ad6ead 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -362,6 +362,10 @@ export const stateSlice = createSlice({ state.history[ state.history.length - 1 ].toolCallState.parsedArgs = parsedArgs; + state.history[ + state.history.length - 1 + ].toolCallState.toolCall.function.arguments += + toolCall.function.arguments; } }); } From ba1fdf7bac07afe04e62bd659a87dc89800a302b Mon Sep 17 00:00:00 2001 From: liuk Date: Fri, 29 Nov 2024 23:34:45 +0800 Subject: [PATCH 077/105] fix: Add context/getSymbolsForFiles endpoint in JetBrains and handle symbol retrieval errors --- core/util/treeSitter.ts | 7 ++++++- .../toolWindow/ContinueBrowser.kt | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 22a59e85c..8029c0609 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -290,7 +290,12 @@ export async function getSymbolsForManyFiles( const filesAndSymbols = await Promise.all( uris.map(async (uri): Promise<[string, SymbolWithRange[]]> => { const contents = await ide.readFile(uri); - const symbols = await getSymbolsForFile(uri, contents); + let symbols = undefined; + try { + symbols = await getSymbolsForFile(uri, contents); + } catch (e) { + console.error(`Failed to get symbols for ${uri}:`, e); + } return [uri, symbols ?? []]; }), ); diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 659ec4998..7651ecc8f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -66,6 +66,7 @@ class ContinueBrowser(val project: Project, url: String) { "config/listProfiles", "profiles/switch", "didChangeSelectedProfile", + "context/getSymbolsForFiles", ) private fun registerAppSchemeHandler() { From 5d4e6e9494767bda8b2ee970f05667ae2a333939 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 08:38:26 -0800 Subject: [PATCH 078/105] read file tool --- core/index.d.ts | 1 + core/tools/builtIn.ts | 1 + core/tools/callTool.ts | 3 ++ core/tools/definitions/readFile.ts | 25 ++++++++++++++ core/tools/definitions/runTerminalCommand.ts | 1 + core/tools/definitions/searchWeb.ts | 1 + core/tools/definitions/viewDiff.ts | 1 + core/tools/definitions/viewRepoMap.ts | 1 + core/tools/definitions/viewSubdirectory.ts | 1 + core/tools/implementations/readFile.ts | 14 ++++++++ .../implementations/runTerminalCommand.ts | 33 ++++++++++++------- core/tools/index.ts | 2 ++ .../InputToolbar/ToolDropdownItem.tsx | 20 +++++++---- gui/src/pages/gui/ToolCallDiv/ExactSearch.tsx | 14 ++++++++ .../FunctionSpecificToolCallDiv.tsx | 3 ++ gui/src/redux/slices/uiStateSlice.ts | 8 +++++ 16 files changed, 110 insertions(+), 19 deletions(-) create mode 100644 core/tools/definitions/readFile.ts create mode 100644 core/tools/implementations/readFile.ts create mode 100644 gui/src/pages/gui/ToolCallDiv/ExactSearch.tsx diff --git a/core/index.d.ts b/core/index.d.ts index 4d7bbed1c..3ec58990d 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -930,6 +930,7 @@ export interface Tool { displayTitle: string; wouldLikeTo: string; + readonly: boolean; } interface BaseCompletionOptions { diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index 421319c14..255967568 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -1,4 +1,5 @@ export enum BuiltInToolNames { + ReadFile = "read_file", CreateNewFile = "create_new_file", RunTerminalCommand = "run_terminal_command", ViewSubdirectory = "view_subdirectory", diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index dbe4a8a9f..80dd69c79 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -2,6 +2,7 @@ import { ContextItem, ToolExtras } from ".."; import { BuiltInToolNames } from "./builtIn"; import { createNewFileImpl } from "./implementations/createNewFile"; import { exactSearchImpl } from "./implementations/exactSearch"; +import { readFileImpl } from "./implementations/readFile"; import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; import { searchWebImpl } from "./implementations/searchWeb"; import { viewDiffImpl } from "./implementations/viewDiff"; @@ -42,6 +43,8 @@ export async function callTool( extras: ToolExtras, ): Promise { switch (uri) { + case BuiltInToolNames.ReadFile: + return await readFileImpl(args, extras); case BuiltInToolNames.CreateNewFile: return await createNewFileImpl(args, extras); case BuiltInToolNames.ExactSearch: diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts new file mode 100644 index 000000000..51d958fc4 --- /dev/null +++ b/core/tools/definitions/readFile.ts @@ -0,0 +1,25 @@ +import { Tool } from "../.."; +import { BuiltInToolNames } from "../builtIn"; + +export const readFileTool: Tool = { + type: "function", + displayTitle: "Read File", + wouldLikeTo: "read a file", + readonly: true, + function: { + name: BuiltInToolNames.ReadFile, + description: + "Use this tool whenever you need to view the contents of a file.", + parameters: { + type: "object", + required: ["filepath"], + properties: { + filepath: { + type: "string", + description: + "The path of the file to read, relative to the root of the workspace.", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index b3c40ca32..94a429e23 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -6,6 +6,7 @@ export const runTerminalCommandTool: Tool = { type: "function", displayTitle: "Run Terminal Command", wouldLikeTo: "run a terminal command", + readonly: false, function: { name: BuiltInToolNames.RunTerminalCommand, description: "Run a terminal command in the current directory", diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index c8ead3c28..d462158c9 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -6,6 +6,7 @@ export const searchWebTool: Tool = { type: "function", displayTitle: "Search Web", wouldLikeTo: "search the web", + readonly: true, function: { name: BuiltInToolNames.SearchWeb, description: diff --git a/core/tools/definitions/viewDiff.ts b/core/tools/definitions/viewDiff.ts index 554f49878..e54086d05 100644 --- a/core/tools/definitions/viewDiff.ts +++ b/core/tools/definitions/viewDiff.ts @@ -6,6 +6,7 @@ export const viewDiffTool: Tool = { type: "function", displayTitle: "View Diff", wouldLikeTo: "view a diff", + readonly: true, function: { name: BuiltInToolNames.ViewDiff, description: "View the current diff of working changes", diff --git a/core/tools/definitions/viewRepoMap.ts b/core/tools/definitions/viewRepoMap.ts index aca91a78b..9cf3d319d 100644 --- a/core/tools/definitions/viewRepoMap.ts +++ b/core/tools/definitions/viewRepoMap.ts @@ -6,6 +6,7 @@ export const viewRepoMapTool: Tool = { type: "function", displayTitle: "View Repo Map", wouldLikeTo: "view the repository map", + readonly: true, function: { name: BuiltInToolNames.ViewRepoMap, description: "View the repository map", diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts index 4ac1b5c40..e3c1d034b 100644 --- a/core/tools/definitions/viewSubdirectory.ts +++ b/core/tools/definitions/viewSubdirectory.ts @@ -6,6 +6,7 @@ export const viewSubdirectoryTool: Tool = { type: "function", displayTitle: "View Subdirectory", wouldLikeTo: "view the contents of a subdirectory", + readonly: true, function: { name: BuiltInToolNames.ViewSubdirectory, description: "View the contents of a subdirectory", diff --git a/core/tools/implementations/readFile.ts b/core/tools/implementations/readFile.ts new file mode 100644 index 000000000..032db3dce --- /dev/null +++ b/core/tools/implementations/readFile.ts @@ -0,0 +1,14 @@ +import { getBasename } from "../../util"; + +import { ToolImpl } from "."; + +export const readFileImpl: ToolImpl = async (args, extras) => { + const content = await extras.ide.readFile(args.filepath); + return [ + { + name: getBasename(args.filepath), + description: args.filepath, + content, + }, + ]; +}; diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index fb4770cee..ddc8575c4 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -1,22 +1,31 @@ import { ToolImpl } from "."; - const util = require("node:util"); const asyncExec = util.promisify(require("node:child_process").exec); export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { const ideInfo = await extras.ide.getIdeInfo(); + if (ideInfo.remoteName === "local" || ideInfo.remoteName === "") { - // If we're local, can just run the terminal command with child_process - const output = await asyncExec(args.command, { - cwd: (await extras.ide.getWorkspaceDirs())[0], - }); - return [ - { - name: "Terminal", - description: "Terminal command output", - content: output.stdout ?? "", - }, - ]; + try { + const output = await asyncExec(args.command, { + cwd: (await extras.ide.getWorkspaceDirs())[0], + }); + return [ + { + name: "Terminal", + description: "Terminal command output", + content: output.stdout ?? "", + }, + ]; + } catch (error: any) { + return [ + { + name: "Terminal", + description: "Terminal command output", + content: error.stderr ?? error.toString(), + }, + ]; + } } await extras.ide.runCommand(args.command); diff --git a/core/tools/index.ts b/core/tools/index.ts index 7f8eb32fb..86dfc82c5 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,5 +1,6 @@ import { createNewFileTool } from "./definitions/createNewFile"; import { exactSearchTool } from "./definitions/exactSearch"; +import { readFileTool } from "./definitions/readFile"; import { runTerminalCommandTool } from "./definitions/runTerminalCommand"; import { searchWebTool } from "./definitions/searchWeb"; import { viewDiffTool } from "./definitions/viewDiff"; @@ -7,6 +8,7 @@ import { viewRepoMapTool } from "./definitions/viewRepoMap"; import { viewSubdirectoryTool } from "./definitions/viewSubdirectory"; export const allTools = [ + readFileTool, createNewFileTool, runTerminalCommandTool, viewSubdirectoryTool, diff --git a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx index e137c18dc..431e6f36b 100644 --- a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx @@ -1,9 +1,7 @@ import { Tool } from "core"; +import { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; -import { - DEFAULT_TOOL_SETTING, - toggleToolSetting, -} from "../../../redux/slices/uiStateSlice"; +import { addTool, toggleToolSetting } from "../../../redux/slices/uiStateSlice"; import { RootState } from "../../../redux/store"; interface ToolDropdownItemProps { @@ -13,11 +11,19 @@ interface ToolDropdownItemProps { function ToolDropdownItem(props: ToolDropdownItemProps) { const dispatch = useDispatch(); const settings = useSelector( - (state: RootState) => - state.uiState.toolSettings[props.tool.function.name] ?? - DEFAULT_TOOL_SETTING, + (state: RootState) => state.uiState.toolSettings[props.tool.function.name], ); + useEffect(() => { + if (!settings) { + dispatch(addTool(props.tool)); + } + }, [props.tool.function.name, settings]); + + if (!settings) { + return null; + } + return (
+ ); +} diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 68fdeb682..dd06c48ca 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -1,5 +1,6 @@ import { ToolCall, ToolCallState } from "core"; import { CreateFile } from "./CreateFile"; +import { ExactSearch } from "./ExactSearch"; import { RunTerminalCommand } from "./RunTerminalCommand"; function FunctionSpecificToolCallDiv({ @@ -18,6 +19,8 @@ function FunctionSpecificToolCallDiv({ ); case "run_terminal_command": return ; + case "exact_search": + return ; default: return null; } diff --git a/gui/src/redux/slices/uiStateSlice.ts b/gui/src/redux/slices/uiStateSlice.ts index 499a78d7b..3472eb018 100644 --- a/gui/src/redux/slices/uiStateSlice.ts +++ b/gui/src/redux/slices/uiStateSlice.ts @@ -1,4 +1,5 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; +import { Tool } from "core"; import { BuiltInToolNames } from "core/tools/builtIn"; import { defaultOnboardingCardState, @@ -33,6 +34,7 @@ export const uiStateSlice = createSlice({ useTools: false, toolSettings: { + [BuiltInToolNames.ReadFile]: "allowedWithoutPermission", [BuiltInToolNames.CreateNewFile]: "allowedWithPermission", [BuiltInToolNames.RunTerminalCommand]: "allowedWithPermission", [BuiltInToolNames.ViewSubdirectory]: "allowedWithoutPermission", @@ -68,6 +70,11 @@ export const uiStateSlice = createSlice({ toggleUseTools: (state) => { state.useTools = !state.useTools; }, + addTool: (state, action: PayloadAction) => { + state.toolSettings[action.payload.function.name] = action.payload.readonly + ? "allowedWithoutPermission" + : "allowedWithPermission"; + }, toggleToolSetting: (state, action: PayloadAction) => { const setting = state.toolSettings[action.payload]; @@ -96,6 +103,7 @@ export const { setShowDialog, toggleUseTools, toggleToolSetting, + addTool, } = uiStateSlice.actions; export default uiStateSlice.reducer; From e8550b0af6a9e003f7affdab0fa758aa0b7230cd Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 08:52:46 -0800 Subject: [PATCH 079/105] show above --- core/tools/definitions/createNewFile.ts | 1 + core/tools/definitions/exactSearch.ts | 1 + .../InputToolbar/ToggleToolsButton.tsx | 116 +++++++++++------- 3 files changed, 73 insertions(+), 45 deletions(-) diff --git a/core/tools/definitions/createNewFile.ts b/core/tools/definitions/createNewFile.ts index 1123de217..f0082891c 100644 --- a/core/tools/definitions/createNewFile.ts +++ b/core/tools/definitions/createNewFile.ts @@ -5,6 +5,7 @@ export const createNewFileTool: Tool = { type: "function", displayTitle: "Create New File", wouldLikeTo: "create a new file", + readonly: false, function: { name: BuiltInToolNames.CreateNewFile, description: "Create a new file", diff --git a/core/tools/definitions/exactSearch.ts b/core/tools/definitions/exactSearch.ts index 5e55c8667..2a0266bd5 100644 --- a/core/tools/definitions/exactSearch.ts +++ b/core/tools/definitions/exactSearch.ts @@ -5,6 +5,7 @@ export const exactSearchTool: Tool = { type: "function", displayTitle: "Exact Search", wouldLikeTo: "search for a specific term within the repository", + readonly: true, function: { name: BuiltInToolNames.ExactSearch, description: "Perform an exact search over the repository using ripgrep", diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index 232a0cd8e..33e642be2 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -1,4 +1,4 @@ -import { Listbox } from "@headlessui/react"; +import { Listbox, Transition } from "@headlessui/react"; import { ChevronDownIcon, ChevronUpIcon, @@ -6,7 +6,7 @@ import { } from "@heroicons/react/24/outline"; import { modelSupportsTools } from "core/llm/autodetect"; import { allTools } from "core/tools/index"; -import { useRef, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, vscForeground } from "../.."; @@ -34,13 +34,35 @@ const BackgroundDiv = styled.div<{ useTools: boolean }>` transition: background-color 200ms; `; -export default function ToolDropdown() { +export default function ToolDropdown({ + +}: { + +}) { const buttonRef = useRef(null); const dispatch = useDispatch(); const [isDropdownOpen, setDropdownOpen] = useState(false); + const useTools = useSelector((store: RootState) => store.uiState.useTools); const defaultModel = useSelector(defaultModelSelector); + + const [showAbove, setShowAbove] = useState(false); + + useEffect(() => { + const checkPosition = () => { + if (buttonRef.current) { + const rect = buttonRef.current.getBoundingClientRect(); + const windowHeight = window.innerHeight; + const spaceBelow = windowHeight - rect.bottom; + setShowAbove(spaceBelow < 250); + } + }; + + if (isDropdownOpen) { + checkPosition(); + } + }, [isDropdownOpen]); if (!modelSupportsTools(defaultModel.model)) { return null; @@ -77,49 +99,53 @@ export default function ToolDropdown() { )} - -
- Tool policies{" "} - -

- Automatic:{" "} - Can be used without asking -

-

- Allowed:{" "} - Will ask before using -

-

- Disabled:{" "} - Cannot be used -

-
- } - /> -
- {allTools.map((tool) => ( - + +
- - - ))} - + Tool policies{" "} + +

+ Automatic:{" "} + Can be used without asking +

+

+ Allowed:{" "} + Will ask before using +

+

+ Disabled:{" "} + Cannot be used +

+
+ } + /> +
+ {allTools.map((tool) => ( + + + + ))} + +
From d3d9af42927477fa0e7667d0bdcd0259b60bc0bd Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 11:37:58 -0800 Subject: [PATCH 080/105] "Run in terminal" button --- core/index.d.ts | 1 + core/tools/definitions/runTerminalCommand.ts | 4 +-- .../StepContainerPreToolbar/ApplyActions.tsx | 12 +++---- .../RunInTerminalButton.tsx | 35 +++++++++++++++++++ .../StepContainerPreToolbar.tsx | 22 +++++++----- .../FunctionSpecificToolCallDiv.tsx | 2 +- .../gui/ToolCallDiv/RunTerminalCommand.tsx | 12 +++---- gui/src/redux/slices/stateSlice.ts | 8 +++++ gui/src/redux/thunks/callTool.ts | 3 ++ 9 files changed, 75 insertions(+), 24 deletions(-) create mode 100644 gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx diff --git a/core/index.d.ts b/core/index.d.ts index 3ec58990d..494b4e314 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -402,6 +402,7 @@ interface ToolCallState { toolCall: ToolCall; status: ToolStatus; parsedArgs: any; + output?: ContextItem[]; } export interface ChatHistoryItem { diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index 94a429e23..82b2d342c 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -1,5 +1,4 @@ import { Tool } from "../.."; - import { BuiltInToolNames } from "../builtIn"; export const runTerminalCommandTool: Tool = { @@ -9,7 +8,8 @@ export const runTerminalCommandTool: Tool = { readonly: false, function: { name: BuiltInToolNames.RunTerminalCommand, - description: "Run a terminal command in the current directory", + description: + "Run a terminal command in the current directory. The shell is not stateful and will not remember any previous commands.", parameters: { type: "object", required: ["command"], diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx index d96afc7fe..42ee8e048 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx @@ -1,10 +1,10 @@ -import { CheckIcon, XMarkIcon, PlayIcon } from "@heroicons/react/24/outline"; -import Spinner from "./Spinner"; -import { lightGray, vscForeground } from "../.."; -import { useState } from "react"; -import { getMetaKeyLabel } from "../../../util"; -import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip"; +import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core"; +import { useState } from "react"; +import { lightGray, vscForeground } from "../.."; +import { getMetaKeyLabel } from "../../../util"; +import Spinner from "./Spinner"; +import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip"; interface ApplyActionsProps { applyState?: ApplyState; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx b/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx new file mode 100644 index 000000000..35bc54349 --- /dev/null +++ b/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx @@ -0,0 +1,35 @@ +import { CommandLineIcon } from "@heroicons/react/24/outline"; +import { useContext } from "react"; +import { lightGray, vscForeground } from "../.."; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; + +interface RunInTerminalButtonProps { + command: string; +} + +export default function RunInTerminalButton({ + command, +}: RunInTerminalButtonProps) { + const ideMessenger = useContext(IdeMessengerContext); + + function runInTerminal() { + void ideMessenger.post("runCommand", { command }); + } + + return ( +
+
+ <> + + Run + +
+
+ ); +} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index cc7de6033..ca7d78d97 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -10,11 +10,12 @@ import { useWebviewListener } from "../../../hooks/useWebviewListener"; import { defaultModelSelector } from "../../../redux/selectors/modelSelectors"; import { RootState } from "../../../redux/store"; import { getFontSize } from "../../../util"; -import { childrenToText } from "../utils"; +import { childrenToText, isTerminalCodeBlock } from "../utils"; import ApplyActions from "./ApplyActions"; import CopyButton from "./CopyButton"; import FileInfo from "./FileInfo"; import GeneratingCodeLoader from "./GeneratingCodeLoader"; +import RunInTerminalButton from "./RunInTerminalButton"; const fadeInAnimation = keyframes` from { @@ -202,14 +203,17 @@ export default function StepContainerPreToolbar( {!isGeneratingCodeBlock && ( <> - {props.hideApply || ( - - )} + {props.hideApply || + (isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( + + ) : ( + + ))} )}
diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index dd06c48ca..34044d71f 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -18,7 +18,7 @@ function FunctionSpecificToolCallDiv({ ); case "run_terminal_command": - return ; + return ; case "exact_search": return ; default: diff --git a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx index 08c00c0bd..35fc0e54f 100644 --- a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx +++ b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx @@ -1,16 +1,16 @@ +import { ToolCallState } from "core"; import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; interface RunTerminalCommandToolCallProps { command: string; + toolCallState: ToolCallState; } export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { return ( - <> - - + ); } diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 0a1ad6ead..475932b2a 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -10,6 +10,7 @@ import { ChatHistoryItem, ChatMessage, Checkpoint, + ContextItem, ContextItemWithId, FileSymbolMap, IndexingStatus, @@ -485,6 +486,12 @@ export const stateSlice = createSlice({ toolCallState.status = "generated"; }, + setToolCallOutput: (state, action: PayloadAction) => { + const toolCallState = findCurrentToolCall(state.history); + if (!toolCallState) return; + + toolCallState.output = action.payload + }, cancelToolCall: (state) => { const toolCallState = findCurrentToolCall(state.history); if (!toolCallState) return; @@ -598,6 +605,7 @@ export const { acceptToolCall, setToolGenerated, updateDocsSuggestions, + setToolCallOutput } = stateSlice.actions; export default stateSlice.reducer; diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index f326423aa..7a8c56669 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -1,5 +1,6 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; +import { setToolCallOutput } from "../slices/stateSlice"; import { ThunkApiType } from "../store"; import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; @@ -24,6 +25,8 @@ export const callTool = createAsyncThunk( if (result.status === "success") { const contextItems = result.content.contextItems; + dispatch(setToolCallOutput(contextItems)); + // Send to the LLM to continue the conversation dispatch( streamResponseAfterToolCall({ From 1beeb586d792cccc2eaeb0dca9fec1163c118192 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 11:44:31 -0800 Subject: [PATCH 081/105] fix "calling" state --- gui/src/pages/gui/ToolCallDiv/index.tsx | 10 ++++++++-- gui/src/redux/thunks/callTool.ts | 6 ++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 4d6838f26..745bb78c4 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -1,5 +1,10 @@ -import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import { + ArrowRightIcon, + CheckIcon, + XMarkIcon, +} from "@heroicons/react/24/outline"; import { ToolCall, ToolCallState, ToolStatus } from "core"; +import { vscButtonBackground } from "../../../components"; import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner"; import FunctionSpecificToolCallDiv from "./FunctionSpecificToolCallDiv"; import { ThreadDiv } from "./ThreadDiv"; @@ -14,8 +19,9 @@ export function ToolCallDiv(props: ToolCallDivProps) { switch (state) { case "generating": case "calling": - case "generated": return ; + case "generated": + return ; case "done": return ; case "canceled": diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 7a8c56669..6541648f3 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -1,6 +1,6 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; -import { setToolCallOutput } from "../slices/stateSlice"; +import { setCalling, setToolCallOutput } from "../slices/stateSlice"; import { ThunkApiType } from "../store"; import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; @@ -19,6 +19,8 @@ export const callTool = createAsyncThunk( return; } + dispatch(setCalling()); + const result = await extra.ideMessenger.request("tools/call", { toolCall: toolCallState.toolCall, }); @@ -26,7 +28,7 @@ export const callTool = createAsyncThunk( if (result.status === "success") { const contextItems = result.content.contextItems; dispatch(setToolCallOutput(contextItems)); - + // Send to the LLM to continue the conversation dispatch( streamResponseAfterToolCall({ From 8a2083813ab62e22acc977df2a166e534e6e0b7e Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 12:00:13 -0800 Subject: [PATCH 082/105] better anthropic error --- core/llm/llms/Anthropic.ts | 15 +++++++++++++++ extensions/vscode/src/VsCodeIde.ts | 2 +- gui/src/components/mainInput/ContinueInputBox.tsx | 2 +- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index b3a099a81..a10d2c4a4 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -178,6 +178,21 @@ class Anthropic extends BaseLLM { signal, }); + if (!response.ok) { + const json = await response.json(); + if (json.type === "error") { + if (json.error?.type === "overloaded_error") { + throw new Error( + "The Anthropic API is currently overloaded. Please check their status page: https://status.anthropic.com/#past-incidents", + ); + } + throw new Error(json.message); + } + throw new Error( + `Anthropic API sent back ${response.status}: ${JSON.stringify(json)}`, + ); + } + if (options.stream === false) { const data = await response.json(); yield { role: "assistant", content: data.content[0].text }; diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index aff491e0c..3871acd4a 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -547,7 +547,7 @@ class VsCodeIde implements IDE { if (code === 0) { resolve(output); } else if (code === 1) { - resolve(""); + resolve(output); } else { reject(new Error(`Process exited with code ${code}`)); } diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index f9ff1172c..463203c4e 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -68,7 +68,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) { (store: RootState) => store.state.config.contextProviders, ); const useTools = useSelector( - (store: RootState) => store.state.config.experimental?.useTools, + (store: RootState) => store.state.config.experimental?.useTools !== false, ); useWebviewListener( From 8cb904c49f4c4898955236dc1299c841addbbefa Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 12:06:50 -0800 Subject: [PATCH 083/105] don't use findLast --- gui/src/redux/selectors/selectLastToolCall.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/gui/src/redux/selectors/selectLastToolCall.ts b/gui/src/redux/selectors/selectLastToolCall.ts index 610a03b4d..5509ab476 100644 --- a/gui/src/redux/selectors/selectLastToolCall.ts +++ b/gui/src/redux/selectors/selectLastToolCall.ts @@ -5,10 +5,14 @@ import { RootState } from "../store"; export const selectLastToolCall = createSelector( [(store: RootState) => store.state.history], (history): ToolCallState | null => { - const lastToolCallHistoryItem = history.findLast( - (item) => - item.message.role === "assistant" && item.message.toolCalls?.length, - ); + let lastToolCallHistoryItem = null; + for (let i = history.length - 1; i >= 0; i--) { + const item = history[i]; + if (item.message.role === "assistant" && item.message.toolCalls?.length) { + lastToolCallHistoryItem = item; + break; + } + } if (!lastToolCallHistoryItem) return null; return lastToolCallHistoryItem.toolCallState; }, From e1d84f51ea1236f844c916478284a52217808036 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 12:08:41 -0800 Subject: [PATCH 084/105] fix type error after merge --- core/commands/slash/mcp.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/core/commands/slash/mcp.ts b/core/commands/slash/mcp.ts index 22eec07f5..a9fa332bb 100644 --- a/core/commands/slash/mcp.ts +++ b/core/commands/slash/mcp.ts @@ -1,8 +1,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { ChatMessage, SlashCommand } from "../../index.js"; -import { stripImages } from "../../llm/images.js"; - +import { renderChatMessage } from "../../util/messageContent.js"; export function constructMcpSlashCommand( client: Client, name: string, @@ -40,7 +39,7 @@ export function constructMcpSlashCommand( messages, new AbortController().signal, )) { - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } }, }; From 1672d9f864e99436b8f309af3529f2fda341172d Mon Sep 17 00:00:00 2001 From: Big Boss Date: Fri, 29 Nov 2024 13:45:51 -0600 Subject: [PATCH 085/105] fix: update intellij getDiff to return string[] --- .../continue/IdeProtocolClient.kt | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index c48c8e58b..54e088c4f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -453,9 +453,10 @@ class IdeProtocolClient( "getDiff" -> { val workspaceDirs = workspaceDirectories() - val output = StringBuilder() + val diffs = mutableListOf() for (workspaceDir in workspaceDirs) { + val output = StringBuilder() val builder = ProcessBuilder("git", "diff") builder.directory(File(workspaceDir)) val process = builder.start() @@ -469,9 +470,10 @@ class IdeProtocolClient( } process.waitFor() + diffs.add(output.toString()) } - respond(output.toString()) + respond(diffs) } "getProblems" -> { @@ -1091,4 +1093,4 @@ class IdeProtocolClient( return matchingModel } -} \ No newline at end of file +} From e43d3bda6aa833bfe686b8c84dfa64d43fa08748 Mon Sep 17 00:00:00 2001 From: Big Boss Date: Fri, 29 Nov 2024 14:27:05 -0600 Subject: [PATCH 086/105] fix: handle when dir might be a file path --- .../continueintellijextension/continue/IdeProtocolClient.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 54e088c4f..6dccf7f08 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -435,8 +435,10 @@ class IdeProtocolClient( "getRepoName" -> { // Get the current repository name val dir = (data as Map)["dir"] as String + val directory = File(dir) + val targetDir = if (directory.isFile) directory.parentFile else directory val builder = ProcessBuilder("git", "config", "--get", "remote.origin.url") - builder.directory(File(dir)) + builder.directory(targetDir) var output = "NONE" try { val process = builder.start() From e2228fedf528cf9c4f567023ff91b1dd71b36890 Mon Sep 17 00:00:00 2001 From: Big Boss Date: Fri, 29 Nov 2024 15:45:26 -0600 Subject: [PATCH 087/105] Add Function Network provider --- core/index.d.ts | 4 +- .../FunctionNetworkEmbeddingsProvider.ts | 69 ++++++++++++++++++ core/indexing/embeddings/index.ts | 2 + core/llm/autodetect.ts | 8 +- core/llm/llms/FunctionNetwork.ts | 41 +++++++++++ core/llm/llms/index.ts | 2 + .../top-level/function-network.md | 67 +++++++++++++++++ extensions/vscode/config_schema.json | 15 +++- gui/public/logos/function-network.png | Bin 0 -> 7965 bytes .../pages/AddNewModel/configs/providers.ts | 25 +++++++ 10 files changed, 225 insertions(+), 8 deletions(-) create mode 100644 core/indexing/embeddings/FunctionNetworkEmbeddingsProvider.ts create mode 100644 core/llm/llms/FunctionNetwork.ts create mode 100644 docs/docs/customize/model-providers/top-level/function-network.md create mode 100644 gui/public/logos/function-network.png diff --git a/core/index.d.ts b/core/index.d.ts index efb7a18e9..58ba9d8a5 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -700,7 +700,8 @@ type ModelProvider = | "nebius" | "xAI" | "moonshot" - | "siliconflow"; + | "siliconflow" + | "function-network"; export type ModelName = | "AUTODETECT" @@ -913,6 +914,7 @@ export type EmbeddingsProviderName = | "nebius" | "vertexai" | "watsonx" + | "function-network" | "siliconflow"; export interface EmbedOptions { diff --git a/core/indexing/embeddings/FunctionNetworkEmbeddingsProvider.ts b/core/indexing/embeddings/FunctionNetworkEmbeddingsProvider.ts new file mode 100644 index 000000000..fe16dbc51 --- /dev/null +++ b/core/indexing/embeddings/FunctionNetworkEmbeddingsProvider.ts @@ -0,0 +1,69 @@ +import { Response } from "node-fetch"; + +import { EmbeddingsProviderName, EmbedOptions } from "../../index.js"; +import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; + +import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; + +class FunctionNetworkEmbeddingsProvider extends BaseEmbeddingsProvider { + static providerName: EmbeddingsProviderName = "function-network"; + static maxBatchSize = 128; + + static defaultOptions: Partial | undefined = { + apiBase: "https://api.function.network/v1/", + model: "baai/bge-base-en-v1.5", + }; + + private _getEndpoint() { + if (!this.options.apiBase) { + throw new Error( + "No API base URL provided. Please set the 'apiBase' option in config.json", + ); + } + + this.options.apiBase = this.options.apiBase.endsWith("/") + ? this.options.apiBase + : `${this.options.apiBase}/`; + return new URL("embeddings", this.options.apiBase); + } + + async embed(chunks: string[]) { + const batchedChunks = this.getBatchedChunks(chunks); + return ( + await Promise.all( + batchedChunks.map(async (batch) => { + if (batch.length === 0) { + return []; + } + + const fetchWithBackoff = () => + withExponentialBackoff(() => + this.fetch(this._getEndpoint(), { + method: "POST", + body: JSON.stringify({ + input: batch, + model: this.options.model, + }), + headers: { + Authorization: `Bearer ${this.options.apiKey}`, + "Content-Type": "application/json", + }, + }), + ); + const resp = await fetchWithBackoff(); + + if (!resp.ok) { + throw new Error(await resp.text()); + } + + const data = (await resp.json()) as any; + return data.data.map( + (result: { embedding: number[] }) => result.embedding, + ); + }), + ) + ).flat(); + } +} + +export default FunctionNetworkEmbeddingsProvider; diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts index 3e895a39e..5adc241ba 100644 --- a/core/indexing/embeddings/index.ts +++ b/core/indexing/embeddings/index.ts @@ -6,6 +6,7 @@ import CohereEmbeddingsProvider from "./CohereEmbeddingsProvider.js"; import ContinueProxyEmbeddingsProvider from "./ContinueProxyEmbeddingsProvider.js"; import DeepInfraEmbeddingsProvider from "./DeepInfraEmbeddingsProvider.js"; import FreeTrialEmbeddingsProvider from "./FreeTrialEmbeddingsProvider.js"; +import FunctionNetworkEmbeddingsProvider from "./FunctionNetworkEmbeddingsProvider.js"; import GeminiEmbeddingsProvider from "./GeminiEmbeddingsProvider.js"; import HuggingFaceTEIEmbeddingsProvider from "./HuggingFaceTEIEmbeddingsProvider.js"; import LMStudioEmbeddingsProvider from "./LMStudio.js"; @@ -36,6 +37,7 @@ export const allEmbeddingsProviders: Record< openai: OpenAIEmbeddingsProvider, cohere: CohereEmbeddingsProvider, "free-trial": FreeTrialEmbeddingsProvider, + "function-network": FunctionNetworkEmbeddingsProvider, "huggingface-tei": HuggingFaceTEIEmbeddingsProvider, gemini: GeminiEmbeddingsProvider, "continue-proxy": ContinueProxyEmbeddingsProvider, diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 8e475d01e..9849af95b 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -124,6 +124,7 @@ const PARALLEL_PROVIDERS: ModelProvider[] = [ "sambanova", "nebius", "vertexai", + "function-network", ]; function llmCanGenerateInParallel( @@ -150,13 +151,12 @@ function autodetectTemplateType(model: string): TemplateType | undefined { lower.includes("chat-bison") || lower.includes("pplx") || lower.includes("gemini") || - lower.includes("grok")|| + lower.includes("grok") || lower.includes("moonshot") ) { - return undefined; + return undefined; } - - if (lower.includes("llama3")) { + if (lower.includes("llama3") || lower.includes("llama-3")) { return "llama3"; } diff --git a/core/llm/llms/FunctionNetwork.ts b/core/llm/llms/FunctionNetwork.ts new file mode 100644 index 000000000..1010e47ed --- /dev/null +++ b/core/llm/llms/FunctionNetwork.ts @@ -0,0 +1,41 @@ +import { LLMOptions, ModelProvider } from "../../index.js"; + +import OpenAI from "./OpenAI.js"; + +class FunctionNetwork extends OpenAI { + static providerName: ModelProvider = "function-network"; + static defaultOptions: Partial = { + apiBase: "https://api.function.network/v1/", + model: "meta/llama-3.1-70b-instruct", + }; + + private static modelConversion: { [key: string]: string } = { + "mistral-7b": "mistral/mistral-7b-instruct-v0.1", + "llama3-8b": "meta/llama-3-8b-instruct", + "llama3.1-8b": "meta/llama-3.1-8b-instruct", + "llama3.1-70b": "meta/llama-3.1-70b-instruct", + "deepseek-7b": "thebloke/deepseek-coder-6.7b-instruct-awq", + }; + + constructor(options: LLMOptions) { + super(options); + } + + protected _convertModelName(model: string): string { + return FunctionNetwork.modelConversion[model] ?? model; + } + + public supportsFim(): boolean { + return false; + } + + public supportsCompletions(): boolean { + return false; + } + + public supportsPrefill(): boolean { + return false; + } +} + +export default FunctionNetwork; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 0297b7868..632607ed1 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -21,6 +21,7 @@ import Deepseek from "./Deepseek"; import Fireworks from "./Fireworks"; import Flowise from "./Flowise"; import FreeTrial from "./FreeTrial"; +import FunctionNetwork from "./FunctionNetwork"; import Gemini from "./Gemini"; import Groq from "./Groq"; import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI"; @@ -54,6 +55,7 @@ const LLMs = [ Anthropic, Cohere, FreeTrial, + FunctionNetwork, Gemini, Llamafile, Moonshot, diff --git a/docs/docs/customize/model-providers/top-level/function-network.md b/docs/docs/customize/model-providers/top-level/function-network.md new file mode 100644 index 000000000..c48e899d8 --- /dev/null +++ b/docs/docs/customize/model-providers/top-level/function-network.md @@ -0,0 +1,67 @@ +--- +title: Function Network +slug: ../function-network +--- +# Function Network + +> Private, Affordable User-Owned AI + +:::info + +To get an API key, login to the Function Network Developer Platform. If you don't have an account, you can create one [here](https://www.function.network/join-waitlist). + +::: + +## Chat model + +Function Network supports a number of models for chat. We recommend using LLama 3.1 70b or Qwen2.5-Coder-32B-Instruct. + +```json title="config.json" +{ + "models": [ + { + "title": "Llama 3.1 70b", + "provider": "function-network", + "model": "meta/llama-3.1-70b-instruct", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` + +[Click here](https://docs.function.network/models-supported/chat-and-code-completion) to see a list of chat model providers. + +## Autocomplete model + +Function Network supports a number of models for autocomplete. We recommend using Llama 3.1 8b or Qwen2.5-Coder-1.5B. + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "Deepseek Coder 6.7b", + "provider": "function-network", + "model": "thebloke/deepseek-coder-6.7b-base-awq", + "apiKey": "YOUR_API_KEY" + } +} +``` + +## Embeddings model + +Function Network supports a number of models for embeddings. We recommend using baai/bge-base-en-v1.5. + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "function-network", + "model": "baai/bge-base-en-v1.5", + "apiKey": "YOUR_API_KEY" + } +} +``` + +[Click here](https://docs.function.network/models-supported/embeddings) to see a list of embeddings model providers. + +## Reranking model + +Function Network currently does not offer any reranking models. diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 682925838..9b17fe65d 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -207,6 +207,7 @@ "xAI", "kindo", "moonshot", + "function-network", "siliconflow" ], "markdownEnumDescriptions": [ @@ -246,7 +247,8 @@ "### xAI offers a world class developer tool set to build scalable applications powered by Grok. To get started, obtain an API key from [the x Console](https://console.x.ai/), and see the [docs](https://docs.x.ai/docs/)", "### Secure AI management software that helps enterprises adopt and manage AI across their workforce. To get started, obtain an API key from [the Kindo console](https://app.kindo.ai/settings/api), and see the [website](https://app.kindo.ai//)", "### Moonshot\nTo get started with Moonshot AI, obtain your API key from [Moonshot AI](https://platform.moonshot.cn/). Moonshot AI provides high-quality large language models with competitive pricing.\n> [Reference](https://platform.moonshot.cn/docs/api)", - "### SiliconFlow\nTo get started with SiliconFlow, obtain your API key from [SiliconCloud](https://cloud.siliconflow.cn/account/ak). SiliconCloud provides cost-effective GenAI services based on excellent open source basic models.\n> [Models](https://siliconflow.cn/zh-cn/models)" + "### SiliconFlow\nTo get started with SiliconFlow, obtain your API key from [SiliconCloud](https://cloud.siliconflow.cn/account/ak). SiliconCloud provides cost-effective GenAI services based on excellent open source basic models.\n> [Models](https://siliconflow.cn/zh-cn/models)", + "### Function Network offers private, affordable user-owned AI\nTo get started with Function Network, obtain your API key from [Function Network](https://www.function.network/join-waitlist). Function Network provides a variety of models for chat, completion, and embeddings." ], "type": "string" }, @@ -2524,7 +2526,8 @@ "mistral", "watsonx", "lmstudio", - "siliconflow" + "siliconflow", + "function-network" ] }, "model": { @@ -2572,7 +2575,13 @@ "if": { "properties": { "provider": { - "enum": ["cohere", "voyage", "nvidia", "gemini", "siliconflow"] + "enum": [ + "cohere", + "voyage", + "nvidia", + "gemini", + "siliconflow" + ] } }, "required": ["provider"] diff --git a/gui/public/logos/function-network.png b/gui/public/logos/function-network.png new file mode 100644 index 0000000000000000000000000000000000000000..177f22fb67504dca6a7bee7f7280063e86d1a422 GIT binary patch literal 7965 zcmV+&AL8JNP)00Bw}1^@s6dnpzL00183Nkl0z!lsLa4U3Wr3YIQWB5`N}9Yz;uv6ZAsBv_{)P2^prNs3^QE)_)B zRiuyz)8RB8q#HrUQiLj3S*~pex%K=?ZvUz zJHPY1@ALi{7!b(jaJ2cg*~Xgt@X)%LL-PfC&%1Act;9odseB&vsOofY z*_~{V8InR!Cg9v~G$a^<%iP!WLsgsvXa5nDJ(M?HF1QEzY4^hm1Y^DOE_~+RK6Xv6 z%r%Mj4ZT88_JrmcU3GIoRipdi(9kB$ab71h`-7nDFomO=Z+ykZ!8kO;XwOyl*WKF< zLbJOF%8t>n+EtAgsT@0rO0%N~$_^+x)$YS9MmYAx4fpVUcsm?9*I0!D)4h;hXBSXA2+D>Lknohbw_O6WSp;Q6 z2uK8$8G+dtg0f}=Bx;r!fmu6(vL*y1nncs5UIb-eTIS=r*jL@e`$Yp9Mqt*1pbUg{ zkciBV8;dZI6oX+uyGZ+X+R|M?UB3e^zlbfddQDCd(W7MMBK75eBpq!Ae zi~PXG7kL3mQg!Ku;?FP?e_+jU`X77ZI+OSb~xodb5BW2;xS58c{OymdOMq^N~O}sm)s^G4ysJxkX3<;pkb?Gxe~0 zwk!d?56VY|qgMz?AUr)&uClzPXUux8*FmX?=R>n=G;M&|Z0H&5dy}WPbCmf%+>QZg zN^kdx_cAEY4@XzoX#+G*J9%zrgKg`X-UX$bTz+rBDda$FbiSnv%S+ZHy$QdO*)|mk!eCL^Fp2E`Z+Z#6cR-2c^!s(=kp4pqJdR_TqnMgX$>Z%?5iGsc7dY^E+<1DG}(u4HrZo=$W@jMOjhiwtIgj#|%$R_7?0mjqBk>+_YZR+P+30w_T@8hp^^ zd}V7vnXi}JGyqs`tIhe!R)*fJmjqDJGk3B znGd-;cb6}K=rz&>Z>pl~%(avNy2Dj^?=`Uyz4oAFVL5=hs(t|XGKW^2SAgq*45alB`9g& z0BBmBjh*1l92z(PT2#x9o!}K^EO%T0NK!33c7j%vRFeQA5p>5+(2A035K(; z(lu~~?%gc|fH(xJDnnM3RFeQ=5-gK~1Z7@L4h;a}G0d~cTd0bXY7#(5WC^a{#>*((MB@$;%GE3czu7Y=|f8JRtGHyi9( z1(hpGcHsc%5?2*ow2CTKlvI-dI;ir=LX|4YL$lgW5(a>pY*an3vQkjGvHq(D0Nqn5 zyH*ZL-G#&HQbSVDoU0F0qBFliVf*i zhu%X2fbM&Bm8)$_2PI7$06n6mLR)1&d6kOtc>{p{C_R-}s+mI*2S6XKn|-UyPMuN} z<$dNR0rb$+h&h{*S&pb{PDSOkKfC=Z>e7tecw$T|L6y1&;4+&nXj>47)2*KwiE`Kmw6_df6u|Z04vWwH4MHVNAjJ$E)ro>gR+c z&;i3d>*iV*lytjSr@6TUz*w7HqLXnD}kP|D>* zXL4V9&MN!j?`D7dyJ3pY*Ywjpv)lhPR5Th_l$U1x+RUKToe~_WR*tGkpKtE2dgFD! zzxUHEfqx*F3WP@z_7iJE<*H}AQniiF(#y2FdUU!YJj|?-s zv^@^IDip97Sezlq17Z3P=TI2&%9YA~An+`-bHE zH{E~#8$$`&u%NK4N@4lzPs_c~;)DY?ANkny8I`Ao-c|0rP1X0Gv>-HJr?;3x^4TBw zg`_HELb5!KEc885m0rZ({k36rGp~r4HAgu#l%n$_eRW~JP7mE1zqHC!-Td@dh7}c~ zjH*(UvPaOW$>y zI^T-&=3gypTKeQujr{)4Zl3H<22ZNWfAXv9jTyb5zr%dxDmJE%T{{t!_o*fubtmFV z%XeF*{%$+}VF*OcFrWEKy{I!^S>E(n7bk*pL{OF%;y~V*honC9lEQ^&;i)?Jov-Aa z)N-b?aC(lCMovi~f-=@MZW?kkFBvDzSNeS4Xjc`d?w4{R3#WsU*PF!o4!Jc%WamwN z6q3H{D^uKdTfye!4~~OUjT}SrbSQ&Q#ld>X`f2#B6%$oy2u>G#sf~vxGVwSl?{ivE z@?Lt@|F8>&+|BSAg6oCwcdr|km^>WlI4DQ#$Vr}WmzyDXbM*E0S$d_W4vn3~Mzey_ z3AA$=U8HK#r-Ac^$I=y4qYB<%U#GZq!)rXg8gXH0%X1E+01 zJ9hK}$z0`pU+39)bY~77?{xWAlRgirmZ*d}9p0y^@}(~F69JCgQy06+JwioQSvBx9 zSJ~#*FJ^h?d+#VH*}9mnAHQgo`JR5HWAwFCBt%&1&q|J zMuhk}C~%+qd-Kx(zQ@oN^tJR^?n6~skF~s^Q&g0X8XBLg3Hkq5<(u56^6Qgi>_J`&z)V5Dm)IL?EzJ}bfbCS!(Z|Qx}%wcIzV)Rh>?7|7T zZc>%h?*p7$smgArp`*m~A`_xx9P*kBjVOGAjy>R~6-$JQpk$6RF}f_QDm{#$=K~eI zRp;j>Dg5hRNPQH@Ker%4UX!7J7vJ4FIBAqOy4Q+zLP(2GHK~vcJw)?8#e0$}y}BNH z-#dgRY04q=oT~1GuZnGrv+1;RRg{~Cr1-9#TeWFamWH7}2{a7VRjqZLkQ1s)U)MDm zz6;R5$42H;zIIcSYxkI+Opece~3NSi7KrSd&jl(DP(geM2IwT$GK0%uWFgIDo@#18xWL9QH2%buzT9h z+hHzW(~Cl=ZthFl{&T3BTBv)ir~ZsSFK9pVX!P}w7M-sdlH#+#yzXK5Bt7gQf=Se& z4$-7Ix>?d=THtD+&VCs_|4t#M7y4vCMVTI-YN6?!8zGxJYQlsVQff+|%9>9#Z<;*V z*r)p)V&8h7xQu*M73D*QWcWM;pLjfcmH$8Y{I^Pq=H5azcT`ob@}kkk9q0P<`CJvj zGNF^y%%SU@5T6I&)0XxEs}c*bz+EpAp%$a7(k(NGs?TZbj&q+8z~kRB(AZR z*G)lLb-t0|_ely$D$3j{OH%Z}`UYjw*C+T?2~9O2<|&#xH{bCeKC8K-IXvILlm2^6 z3(WgI(66<5BF`89WtB1XeqfNVqa-L3;Zu#pa0FLzEL#YncJ9nO(4*<*%`84I1o~bH zxmdsJSRRxRpW&2GbrO>1Dnm7QLfvgW-Q0=g>RwghK5J1QA}Eiotx-`X!>59Z>6}7^ zP>2dw!^g&|Ty*-P3;W#+|b;c&<(Lk3Fl!@>O$}T)?A@AJLVZT&U zbiF4Ll<19OOQEmgj_|$&Mb#HNg7N{KM|ogCPlUW9ypPQtRC2I(NKm3@)Z7WN_EXKB zy6*@_{8UUb^hPg*YVK$;I#(lrphPdlc#QPEj z^+9{-*>J;VHFtJ8x){CczaMKbA5ca4rJ?ukBzB6-QLz2og3?0tt~Gb4CWH7F6(yGH z+QX(l@B1|kmDSwo(lrTv-n!ZpS4@7T^CAOt+{mXt;~T%UMya_I;u?uMo$KL&%}vwvv=P`Fm zP#!y)nk;ta{L9dL3WKVhOoe1DRb|n<2{A9J6VY{WMyNZ&)!d2Y>*Vw2`1Eswjh6=L z{aXG5D#}Fo+*bI#CoKvZ;)V#x-~ZWFrPszE>qX@9Z!L%zcJAoK#HSno1r_CyQGOQ2 zQBbnzJRLqk8N)Idg`|eKz7&i_NETFChPZP_A^y8S(*jj}-{VD1UmF@ZV}r>#%Cl6I z$+-Dft4u-J<~*f_k|CNm3WAsC47C-WeYhjsXB+1yq`|Sn$)UH=^-hM*Jf&!xU>ibS z_N6;@7FA4rXzut_|2{9KeRFm)D78+AB|_==<40CmTWc0WH*Xfv3rVQvjw;}$n>z|g zpRW}a<*_|wqdqu3kCG)q>G+FB#n8qwp(}xQ-Y6ia=OyP+MXAcum%di-HoO>JC%adr zkYtbdvE$y&aZrvp={y-e4}%_fp9gVO8oGvR-mKcye*dFx-VyFI?0)~I;eq2tQjf#-=C5K$6UudD?UCBN;=eR7DP`_uWMdiBzy4I84 z{ZqWn9sQm@!|pc%ya@Eni7cG1D4C~Bh(gk*siQf!kd;xWySR(yO&#-XA)7lPk7e^+ zi9i$Qq`{(!^6W&H2Wj||$GlX?s!}1TMdcxAh+Jn=Ld%RoGrR9ZWWI zWO|O0;dg?39+VJOrG}s(mK!PXLp5)f(F@FOpq)ED%^d}#&w_la$(c@N;M$Cz_|T9P z1x#C2rK+J&&6{5YI#05!kj#+J!?%&Xmpi$+bB@$vkC(^sxKP zS;cr|YaeMe<1?>2>lzGiPF%_cL?6*#aeyE zkh^x-ykD3bl!t6*Oj?K`cnsIu_KEMkK@7Q6?N|J_ zDKg|<>`ax4GQWK+GbGD*PqQBE-@R_|H4##CN{3jzfO?t~h$mXD>IqZ^}8dWc0i+DDzS@ zGbGRVf-O}=Gr%>aAQ-0@kAuCo^j%f-~;_BmrxAxZP5yfQ0%mIfumZ%opWVw(4= z8kQPL5|;BRBz-#EI_!dwTuHWU*ezv--gLilLWr<@(epB_zVZ#p%fB(KU{GS%oqyhP zI-~NQ*;fVtJ>sSo9}8AdviKZ84}DlBB&AeP=5`GLdSbA`I`Ps$=}Oc+j$Q-M2Rc&i zb~dUpblu9R@FS9uuZQM8e%mwDA z0YC$)o?c!?@QPAYRl0ZE1^~^et(ja)MOipE9Nlv7h6Vuj(&F-GtR}Tol!bM(O9lWn zt2=9I4a$5{m9>=s>QqYuXHu;}DfvZY`vw4kDO;2=ROoRQ8#)2|0j~Rjk2%+`{&ZNeIQe2sQ!@UyR zFaW5i$su>4(V!GpE?=Sx4xoyrhunq6gOV;d01w+u4!H}B2c_gE4|Bp0fK}{j`p#NV z>t63gbi&X*GwlW6G5}bh&Xa-4Xr-bQ4Z+vVUSP=(fJKxMZeFss124*GEht5E4FmRq z16bg&;iW*cv^MmfbZ$7(Ud>kx08V<#^)z0ymbF?@7Tgeghb2P*CglfS>{tY%s3^rX zcQ*6uBQ^{`((-x9r`jHJ7ow;rCI5o3z7l|3iX|i^nxK??jTFrtAZ@L!mz*b>q4%Wo z!_fzB2!6o;Bt>UIxR89oA`?|bSztdnke+-Wca+m_Q3j&74`*$A@@E-6aEX%HDd*2k=(a$%<0A zN&@JVqmYbsLHRPB4N4&_fllajNJ^)JQV2^RYMl>B>3mQMVF^U37a=LV2udL=fvEH* zB&9b&Szw(d(5^17lU$~g%Yzol|AF2z0Bv}yZy_nY3rfkiMsbh^(5&4qZA)B5?}px! zI7kC%OlJ^`t;D7Q@G^17&Aug|m(846^bhL(VV}}ftXGyxEobCC?_!#2af3EpBGZEA}1w1 z^q!_~3^!T*n6XbB>3VBD@%hMEs3_;iyW&@=E|CH?Y~1(yr90UmGn_(2Ifs@(sMF`Z zfvy|SW5oh;LUKMT$`bN}HLg%yqEAv^8@UQ9$`W)k3e_e0#CU74@HM`73RzpSULF+E>nZ4&e92yX>Y~59nEcvO9pbUWFIAWw> zwvA68XCBfMK^YLow;=}VW{<`T$KUMBz1nRfCUx|tz3g0g0AI6k!TaC~S$c$pE9wIe7SLSQ1W%m~QF5R?rgFySdP0={}^P)0(5d1!XQJru99a6N6TgNzSB z86oZT$t%pEAtjkHyp9q<8L?tm?mm2)Dzl%8>e0R3V0axbg0ds>{p8QP2kL^M4>I?* z>xS2R46oxyPH}v8#;-g z>2+AHRLes`?G=gfDU($8MRrVjB9fu>s>YgDe6QEr{uDaQB5AyRy zwdpPIRPU*3bYIgwmh%rza1bgI)sP(nlXt^4D^R72=# zOSmzVhvL5b@MDFe8%k%)GlHPROnG>2j>eVelQyn8dljGxL{}y5x%Xe@p{PocMc+7u zphRgdJQbFkd4O)YZ=Of- zAn&#-P;LBk#a!s|$7?5lekKiv567M5;>Y`w?^O}H-{(LfsP|{aKYzfG8KL|?uQc4W TnlE0^00000NkvXXu0mjfE_Rb5 literal 0 HcmV?d00001 diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index cc668c0c2..4c56dd8a6 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -137,6 +137,31 @@ export const providers: Partial> = { ...completionParamsInputsConfigs, ], }, + "function-network": { + title: "Function Network", + provider: "function-network", + refPage: "function-network", + description: + "Run open-source models on Function Network. Private, Affordable User-Owned AI", + icon: "function-network.png", + longDescription: `Function Network is a private, affordable user-owned AI platform that allows you to run open-source models. Experience bleeding-edge Generative AI models with limitless scalability, all powered by our distributed inference network.`, + tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource], + params: { + apiKey: "", + }, + collectInputFor: [ + { + inputType: "text", + key: "apiKey", + label: "API Key", + placeholder: "Enter your Function Network API key", + required: true, + }, + ...completionParamsInputsConfigs, + ], + packages: [models.llama31Chat, models.deepseek], + apiKeyUrl: "https://function.network/join-waitlist", + }, azure: { title: "Azure OpenAI", provider: "azure", From 823f96ca30f81db776fd6431c542f4d7522154b1 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 13:51:31 -0800 Subject: [PATCH 088/105] inject and call MCP tools --- core/config/load.ts | 3 + core/context/mcp/index.ts | 29 +++-- core/core.ts | 7 +- core/index.d.ts | 3 + core/tools/callTool.ts | 58 ++++++++-- .../InputToolbar/ToggleToolsButton.tsx | 109 +++++++++--------- .../InputToolbar/ToolDropdownItem.tsx | 9 +- gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx | 9 +- gui/src/redux/slices/stateSlice.ts | 5 +- gui/src/redux/thunks/streamNormalInput.ts | 5 +- 10 files changed, 156 insertions(+), 81 deletions(-) diff --git a/core/config/load.ts b/core/config/load.ts index 7a4f91ea1..5c21a0656 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -44,6 +44,7 @@ import { BaseLLM } from "../llm"; import { llmFromDescription } from "../llm/llms"; import CustomLLMClass from "../llm/llms/CustomLLM"; import FreeTrial from "../llm/llms/FreeTrial"; +import { allTools } from "../tools"; import { copyOf } from "../util"; import { fetchwithRequestOptions } from "../util/fetchWithOptions"; import { GlobalContext } from "../util/GlobalContext"; @@ -492,6 +493,7 @@ async function intermediateToFinalConfig( embeddingsProvider: config.embeddingsProvider as any, tabAutocompleteModels, reranker: config.reranker as any, + tools: allTools, }; // Apply MCP if specified @@ -550,6 +552,7 @@ function finalToBrowserConfig( ui: final.ui, experimental: final.experimental, docs: final.docs, + tools: final.tools, }; } diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index 262db9b19..984ba8f7b 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -4,13 +4,13 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js" import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; -import { ContinueConfig, MCPOptions, SlashCommand } from "../.."; +import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../.."; import { constructMcpSlashCommand } from "../../commands/slash/mcp"; import MCPContextProvider from "../providers/MCPContextProvider"; class MCPConnectionSingleton { private static instance: MCPConnectionSingleton; - private client: Client; + public client: Client; private transport: Transport; private constructor(private readonly options: MCPOptions) { @@ -34,6 +34,10 @@ class MCPConnectionSingleton { return MCPConnectionSingleton.instance; } + public static getExistingInstance(): MCPConnectionSingleton | null { + return MCPConnectionSingleton.instance; + } + private constructTransport(options: MCPOptions): Transport { switch (options.transport.type) { case "stdio": @@ -114,14 +118,21 @@ class MCPConnectionSingleton { ); // Tools <—> Tools - // const { tools } = await this.client.listTools(); - // const continueTools: Tool = tools.map((tool) => ({ + const { tools } = await this.client.listTools(); + const continueTools: Tool[] = tools.map((tool) => ({ + displayTitle: tool.name, + function: { + description: tool.description, + name: tool.name, + parameters: tool.inputSchema, + }, + readonly: false, + type: "function", + wouldLikeTo: `use the ${tool.name} tool`, + uri: `mcp://${tool.name}`, + })); - // })) - // if (!config.tools) { - // config.tools = [] - // } - // config.tools!.push(...continueTools); + config.tools = [...config.tools, ...continueTools]; // Prompts <—> Slash commands const { prompts } = await this.client.listPrompts(); diff --git a/core/core.ts b/core/core.ts index 38a7104b8..2108d3706 100644 --- a/core/core.ts +++ b/core/core.ts @@ -36,7 +36,6 @@ import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; -import { allTools } from "./tools"; import { callTool } from "./tools/callTool"; import type { IMessenger, Message } from "./util/messenger"; @@ -782,7 +781,8 @@ export class Core { }); on("tools/call", async ({ data: { toolCall } }) => { - const tool = allTools.find( + const config = await this.configHandler.loadConfig(); + const tool = config.tools.find( (t) => t.function.name === toolCall.function.name, ); @@ -790,11 +790,10 @@ export class Core { throw new Error(`Tool ${toolCall.function.name} not found`); } - const config = await this.configHandler.loadConfig(); const llm = await this.getSelectedModel(); const contextItems = await callTool( - tool.function.name, + tool.uri ?? tool.function.name, JSON.parse(toolCall.function.arguments || "{}"), { ide: this.ide, diff --git a/core/index.d.ts b/core/index.d.ts index de7a95481..6da58c81b 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -932,6 +932,7 @@ export interface Tool { displayTitle: string; wouldLikeTo: string; readonly: boolean; + uri?: string; } interface BaseCompletionOptions { @@ -1297,6 +1298,7 @@ export interface ContinueConfig { experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; + tools: Tool[]; } export interface BrowserSerializedContinueConfig { @@ -1316,6 +1318,7 @@ export interface BrowserSerializedContinueConfig { experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; + tools: Tool[]; } // DOCS SUGGESTIONS AND PACKAGE INFO diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 80dd69c79..d34851787 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -1,4 +1,5 @@ import { ContextItem, ToolExtras } from ".."; +import MCPConnectionSingleton from "../context/mcp"; import { BuiltInToolNames } from "./builtIn"; import { createNewFileImpl } from "./implementations/createNewFile"; import { exactSearchImpl } from "./implementations/exactSearch"; @@ -9,17 +10,12 @@ import { viewDiffImpl } from "./implementations/viewDiff"; import { viewRepoMapImpl } from "./implementations/viewRepoMap"; import { viewSubdirectoryImpl } from "./implementations/viewSubdirectory"; -async function callToolFromUri( - uri: string, +async function callHttpTool( + url: string, args: any, extras: ToolExtras, ): Promise { - const canParse = URL.canParse(uri); - if (!canParse) { - throw new Error(`Invalid URI: ${uri}`); - } - - const response = await extras.fetch(uri, { + const response = await extras.fetch(url, { method: "POST", headers: { "Content-Type": "application/json", @@ -30,13 +26,57 @@ async function callToolFromUri( }); if (!response.ok) { - throw new Error(`Failed to call tool: ${uri}`); + throw new Error(`Failed to call tool: ${url}`); } const data = await response.json(); return data.output; } +async function callToolFromUri( + uri: string, + args: any, + extras: ToolExtras, +): Promise { + const canParse = URL.canParse(uri); + if (!canParse) { + throw new Error(`Invalid URI: ${uri}`); + } + const parsedUri = URL.parse(uri)!; + + switch (parsedUri?.protocol) { + case "http:": + case "https:": + return callHttpTool(uri, args, extras); + case "mcp:": + const client = await MCPConnectionSingleton.getExistingInstance(); + if (!client) { + throw new Error("MCP connection not found"); + } + const toolName = parsedUri!.hostname; + const response = await client.client.callTool({ + name: toolName, + arguments: args, + }); + + if (response.isError === true) { + throw new Error(`Failed to call tool: ${toolName}`); + } + + return (response.content as any).map((item: any) => { + if (item.type !== "text") { + throw new Error( + `Continue received item of type "${item.type}" from MCP tool, but currently only supports "text".`, + ); + } + return { name: toolName, description: toolName, content: item.text }; + }); + + default: + throw new Error(`Unsupported protocol: ${parsedUri?.protocol}`); + } +} + export async function callTool( uri: string, args: any, diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index 33e642be2..d17842cb7 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -5,7 +5,6 @@ import { WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { modelSupportsTools } from "core/llm/autodetect"; -import { allTools } from "core/tools/index"; import { useEffect, useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; @@ -34,19 +33,17 @@ const BackgroundDiv = styled.div<{ useTools: boolean }>` transition: background-color 200ms; `; -export default function ToolDropdown({ - -}: { - -}) { +export default function ToolDropdown({}: {}) { const buttonRef = useRef(null); const dispatch = useDispatch(); const [isDropdownOpen, setDropdownOpen] = useState(false); - const useTools = useSelector((store: RootState) => store.uiState.useTools); + const availableTools = useSelector( + (store: RootState) => store.state.config.tools, + ); const defaultModel = useSelector(defaultModelSelector); - + const [showAbove, setShowAbove] = useState(false); useEffect(() => { @@ -99,51 +96,59 @@ export default function ToolDropdown({ )} - - -
- Tool policies{" "} - -

- Automatic:{" "} - Can be used without asking -

-

- Allowed:{" "} - Will ask before using -

-

- Disabled:{" "} - Cannot be used -

-
- } - /> -
- {allTools.map((tool) => ( - + +
+
- - - ))} + Tool policies{" "} + +

+ + Automatic: + {" "} + Can be used without asking +

+

+ + Allowed: + {" "} + Will ask before using +

+

+ Disabled:{" "} + Cannot be used +

+
+ } + /> +
+
+
+ {availableTools.map((tool) => ( + + + + ))} +
diff --git a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx index 431e6f36b..7098733eb 100644 --- a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx @@ -33,7 +33,14 @@ function ToolDropdownItem(props: ToolDropdownItemProps) { e.preventDefault(); }} > - {props.tool.displayTitle} + + {props.tool.displayTitle}{" "} + {/* */} +
{(settings === "allowedWithPermission" || settings === undefined) && ( Allowed diff --git a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx index 12f28eea8..d3c96419f 100644 --- a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx @@ -1,6 +1,7 @@ import { ToolCall } from "core"; -import { allTools } from "core/tools"; +import { useSelector } from "react-redux"; import styled from "styled-components"; +import { RootState } from "../../../redux/store"; interface ThreadDivProps { children: React.ReactNode; @@ -29,6 +30,10 @@ const HeaderDiv = styled.div` `; export function ThreadDiv(props: ThreadDivProps) { + const availableTools = useSelector( + (state: RootState) => state.state.config.tools, + ); + return ( @@ -44,7 +49,7 @@ export function ThreadDiv(props: ThreadDivProps) {
Continue wants to{" "} { - allTools.find( + availableTools.find( (tool) => props.toolCall.function.name === tool.function.name, )?.wouldLikeTo } diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 475932b2a..6f542a1b2 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -84,6 +84,7 @@ const initialState: State = { ], contextProviders: [], models: [], + tools: [], }, title: "New Session", sessionId: v4(), @@ -490,7 +491,7 @@ export const stateSlice = createSlice({ const toolCallState = findCurrentToolCall(state.history); if (!toolCallState) return; - toolCallState.output = action.payload + toolCallState.output = action.payload; }, cancelToolCall: (state) => { const toolCallState = findCurrentToolCall(state.history); @@ -605,7 +606,7 @@ export const { acceptToolCall, setToolGenerated, updateDocsSuggestions, - setToolCallOutput + setToolCallOutput, } = stateSlice.actions; export default stateSlice.reducer; diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index cda38911b..05d5147e1 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -1,6 +1,5 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { ChatMessage, PromptLog } from "core"; -import { allTools } from "core/tools"; import { defaultModelSelector } from "../selectors/modelSelectors"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { @@ -40,7 +39,9 @@ export const streamNormalInput = createAsyncThunk< ? Object.keys(toolSettings) .filter((tool) => toolSettings[tool] !== "disabled") .map((toolName) => - allTools.find((tool) => tool.function.name === toolName), + state.state.config.tools.find( + (tool) => tool.function.name === toolName, + ), ) : undefined, }, From 99de578e64049372c72dea482cbe1a543de4b75b Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 14:11:27 -0800 Subject: [PATCH 089/105] templated wouldLikeTo messages --- core/tools/definitions/exactSearch.ts | 2 +- core/tools/definitions/readFile.ts | 2 +- core/tools/definitions/searchWeb.ts | 2 +- core/tools/definitions/viewSubdirectory.ts | 6 ++--- gui/package-lock.json | 16 ++++++++++++++ gui/package.json | 2 ++ .../InputToolbar/ToggleToolsButton.tsx | 4 ++-- gui/src/pages/gui/Chat.tsx | 3 ++- .../FunctionSpecificToolCallDiv.tsx | 7 +++++- gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx | 22 +++++++++++++++---- gui/src/pages/gui/ToolCallDiv/index.tsx | 3 +++ 11 files changed, 55 insertions(+), 14 deletions(-) diff --git a/core/tools/definitions/exactSearch.ts b/core/tools/definitions/exactSearch.ts index 2a0266bd5..524dcb6f5 100644 --- a/core/tools/definitions/exactSearch.ts +++ b/core/tools/definitions/exactSearch.ts @@ -4,7 +4,7 @@ import { BuiltInToolNames } from "../builtIn"; export const exactSearchTool: Tool = { type: "function", displayTitle: "Exact Search", - wouldLikeTo: "search for a specific term within the repository", + wouldLikeTo: 'search for "{{ query }}" in the repository', readonly: true, function: { name: BuiltInToolNames.ExactSearch, diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts index 51d958fc4..e64e32728 100644 --- a/core/tools/definitions/readFile.ts +++ b/core/tools/definitions/readFile.ts @@ -4,7 +4,7 @@ import { BuiltInToolNames } from "../builtIn"; export const readFileTool: Tool = { type: "function", displayTitle: "Read File", - wouldLikeTo: "read a file", + wouldLikeTo: "read {{ filepath }}", readonly: true, function: { name: BuiltInToolNames.ReadFile, diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index d462158c9..83d9dff6d 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -5,7 +5,7 @@ import { BuiltInToolNames } from "../builtIn"; export const searchWebTool: Tool = { type: "function", displayTitle: "Search Web", - wouldLikeTo: "search the web", + wouldLikeTo: 'search the web for "{{ query }}"', readonly: true, function: { name: BuiltInToolNames.SearchWeb, diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts index e3c1d034b..65247f144 100644 --- a/core/tools/definitions/viewSubdirectory.ts +++ b/core/tools/definitions/viewSubdirectory.ts @@ -1,11 +1,10 @@ import { Tool } from "../.."; - import { BuiltInToolNames } from "../builtIn"; export const viewSubdirectoryTool: Tool = { type: "function", displayTitle: "View Subdirectory", - wouldLikeTo: "view the contents of a subdirectory", + wouldLikeTo: 'view the contents of "{{ directory_path }}"', readonly: true, function: { name: BuiltInToolNames.ViewSubdirectory, @@ -16,7 +15,8 @@ export const viewSubdirectoryTool: Tool = { properties: { directory_path: { type: "string", - description: "The path of the subdirectory to view", + description: + "The path of the subdirectory to view, relative to the root of the workspace", }, }, }, diff --git a/gui/package-lock.json b/gui/package-lock.json index 88481b71e..1b087fdf9 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -30,6 +30,7 @@ "downshift": "^7.6.0", "lodash": "^4.17.21", "minisearch": "^7.0.2", + "mustache": "^4.2.0", "onigasm": "^2.2.5", "posthog-js": "^1.130.1", "prismjs": "^1.29.0", @@ -70,6 +71,7 @@ "@testing-library/react": "^16.0.1", "@testing-library/user-event": "^14.5.2", "@types/lodash": "^4.17.6", + "@types/mustache": "^4.2.5", "@types/node": "^20.5.6", "@types/node-fetch": "^2.6.4", "@types/react": "^18.3.11", @@ -3121,6 +3123,12 @@ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-0.7.34.tgz", "integrity": "sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g==" }, + "node_modules/@types/mustache": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@types/mustache/-/mustache-4.2.5.tgz", + "integrity": "sha512-PLwiVvTBg59tGFL/8VpcGvqOu3L4OuveNvPi0EYbWchRdEVP++yRUXJPFl+CApKEq13017/4Nf7aQ5lTtHUNsA==", + "dev": true + }, "node_modules/@types/node": { "version": "20.16.5", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.16.5.tgz", @@ -9357,6 +9365,14 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" }, + "node_modules/mustache": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz", + "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==", + "bin": { + "mustache": "bin/mustache" + } + }, "node_modules/mz": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", diff --git a/gui/package.json b/gui/package.json index 989aa882a..c305006b8 100644 --- a/gui/package.json +++ b/gui/package.json @@ -38,6 +38,7 @@ "downshift": "^7.6.0", "lodash": "^4.17.21", "minisearch": "^7.0.2", + "mustache": "^4.2.0", "onigasm": "^2.2.5", "posthog-js": "^1.130.1", "prismjs": "^1.29.0", @@ -78,6 +79,7 @@ "@testing-library/react": "^16.0.1", "@testing-library/user-event": "^14.5.2", "@types/lodash": "^4.17.6", + "@types/mustache": "^4.2.5", "@types/node": "^20.5.6", "@types/node-fetch": "^2.6.4", "@types/react": "^18.3.11", diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index d17842cb7..15dad8a85 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -33,7 +33,7 @@ const BackgroundDiv = styled.div<{ useTools: boolean }>` transition: background-color 200ms; `; -export default function ToolDropdown({}: {}) { +export default function ToolDropdown() { const buttonRef = useRef(null); const dispatch = useDispatch(); const [isDropdownOpen, setDropdownOpen] = useState(false); @@ -61,7 +61,7 @@ export default function ToolDropdown({}: {}) { } }, [isDropdownOpen]); - if (!modelSupportsTools(defaultModel.model)) { + if (!defaultModel || !modelSupportsTools(defaultModel.model)) { return null; } diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 6ab4efce4..8234f3feb 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -369,9 +369,10 @@ export function Chat() { item.message.toolCalls && item.toolCallState ? (
- {item.message.toolCalls?.map((toolCall) => { + {item.message.toolCalls?.map((toolCall, i) => { return ( diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 34044d71f..0a5ed2ebd 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -18,7 +18,12 @@ function FunctionSpecificToolCallDiv({ ); case "run_terminal_command": - return ; + return ( + + ); case "exact_search": return ; default: diff --git a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx index d3c96419f..97c628a0c 100644 --- a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx @@ -1,4 +1,5 @@ -import { ToolCall } from "core"; +import { Tool, ToolCall, ToolCallState } from "core"; +import Mustache from "mustache"; import { useSelector } from "react-redux"; import styled from "styled-components"; import { RootState } from "../../../redux/store"; @@ -7,6 +8,7 @@ interface ThreadDivProps { children: React.ReactNode; icon: React.ReactNode; toolCall: ToolCall; + toolCallState: ToolCallState; } const Container = styled.div` @@ -34,6 +36,17 @@ export function ThreadDiv(props: ThreadDivProps) { (state: RootState) => state.state.config.tools, ); + function renderWouldLikeToMessage( + tool: Tool, + toolCallState: ToolCallState, + ): string { + const rendered = Mustache.render( + tool.wouldLikeTo, + toolCallState.parsedArgs, + ); + return rendered; + } + return ( @@ -48,11 +61,12 @@ export function ThreadDiv(props: ThreadDivProps) { {props.icon}
Continue wants to{" "} - { + {renderWouldLikeToMessage( availableTools.find( (tool) => props.toolCall.function.name === tool.function.name, - )?.wouldLikeTo - } + ), + props.toolCallState, + )} {props.children} diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 745bb78c4..5b21b8fc5 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -12,6 +12,7 @@ import { ThreadDiv } from "./ThreadDiv"; interface ToolCallDivProps { toolCall: ToolCall; toolCallState: ToolCallState; + key: number; } export function ToolCallDiv(props: ToolCallDivProps) { @@ -31,8 +32,10 @@ export function ToolCallDiv(props: ToolCallDivProps) { return ( Date: Fri, 29 Nov 2024 14:48:43 -0800 Subject: [PATCH 090/105] fix viewSubdirectory tool --- core/tools/implementations/viewSubdirectory.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/core/tools/implementations/viewSubdirectory.ts b/core/tools/implementations/viewSubdirectory.ts index 8ac126a58..a8204ca6a 100644 --- a/core/tools/implementations/viewSubdirectory.ts +++ b/core/tools/implementations/viewSubdirectory.ts @@ -1,11 +1,21 @@ import generateRepoMap from "../../util/generateRepoMap"; +import { resolveRelativePathInWorkspace } from "../../util/ideUtils"; import { ToolImpl } from "."; export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => { const { directory_path } = args; + const absolutePath = await resolveRelativePathInWorkspace( + directory_path, + extras.ide, + ); + + if (!absolutePath) { + throw new Error(`Directory path "${directory_path}" does not exist.`); + } + const repoMap = await generateRepoMap(extras.llm, extras.ide, { - dirs: [directory_path], + dirs: [absolutePath], }); return [ { From a1ef58dbf5a9ab12f263f86f57f225dd8c8f2295 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 14:49:09 -0800 Subject: [PATCH 091/105] various UI bug fixes --- .../components/modelSelection/ModelSelect.tsx | 10 +-- gui/src/pages/gui/Chat.tsx | 5 +- gui/src/pages/gui/ToolCallDiv/ExactSearch.tsx | 14 ---- .../FunctionSpecificToolCallDiv.tsx | 3 - gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx | 7 +- .../gui/ToolCallDiv/ToolCallButtonsDiv.tsx | 17 ++--- gui/src/redux/thunks/callTool.ts | 7 +- gui/src/redux/thunks/cancelTool.ts | 70 +++++++++++++++++++ gui/src/redux/thunks/streamNormalInput.ts | 1 + .../thunks/streamResponseAfterToolCall.ts | 2 - 10 files changed, 92 insertions(+), 44 deletions(-) delete mode 100644 gui/src/pages/gui/ToolCallDiv/ExactSearch.tsx create mode 100644 gui/src/redux/thunks/cancelTool.ts diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 472593211..b89715a35 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -105,14 +105,14 @@ const StyledListboxOption = styled(Listbox.Option)<{ isDisabled?: boolean }>` `} `; -const IconBase = styled.div<{ hovered: boolean }>` +const IconBase = styled.div<{ $hovered: boolean }>` width: 1.2em; height: 1.2em; cursor: pointer; padding: 4px; border-radius: ${defaultBorderRadius}; - opacity: ${(props) => (props.hovered ? 0.75 : 0)}; - visibility: ${(props) => (props.hovered ? "visible" : "hidden")}; + opacity: ${(props) => (props.$hovered ? 0.75 : 0)}; + visibility: ${(props) => (props.$hovered ? "visible" : "hidden")}; &:hover { opacity: 1; @@ -204,9 +204,9 @@ function ModelOption({
- + {showDelete && ( - + )}
diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 8234f3feb..b65e571b2 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -184,7 +184,7 @@ export function Chat() { isMetaEquivalentKeyPressed(e) && !e.shiftKey ) { - dispatch(cancelGeneration()); + // dispatch(cancelGeneration()); TODO!!! } }; window.addEventListener("keydown", listener); @@ -506,6 +506,3 @@ export function Chat() { ); } -function cancelGeneration(): any { - throw new Error("Function not implemented."); -} diff --git a/gui/src/pages/gui/ToolCallDiv/ExactSearch.tsx b/gui/src/pages/gui/ToolCallDiv/ExactSearch.tsx deleted file mode 100644 index ed4b47321..000000000 --- a/gui/src/pages/gui/ToolCallDiv/ExactSearch.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; - -interface ExactSearchToolCallProps { - query: string; -} - -export function ExactSearch(props: ExactSearchToolCallProps) { - return ( - - ); -} diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 0a5ed2ebd..d55055b03 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -1,6 +1,5 @@ import { ToolCall, ToolCallState } from "core"; import { CreateFile } from "./CreateFile"; -import { ExactSearch } from "./ExactSearch"; import { RunTerminalCommand } from "./RunTerminalCommand"; function FunctionSpecificToolCallDiv({ @@ -24,8 +23,6 @@ function FunctionSpecificToolCallDiv({ toolCallState={toolCallState} /> ); - case "exact_search": - return ; default: return null; } diff --git a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx index 97c628a0c..e02e1b28d 100644 --- a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx @@ -9,6 +9,7 @@ interface ThreadDivProps { icon: React.ReactNode; toolCall: ToolCall; toolCallState: ToolCallState; + key: number; } const Container = styled.div` @@ -37,9 +38,11 @@ export function ThreadDiv(props: ThreadDivProps) { ); function renderWouldLikeToMessage( - tool: Tool, + tool: Tool | undefined, toolCallState: ToolCallState, ): string { + if (!tool) return ""; + const rendered = Mustache.render( tool.wouldLikeTo, toolCallState.parsedArgs, @@ -48,7 +51,7 @@ export function ThreadDiv(props: ThreadDivProps) { } return ( - +
) : toolCallState.status === "generated" ? ( <> - Cancel + dispatch(cancelTool())}> + Cancel + dispatch(callTool())}> Continue diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 6541648f3..b022b3497 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -1,6 +1,10 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; -import { setCalling, setToolCallOutput } from "../slices/stateSlice"; +import { + acceptToolCall, + setCalling, + setToolCallOutput, +} from "../slices/stateSlice"; import { ThunkApiType } from "../store"; import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; @@ -28,6 +32,7 @@ export const callTool = createAsyncThunk( if (result.status === "success") { const contextItems = result.content.contextItems; dispatch(setToolCallOutput(contextItems)); + dispatch(acceptToolCall()); // Send to the LLM to continue the conversation dispatch( diff --git a/gui/src/redux/thunks/cancelTool.ts b/gui/src/redux/thunks/cancelTool.ts new file mode 100644 index 000000000..8bd09e911 --- /dev/null +++ b/gui/src/redux/thunks/cancelTool.ts @@ -0,0 +1,70 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; +import { + cancelToolCall, + setCalling, + setToolCallOutput, +} from "../slices/stateSlice"; +import { ThunkApiType } from "../store"; +import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; + +export const cancelTool = createAsyncThunk( + "chat/callTool", + async (_, { dispatch, extra, getState }) => { + const state = getState(); + const toolCallState = selectCurrentToolCall(state); + + if (!toolCallState) { + return; + } + + if (toolCallState.status !== "generated") { + return; + } + + dispatch(cancelToolCall()); + + dispatch( + streamResponseAfterToolCall({ + toolCallId: toolCallState.toolCallId, + toolOutput: [], + }), + ); + }, +); + +export const callTool = createAsyncThunk( + "chat/callTool", + async (_, { dispatch, extra, getState }) => { + const state = getState(); + const toolCallState = selectCurrentToolCall(state); + + console.log("calling tool", toolCallState.toolCall); + if (!toolCallState) { + return; + } + + if (toolCallState.status !== "generated") { + return; + } + + dispatch(setCalling()); + + const result = await extra.ideMessenger.request("tools/call", { + toolCall: toolCallState.toolCall, + }); + + if (result.status === "success") { + const contextItems = result.content.contextItems; + dispatch(setToolCallOutput(contextItems)); + + // Send to the LLM to continue the conversation + dispatch( + streamResponseAfterToolCall({ + toolCallId: toolCallState.toolCall.id, + toolOutput: contextItems, + }), + ); + } + }, +); diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 05d5147e1..d17f2d870 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -43,6 +43,7 @@ export const streamNormalInput = createAsyncThunk< (tool) => tool.function.name === toolName, ), ) + .filter(Boolean) : undefined, }, ); diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 97f7c15d9..6652f3a0e 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -4,7 +4,6 @@ import { constructMessages } from "core/llm/constructMessages"; import { renderContextItems } from "core/util/messageContent"; import { defaultModelSelector } from "../selectors/modelSelectors"; import { - acceptToolCall, addContextItemsAtIndex, setActive, streamUpdate, @@ -32,7 +31,6 @@ export const streamResponseAfterToolCall = createAsyncThunk< resetStateForNewMessage(); - dispatch(acceptToolCall()); await new Promise((resolve) => setTimeout(resolve, 0)); const newMessage: ChatMessage = { From dfb358aace176a901fa40dd36b06c3e4f1355bc3 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 14:50:56 -0800 Subject: [PATCH 092/105] non-escaped mustache templating --- core/tools/definitions/exactSearch.ts | 2 +- core/tools/definitions/readFile.ts | 2 +- core/tools/definitions/searchWeb.ts | 2 +- core/tools/definitions/viewSubdirectory.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/core/tools/definitions/exactSearch.ts b/core/tools/definitions/exactSearch.ts index 524dcb6f5..99d243f91 100644 --- a/core/tools/definitions/exactSearch.ts +++ b/core/tools/definitions/exactSearch.ts @@ -4,7 +4,7 @@ import { BuiltInToolNames } from "../builtIn"; export const exactSearchTool: Tool = { type: "function", displayTitle: "Exact Search", - wouldLikeTo: 'search for "{{ query }}" in the repository', + wouldLikeTo: 'search for "{{{ query }}}" in the repository', readonly: true, function: { name: BuiltInToolNames.ExactSearch, diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts index e64e32728..00e16ba32 100644 --- a/core/tools/definitions/readFile.ts +++ b/core/tools/definitions/readFile.ts @@ -4,7 +4,7 @@ import { BuiltInToolNames } from "../builtIn"; export const readFileTool: Tool = { type: "function", displayTitle: "Read File", - wouldLikeTo: "read {{ filepath }}", + wouldLikeTo: "read {{{ filepath }}}", readonly: true, function: { name: BuiltInToolNames.ReadFile, diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index 83d9dff6d..eb8e58c99 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -5,7 +5,7 @@ import { BuiltInToolNames } from "../builtIn"; export const searchWebTool: Tool = { type: "function", displayTitle: "Search Web", - wouldLikeTo: 'search the web for "{{ query }}"', + wouldLikeTo: 'search the web for "{{{ query }}}"', readonly: true, function: { name: BuiltInToolNames.SearchWeb, diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts index 65247f144..70b7524bd 100644 --- a/core/tools/definitions/viewSubdirectory.ts +++ b/core/tools/definitions/viewSubdirectory.ts @@ -4,7 +4,7 @@ import { BuiltInToolNames } from "../builtIn"; export const viewSubdirectoryTool: Tool = { type: "function", displayTitle: "View Subdirectory", - wouldLikeTo: 'view the contents of "{{ directory_path }}"', + wouldLikeTo: 'view the contents of "{{{ directory_path }}}"', readonly: true, function: { name: BuiltInToolNames.ViewSubdirectory, From 98582d00e4271b861efcd0c488af41d0e403871f Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 14:58:44 -0800 Subject: [PATCH 093/105] tell llm tool was cancelled --- core/context/providers/utils.ts | 1 + core/index.d.ts | 1 + gui/src/components/mainInput/ContextItemsPeek.tsx | 7 +------ gui/src/redux/thunks/cancelTool.ts | 10 +++++++++- 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/core/context/providers/utils.ts b/core/context/providers/utils.ts index 7bc20e491..fd73a9bec 100644 --- a/core/context/providers/utils.ts +++ b/core/context/providers/utils.ts @@ -4,4 +4,5 @@ export const INSTRUCTIONS_BASE_ITEM: ContextItem = { name: "Instructions", description: "Instructions", content: "", + hidden: true, }; diff --git a/core/index.d.ts b/core/index.d.ts index 6da58c81b..178cf5b4c 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -364,6 +364,7 @@ export interface ContextItem { editable?: boolean; icon?: string; uri?: ContextItemUri; + hidden?: boolean; } export interface ContextItemWithId extends ContextItem { diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index ddac0046c..80ed7243a 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -5,7 +5,6 @@ import { } from "@heroicons/react/24/outline"; import { ContextItemWithId } from "core"; import { ctxItemToRifWithContents } from "core/commands/util"; -import { INSTRUCTIONS_BASE_ITEM } from "core/context/providers/utils"; import { getBasename } from "core/util"; import { useContext, useMemo, useState } from "react"; import { useSelector } from "react-redux"; @@ -136,11 +135,7 @@ function ContextItemsPeek({ const [open, setOpen] = useState(false); const ctxItems = useMemo(() => { - return ( - contextItems?.filter( - (ctxItem) => !ctxItem.name.includes(INSTRUCTIONS_BASE_ITEM.name), - ) ?? [] - ); + return contextItems?.filter((ctxItem) => !ctxItem.hidden) ?? []; }, [contextItems]); const isGatheringContext = useSelector( diff --git a/gui/src/redux/thunks/cancelTool.ts b/gui/src/redux/thunks/cancelTool.ts index 8bd09e911..c93c4585c 100644 --- a/gui/src/redux/thunks/cancelTool.ts +++ b/gui/src/redux/thunks/cancelTool.ts @@ -27,7 +27,15 @@ export const cancelTool = createAsyncThunk( dispatch( streamResponseAfterToolCall({ toolCallId: toolCallState.toolCallId, - toolOutput: [], + toolOutput: [ + { + name: "Tool Cancelled", + description: "Tool Cancelled", + content: + "The tool call was cancelled by the user. Please try something else or request further instructions.", + hidden: true, + }, + ], }), ); }, From aee7e21bce408523ce8e9e2bf9ee2edd86a9de7c Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 15:08:52 -0800 Subject: [PATCH 094/105] read current file tool --- core/tools/builtIn.ts | 1 + core/tools/callTool.ts | 4 ++++ .../definitions/readCurrentlyOpenFile.ts | 18 +++++++++++++++++ .../implementations/readCurrentlyOpenFile.ts | 20 +++++++++++++++++++ core/tools/index.ts | 2 ++ 5 files changed, 45 insertions(+) create mode 100644 core/tools/definitions/readCurrentlyOpenFile.ts create mode 100644 core/tools/implementations/readCurrentlyOpenFile.ts diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index 255967568..55e2c5214 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -1,5 +1,6 @@ export enum BuiltInToolNames { ReadFile = "read_file", + ReadCurrentlyOpenFile = "read_currently_open_file", CreateNewFile = "create_new_file", RunTerminalCommand = "run_terminal_command", ViewSubdirectory = "view_subdirectory", diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index d34851787..4e7028d68 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -1,8 +1,10 @@ import { ContextItem, ToolExtras } from ".."; import MCPConnectionSingleton from "../context/mcp"; import { BuiltInToolNames } from "./builtIn"; + import { createNewFileImpl } from "./implementations/createNewFile"; import { exactSearchImpl } from "./implementations/exactSearch"; +import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile"; import { readFileImpl } from "./implementations/readFile"; import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; import { searchWebImpl } from "./implementations/searchWeb"; @@ -99,6 +101,8 @@ export async function callTool( return await viewRepoMapImpl(args, extras); case BuiltInToolNames.ViewSubdirectory: return await viewSubdirectoryImpl(args, extras); + case BuiltInToolNames.ReadCurrentlyOpenFile: + return await readCurrentlyOpenFileImpl(args, extras); default: return await callToolFromUri(uri, args, extras); } diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts new file mode 100644 index 000000000..79497a158 --- /dev/null +++ b/core/tools/definitions/readCurrentlyOpenFile.ts @@ -0,0 +1,18 @@ +import { Tool } from "../.."; +import { BuiltInToolNames } from "../builtIn"; + +export const readCurrentlyOpenFileTool: Tool = { + type: "function", + displayTitle: "Read Currently Open File", + wouldLikeTo: "read the current file", + readonly: true, + function: { + name: BuiltInToolNames.ReadCurrentlyOpenFile, + description: + "Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, this is probably it.", + parameters: { + type: "object", + properties: {}, + }, + }, +}; diff --git a/core/tools/implementations/readCurrentlyOpenFile.ts b/core/tools/implementations/readCurrentlyOpenFile.ts new file mode 100644 index 000000000..7fff3b621 --- /dev/null +++ b/core/tools/implementations/readCurrentlyOpenFile.ts @@ -0,0 +1,20 @@ +import { ToolImpl } from "."; +import { getBasename } from "../../util"; + +export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => { + const result = await extras.ide.getCurrentFile(); + + if (!result) { + return []; + } + + const basename = getBasename(result.path); + + return [ + { + name: "Current file", + description: basename, + content: `\`\`\`${basename}\n${result.contents}\n\`\`\``, + }, + ]; +}; diff --git a/core/tools/index.ts b/core/tools/index.ts index 86dfc82c5..c27860a6f 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,5 +1,6 @@ import { createNewFileTool } from "./definitions/createNewFile"; import { exactSearchTool } from "./definitions/exactSearch"; +import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile"; import { readFileTool } from "./definitions/readFile"; import { runTerminalCommandTool } from "./definitions/runTerminalCommand"; import { searchWebTool } from "./definitions/searchWeb"; @@ -16,4 +17,5 @@ export const allTools = [ exactSearchTool, searchWebTool, viewDiffTool, + readCurrentlyOpenFileTool, ]; From 73b8496ef895f00e0768271df631a8b3aa99aceb Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Fri, 29 Nov 2024 15:51:58 -0800 Subject: [PATCH 095/105] improv: use import definition snippets --- core/autocomplete/templating/filtering.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/autocomplete/templating/filtering.ts b/core/autocomplete/templating/filtering.ts index bc85fb909..a6cdf0957 100644 --- a/core/autocomplete/templating/filtering.ts +++ b/core/autocomplete/templating/filtering.ts @@ -46,7 +46,7 @@ export const getSnippets = ( ...payload.clipboardSnippets, ...shuffleArray( filterSnippetsAlreadyInCaretWindow( - [...payload.rootPathSnippets], + [...payload.rootPathSnippets, ...payload.importDefinitionSnippets], helper.prunedCaretWindow, ), ), From 63e63f54cd08c99bfe7877ecaf81c2f8dc8e67e9 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Fri, 29 Nov 2024 15:54:11 -0800 Subject: [PATCH 096/105] improv: update suffix and prefix percentages, clean up code --- core/autocomplete/templating/index.ts | 1 - core/util/parameters.ts | 6 ++++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 8a2cfaae4..8aaa98248 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -10,7 +10,6 @@ import { getTemplateForModel, } from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; -import { AutocompleteCodeSnippet } from "../snippets/types"; import { SnippetPayload } from "../snippets"; import { formatSnippets } from "./formatting"; import { getSnippets } from "./filtering"; diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 24e94781c..a7a11b503 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -4,11 +4,13 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { disable: false, useFileSuffix: true, maxPromptTokens: 1024, - prefixPercentage: 0.85, - maxSuffixPercentage: 0.25, + prefixPercentage: 0.3, + maxSuffixPercentage: 0.2, debounceDelay: 350, multilineCompletions: "auto", + // @deprecated TO BE REMOVED slidingWindowPrefixPercentage: 0.75, + // @deprecated TO BE REMOVED slidingWindowSize: 500, useCache: true, onlyMyCode: true, From 832927553a39e925665cc824616aa4f11f02015a Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 16:09:43 -0800 Subject: [PATCH 097/105] fix ripgrep search again --- extensions/vscode/src/VsCodeIde.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 3871acd4a..5138ba490 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -531,8 +531,14 @@ class VsCodeIde implements IDE { "bin", "rg", ), - ["-i", "-C", "2", "-F", "--", `"${query}"`, "."], //no regex - //["-i", "-C", "2", "-e", `${query}`, "."], //use regex + [ + "-i", // Case-insensitive search + "-C", + "2", // Show 2 lines of context + "-e", + query, // Pattern to search for + ".", // Directory to search in + ], { cwd: dir }, ); let output = ""; @@ -547,7 +553,8 @@ class VsCodeIde implements IDE { if (code === 0) { resolve(output); } else if (code === 1) { - resolve(output); + // No matches + resolve("No matches found"); } else { reject(new Error(`Process exited with code ${code}`)); } From e992e1ff290abc77909f1b60c4d21e7030dad730 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 16:09:55 -0800 Subject: [PATCH 098/105] fix key err --- core/config/load.ts | 4 ++-- core/tools/definitions/exactSearch.ts | 5 +++-- gui/src/pages/gui/Chat.tsx | 12 +++++++----- gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx | 5 +++-- gui/src/pages/gui/ToolCallDiv/index.tsx | 4 ++-- 5 files changed, 17 insertions(+), 13 deletions(-) diff --git a/core/config/load.ts b/core/config/load.ts index 5c21a0656..1e16913e5 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -505,8 +505,8 @@ async function intermediateToFinalConfig( mcpConnection.modifyConfig(continueConfig), new Promise((_, reject) => setTimeout( - () => reject(new Error("MCP connection timed out after 1000ms")), - 1000, + () => reject(new Error("MCP connection timed out after 2000ms")), + 2000, ), ), ]).catch((error) => { diff --git a/core/tools/definitions/exactSearch.ts b/core/tools/definitions/exactSearch.ts index 99d243f91..8358b55da 100644 --- a/core/tools/definitions/exactSearch.ts +++ b/core/tools/definitions/exactSearch.ts @@ -8,14 +8,15 @@ export const exactSearchTool: Tool = { readonly: true, function: { name: BuiltInToolNames.ExactSearch, - description: "Perform an exact search over the repository using ripgrep", + description: "Perform an exact search over the repository using ripgrep.", parameters: { type: "object", required: ["query"], properties: { query: { type: "string", - description: "The search query to use", + description: + "The search query to use. Must be a valid ripgrep regex expression, escaped where needed", }, }, }, diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index b65e571b2..f297e71da 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -371,11 +371,13 @@ export function Chat() {
{item.message.toolCalls?.map((toolCall, i) => { return ( - +
+ +
); })}
diff --git a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx index e02e1b28d..e02eaca8f 100644 --- a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx @@ -9,7 +9,7 @@ interface ThreadDivProps { icon: React.ReactNode; toolCall: ToolCall; toolCallState: ToolCallState; - key: number; + reactKey: string; } const Container = styled.div` @@ -51,7 +51,7 @@ export function ThreadDiv(props: ThreadDivProps) { } return ( - +
{props.icon} diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 5b21b8fc5..e1745c459 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -12,7 +12,7 @@ import { ThreadDiv } from "./ThreadDiv"; interface ToolCallDivProps { toolCall: ToolCall; toolCallState: ToolCallState; - key: number; + reactKey: string; } export function ToolCallDiv(props: ToolCallDivProps) { @@ -32,7 +32,7 @@ export function ToolCallDiv(props: ToolCallDivProps) { return ( Date: Fri, 29 Nov 2024 16:29:03 -0800 Subject: [PATCH 099/105] responsive ui for tools button --- gui/src/components/mainInput/InputToolbar.tsx | 2 +- .../components/mainInput/InputToolbar/ToggleToolsButton.tsx | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index ea85c7b2e..1aec78c92 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -147,7 +147,7 @@ function InputToolbar(props: InputToolbarProps) {
{props.activeKey === "Alt" ? ( - {`${getAltKeyLabel()}⏎ + {`${getAltKeyLabel()}⏎ ${useActiveFile ? "No active file" : "Active file"}`} ) : ( diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index 15dad8a85..1c91aee04 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -28,7 +28,7 @@ const BackgroundDiv = styled.div<{ useTools: boolean }>` display: flex; flex-direction: row; align-items: center; - gap: 4px; + gap: 2px; transition: background-color 200ms; `; @@ -78,7 +78,7 @@ export default function ToolDropdown() { /> {useTools && ( <> - Tools + Tools
{}}> @@ -98,7 +98,7 @@ export default function ToolDropdown() {
Date: Fri, 29 Nov 2024 16:35:44 -0800 Subject: [PATCH 100/105] fix tsc error --- core/tools/callTool.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 4e7028d68..69307100e 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -44,7 +44,7 @@ async function callToolFromUri( if (!canParse) { throw new Error(`Invalid URI: ${uri}`); } - const parsedUri = URL.parse(uri)!; + const parsedUri = new URL(uri); switch (parsedUri?.protocol) { case "http:": From f420e7d9a4e48a1b9cbf148fb1364aaa6304d982 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 16:47:52 -0800 Subject: [PATCH 101/105] changelog and version bump --- .changes/unreleased/Added-20241129-164631.yaml | 4 ++++ .changes/unreleased/Added-20241129-164644.yaml | 4 ++++ extensions/vscode/CHANGELOG.md | 5 +++++ extensions/vscode/package.json | 2 +- 4 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 .changes/unreleased/Added-20241129-164631.yaml create mode 100644 .changes/unreleased/Added-20241129-164644.yaml diff --git a/.changes/unreleased/Added-20241129-164631.yaml b/.changes/unreleased/Added-20241129-164631.yaml new file mode 100644 index 000000000..cec797027 --- /dev/null +++ b/.changes/unreleased/Added-20241129-164631.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Tool use +time: 2024-11-29T16:46:31.677532-08:00 diff --git a/.changes/unreleased/Added-20241129-164644.yaml b/.changes/unreleased/Added-20241129-164644.yaml new file mode 100644 index 000000000..7dfa427dd --- /dev/null +++ b/.changes/unreleased/Added-20241129-164644.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Support for Model Context Protocol +time: 2024-11-29T16:46:44.960691-08:00 diff --git a/extensions/vscode/CHANGELOG.md b/extensions/vscode/CHANGELOG.md index d33482747..8f6a1cd01 100644 --- a/extensions/vscode/CHANGELOG.md +++ b/extensions/vscode/CHANGELOG.md @@ -5,6 +5,11 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html), and is generated by [Changie](https://github.com/miniscruff/changie). +Pre-release Changes +### Added +* Tool use +* Support for Model Context Protocol + ## 0.8.59 - 2024-11-25 ### Fixed * Hotfix for Ollama onboarding diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index af638882d..a88bffe51 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.237", + "version": "0.9.238", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From 1db3a87fde12896105db98927d55c3af45dfe17a Mon Sep 17 00:00:00 2001 From: Big Boss Date: Sun, 24 Nov 2024 15:54:58 -0600 Subject: [PATCH 102/105] handle RangeError during didChangeActiveTextEditor This can happen when path.relative returns something like `../foo`. --- core/core.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/core/core.ts b/core/core.ts index 2108d3706..1eaef976d 100644 --- a/core/core.ts +++ b/core/core.ts @@ -775,8 +775,16 @@ export class Core { const ignoreInstance = ignore().add(defaultIgnoreFile); let rootDirectory = await this.ide.getWorkspaceDirs(); const relativeFilePath = path.relative(rootDirectory[0], filepath); - if (!ignoreInstance.ignores(relativeFilePath)) { - recentlyEditedFilesCache.set(filepath, filepath); + try { + if (!ignoreInstance.ignores(relativeFilePath)) { + recentlyEditedFilesCache.set(filepath, filepath); + } + } catch (e) { + if (e instanceof RangeError) { + // do nothing, this can happen when editing a file outside the workspace such as `../extensions/.continue-debug/config.json` + } else { + console.debug("unhandled ignores error", relativeFilePath, e); + } } }); From 1d29cfa4bca58b5b61157cd08171d2c3fbfdf071 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 21:23:01 -0800 Subject: [PATCH 103/105] hide tools in edit mode --- gui/src/pages/edit/Edit.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/gui/src/pages/edit/Edit.tsx b/gui/src/pages/edit/Edit.tsx index d1c8f343f..2447fdb41 100644 --- a/gui/src/pages/edit/Edit.tsx +++ b/gui/src/pages/edit/Edit.tsx @@ -6,6 +6,7 @@ import { useCallback, useContext, useEffect, useMemo } from "react"; import { useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; +import { ToolbarOptions } from "../../components/mainInput/InputToolbar"; import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; import resolveEditorContent from "../../components/mainInput/resolveInput"; import TipTapEditor from "../../components/mainInput/TipTapEditor"; @@ -87,11 +88,12 @@ export default function Edit() { editModeState.editStatus === "streaming" || editModeState.editStatus === "accepting"; - const toolbarOptions = { + const toolbarOptions: ToolbarOptions = { hideAddContext: false, hideImageUpload: false, hideUseCodebase: true, hideSelectModel: false, + hideTools: true, enterText: isStreaming ? "Retry" : "Edit", }; From 0f5be8ba5fd8f4564486daac56966b05bad2d86e Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 29 Nov 2024 21:57:57 -0800 Subject: [PATCH 104/105] hotfix: openai displaying as undefinedundefinedundefined --- core/llm/llms/Cloudflare.ts | 5 ++++- core/llm/llms/OpenAI.ts | 7 +++++-- extensions/vscode/package.json | 2 +- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/core/llm/llms/Cloudflare.ts b/core/llm/llms/Cloudflare.ts index 215e97b37..3c4766365 100644 --- a/core/llm/llms/Cloudflare.ts +++ b/core/llm/llms/Cloudflare.ts @@ -41,7 +41,10 @@ export default class Cloudflare extends BaseLLM { for await (const value of streamSse(resp)) { if (value.choices?.[0]?.delta?.content) { - yield value.choices[0].delta; + yield { + role: "assistant", + content: value.choices[0].delta, + }; } } } diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 35d05a62d..ed9810932 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -310,7 +310,10 @@ class OpenAI extends BaseLLM { for await (const value of streamSse(response)) { if (value.choices?.[0]?.delta?.content) { - yield value.choices[0].delta; + yield { + role: "assistant", + content: value.choices[0].delta.content, + }; } else if (value.choices?.[0]?.delta?.tool_calls) { yield { role: "assistant", @@ -375,4 +378,4 @@ class OpenAI extends BaseLLM { } } -export default OpenAI; \ No newline at end of file +export default OpenAI; diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index a88bffe51..a1b19a226 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.238", + "version": "0.9.239", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From ddca5ab9407c29f373e5f37bddb43b34c41a843a Mon Sep 17 00:00:00 2001 From: Big Boss Date: Sat, 30 Nov 2024 09:22:28 -0600 Subject: [PATCH 105/105] fix order of providers in config schema function-network & siliconflow had their markdown descriptions mixed up. --- extensions/vscode/config_schema.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index ba68ed19a..86a9d54a2 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -207,8 +207,8 @@ "xAI", "kindo", "moonshot", - "function-network", - "siliconflow" + "siliconflow", + "function-network" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)",