From e2bd9cc2b7236a3959fa42baa73d303a9622c4b6 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 15 Nov 2024 09:43:40 -0800 Subject: [PATCH] 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: (