WIP on tools

This commit is contained in:
Nate 2024-11-15 09:43:40 -08:00
parent 6240180fda
commit e2bd9cc2b7
12 changed files with 160 additions and 25 deletions

View file

@ -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) {

View file

@ -83,7 +83,7 @@ export class Core {
constructor(
private readonly messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
private readonly ide: IDE,
private readonly onWrite: (text: string) => Promise<void> = async () => { },
private readonly onWrite: (text: string) => Promise<void> = 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) => {

24
core/index.d.ts vendored
View file

@ -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<string, any>;
strict?: boolean | null;
};
action: (parameters: any) => Promise<any>;
}
interface BaseCompletionOptions {
temperature?: number;
topP?: number;
@ -821,6 +842,7 @@ interface BaseCompletionOptions {
raw?: boolean;
stream?: boolean;
prediction?: Prediction;
tools?: Tool[];
}
export interface ModelCapability {

View file

@ -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,
},
}),
),
};
}
}
}

View file

@ -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<MessageContent>,
ProtocolGeneratorType<ChatMessage>,
];
streamDiffLines: [
{

26
core/tools/index.ts Normal file
View file

@ -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",
},
},
},
},
});

View file

@ -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",

View file

@ -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();
}

View file

@ -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();
}

View file

@ -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" ? (
<ContinueInputBox
onEnter={async (editorState, modifiers) => {
@ -341,6 +343,13 @@ export function Chat() {
editorState={item.editorState}
contextItems={item.contextItems}
/>
) : item.message.role === "assistant" &&
item.message.toolCalls ? (
<div>
{item.message.toolCalls?.map((toolCall) => {
return <ToolCallDiv toolCall={toolCall}></ToolCallDiv>;
})}
</div>
) : (
<div className="thread-message">
<TimelineItem

View file

@ -0,0 +1,8 @@
import { ToolCall } from "core";
interface ToolCallDivProps {
toolCall: ToolCall;
}
export function ToolCallDiv(props: ToolCallDivProps) {
return <div>{props.toolCall.function.name}...</div>;
}

View file

@ -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<string>) => {
streamUpdate: (state, action: PayloadAction<ChatMessage>) => {
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: (