From 50cfee3fe7dccd37fcb1586eb2989ca7f1aca4b0 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Sun, 22 Sep 2024 19:30:23 -0700 Subject: [PATCH 1/7] [FIND_FILES_PLEASE] marker instead of update_file_context tool --- backend/src/main-prompt.ts | 32 +++++++++++++---------------- backend/src/request-files-prompt.ts | 31 ++++++++++++++++------------ backend/src/system-prompt.ts | 23 +++++---------------- common/src/constants.ts | 1 + common/src/util/tools.ts | 15 -------------- npm-app/src/tool-handlers.ts | 8 -------- todo.knowledge.md | 2 +- 7 files changed, 39 insertions(+), 73 deletions(-) diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index 46a380d3de..c47ab9dfd6 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -7,7 +7,7 @@ import { promptClaudeStream } from './claude' import { createFileBlock, ProjectFileContext } from 'common/util/file' import { didClientUseTool, DEFAULT_TOOLS } from 'common/util/tools' import { getSearchSystemPrompt, getAgentSystemPrompt } from './system-prompt' -import { STOP_MARKER } from 'common/constants' +import { FIND_FILES_MARKER, STOP_MARKER } from 'common/constants' import { FileChange, Message } from 'common/actions' import { ToolCall } from 'common/actions' import { debugLog } from './util/debug' @@ -171,24 +171,20 @@ ${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 - } + } else if (fullResponse.includes(FIND_FILES_MARKER)) { + const responseChunk = await updateFileContext( + ws, + fileContext, + { messages, system: getSearchSystemPrompt(fileContext), tools }, + fullResponse, + onResponseChunk, + userId + ) + if (responseChunk !== null) { + onResponseChunk(responseChunk) + fullResponse += responseChunk } + } else if (toolCall) { isComplete = true } else { console.log('continuing to generate') diff --git a/backend/src/request-files-prompt.ts b/backend/src/request-files-prompt.ts index ec4d681fd9..0d57a7ef04 100644 --- a/backend/src/request-files-prompt.ts +++ b/backend/src/request-files-prompt.ts @@ -35,14 +35,16 @@ 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, + tools, + userId, + previousFiles, + userPrompt + ) const fileRequestsPromise = generateFileRequests( userPrompt, @@ -253,7 +255,11 @@ function generateNonObviousRequestFilesPrompt( count: number, index: number ): string { + const exampleFiles = getExampleFileList(fileContext, 100) return ` +Random project files: +${exampleFiles.join('\n')} + ${ userPrompt ? `${userPrompt}` @@ -293,9 +299,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() } @@ -308,7 +311,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}` @@ -348,8 +355,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() } diff --git a/backend/src/system-prompt.ts b/backend/src/system-prompt.ts index c89fabc95d..e29c466df8 100644 --- a/backend/src/system-prompt.ts +++ b/backend/src/system-prompt.ts @@ -5,7 +5,7 @@ import { printFileTreeWithTokens, } from 'common/util/file' import { buildArray } from 'common/util/array' -import { STOP_MARKER } from 'common/constants' +import { FIND_FILES_MARKER, STOP_MARKER } from 'common/constants' import { countTokens, countTokensForFiles } from './util/token-counter' import { debugLog } from './util/debug' import { sortBy, sum } from 'lodash' @@ -186,22 +186,9 @@ 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. -## Updating file context - -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. - ## 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: @@ -291,11 +278,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 write the special token ${FIND_FILES_MARKER} to update the set of files and their contents. `.trim() } @@ -343,7 +328,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 write what files you are looking for and then the special marker: ${FIND_FILES_MARKER}. E.g. "I am looking for agent.ts ${FIND_FILES_MARKER}" or "I need the file with the api routes in it ${FIND_FILES_MARKER}" or "Find me the file with class Foo in it ${FIND_FILES_MARKER}". + +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 the special marker ${FIND_FILES_MARKER} 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/common/src/constants.ts b/common/src/constants.ts index c8ace7ad2b..30e7d42593 100644 --- a/common/src/constants.ts +++ b/common/src/constants.ts @@ -1,4 +1,5 @@ export const STOP_MARKER = '[' + 'END]' +export const FIND_FILES_MARKER = '[' + 'FIND_FILES_PLEASE]' export const SKIPPED_TERMINAL_COMMANDS = [ 'continue', diff --git a/common/src/util/tools.ts b/common/src/util/tools.ts index ddcc7d050b..57cd53ba20 100644 --- a/common/src/util/tools.ts +++ b/common/src/util/tools.ts @@ -15,21 +15,6 @@ export const didClientUseTool = (message: Message) => 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.`, 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/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 From 2007b74df6caf25bfc0d5aaf0123185a5222ce8a Mon Sep 17 00:00:00 2001 From: James Grugett Date: Sun, 22 Sep 2024 19:59:52 -0700 Subject: [PATCH 2/7] Check new files necessary more info --- backend/src/request-files-prompt.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/src/request-files-prompt.ts b/backend/src/request-files-prompt.ts index 0d57a7ef04..97ef4872bf 100644 --- a/backend/src/request-files-prompt.ts +++ b/backend/src/request-files-prompt.ts @@ -154,9 +154,11 @@ const checkNewFilesNecessary = async ( ) => { const prompt = ` Given the user's request and the current context, determine if new files are necessary to fulfill the request. -Current files: ${previousFiles.join(', ')} +Current files: ${previousFiles.length > 0 ? previousFiles.join(', ') : 'None'} 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. ` const response = await promptClaude( From e820919cbda7595317c1f8b6611829455b8ae7d2 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Sun, 22 Sep 2024 20:00:26 -0700 Subject: [PATCH 3/7] Generic process stream --- backend/src/main-prompt.ts | 48 ++++++++-------- backend/src/process-stream.ts | 89 ++++++++++++++++++++--------- test/__src__/process-stream.test.ts | 21 ++++--- test/package.json | 3 +- 4 files changed, 102 insertions(+), 59 deletions(-) diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index c47ab9dfd6..0ac6669360 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -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' /** @@ -132,29 +132,31 @@ ${STOP_MARKER} tools, userId, }) - const fileStream = processStreamWithFiles( - stream, - (_filePath) => { - onResponseChunk('Modifying...') + const fileStream = processStreamWithTags(stream, { + file: { + attributeNames: ['path'], + onTagStart: () => { + onResponseChunk('Modifying...') + }, + onTagEnd: (fileContent, { path}) => { + console.log('on file!', path) + fileProcessingPromises.push( + processFileBlock( + userId, + ws, + messages, + fullResponse, + path, + fileContent + ).catch((error) => { + console.error('Error processing file block', error) + return null + }) + ) + fullResponse += fileContent + }, }, - (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') { diff --git a/backend/src/process-stream.ts b/backend/src/process-stream.ts index fcb1fb5fa4..f1512ae98e 100644 --- a/backend/src/process-stream.ts +++ b/backend/src/process-stream.ts @@ -1,14 +1,27 @@ 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) => void + } + } ) { 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 tagRegex = new RegExp( + `<(${tagNames.map(escapeRegExp).join('|')})\\s*([^>]*)>|`, + 'g' + ) for await (const chunk of stream) { if (typeof chunk === 'object') { @@ -19,36 +32,45 @@ export async function* processStreamWithFiles( 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 = tagRegex.exec(buffer) + if (match) { + const [fullMatch, openTag, attributesString, closeTag] = match + const matchIndex = match.index + const afterMatchIndex = matchIndex + fullMatch.length + + yield buffer.slice(0, afterMatchIndex) + buffer = buffer.slice(afterMatchIndex) + + if (openTag) { + insideTag = openTag + currentAttributes = parseAttributes( + attributesString, + tags[openTag].attributeNames + ) + tags[openTag].onTagStart(currentAttributes) + } else if (closeTag) { + // Ignore closing tags when not inside a tag + } } else { - yield chunk + if (buffer.length > 0) { + yield buffer + } + buffer = '' break } - } else if (insideTag === 'file') { - const closeMatch = fileCloseRegex.exec(buffer) + } else { + const closeMatch = new RegExp(``).exec(buffer) if (closeMatch) { const closeIndex = closeMatch.index - - const fileContent = buffer.startsWith('\n') - ? buffer.slice(1, closeIndex) - : buffer.slice(0, closeIndex) - onFile(currentFilePath, fileContent) - currentFilePath = '' + const content = buffer.slice(0, closeIndex) + tags[insideTag].onTagEnd(content, currentAttributes) const afterCloseIndex = closeIndex + closeMatch[0].length - yield buffer.slice(closeIndex) + yield buffer.slice(closeIndex, afterCloseIndex) buffer = buffer.slice(afterCloseIndex) - insideTag = 'none' - break + insideTag = null + currentAttributes = {} } else { break } @@ -56,3 +78,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/test/__src__/process-stream.test.ts b/test/__src__/process-stream.test.ts index a537d57e99..c22b1b8ad4 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,13 +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) => {}) const result = [] - for await (const chunk of processStreamWithFiles( + for await (const chunk of processStreamWithTags( mockStream(), - onFileStart, - onFile + { + file: { + attributeNames: ['path'], + onTagStart: onFileStart, + onTagEnd: onFile, + }, + } )) { result.push(chunk) } @@ -23,6 +28,6 @@ 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' }) }) 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", From c6682c1a746f6e4de9dcef3564e2ef19a23ba590 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Sun, 22 Sep 2024 20:01:48 -0700 Subject: [PATCH 4/7] In prog --- backend/src/system-prompt.ts | 6 ++-- common/src/util/tools.ts | 56 ++++++++++++++++++------------------ 2 files changed, 31 insertions(+), 31 deletions(-) diff --git a/backend/src/system-prompt.ts b/backend/src/system-prompt.ts index e29c466df8..2d08074ffb 100644 --- a/backend/src/system-prompt.ts +++ b/backend/src/system-prompt.ts @@ -186,12 +186,12 @@ const toolsPrompt = ` # Tools You have access to the following tools: -- 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. +- [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. ## 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 tags 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. diff --git a/common/src/util/tools.ts b/common/src/util/tools.ts index 57cd53ba20..3be9375ac4 100644 --- a/common/src/util/tools.ts +++ b/common/src/util/tools.ts @@ -15,34 +15,34 @@ export const didClientUseTool = (message: Message) => export const getTools = (): Tool[] => { return [ - { - 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: '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.`, From e30e58a7bfd7ffe51d7d7e74eb26ef516a94acac Mon Sep 17 00:00:00 2001 From: James Grugett Date: Mon, 23 Sep 2024 14:24:35 -0700 Subject: [PATCH 5/7] Working tool calls --- backend/src/claude.ts | 1 + backend/src/main-prompt.ts | 36 ++++++++++-- backend/src/process-stream.ts | 60 ++++++++++--------- backend/src/system-prompt.ts | 6 +- common/src/constants.ts | 1 + common/src/util/tools.ts | 5 +- npm-app/src/client.ts | 23 +------- test/__src__/process-stream.test.ts | 90 +++++++++++++++++++++++++---- 8 files changed, 156 insertions(+), 66 deletions(-) diff --git a/backend/src/claude.ts b/backend/src/claude.ts index b0048046fe..959d6d757d 100644 --- a/backend/src/claude.ts +++ b/backend/src/claude.ts @@ -70,6 +70,7 @@ export const promptClaudeStream = async function* ( messages, system, tools, + stop_sequences: [STOP_MARKER], }) ) diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index 0ac6669360..bc6b6aca30 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -132,14 +132,17 @@ ${STOP_MARKER} tools, userId, }) - const fileStream = processStreamWithTags(stream, { + const streamWithTags = processStreamWithTags(stream, { file: { attributeNames: ['path'], onTagStart: () => { onResponseChunk('Modifying...') }, - onTagEnd: (fileContent, { path}) => { + onTagEnd: (fileContent, { path }) => { console.log('on file!', path) + const filePathWithoutStartNewline = fileContent.startsWith('\n') + ? fileContent.slice(1) + : fileContent fileProcessingPromises.push( processFileBlock( userId, @@ -147,18 +150,43 @@ ${STOP_MARKER} messages, fullResponse, path, - fileContent + filePathWithoutStartNewline ).catch((error) => { console.error('Error processing file block', error) return null }) ) fullResponse += fileContent + return false + }, + }, + tool_call: { + attributeNames: ['name'], + onTagStart: (attributes) => { + console.log('tool call start', attributes) + }, + onTagEnd: (content, attributes) => { + console.log('tool call end', content, attributes) + const name = attributes.name + const contentAttributes: Record = {} + if (name === 'run_terminal_command') { + contentAttributes.command = 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 fileStream) { + for await (const chunk of streamWithTags) { if (typeof chunk === 'object') { toolCall = chunk debugLog('Received tool call:', toolCall) diff --git a/backend/src/process-stream.ts b/backend/src/process-stream.ts index f1512ae98e..840a822c0d 100644 --- a/backend/src/process-stream.ts +++ b/backend/src/process-stream.ts @@ -1,13 +1,13 @@ -const fileOpenRegex = //g -const fileCloseRegex = /<\/file>/g - export async function* processStreamWithTags( stream: AsyncGenerator, tags: { [tagName: string]: { attributeNames: string[] onTagStart: (attributes: Record) => void - onTagEnd: (content: string, attributes: Record) => void + onTagEnd: ( + content: string, + attributes: Record + ) => boolean } } ) { @@ -18,8 +18,12 @@ export async function* processStreamWithTags( const escapeRegExp = (string: string) => string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') const tagNames = Object.keys(tags) - const tagRegex = new RegExp( - `<(${tagNames.map(escapeRegExp).join('|')})\\s*([^>]*)>|`, + const openTagRegex = new RegExp( + `<(${tagNames.map(escapeRegExp).join('|')})\\s*([^>]*)>`, + 'g' + ) + const closeTagRegex = new RegExp( + ``, 'g' ) @@ -28,49 +32,51 @@ export async function* processStreamWithTags( yield chunk continue } + let currentChunk: string = chunk buffer += chunk while (true) { if (insideTag === null) { - const match = tagRegex.exec(buffer) + const match = openTagRegex.exec(buffer) if (match) { - const [fullMatch, openTag, attributesString, closeTag] = match - const matchIndex = match.index - const afterMatchIndex = matchIndex + fullMatch.length + const [fullMatch, openTag, attributesString] = match + + const afterMatchIndex = match.index + fullMatch.length + const chunkStartIndex = buffer.length - currentChunk.length + yield buffer.slice(chunkStartIndex, afterMatchIndex) - yield buffer.slice(0, afterMatchIndex) buffer = buffer.slice(afterMatchIndex) - if (openTag) { - insideTag = openTag - currentAttributes = parseAttributes( - attributesString, - tags[openTag].attributeNames - ) - tags[openTag].onTagStart(currentAttributes) - } else if (closeTag) { - // Ignore closing tags when not inside a tag - } + insideTag = openTag + currentAttributes = parseAttributes( + attributesString, + tags[openTag].attributeNames + ) + tags[openTag].onTagStart(currentAttributes) } else { - if (buffer.length > 0) { - yield buffer + if (currentChunk !== '') { + yield currentChunk } - buffer = '' break } } else { - const closeMatch = new RegExp(``).exec(buffer) + const closeMatch = closeTagRegex.exec(buffer) if (closeMatch) { + const [fullMatch, closeTag] = closeMatch const closeIndex = closeMatch.index const content = buffer.slice(0, closeIndex) - tags[insideTag].onTagEnd(content, currentAttributes) + const complete = tags[insideTag].onTagEnd(content, currentAttributes) - const afterCloseIndex = closeIndex + closeMatch[0].length + const afterCloseIndex = closeIndex + fullMatch.length yield buffer.slice(closeIndex, afterCloseIndex) buffer = buffer.slice(afterCloseIndex) + currentChunk = buffer insideTag = null currentAttributes = {} + if (complete) { + return + } } else { break } diff --git a/backend/src/system-prompt.ts b/backend/src/system-prompt.ts index 2d08074ffb..ae1ad0c3d1 100644 --- a/backend/src/system-prompt.ts +++ b/backend/src/system-prompt.ts @@ -186,12 +186,12 @@ const toolsPrompt = ` # Tools You have access to the following tools: -- [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. +- [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. ## Running terminal commands -You can write out the tags 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. diff --git a/common/src/constants.ts b/common/src/constants.ts index 30e7d42593..7c567aebe2 100644 --- a/common/src/constants.ts +++ b/common/src/constants.ts @@ -1,5 +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 3be9375ac4..33ccc1046e 100644 --- a/common/src/util/tools.ts +++ b/common/src/util/tools.ts @@ -1,13 +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 ) 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/test/__src__/process-stream.test.ts b/test/__src__/process-stream.test.ts index c22b1b8ad4..0d75a46df4 100644 --- a/test/__src__/process-stream.test.ts +++ b/test/__src__/process-stream.test.ts @@ -8,18 +8,17 @@ test('processStreamWithFiles basic functionality', async () => { yield 'after' } const onFileStart = mock((attributes: Record) => {}) - const onFile = mock((content: string, attributes: Record) => {}) + const onFile = mock((content: string, attributes: Record) => { + return false + }) const result = [] - for await (const chunk of processStreamWithTags( - mockStream(), - { - file: { - attributeNames: ['path'], - onTagStart: onFileStart, - onTagEnd: onFile, - }, - } - )) { + for await (const chunk of processStreamWithTags(mockStream(), { + file: { + attributeNames: ['path'], + onTagStart: onFileStart, + onTagEnd: onFile, + }, + })) { result.push(chunk) } expect(result).toEqual([ @@ -31,3 +30,72 @@ test('processStreamWithFiles basic functionality', async () => { 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', + }) +}) From 04588de1351159ad60913568ec7ab44890216222 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Mon, 23 Sep 2024 14:41:09 -0700 Subject: [PATCH 6/7] Remove tool calls on backend --- backend/src/claude.ts | 5 ++- backend/src/generate-knowledge-files.ts | 4 +- backend/src/main-prompt.ts | 34 +++++--------- backend/src/process-stream.ts | 11 +---- backend/src/request-files-prompt.ts | 16 +------ backend/src/websockets/websocket-action.ts | 4 -- common/src/util/tools.ts | 52 ---------------------- 7 files changed, 17 insertions(+), 109 deletions(-) diff --git a/backend/src/claude.ts b/backend/src/claude.ts index 959d6d757d..10892f0ec6 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, @@ -107,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 97781720e4..38b8e231af 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 { getRelevantFilesPrompt, knowledgeFilesPrompt } from './system-prompt' -import { DEFAULT_TOOLS } from 'common/util/tools' import { debugLog } from './util/debug' import { env } from './env.mjs' @@ -47,7 +46,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. ` const userPrompt = ` @@ -94,7 +93,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 bc6b6aca30..09ef97c7a7 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -5,7 +5,7 @@ import { TextBlockParam, Tool } 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 { FIND_FILES_MARKER, STOP_MARKER } from 'common/constants' import { FileChange, Message } from 'common/actions' @@ -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,7 +50,7 @@ export async function mainPrompt( const responseChunk = await updateFileContext( ws, fileContext, - { messages, system, tools }, + { messages, system }, null, onResponseChunk, userId @@ -61,7 +60,7 @@ export async function mainPrompt( // Prompt cache the new files. const system = getSearchSystemPrompt(fileContext) - warmCacheForRequestRelevantFiles(system, DEFAULT_TOOLS, userId) + warmCacheForRequestRelevantFiles(system, userId) } } @@ -125,11 +124,10 @@ ${STOP_MARKER} ? [...messagesWithoutLastMessage, newLastMessage, ...continuedMessages] : messages - savePromptLengthInfo(messagesWithContinuedMessage, system, tools) + savePromptLengthInfo(messagesWithContinuedMessage, system) const stream = promptClaudeStream(messagesWithContinuedMessage, { system, - tools, userId, }) const streamWithTags = processStreamWithTags(stream, { @@ -162,15 +160,15 @@ ${STOP_MARKER} }, tool_call: { attributeNames: ['name'], - onTagStart: (attributes) => { - console.log('tool call start', attributes) - }, + onTagStart: (attributes) => {}, onTagEnd: (content, attributes) => { console.log('tool call end', content, attributes) 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) @@ -187,12 +185,6 @@ ${STOP_MARKER} }) for await (const chunk of streamWithTags) { - if (typeof chunk === 'object') { - toolCall = chunk - debugLog('Received tool call:', toolCall) - continue - } - fullResponse += chunk onResponseChunk(chunk) } @@ -205,7 +197,7 @@ ${STOP_MARKER} const responseChunk = await updateFileContext( ws, fileContext, - { messages, system: getSearchSystemPrompt(fileContext), tools }, + { messages, system: getSearchSystemPrompt(fileContext) }, fullResponse, onResponseChunk, userId @@ -214,8 +206,6 @@ ${STOP_MARKER} onResponseChunk(responseChunk) fullResponse += responseChunk } - } else if (toolCall) { - isComplete = true } else { console.log('continuing to generate') debugLog('continuing to generate') @@ -257,7 +247,7 @@ ${STOP_MARKER} return { response: responseWithChanges, changes, - toolCall, + toolCall: toolCall as ToolCall | null, } } @@ -274,18 +264,16 @@ 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 @@ -350,7 +338,6 @@ export async function processFileBlock( const savePromptLengthInfo = ( messages: Message[], system: string | Array, - tools: Tool[] ) => { console.log('Prompting claude num messages:', messages.length) debugLog('Prompting claude num messages:', messages.length) @@ -363,7 +350,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 840a822c0d..3959f93950 100644 --- a/backend/src/process-stream.ts +++ b/backend/src/process-stream.ts @@ -1,13 +1,10 @@ -export async function* processStreamWithTags( +export async function* processStreamWithTags( stream: AsyncGenerator, tags: { [tagName: string]: { attributeNames: string[] onTagStart: (attributes: Record) => void - onTagEnd: ( - content: string, - attributes: Record - ) => boolean + onTagEnd: (content: string, attributes: Record) => boolean } } ) { @@ -28,10 +25,6 @@ export async function* processStreamWithTags( ) for await (const chunk of stream) { - if (typeof chunk === 'object') { - yield chunk - continue - } let currentChunk: string = chunk buffer += chunk diff --git a/backend/src/request-files-prompt.ts b/backend/src/request-files-prompt.ts index 97ef4872bf..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, @@ -40,7 +38,6 @@ export async function requestRelevantFiles( : checkNewFilesNecessary( messagesExcludingLastIfByUser, system, - tools, userId, previousFiles, userPrompt @@ -53,7 +50,6 @@ export async function requestRelevantFiles( countPerRequest, messagesExcludingLastIfByUser, system, - tools, userId ) @@ -77,7 +73,6 @@ async function generateFileRequests( countPerRequest: number, messagesExcludingLastIfByUser: Message[], system: string | Array, - tools: Tool[], userId: string ) { const numNonObviousPrompts = assistantPrompt ? 1 : 1 @@ -95,7 +90,6 @@ async function generateFileRequests( { messages: messagesExcludingLastIfByUser, system, - tools, }, nonObviousPrompt, models.sonnet, @@ -123,7 +117,6 @@ async function generateFileRequests( { messages: messagesExcludingLastIfByUser, system, - tools, }, keyPrompt, models.sonnet, @@ -147,7 +140,6 @@ async function generateFileRequests( const checkNewFilesNecessary = async ( messages: Message[], system: System, - tools: Tool[], userId: string, previousFiles: string[], userPrompt: string @@ -159,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) => { @@ -181,11 +172,9 @@ async function getRelevantFiles( { messages, system, - tools, }: { messages: Message[] system: string | Array - tools: Tool[] }, userPrompt: string, model: model_types, @@ -203,7 +192,6 @@ async function getRelevantFiles( const response = await promptClaude(messagesWithPrompt, { model, system, - tools, userId, }) const end = performance.now() @@ -362,7 +350,6 @@ ${topLevelDirectories(fileContext).join('\n')} export const warmCacheForRequestRelevantFiles = async ( system: System, - tools: Tool[], userId: string ) => { await promptClaude( @@ -375,7 +362,6 @@ export const warmCacheForRequestRelevantFiles = async ( { model: models.sonnet, system, - tools, userId, maxTokens: 1, } 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/util/tools.ts b/common/src/util/tools.ts index 33ccc1046e..2c097b15fa 100644 --- a/common/src/util/tools.ts +++ b/common/src/util/tools.ts @@ -15,55 +15,3 @@ export const didClientUseTool = (message: Message) => () => true ) .otherwise(() => false) - -export const getTools = (): Tool[] => { - return [ - // { - // 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() From 633cca90fcde62e43a3848fc92eb6630d4fff3da Mon Sep 17 00:00:00 2001 From: James Grugett Date: Mon, 23 Sep 2024 18:53:56 -0700 Subject: [PATCH 7/7] Working find files with prefilling assistant response --- backend/src/claude.ts | 2 +- backend/src/main-prompt.ts | 72 ++++++++++++++++++++++-------------- backend/src/system-prompt.ts | 13 +++++-- common/src/util/tools.ts | 1 - 4 files changed, 55 insertions(+), 33 deletions(-) diff --git a/backend/src/claude.ts b/backend/src/claude.ts index 10892f0ec6..222e3f588c 100644 --- a/backend/src/claude.ts +++ b/backend/src/claude.ts @@ -70,7 +70,7 @@ export const promptClaudeStream = async function* ( messages, system, tools, - stop_sequences: [STOP_MARKER], + stop_sequences: [], }) ) diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index 09ef97c7a7..b8fd2470c6 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -1,13 +1,13 @@ 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 } from 'common/util/tools' import { getSearchSystemPrompt, getAgentSystemPrompt } from './system-prompt' -import { FIND_FILES_MARKER, STOP_MARKER } from 'common/constants' +import { STOP_MARKER } from 'common/constants' import { FileChange, Message } from 'common/actions' import { ToolCall } from 'common/actions' import { debugLog } from './util/debug' @@ -52,11 +52,11 @@ export async function mainPrompt( fileContext, { 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) @@ -67,7 +67,6 @@ export async function mainPrompt( 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, @@ -95,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 @@ -162,7 +163,7 @@ ${STOP_MARKER} attributeNames: ['name'], onTagStart: (attributes) => {}, onTagEnd: (content, attributes) => { - console.log('tool call end', content, attributes) + console.log('tool call', { ...attributes, content }) const name = attributes.name const contentAttributes: Record = {} if (name === 'run_terminal_command') { @@ -189,23 +190,33 @@ ${STOP_MARKER} onResponseChunk(chunk) } - if (fullResponse.includes(STOP_MARKER)) { - isComplete = true - fullResponse = fullResponse.replace(STOP_MARKER, '') - debugLog('Reached STOP_MARKER') - } else if (fullResponse.includes(FIND_FILES_MARKER)) { - const responseChunk = await updateFileContext( + const maybeToolCall = toolCall as ToolCall | null + + if (maybeToolCall?.name === 'find_files') { + const response = await updateFileContext( ws, fileContext, { messages, system: getSearchSystemPrompt(fileContext) }, fullResponse, - onResponseChunk, userId ) - if (responseChunk !== null) { - onResponseChunk(responseChunk) - fullResponse += responseChunk + 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 { console.log('continuing to generate') debugLog('continuing to generate') @@ -230,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( @@ -252,10 +264,9 @@ ${STOP_MARKER} } 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( @@ -269,7 +280,6 @@ async function updateFileContext( system: string | Array }, prompt: string | null, - onResponseChunk: (chunk: string) => void, userId: string ) { const relevantFiles = await requestRelevantFiles( @@ -283,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( @@ -337,7 +355,7 @@ export async function processFileBlock( const savePromptLengthInfo = ( messages: Message[], - system: string | Array, + system: string | Array ) => { console.log('Prompting claude num messages:', messages.length) debugLog('Prompting claude num messages:', messages.length) diff --git a/backend/src/system-prompt.ts b/backend/src/system-prompt.ts index ae1ad0c3d1..36ea364236 100644 --- a/backend/src/system-prompt.ts +++ b/backend/src/system-prompt.ts @@ -5,7 +5,7 @@ import { printFileTreeWithTokens, } from 'common/util/file' import { buildArray } from 'common/util/array' -import { FIND_FILES_MARKER, STOP_MARKER } from 'common/constants' +import { STOP_MARKER } from 'common/constants' import { countTokens, countTokensForFiles } from './util/token-counter' import { debugLog } from './util/debug' import { sortBy, sum } from 'lodash' @@ -186,9 +186,14 @@ const toolsPrompt = ` # Tools You have access to the following tools: +- [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. +## Finding files + +Use the find_files tool to read more files beyond what is provided in the initial set of files. + ## Running terminal commands 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: @@ -280,7 +285,7 @@ Here are some files that were selected to aid in the user request, ordered by mo ${fileBlocks} -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 write the special token ${FIND_FILES_MARKER} 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() } @@ -328,9 +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. If you need to read more files, please write what files you are looking for and then the special marker: ${FIND_FILES_MARKER}. E.g. "I am looking for agent.ts ${FIND_FILES_MARKER}" or "I need the file with the api routes in it ${FIND_FILES_MARKER}" or "Find me the file with class Foo in it ${FIND_FILES_MARKER}". +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 the special marker ${FIND_FILES_MARKER} to request the file. +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/common/src/util/tools.ts b/common/src/util/tools.ts index 2c097b15fa..e06d18b5e3 100644 --- a/common/src/util/tools.ts +++ b/common/src/util/tools.ts @@ -1,6 +1,5 @@ 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) =>