diff --git a/backend/src/claude.ts b/backend/src/claude.ts index b0048046fe..222e3f588c 100644 --- a/backend/src/claude.ts +++ b/backend/src/claude.ts @@ -26,7 +26,7 @@ export const promptClaudeStream = async function* ( userId: string ignoreHelicone?: boolean } -): AsyncGenerator { +): AsyncGenerator { const { model = models.sonnet, system, @@ -70,6 +70,7 @@ export const promptClaudeStream = async function* ( messages, system, tools, + stop_sequences: [], }) ) @@ -106,7 +107,8 @@ export const promptClaudeStream = async function* ( if (type === 'message_delta' && chunk.delta.stop_reason === 'tool_use') { const { name, id, json } = toolInfo const input = JSON.parse(json) - yield { name, id, input } + console.error('tried to yield tool call', name, id, input) + // yield { name, id, input } } // if (type === 'message_start') { // console.log('message start', chunk) diff --git a/backend/src/generate-knowledge-files.ts b/backend/src/generate-knowledge-files.ts index d7ac75c340..e8cfa9f283 100644 --- a/backend/src/generate-knowledge-files.ts +++ b/backend/src/generate-knowledge-files.ts @@ -4,7 +4,6 @@ import { parseFileBlocks, ProjectFileContext } from 'common/util/file' import { processFileBlock } from './main-prompt' import { promptClaude } from './claude' import { getProjectFileTreePrompt, getRelevantFilesPrompt, knowledgeFilesPrompt } from './system-prompt' -import { DEFAULT_TOOLS } from 'common/util/tools' import { debugLog } from './util/debug' import { env } from './env.mjs' @@ -43,7 +42,7 @@ export async function generateKnowledgeFiles( If the change isn't important enough to warrant a new knowledge file, please do not output anything. We don't want to waste the user's time on irrelevant changes. This is also meant to be helpful for future LLMs like yourself. Thus, please be concise and avoid unnecessary details. If the change is important, please provide a detailed description of what we're doing and why. - Do not include any code or other files in the knowledge file. Don't use any tools. Make the most minimal changes necessary to the files to ensure the information is captured. + Do not include any code or other files in the knowledge file. Make the most minimal changes necessary to the files to ensure the information is captured. @@ -98,7 +97,6 @@ export async function generateKnowledgeFiles( const response = await promptClaude(messages, { userId, system: systemPrompt, - tools: DEFAULT_TOOLS, }) const files = parseFileBlocks(response) diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index 46a380d3de..b8fd2470c6 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -1,11 +1,11 @@ import { WebSocket } from 'ws' import fs from 'fs' import path from 'path' -import { TextBlockParam, Tool } from '@anthropic-ai/sdk/resources' +import { TextBlockParam } from '@anthropic-ai/sdk/resources' import { promptClaudeStream } from './claude' import { createFileBlock, ProjectFileContext } from 'common/util/file' -import { didClientUseTool, DEFAULT_TOOLS } from 'common/util/tools' +import { didClientUseTool } from 'common/util/tools' import { getSearchSystemPrompt, getAgentSystemPrompt } from './system-prompt' import { STOP_MARKER } from 'common/constants' import { FileChange, Message } from 'common/actions' @@ -17,7 +17,7 @@ import { requestRelevantFiles, warmCacheForRequestRelevantFiles, } from './request-files-prompt' -import { processStreamWithFiles } from './process-stream' +import { processStreamWithTags } from './process-stream' import { generateKnowledgeFiles } from './generate-knowledge-files' /** @@ -40,7 +40,6 @@ export async function mainPrompt( let genKnowledgeFilesPromise: Promise[]> = Promise.resolve([]) const fileProcessingPromises: Promise[] = [] - const tools = DEFAULT_TOOLS const lastMessage = messages[messages.length - 1] const messagesWithoutLastMessage = messages.slice(0, -1) @@ -51,24 +50,23 @@ export async function mainPrompt( const responseChunk = await updateFileContext( ws, fileContext, - { messages, system, tools }, + { messages, system }, null, - onResponseChunk, userId ) if (responseChunk !== null) { - fullResponse += responseChunk + onResponseChunk(responseChunk.readFilesMessage) + fullResponse += `\n\n${responseChunk.toolCallMessage}\n\n${responseChunk.readFilesMessage}` // Prompt cache the new files. const system = getSearchSystemPrompt(fileContext) - warmCacheForRequestRelevantFiles(system, DEFAULT_TOOLS, userId) + warmCacheForRequestRelevantFiles(system, userId) } } if (messages.length > 1 && !didClientUseTool(lastMessage)) { // Already have context from existing chat // If client used tool, we don't want to generate knowledge files because the user isn't really in control - genKnowledgeFilesPromise = generateKnowledgeFiles( userId, ws, @@ -96,7 +94,9 @@ export async function mainPrompt( } let toolCall: ToolCall | null = null - let continuedMessages: Message[] = [] + let continuedMessages: Message[] = fullResponse + ? [{ role: 'assistant', content: fullResponse }] + : [] let isComplete = false let iterationCount = 0 const MAX_ITERATIONS = 10 @@ -125,71 +125,98 @@ ${STOP_MARKER} ? [...messagesWithoutLastMessage, newLastMessage, ...continuedMessages] : messages - savePromptLengthInfo(messagesWithContinuedMessage, system, tools) + savePromptLengthInfo(messagesWithContinuedMessage, system) const stream = promptClaudeStream(messagesWithContinuedMessage, { system, - tools, userId, }) - const fileStream = processStreamWithFiles( - stream, - (_filePath) => { - onResponseChunk('Modifying...') + const streamWithTags = processStreamWithTags(stream, { + file: { + attributeNames: ['path'], + onTagStart: () => { + onResponseChunk('Modifying...') + }, + onTagEnd: (fileContent, { path }) => { + console.log('on file!', path) + const filePathWithoutStartNewline = fileContent.startsWith('\n') + ? fileContent.slice(1) + : fileContent + fileProcessingPromises.push( + processFileBlock( + userId, + ws, + messages, + fullResponse, + path, + filePathWithoutStartNewline + ).catch((error) => { + console.error('Error processing file block', error) + return null + }) + ) + fullResponse += fileContent + return false + }, }, - (filePath, fileContent) => { - console.log('on file!', filePath) - fileProcessingPromises.push( - processFileBlock( - userId, - ws, - messages, - fullResponse, - filePath, - fileContent - ).catch((error) => { - console.error('Error processing file block', error) - return null - }) - ) - fullResponse += fileContent - } - ) - - for await (const chunk of fileStream) { - if (typeof chunk === 'object') { - toolCall = chunk - debugLog('Received tool call:', toolCall) - continue - } + tool_call: { + attributeNames: ['name'], + onTagStart: (attributes) => {}, + onTagEnd: (content, attributes) => { + console.log('tool call', { ...attributes, content }) + const name = attributes.name + const contentAttributes: Record = {} + if (name === 'run_terminal_command') { + contentAttributes.command = content + } else if (name === 'scrape_web_page') { + contentAttributes.url = content + } + const responseChunk = `${content}` + onResponseChunk(responseChunk) + fullResponse += responseChunk + toolCall = { + id: Math.random().toString(36).slice(2), + name: attributes.name, + input: contentAttributes, + } + isComplete = true + return true + }, + }, + }) + for await (const chunk of streamWithTags) { fullResponse += chunk onResponseChunk(chunk) } - if (fullResponse.includes(STOP_MARKER)) { + const maybeToolCall = toolCall as ToolCall | null + + if (maybeToolCall?.name === 'find_files') { + const response = await updateFileContext( + ws, + fileContext, + { messages, system: getSearchSystemPrompt(fileContext) }, + fullResponse, + userId + ) + if (response !== null) { + const { readFilesMessage } = response + onResponseChunk(`\n\n${readFilesMessage}`) + fullResponse += `\n\n${readFilesMessage}` + } + toolCall = null + isComplete = false + continuedMessages = [ + { + role: 'assistant', + content: fullResponse.trim(), + }, + ] + } else if (fullResponse.includes(STOP_MARKER)) { isComplete = true fullResponse = fullResponse.replace(STOP_MARKER, '') debugLog('Reached STOP_MARKER') - } else if (toolCall) { - if (toolCall.name === 'update_file_context') { - const relevantFiles = await requestRelevantFiles( - { - messages, - system: getSearchSystemPrompt(fileContext), - tools, - }, - fileContext, - toolCall.input['prompt'], - userId - ) - if (relevantFiles !== null && relevantFiles.length > 0) { - const responseChunk = '\n' + getRelevantFileInfoMessage(relevantFiles) - onResponseChunk(responseChunk) - fullResponse += responseChunk - } - } - isComplete = true } else { console.log('continuing to generate') debugLog('continuing to generate') @@ -214,6 +241,7 @@ ${STOP_MARKER} console.log('Reached maximum number of iterations in mainPrompt') debugLog('Reached maximum number of iterations in mainPrompt') } + const knowledgeChanges = await genKnowledgeFilesPromise fileProcessingPromises.push(...knowledgeChanges) const changes = (await Promise.all(fileProcessingPromises)).filter( @@ -231,15 +259,14 @@ ${STOP_MARKER} return { response: responseWithChanges, changes, - toolCall, + toolCall: toolCall as ToolCall | null, } } function getRelevantFileInfoMessage(filePaths: string[]) { - if (filePaths.length === 0) { - return '' - } - return `Reading the following files...${filePaths.join(', ')}\n\n` + const readFilesMessage = `Reading the following files...${filePaths.join(', ')}` + const toolCallMessage = `Please find the files relevant to the user request` + return { readFilesMessage, toolCallMessage } } async function updateFileContext( @@ -248,18 +275,15 @@ async function updateFileContext( { messages, system, - tools, }: { messages: Message[] system: string | Array - tools: Tool[] }, prompt: string | null, - onResponseChunk: (chunk: string) => void, userId: string ) { const relevantFiles = await requestRelevantFiles( - { messages, system, tools }, + { messages, system }, fileContext, prompt, userId @@ -269,13 +293,21 @@ async function updateFileContext( return null } - const responseChunk = getRelevantFileInfoMessage(relevantFiles) - onResponseChunk(responseChunk) - // Load relevant files into fileContext fileContext.files = await requestFiles(ws, relevantFiles) - return responseChunk + const existingFiles = Object.keys(fileContext.files).filter( + (filePath) => fileContext.files[filePath] !== null + ) + + if (existingFiles.length === 0) { + return null + } + + const { readFilesMessage, toolCallMessage } = + getRelevantFileInfoMessage(existingFiles) + + return { readFilesMessage, toolCallMessage } } export async function processFileBlock( @@ -323,8 +355,7 @@ export async function processFileBlock( const savePromptLengthInfo = ( messages: Message[], - system: string | Array, - tools: Tool[] + system: string | Array ) => { console.log('Prompting claude num messages:', messages.length) debugLog('Prompting claude num messages:', messages.length) @@ -337,7 +368,6 @@ const savePromptLengthInfo = ( typeof lastMessageContent === 'string' ? lastMessageContent : '[object]', messages: JSON.stringify(messages).length, system: system.length, - tools: JSON.stringify(tools).length, timestamp: new Date().toISOString(), // Add a timestamp for each entry } diff --git a/backend/src/process-stream.ts b/backend/src/process-stream.ts index fcb1fb5fa4..3959f93950 100644 --- a/backend/src/process-stream.ts +++ b/backend/src/process-stream.ts @@ -1,54 +1,75 @@ -const fileOpenRegex = //g -const fileCloseRegex = /<\/file>/g - -export async function* processStreamWithFiles( +export async function* processStreamWithTags( stream: AsyncGenerator, - onFileStart: (filePath: string) => void, - onFile: (filePath: string, fileContent: string) => void + tags: { + [tagName: string]: { + attributeNames: string[] + onTagStart: (attributes: Record) => void + onTagEnd: (content: string, attributes: Record) => boolean + } + } ) { let buffer = '' - let insideTag = 'none' - let currentFilePath = '' + let insideTag: string | null = null + let currentAttributes: Record = {} + + const escapeRegExp = (string: string) => + string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + const tagNames = Object.keys(tags) + const openTagRegex = new RegExp( + `<(${tagNames.map(escapeRegExp).join('|')})\\s*([^>]*)>`, + 'g' + ) + const closeTagRegex = new RegExp( + ``, + 'g' + ) for await (const chunk of stream) { - if (typeof chunk === 'object') { - yield chunk - continue - } + let currentChunk: string = chunk buffer += chunk while (true) { - if (insideTag === 'none') { - const openMatch = fileOpenRegex.exec(buffer) - if (openMatch) { - const afterOpenIndex = openMatch.index + openMatch[0].length - const chunkStartIndex = buffer.length - chunk.length - yield buffer.slice(chunkStartIndex, afterOpenIndex) - buffer = buffer.slice(afterOpenIndex) - currentFilePath = openMatch[1] - onFileStart(currentFilePath) - insideTag = 'file' + if (insideTag === null) { + const match = openTagRegex.exec(buffer) + if (match) { + const [fullMatch, openTag, attributesString] = match + + const afterMatchIndex = match.index + fullMatch.length + const chunkStartIndex = buffer.length - currentChunk.length + yield buffer.slice(chunkStartIndex, afterMatchIndex) + + buffer = buffer.slice(afterMatchIndex) + + insideTag = openTag + currentAttributes = parseAttributes( + attributesString, + tags[openTag].attributeNames + ) + tags[openTag].onTagStart(currentAttributes) } else { - yield chunk + if (currentChunk !== '') { + yield currentChunk + } break } - } else if (insideTag === 'file') { - const closeMatch = fileCloseRegex.exec(buffer) + } else { + const closeMatch = closeTagRegex.exec(buffer) if (closeMatch) { + const [fullMatch, closeTag] = closeMatch const closeIndex = closeMatch.index + const content = buffer.slice(0, closeIndex) + const complete = tags[insideTag].onTagEnd(content, currentAttributes) - const fileContent = buffer.startsWith('\n') - ? buffer.slice(1, closeIndex) - : buffer.slice(0, closeIndex) - onFile(currentFilePath, fileContent) - currentFilePath = '' - - const afterCloseIndex = closeIndex + closeMatch[0].length - yield buffer.slice(closeIndex) + const afterCloseIndex = closeIndex + fullMatch.length + yield buffer.slice(closeIndex, afterCloseIndex) buffer = buffer.slice(afterCloseIndex) - insideTag = 'none' - break + currentChunk = buffer + insideTag = null + currentAttributes = {} + if (complete) { + return + } } else { break } @@ -56,3 +77,16 @@ export async function* processStreamWithFiles( } } } + +function parseAttributes( + attributesString: string, + attributeNames: string[] +): Record { + const attributes: Record = {} + const regex = new RegExp(`(${attributeNames.join('|')})="([^"]*)"`, 'g') + let match + while ((match = regex.exec(attributesString)) !== null) { + attributes[match[1]] = match[2] + } + return attributes +} diff --git a/backend/src/request-files-prompt.ts b/backend/src/request-files-prompt.ts index 49b92e6e1a..ad180356f7 100644 --- a/backend/src/request-files-prompt.ts +++ b/backend/src/request-files-prompt.ts @@ -12,11 +12,9 @@ export async function requestRelevantFiles( { messages, system, - tools, }: { messages: Message[] system: string | Array - tools: Tool[] }, fileContext: ProjectFileContext, assistantPrompt: string | null, @@ -35,14 +33,15 @@ export async function requestRelevantFiles( : JSON.stringify(lastMessage.content) : '' - const newFilesNecessaryPromise = checkNewFilesNecessary( - messagesExcludingLastIfByUser, - system, - tools, - userId, - previousFiles, - userPrompt - ) + const newFilesNecessaryPromise = assistantPrompt + ? Promise.resolve(true) + : checkNewFilesNecessary( + messagesExcludingLastIfByUser, + system, + userId, + previousFiles, + userPrompt + ) const fileRequestsPromise = generateFileRequests( userPrompt, @@ -51,7 +50,6 @@ export async function requestRelevantFiles( countPerRequest, messagesExcludingLastIfByUser, system, - tools, userId ) @@ -75,7 +73,6 @@ async function generateFileRequests( countPerRequest: number, messagesExcludingLastIfByUser: Message[], system: string | Array, - tools: Tool[], userId: string ) { const numNonObviousPrompts = assistantPrompt ? 1 : 1 @@ -93,7 +90,6 @@ async function generateFileRequests( { messages: messagesExcludingLastIfByUser, system, - tools, }, nonObviousPrompt, models.sonnet, @@ -121,7 +117,6 @@ async function generateFileRequests( { messages: messagesExcludingLastIfByUser, system, - tools, }, keyPrompt, models.sonnet, @@ -145,7 +140,6 @@ async function generateFileRequests( const checkNewFilesNecessary = async ( messages: Message[], system: System, - tools: Tool[], userId: string, previousFiles: string[], userPrompt: string @@ -157,14 +151,13 @@ User request: ${userPrompt} We'll need any files that should be modified to fulfill the user's request, or any files that could be helpful to read to answer the user's request. -Answer with just 'YES' if new files are necessary, or 'NO' if the current files are sufficient. Do not call any tools. +Answer with just 'YES' if new files are necessary, or 'NO' if the current files are sufficient. ` const response = await promptClaude( [...messages, { role: 'user', content: prompt }], { model: models.sonnet, system, - tools, userId, } ).catch((error) => { @@ -179,11 +172,9 @@ async function getRelevantFiles( { messages, system, - tools, }: { messages: Message[] system: string | Array - tools: Tool[] }, userPrompt: string, model: model_types, @@ -201,7 +192,6 @@ async function getRelevantFiles( const response = await promptClaude(messagesWithPrompt, { model, system, - tools, userId, }) const end = performance.now() @@ -255,7 +245,11 @@ function generateNonObviousRequestFilesPrompt( count: number, index: number ): string { + const exampleFiles = getExampleFileList(fileContext, 100) return ` +Random project files: +${exampleFiles.join('\n')} + ${ userPrompt ? `${userPrompt}` @@ -295,9 +289,6 @@ Be sure to include the full path from the project root directory for each file. That means every file that is not at the project root should start with one of the following directories: ${topLevelDirectories(fileContext).join('\n')} - -Example response: -${getExampleFileList(fileContext, count).join('\n')} `.trim() } @@ -310,7 +301,11 @@ function generateKeyRequestFilesPrompt( ): string { const start = (index - 1) * count + 1 const end = start + count - 1 + const exampleFiles = getExampleFileList(fileContext, 100) return ` +Random project files: +${exampleFiles.join('\n')} + ${ userPrompt ? `${userPrompt}` @@ -350,14 +345,11 @@ Be sure to include the full path from the project root directory for each file. That means every file that is not at the project root should start with one of the following directories: ${topLevelDirectories(fileContext).join('\n')} -Example response: -${getExampleFileList(fileContext, count).join('\n')} `.trim() } export const warmCacheForRequestRelevantFiles = async ( system: System, - tools: Tool[], userId: string ) => { await promptClaude( @@ -370,7 +362,6 @@ export const warmCacheForRequestRelevantFiles = async ( { model: models.sonnet, system, - tools, userId, maxTokens: 1, } diff --git a/backend/src/system-prompt.ts b/backend/src/system-prompt.ts index 00b735bdd1..d051f42dbb 100644 --- a/backend/src/system-prompt.ts +++ b/backend/src/system-prompt.ts @@ -186,25 +186,17 @@ const toolsPrompt = ` # Tools You have access to the following tools: -- update_file_context(prompt): Update the set of files and their contents included in your system promptbased on the user's request. Use this to read more files. -- run_terminal_command(command): Execute a command in the terminal and return the result. -- web_scrape(url): Scrape the web page at the given url and return the content. +- [DESCRIPTION_OF_FILES]: Find files given a brief natural language description of the files or the name of a function or class you are looking for. +- [YOUR COMMAND HERE]: Execute a command in the terminal and return the result. +- [URL HERE]: Scrape the web page at the given url and return the content. -## Updating file context +## Finding files -The system prompt already includes some files and their content that you might find useful. If the included set of files is not sufficient to address the user's request, you should use the update_file_context tool to update the set of files and their contents. - -Use this tool only when you need to read different files than what were included. - -If you are intending to modify a file that is not included in the set of files, you should first use the update_file_context tool with a prompt to read that file. If the file is already included, you do not need to read it again. - -Any files that are not listed in the block should not be requested, because that means they don't exist or are gitignored. - -If you are requesting a file path, be sure to include the full path from the project root directory. Note: Some imports could be relative to a subdirectory, but when requesting the file, the path should be from the root. +Use the find_files tool to read more files beyond what is provided in the initial set of files. ## Running terminal commands -You can use the run_terminal_command tool to execute shell commands in the user's terminal. This can be useful for tasks such as: +You can write out the for run_terminal_command to execute shell commands in the user's terminal. This can be useful for tasks such as: 1. Running build or test scripts (e.g., "npm run build" or "npm test"). 2. Moving, renaming, or deleting files and directories. @@ -291,11 +283,9 @@ const getRelevantFilesPromptPart2 = ( Here are some files that were selected to aid in the user request, ordered by most important first. These files represent the current file state after the user's last request: ${fileBlocks} - -Use the tool update_file_context to change the set of files listed here. You should not use this tool to read a file that is already included. -As you can see, some files that you might find useful are already provided. If the included set of files is not sufficient to address the user's request, you should use the update_file_context tool to update the set of files and their contents. +As you can see, some files that you might find useful are already provided. If the included set of files is not sufficient to address the user's request, you can call the find_files tool to update the set of files and their contents. `.trim() } @@ -343,7 +333,9 @@ The goal is to make as few changes as possible to the codebase to address the us You may edit files to address the user's request and run commands in the terminal. However, you will only be able to run up to a maximum of 3 terminal commands in a row before awaiting further user input. -You are reading the following files: ${files.join(', ')}. These were fetched for you after the last user's message and are up to date. Do not request more files with update_file_context unless you are sure you need them and don't have them already. +You are reading the following files: ${files.join(', ')}. These were fetched for you after the last user's message and are up to date. If you need to read more files, please use ... to write what files you are looking for. E.g. "I am looking for agent.ts" or "I need the file with the api routes in it" or "Find me the file with class Foo in it". + +If there is a file that is not visible to you, or you are tempted to say you don't have direct access to it, then you should use ... to request the file. If the user is requesting a change that you think has already been made based on the current version of files, simply tell the user that "the change has already been made". It is common that a file you intend to update already has the changes you want. diff --git a/backend/src/websockets/websocket-action.ts b/backend/src/websockets/websocket-action.ts index dfdfbdf515..be0fdb995d 100644 --- a/backend/src/websockets/websocket-action.ts +++ b/backend/src/websockets/websocket-action.ts @@ -6,10 +6,8 @@ import { sendMessage } from './server' import { isEqual } from 'lodash' import fs from 'fs' import path from 'path' -import { getTools } from 'common/util/tools' import { getSearchSystemPrompt } from '../system-prompt' import { promptClaude, models } from '../claude' -import { env } from '../env.mjs' const sendAction = (ws: WebSocket, action: ServerAction) => { sendMessage(ws, { @@ -116,7 +114,6 @@ const onWarmContextCache = async ( ws: WebSocket ) => { const startTime = Date.now() - const tools = getTools() const system = getSearchSystemPrompt(fileContext) await promptClaude( [ @@ -128,7 +125,6 @@ const onWarmContextCache = async ( { model: models.sonnet, system, - tools, userId: fingerprintId, } ) diff --git a/common/src/constants.ts b/common/src/constants.ts index c8ace7ad2b..7c567aebe2 100644 --- a/common/src/constants.ts +++ b/common/src/constants.ts @@ -1,4 +1,6 @@ export const STOP_MARKER = '[' + 'END]' +export const FIND_FILES_MARKER = '[' + 'FIND_FILES_PLEASE]' +export const TOOL_RESULT_MARKER = '[' + 'TOOL_RESULT]' export const SKIPPED_TERMINAL_COMMANDS = [ 'continue', diff --git a/common/src/util/tools.ts b/common/src/util/tools.ts index ddcc7d050b..e06d18b5e3 100644 --- a/common/src/util/tools.ts +++ b/common/src/util/tools.ts @@ -1,81 +1,16 @@ import { Message } from 'src/actions' import { match, P } from 'ts-pattern' -import { Tool } from '@anthropic-ai/sdk/resources' +import { TOOL_RESULT_MARKER } from 'src/constants' export const didClientUseTool = (message: Message) => match(message) .with( { role: 'user', - content: P.array({ type: 'tool_result' }), + content: P.string.and( + P.when((content) => (content as string).includes(TOOL_RESULT_MARKER)) + ), }, () => true ) .otherwise(() => false) - -export const getTools = (): Tool[] => { - return [ - { - name: 'update_file_context', - description: `Updates the context with a the set of existing files you want to read. Another assistant will try to choose files that will be helpful based on the message history. You should also provide a prompt that describes in natural language what files to add or remove from the context. Do not use this tool to create a new file, only to read existing files.`, - input_schema: { - type: 'object', - properties: { - prompt: { - type: 'string', - description: - 'A prompt that describes in natural language what files to add or remove from the context. You can list specific files, or give general instructions about what files to include.', - }, - }, - required: ['prompt'], - }, - } as Tool, - { - name: 'scrape_web_page', - description: `Retrieves the content of a web page given a URL. This tool is helpful when you need to gather information from external sources, such as documentation, APIs, or other web-based resources. Use this tool when the user asks for information that might be available on a specific website or when you need to reference external documentation to answer a question or solve a problem.`, - input_schema: { - type: 'object', - properties: { - url: { - type: 'string', - description: 'The URL of the web page to scrape', - }, - }, - required: ['url'], - }, - } as Tool, - { - name: 'run_terminal_command', - description: `Executes a command in the terminal and returns the result. This tool allows the assistant to run shell commands, which can be useful for various tasks such as grepping for code references, installing dependencies, running scripts, or performing system operations. Use this tool when you need to execute a specific command in the user's terminal.`, - input_schema: { - type: 'object', - properties: { - command: { - type: 'string', - description: 'The command to run in the terminal', - }, - }, - required: ['command'], - }, - } as Tool, - // { - // name: 'search_manifold_markets', - // description: `Searches for relevant markets on Manifold and returns a list of Yes/No markets with their probabilities. This tool should be used when the user wants to know about a future event, like who will win the next presidential election. You can search for a relevant prediction market, which is a question about the future, and get the market's forecast as a probability which you can interpret.`, - // input_schema: { - // type: 'object', - // properties: { - // query: { - // type: 'string', - // description: 'The search query for finding relevant binary markets', - // }, - // limit: { - // type: 'number', - // description: 'The maximum number of markets to return (default: 5)', - // }, - // }, - // }, - // } as Tool, - ] -} - -export const DEFAULT_TOOLS: Tool[] = getTools() diff --git a/npm-app/src/client.ts b/npm-app/src/client.ts index eed18a6282..8c1f6662dc 100644 --- a/npm-app/src/client.ts +++ b/npm-app/src/client.ts @@ -11,7 +11,7 @@ import { applyChanges } from 'common/util/changes' import { ChatStorage } from './chat-storage' import { FileChanges, Message } from 'common/actions' import { toolHandlers } from './tool-handlers' -import { STOP_MARKER } from 'common/constants' +import { STOP_MARKER, TOOL_RESULT_MARKER } from 'common/constants' import { fingerprintId } from './config' import { parseUrlsFromContent, getScrapedContentBlocks } from './web-scraper' import { uniq } from 'lodash' @@ -59,18 +59,7 @@ export class Client { const assistantMessage: Message = { role: 'assistant', - content: [ - { - type: 'text', - text: response, - }, - { - type: 'tool_use', - id, - name, - input, - }, - ], + content: response, } this.chatStorage.addMessage( this.chatStorage.getCurrentChat(), @@ -82,13 +71,7 @@ export class Client { const content = await handler(input, id) const toolResultMessage: Message = { role: 'user', - content: [ - { - type: 'tool_result', - tool_use_id: id, - content, - }, - ], + content: `${TOOL_RESULT_MARKER}\n${content}`, } this.chatStorage.addMessage( this.chatStorage.getCurrentChat(), diff --git a/npm-app/src/tool-handlers.ts b/npm-app/src/tool-handlers.ts index 54638f74f6..4aff0709a0 100644 --- a/npm-app/src/tool-handlers.ts +++ b/npm-app/src/tool-handlers.ts @@ -11,13 +11,6 @@ import { export type ToolHandler = (input: any, id: string) => Promise -export const handleUpdateFileContext: ToolHandler = async ( - input: { prompt: string }, - id: string -) => { - return '' -} - export const handleScrapeWebPage: ToolHandler = async ( input: { url: string }, id: string @@ -143,7 +136,6 @@ function formatResult( } export const toolHandlers: Record = { - update_file_context: handleUpdateFileContext, scrape_web_page: handleScrapeWebPage, search_manifold_markets: handleSearchManifoldMarkets, run_terminal_command: ((input, id) => diff --git a/test/__src__/process-stream.test.ts b/test/__src__/process-stream.test.ts index a537d57e99..0d75a46df4 100644 --- a/test/__src__/process-stream.test.ts +++ b/test/__src__/process-stream.test.ts @@ -1,5 +1,5 @@ import { test, expect, mock } from 'bun:test' -import { processStreamWithFiles } from 'backend/process-stream' +import { processStreamWithTags } from 'backend/process-stream' test('processStreamWithFiles basic functionality', async () => { const mockStream = async function* () { @@ -7,14 +7,18 @@ test('processStreamWithFiles basic functionality', async () => { yield 'file content' yield 'after' } - const onFileStart = mock((filePath: string) => {}) - const onFile = mock((filePath: string, content: string) => {}) + const onFileStart = mock((attributes: Record) => {}) + const onFile = mock((content: string, attributes: Record) => { + return false + }) const result = [] - for await (const chunk of processStreamWithFiles( - mockStream(), - onFileStart, - onFile - )) { + for await (const chunk of processStreamWithTags(mockStream(), { + file: { + attributeNames: ['path'], + onTagStart: onFileStart, + onTagEnd: onFile, + }, + })) { result.push(chunk) } expect(result).toEqual([ @@ -23,6 +27,75 @@ test('processStreamWithFiles basic functionality', async () => { '', 'after', ]) - expect(onFileStart).toHaveBeenCalledWith('test.txt') - expect(onFile).toHaveBeenCalledWith('test.txt', 'file content') + expect(onFileStart).toHaveBeenCalledWith({ path: 'test.txt' }) + expect(onFile).toHaveBeenCalledWith('file content', { path: 'test.txt' }) +}) + +test('processStreamWithTags handles tool_call for terminal command', async () => { + const mockStream = async function* () { + yield 'I will run bun install for you. ' + yield 'bun install' + } + const onToolCallStart = mock((attributes: Record) => {}) + const onToolCall = mock( + (content: string, attributes: Record) => { + return false + } + ) + const result = [] + for await (const chunk of processStreamWithTags(mockStream(), { + tool_call: { + attributeNames: ['name'], + onTagStart: onToolCallStart, + onTagEnd: onToolCall, + }, + })) { + result.push(chunk) + } + expect(result).toEqual([ + 'I will run bun install for you. ', + '', + '', + ]) + expect(onToolCallStart).toHaveBeenCalledWith({ name: 'run_terminal_command' }) + expect(onToolCall).toHaveBeenCalledWith('bun install', { + name: 'run_terminal_command', + }) +}) + +test('processStreamWithTags handles tool_call for terminal command split into many chunks', async () => { + const mockStream = async function* () { + yield 'I will run bun install for' + yield ' you. bun ' + yield 'install' + } + const onToolCallStart = mock((attributes: Record) => {}) + const onToolCall = mock( + (content: string, attributes: Record) => { + return false + } + ) + const result = [] + for await (const chunk of processStreamWithTags(mockStream(), { + tool_call: { + attributeNames: ['name'], + onTagStart: onToolCallStart, + onTagEnd: onToolCall, + }, + })) { + result.push(chunk) + } + expect(result).toEqual([ + 'I will run bun install for', + ' you. ', + '', + ]) + expect(onToolCallStart).toHaveBeenCalledWith({ name: 'run_terminal_command' }) + expect(onToolCall).toHaveBeenCalledWith('bun install', { + name: 'run_terminal_command', + }) }) diff --git a/test/package.json b/test/package.json index bae8ffce63..5034087647 100644 --- a/test/package.json +++ b/test/package.json @@ -6,7 +6,8 @@ "test": "bun test __src__", "test-manifold": "bun test manifold-project.test.ts", "test-patch": "bun test generate-patch.test.ts", - "test-generate-knowledge": "bun test generate-knowledge-files.test.ts" + "test-generate-knowledge": "bun test generate-knowledge-files.test.ts", + "test-stream": "bun test process-stream.test.ts" }, "dependencies": { "backend": "file:../backend", diff --git a/todo.knowledge.md b/todo.knowledge.md index 04c3a97383..a5ab1ae7ae 100644 --- a/todo.knowledge.md +++ b/todo.knowledge.md @@ -84,7 +84,7 @@ Notes from Janna & Stephen test - Also openai defaults to 0 [] Add current file diff from main into context (git status/git diff?) -[] It thought that update_file_context would create a file? (a knowledge file?) +[x] It thought that update_file_context would create a file? (a knowledge file?) [] Claude doesn't leave a comment that there's more code in between when it should. Then lots gets deleted [] Try using the native stop marker feature [] Use tree sitter to include exported tokens ttps://github.com/tree-sitter/node-tree-sitter