From e2bd9cc2b7236a3959fa42baa73d303a9622c4b6 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 15 Nov 2024 09:43:40 -0800 Subject: [PATCH 001/747] 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/747] 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/747] 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/747] 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/747] 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/747] 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/747] 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/747] 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/747] 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/747] 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/747] 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/747] 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 4b866097e0c9086e756932d80e2568a650658b4b Mon Sep 17 00:00:00 2001 From: Anoyi <545544032@qq.com> Date: Mon, 18 Nov 2024 17:27:14 +0800 Subject: [PATCH 013/747] support `Qwen/Qwen2.5-Coder-32B-Instruct` model provided by siliconflow --- core/config/validation.ts | 3 ++- core/llm/llms/OpenAI.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/core/config/validation.ts b/core/config/validation.ts index 062c0eaed..e10b3f523 100644 --- a/core/config/validation.ts +++ b/core/config/validation.ts @@ -63,7 +63,8 @@ export function validateConfig(config: SerializedContinueConfig) { if ( nonAutocompleteModels.some((m) => modelName.includes(m)) && !modelName.includes("deepseek") && - !modelName.includes("codestral") + !modelName.includes("codestral") && + !modelName.toLowerCase().includes("coder") ) { errors.push({ fatal: false, diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 168e0afff..5463486d3 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -288,7 +288,8 @@ class OpenAI extends BaseLLM { suffix: string, options: CompletionOptions, ): AsyncGenerator { - const endpoint = new URL("fim/completions", this.apiBase); + const url = this.apiBase?.includes("api.siliconflow.cn") ? "completions" : "fim/completions" + const endpoint = new URL(url, this.apiBase); const resp = await this.fetch(endpoint, { method: "POST", body: JSON.stringify({ From 6117d789757ec330cb1661e300c0f27edc9b6e1a Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 18 Nov 2024 14:20:50 -0800 Subject: [PATCH 014/747] 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 015/747] 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 016/747] 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 acf832aab265d43d0c7774e930ec0839c99c7437 Mon Sep 17 00:00:00 2001 From: Anoyi <545544032@qq.com> Date: Tue, 19 Nov 2024 17:26:50 +0800 Subject: [PATCH 017/747] Update OpenAI.ts --- core/llm/llms/OpenAI.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 5463486d3..27f1e76cb 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -288,8 +288,7 @@ class OpenAI extends BaseLLM { suffix: string, options: CompletionOptions, ): AsyncGenerator { - const url = this.apiBase?.includes("api.siliconflow.cn") ? "completions" : "fim/completions" - const endpoint = new URL(url, this.apiBase); + const endpoint = this.apiBase?.includes("completions") ? new URL(this.apiBase) : new URL("fim/completions", this.apiBase); const resp = await this.fetch(endpoint, { method: "POST", body: JSON.stringify({ From b23d36e18994898540690927558a5420aa120450 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 11:14:49 -0800 Subject: [PATCH 018/747] 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 019/747] 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 020/747] 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 021/747] 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 022/747] 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 023/747] 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 024/747] 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 025/747] 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 026/747] 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 027/747] 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 028/747] 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 029/747] 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 030/747] 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 031/747] 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 032/747] 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 cb071a74194f656a462f53ed503ba725c31958e3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 21 Nov 2024 00:42:09 -0800 Subject: [PATCH 033/747] package file parsers --- core/core.ts | 4 + core/indexing/docs/suggestions/index.ts | 100 +++++++++++++++++ .../suggestions/packageCrawlers/Python.ts | 33 ++++++ .../docs/suggestions/packageCrawlers/TsJs.ts | 33 ++++++ core/protocol/core.ts | 1 + core/protocol/passThrough.ts | 1 + extensions/vscode/package-lock.json | 4 +- gui/src/hooks/useSetup.ts | 3 +- manual-testing-sandbox/package.json | 102 ++++++++++++++++++ manual-testing-sandbox/requirements.txt | 10 ++ 10 files changed, 287 insertions(+), 4 deletions(-) create mode 100644 core/indexing/docs/suggestions/index.ts create mode 100644 core/indexing/docs/suggestions/packageCrawlers/Python.ts create mode 100644 core/indexing/docs/suggestions/packageCrawlers/TsJs.ts create mode 100644 manual-testing-sandbox/package.json create mode 100644 manual-testing-sandbox/requirements.txt diff --git a/core/core.ts b/core/core.ts index c6b336c7d..d080ec34b 100644 --- a/core/core.ts +++ b/core/core.ts @@ -40,6 +40,7 @@ import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./util/messenger"; +import { getAllSuggestedDocs } from "./indexing/docs/suggestions"; export class Core { // implements IMessenger @@ -737,6 +738,9 @@ export class Core { on("indexing/initStatuses", async (msg) => { return this.docsService.initStatuses(); }); + on("docs/getSuggestedDocs", async (msg) => { + getAllSuggestedDocs(this.ide); + }); // on("didChangeSelectedProfile", (msg) => { diff --git a/core/indexing/docs/suggestions/index.ts b/core/indexing/docs/suggestions/index.ts new file mode 100644 index 000000000..d3d68aca2 --- /dev/null +++ b/core/indexing/docs/suggestions/index.ts @@ -0,0 +1,100 @@ +// write me an interface PackageCrawler that contains: +// 1. property `language` to store a given language like "python" or "typescript" +// 2. has a method `getPackageFiles` which takes a list of file names and decides which ones match package/dependency files (e.g. package.json for typescript, requirements.txt for python, etc) +// 3. has a method `parsePackageFile` which returns a list of package name and version from a relevant package file, in a standardized format like semver +// 4. has a method `getDocumentationLink` to check for documentation link for a given package (e.g. GET `https://registry.npmjs.org/` and find docs field for typescript, documentation link in the package metadata for PyPi, etc.) +// Then, write typescript classes to implement this typescript interface for the languages "python" and "typescript" + +import { IDE } from "../../.."; +import { walkDir } from "../../walkDir"; +import { PythonPackageCrawler } from "./packageCrawlers/Python"; +import { TypeScriptPackageCrawler } from "./packageCrawlers/TsJs"; + +const PACKAGE_CRAWLERS = [TypeScriptPackageCrawler, PythonPackageCrawler]; + +export interface PackageCrawler { + language: string; + getPackageFiles(fileNames: string[]): string[]; + parsePackageFile(fileContent: string, filePath: string): PackageInfo[]; + getDocumentationLink(packageName: string): Promise; +} + +export type PackageInfo = { + name: string; + version: string; + foundInFilepath: string; +}; +export type PackageDocsResult = PackageInfo & + ({ error: string; link?: never } | { link: string; error?: never }); + +export async function getAllSuggestedDocs(ide: IDE) { + const workspaceDirs = await ide.getWorkspaceDirs(); + const results = await Promise.all( + workspaceDirs.map((dir) => { + return walkDir(dir, ide); + }), + ); + const allPaths = results.flat(); // TODO only get files, not dirs. Not critical for now + const allFiles = allPaths.map((path) => path.split("/").pop()!); + const packageFilesByLanguage: Record = {}; + for (const Crawler of PACKAGE_CRAWLERS) { + const crawler = new Crawler(); + const packageFilePaths = crawler.getPackageFiles(allFiles); + packageFilesByLanguage[crawler.language] = packageFilePaths; + } + + const uniqueFilePaths = Array.from( + new Set(Object.values(packageFilesByLanguage).flat()), + ); + const fileContentsArray = await Promise.all( + uniqueFilePaths.map(async (path) => { + const contents = await ide.readFile(path); + return { path, contents }; + }), + ); + const fileContents = new Map( + fileContentsArray.map(({ path, contents }) => [path, contents]), + ); + + const packagesByLanguage: Record = {}; + PACKAGE_CRAWLERS.forEach((Crawler) => { + const crawler = new Crawler(); + const packageFiles = packageFilesByLanguage[crawler.language]; + packageFiles.forEach((file) => { + const contents = fileContents.get(file); + if (!contents) { + return; + } + const packages = crawler.parsePackageFile(contents, file); + if (!packagesByLanguage[crawler.language]) { + packagesByLanguage[crawler.language] = []; + } + packagesByLanguage[crawler.language].push(...packages); + }); + }); + console.log(packagesByLanguage); + // const allPackages = await Promise.all( + // PACKAGE_CRAWLERS.map(async (Crawler) => { + // const crawler = new Crawler(); + // const packageInfos = uniqueFileContents + // .filter(({ path }) => languageToFilePaths[crawler.language].includes(path)) + // .map(({ path, contents }) => crawler.parsePackageFile(contents, path)) + // .flat(); + // return packageInfos; + // }) + // ); + // for (const Crawler of PACKAGE_CRAWLERS) { + // const crawler = new Crawler(); + // const packages = crawler.parsePackageFile() + // languageToFilePaths[crawler.language] = packageFilePaths; + // } +} + +// I want to present the user with a list of dependencies and allow them to select which ones to index (embed) documentation for. +// In order to prevent duplicate file reads, the process will be like this: +// 1. take in a list of filepaths called `filepaths` +// 2. loop an array of PackageCrawler classes to build a map of `language` (string) to `packageFilePaths` (string[]) +// 3. Get unique filepaths from `packageFilePaths` and build a map ` of filepath to file contents using an existing `readFile` function, and skipping file reads of already in the map +// Finally, +// Add a `` method to the interface and classes that returns +// Then, assemble the classes in an array, and write a function getAllSuggestedDocs that returns a map of `language` to an ar diff --git a/core/indexing/docs/suggestions/packageCrawlers/Python.ts b/core/indexing/docs/suggestions/packageCrawlers/Python.ts new file mode 100644 index 000000000..ac0699766 --- /dev/null +++ b/core/indexing/docs/suggestions/packageCrawlers/Python.ts @@ -0,0 +1,33 @@ +import { PackageCrawler, PackageDocsResult, PackageInfo } from ".."; + +export class PythonPackageCrawler implements PackageCrawler { + language = "python"; + + getPackageFiles(fileNames: string[]): string[] { + // For Python, we typically look for files like requirements.txt or Pipfile + return fileNames.filter( + (fileName) => fileName === "requirements.txt" || fileName === "Pipfile", + ); + } + + parsePackageFile(fileContent: string, filepath: string): PackageInfo[] { + // Assume the fileContent is a string from a requirements.txt formatted file + return fileContent + .split("\n") + .map((line) => { + const [name, version] = line.split("=="); + return { name, version, foundInFilepath: filepath }; + }) + .filter((pkg) => pkg.name && pkg.version); + } + + async getDocumentationLink(packageName: string): Promise { + // Fetch metadata from PyPI to find the documentation link + const response = await fetch(`https://pypi.org/pypi/${packageName}/json`); + if (!response.ok) { + throw new Error(`Could not fetch data for package ${packageName}`); + } + const data = await response.json(); + return data.info.project_urls?.Documentation; + } +} diff --git a/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts b/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts new file mode 100644 index 000000000..fb073e2a1 --- /dev/null +++ b/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts @@ -0,0 +1,33 @@ +import { PackageCrawler, PackageDocsResult, PackageInfo } from ".."; + +export class TypeScriptPackageCrawler implements PackageCrawler { + language = "typescript"; + + getPackageFiles(fileNames: string[]): string[] { + // For TypeScript, we look for package.json file + return fileNames.filter((fileName) => fileName === "package.json"); + } + + parsePackageFile(fileContent: string, filepath: string): PackageInfo[] { + // Parse the package.json content + const jsonData = JSON.parse(fileContent) as Record; + const dependencies = Object.entries(jsonData.dependencies || {}).concat( + Object.entries(jsonData.devDependencies || {}), + ); + return dependencies.map(([name, version]) => ({ + name, + version, + foundInFilepath: filepath, + })); + } + + async getDocumentationLink(packageName: string): Promise { + // Fetch metadata from the NPM registry to find the documentation link + const response = await fetch(`https://registry.npmjs.org/${packageName}`); + if (!response.ok) { + throw new Error(`Could not fetch data for package ${packageName}`); + } + const data = await response.json(); + return data.homepage; + } +} diff --git a/core/protocol/core.ts b/core/protocol/core.ts index c757e5d34..069f9e297 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -167,6 +167,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "indexing/abort": [{ type: string; id: string }, void]; "indexing/setPaused": [{ type: string; id: string; paused: boolean }, void]; "indexing/initStatuses": [undefined, void]; + "docs/getSuggestedDocs": [undefined, void]; addAutocompleteModel: [{ model: ModelDescription }, void]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 40d537d41..ebe2a8697 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -52,6 +52,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "indexing/reindex", "indexing/abort", "indexing/setPaused", + "docs/getSuggestedDocs", // "completeOnboarding", "addAutocompleteModel", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 940503505..b30a951df 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", diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 4bef9da9c..f18379889 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -84,6 +84,7 @@ function useSetup(dispatch: Dispatch) { // ON LOAD useEffect(() => { + ideMessenger.post("docs/getSuggestedDocs", undefined); // Override persisted state dispatch(setInactive()); @@ -178,8 +179,6 @@ function useSetup(dispatch: Dispatch) { }, [defaultModelTitle], ); - - } export default useSetup; diff --git a/manual-testing-sandbox/package.json b/manual-testing-sandbox/package.json new file mode 100644 index 000000000..ef77ac910 --- /dev/null +++ b/manual-testing-sandbox/package.json @@ -0,0 +1,102 @@ +{ + "name": "gui", + "private": true, + "type": "module", + "author": "Continue Dev, Inc", + "license": "Apache-2.0", + "scripts": { + "dev": "vite", + "tsc:check": "tsc -p ./ --noEmit", + "build": "tsc && vite build", + "preview": "vite preview", + "test": "vitest run", + "test:coverage": "vitest run --coverage", + "test:ui": "vitest --ui", + "test:watch": "vitest" + }, + "dependencies": { + "@headlessui/react": "^1.7.17", + "@heroicons/react": "^2.0.18", + "@monaco-editor/react": "^4.6.0", + "@reduxjs/toolkit": "^1.9.3", + "@tiptap/core": "^2.3.2", + "@tiptap/extension-document": "^2.3.2", + "@tiptap/extension-dropcursor": "^2.1.16", + "@tiptap/extension-history": "^2.3.2", + "@tiptap/extension-image": "^2.1.16", + "@tiptap/extension-mention": "^2.1.13", + "@tiptap/extension-paragraph": "^2.3.2", + "@tiptap/extension-placeholder": "^2.1.13", + "@tiptap/extension-text": "^2.3.2", + "@tiptap/pm": "^2.1.13", + "@tiptap/react": "^2.1.13", + "@tiptap/starter-kit": "^2.1.13", + "@tiptap/suggestion": "^2.1.13", + "@types/vscode-webview": "^1.57.1", + "core": "file:../core", + "dompurify": "^3.0.6", + "downshift": "^7.6.0", + "lodash": "^4.17.21", + "minisearch": "^7.0.2", + "onigasm": "^2.2.5", + "posthog-js": "^1.130.1", + "prismjs": "^1.29.0", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "react-error-boundary": "^4.0.11", + "react-hook-form": "^7.47.0", + "react-intersection-observer": "^9.13.1", + "react-markdown": "^9.0.1", + "react-redux": "^8.0.5", + "react-remark": "^2.1.0", + "react-router-dom": "^6.14.2", + "react-switch": "^7.0.0", + "react-syntax-highlighter": "^15.5.0", + "react-tooltip": "^5.18.0", + "redux-persist": "^6.0.0", + "redux-persist-transform-filter": "^0.0.22", + "rehype-highlight": "^7.0.0", + "rehype-katex": "^7.0.0", + "rehype-wrap-all": "^1.1.0", + "remark-math": "^6.0.0", + "reselect": "^5.1.1", + "seti-file-icons": "^0.0.8", + "socket.io-client": "^4.7.2", + "styled-components": "^5.3.6", + "table": "^6.8.1", + "tippy.js": "^6.3.7", + "unist-util-visit": "^5.0.0", + "uuid": "^9.0.1", + "vscode-webview": "^1.0.1-beta.1" + }, + "devDependencies": { + "@swc/cli": "^0.3.14", + "@swc/core": "^1.7.26", + "@testing-library/dom": "^10.4.0", + "@testing-library/jest-dom": "^6.5.0", + "@testing-library/react": "^16.0.1", + "@testing-library/user-event": "^14.5.2", + "@types/lodash": "^4.17.6", + "@types/node": "^20.5.6", + "@types/node-fetch": "^2.6.4", + "@types/react": "^18.3.11", + "@types/react-dom": "^18.3.1", + "@types/react-router-dom": "^5.3.3", + "@types/react-syntax-highlighter": "^15.5.7", + "@types/styled-components": "^5.1.26", + "@vitejs/plugin-react-swc": "^3.7.0", + "@vitest/coverage-v8": "^2.1.3", + "@vitest/ui": "^2.1.3", + "autoprefixer": "^10.4.13", + "jsdom": "^25.0.1", + "postcss": "^8.4.21", + "tailwindcss": "^3.2.7", + "typescript": "^4.9.3", + "vite": "^4.1.0", + "vitest": "^2.1.3" + }, + "engine-strict": true, + "engines": { + "node": ">=20.11.0" + } +} diff --git a/manual-testing-sandbox/requirements.txt b/manual-testing-sandbox/requirements.txt new file mode 100644 index 000000000..793d6a827 --- /dev/null +++ b/manual-testing-sandbox/requirements.txt @@ -0,0 +1,10 @@ +flask==2.1.1 +requests==2.28.1 +numpy==1.23.4 +pandas==1.5.0 +scipy==1.9.3 +django==4.1.3 +matplotlib==3.6.2 +pytest==7.2.0 +sqlalchemy==1.4.41 +beautifulsoup4==4.11.1 \ No newline at end of file From 97e88c9c189e2ee8813a5649c1ee7f8e75f35859 Mon Sep 17 00:00:00 2001 From: Anoyi <545544032@qq.com> Date: Thu, 21 Nov 2024 17:16:08 +0800 Subject: [PATCH 034/747] fixed `downloadedOllamaModels` type errors --- .../OnboardingCard/tabs/OnboardingLocalTab.tsx | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx index d16587427..71d45d7f9 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx +++ b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx @@ -24,19 +24,19 @@ function OnboardingLocalTab() { hasPassedFTL() ? "LocalAfterFreeTrial" : "Local", ); const [hasLoadedChatModel, setHasLoadedChatModel] = useState(false); - const [downloadedOllamaModels, setDownloadedOllamaModels] = useState< - string[] - >([]); + const [downloadedOllamaModels, setDownloadedOllamaModels] = useState([]); const [isOllamaConnected, setIsOllamaConnected] = useState(false); - const hasDownloadedChatModel = downloadedOllamaModels.some((ollamaModel) => - ollamaModel.startsWith(LOCAL_ONBOARDING_CHAT_MODEL), - ); + const hasDownloadedChatModel = Array.isArray(downloadedOllamaModels) + ? downloadedOllamaModels.some((ollamaModel) => + ollamaModel.startsWith(LOCAL_ONBOARDING_CHAT_MODEL)) + : false; - const hasDownloadedAutocompleteModel = downloadedOllamaModels.some( - (ollamaModel) => ollamaModel.startsWith(LOCAL_ONBOARDING_CHAT_MODEL), - ); + const hasDownloadedAutocompleteModel = Array.isArray(downloadedOllamaModels) + ? downloadedOllamaModels.some((ollamaModel) => + ollamaModel.startsWith(LOCAL_ONBOARDING_CHAT_MODEL)) + : false; /** * The first time we detect that a chat model has been loaded, From c3e6b4fd99de6f8c051926321e30e4e8f6b8ec78 Mon Sep 17 00:00:00 2001 From: Anoyi <545544032@qq.com> Date: Thu, 21 Nov 2024 17:26:52 +0800 Subject: [PATCH 035/747] add new provider `siliconflow` --- core/config/types.ts | 3 +- core/control-plane/schema.ts | 2 + core/index.d.ts | 5 ++- core/llm/llms/SiliconFlow.ts | 28 +++++++++++++ extensions/vscode/config_schema.json | 26 ++++++++++++- gui/src/pages/AddNewModel/configs/models.ts | 39 +++++++++++++++++++ .../pages/AddNewModel/configs/providers.ts | 28 +++++++++++-- 7 files changed, 124 insertions(+), 7 deletions(-) create mode 100644 core/llm/llms/SiliconFlow.ts diff --git a/core/config/types.ts b/core/config/types.ts index f397b1ed7..66893cc41 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -604,7 +604,8 @@ declare global { | "openrouter" | "sambanova" | "nvidia" - | "nebius"; + | "nebius" + | "siliconflow"; export type ModelName = | "AUTODETECT" diff --git a/core/control-plane/schema.ts b/core/control-plane/schema.ts index e6987f1fe..4aae9f3cc 100644 --- a/core/control-plane/schema.ts +++ b/core/control-plane/schema.ts @@ -17,6 +17,7 @@ const modelDescriptionSchema = z.object({ "cloudflare", "azure", "nebius", + "siliconflow", ]), model: z.string(), apiKey: z.string().optional(), @@ -84,6 +85,7 @@ const embeddingsProviderSchema = z.object({ "free-trial", "gemini", "nebius", + "siliconflow", ]), apiBase: z.string().optional(), apiKey: z.string().optional(), diff --git a/core/index.d.ts b/core/index.d.ts index 0646edc54..2943d8ff3 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -703,7 +703,8 @@ type ModelProvider = | "vertexai" | "nebius" | "xAI" - | "moonshot"; + | "moonshot" + | "siliconflow"; export type ModelName = | "AUTODETECT" @@ -776,6 +777,8 @@ export type ModelName = | "gemma2-9b-it" | "olmo-7b" | "qwen-coder2.5-7b" + | "qwen2.5-coder-7b" + | "qwen2.5-coder-32b" // Anthropic | "claude-3-5-sonnet-latest" | "claude-3-5-sonnet-20240620" diff --git a/core/llm/llms/SiliconFlow.ts b/core/llm/llms/SiliconFlow.ts new file mode 100644 index 000000000..500b158ce --- /dev/null +++ b/core/llm/llms/SiliconFlow.ts @@ -0,0 +1,28 @@ +import { LLMOptions, ModelProvider } from "../../index.js"; +import { osModelsEditPrompt } from "../templates/edit.js"; + +import OpenAI from "./OpenAI.js"; + +class SiliconFlow extends OpenAI { + static providerName: ModelProvider = "siliconflow"; + static defaultOptions: Partial = { + apiBase: "https://api.siliconflow.cn/v1", + model: "Qwen/Qwen2.5-Coder-32B-Instruct", + promptTemplates: { + edit: osModelsEditPrompt, + }, + useLegacyCompletionsEndpoint: false, + }; + maxStopWords: number | undefined = 16; + + supportsFim(): boolean { + return true; + } + + _getFimEndpoint(endpoint: string) { + return new URL("chat/completions", this.apiBase); + } + +} + +export default SiliconFlow; diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 7edceced4..eb070bd00 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -206,7 +206,8 @@ "vertexai", "xAI", "kindo", - "moonshot" + "moonshot", + "siliconflow" ], "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)", @@ -244,7 +245,8 @@ "### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)", "### 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)" + "### 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)" ], "type": "string" }, @@ -1235,6 +1237,26 @@ } } }, + { + "if": { + "properties": { + "provider": { + "enum": ["siliconflow"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "enum": [ + "Qwen/Qwen2.5-Coder-32B-Instruct", + "Qwen/Qwen2.5-Coder-7B-Instruct" + ] + } + } + } + }, { "if": { "properties": { diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index 5e55c5c64..e9eecaf49 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -1175,6 +1175,45 @@ export const models: { [key: string]: ModelPackage } = { }, isOpenSource: true, }, + Qwen25Coder_7b: { + title: "Qwen 2.5 Coder 7b", + description: + "Qwen 2.5 is an auto-regressive language model that uses an optimized transformer architecture.", + params: { + title: "Qwen 2.5 Coder 7b", + model: "Qwen/Qwen2.5-Coder-7B-Instruct", + contextLength: 32_000, + }, + icon: "qwen.png", + providerOptions: ["siliconflow"], + isOpenSource: true, + }, + Qwen25Coder_7b_pro: { + title: "Qwen 2.5 Coder 7b pro", + description: + "Qwen 2.5 is an auto-regressive language model that uses an optimized transformer architecture.", + params: { + title: "Qwen 2.5 Coder 7b pro", + model: "Pro/Qwen/Qwen2.5-Coder-7B-Instruct", + contextLength: 32_000, + }, + icon: "qwen.png", + providerOptions: ["siliconflow"], + isOpenSource: true, + }, + Qwen25Coder_32b: { + title: "Qwen 2.5 Coder 32b", + description: + "Qwen 2.5 is an auto-regressive language model that uses an optimized transformer architecture.", + params: { + title: "Qwen 2.5 Coder 32b", + model: "Qwen/Qwen2.5-Coder-32B-Instruct", + contextLength: 128_000, + }, + icon: "qwen.png", + providerOptions: ["siliconflow"], + isOpenSource: true, + }, AUTODETECT: { title: "Autodetect", description: diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 3100f1ddc..cc668c0c2 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -125,9 +125,7 @@ export const providers: Partial> = { tags: [ModelProviderTags.RequiresApiKey], refPage: "moonshot", apiKeyUrl: "https://docs.moonshot.cn/docs/getting-started", - packages: [ - models.moonshotChat, - ], + packages: [models.moonshotChat], collectInputFor: [ { inputType: "text", @@ -785,4 +783,28 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo ], apiKeyUrl: "https://studio.nebius.ai/settings/api-keys", }, + siliconflow: { + title: "SiliconFlow", + provider: "siliconflow", + icon: "siliconflow.png", + description: "SiliconFlow provides cheap open-source models.", + longDescription: + "To get started with SiliconFlow, obtain an API key from their website [here](https://cloud.siliconflow.cn/account/ak).", + tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource], + collectInputFor: [ + { + inputType: "text", + key: "apiKey", + label: "API Key", + placeholder: "Enter your SiliconFlow API key", + required: true, + }, + ], + packages: [ + models.Qwen25Coder_7b, + models.Qwen25Coder_7b_pro, + models.Qwen25Coder_32b, + ], + apiKeyUrl: "https://cloud.siliconflow.cn/account/ak", + }, }; From a450fb8e29fb47f1193f8c55d05bc9bff74a0ef3 Mon Sep 17 00:00:00 2001 From: Anoyi <545544032@qq.com> Date: Thu, 21 Nov 2024 17:40:58 +0800 Subject: [PATCH 036/747] add docs --- core/index.d.ts | 2 - .../model-providers/more/siliconflow.md | 53 +++++++++++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) create mode 100644 docs/docs/customize/model-providers/more/siliconflow.md diff --git a/core/index.d.ts b/core/index.d.ts index 2943d8ff3..addbb7e6f 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -777,8 +777,6 @@ export type ModelName = | "gemma2-9b-it" | "olmo-7b" | "qwen-coder2.5-7b" - | "qwen2.5-coder-7b" - | "qwen2.5-coder-32b" // Anthropic | "claude-3-5-sonnet-latest" | "claude-3-5-sonnet-20240620" diff --git a/docs/docs/customize/model-providers/more/siliconflow.md b/docs/docs/customize/model-providers/more/siliconflow.md new file mode 100644 index 000000000..3bcdd901c --- /dev/null +++ b/docs/docs/customize/model-providers/more/siliconflow.md @@ -0,0 +1,53 @@ +--- +title: SiliconFlow +--- + +:::info + +You can get an API key from the [Silicon Cloud](https://cloud.siliconflow.cn/account/ak). + +::: + +## Chat model + +We recommend configuring **Qwen/Qwen2.5-Coder-32B-Instruct** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Qwen", + "provider": "siliconflow", + "model": "Qwen/Qwen2.5-Coder-32B-Instruct", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## Autocomplete model + +We recommend configuring **Qwen/Qwen2.5-Coder-7B-Instruct** as your autocomplete model. + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "Qwen", + "provider": "siliconflow", + "model": "Qwen/Qwen2.5-Coder-7B-Instruct", + "apiKey": "[API_KEY]" + } +} +``` + +## Embeddings model + +SiliconFlow provide some embeddings models. + +[Click here](https://siliconflow.cn/models) to see a list of embeddings models. + +## Reranking model + +SiliconFlow provide some reranking models. + +[Click here](https://siliconflow.cn/models) to see a list of reranking models. From 10979ca8af32843ee42ad3ec74693ab8126b6be1 Mon Sep 17 00:00:00 2001 From: Anoyi <545544032@qq.com> Date: Thu, 21 Nov 2024 17:44:42 +0800 Subject: [PATCH 037/747] add new provider --- core/llm/llms/index.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 121f0f46d..0297b7868 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -48,6 +48,7 @@ import VertexAI from "./VertexAI"; import Vllm from "./Vllm"; import WatsonX from "./WatsonX"; import xAI from "./xAI"; +import SiliconFlow from "./SiliconFlow"; const LLMs = [ Anthropic, @@ -90,6 +91,7 @@ const LLMs = [ Nebius, VertexAI, xAI, + SiliconFlow, ]; export async function llmFromDescription( From 4e88502331a4132564eaa4af6b2b90adb12a417d Mon Sep 17 00:00:00 2001 From: Anoyi <545544032@qq.com> Date: Thu, 21 Nov 2024 17:57:59 +0800 Subject: [PATCH 038/747] add new provider --- core/llm/llms/SiliconFlow.ts | 38 ++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/core/llm/llms/SiliconFlow.ts b/core/llm/llms/SiliconFlow.ts index 500b158ce..86804cb45 100644 --- a/core/llm/llms/SiliconFlow.ts +++ b/core/llm/llms/SiliconFlow.ts @@ -1,4 +1,5 @@ -import { LLMOptions, ModelProvider } from "../../index.js"; +import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js"; +import { streamSse } from "../stream.js"; import { osModelsEditPrompt } from "../templates/edit.js"; import OpenAI from "./OpenAI.js"; @@ -6,7 +7,7 @@ import OpenAI from "./OpenAI.js"; class SiliconFlow extends OpenAI { static providerName: ModelProvider = "siliconflow"; static defaultOptions: Partial = { - apiBase: "https://api.siliconflow.cn/v1", + apiBase: "https://api.siliconflow.cn/v1/", model: "Qwen/Qwen2.5-Coder-32B-Instruct", promptTemplates: { edit: osModelsEditPrompt, @@ -19,8 +20,37 @@ class SiliconFlow extends OpenAI { return true; } - _getFimEndpoint(endpoint: string) { - return new URL("chat/completions", this.apiBase); + async *_streamFim( + prefix: string, + suffix: string, + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const endpoint = new URL("completions", this.apiBase); + const resp = await this.fetch(endpoint, { + method: "POST", + body: JSON.stringify({ + model: options.model, + prompt: prefix, + suffix, + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + stop: options.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + signal + }); + for await (const chunk of streamSse(resp)) { + yield chunk.choices[0].text; + } } } From 4c51088434fcab7e5f48bf9c306034e5c92ddd64 Mon Sep 17 00:00:00 2001 From: Anoyi <545544032@qq.com> Date: Thu, 21 Nov 2024 18:09:02 +0800 Subject: [PATCH 039/747] add zh docs --- .../model-providers/more/siliconflow.md | 8 +-- .../model-providers/more/siliconflow.md | 51 +++++++++++++++++++ 2 files changed, 53 insertions(+), 6 deletions(-) create mode 100644 docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/siliconflow.md diff --git a/docs/docs/customize/model-providers/more/siliconflow.md b/docs/docs/customize/model-providers/more/siliconflow.md index 3bcdd901c..c27fbbdaf 100644 --- a/docs/docs/customize/model-providers/more/siliconflow.md +++ b/docs/docs/customize/model-providers/more/siliconflow.md @@ -42,12 +42,8 @@ We recommend configuring **Qwen/Qwen2.5-Coder-7B-Instruct** as your autocomplete ## Embeddings model -SiliconFlow provide some embeddings models. - -[Click here](https://siliconflow.cn/models) to see a list of embeddings models. +SiliconFlow provide some embeddings models, [Click here](https://siliconflow.cn/models) to see a list of embeddings models. ## Reranking model -SiliconFlow provide some reranking models. - -[Click here](https://siliconflow.cn/models) to see a list of reranking models. +SiliconFlow provide some reranking models, [Click here](https://siliconflow.cn/models) to see a list of reranking models. diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/siliconflow.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/siliconflow.md new file mode 100644 index 000000000..b87101832 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/siliconflow.md @@ -0,0 +1,51 @@ +--- +title: 硅基流动 +--- + +:::info + +你可以从 [Silicon Cloud](https://cloud.siliconflow.cn/account/ak) 获取 API key 。 + +::: + +## 聊天模型 + +我们推荐配置 **Qwen/Qwen2.5-Coder-32B-Instruct** 作为你的聊天模型。 + +```json title="config.json" +{ + "models": [ + { + "title": "Qwen", + "provider": "siliconflow", + "model": "Qwen/Qwen2.5-Coder-32B-Instruct", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## 自动补全模型 + +我们推荐配置 **Qwen/Qwen2.5-Coder-7B-Instruct** 作为你的自动补全模型。 + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "Qwen", + "provider": "siliconflow", + "model": "Qwen/Qwen2.5-Coder-7B-Instruct", + "apiKey": "[API_KEY]" + } +} +``` + +## 嵌入模型 + +SiliconFlow 提供了一些嵌入模型,[点击这里](https://siliconflow.cn/models) 查看所有的嵌入模型. + +## 重排序模型 + +SiliconFlow 提供了一些重排序模型,[点击这里](https://siliconflow.cn/models) 查看所有的重排序模型. + +[Click here](https://siliconflow.cn/models) to see a list of reranking models. From 50e84f7d21dba0ecd312cae355dff8126b2a70a1 Mon Sep 17 00:00:00 2001 From: pdanek Date: Thu, 21 Nov 2024 14:06:14 +0100 Subject: [PATCH 040/747] Fix undefined model name --- core/autocomplete/CompletionProvider.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index b2cfbd9d9..0e4ef0669 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -67,6 +67,10 @@ export class CompletionProvider { return undefined; } + if (llm.model === undefined && llm.completionOptions?.model !== undefined) { + llm.model = llm.completionOptions.model + } + // Ignore empty API keys for Mistral since we currently write // a template provider without one during onboarding if (llm.providerName === "mistral" && llm.apiKey === "") { From e93ae594825d71471438adc11c99eeb306b4e392 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 21 Nov 2024 08:38:00 -0800 Subject: [PATCH 041/747] 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 042/747] 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 043/747] 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 044/747] 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 78ef8fe118ef227b73ad544a684ea20b56a0b63d Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 21 Nov 2024 10:39:59 -0800 Subject: [PATCH 045/747] refactor: clean up code, add tests --- core/autocomplete/CompletionProvider.ts | 8 ++-- core/autocomplete/aggregateSnippets.ts | 10 ++--- .../context/ContextRetrievalService.ts | 10 ++--- core/autocomplete/context/ranking/index.ts | 44 ++++++++++++------- .../context/ranking/slidingWindow.ts | 6 +-- .../RootPathContextService.ts | 14 +++--- core/autocomplete/filtering/test/testCases.ts | 12 +++++ core/autocomplete/filtering/test/util.ts | 1 - core/autocomplete/snippets/types.ts | 17 +++++++ .../templating/AutocompleteTemplate.ts | 16 +++---- core/autocomplete/templating/index.ts | 6 +-- core/autocomplete/util/types.ts | 1 - .../src/autocomplete/completionProvider.ts | 15 +------ extensions/vscode/src/autocomplete/lsp.ts | 16 ++++--- 14 files changed, 103 insertions(+), 73 deletions(-) create mode 100644 core/autocomplete/snippets/types.ts diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index b2cfbd9d9..c3445498e 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -10,7 +10,7 @@ import { aggregateSnippets } from "./aggregateSnippets"; // @prettier-ignore import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; -import { AutocompleteSnippet } from "./context/ranking/index.js"; +import { AutocompleteSnippetDeprecated } from "./context/ranking/index.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { postprocessCompletion } from "./postprocessing/index.js"; @@ -38,7 +38,7 @@ export type GetLspDefinitionsFunction = ( cursorIndex: number, ide: IDE, lang: AutocompleteLanguageInfo, -) => Promise; +) => Promise; export class CompletionProvider { private autocompleteCache = AutocompleteLruCache.get(); @@ -291,7 +291,7 @@ export class CompletionProvider { private async _getExtraSnippets( helper: HelperVars, - ): Promise { + ): Promise { let extraSnippets = helper.options.useOtherFiles ? ((await Promise.race([ this.getDefinitionsFromLsp( @@ -304,7 +304,7 @@ export class CompletionProvider { new Promise((resolve) => { setTimeout(() => resolve([]), 100); }), - ])) as AutocompleteSnippet[]) + ])) as AutocompleteSnippetDeprecated[]) : []; const workspaceDirs = await this.ide.getWorkspaceDirs(); diff --git a/core/autocomplete/aggregateSnippets.ts b/core/autocomplete/aggregateSnippets.ts index f47b9021f..e6c750a4b 100644 --- a/core/autocomplete/aggregateSnippets.ts +++ b/core/autocomplete/aggregateSnippets.ts @@ -2,14 +2,14 @@ import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, rankAndOrderSnippets, - type AutocompleteSnippet, + type AutocompleteSnippetDeprecated, } from "./context/ranking/index.js"; import { HelperVars } from "./util/HelperVars.js"; function filterSnippetsAlreadyInCaretWindow( - snippets: AutocompleteSnippet[], + snippets: AutocompleteSnippetDeprecated[], caretWindow: string, -): AutocompleteSnippet[] { +): AutocompleteSnippetDeprecated[] { return snippets .map((snippet) => ({ ...snippet })) .filter( @@ -20,9 +20,9 @@ function filterSnippetsAlreadyInCaretWindow( export async function aggregateSnippets( helper: HelperVars, - extraSnippets: AutocompleteSnippet[], + extraSnippets: AutocompleteSnippetDeprecated[], contextRetrievalService: ContextRetrievalService, -): Promise { +): Promise { let snippets = await contextRetrievalService.retrieveCandidateSnippets( helper, extraSnippets, diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index 24f6e9182..66b67eec3 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -3,7 +3,7 @@ import { HelperVars } from "../util/HelperVars"; import { RecentlyEditedRange } from "../util/types"; import { ImportDefinitionsService } from "./ImportDefinitionsService"; -import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking"; +import { AutocompleteSnippetDeprecated, getSymbolsForSnippet } from "./ranking"; import { RootPathContextService } from "./root-path-context/RootPathContextService"; export class ContextRetrievalService { @@ -20,13 +20,13 @@ export class ContextRetrievalService { public async retrieveCandidateSnippets( helper: HelperVars, - extraSnippets: AutocompleteSnippet[], + extraSnippets: AutocompleteSnippetDeprecated[], ) { if (helper.options.useOtherFiles === false) { return []; } - let snippets: AutocompleteSnippet[] = []; + let snippets: AutocompleteSnippetDeprecated[] = []; // Snippets injected by the IDE for IDE-specific reasons snippets.push(...extraSnippets); @@ -52,7 +52,7 @@ export class ContextRetrievalService { private getSnippetsFromRecentlyEditedRanges( helper: HelperVars, - ): AutocompleteSnippet[] { + ): AutocompleteSnippetDeprecated[] { if (helper.options.useRecentlyEdited === false) { return []; } @@ -85,7 +85,7 @@ export class ContextRetrievalService { private async getSnippetsFromImportDefinitions( helper: HelperVars, - ): Promise { + ): Promise { if (helper.options.useImports === false) { return []; } diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index 3e83afca5..28e9b8112 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -3,7 +3,12 @@ import { Range } from "../../../index.js"; import { countTokens } from "../../../llm/countTokens.js"; import { HelperVars } from "../../util/HelperVars.js"; -export type AutocompleteSnippet = RangeInFileWithContents & { +/** + * @deprecated This type should be removed in the future or renamed. + * We have a new interface called AutocompleteSnippet which is more + * general. + */ +export type AutocompleteSnippetDeprecated = RangeInFileWithContents & { score?: number; }; @@ -43,9 +48,9 @@ export function jaccardSimilarity(a: string, b: string): number { * Rank code snippets to be used in tab-autocomplete prompt. Returns a sorted version of the snippet array. */ export function rankAndOrderSnippets( - ranges: AutocompleteSnippet[], + ranges: AutocompleteSnippetDeprecated[], helper: HelperVars, -): Required[] { +): Required[] { const windowAroundCursor = helper.fullPrefix.slice( -helper.options.slidingWindowSize * @@ -56,11 +61,14 @@ export function rankAndOrderSnippets( (1 - helper.options.slidingWindowPrefixPercentage), ); - const snippets: Required[] = ranges.map((snippet) => ({ - score: - snippet.score ?? jaccardSimilarity(snippet.contents, windowAroundCursor), - ...snippet, - })); + const snippets: Required[] = ranges.map( + (snippet) => ({ + score: + snippet.score ?? + jaccardSimilarity(snippet.contents, windowAroundCursor), + ...snippet, + }), + ); const uniqueSnippets = deduplicateSnippets(snippets); return uniqueSnippets.sort((a, b) => a.score - b.score); } @@ -69,10 +77,12 @@ export function rankAndOrderSnippets( * Deduplicate code snippets by merging overlapping ranges into a single range. */ export function deduplicateSnippets( - snippets: Required[], -): Required[] { + snippets: Required[], +): Required[] { // Group by file - const fileGroups: { [key: string]: Required[] } = {}; + const fileGroups: { + [key: string]: Required[]; + } = {}; for (const snippet of snippets) { if (!fileGroups[snippet.filepath]) { fileGroups[snippet.filepath] = []; @@ -89,8 +99,8 @@ export function deduplicateSnippets( } function mergeSnippetsByRange( - snippets: Required[], -): Required[] { + snippets: Required[], +): Required[] { if (snippets.length <= 1) { return snippets; } @@ -98,7 +108,7 @@ function mergeSnippetsByRange( const sorted = snippets.sort( (a, b) => a.range.start.line - b.range.start.line, ); - const merged: Required[] = []; + const merged: Required[] = []; while (sorted.length > 0) { const next = sorted.shift()!; @@ -134,12 +144,12 @@ function mergeOverlappingRangeContents( * It is assumed that the snippets are sorted by score. */ export function fillPromptWithSnippets( - snippets: Required[], + snippets: Required[], maxSnippetTokens: number, modelName: string, -): Required[] { +): Required[] { let tokensRemaining = maxSnippetTokens; - const keptSnippets: Required[] = []; + const keptSnippets: Required[] = []; for (let i = 0; i < snippets.length; i++) { const snippet = snippets[i]; const tokenCount = countTokens(snippet.contents, modelName); diff --git a/core/autocomplete/context/ranking/slidingWindow.ts b/core/autocomplete/context/ranking/slidingWindow.ts index 7b650eb44..3fd3a3f17 100644 --- a/core/autocomplete/context/ranking/slidingWindow.ts +++ b/core/autocomplete/context/ranking/slidingWindow.ts @@ -1,6 +1,6 @@ import { RangeInFileWithContents } from "../../../commands/util.js"; -import { AutocompleteSnippet, jaccardSimilarity } from "./index.js"; +import { AutocompleteSnippetDeprecated, jaccardSimilarity } from "./index.js"; function* slidingWindow( content: string, @@ -37,9 +37,9 @@ export async function slidingWindowMatcher( windowAroundCursor: string, topN: number, windowSize: number, -): Promise { +): Promise { // Sorted lowest similarity to highest - const topMatches: Required[] = []; + const topMatches: Required[] = []; for (const { filepath, contents, range } of recentFiles) { for (const window of slidingWindow(contents, windowSize)) { diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index 0147df151..98a947fb1 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -12,7 +12,7 @@ import { } from "../../../util/treeSitter"; import { AstPath } from "../../util/ast"; import { ImportDefinitionsService } from "../ImportDefinitionsService"; -import { AutocompleteSnippet } from "../ranking"; +import { AutocompleteSnippetDeprecated } from "../ranking"; function getSyntaxTreeString( node: Parser.SyntaxNode, @@ -30,7 +30,7 @@ function getSyntaxTreeString( } export class RootPathContextService { - private cache = new LRUCache({ + private cache = new LRUCache({ max: 100, }); @@ -72,8 +72,8 @@ export class RootPathContextService { private async getSnippetsForNode( filepath: string, node: Parser.SyntaxNode, - ): Promise { - const snippets: AutocompleteSnippet[] = []; + ): Promise { + const snippets: AutocompleteSnippetDeprecated[] = []; const language = getFullLanguageName(filepath); let query: Parser.Query | undefined; @@ -123,7 +123,7 @@ export class RootPathContextService { filepath: string, endPosition: Parser.Point, language: LanguageName, - ): Promise { + ): Promise { const definitions = await this.ide.gotoDefinition({ filepath, position: { @@ -153,8 +153,8 @@ export class RootPathContextService { filepath: string, astPath: AstPath, // cursorIndex: number, - ): Promise { - const snippets: AutocompleteSnippet[] = []; + ): Promise { + const snippets: AutocompleteSnippetDeprecated[] = []; let parentKey = filepath; for (const astNode of astPath.filter((node) => diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts index f0584ab48..0640b6918 100644 --- a/core/autocomplete/filtering/test/testCases.ts +++ b/core/autocomplete/filtering/test/testCases.ts @@ -1565,7 +1565,19 @@ interface User { age: number; }`, }, + { + description: "Should autocomplete TypeScript interface declarations", + filename: "autocomplete.ts", + input: `interface AutocompleteDiffSnippet extends BaseAutocompleteSnippet {} +interface AutocompleteCodeSnippet`, + llmOutput: ` extends BaseAutocompleteSnippet { + filepath: string; +}`, + expectedCompletion: ` extends BaseAutocompleteSnippet { + filepath: string; +}`, + }, { description: "Should autocomplete a TypeScript arrow function inside a variable assignment", diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index 42ab196b7..dc35d5f94 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -54,7 +54,6 @@ export async function testAutocompleteFiltering( const line = prefix.split("\n").length - 1; const character = prefix.split("\n")[line].length; const autocompleteInput: AutocompleteInput = { - clipboardText: "", completionId: "test-completion-id", filepath, pos: { diff --git a/core/autocomplete/snippets/types.ts b/core/autocomplete/snippets/types.ts new file mode 100644 index 000000000..e39406b11 --- /dev/null +++ b/core/autocomplete/snippets/types.ts @@ -0,0 +1,17 @@ +interface BaseAutocompleteSnippet { + score?: number; + content: string; +} + +export interface AutocompleteCodeSnippet extends BaseAutocompleteSnippet { + filepath: string; +} + +export interface AutocompleteDiffSnippet extends BaseAutocompleteSnippet {} + +export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet {} + +export type AutocompleteSnippet = + | AutocompleteCodeSnippet + | AutocompleteDiffSnippet + | AutocompleteClipboardSnippet; diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index ae8cf1487..11fd47333 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -2,7 +2,7 @@ import { CompletionOptions } from "../../index.js"; import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js"; -import { AutocompleteSnippet } from "../context/ranking/index.js"; +import { AutocompleteSnippetDeprecated } from "../context/ranking/index.js"; export interface AutocompleteTemplate { compilePrefixSuffix?: ( @@ -10,7 +10,7 @@ export interface AutocompleteTemplate { suffix: string, filepath: string, reponame: string, - snippets: AutocompleteSnippet[], + snippets: AutocompleteSnippetDeprecated[], ) => [string, string]; template: | string @@ -20,7 +20,7 @@ export interface AutocompleteTemplate { filepath: string, reponame: string, language: string, - snippets: AutocompleteSnippet[], + snippets: AutocompleteSnippetDeprecated[], ) => string); completionOptions?: Partial; } @@ -73,7 +73,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { suffix: string, filepath: string, reponame: string, - snippets: AutocompleteSnippet[], + snippets: AutocompleteSnippetDeprecated[], ): [string, string] => { if (snippets.length === 0) { if (suffix.trim().length === 0 && prefix.trim().length === 0) { @@ -101,7 +101,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { filepath: string, reponame: string, language: string, - snippets: AutocompleteSnippet[], + snippets: AutocompleteSnippetDeprecated[], ): string => { return `[SUFFIX]${suffix}[PREFIX]${prefix}`; }, @@ -133,7 +133,7 @@ const starcoder2FimTemplate: AutocompleteTemplate = { filename: string, reponame: string, language: string, - snippets: AutocompleteSnippet[], + snippets: AutocompleteSnippetDeprecated[], ): string => { const otherFiles = snippets.length === 0 @@ -187,7 +187,7 @@ const codegeexFimTemplate: AutocompleteTemplate = { filepath: string, reponame: string, language: string, - snippets: AutocompleteSnippet[], + snippets: AutocompleteSnippetDeprecated[], ): string => { const relativePaths = shortestRelativePaths([ ...snippets.map((snippet) => snippet.filepath), @@ -233,7 +233,7 @@ const holeFillerTemplate: AutocompleteTemplate = { filename: string, reponame: string, language: string, - snippets: AutocompleteSnippet[], + snippets: AutocompleteSnippetDeprecated[], ) => { // From https://github.com/VictorTaelin/AI-scripts const SYSTEM_MSG = `You are a HOLE FILLER. You are provided with a file containing holes, formatted as '{{HOLE_NAME}}'. Your TASK is to complete with a string to replace this hole with, inside a XML tag, including context-aware indentation, if needed. All completions MUST be truthful, accurate, well-written and correct. diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 6f95923d1..be2d178d4 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -3,7 +3,7 @@ import Handlebars from "handlebars"; import { CompletionOptions } from "../.."; import { getBasename, getLastNPathParts } from "../../util"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; -import { AutocompleteSnippet } from "../context/ranking"; +import { AutocompleteSnippetDeprecated } from "../context/ranking"; import { HelperVars } from "../util/HelperVars"; import { @@ -34,7 +34,7 @@ export function formatExternalSnippet( } function getContextComments( - snippets: AutocompleteSnippet[], + snippets: AutocompleteSnippetDeprecated[], lang: AutocompleteLanguageInfo, filepath: string, ) { @@ -137,7 +137,7 @@ export function renderPrompt({ diff, clipboardContent, }: { - snippets: AutocompleteSnippet[]; + snippets: AutocompleteSnippetDeprecated[]; workspaceDirs: string[]; helper: HelperVars; diff?: string; diff --git a/core/autocomplete/util/types.ts b/core/autocomplete/util/types.ts index cb9064b62..47d19b233 100644 --- a/core/autocomplete/util/types.ts +++ b/core/autocomplete/util/types.ts @@ -13,7 +13,6 @@ export interface AutocompleteInput { pos: Position; recentlyEditedFiles: RangeInFileWithContents[]; recentlyEditedRanges: RecentlyEditedRange[]; - clipboardText: string; // Used for notebook files manuallyPassFileContents?: string; // Used for VS Code git commit input box diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 0df8e58b1..ffe69a2c4 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -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; @@ -153,12 +153,6 @@ export class ContinueCompletionProvider const signal = abortController.signal; token.onCancellationRequested(() => abortController.abort()); - const config = await this.configHandler.loadConfig(); - let clipboardText = ""; - if (config.tabAutocompleteOptions?.useCopyBuffer === true) { - clipboardText = await vscode.env.clipboard.readText(); - } - // Handle notebook cells const pos = { line: position.line, @@ -194,12 +188,6 @@ export class ContinueCompletionProvider } // Handle commit message input box let manuallyPassPrefix: string | undefined = undefined; - if (document.uri.scheme === "vscode-scm") { - return null; - // let diff = await this.ide.getDiff(); - // diff = diff.split("\n").splice(-150).join("\n"); - // manuallyPassPrefix = `${diff}\n\nCommit message: `; - } const input: AutocompleteInput = { completionId: uuidv4(), @@ -208,7 +196,6 @@ export class ContinueCompletionProvider recentlyEditedFiles: [], recentlyEditedRanges: await this.recentlyEditedTracker.getRecentlyEditedRanges(), - clipboardText: clipboardText, manuallyPassFileContents, manuallyPassPrefix, selectedCompletionInfo, diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index f900058ab..de719d3bf 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -1,6 +1,6 @@ import { GetLspDefinitionsFunction } from "core/autocomplete/CompletionProvider"; import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo"; -import { AutocompleteSnippet } from "core/autocomplete/context/ranking"; +import { AutocompleteSnippetDeprecated } from "core/autocomplete/context/ranking"; import { getAst, getTreePathAtCursor } from "core/autocomplete/util/ast"; import { RangeInFileWithContents } from "core/commands/util"; import { @@ -134,7 +134,9 @@ async function crawlTypes( // Parse AST const ast = await getAst(rif.filepath, contents); - if (!ast) {return results;} + if (!ast) { + return results; + } const astLineCount = ast.rootNode.text.split("\n").length; // Find type identifiers @@ -340,13 +342,17 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( cursorIndex: number, ide: IDE, lang: AutocompleteLanguageInfo, -): Promise => { +): Promise => { try { const ast = await getAst(filepath, contents); - if (!ast) {return [];} + if (!ast) { + return []; + } const treePath = await getTreePathAtCursor(ast, cursorIndex); - if (!treePath) {return [];} + if (!treePath) { + return []; + } const results: RangeInFileWithContents[] = []; for (const node of treePath.reverse()) { From 954bd5f563a278c04f40f0ec40bfbe27fc497afb Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 21 Nov 2024 11:58:48 -0800 Subject: [PATCH 046/747] python and typescript crawlers --- core/index.d.ts | 29 +++++ core/indexing/docs/suggestions/index.ts | 115 +++++++++++------- .../suggestions/packageCrawlers/Python.ts | 39 ++++-- .../docs/suggestions/packageCrawlers/TsJs.ts | 40 ++++-- 4 files changed, 159 insertions(+), 64 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 0646edc54..de1adb893 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1190,3 +1190,32 @@ export interface BrowserSerializedContinueConfig { experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; } + +// DOCS SUGGESTIONS AND PACKAGE INFO +export interface FilePathAndName { + path: string; + name: string; +} +export type ParsedPackageInfo = { + language: string; + name: string; + version: string; + packageFile: FilePathAndName; +}; + +export type PackageDetails = { + docsLink?: string; + title?: string; + description?: string; +}; + +export type PackageDetailsSuccess = PackageDetails & { + docsLink: string; +}; + +export type PackageDocsResult = { + packageInfo: ParsedPackageInfo; +} & ( + | { error: string; details?: never } + | { details: PackageDetailsSuccess; error?: never } +); diff --git a/core/indexing/docs/suggestions/index.ts b/core/indexing/docs/suggestions/index.ts index d3d68aca2..5699cd761 100644 --- a/core/indexing/docs/suggestions/index.ts +++ b/core/indexing/docs/suggestions/index.ts @@ -1,12 +1,12 @@ -// write me an interface PackageCrawler that contains: -// 1. property `language` to store a given language like "python" or "typescript" -// 2. has a method `getPackageFiles` which takes a list of file names and decides which ones match package/dependency files (e.g. package.json for typescript, requirements.txt for python, etc) -// 3. has a method `parsePackageFile` which returns a list of package name and version from a relevant package file, in a standardized format like semver -// 4. has a method `getDocumentationLink` to check for documentation link for a given package (e.g. GET `https://registry.npmjs.org/` and find docs field for typescript, documentation link in the package metadata for PyPi, etc.) -// Then, write typescript classes to implement this typescript interface for the languages "python" and "typescript" - -import { IDE } from "../../.."; +import { + FilePathAndName, + IDE, + PackageDetails, + PackageDocsResult, + ParsedPackageInfo, +} from "../../.."; import { walkDir } from "../../walkDir"; + import { PythonPackageCrawler } from "./packageCrawlers/Python"; import { TypeScriptPackageCrawler } from "./packageCrawlers/TsJs"; @@ -14,19 +14,14 @@ const PACKAGE_CRAWLERS = [TypeScriptPackageCrawler, PythonPackageCrawler]; export interface PackageCrawler { language: string; - getPackageFiles(fileNames: string[]): string[]; - parsePackageFile(fileContent: string, filePath: string): PackageInfo[]; - getDocumentationLink(packageName: string): Promise; + getPackageFiles(files: FilePathAndName[]): FilePathAndName[]; + parsePackageFile( + file: FilePathAndName, + contents: string, + ): ParsedPackageInfo[]; + getPackageDetails(packageInfo: ParsedPackageInfo): Promise; } -export type PackageInfo = { - name: string; - version: string; - foundInFilepath: string; -}; -export type PackageDocsResult = PackageInfo & - ({ error: string; link?: never } | { link: string; error?: never }); - export async function getAllSuggestedDocs(ide: IDE) { const workspaceDirs = await ide.getWorkspaceDirs(); const results = await Promise.all( @@ -35,16 +30,26 @@ export async function getAllSuggestedDocs(ide: IDE) { }), ); const allPaths = results.flat(); // TODO only get files, not dirs. Not critical for now - const allFiles = allPaths.map((path) => path.split("/").pop()!); - const packageFilesByLanguage: Record = {}; + const allFiles = allPaths.map((path) => ({ + path, + name: path.split(/[\\/]/).pop()!, + })); + + // Build map of language -> package files + const packageFilesByLanguage: Record = {}; for (const Crawler of PACKAGE_CRAWLERS) { const crawler = new Crawler(); const packageFilePaths = crawler.getPackageFiles(allFiles); packageFilesByLanguage[crawler.language] = packageFilePaths; } + // Get file contents for all unique package files const uniqueFilePaths = Array.from( - new Set(Object.values(packageFilesByLanguage).flat()), + new Set( + Object.values(packageFilesByLanguage).flatMap((files) => + files.map((file) => file.path), + ), + ), ); const fileContentsArray = await Promise.all( uniqueFilePaths.map(async (path) => { @@ -56,40 +61,68 @@ export async function getAllSuggestedDocs(ide: IDE) { fileContentsArray.map(({ path, contents }) => [path, contents]), ); - const packagesByLanguage: Record = {}; + // Parse package files and build map of language -> packages + const packagesByLanguage: Record = {}; PACKAGE_CRAWLERS.forEach((Crawler) => { const crawler = new Crawler(); const packageFiles = packageFilesByLanguage[crawler.language]; packageFiles.forEach((file) => { - const contents = fileContents.get(file); + const contents = fileContents.get(file.path); if (!contents) { return; } - const packages = crawler.parsePackageFile(contents, file); + const packages = crawler.parsePackageFile(file, contents); if (!packagesByLanguage[crawler.language]) { packagesByLanguage[crawler.language] = []; } packagesByLanguage[crawler.language].push(...packages); }); }); - console.log(packagesByLanguage); - // const allPackages = await Promise.all( - // PACKAGE_CRAWLERS.map(async (Crawler) => { - // const crawler = new Crawler(); - // const packageInfos = uniqueFileContents - // .filter(({ path }) => languageToFilePaths[crawler.language].includes(path)) - // .map(({ path, contents }) => crawler.parsePackageFile(contents, path)) - // .flat(); - // return packageInfos; - // }) - // ); - // for (const Crawler of PACKAGE_CRAWLERS) { - // const crawler = new Crawler(); - // const packages = crawler.parsePackageFile() - // languageToFilePaths[crawler.language] = packageFilePaths; - // } + + // Get documentation links for all packages + const docsByLanguage: Record = {}; + await Promise.all( + PACKAGE_CRAWLERS.map(async (Crawler) => { + const crawler = new Crawler(); + const packages = packagesByLanguage[crawler.language]; + docsByLanguage[crawler.language] = await Promise.all( + packages.map(async (packageInfo) => { + try { + const details = await crawler.getPackageDetails(packageInfo); + if (!details.docsLink) { + return { + packageInfo, + error: `No documentation link found for ${packageInfo.name}`, + }; + } + return { + packageInfo, + details: { + ...details, + docsLink: details.docsLink, + }, + }; + } catch (error) { + return { + packageInfo, + error: `Error getting package details for ${name}`, + }; + } + }), + ); + }), + ); + + return docsByLanguage; } +// write me an interface PackageCrawler that contains: +// 1. property `language` to store a given language like "python" or "typescript" +// 2. has a method `getPackageFiles` which takes a list of file names and decides which ones match package/dependency files (e.g. package.json for typescript, requirements.txt for python, etc) +// 3. has a method `parsePackageFile` which returns a list of package name and version from a relevant package file, in a standardized format like semver +// 4. has a method `getDocumentationLink` to check for documentation link for a given package (e.g. GET `https://registry.npmjs.org/` and find docs field for typescript, documentation link in the package metadata for PyPi, etc.) +// Then, write typescript classes to implement this typescript interface for the languages "python" and "typescript" + // I want to present the user with a list of dependencies and allow them to select which ones to index (embed) documentation for. // In order to prevent duplicate file reads, the process will be like this: // 1. take in a list of filepaths called `filepaths` diff --git a/core/indexing/docs/suggestions/packageCrawlers/Python.ts b/core/indexing/docs/suggestions/packageCrawlers/Python.ts index ac0699766..233e44428 100644 --- a/core/indexing/docs/suggestions/packageCrawlers/Python.ts +++ b/core/indexing/docs/suggestions/packageCrawlers/Python.ts @@ -1,33 +1,50 @@ -import { PackageCrawler, PackageDocsResult, PackageInfo } from ".."; +import { PackageCrawler } from ".."; +import { + FilePathAndName, + PackageDetails, + ParsedPackageInfo, +} from "../../../.."; export class PythonPackageCrawler implements PackageCrawler { language = "python"; - getPackageFiles(fileNames: string[]): string[] { + getPackageFiles(files: FilePathAndName[]): FilePathAndName[] { // For Python, we typically look for files like requirements.txt or Pipfile - return fileNames.filter( - (fileName) => fileName === "requirements.txt" || fileName === "Pipfile", + return files.filter( + (file) => file.name === "requirements.txt" || file.name === "Pipfile", ); } - parsePackageFile(fileContent: string, filepath: string): PackageInfo[] { + parsePackageFile( + file: FilePathAndName, + contents: string, + ): ParsedPackageInfo[] { // Assume the fileContent is a string from a requirements.txt formatted file - return fileContent + return contents .split("\n") .map((line) => { const [name, version] = line.split("=="); - return { name, version, foundInFilepath: filepath }; + return { name, version, packageFile: file, language: this.language }; }) .filter((pkg) => pkg.name && pkg.version); } - async getDocumentationLink(packageName: string): Promise { + async getPackageDetails( + packageInfo: ParsedPackageInfo, + ): Promise { // Fetch metadata from PyPI to find the documentation link - const response = await fetch(`https://pypi.org/pypi/${packageName}/json`); + + const response = await fetch( + `https://pypi.org/pypi/${packageInfo.name}/json`, + ); if (!response.ok) { - throw new Error(`Could not fetch data for package ${packageName}`); + throw new Error(`Could not fetch data for package ${packageInfo.name}`); } const data = await response.json(); - return data.info.project_urls?.Documentation; + return { + docsLink: data.info.project_urls?.Documentation as string | undefined, + // title: data.info.name, + // description: data.info.summary as string | undefined, + }; } } diff --git a/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts b/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts index fb073e2a1..107d9ac2a 100644 --- a/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts +++ b/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts @@ -1,33 +1,49 @@ -import { PackageCrawler, PackageDocsResult, PackageInfo } from ".."; +import { PackageCrawler } from ".."; +import { + FilePathAndName, + PackageDetails, + ParsedPackageInfo, +} from "../../../.."; export class TypeScriptPackageCrawler implements PackageCrawler { - language = "typescript"; + language = "js-ts"; - getPackageFiles(fileNames: string[]): string[] { - // For TypeScript, we look for package.json file - return fileNames.filter((fileName) => fileName === "package.json"); + getPackageFiles(files: FilePathAndName[]): FilePathAndName[] { + // For Javascript/TypeScript, we look for package.json file + return files.filter((file) => file.name === "package.json"); } - parsePackageFile(fileContent: string, filepath: string): PackageInfo[] { + parsePackageFile( + file: FilePathAndName, + contents: string, + ): ParsedPackageInfo[] { // Parse the package.json content - const jsonData = JSON.parse(fileContent) as Record; + const jsonData = JSON.parse(contents) as Record; const dependencies = Object.entries(jsonData.dependencies || {}).concat( Object.entries(jsonData.devDependencies || {}), ); return dependencies.map(([name, version]) => ({ name, version, - foundInFilepath: filepath, + packageFile: file, + language: this.language, })); } - async getDocumentationLink(packageName: string): Promise { + async getPackageDetails( + packageInfo: ParsedPackageInfo, + ): Promise { + const { name } = packageInfo; // Fetch metadata from the NPM registry to find the documentation link - const response = await fetch(`https://registry.npmjs.org/${packageName}`); + const response = await fetch(`https://registry.npmjs.org/${name}`); if (!response.ok) { - throw new Error(`Could not fetch data for package ${packageName}`); + throw new Error(`Could not fetch data for package ${name}`); } const data = await response.json(); - return data.homepage; + return { + docsLink: data.homepage as string | undefined, + // title: data.name, + // description: data.description as string | undefined, + }; } } From abd46dfb4ff1aea84e94922fdda5d6fce23c6edf Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 21 Nov 2024 12:52:25 -0800 Subject: [PATCH 047/747] docs suggestions: packages in GUI --- core/core.ts | 3 +- core/index.d.ts | 3 ++ core/indexing/docs/suggestions/index.ts | 4 +-- core/protocol/passThrough.ts | 1 + core/protocol/webview.ts | 2 ++ gui/src/components/dialogs/AddDocsDialog.tsx | 37 ++++++++++++++++++-- gui/src/hooks/useSetup.ts | 6 ++++ gui/src/redux/slices/stateSlice.ts | 11 ++++++ 8 files changed, 61 insertions(+), 6 deletions(-) diff --git a/core/core.ts b/core/core.ts index d080ec34b..d81df8a37 100644 --- a/core/core.ts +++ b/core/core.ts @@ -739,7 +739,8 @@ export class Core { return this.docsService.initStatuses(); }); on("docs/getSuggestedDocs", async (msg) => { - getAllSuggestedDocs(this.ide); + const suggestedDocs = await getAllSuggestedDocs(this.ide); + this.messenger.send("docs/suggestions", suggestedDocs); }); // diff --git a/core/index.d.ts b/core/index.d.ts index de1adb893..d6b2c1970 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1219,3 +1219,6 @@ export type PackageDocsResult = { | { error: string; details?: never } | { details: PackageDetailsSuccess; error?: never } ); + +// language -> package -> package info +export type DocsSuggestions = Record; diff --git a/core/indexing/docs/suggestions/index.ts b/core/indexing/docs/suggestions/index.ts index 5699cd761..3ee4fb642 100644 --- a/core/indexing/docs/suggestions/index.ts +++ b/core/indexing/docs/suggestions/index.ts @@ -1,4 +1,5 @@ import { + DocsSuggestions, FilePathAndName, IDE, PackageDetails, @@ -80,7 +81,7 @@ export async function getAllSuggestedDocs(ide: IDE) { }); // Get documentation links for all packages - const docsByLanguage: Record = {}; + const docsByLanguage: DocsSuggestions = {}; await Promise.all( PACKAGE_CRAWLERS.map(async (Crawler) => { const crawler = new Crawler(); @@ -112,7 +113,6 @@ export async function getAllSuggestedDocs(ide: IDE) { ); }), ); - return docsByLanguage; } diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index ebe2a8697..2bd8de2c1 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -75,4 +75,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "getWebviewHistoryLength", "signInToControlPlane", "openDialogMessage", + "docs/suggestions", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 0dcdb047f..bf90497c8 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -2,6 +2,7 @@ import { ConfigValidationError } from "../config/validation.js"; import type { ContextItemWithId, + DocsSuggestions, IndexingProgressUpdate, IndexingStatus, } from "../index.js"; @@ -25,4 +26,5 @@ export type ToWebviewFromIdeOrCoreProtocol = { getWebviewHistoryLength: [undefined, number]; signInToControlPlane: [undefined, void]; openDialogMessage: ["account", void]; + "docs/suggestions": [DocsSuggestions, void]; }; diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 098194886..c21aca5a6 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -5,7 +5,7 @@ import { } from "@heroicons/react/24/outline"; import { SiteIndexingConfig } from "core"; import { usePostHog } from "posthog-js/react"; -import { useContext, useLayoutEffect, useRef, useState } from "react"; +import { useContext, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Button, HelperText, Input, lightGray, SecondaryButton } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; @@ -15,6 +15,7 @@ import { } from "../../redux/slices/uiStateSlice"; import { RootState } from "../../redux/store"; import IndexingStatusViewer from "../indexing/IndexingStatus"; +import { C } from "core/autocomplete/constants/AutocompleteLanguageInfo"; function AddDocsDialog() { const posthog = usePostHog(); @@ -34,6 +35,21 @@ function AddDocsDialog() { (store: RootState) => store.state.indexing.statuses, ); + const docsSuggestions = useSelector( + (store: RootState) => store.state.docsSuggestions, + ); + + const docsByLanguage = useMemo(() => { + console.log(docsSuggestions); + const languages = Object.keys(docsSuggestions); + return languages.map((language) => { + return { + language, + packages: docsSuggestions[language], + }; + }); + }, [docsSuggestions]); + const isFormValid = startUrl && title; useLayoutEffect(() => { @@ -118,8 +134,23 @@ function AddDocsDialog() { return (
-

Add a documentation site

- +

Add documentation

+ {docsByLanguage.map(({ language, packages }) => { + return ( +
+

{language}

+
+ {packages.map((pkg) => { + return ( +
+

{pkg.packageInfo.name}

+
+ ); + })} +
+
+ ); + })}

Continue pre-indexes many common documentation sites, but if there's one you don't see in the dropdown, enter the URL here. diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index f18379889..ecc7a7ac9 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -11,6 +11,7 @@ import { setInactive, setSelectedProfileId, setTTSActive, + updateDocsSuggestions, updateIndexingStatus, } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; @@ -85,6 +86,7 @@ function useSetup(dispatch: Dispatch) { // ON LOAD useEffect(() => { ideMessenger.post("docs/getSuggestedDocs", undefined); + // Override persisted state dispatch(setInactive()); @@ -116,6 +118,10 @@ function useSetup(dispatch: Dispatch) { } }, []); + useWebviewListener("docs/suggestions", async (data) => { + dispatch(updateDocsSuggestions(data)); + }); + const { streamResponse } = useChatHandler(dispatch, ideMessenger); const defaultModelTitle = useSelector( diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 770e9ce69..e965455c4 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -5,6 +5,7 @@ import { ChatMessage, Checkpoint, ContextItemWithId, + DocsSuggestions, FileSymbolMap, IndexingStatus, PersistedSessionInfo, @@ -47,6 +48,7 @@ type State = { }; streamAborter: AbortController; isMultifileEdit: boolean; + docsSuggestions: DocsSuggestions; }; const initialState: State = { @@ -89,6 +91,7 @@ const initialState: State = { }, }, streamAborter: new AbortController(), + docsSuggestions: {}, }; export const stateSlice = createSlice({ @@ -447,6 +450,13 @@ export const stateSlice = createSlice({ [payload.type]: payload.hidden, }; }, + updateDocsSuggestions: ( + state, + { payload }: PayloadAction, + ) => { + console.log("FROM REDUX", payload); + state.docsSuggestions = payload; + }, }, }); @@ -480,6 +490,7 @@ export const { updateIndexingStatus, setIndexingChatPeekHidden, abortStream, + updateDocsSuggestions, } = stateSlice.actions; export default stateSlice.reducer; From fec4b21f7b713708befa8dbd12cdd9f8a4f4f219 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 21 Nov 2024 11:45:37 -0800 Subject: [PATCH 048/747] improv: unify autocomplete snippets --- core/autocomplete/CompletionProvider.ts | 84 +++++------ core/autocomplete/aggregateSnippets.ts | 45 ------ .../context/ContextRetrievalService.ts | 109 ++++---------- core/autocomplete/context/ranking/index.ts | 116 +++++++-------- .../context/ranking/slidingWindow.ts | 105 +++++++------- .../RootPathContextService.ts | 21 ++- .../snippets/aggregateSnippets.ts | 45 ++++++ core/autocomplete/snippets/getAllSnippets.ts | 134 ++++++++++++++++++ core/autocomplete/snippets/index.ts | 1 + core/autocomplete/snippets/types.ts | 17 ++- .../templating/AutocompleteTemplate.ts | 24 ++-- core/autocomplete/templating/index.ts | 17 ++- core/autocomplete/types.ts | 21 +++ core/config/types.ts | 1 - core/index.d.ts | 1 - core/util/parameters.ts | 1 - extensions/vscode/package-lock.json | 4 +- extensions/vscode/src/autocomplete/lsp.ts | 16 ++- packages/config-types/src/index.ts | 1 - 19 files changed, 442 insertions(+), 321 deletions(-) delete mode 100644 core/autocomplete/aggregateSnippets.ts create mode 100644 core/autocomplete/snippets/aggregateSnippets.ts create mode 100644 core/autocomplete/snippets/getAllSnippets.ts create mode 100644 core/autocomplete/snippets/index.ts create mode 100644 core/autocomplete/types.ts diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index c3445498e..c41bbb389 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -5,17 +5,16 @@ import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; -import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; -import { aggregateSnippets } from "./aggregateSnippets"; +import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; // @prettier-ignore -import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; -import { AutocompleteSnippetDeprecated } from "./context/ranking/index.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { postprocessCompletion } from "./postprocessing/index.js"; import { shouldPrefilter } from "./prefiltering/index.js"; +import { getAllSnippets, TEMP__Snippets } from "./snippets/index.js"; import { renderPrompt } from "./templating/index.js"; +import { GetLspDefinitionsFunction } from "./types.js"; import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js"; import AutocompleteLruCache from "./util/AutocompleteLruCache.js"; @@ -32,14 +31,6 @@ const ERRORS_TO_IGNORE = [ "operation was aborted", ]; -export type GetLspDefinitionsFunction = ( - filepath: string, - contents: string, - cursorIndex: number, - ide: IDE, - lang: AutocompleteLanguageInfo, -) => Promise; - export class CompletionProvider { private autocompleteCache = AutocompleteLruCache.get(); public errorsShown: Set = new Set(); @@ -171,21 +162,14 @@ export class CompletionProvider { token = controller.signal; } - ////////// - - // Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, - // or they might separately track recently edited ranges) - const extraSnippets = await this._getExtraSnippets(helper); - - const [snippets, diff, clipboardContent, workspaceDirs] = + const [{ snippets, diff, clipboardContent }, workspaceDirs] = await Promise.all([ - aggregateSnippets( + getAllSnippets({ helper, - extraSnippets, - this.contextRetrievalService, - ), - this.ide.getDiff(true), - this.ide.getClipboardContent(), + ide: this.ide, + getDefinitionsFromLsp: this.getDefinitionsFromLsp, + contextRetrievalService: this.contextRetrievalService, + }), this.ide.getWorkspaceDirs(), ]); @@ -289,31 +273,31 @@ export class CompletionProvider { } } - private async _getExtraSnippets( - helper: HelperVars, - ): Promise { - let extraSnippets = helper.options.useOtherFiles - ? ((await Promise.race([ - this.getDefinitionsFromLsp( - helper.input.filepath, - helper.fullPrefix + helper.fullSuffix, - helper.fullPrefix.length, - this.ide, - helper.lang, - ), - new Promise((resolve) => { - setTimeout(() => resolve([]), 100); - }), - ])) as AutocompleteSnippetDeprecated[]) - : []; + // private async _getExtraSnippets( + // helper: HelperVars, + // ): Promise { + // let extraSnippets = helper.options.useOtherFiles + // ? ((await Promise.race([ + // this.getDefinitionsFromLsp( + // helper.input.filepath, + // helper.fullPrefix + helper.fullSuffix, + // helper.fullPrefix.length, + // this.ide, + // helper.lang, + // ), + // new Promise((resolve) => { + // setTimeout(() => resolve([]), 100); + // }), + // ])) as AutocompleteSnippetDeprecated[]) + // : []; - const workspaceDirs = await this.ide.getWorkspaceDirs(); - if (helper.options.onlyMyCode) { - extraSnippets = extraSnippets.filter((snippet) => { - return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); - }); - } + // const workspaceDirs = await this.ide.getWorkspaceDirs(); + // if (helper.options.onlyMyCode) { + // extraSnippets = extraSnippets.filter((snippet) => { + // return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); + // }); + // } - return extraSnippets; - } + // return extraSnippets; + // } } diff --git a/core/autocomplete/aggregateSnippets.ts b/core/autocomplete/aggregateSnippets.ts deleted file mode 100644 index e6c750a4b..000000000 --- a/core/autocomplete/aggregateSnippets.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; -import { - fillPromptWithSnippets, - rankAndOrderSnippets, - type AutocompleteSnippetDeprecated, -} from "./context/ranking/index.js"; -import { HelperVars } from "./util/HelperVars.js"; - -function filterSnippetsAlreadyInCaretWindow( - snippets: AutocompleteSnippetDeprecated[], - caretWindow: string, -): AutocompleteSnippetDeprecated[] { - return snippets - .map((snippet) => ({ ...snippet })) - .filter( - (s) => - s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()), - ); -} - -export async function aggregateSnippets( - helper: HelperVars, - extraSnippets: AutocompleteSnippetDeprecated[], - contextRetrievalService: ContextRetrievalService, -): Promise { - let snippets = await contextRetrievalService.retrieveCandidateSnippets( - helper, - extraSnippets, - ); - - snippets = filterSnippetsAlreadyInCaretWindow( - snippets, - helper.prunedCaretWindow, - ); - - const scoredSnippets = rankAndOrderSnippets(snippets, helper); - - const finalSnippets = fillPromptWithSnippets( - scoredSnippets, - helper.maxSnippetTokens, - helper.modelName, - ); - - return finalSnippets; -} diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index 66b67eec3..72e061fed 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -1,9 +1,12 @@ import { IDE } from "../.."; +import { + AutocompleteCodeSnippet, + AutocompleteSnippetType, +} from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; -import { RecentlyEditedRange } from "../util/types"; import { ImportDefinitionsService } from "./ImportDefinitionsService"; -import { AutocompleteSnippetDeprecated, getSymbolsForSnippet } from "./ranking"; +import { getSymbolsForSnippet } from "./ranking"; import { RootPathContextService } from "./root-path-context/RootPathContextService"; export class ContextRetrievalService { @@ -18,79 +21,14 @@ export class ContextRetrievalService { ); } - public async retrieveCandidateSnippets( + public async getSnippetsFromImportDefinitions( helper: HelperVars, - extraSnippets: AutocompleteSnippetDeprecated[], - ) { - if (helper.options.useOtherFiles === false) { - return []; - } - - let snippets: AutocompleteSnippetDeprecated[] = []; - - // Snippets injected by the IDE for IDE-specific reasons - snippets.push(...extraSnippets); - - // If a recently edited range has a line that is a perfect match with the start of the current line - snippets.push(...this.getSnippetsFromRecentlyEditedRanges(helper)); - - // Import definitions of any symbols in near range of the caret - snippets.push(...(await this.getSnippetsFromImportDefinitions(helper))); - - // Root path context https://blog.continue.dev/root-path-context-the-secret-ingredient-in-continues-autocomplete-prompt/ - if (helper.options.useRootPathContext && helper.treePath) { - snippets.push( - ...(await this.rootPathContextService.getContextForPath( - helper.filepath, - helper.treePath, - )), - ); - } - - return snippets; - } - - private getSnippetsFromRecentlyEditedRanges( - helper: HelperVars, - ): AutocompleteSnippetDeprecated[] { - if (helper.options.useRecentlyEdited === false) { - return []; - } - - const currentLinePrefix = helper.prunedPrefix - .trim() - .split("\n") - .slice(-1)[0]; - if ( - currentLinePrefix?.length > helper.options.recentLinePrefixMatchMinLength - ) { - const matchingRange = this.findMatchingRange( - helper.input.recentlyEditedRanges, - currentLinePrefix, - ); - - if (matchingRange) { - return [ - { - ...matchingRange, - contents: matchingRange.lines.join("\n"), - score: 0.8, - }, - ]; - } - } - - return []; - } - - private async getSnippetsFromImportDefinitions( - helper: HelperVars, - ): Promise { + ): Promise { if (helper.options.useImports === false) { return []; } - const importSnippets = []; + const importSnippets: AutocompleteCodeSnippet[] = []; const fileInfo = this.importDefinitionsService.get(helper.filepath); if (fileInfo) { const { imports } = fileInfo; @@ -104,21 +42,32 @@ export class ContextRetrievalService { for (const symbol of symbols) { const rifs = imports[symbol]; if (Array.isArray(rifs)) { - importSnippets.push(...rifs); + const snippets: AutocompleteCodeSnippet[] = rifs.map((rif) => { + return { + filepath: rif.filepath, + content: rif.contents, + type: AutocompleteSnippetType.Code, + }; + }); + + importSnippets.push(...snippets); } } } + return importSnippets; } - findMatchingRange( - recentlyEditedRanges: RecentlyEditedRange[], - linePrefix: string, - ): RecentlyEditedRange | undefined { - return recentlyEditedRanges.find((recentlyEditedRange) => { - return recentlyEditedRange.lines.some((line) => - line.startsWith(linePrefix), - ); - }); + public async getRootPathSnippets( + helper: HelperVars, + ): Promise { + if (!helper.treePath) { + return []; + } + + return this.rootPathContextService.getContextForPath( + helper.filepath, + helper.treePath, + ); } } diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index 28e9b8112..a11389470 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -1,17 +1,9 @@ import { RangeInFileWithContents } from "../../../commands/util.js"; import { Range } from "../../../index.js"; import { countTokens } from "../../../llm/countTokens.js"; +import { AutocompleteSnippetDeprecated } from "../../types.js"; import { HelperVars } from "../../util/HelperVars.js"; -/** - * @deprecated This type should be removed in the future or renamed. - * We have a new interface called AutocompleteSnippet which is more - * general. - */ -export type AutocompleteSnippetDeprecated = RangeInFileWithContents & { - score?: number; -}; - const rx = /[\s.,\/#!$%\^&\*;:{}=\-_`~()\[\]]/g; export function getSymbolsForSnippet(snippet: string): Set { const symbols = snippet @@ -24,7 +16,7 @@ export function getSymbolsForSnippet(snippet: string): Set { /** * Calculate similarity as number of shared symbols divided by total number of unique symbols between both. */ -export function jaccardSimilarity(a: string, b: string): number { +function jaccardSimilarity(a: string, b: string): number { const aSet = getSymbolsForSnippet(a); const bSet = getSymbolsForSnippet(b); const union = new Set([...aSet, ...bSet]).size; @@ -76,7 +68,7 @@ export function rankAndOrderSnippets( /** * Deduplicate code snippets by merging overlapping ranges into a single range. */ -export function deduplicateSnippets( +function deduplicateSnippets( snippets: Required[], ): Required[] { // Group by file @@ -166,54 +158,54 @@ export function fillPromptWithSnippets( /** * Remove one range from another range, which may lead to returning two disjoint ranges */ -function rangeDifferenceByLines(orig: Range, remove: Range): Range[] { - if ( - orig.start.line >= remove.start.line && - orig.end.line <= remove.end.line - ) { - // / | | / - return []; - } - if ( - orig.start.line <= remove.start.line && - orig.end.line >= remove.end.line - ) { - // | / / | - // Splits the range - return [ - { - start: orig.start, - end: remove.start, - }, - { - start: remove.end, - end: orig.end, - }, - ]; - } - if ( - orig.start.line >= remove.start.line && - orig.end.line >= remove.end.line - ) { - // \ | / | - return [ - { - start: remove.end, - end: orig.end, - }, - ]; - } - if ( - orig.start.line <= remove.start.line && - orig.end.line <= remove.end.line - ) { - // | / | / - return [ - { - start: orig.start, - end: remove.start, - }, - ]; - } - return [orig]; -} +// function rangeDifferenceByLines(orig: Range, remove: Range): Range[] { +// if ( +// orig.start.line >= remove.start.line && +// orig.end.line <= remove.end.line +// ) { +// // / | | / +// return []; +// } +// if ( +// orig.start.line <= remove.start.line && +// orig.end.line >= remove.end.line +// ) { +// // | / / | +// // Splits the range +// return [ +// { +// start: orig.start, +// end: remove.start, +// }, +// { +// start: remove.end, +// end: orig.end, +// }, +// ]; +// } +// if ( +// orig.start.line >= remove.start.line && +// orig.end.line >= remove.end.line +// ) { +// // \ | / | +// return [ +// { +// start: remove.end, +// end: orig.end, +// }, +// ]; +// } +// if ( +// orig.start.line <= remove.start.line && +// orig.end.line <= remove.end.line +// ) { +// // | / | / +// return [ +// { +// start: orig.start, +// end: remove.start, +// }, +// ]; +// } +// return [orig]; +// } diff --git a/core/autocomplete/context/ranking/slidingWindow.ts b/core/autocomplete/context/ranking/slidingWindow.ts index 3fd3a3f17..88ee2bff3 100644 --- a/core/autocomplete/context/ranking/slidingWindow.ts +++ b/core/autocomplete/context/ranking/slidingWindow.ts @@ -1,60 +1,61 @@ -import { RangeInFileWithContents } from "../../../commands/util.js"; +// import { RangeInFileWithContents } from "../../../commands/util.js"; +// import { AutocompleteSnippetDeprecated } from "../../types.js"; -import { AutocompleteSnippetDeprecated, jaccardSimilarity } from "./index.js"; +// import { jaccardSimilarity } from "./index.js"; -function* slidingWindow( - content: string, - windowSize: number, -): Generator { - const lines = content.split("\n"); +// function* slidingWindow( +// content: string, +// windowSize: number, +// ): Generator { +// const lines = content.split("\n"); - let charCount = 0; - let currWindowLines: string[] = []; - for (let i = 0; i < lines.length; i++) { - if (charCount + lines[i].length >= windowSize) { - yield currWindowLines.join("\n"); - currWindowLines = [lines[i]]; - charCount = 0; - } else { - currWindowLines.push(lines[i]); - } - charCount += lines[i].length; - } +// let charCount = 0; +// let currWindowLines: string[] = []; +// for (let i = 0; i < lines.length; i++) { +// if (charCount + lines[i].length >= windowSize) { +// yield currWindowLines.join("\n"); +// currWindowLines = [lines[i]]; +// charCount = 0; +// } else { +// currWindowLines.push(lines[i]); +// } +// charCount += lines[i].length; +// } - if (currWindowLines.length > 0) { - yield currWindowLines.join("\n"); - } -} +// if (currWindowLines.length > 0) { +// yield currWindowLines.join("\n"); +// } +// } -/** - * Match by similarity over sliding windows of recent documents. - * @param recentFiles - * @param prefix - * @param suffix - */ -export async function slidingWindowMatcher( - recentFiles: RangeInFileWithContents[], - windowAroundCursor: string, - topN: number, - windowSize: number, -): Promise { - // Sorted lowest similarity to highest - const topMatches: Required[] = []; +// /** +// * Match by similarity over sliding windows of recent documents. +// * @param recentFiles +// * @param prefix +// * @param suffix +// */ +// export async function slidingWindowMatcher( +// recentFiles: RangeInFileWithContents[], +// windowAroundCursor: string, +// topN: number, +// windowSize: number, +// ): Promise { +// // Sorted lowest similarity to highest +// const topMatches: Required[] = []; - for (const { filepath, contents, range } of recentFiles) { - for (const window of slidingWindow(contents, windowSize)) { - const score = jaccardSimilarity(window, windowAroundCursor); +// for (const { filepath, contents, range } of recentFiles) { +// for (const window of slidingWindow(contents, windowSize)) { +// const score = jaccardSimilarity(window, windowAroundCursor); - // Insertion sort - let i = -1; - while (++i < topMatches.length && score > topMatches[i].score) {} - topMatches.splice(i + 1, 0, { filepath, contents, score, range }); - if (topMatches.length > topN) { - topMatches.shift(); - } - } - } +// // Insertion sort +// let i = -1; +// while (++i < topMatches.length && score > topMatches[i].score) {} +// topMatches.splice(i + 1, 0, { filepath, contents, score, range }); +// if (topMatches.length > topN) { +// topMatches.shift(); +// } +// } +// } - // TODO: convert the arbitrary window frame to some whole AST node? - return topMatches; -} +// // TODO: convert the arbitrary window frame to some whole AST node? +// return topMatches; +// } diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index 98a947fb1..a94e37e38 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -12,7 +12,11 @@ import { } from "../../../util/treeSitter"; import { AstPath } from "../../util/ast"; import { ImportDefinitionsService } from "../ImportDefinitionsService"; -import { AutocompleteSnippetDeprecated } from "../ranking"; +import { AutocompleteSnippetDeprecated } from "../../types"; +import { + AutocompleteCodeSnippet, + AutocompleteSnippetType, +} from "../../snippets/types"; function getSyntaxTreeString( node: Parser.SyntaxNode, @@ -153,8 +157,8 @@ export class RootPathContextService { filepath: string, astPath: AstPath, // cursorIndex: number, - ): Promise { - const snippets: AutocompleteSnippetDeprecated[] = []; + ): Promise { + const snippets: AutocompleteCodeSnippet[] = []; let parentKey = filepath; for (const astNode of astPath.filter((node) => @@ -167,7 +171,16 @@ export class RootPathContextService { const foundInCache = this.cache.get(key); const newSnippets = foundInCache ?? (await this.getSnippetsForNode(filepath, astNode)); - snippets.push(...newSnippets); + + const formattedSnippets: AutocompleteCodeSnippet[] = newSnippets.map( + (item) => ({ + filepath: item.filepath, + content: item.contents, + type: AutocompleteSnippetType.Code, + }), + ); + + snippets.push(...formattedSnippets); if (!foundInCache) { this.cache.set(key, newSnippets); diff --git a/core/autocomplete/snippets/aggregateSnippets.ts b/core/autocomplete/snippets/aggregateSnippets.ts new file mode 100644 index 000000000..1562c6f57 --- /dev/null +++ b/core/autocomplete/snippets/aggregateSnippets.ts @@ -0,0 +1,45 @@ +// import { ContextRetrievalService } from "../context/ContextRetrievalService.js"; +// import { +// fillPromptWithSnippets, +// rankAndOrderSnippets, +// } from "../context/ranking/index.js"; +// import { AutocompleteSnippetDeprecated } from "../types.js"; +// import { HelperVars } from "../util/HelperVars.js"; + +// function filterSnippetsAlreadyInCaretWindow( +// snippets: AutocompleteSnippetDeprecated[], +// caretWindow: string, +// ): AutocompleteSnippetDeprecated[] { +// return snippets +// .map((snippet) => ({ ...snippet })) +// .filter( +// (s) => +// s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()), +// ); +// } + +// export async function aggregateSnippets( +// helper: HelperVars, +// extraSnippets: AutocompleteSnippetDeprecated[], +// contextRetrievalService: ContextRetrievalService, +// ): Promise { +// let snippets = await contextRetrievalService.retrieveCandidateSnippets( +// helper, +// extraSnippets, +// ); + +// snippets = filterSnippetsAlreadyInCaretWindow( +// snippets, +// helper.prunedCaretWindow, +// ); + +// const scoredSnippets = rankAndOrderSnippets(snippets, helper); + +// const finalSnippets = fillPromptWithSnippets( +// scoredSnippets, +// helper.maxSnippetTokens, +// helper.modelName, +// ); + +// return finalSnippets; +// } diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts new file mode 100644 index 000000000..6f6c79ba3 --- /dev/null +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -0,0 +1,134 @@ +import { IDE } from "../../index"; +import { ContextRetrievalService } from "../context/ContextRetrievalService"; +import { GetLspDefinitionsFunction } from "../types"; +import { HelperVars } from "../util/HelperVars"; +import { + AutocompleteClipboardSnippet, + AutocompleteCodeSnippet, + AutocompleteDiffSnippet, + AutocompleteSnippetType, +} from "./types"; + +// Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, +// or they might separately track recently edited ranges) +async function getIdeSnippets( + helper: HelperVars, + ide: IDE, + getDefinitionsFromLsp: GetLspDefinitionsFunction, +): Promise { + const ideSnippets = (await Promise.race([ + getDefinitionsFromLsp( + helper.input.filepath, + helper.fullPrefix + helper.fullSuffix, + helper.fullPrefix.length, + ide, + helper.lang, + ), + new Promise((resolve) => { + setTimeout(() => resolve([]), 100); + }), + ])) as AutocompleteCodeSnippet[]; + + if (helper.options.onlyMyCode) { + const workspaceDirs = await ide.getWorkspaceDirs(); + + return ideSnippets.filter((snippet) => + workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)), + ); + } + + return ideSnippets; +} + +function getSnippetsFromRecentlyEditedRanges( + helper: HelperVars, +): AutocompleteCodeSnippet[] { + if (helper.options.useRecentlyEdited === false) { + return []; + } + + return helper.input.recentlyEditedRanges.map((range) => { + return { + filepath: range.filepath, + content: range.lines.join("\n"), + score: 0.8, + type: AutocompleteSnippetType.Code, + }; + }); +} + +export type TEMP__Snippets = { + snippets: AutocompleteCodeSnippet[]; + diff: string | undefined; + clipboardContent: { + text: string; + copiedAt: string; + }; + new: { + rootPathSnippets: AutocompleteCodeSnippet[]; + importDefinitionSnippets: AutocompleteCodeSnippet[]; + ideSnippets: AutocompleteCodeSnippet[]; + recentlyEditedRangeSnippets: AutocompleteCodeSnippet[]; + diffSnippets: AutocompleteDiffSnippet[]; + clipboardSnippets: AutocompleteClipboardSnippet[]; + }; +}; + +export const getAllSnippets = async ({ + helper, + ide, + getDefinitionsFromLsp, + contextRetrievalService, +}: { + helper: HelperVars; + ide: IDE; + getDefinitionsFromLsp: GetLspDefinitionsFunction; + contextRetrievalService: ContextRetrievalService; +}): Promise => { + const recentlyEditedRangeSnippets = + getSnippetsFromRecentlyEditedRanges(helper); + + const [ + rootPathSnippets, + importDefinitionSnippets, + ideSnippets, + diff, + clipboardContent, + ] = await Promise.all([ + contextRetrievalService.getRootPathSnippets(helper), + contextRetrievalService.getSnippetsFromImportDefinitions(helper), + getIdeSnippets(helper, ide, getDefinitionsFromLsp), + ide.getDiff(true), + ide.getClipboardContent(), + ]); + + return { + snippets: [ + ...rootPathSnippets, + ...importDefinitionSnippets, + ...ideSnippets, + ...recentlyEditedRangeSnippets, + ], + diff, + clipboardContent, + new: { + rootPathSnippets, + importDefinitionSnippets, + ideSnippets, + recentlyEditedRangeSnippets, + diffSnippets: [diff].map((item) => { + return { + content: item, + type: AutocompleteSnippetType.Diff, + }; + }), + clipboardSnippets: [clipboardContent].map((item) => { + return { + content: item.text, + copiedAt: item.copiedAt, + type: AutocompleteSnippetType.Clipboard, + }; + }), + }, + }; +}; diff --git a/core/autocomplete/snippets/index.ts b/core/autocomplete/snippets/index.ts new file mode 100644 index 000000000..2a9e1a7ce --- /dev/null +++ b/core/autocomplete/snippets/index.ts @@ -0,0 +1 @@ +export * from "./getAllSnippets"; diff --git a/core/autocomplete/snippets/types.ts b/core/autocomplete/snippets/types.ts index e39406b11..b97e07604 100644 --- a/core/autocomplete/snippets/types.ts +++ b/core/autocomplete/snippets/types.ts @@ -1,15 +1,28 @@ +export enum AutocompleteSnippetType { + Code = "code", + Diff = "diff", + Clipboard = "clipboard", +} + interface BaseAutocompleteSnippet { score?: number; content: string; + type: AutocompleteSnippetType; } export interface AutocompleteCodeSnippet extends BaseAutocompleteSnippet { filepath: string; + type: AutocompleteSnippetType.Code; } -export interface AutocompleteDiffSnippet extends BaseAutocompleteSnippet {} +export interface AutocompleteDiffSnippet extends BaseAutocompleteSnippet { + type: AutocompleteSnippetType.Diff; +} -export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet {} +export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet { + type: AutocompleteSnippetType.Clipboard; + copiedAt: string; +} export type AutocompleteSnippet = | AutocompleteCodeSnippet diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index 11fd47333..b84337c0e 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -2,7 +2,8 @@ import { CompletionOptions } from "../../index.js"; import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js"; -import { AutocompleteSnippetDeprecated } from "../context/ranking/index.js"; +import { AutocompleteCodeSnippet } from "../snippets/types.js"; +import { AutocompleteSnippetDeprecated } from "../types.js"; export interface AutocompleteTemplate { compilePrefixSuffix?: ( @@ -10,7 +11,7 @@ export interface AutocompleteTemplate { suffix: string, filepath: string, reponame: string, - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], ) => [string, string]; template: | string @@ -20,7 +21,7 @@ export interface AutocompleteTemplate { filepath: string, reponame: string, language: string, - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], ) => string); completionOptions?: Partial; } @@ -73,7 +74,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { suffix: string, filepath: string, reponame: string, - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], ): [string, string] => { if (snippets.length === 0) { if (suffix.trim().length === 0 && prefix.trim().length === 0) { @@ -86,7 +87,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { filepath, ]); const otherFiles = snippets - .map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.contents}`) + .map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.content}`) .join("\n\n"); return [ `${otherFiles}\n\n+++++ ${ @@ -101,7 +102,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { filepath: string, reponame: string, language: string, - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], ): string => { return `[SUFFIX]${suffix}[PREFIX]${prefix}`; }, @@ -133,15 +134,14 @@ const starcoder2FimTemplate: AutocompleteTemplate = { filename: string, reponame: string, language: string, - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], ): string => { const otherFiles = snippets.length === 0 ? "" : `${snippets .map((snippet) => { - return snippet.contents; - // return `${getBasename(snippet.filepath)}\n${snippet.contents}`; + return snippet.content; }) .join("")}`; @@ -187,7 +187,7 @@ const codegeexFimTemplate: AutocompleteTemplate = { filepath: string, reponame: string, language: string, - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], ): string => { const relativePaths = shortestRelativePaths([ ...snippets.map((snippet) => snippet.filepath), @@ -200,7 +200,7 @@ const codegeexFimTemplate: AutocompleteTemplate = { return `<|user|>\n${baseTemplate}<|assistant|>\n`; } const references = `###REFERENCE:\n${snippets - .map((snippet, i) => `###PATH:${relativePaths[i]}\n${snippet.contents}\n`) + .map((snippet, i) => `###PATH:${relativePaths[i]}\n${snippet.content}\n`) .join("###REFERENCE:\n")}`; const prompt = `<|user|>\n${references}\n${baseTemplate}<|assistant|>\n`; return prompt; @@ -233,7 +233,7 @@ const holeFillerTemplate: AutocompleteTemplate = { filename: string, reponame: string, language: string, - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], ) => { // From https://github.com/VictorTaelin/AI-scripts const SYSTEM_MSG = `You are a HOLE FILLER. You are provided with a file containing holes, formatted as '{{HOLE_NAME}}'. Your TASK is to complete with a string to replace this hole with, inside a XML tag, including context-aware indentation, if needed. All completions MUST be truthful, accurate, well-written and correct. diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index be2d178d4..2812130c5 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -3,7 +3,6 @@ import Handlebars from "handlebars"; import { CompletionOptions } from "../.."; import { getBasename, getLastNPathParts } from "../../util"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; -import { AutocompleteSnippetDeprecated } from "../context/ranking"; import { HelperVars } from "../util/HelperVars"; import { @@ -12,6 +11,11 @@ import { } from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; import { countTokens } from "../../llm/countTokens"; +import { AutocompleteSnippetDeprecated } from "../types"; +import { + AutocompleteCodeSnippet, + AutocompleteSnippet, +} from "../snippets/types"; const addCommentMarks = (text: string, language: AutocompleteLanguageInfo) => { const comment = language.singleLineComment; @@ -34,7 +38,7 @@ export function formatExternalSnippet( } function getContextComments( - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], lang: AutocompleteLanguageInfo, filepath: string, ) { @@ -49,7 +53,7 @@ function getContextComments( headerSnipper + snippets .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), + formatExternalSnippet(snippet.filepath, snippet.content, lang), ) .join("\n") + fileNameSnippet; @@ -122,6 +126,11 @@ const formatClipboardContent = ( return ""; } + const isEmpty = text.trim() === ""; + if (isEmpty) { + return ""; + } + return ( addCommentMarks( `Recently copied by user:${text.includes("\n") ? "\n" : ""} ${text}`, @@ -137,7 +146,7 @@ export function renderPrompt({ diff, clipboardContent, }: { - snippets: AutocompleteSnippetDeprecated[]; + snippets: AutocompleteCodeSnippet[]; workspaceDirs: string[]; helper: HelperVars; diff?: string; diff --git a/core/autocomplete/types.ts b/core/autocomplete/types.ts new file mode 100644 index 000000000..9488fb085 --- /dev/null +++ b/core/autocomplete/types.ts @@ -0,0 +1,21 @@ +import { RangeInFileWithContents } from "../commands/util"; +import { IDE } from "../index"; +import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo"; +import { AutocompleteCodeSnippet } from "./snippets/types"; + +/** + * @deprecated This type should be removed in the future or renamed. + * We have a new interface called AutocompleteSnippet which is more + * general. + */ +export type AutocompleteSnippetDeprecated = RangeInFileWithContents & { + score?: number; +}; + +export type GetLspDefinitionsFunction = ( + filepath: string, + contents: string, + cursorIndex: number, + ide: IDE, + lang: AutocompleteLanguageInfo, +) => Promise; diff --git a/core/config/types.ts b/core/config/types.ts index f397b1ed7..47c4a5aa7 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -842,7 +842,6 @@ declare global { onlyMyCode: boolean; useOtherFiles: boolean; useRecentlyEdited: boolean; - recentLinePrefixMatchMinLength: number; disableInFiles?: string[]; useImports?: boolean; } diff --git a/core/index.d.ts b/core/index.d.ts index 0646edc54..f96cbd122 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -986,7 +986,6 @@ export interface TabAutocompleteOptions { onlyMyCode: boolean; useOtherFiles: boolean; useRecentlyEdited: boolean; - recentLinePrefixMatchMinLength: number; disableInFiles?: string[]; useImports?: boolean; useRootPathContext?: boolean; diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 20b96ac47..7ba828f7a 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -18,7 +18,6 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { onlyMyCode: true, useOtherFiles: true, useRecentlyEdited: true, - recentLinePrefixMatchMinLength: 7, disableInFiles: undefined, useImports: true, useRootPathContext: true, diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 940503505..b30a951df 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", diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index de719d3bf..a11aeeead 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -1,6 +1,4 @@ -import { GetLspDefinitionsFunction } from "core/autocomplete/CompletionProvider"; import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo"; -import { AutocompleteSnippetDeprecated } from "core/autocomplete/context/ranking"; import { getAst, getTreePathAtCursor } from "core/autocomplete/util/ast"; import { RangeInFileWithContents } from "core/commands/util"; import { @@ -12,6 +10,14 @@ import * as vscode from "vscode"; import type { IDE, Range, RangeInFile } from "core"; import type Parser from "web-tree-sitter"; +import { + AutocompleteSnippetDeprecated, + GetLspDefinitionsFunction, +} from "core/autocomplete/types"; +import { + AutocompleteCodeSnippet, + AutocompleteSnippetType, +} from "core/autocomplete/snippets/types"; type GotoProviderName = | "vscode.executeDefinitionProvider" @@ -342,7 +348,7 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( cursorIndex: number, ide: IDE, lang: AutocompleteLanguageInfo, -): Promise => { +): Promise => { try { const ast = await getAst(filepath, contents); if (!ast) { @@ -366,8 +372,10 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( } return results.map((result) => ({ - ...result, + filepath: result.filepath, + content: result.contents, score: 0.8, + type: AutocompleteSnippetType.Code, })); } catch (e) { console.warn("Error getting definitions from LSP: ", e); diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index 876115d11..fc53c742f 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -148,7 +148,6 @@ export const tabAutocompleteOptionsSchema = z.object({ onlyMyCode: z.boolean(), useOtherFiles: z.boolean(), useRecentlyEdited: z.boolean(), - recentLinePrefixMatchMinLength: z.number(), disableInFiles: z.array(z.string()).optional(), useImports: z.boolean().optional(), }); From 53f3638b8f0ec703579f3136f7293d4d88ea8a28 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 21 Nov 2024 16:37:28 -0800 Subject: [PATCH 049/747] suggested docs continued --- core/index.d.ts | 11 +++++-- core/indexing/docs/suggestions/index.ts | 30 ++++++++++++----- .../suggestions/packageCrawlers/Python.ts | 29 +++++++++++++---- .../docs/suggestions/packageCrawlers/TsJs.ts | 24 +++++++++++--- gui/src/components/dialogs/AddDocsDialog.tsx | 32 ++++--------------- gui/src/components/dialogs/SuggestedDocs.tsx | 18 +++++++++++ gui/src/redux/slices/stateSlice.ts | 9 +++--- 7 files changed, 100 insertions(+), 53 deletions(-) create mode 100644 gui/src/components/dialogs/SuggestedDocs.tsx diff --git a/core/index.d.ts b/core/index.d.ts index d6b2c1970..328462e70 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1196,6 +1196,12 @@ export interface FilePathAndName { path: string; name: string; } + +export interface PackageFilePathAndName extends FilePathAndName { + language: string; // e.g. javascript + registry: string; // e.g. npm +} + export type ParsedPackageInfo = { language: string; name: string; @@ -1207,6 +1213,8 @@ export type PackageDetails = { docsLink?: string; title?: string; description?: string; + repo?: string; + license?: string; }; export type PackageDetailsSuccess = PackageDetails & { @@ -1219,6 +1227,3 @@ export type PackageDocsResult = { | { error: string; details?: never } | { details: PackageDetailsSuccess; error?: never } ); - -// language -> package -> package info -export type DocsSuggestions = Record; diff --git a/core/indexing/docs/suggestions/index.ts b/core/indexing/docs/suggestions/index.ts index 3ee4fb642..0f86f5390 100644 --- a/core/indexing/docs/suggestions/index.ts +++ b/core/indexing/docs/suggestions/index.ts @@ -1,9 +1,9 @@ import { - DocsSuggestions, + PackageDocsResult, FilePathAndName, + PackageFilePathAndName, IDE, PackageDetails, - PackageDocsResult, ParsedPackageInfo, } from "../../.."; import { walkDir } from "../../walkDir"; @@ -15,9 +15,9 @@ const PACKAGE_CRAWLERS = [TypeScriptPackageCrawler, PythonPackageCrawler]; export interface PackageCrawler { language: string; - getPackageFiles(files: FilePathAndName[]): FilePathAndName[]; + getPackageFiles(files: FilePathAndName[]): PackageFilePathAndName[]; parsePackageFile( - file: FilePathAndName, + file: PackageFilePathAndName, contents: string, ): ParsedPackageInfo[]; getPackageDetails(packageInfo: ParsedPackageInfo): Promise; @@ -37,7 +37,7 @@ export async function getAllSuggestedDocs(ide: IDE) { })); // Build map of language -> package files - const packageFilesByLanguage: Record = {}; + const packageFilesByLanguage: Record = {}; for (const Crawler of PACKAGE_CRAWLERS) { const crawler = new Crawler(); const packageFilePaths = crawler.getPackageFiles(allFiles); @@ -80,13 +80,26 @@ export async function getAllSuggestedDocs(ide: IDE) { }); }); + // Deduplicate packages per language + // TODO - this is where you would allow docs for different versions + // by e.g. using "name-version" as the map key instead of just name + // For now have not allowed + const languages = Object.keys(packagesByLanguage); + languages.forEach((language) => { + const packages = packagesByLanguage[language]; + const uniquePackages = Array.from( + new Map(packages.map((pkg) => [pkg.name, pkg])).values(), + ); + packagesByLanguage[language] = uniquePackages; + }); + // Get documentation links for all packages - const docsByLanguage: DocsSuggestions = {}; + const allDocsResults: PackageDocsResult[] = []; await Promise.all( PACKAGE_CRAWLERS.map(async (Crawler) => { const crawler = new Crawler(); const packages = packagesByLanguage[crawler.language]; - docsByLanguage[crawler.language] = await Promise.all( + const docsByLanguage = await Promise.all( packages.map(async (packageInfo) => { try { const details = await crawler.getPackageDetails(packageInfo); @@ -111,9 +124,10 @@ export async function getAllSuggestedDocs(ide: IDE) { } }), ); + allDocsResults.push(...docsByLanguage); }), ); - return docsByLanguage; + return allDocsResults; } // write me an interface PackageCrawler that contains: diff --git a/core/indexing/docs/suggestions/packageCrawlers/Python.ts b/core/indexing/docs/suggestions/packageCrawlers/Python.ts index 233e44428..28b893b66 100644 --- a/core/indexing/docs/suggestions/packageCrawlers/Python.ts +++ b/core/indexing/docs/suggestions/packageCrawlers/Python.ts @@ -2,17 +2,24 @@ import { PackageCrawler } from ".."; import { FilePathAndName, PackageDetails, + PackageFilePathAndName, ParsedPackageInfo, } from "../../../.."; export class PythonPackageCrawler implements PackageCrawler { language = "python"; - getPackageFiles(files: FilePathAndName[]): FilePathAndName[] { + getPackageFiles(files: FilePathAndName[]): PackageFilePathAndName[] { // For Python, we typically look for files like requirements.txt or Pipfile - return files.filter( - (file) => file.name === "requirements.txt" || file.name === "Pipfile", - ); + return files + .filter( + (file) => file.name === "requirements.txt" || file.name === "Pipfile", + ) + .map((file) => ({ + ...file, + language: this.language, + registry: "pypi", + })); } parsePackageFile( @@ -41,10 +48,18 @@ export class PythonPackageCrawler implements PackageCrawler { throw new Error(`Could not fetch data for package ${packageInfo.name}`); } const data = await response.json(); + const homePage = data?.info?.home_page as string | undefined; + return { - docsLink: data.info.project_urls?.Documentation as string | undefined, - // title: data.info.name, - // description: data.info.summary as string | undefined, + docsLink: + (data?.info?.project_urls?.Documentation as string | undefined) ?? + homePage, + title: data?.info?.name as string | undefined, + description: data?.info?.summary as string | undefined, + repo: + (data?.info?.project_urls?.Repository as string | undefined) ?? + homePage, + license: data?.info?.license as string | undefined, }; } } diff --git a/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts b/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts index 107d9ac2a..c16b8872e 100644 --- a/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts +++ b/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts @@ -2,15 +2,22 @@ import { PackageCrawler } from ".."; import { FilePathAndName, PackageDetails, + PackageFilePathAndName, ParsedPackageInfo, } from "../../../.."; export class TypeScriptPackageCrawler implements PackageCrawler { language = "js-ts"; - getPackageFiles(files: FilePathAndName[]): FilePathAndName[] { + getPackageFiles(files: FilePathAndName[]): PackageFilePathAndName[] { // For Javascript/TypeScript, we look for package.json file - return files.filter((file) => file.name === "package.json"); + return files + .filter((file) => file.name === "package.json") + .map((file) => ({ + ...file, + language: this.language, + registry: "npm", + })); } parsePackageFile( @@ -22,7 +29,10 @@ export class TypeScriptPackageCrawler implements PackageCrawler { const dependencies = Object.entries(jsonData.dependencies || {}).concat( Object.entries(jsonData.devDependencies || {}), ); - return dependencies.map(([name, version]) => ({ + const filtered = dependencies.filter( + ([name, version]) => !name.startsWith("@types/"), + ); + return filtered.map(([name, version]) => ({ name, version, packageFile: file, @@ -42,8 +52,12 @@ export class TypeScriptPackageCrawler implements PackageCrawler { const data = await response.json(); return { docsLink: data.homepage as string | undefined, - // title: data.name, - // description: data.description as string | undefined, + title: name, // package.json doesn't have specific title field + description: data.description as string | undefined, + repo: Array.isArray(data.repository) + ? (data.respository[0]?.url as string | undefined) + : undefined, + license: data.license as string | undefined, }; } } diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index c21aca5a6..7dcc478fc 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -15,7 +15,6 @@ import { } from "../../redux/slices/uiStateSlice"; import { RootState } from "../../redux/store"; import IndexingStatusViewer from "../indexing/IndexingStatus"; -import { C } from "core/autocomplete/constants/AutocompleteLanguageInfo"; function AddDocsDialog() { const posthog = usePostHog(); @@ -39,17 +38,6 @@ function AddDocsDialog() { (store: RootState) => store.state.docsSuggestions, ); - const docsByLanguage = useMemo(() => { - console.log(docsSuggestions); - const languages = Object.keys(docsSuggestions); - return languages.map((language) => { - return { - language, - packages: docsSuggestions[language], - }; - }); - }, [docsSuggestions]); - const isFormValid = startUrl && title; useLayoutEffect(() => { @@ -135,22 +123,16 @@ function AddDocsDialog() {

Add documentation

- {docsByLanguage.map(({ language, packages }) => { + {/* {docsSuggestions.map((docsResult) => { + const { error, details } = docsResult; + const { language, name, version } = docsResult.packageInfo; return ( -
-

{language}

-
- {packages.map((pkg) => { - return ( -
-

{pkg.packageInfo.name}

-
- ); - })} -
+
+

{`${name}`}

+

{error ? "error" : details.docsLink}

); - })} + })} */}

Continue pre-indexes many common documentation sites, but if there's one you don't see in the dropdown, enter the URL here. diff --git a/gui/src/components/dialogs/SuggestedDocs.tsx b/gui/src/components/dialogs/SuggestedDocs.tsx new file mode 100644 index 000000000..1540ea92f --- /dev/null +++ b/gui/src/components/dialogs/SuggestedDocs.tsx @@ -0,0 +1,18 @@ +import { PackageDocsResult } from "core"; + +interface SuggestedDocProps { + docResult: PackageDocsResult; +} +const SuggestedDoc = ({ docResult }: SuggestedDocProps) => { + return

SuggestedDoc
; +}; + +interface SuggestedDocsListProps { + docs: PackageDocsResult[]; + // on +} +const SuggestedDocsList = ({ docs }: SuggestedDocsListProps) => { + return
; +}; + +export default SuggestedDocsList; diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index e965455c4..2feaf8065 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -5,7 +5,7 @@ import { ChatMessage, Checkpoint, ContextItemWithId, - DocsSuggestions, + PackageDocsResult, FileSymbolMap, IndexingStatus, PersistedSessionInfo, @@ -48,7 +48,7 @@ type State = { }; streamAborter: AbortController; isMultifileEdit: boolean; - docsSuggestions: DocsSuggestions; + docsSuggestions: PackageDocsResult[]; }; const initialState: State = { @@ -91,7 +91,7 @@ const initialState: State = { }, }, streamAborter: new AbortController(), - docsSuggestions: {}, + docsSuggestions: [], }; export const stateSlice = createSlice({ @@ -452,9 +452,8 @@ export const stateSlice = createSlice({ }, updateDocsSuggestions: ( state, - { payload }: PayloadAction, + { payload }: PayloadAction, ) => { - console.log("FROM REDUX", payload); state.docsSuggestions = payload; }, }, From 48806f3f0831de8cf67546ef77467548187641cc Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 21 Nov 2024 18:07:37 -0800 Subject: [PATCH 050/747] docs suggestions p4 --- core/core.ts | 8 +- core/index.d.ts | 7 +- core/indexing/docs/suggestions/index.ts | 36 ++-- .../suggestions/packageCrawlers/Python.ts | 9 +- .../docs/suggestions/packageCrawlers/TsJs.ts | 27 ++- gui/src/components/dialogs/AddDocsDialog.tsx | 186 ++++++++++++------ gui/src/components/index.ts | 10 + .../components/indexing/IndexingStatuses.tsx | 27 ++- gui/tailwind.config.cjs | 11 +- 9 files changed, 199 insertions(+), 122 deletions(-) diff --git a/core/core.ts b/core/core.ts index d81df8a37..b2be3478c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -19,6 +19,7 @@ import { ControlPlaneClient } from "./control-plane/client"; import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; +import { getAllSuggestedDocs } from "./indexing/docs/suggestions"; import { defaultIgnoreFile } from "./indexing/ignore.js"; import Ollama from "./llm/llms/Ollama"; import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; @@ -28,11 +29,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"; @@ -40,7 +37,6 @@ import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./util/messenger"; -import { getAllSuggestedDocs } from "./indexing/docs/suggestions"; export class Core { // implements IMessenger diff --git a/core/index.d.ts b/core/index.d.ts index 328462e70..5541584eb 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1198,15 +1198,14 @@ export interface FilePathAndName { } export interface PackageFilePathAndName extends FilePathAndName { - language: string; // e.g. javascript - registry: string; // e.g. npm + packageRegistry: string; // e.g. npm, pypi } export type ParsedPackageInfo = { - language: string; name: string; + packageFile: PackageFilePathAndName; + language: string; version: string; - packageFile: FilePathAndName; }; export type PackageDetails = { diff --git a/core/indexing/docs/suggestions/index.ts b/core/indexing/docs/suggestions/index.ts index 0f86f5390..4e0c2104a 100644 --- a/core/indexing/docs/suggestions/index.ts +++ b/core/indexing/docs/suggestions/index.ts @@ -9,12 +9,12 @@ import { import { walkDir } from "../../walkDir"; import { PythonPackageCrawler } from "./packageCrawlers/Python"; -import { TypeScriptPackageCrawler } from "./packageCrawlers/TsJs"; +import { NodePackageCrawler } from "./packageCrawlers/TsJs"; -const PACKAGE_CRAWLERS = [TypeScriptPackageCrawler, PythonPackageCrawler]; +const PACKAGE_CRAWLERS = [NodePackageCrawler, PythonPackageCrawler]; export interface PackageCrawler { - language: string; + packageRegistry: string; getPackageFiles(files: FilePathAndName[]): PackageFilePathAndName[]; parsePackageFile( file: PackageFilePathAndName, @@ -37,17 +37,17 @@ export async function getAllSuggestedDocs(ide: IDE) { })); // Build map of language -> package files - const packageFilesByLanguage: Record = {}; + const packageFilesByRegistry: Record = {}; for (const Crawler of PACKAGE_CRAWLERS) { const crawler = new Crawler(); const packageFilePaths = crawler.getPackageFiles(allFiles); - packageFilesByLanguage[crawler.language] = packageFilePaths; + packageFilesByRegistry[crawler.packageRegistry] = packageFilePaths; } // Get file contents for all unique package files const uniqueFilePaths = Array.from( new Set( - Object.values(packageFilesByLanguage).flatMap((files) => + Object.values(packageFilesByRegistry).flatMap((files) => files.map((file) => file.path), ), ), @@ -63,20 +63,20 @@ export async function getAllSuggestedDocs(ide: IDE) { ); // Parse package files and build map of language -> packages - const packagesByLanguage: Record = {}; + const packagesByRegistry: Record = {}; PACKAGE_CRAWLERS.forEach((Crawler) => { const crawler = new Crawler(); - const packageFiles = packageFilesByLanguage[crawler.language]; + const packageFiles = packageFilesByRegistry[crawler.packageRegistry]; packageFiles.forEach((file) => { const contents = fileContents.get(file.path); if (!contents) { return; } const packages = crawler.parsePackageFile(file, contents); - if (!packagesByLanguage[crawler.language]) { - packagesByLanguage[crawler.language] = []; + if (!packagesByRegistry[crawler.packageRegistry]) { + packagesByRegistry[crawler.packageRegistry] = []; } - packagesByLanguage[crawler.language].push(...packages); + packagesByRegistry[crawler.packageRegistry].push(...packages); }); }); @@ -84,13 +84,13 @@ export async function getAllSuggestedDocs(ide: IDE) { // TODO - this is where you would allow docs for different versions // by e.g. using "name-version" as the map key instead of just name // For now have not allowed - const languages = Object.keys(packagesByLanguage); + const languages = Object.keys(packagesByRegistry); languages.forEach((language) => { - const packages = packagesByLanguage[language]; + const packages = packagesByRegistry[language]; const uniquePackages = Array.from( new Map(packages.map((pkg) => [pkg.name, pkg])).values(), ); - packagesByLanguage[language] = uniquePackages; + packagesByRegistry[language] = uniquePackages; }); // Get documentation links for all packages @@ -98,8 +98,8 @@ export async function getAllSuggestedDocs(ide: IDE) { await Promise.all( PACKAGE_CRAWLERS.map(async (Crawler) => { const crawler = new Crawler(); - const packages = packagesByLanguage[crawler.language]; - const docsByLanguage = await Promise.all( + const packages = packagesByRegistry[crawler.packageRegistry]; + const docsByRegistry = await Promise.all( packages.map(async (packageInfo) => { try { const details = await crawler.getPackageDetails(packageInfo); @@ -119,12 +119,12 @@ export async function getAllSuggestedDocs(ide: IDE) { } catch (error) { return { packageInfo, - error: `Error getting package details for ${name}`, + error: `Error getting package details for ${packageInfo.name}`, }; } }), ); - allDocsResults.push(...docsByLanguage); + allDocsResults.push(...docsByRegistry); }), ); return allDocsResults; diff --git a/core/indexing/docs/suggestions/packageCrawlers/Python.ts b/core/indexing/docs/suggestions/packageCrawlers/Python.ts index 28b893b66..d00045f97 100644 --- a/core/indexing/docs/suggestions/packageCrawlers/Python.ts +++ b/core/indexing/docs/suggestions/packageCrawlers/Python.ts @@ -7,7 +7,7 @@ import { } from "../../../.."; export class PythonPackageCrawler implements PackageCrawler { - language = "python"; + packageRegistry = "pypi"; getPackageFiles(files: FilePathAndName[]): PackageFilePathAndName[] { // For Python, we typically look for files like requirements.txt or Pipfile @@ -17,13 +17,12 @@ export class PythonPackageCrawler implements PackageCrawler { ) .map((file) => ({ ...file, - language: this.language, - registry: "pypi", + packageRegistry: "pypi", })); } parsePackageFile( - file: FilePathAndName, + file: PackageFilePathAndName, contents: string, ): ParsedPackageInfo[] { // Assume the fileContent is a string from a requirements.txt formatted file @@ -31,7 +30,7 @@ export class PythonPackageCrawler implements PackageCrawler { .split("\n") .map((line) => { const [name, version] = line.split("=="); - return { name, version, packageFile: file, language: this.language }; + return { name, version, packageFile: file, language: "python" }; }) .filter((pkg) => pkg.name && pkg.version); } diff --git a/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts b/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts index c16b8872e..42c500748 100644 --- a/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts +++ b/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts @@ -6,8 +6,8 @@ import { ParsedPackageInfo, } from "../../../.."; -export class TypeScriptPackageCrawler implements PackageCrawler { - language = "js-ts"; +export class NodePackageCrawler implements PackageCrawler { + packageRegistry = "npm"; getPackageFiles(files: FilePathAndName[]): PackageFilePathAndName[] { // For Javascript/TypeScript, we look for package.json file @@ -15,13 +15,12 @@ export class TypeScriptPackageCrawler implements PackageCrawler { .filter((file) => file.name === "package.json") .map((file) => ({ ...file, - language: this.language, - registry: "npm", + packageRegistry: this.packageRegistry, })); } parsePackageFile( - file: FilePathAndName, + file: PackageFilePathAndName, contents: string, ): ParsedPackageInfo[] { // Parse the package.json content @@ -29,14 +28,24 @@ export class TypeScriptPackageCrawler implements PackageCrawler { const dependencies = Object.entries(jsonData.dependencies || {}).concat( Object.entries(jsonData.devDependencies || {}), ); - const filtered = dependencies.filter( - ([name, version]) => !name.startsWith("@types/"), - ); + + // Filter out types packages and check if typescript is present + let foundTypes = false; + const filtered = dependencies.filter(([name, _]) => { + if (name.startsWith("@types/")) { + foundTypes = true; + return false; + } + if (name.includes("typescript")) { + foundTypes = true; + } + return true; + }); return filtered.map(([name, version]) => ({ name, version, packageFile: file, - language: this.language, + language: foundTypes ? "ts" : "js", })); } diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 7dcc478fc..ca6a8bceb 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -2,8 +2,11 @@ import { CheckCircleIcon, ChevronDownIcon, ChevronUpIcon, + CodeBracketIcon, + InformationCircleIcon, + LinkIcon, } from "@heroicons/react/24/outline"; -import { SiteIndexingConfig } from "core"; +import { PackageDocsResult, SiteIndexingConfig } from "core"; import { usePostHog } from "posthog-js/react"; import { useContext, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; @@ -16,6 +19,8 @@ import { import { RootState } from "../../redux/store"; import IndexingStatusViewer from "../indexing/IndexingStatus"; +import { ToolTip } from "../gui/Tooltip"; + function AddDocsDialog() { const posthog = usePostHog(); const dispatch = useDispatch(); @@ -67,72 +72,125 @@ function AddDocsDialog() { posthog.capture("add_docs_gui", { url: startUrl }); } - if (submittedConfig) { - const status = indexingStatuses[submittedConfig.startUrl]; - return ( -
-
- -

{`Docs added`}

-
-
-

Title: {submittedConfig.title}

-

Start URL: {submittedConfig.startUrl}

- {submittedConfig.rootUrl && ( -

Root URL: {submittedConfig.rootUrl}

- )} - {submittedConfig.maxDepth && ( -

Max depth: {submittedConfig.maxDepth}

- )} - {submittedConfig.faviconUrl && ( -

Favicon URL: {submittedConfig.faviconUrl}

- )} -
- {!!status && ( -
-

{`Type "@docs" and select ${submittedConfig.title} to reference these docs once indexing is complete. Check indexing status from the "More" page.`}

-
- -
-
- )} -
- { - setSubmittedConfig(undefined); - }} - > - Add another - - -
-
- ); - } + const handleSelectSuggestion = (docsResult: PackageDocsResult) => {}; + + // if (submittedConfig) { + // const status = indexingStatuses[submittedConfig.startUrl]; + // return ( + //
+ //
+ // + //

{`Docs added`}

+ //
+ //
+ //

Title: {submittedConfig.title}

+ //

Start URL: {submittedConfig.startUrl}

+ // {submittedConfig.rootUrl && ( + //

Root URL: {submittedConfig.rootUrl}

+ // )} + // {submittedConfig.maxDepth && ( + //

Max depth: {submittedConfig.maxDepth}

+ // )} + // {submittedConfig.faviconUrl && ( + //

Favicon URL: {submittedConfig.faviconUrl}

+ // )} + //
+ // {!!status && ( + //
+ //

{`Type "@docs" and select ${submittedConfig.title} to reference these docs once indexing is complete. Check indexing status from the "More" page.`}

+ //
+ // + //
+ //
+ // )} + //
+ // { + // setSubmittedConfig(undefined); + // }} + // > + // Add another + // + // + //
+ //
+ // ); + // } return (

Add documentation

- {/* {docsSuggestions.map((docsResult) => { - const { error, details } = docsResult; - const { language, name, version } = docsResult.packageInfo; - return ( -
-

{`${name}`}

-

{error ? "error" : details.docsLink}

-
- ); - })} */} + {docsSuggestions.length ? ( +
+ + + + + + {/* */} + + + + + + Add docs + {docsSuggestions.map((docsResult) => { + const { error, details } = docsResult; + const { language, name, version } = docsResult.packageInfo; + const id = `${language}-${name}-${version}`; + return ( + + + + {/* */} + + + + ); + })} + +
+ + TitleVersionStart Link
+ + {name}{version} + {error ? ( + + No docs link found + + ) : ( + +
+ +
+

+ {details.docsLink} +

+
+ )} +
+ + + +

{`Version: ${version}`}

+

{`Found in ${docsResult.packageInfo.packageFile.path}`}

+
+
+
+ ) : null}

Continue pre-indexes many common documentation sites, but if there's one you don't see in the dropdown, enter the URL here. @@ -143,7 +201,7 @@ function AddDocsDialog() { so that you can ask questions.

- + {/*
- + */}
); } diff --git a/gui/src/components/index.ts b/gui/src/components/index.ts index e380f3ef6..74f27a44a 100644 --- a/gui/src/components/index.ts +++ b/gui/src/components/index.ts @@ -4,6 +4,10 @@ import { getFontSize, isJetBrains } from "../util"; export const VSC_INPUT_BACKGROUND_VAR = "--vscode-input-background"; export const VSC_BACKGROUND_VAR = "--vscode-sideBar-background"; export const VSC_FOREGROUND_VAR = "--vscode-editor-foreground"; +export const VSC_FOREGROUND_MUTED_VAR = "--vscode-foreground-muted"; +export const VSC_DESCRIPTION_FOREGROUND = "--vscode-descriptionForeground"; +export const VSC_INPUT_PLACEHOLDER_FOREGROUND = + "--vscode-input-placeholderForeground"; export const VSC_BUTTON_BACKGROUND_VAR = "--vscode-button-background"; export const VSC_BUTTON_FOREGROUND_VAR = "--vscode-button-foreground"; export const VSC_EDITOR_BACKGROUND_VAR = "--vscode-editor-background"; @@ -27,6 +31,9 @@ export const VSC_THEME_COLOR_VARS = [ VSC_INPUT_BACKGROUND_VAR, VSC_BACKGROUND_VAR, VSC_FOREGROUND_VAR, + VSC_FOREGROUND_MUTED_VAR, + VSC_DESCRIPTION_FOREGROUND, + VSC_INPUT_PLACEHOLDER_FOREGROUND, VSC_BUTTON_BACKGROUND_VAR, VSC_BUTTON_FOREGROUND_VAR, VSC_EDITOR_BACKGROUND_VAR, @@ -51,6 +58,9 @@ export const vscInputBackground = `var(${VSC_INPUT_BACKGROUND_VAR}, rgb(45 45 45 export const vscQuickInputBackground = `var(${VSC_QUICK_INPUT_BACKGROUND_VAR}, ${VSC_INPUT_BACKGROUND_VAR}, rgb(45 45 45))`; export const vscBackground = `var(${VSC_BACKGROUND_VAR}, rgb(30 30 30))`; export const vscForeground = `var(${VSC_FOREGROUND_VAR}, #fff)`; +export const vscForegroundMuted = `var(${VSC_FOREGROUND_MUTED_VAR}, #999)`; +export const vscDescriptionForeground = `var(${VSC_DESCRIPTION_FOREGROUND}, #999)`; +export const vscInputPlaceholderForeground = `var(${VSC_INPUT_PLACEHOLDER_FOREGROUND}, #999)`; export const vscButtonBackground = `var(${VSC_BUTTON_BACKGROUND_VAR}, #1bbe84)`; export const vscButtonForeground = `var(${VSC_BUTTON_FOREGROUND_VAR}, #ffffff)`; export const vscEditorBackground = `var(${VSC_EDITOR_BACKGROUND_VAR}, ${VSC_BACKGROUND_VAR}, rgb(30 30 30))`; diff --git a/gui/src/components/indexing/IndexingStatuses.tsx b/gui/src/components/indexing/IndexingStatuses.tsx index 7441212f9..61bf102a9 100644 --- a/gui/src/components/indexing/IndexingStatuses.tsx +++ b/gui/src/components/indexing/IndexingStatuses.tsx @@ -34,20 +34,19 @@ function IndexingStatuses() { Manage your documentation sources {/*
*/} - {docsStatuses.length ? ( - docsStatuses.map((status) => { - return ; - }) - ) : ( - { - dispatch(setShowDialog(true)); - dispatch(setDialogMessage()); - }} - > - Add Docs - - )} + {docsStatuses.length + ? docsStatuses.map((status) => { + return ; + }) + : null} + { + dispatch(setShowDialog(true)); + dispatch(setDialogMessage()); + }} + > + Add Docs +
//
); diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index f021c748b..3b3642d6b 100644 --- a/gui/tailwind.config.cjs +++ b/gui/tailwind.config.cjs @@ -46,8 +46,15 @@ module.exports = { "vsc-badge-background": "var(--vscode-badge-background, #1bbe84)", "vsc-badge-foreground": "var(--vscode-badge-foreground, #fff)", "vsc-sidebar-border": "var(--vscode-sideBar-border, transparent)", - "vsc-find-match": "var(--vscode-editor-findMatchBackground, rgba(255, 255, 0, 0.6))", - "vsc-find-match-selected": "var(--vscode-editor-findMatchHighlightBackground, rgba(255, 223, 0, 0.8))", + "vsc-find-match": + "var(--vscode-editor-findMatchBackground, rgba(255, 255, 0, 0.6))", + "vsc-find-match-selected": + "var(--vscode-editor-findMatchHighlightBackground, rgba(255, 223, 0, 0.8))", + "vsc-foreground-muted": "var(--vscode-foreground-muted, #999)", + "vsc-description-foreground": + "var(--vscode-descriptionForeground, #999)", + "vsc-input-placeholder-foreground": + "var(--vscode-input-placeholderForeground, #999)", }, }, }, From ee7bea7c19e3f52a50a8c9a0d26f242757dfd8a5 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 21 Nov 2024 18:31:50 -0800 Subject: [PATCH 051/747] 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 8e56613cf779e4a258596ad0e6ce6633b9c0f64a Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 21 Nov 2024 17:03:55 -0800 Subject: [PATCH 052/747] improv: generating context (snippets) string --- core/autocomplete/CompletionProvider.ts | 25 ++-- core/autocomplete/snippets/getAllSnippets.ts | 20 ++-- core/autocomplete/templating/filtering.ts | 45 +++++++ core/autocomplete/templating/formatting.ts | 100 ++++++++++++++++ core/autocomplete/templating/index.ts | 120 ++----------------- core/autocomplete/templating/validation.ts | 29 +++++ 6 files changed, 209 insertions(+), 130 deletions(-) create mode 100644 core/autocomplete/templating/filtering.ts create mode 100644 core/autocomplete/templating/formatting.ts create mode 100644 core/autocomplete/templating/validation.ts diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index c41bbb389..fe9ec02e6 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -12,7 +12,7 @@ import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { postprocessCompletion } from "./postprocessing/index.js"; import { shouldPrefilter } from "./prefiltering/index.js"; -import { getAllSnippets, TEMP__Snippets } from "./snippets/index.js"; +import { getAllSnippets } from "./snippets/index.js"; import { renderPrompt } from "./templating/index.js"; import { GetLspDefinitionsFunction } from "./types.js"; import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; @@ -162,19 +162,22 @@ export class CompletionProvider { token = controller.signal; } - const [{ snippets, diff, clipboardContent }, workspaceDirs] = - await Promise.all([ - getAllSnippets({ - helper, - ide: this.ide, - getDefinitionsFromLsp: this.getDefinitionsFromLsp, - contextRetrievalService: this.contextRetrievalService, - }), - this.ide.getWorkspaceDirs(), - ]); + const [ + { snippets, diff, clipboardContent, payload: snippetPayload }, + workspaceDirs, + ] = await Promise.all([ + getAllSnippets({ + helper, + ide: this.ide, + getDefinitionsFromLsp: this.getDefinitionsFromLsp, + contextRetrievalService: this.contextRetrievalService, + }), + this.ide.getWorkspaceDirs(), + ]); const { prompt, prefix, suffix, completionOptions } = renderPrompt({ snippets, + snippetPayload, diff, clipboardContent, workspaceDirs, diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index 6f6c79ba3..cda4874a1 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -57,6 +57,15 @@ function getSnippetsFromRecentlyEditedRanges( }); } +export interface SnippetPayload { + rootPathSnippets: AutocompleteCodeSnippet[]; + importDefinitionSnippets: AutocompleteCodeSnippet[]; + ideSnippets: AutocompleteCodeSnippet[]; + recentlyEditedRangeSnippets: AutocompleteCodeSnippet[]; + diffSnippets: AutocompleteDiffSnippet[]; + clipboardSnippets: AutocompleteClipboardSnippet[]; +} + export type TEMP__Snippets = { snippets: AutocompleteCodeSnippet[]; diff: string | undefined; @@ -64,14 +73,7 @@ export type TEMP__Snippets = { text: string; copiedAt: string; }; - new: { - rootPathSnippets: AutocompleteCodeSnippet[]; - importDefinitionSnippets: AutocompleteCodeSnippet[]; - ideSnippets: AutocompleteCodeSnippet[]; - recentlyEditedRangeSnippets: AutocompleteCodeSnippet[]; - diffSnippets: AutocompleteDiffSnippet[]; - clipboardSnippets: AutocompleteClipboardSnippet[]; - }; + payload: SnippetPayload; }; export const getAllSnippets = async ({ @@ -111,7 +113,7 @@ export const getAllSnippets = async ({ ], diff, clipboardContent, - new: { + payload: { rootPathSnippets, importDefinitionSnippets, ideSnippets, diff --git a/core/autocomplete/templating/filtering.ts b/core/autocomplete/templating/filtering.ts new file mode 100644 index 000000000..c657a75f3 --- /dev/null +++ b/core/autocomplete/templating/filtering.ts @@ -0,0 +1,45 @@ +import { countTokens } from "../../llm/countTokens"; +import { SnippetPayload } from "../snippets"; +import { AutocompleteSnippet } from "../snippets/types"; +import { HelperVars } from "../util/HelperVars"; +import { isValidSnippet } from "./validation"; + +const getRemainingTokenCount = (helper: HelperVars): number => { + const tokenCount = countTokens(helper.prunedCaretWindow, helper.modelName); + + return helper.options.maxPromptTokens - tokenCount; +}; + +const TOKEN_BUFFER = 10; // We may need extra tokens for snippet description etc. + +export const getSnippets = ( + helper: HelperVars, + payload: SnippetPayload, +): AutocompleteSnippet[] => { + const snippets = [ + ...payload.diffSnippets, + ...payload.clipboardSnippets, + ...payload.rootPathSnippets, + ]; + + const finalSnippets = []; + + let remainingTokenCount = getRemainingTokenCount(helper); + + while (remainingTokenCount > 0 && snippets.length > 0) { + const snippet = snippets.shift(); + if (!snippet || !isValidSnippet(snippet)) { + continue; + } + + const snippetSize = + countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER; + + if (remainingTokenCount >= snippetSize) { + finalSnippets.push(snippet); + remainingTokenCount -= snippetSize; + } + } + + return finalSnippets; +}; diff --git a/core/autocomplete/templating/formatting.ts b/core/autocomplete/templating/formatting.ts new file mode 100644 index 000000000..904262d7a --- /dev/null +++ b/core/autocomplete/templating/formatting.ts @@ -0,0 +1,100 @@ +import { getBasename, getLastNPathParts } from "../../util"; +import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; +import { + AutocompleteClipboardSnippet, + AutocompleteCodeSnippet, + AutocompleteDiffSnippet, + AutocompleteSnippet, + AutocompleteSnippetType, +} from "../snippets/types"; +import { HelperVars } from "../util/HelperVars"; + +const getCommentMark = (helper: HelperVars) => { + return helper.lang.singleLineComment; +}; + +const addCommentMarks = (text: string, helper: HelperVars) => { + const lines = [ + ...text + .trim() + .split("\n") + .map((line) => `${getCommentMark(helper)} ${line}`), + ]; + return lines.join("\n"); +}; + +const formatClipboardSnippet = ( + snippet: AutocompleteClipboardSnippet, +): AutocompleteClipboardSnippet => { + return { + ...snippet, + content: `Recently copied by user:${snippet.content.includes("\n") ? "\n" : ""} ${snippet.content}`, + }; +}; + +const formatCodeSnippet = ( + snippet: AutocompleteCodeSnippet, +): AutocompleteCodeSnippet => { + return { + ...snippet, + content: `Path: ${getBasename(snippet.filepath)}\n${snippet.content}`, + }; +}; + +const formatDiffSnippet = ( + snippet: AutocompleteDiffSnippet, +): AutocompleteDiffSnippet => { + return snippet; +}; + +// TODO: Insert this somewhere +const getCurrentFilepathSnippet = (helper: HelperVars) => { + const currentFilePath = `\n\n${getLastNPathParts(helper.filepath, 2)}\n\n`; +}; + +const commentifySnippet = ( + helper: HelperVars, + snippet: AutocompleteSnippet, +): AutocompleteSnippet => { + return { + ...snippet, + content: addCommentMarks(snippet.content, helper), + }; +}; + +const SNIPPET_TYPES_TO_COMMENT = [ + AutocompleteSnippetType.Code, + AutocompleteSnippetType.Clipboard, +]; + +export const formatSnippets = ( + helper: HelperVars, + snippets: AutocompleteSnippet[], +): string => { + return snippets + .map((snippet) => { + switch (snippet.type) { + case AutocompleteSnippetType.Code: + return formatCodeSnippet(snippet); + case AutocompleteSnippetType.Diff: + return formatDiffSnippet(snippet); + case AutocompleteSnippetType.Clipboard: + return formatClipboardSnippet(snippet); + } + }) + .map((item) => { + if (SNIPPET_TYPES_TO_COMMENT.includes(item.type)) { + return commentifySnippet(helper, item); + } + + return item; + }) + .map((item) => { + if (SNIPPET_TYPES_TO_COMMENT.includes(item.type)) { + return item.content + `\n${getCommentMark}\n${getCommentMark}`; + } + + return item.content + "\n\n"; + }) + .join(""); +}; diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 2812130c5..364c9114c 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,7 +1,7 @@ import Handlebars from "handlebars"; import { CompletionOptions } from "../.."; -import { getBasename, getLastNPathParts } from "../../util"; +import { getBasename } from "../../util"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; import { HelperVars } from "../util/HelperVars"; @@ -10,56 +10,10 @@ import { getTemplateForModel, } from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; -import { countTokens } from "../../llm/countTokens"; -import { AutocompleteSnippetDeprecated } from "../types"; -import { - AutocompleteCodeSnippet, - AutocompleteSnippet, -} from "../snippets/types"; - -const addCommentMarks = (text: string, language: AutocompleteLanguageInfo) => { - const comment = language.singleLineComment; - const lines = [ - ...text - .trim() - .split("\n") - .map((line) => `${comment} ${line}`), - ]; - return lines.join("\n"); -}; - -export function formatExternalSnippet( - filepath: string, - snippet: string, - language: AutocompleteLanguageInfo, -) { - const filePathString = `Path: ${getBasename(filepath)}\n`; - return addCommentMarks(`${filePathString}${snippet}`, language); -} - -function getContextComments( - snippets: AutocompleteCodeSnippet[], - lang: AutocompleteLanguageInfo, - filepath: string, -) { - if (snippets.length === 0) { - return ""; - } - - const headerSnipper = `\n\n${lang.singleLineComment} Related code:\n`; - const fileNameSnippet = `\n\n${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n\n`; - - const formattedSnippets = - headerSnipper + - snippets - .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.content, lang), - ) - .join("\n") + - fileNameSnippet; - - return formattedSnippets; -} +import { AutocompleteCodeSnippet } from "../snippets/types"; +import { SnippetPayload } from "../snippets"; +import { formatSnippets } from "./formatting"; +import { getSnippets } from "./filtering"; function getTemplate(helper: HelperVars): AutocompleteTemplate { if (helper.options.template) { @@ -92,61 +46,14 @@ function renderStringTemplate( }); } -const formatDiff = (helper: HelperVars, diff?: string) => { - if (!diff) return ""; - - const tokenCount = countTokens(diff, helper.modelName); - - if (tokenCount > helper.maxDiffTokens) { - return ""; - } - - return `${diff}\n\n`; -}; - -const MAX_CLIPBOARD_AGE = 5 * 60 * 1000; - -const formatClipboardContent = ( - helper: HelperVars, - { text, copiedAt }: { text: string; copiedAt: string }, -) => { - const currDate = new Date(); - - const isTooOld = - currDate.getTime() - new Date(copiedAt).getTime() > MAX_CLIPBOARD_AGE; - - if (isTooOld) { - return ""; - } - - const tokenCount = countTokens(text, helper.modelName); - const isTooLong = tokenCount > helper.maxClipboardTokens; - - if (isTooLong) { - return ""; - } - - const isEmpty = text.trim() === ""; - if (isEmpty) { - return ""; - } - - return ( - addCommentMarks( - `Recently copied by user:${text.includes("\n") ? "\n" : ""} ${text}`, - helper.lang, - ) + "\n" - ); -}; - export function renderPrompt({ snippets, + snippetPayload, workspaceDirs, helper, - diff, - clipboardContent, }: { snippets: AutocompleteCodeSnippet[]; + snippetPayload: SnippetPayload; workspaceDirs: string[]; helper: HelperVars; diff?: string; @@ -180,17 +87,10 @@ export function renderPrompt({ snippets, ); } else { - const contextComments = getContextComments( - snippets, - helper.lang, - helper.filepath, - ); - const formattedDiff = formatDiff(helper, diff); - const formattedClipboard = formatClipboardContent(helper, clipboardContent); + const finalSnippets = getSnippets(helper, snippetPayload); + const formattedSnippets = formatSnippets(helper, finalSnippets); - prefix = [formattedClipboard, formattedDiff, contextComments, prefix].join( - "", - ); + prefix = [formattedSnippets, prefix].join("\n"); } const prompt = diff --git a/core/autocomplete/templating/validation.ts b/core/autocomplete/templating/validation.ts new file mode 100644 index 000000000..dad55dc5c --- /dev/null +++ b/core/autocomplete/templating/validation.ts @@ -0,0 +1,29 @@ +import { + AutocompleteClipboardSnippet, + AutocompleteSnippet, + AutocompleteSnippetType, +} from "../snippets/types"; + +const MAX_CLIPBOARD_AGE = 5 * 60 * 1000; + +const isValidClipboardSnippet = ( + snippet: AutocompleteClipboardSnippet, +): boolean => { + const currDate = new Date(); + + const isTooOld = + currDate.getTime() - new Date(snippet.copiedAt).getTime() > + MAX_CLIPBOARD_AGE; + + return !isTooOld; +}; + +export const isValidSnippet = (snippet: AutocompleteSnippet): boolean => { + if (snippet.content.trim() === "") return false; + + if (snippet.type === AutocompleteSnippetType.Clipboard) { + return isValidClipboardSnippet(snippet); + } + + return true; +}; From 0069b9488b92a2d61fd8ae3299a968599b6ece89 Mon Sep 17 00:00:00 2001 From: Anoyi <545544032@qq.com> Date: Fri, 22 Nov 2024 13:12:59 +0800 Subject: [PATCH 053/747] restore code --- 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 aefcc8896..d7d4a064f 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -297,7 +297,7 @@ class OpenAI extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - const endpoint = this.apiBase?.includes("completions") ? new URL(this.apiBase) : new URL("fim/completions", this.apiBase); + const endpoint = new URL("fim/completions", this.apiBase); const resp = await this.fetch(endpoint, { method: "POST", body: JSON.stringify({ @@ -336,4 +336,4 @@ class OpenAI extends BaseLLM { } } -export default OpenAI; +export default OpenAI; \ No newline at end of file From 785ca419e6704799ec227a111cd2ea51ffc56e9f Mon Sep 17 00:00:00 2001 From: Anoyi <545544032@qq.com> Date: Fri, 22 Nov 2024 13:15:24 +0800 Subject: [PATCH 054/747] add siliconflow pro model --- extensions/vscode/config_schema.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index eb070bd00..76ab32f87 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -1251,7 +1251,8 @@ "model": { "enum": [ "Qwen/Qwen2.5-Coder-32B-Instruct", - "Qwen/Qwen2.5-Coder-7B-Instruct" + "Qwen/Qwen2.5-Coder-7B-Instruct", + "Pro/Qwen/Qwen2.5-Coder-7B-Instruct" ] } } From f3ba421ca4da5a5baf27d2f51a81b11f6e469319 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 21 Nov 2024 22:03:32 -0800 Subject: [PATCH 055/747] 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 056/747] 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 057/747] 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 058/747] 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 55fdafaf0d65296bafad50e76c7da4be91a19783 Mon Sep 17 00:00:00 2001 From: Anoyi <545544032@qq.com> Date: Fri, 22 Nov 2024 17:13:53 +0800 Subject: [PATCH 059/747] add siliconflow to embedding provider list --- core/index.d.ts | 3 ++- .../embeddings/SiliconFlowEmbeddingsProvider.ts | 14 ++++++++++++++ core/indexing/embeddings/index.ts | 4 +++- extensions/vscode/config_schema.json | 5 +++-- 4 files changed, 22 insertions(+), 4 deletions(-) create mode 100644 core/indexing/embeddings/SiliconFlowEmbeddingsProvider.ts diff --git a/core/index.d.ts b/core/index.d.ts index d9f26d1b9..ec4c20233 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -916,7 +916,8 @@ export type EmbeddingsProviderName = | "mistral" | "nebius" | "vertexai" - | "watsonx"; + | "watsonx" + | "siliconflow"; export interface EmbedOptions { apiBase?: string; diff --git a/core/indexing/embeddings/SiliconFlowEmbeddingsProvider.ts b/core/indexing/embeddings/SiliconFlowEmbeddingsProvider.ts new file mode 100644 index 000000000..bc463b047 --- /dev/null +++ b/core/indexing/embeddings/SiliconFlowEmbeddingsProvider.ts @@ -0,0 +1,14 @@ +import { EmbeddingsProviderName, EmbedOptions } from "../.."; + +import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider"; + +class SiliconFlowEmbeddingsProvider extends OpenAIEmbeddingsProvider { + static providerName: EmbeddingsProviderName = "siliconflow"; + + static defaultOptions: Partial | undefined = { + apiBase: "https://api.siliconflow.cn/v1/", + model: "BAAI/bge-m3", + }; +} + +export default SiliconFlowEmbeddingsProvider; diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts index 90e450361..3e895a39e 100644 --- a/core/indexing/embeddings/index.ts +++ b/core/indexing/embeddings/index.ts @@ -15,6 +15,7 @@ import NvidiaEmbeddingsProvider from "./NvidiaEmbeddingsProvider.js"; import OllamaEmbeddingsProvider from "./OllamaEmbeddingsProvider.js"; import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js"; import SageMakerEmbeddingsProvider from "./SageMakerEmbeddingsProvider.js"; +import SiliconFlowEmbeddingsProvider from "./SiliconFlowEmbeddingsProvider.js"; import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider.js"; import VertexEmbeddingsProvider from "./VertexEmbeddingsProvider.js"; import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js"; @@ -45,5 +46,6 @@ export const allEmbeddingsProviders: Record< nebius: NebiusEmbeddingsProvider, vertexai: VertexEmbeddingsProvider, watsonx: WatsonxEmbeddingsProvider, - lmstudio: LMStudioEmbeddingsProvider + lmstudio: LMStudioEmbeddingsProvider, + siliconflow: SiliconFlowEmbeddingsProvider, }; diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 76ab32f87..dc791d577 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2523,7 +2523,8 @@ "deepinfra", "mistral", "watsonx", - "lmstudio" + "lmstudio", + "siliconflow" ] }, "model": { @@ -2571,7 +2572,7 @@ "if": { "properties": { "provider": { - "enum": ["cohere", "voyage", "nvidia", "gemini"] + "enum": ["cohere", "voyage", "nvidia", "gemini", "siliconflow"] } }, "required": ["provider"] From 504c0c3843e5388fcd661f9755be9b174e9ef334 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 22 Nov 2024 02:51:34 -0800 Subject: [PATCH 060/747] autodetect docs v1 --- core/config/ProfileLifecycleManager.ts | 2 - core/config/load.ts | 1 + core/core.ts | 6 + core/index.d.ts | 2 + core/indexing/docs/suggestions/index.ts | 39 +- .../suggestions/packageCrawlers/Python.ts | 2 +- core/protocol/core.ts | 1 - core/protocol/webview.ts | 4 +- gui/src/components/dialogs/AddDocsDialog.tsx | 479 ++++++++++-------- gui/src/components/dialogs/index.tsx | 2 +- .../components/indexing/ChatIndexingPeeks.tsx | 2 +- .../components/indexing/DocsIndexingPeeks.tsx | 76 +++ .../components/indexing/IndexingStatuses.tsx | 41 +- 13 files changed, 396 insertions(+), 261 deletions(-) create mode 100644 gui/src/components/indexing/DocsIndexingPeeks.tsx diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index 85116f213..8d44c8bac 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -1,5 +1,3 @@ -import { config } from "dotenv"; - import { BrowserSerializedContinueConfig, ContinueConfig, diff --git a/core/config/load.ts b/core/config/load.ts index b692b36bf..9911c840f 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -527,6 +527,7 @@ function finalToBrowserConfig( embeddingsProvider: final.embeddingsProvider?.id, ui: final.ui, experimental: final.experimental, + docs: final.docs, }; } diff --git a/core/core.ts b/core/core.ts index b2be3478c..331ffbe85 100644 --- a/core/core.ts +++ b/core/core.ts @@ -735,6 +735,10 @@ export class Core { return this.docsService.initStatuses(); }); on("docs/getSuggestedDocs", async (msg) => { + if (hasRequestedDocs) { + return; + } // TODO, remove, hack because of rerendering + hasRequestedDocs = true; const suggestedDocs = await getAllSuggestedDocs(this.ide); this.messenger.send("docs/suggestions", suggestedDocs); }); @@ -842,3 +846,5 @@ export class Core { // private } + +let hasRequestedDocs = false; diff --git a/core/index.d.ts b/core/index.d.ts index 5541584eb..35c072bdb 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1189,6 +1189,7 @@ export interface BrowserSerializedContinueConfig { reranker?: RerankerDescription; experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; + docs?: SiteIndexingConfig[]; } // DOCS SUGGESTIONS AND PACKAGE INFO @@ -1210,6 +1211,7 @@ export type ParsedPackageInfo = { export type PackageDetails = { docsLink?: string; + docsLinkWarning?: string; title?: string; description?: string; repo?: string; diff --git a/core/indexing/docs/suggestions/index.ts b/core/indexing/docs/suggestions/index.ts index 4e0c2104a..db192489a 100644 --- a/core/indexing/docs/suggestions/index.ts +++ b/core/indexing/docs/suggestions/index.ts @@ -63,9 +63,10 @@ export async function getAllSuggestedDocs(ide: IDE) { ); // Parse package files and build map of language -> packages - const packagesByRegistry: Record = {}; + const packagesByCrawler: Record = {}; PACKAGE_CRAWLERS.forEach((Crawler) => { const crawler = new Crawler(); + packagesByCrawler[crawler.packageRegistry] = []; const packageFiles = packageFilesByRegistry[crawler.packageRegistry]; packageFiles.forEach((file) => { const contents = fileContents.get(file.path); @@ -73,10 +74,7 @@ export async function getAllSuggestedDocs(ide: IDE) { return; } const packages = crawler.parsePackageFile(file, contents); - if (!packagesByRegistry[crawler.packageRegistry]) { - packagesByRegistry[crawler.packageRegistry] = []; - } - packagesByRegistry[crawler.packageRegistry].push(...packages); + packagesByCrawler[crawler.packageRegistry].push(...packages); }); }); @@ -84,13 +82,13 @@ export async function getAllSuggestedDocs(ide: IDE) { // TODO - this is where you would allow docs for different versions // by e.g. using "name-version" as the map key instead of just name // For now have not allowed - const languages = Object.keys(packagesByRegistry); - languages.forEach((language) => { - const packages = packagesByRegistry[language]; + const registries = Object.keys(packagesByCrawler); + registries.forEach((registry) => { + const packages = packagesByCrawler[registry]; const uniquePackages = Array.from( new Map(packages.map((pkg) => [pkg.name, pkg])).values(), ); - packagesByRegistry[language] = uniquePackages; + packagesByCrawler[registry] = uniquePackages; }); // Get documentation links for all packages @@ -98,7 +96,7 @@ export async function getAllSuggestedDocs(ide: IDE) { await Promise.all( PACKAGE_CRAWLERS.map(async (Crawler) => { const crawler = new Crawler(); - const packages = packagesByRegistry[crawler.packageRegistry]; + const packages = packagesByCrawler[crawler.packageRegistry]; const docsByRegistry = await Promise.all( packages.map(async (packageInfo) => { try { @@ -114,6 +112,11 @@ export async function getAllSuggestedDocs(ide: IDE) { details: { ...details, docsLink: details.docsLink, + docsLinkWarning: details.docsLink.includes("github.com") + ? "Github docs not supported, find the docs site" + : details.docsLink.includes("docs") + ? undefined + : "May not be a docs site, check the URL", }, }; } catch (error) { @@ -129,19 +132,3 @@ export async function getAllSuggestedDocs(ide: IDE) { ); return allDocsResults; } - -// write me an interface PackageCrawler that contains: -// 1. property `language` to store a given language like "python" or "typescript" -// 2. has a method `getPackageFiles` which takes a list of file names and decides which ones match package/dependency files (e.g. package.json for typescript, requirements.txt for python, etc) -// 3. has a method `parsePackageFile` which returns a list of package name and version from a relevant package file, in a standardized format like semver -// 4. has a method `getDocumentationLink` to check for documentation link for a given package (e.g. GET `https://registry.npmjs.org/` and find docs field for typescript, documentation link in the package metadata for PyPi, etc.) -// Then, write typescript classes to implement this typescript interface for the languages "python" and "typescript" - -// I want to present the user with a list of dependencies and allow them to select which ones to index (embed) documentation for. -// In order to prevent duplicate file reads, the process will be like this: -// 1. take in a list of filepaths called `filepaths` -// 2. loop an array of PackageCrawler classes to build a map of `language` (string) to `packageFilePaths` (string[]) -// 3. Get unique filepaths from `packageFilePaths` and build a map ` of filepath to file contents using an existing `readFile` function, and skipping file reads of already in the map -// Finally, -// Add a `` method to the interface and classes that returns -// Then, assemble the classes in an array, and write a function getAllSuggestedDocs that returns a map of `language` to an ar diff --git a/core/indexing/docs/suggestions/packageCrawlers/Python.ts b/core/indexing/docs/suggestions/packageCrawlers/Python.ts index d00045f97..6a486c984 100644 --- a/core/indexing/docs/suggestions/packageCrawlers/Python.ts +++ b/core/indexing/docs/suggestions/packageCrawlers/Python.ts @@ -30,7 +30,7 @@ export class PythonPackageCrawler implements PackageCrawler { .split("\n") .map((line) => { const [name, version] = line.split("=="); - return { name, version, packageFile: file, language: "python" }; + return { name, version, packageFile: file, language: "py" }; }) .filter((pkg) => pkg.name && pkg.version); } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 069f9e297..f5b04c9cf 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -9,7 +9,6 @@ import type { DiffLine, FileSymbolMap, IdeSettings, - IndexingStatusMap, LLMFullCompletionOptions, MessageContent, ModelDescription, diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index bf90497c8..fb6a8837c 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -2,9 +2,9 @@ import { ConfigValidationError } from "../config/validation.js"; import type { ContextItemWithId, - DocsSuggestions, IndexingProgressUpdate, IndexingStatus, + PackageDocsResult, } from "../index.js"; export type ToWebviewFromIdeOrCoreProtocol = { @@ -26,5 +26,5 @@ export type ToWebviewFromIdeOrCoreProtocol = { getWebviewHistoryLength: [undefined, number]; signInToControlPlane: [undefined, void]; openDialogMessage: ["account", void]; - "docs/suggestions": [DocsSuggestions, void]; + "docs/suggestions": [PackageDocsResult[], void]; }; diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index ca6a8bceb..0a90a60d2 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -1,12 +1,15 @@ import { CheckCircleIcon, + CheckIcon, ChevronDownIcon, ChevronUpIcon, CodeBracketIcon, + ExclamationTriangleIcon, InformationCircleIcon, LinkIcon, + PlusCircleIcon, } from "@heroicons/react/24/outline"; -import { PackageDocsResult, SiteIndexingConfig } from "core"; +import { IndexingStatus, PackageDocsResult, SiteIndexingConfig } from "core"; import { usePostHog } from "posthog-js/react"; import { useContext, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; @@ -20,39 +23,79 @@ import { RootState } from "../../redux/store"; import IndexingStatusViewer from "../indexing/IndexingStatus"; import { ToolTip } from "../gui/Tooltip"; +import FileIcon from "../FileIcon"; +import DocsIndexingPeeks from "../indexing/DocsIndexingPeeks"; +import { updateIndexingStatus } from "../../redux/slices/stateSlice"; +import preIndexedDocs from "core/indexing/docs/preIndexedDocs"; function AddDocsDialog() { const posthog = usePostHog(); const dispatch = useDispatch(); - const ref = useRef(null); + const titleRef = useRef(null); + const urlRef = useRef(null); const [title, setTitle] = useState(""); const [startUrl, setStartUrl] = useState(""); const [faviconUrl, setFaviconUrl] = useState(""); - const [isOpen, setIsOpen] = useState(false); - - const [submittedConfig, setSubmittedConfig] = useState(); const ideMessenger = useContext(IdeMessengerContext); const indexingStatuses = useSelector( (store: RootState) => store.state.indexing.statuses, ); + const docsIndexingStatuses: IndexingStatus[] = useMemo(() => { + return Object.values(indexingStatuses).filter( + (status) => status.type === "docs" && status.status === "indexing", + ); + }, [indexingStatuses]); + const docsSuggestions = useSelector( (store: RootState) => store.state.docsSuggestions, ); + const configDocs = useSelector((store: RootState) => store.state.config.docs); + + const sortedDocsSuggestions = useMemo(() => { + const docsFromConfig = configDocs ?? []; + const filtered = docsSuggestions.filter((sug) => { + const startUrl = sug.details?.docsLink; + return ( + !docsFromConfig.find((d) => d.startUrl === startUrl) && + !docsIndexingStatuses.find((s) => s.id === startUrl) && + (startUrl ? !preIndexedDocs[startUrl] : true) + ); + }); + + filtered.sort((a, b) => { + const rank = (result: PackageDocsResult) => { + if (result.error) { + return 2; + } else if (result.details?.docsLinkWarning) { + return 1; + } else { + return 0; + } + }; + return rank(a) - rank(b); + }); + return filtered; + }, [docsSuggestions, configDocs, docsIndexingStatuses]); + const isFormValid = startUrl && title; useLayoutEffect(() => { setTimeout(() => { - if (ref.current) { - ref.current.focus(); + if (titleRef.current) { + titleRef.current.focus(); } }, 100); - }, [ref]); + }, [titleRef]); + const closeDialog = () => { + dispatch(setShowDialog(false)); + dispatch(setDialogMessage(undefined)); + }; function onSubmit(e: any) { e.preventDefault(); @@ -64,220 +107,236 @@ function AddDocsDialog() { ideMessenger.post("context/addDocs", siteIndexingConfig); - setSubmittedConfig(siteIndexingConfig); setTitle(""); setStartUrl(""); setFaviconUrl(""); posthog.capture("add_docs_gui", { url: startUrl }); + + // Optimistic status update + dispatch( + updateIndexingStatus({ + type: "docs", + description: "Initializing", + id: startUrl, + embeddingsProviderId: "mock-embeddings-provider-id", + progress: 0, + status: "indexing", + title, + url: startUrl, + }), + ); } - const handleSelectSuggestion = (docsResult: PackageDocsResult) => {}; + const handleSelectSuggestion = (docsResult: PackageDocsResult) => { + if (docsResult.error) { + setTitle(docsResult.packageInfo.name); + setStartUrl(""); + urlRef.current?.focus(); + return; + } + if (docsResult.details?.docsLinkWarning) { + setTitle(docsResult.packageInfo.name); + setStartUrl(docsResult.details.docsLink); + urlRef.current?.focus(); + return; + } + const siteIndexingConfig: SiteIndexingConfig = { + startUrl: docsResult.details.docsLink, + title: docsResult.details.title, + faviconUrl: undefined, + }; - // if (submittedConfig) { - // const status = indexingStatuses[submittedConfig.startUrl]; - // return ( - //
- //
- // - //

{`Docs added`}

- //
- //
- //

Title: {submittedConfig.title}

- //

Start URL: {submittedConfig.startUrl}

- // {submittedConfig.rootUrl && ( - //

Root URL: {submittedConfig.rootUrl}

- // )} - // {submittedConfig.maxDepth && ( - //

Max depth: {submittedConfig.maxDepth}

- // )} - // {submittedConfig.faviconUrl && ( - //

Favicon URL: {submittedConfig.faviconUrl}

- // )} - //
- // {!!status && ( - //
- //

{`Type "@docs" and select ${submittedConfig.title} to reference these docs once indexing is complete. Check indexing status from the "More" page.`}

- //
- // - //
- //
- // )} - //
- // { - // setSubmittedConfig(undefined); - // }} - // > - // Add another - // - // - //
- //
- // ); - // } + ideMessenger.post("context/addDocs", siteIndexingConfig); + + posthog.capture("add_docs_gui", { url: startUrl }); + + // Optimistic status update + dispatch( + updateIndexingStatus({ + type: "docs", + description: "Initializing", + id: docsResult.details.docsLink, + embeddingsProviderId: "mock-embeddings-provider-id", + progress: 0, + status: "indexing", + title: docsResult.details.title ?? docsResult.packageInfo.name, + url: docsResult.details.docsLink, + }), + ); + }; return ( -
-
-

Add documentation

- {docsSuggestions.length ? ( -
- - - - - - {/* */} - - - - - - Add docs - {docsSuggestions.map((docsResult) => { - const { error, details } = docsResult; - const { language, name, version } = docsResult.packageInfo; - const id = `${language}-${name}-${version}`; - return ( - - - - {/* */} - - - - ); - })} - -
- - TitleVersionStart Link
- - {name}{version} - {error ? ( - - No docs link found - - ) : ( - -
- -
-

- {details.docsLink} -

-
- )} -
- - - -

{`Version: ${version}`}

-

{`Found in ${docsResult.packageInfo.packageFile.path}`}

-
-
-
- ) : null} -

- Continue pre-indexes many common documentation sites, but if there's - one you don't see in the dropdown, enter the URL here. -

- -

- Continue's indexing engine will crawl the site and generate embeddings - so that you can ask questions. -

-
- {/* -
- - - - -
setIsOpen((prev) => !prev)} - > - {isOpen ? ( - - ) : ( - - )} - Advanced -
- - {isOpen && ( -
- -
+
+
+

Add documentation

+

Add docs

+ {sortedDocsSuggestions.length && ( +

Suggestions

)} - -
- +
+ {sortedDocsSuggestions.map((docsResult) => { + const { error, details } = docsResult; + const { language, name, version } = docsResult.packageInfo; + const id = `${language}-${name}-${version}`; + return ( + <> +
{ + handleSelectSuggestion(docsResult); + }} + > +
+ {error ? ( +
+ + + Docs URL not found + +
+ ) : details.docsLinkWarning ? ( +
+ + + Start URL might not lead to docs + +
+ ) : ( + + )} +
+
+
+ +
+ {name} +
+
+ {error ? ( + + No docs link found + + ) : ( +
+ {/*
+ +
*/} +

+ {details.docsLink} +

+
+ )} +
+
+ + +

{`Version: ${version}`}

+

{`Found in ${docsResult.packageInfo.packageFile.path}`}

+
+
+
+ + {error ? "Add to form" : "Index these docs"} + + + ); + })}
- */} +
+
+
+ + + +
+
+ + Done + + +
+
+
+
+ + +
+
+ {docsIndexingStatuses.length ? ( +

+ It is safe to close this form while indexing +

+ ) : null} +
+
); } diff --git a/gui/src/components/dialogs/index.tsx b/gui/src/components/dialogs/index.tsx index 7685109ba..8a3a67fe8 100644 --- a/gui/src/components/dialogs/index.tsx +++ b/gui/src/components/dialogs/index.tsx @@ -71,7 +71,7 @@ const TextDialog = (props: TextDialogProps) => { return (