From 3181d207aedd23de47505114ec45e9254cab4009 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Thu, 12 Sep 2024 11:42:10 -0700 Subject: [PATCH 1/7] Use o1 as a coder --- backend/src/code-agent.ts | 59 ++++++++++++++++++++++++++++++++++++ backend/src/main-prompt.ts | 8 ++++- backend/src/openai-api.ts | 5 +-- backend/src/system-prompt.ts | 16 +++++++++- 4 files changed, 84 insertions(+), 4 deletions(-) create mode 100644 backend/src/code-agent.ts diff --git a/backend/src/code-agent.ts b/backend/src/code-agent.ts new file mode 100644 index 0000000000..bbd3a99ce6 --- /dev/null +++ b/backend/src/code-agent.ts @@ -0,0 +1,59 @@ +import { WebSocket } from 'ws' + +import { Message } from 'common/actions' +import { parseFileBlocks, ProjectFileContext } from 'common/util/file' +import { getCoderPrompt } from './system-prompt' +import { assert } from 'common/util/object' +import { OpenAIMessage, promptOpenAI } from './openai-api' +import { processFileBlock } from './main-prompt' + +export const codeAgent = async ( + userId: string, + fileContext: ProjectFileContext, + messages: Message[], + ws: WebSocket, + onResponseChunk: (chunk: string) => void +) => { + const coderPrompt = getCoderPrompt(fileContext) + const lastMessage = messages[messages.length - 1] + assert(lastMessage.role === 'user', 'Last message must be from user') + assert( + typeof lastMessage.content === 'string', + 'Last user message must be text' + ) + + const infoPrompt = `Please use the above information to answer the user's question:` + const content = [coderPrompt, infoPrompt, lastMessage.content].join('\n\n') + + const messagesWithContext = [ + ...messages.slice(0, -1), + { + ...lastMessage, + content, + }, + ] as OpenAIMessage[] + console.log('messagesWithContext', messagesWithContext) + + onResponseChunk('Generating response with o1-preview...\n\n') + + const response = await promptOpenAI( + userId, + messagesWithContext, + 'o1-preview', + { temperature: 1 } + ) + + onResponseChunk(response + '\n') + console.log('response', response) + + const fileBlocks = parseFileBlocks(response) + const changes = await Promise.all( + Object.entries(fileBlocks).map(([filePath, fileBlock]) => + processFileBlock(userId, ws, messages, response, filePath, fileBlock) + ) + ) + + console.log('changes', changes) + + return { response, changes } +} diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index 531ea58434..e2ff1e0b7b 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -16,7 +16,9 @@ import { generatePatch } from './generate-patch' import { requestRelevantFiles } from './request-files-prompt' import { processStreamWithFiles } from './process-stream' import { countTokens } from './util/token-counter' +import { codeAgent } from './code-agent' +const O1_ENABLED = true /** * Prompt claude, handle tool calls, and generate file changes. */ @@ -37,7 +39,7 @@ export async function mainPrompt( const tools = getTools() let shouldCheckFiles = true - if (Object.keys(fileContext.files).length === 0) { + if (Object.keys(fileContext.files).length === 0 || O1_ENABLED) { const system = getSystemPrompt(fileContext, { checkFiles: true, }) @@ -54,6 +56,10 @@ export async function mainPrompt( shouldCheckFiles = false } + if (O1_ENABLED) { + return await codeAgent(userId, fileContext, messages, ws, onResponseChunk) + } + const lastMessage = messages[messages.length - 1] const fileProcessingPromises: Promise[] = [] let toolCall: ToolCall | null = null diff --git a/backend/src/openai-api.ts b/backend/src/openai-api.ts index a7d5deb478..7144fc1ded 100644 --- a/backend/src/openai-api.ts +++ b/backend/src/openai-api.ts @@ -32,7 +32,8 @@ const timeoutPromise = (ms: number) => export async function promptOpenAI( userId: string, messages: OpenAIMessage[], - model: string + model: string, + options: { temperature?: number } = {} ) { const openai = getOpenAI(userId) try { @@ -40,7 +41,7 @@ export async function promptOpenAI( openai.chat.completions.create({ model, messages, - temperature: 0, + temperature: options.temperature || 0, }), timeoutPromise(200000) as Promise, ]) diff --git a/backend/src/system-prompt.ts b/backend/src/system-prompt.ts index 6ad4fcad91..e216255333 100644 --- a/backend/src/system-prompt.ts +++ b/backend/src/system-prompt.ts @@ -56,12 +56,26 @@ ${getResponseFormatPrompt(checkFiles ?? false, files)} return systemPrompt } +export const getCoderPrompt = (fileContext: ProjectFileContext) => { + const truncatedFiles = getTruncatedFilesBasedOnTokenBudget( + fileContext, + 80_000 + ) + return [ + introPrompt, + editingFilesPrompt, + knowledgeFilesPrompt, + getRelevantFilesPromptPart1(fileContext), + getRelevantFilesPromptPart2(fileContext, truncatedFiles), + ].join('\n\n') +} + const introPrompt = ` You are Manny, an expert programmer assistant with extensive knowledge across backend and frontend technologies. You are a strong technical writer that communicates with clarity. You are concise. You produce opinions and code that are as simple as possible while accomplishing their purpose. As Manny, you are friendly, professional, and always eager to help users improve their code and understanding of programming concepts. -You are assisting the user with one particular coding project to which you have full access. You can see the file tree of all the files in the project. You can request to read any set of files to see their full content. You can run terminal commands on the user's computer within the project directory to compile code, run tests, install pakages, and search for relevant code. You will be called on again and again for advice and for direct code changes and other changes to files in this project. +You are assisting the user with one particular coding project to which you have full access. You can see the file tree of all the files in the project. You can request to read any set of files to see their full content. You can run terminal commands on the user's computer within the project directory to compile code, run tests, install packages, and search for relevant code. You will be called on again and again for advice and for direct code changes and other changes to files in this project. If you are unsure about the answer to a user's question, you should say "I don't have enough information to confidently answer your question." If the scope of the change the user is requesting is too large to implement all at once (e.g. requires greater than 750 lines of code), you can tell the user the scope is too big and ask which sub-problem to focus on first. `.trim() From 6caec13813725df0ca6ce19d052e51b9ec36526e Mon Sep 17 00:00:00 2001 From: James Grugett Date: Thu, 12 Sep 2024 11:46:36 -0700 Subject: [PATCH 2/7] Increase timeout --- backend/src/openai-api.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/openai-api.ts b/backend/src/openai-api.ts index 7144fc1ded..f7683e498a 100644 --- a/backend/src/openai-api.ts +++ b/backend/src/openai-api.ts @@ -43,7 +43,7 @@ export async function promptOpenAI( messages, temperature: options.temperature || 0, }), - timeoutPromise(200000) as Promise, + timeoutPromise(1_000_000) as Promise, ]) if ( From 0f35a08a81166fb0aceb6c3106b8caa1e545605f Mon Sep 17 00:00:00 2001 From: James Grugett Date: Thu, 12 Sep 2024 12:28:59 -0700 Subject: [PATCH 3/7] Switch to o1 mini. Also use it to generate patch --- backend/src/code-agent.ts | 21 ++++--- backend/src/generate-patch.ts | 113 +++++++++++++++++++++++++++++++++- 2 files changed, 123 insertions(+), 11 deletions(-) diff --git a/backend/src/code-agent.ts b/backend/src/code-agent.ts index bbd3a99ce6..299cea6dee 100644 --- a/backend/src/code-agent.ts +++ b/backend/src/code-agent.ts @@ -32,21 +32,24 @@ export const codeAgent = async ( content, }, ] as OpenAIMessage[] - console.log('messagesWithContext', messagesWithContext) onResponseChunk('Generating response with o1-preview...\n\n') - const response = await promptOpenAI( - userId, - messagesWithContext, - 'o1-preview', - { temperature: 1 } - ) + const response = await promptOpenAI(userId, messagesWithContext, 'o1-mini', { + temperature: 1, + }) onResponseChunk(response + '\n') console.log('response', response) - - const fileBlocks = parseFileBlocks(response) + const modifiedResponse = response + .split('\n') + .filter((line) => { + !line.includes('```') + }) + .join('\n') + + console.log('modifiedResponse', modifiedResponse) + const fileBlocks = parseFileBlocks(modifiedResponse) const changes = await Promise.all( Object.entries(fileBlocks).map(([filePath, fileBlock]) => processFileBlock(userId, ws, messages, response, filePath, fileBlock) diff --git a/backend/src/generate-patch.ts b/backend/src/generate-patch.ts index 35b966f7d8..8ae8b554e6 100644 --- a/backend/src/generate-patch.ts +++ b/backend/src/generate-patch.ts @@ -52,7 +52,115 @@ And here's a sketch of the changes: ${newContent} \`\`\` -Please produce a patch file based on this change. +Please produce a patch file based on this change. Respond with the patch file only. + +For example: + +Sketch of the changes: + +\`\`\` +import { createInsertSchema, createSelectSchema } from "drizzle-zod"; +import { z } from "zod"; +import models from "./models"; +import { ArticleNodeDataType } from "@/lib/types"; + +// ... (keep all existing code up to the souvenirValidationSchema) + +// Base Souvenir Validation Schema +const baseSouvenirValidationSchema = { + article_id: z.number().int().positive(), + type: ArticleNodeDataType, + created_at: z.date().optional(), +}; + +// Discriminated union for souvenir data based on type +const souvenirDataSchema = z.discriminatedUnion("type", [ + z.object({ + type: z.literal(ArticleNodeDataType.Enum.code), + data: z.object({ + souvenir: z.object({ + steps: z.array(z.string()), + components: z.array(z.object({ + fn: z.string(), + name: z.string(), + })), + srcs: z.array(z.string()).optional(), + }), + }), + }), + // Add other types here as needed +]); + +const souvenirValidationSchema = { + ...baseSouvenirValidationSchema, + ...souvenirDataSchema.shape, +}; + +const souvenirInsertSchema = createInsertSchema( + models.souvenirs, + souvenirValidationSchema +); +const souvenirSelectSchema = createSelectSchema( + models.souvenirs, + souvenirValidationSchema +); + +// ... (keep the rest of the existing code) +\`\`\` + + +Patch: +\`\`\` +diff --git a/apps/ebook-web/db/schemas.ts b/apps/ebook-web/db/schemas.ts +index 0b3b1c3b0..b3b8b0b3b 100644 +--- a/apps/ebook-web/db/schemas.ts ++++ b/apps/ebook-web/db/schemas.ts +@@ -47,23 +47,37 @@ const articleSelectSchema = createSelectSchema( + articleValidationSchema + ); + +-const souvenirValidationSchema = { ++// Base Souvenir Validation Schema ++const baseSouvenirValidationSchema = { + article_id: z.number().int().positive(), + type: ArticleNodeDataType, +- data: z.object({ ++ created_at: z.date().optional(), ++}; ++ ++// Discriminated union for souvenir data based on type ++const souvenirDataSchema = z.discriminatedUnion("type", [ ++ z.object({ ++ type: z.literal(ArticleNodeDataType.Enum.code), ++ data: z.object({ + souvenir: z.object({ + steps: z.array(z.string()), +- components: z.array( +- z.object({ +- fn: z.string(), +- name: z.string(), +- }) +- ), ++ components: z.array(z.object({ ++ fn: z.string(), ++ name: z.string(), ++ })), + srcs: z.array(z.string()).optional(), + }), + }), ++ // Add other types here as needed ++]); ++ ++const souvenirValidationSchema = { ++ ...baseSouvenirValidationSchema, ++ ...souvenirDataSchema.shape, + }; ++ + const souvenirInsertSchema = createInsertSchema( + models.souvenirs, + souvenirValidationSchema +\`\`\` + `.trim() const messages = [ @@ -64,6 +172,7 @@ Please produce a patch file based on this change. return await promptOpenAI( userId, messages, - 'ft:gpt-4o-2024-08-06:manifold-markets:run-1:A4VfZwvz' + 'o1-mini' + // 'ft:gpt-4o-2024-08-06:manifold-markets:run-1:A4VfZwvz' ) } From 66ddbe86cf9bc8b438dd3c2f85423a86fb0eacbe Mon Sep 17 00:00:00 2001 From: Brandon Chen Date: Thu, 12 Sep 2024 23:39:59 -0700 Subject: [PATCH 4/7] fix: change openai response temp to 1, fixed '```' filter issue, added some comments --- backend/src/code-agent.ts | 27 ++++++++++++++++++++++++--- backend/src/generate-patch.ts | 15 +++++++++++++++ backend/src/openai-api.ts | 2 +- 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/backend/src/code-agent.ts b/backend/src/code-agent.ts index 299cea6dee..64763283c7 100644 --- a/backend/src/code-agent.ts +++ b/backend/src/code-agent.ts @@ -7,6 +7,29 @@ import { assert } from 'common/util/object' import { OpenAIMessage, promptOpenAI } from './openai-api' import { processFileBlock } from './main-prompt' +/** + * Handles code-related actions by interacting with the AI assistant to generate and apply code changes. + * + * The `codeAgent` function serves as the primary handler for processing user instructions related to code modifications. + * It leverages the AI assistant to interpret user requests, generate appropriate responses, and apply necessary changes + * to the codebase in a context-aware manner. + * + * Steps involved: + * 1. Constructs a prompt using the system-generated coder prompt and the latest user message. + * 2. Sends the prompt to the OpenAI API to generate a response. + * 3. Processes the AI's response by removing unnecessary markdown syntax. + * 4. Parses the response into file blocks and generates corresponding file changes. + * 5. Applies the generated patches to the relevant files. + * + * @param userId - The unique identifier of the user initiating the code action. + * @param fileContext - An object representing the current context of project files, including their contents. + * @param messages - An array of user and assistant messages exchanged in the current session. + * @param ws - The WebSocket connection instance for real-time communication with the client. + * @param onResponseChunk - A callback function to handle chunks of the AI assistant's response as they are received. + * @returns An object containing the AI assistant's full response and the list of file changes generated. + * + * @throws Will throw an error if the OpenAI API request fails or returns an unexpected response. + */ export const codeAgent = async ( userId: string, fileContext: ProjectFileContext, @@ -43,9 +66,7 @@ export const codeAgent = async ( console.log('response', response) const modifiedResponse = response .split('\n') - .filter((line) => { - !line.includes('```') - }) + .filter((line) => !line.includes('```')) .join('\n') console.log('modifiedResponse', modifiedResponse) diff --git a/backend/src/generate-patch.ts b/backend/src/generate-patch.ts index 8ae8b554e6..8b4cca4063 100644 --- a/backend/src/generate-patch.ts +++ b/backend/src/generate-patch.ts @@ -27,6 +27,21 @@ export async function generatePatch( return updatedPatch } +/** + * Generates a patch file based on the differences between the old and new file contents. + * + * This function analyzes the modifications made to a file by comparing its original content (`oldContent`) + * with the updated content (`newContent`). It leverages the user's message history and the full AI response + * to ensure that the generated patch accurately reflects the intended changes in a context-aware manner. + * + * @param userId - The unique identifier of the user initiating the patch generation. + * @param oldContent - The original content of the file before any changes. + * @param newContent - The updated content of the file after modifications. + * @param filePath - The specific file path where the patch will be applied. + * @param messageHistory - An array of previous messages exchanged, providing context for the changes. + * @param fullResponse - The complete response from the AI, which may include explanations or additional instructions relevant to the patch. + * @returns A string representing the generated patch that can be applied to the original file. + */ const generatePatchPrompt = async ( userId: string, oldContent: string, diff --git a/backend/src/openai-api.ts b/backend/src/openai-api.ts index f7683e498a..0595fa8a5d 100644 --- a/backend/src/openai-api.ts +++ b/backend/src/openai-api.ts @@ -41,7 +41,7 @@ export async function promptOpenAI( openai.chat.completions.create({ model, messages, - temperature: options.temperature || 0, + temperature: options.temperature || 1, }), timeoutPromise(1_000_000) as Promise, ]) From a842553c1ad5ab0e6b6834ac79afbd8f5b7e45e2 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Fri, 13 Sep 2024 09:08:46 -0700 Subject: [PATCH 5/7] Produce patch file directly --- backend/src/code-agent.ts | 18 ++++--- backend/src/main-prompt.ts | 8 +--- backend/src/system-prompt.ts | 91 +++++++++++------------------------- 3 files changed, 41 insertions(+), 76 deletions(-) diff --git a/backend/src/code-agent.ts b/backend/src/code-agent.ts index 64763283c7..e2c78c7a95 100644 --- a/backend/src/code-agent.ts +++ b/backend/src/code-agent.ts @@ -5,7 +5,7 @@ import { parseFileBlocks, ProjectFileContext } from 'common/util/file' import { getCoderPrompt } from './system-prompt' import { assert } from 'common/util/object' import { OpenAIMessage, promptOpenAI } from './openai-api' -import { processFileBlock } from './main-prompt' +import { FileChange } from 'common/actions' /** * Handles code-related actions by interacting with the AI assistant to generate and apply code changes. @@ -37,7 +37,9 @@ export const codeAgent = async ( ws: WebSocket, onResponseChunk: (chunk: string) => void ) => { - const coderPrompt = getCoderPrompt(fileContext) + const coderPrompt = getCoderPrompt(fileContext, { + checkFiles: true, + }) const lastMessage = messages[messages.length - 1] assert(lastMessage.role === 'user', 'Last message must be from user') assert( @@ -58,7 +60,7 @@ export const codeAgent = async ( onResponseChunk('Generating response with o1-preview...\n\n') - const response = await promptOpenAI(userId, messagesWithContext, 'o1-mini', { + const response = await promptOpenAI(userId, messagesWithContext, 'o1-preview', { temperature: 1, }) @@ -71,10 +73,12 @@ export const codeAgent = async ( console.log('modifiedResponse', modifiedResponse) const fileBlocks = parseFileBlocks(modifiedResponse) - const changes = await Promise.all( - Object.entries(fileBlocks).map(([filePath, fileBlock]) => - processFileBlock(userId, ws, messages, response, filePath, fileBlock) - ) + const changes: FileChange[] = await Promise.all( + Object.entries(fileBlocks).map(([filePath, fileBlock]) => ({ + filePath, + content: fileBlock, + type: 'patch', + })) ) console.log('changes', changes) diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index e2ff1e0b7b..13d3190545 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -40,9 +40,7 @@ export async function mainPrompt( let shouldCheckFiles = true if (Object.keys(fileContext.files).length === 0 || O1_ENABLED) { - const system = getSystemPrompt(fileContext, { - checkFiles: true, - }) + const system = getSystemPrompt(fileContext) // If the fileContext.files is empty, use prompts to select files and add them to context. const responseChunk = await updateFileContext( ws, @@ -81,9 +79,7 @@ ${STOP_MARKER} } while (!isComplete && iterationCount < MAX_ITERATIONS) { - const system = getSystemPrompt(fileContext, { - checkFiles: shouldCheckFiles, - }) + const system = getSystemPrompt(fileContext) const messagesWithContinuedMessage = continuedMessages ? [...messages, ...continuedMessages] : messages diff --git a/backend/src/system-prompt.ts b/backend/src/system-prompt.ts index e216255333..83007b8cac 100644 --- a/backend/src/system-prompt.ts +++ b/backend/src/system-prompt.ts @@ -11,14 +11,7 @@ import { debugLog } from './util/debug' import { sortBy, sum } from 'lodash' import { filterObject } from 'common/util/object' -export function getSystemPrompt( - fileContext: ProjectFileContext, - options: { - checkFiles?: boolean - onlyCachePrefix?: boolean - } = {} -) { - const { checkFiles, onlyCachePrefix } = options +export function getSystemPrompt(fileContext: ProjectFileContext) { const truncatedFiles = getTruncatedFilesBasedOnTokenBudget( fileContext, 80_000 @@ -29,44 +22,42 @@ export function getSystemPrompt( { type: 'text' as const, cache_control: { type: 'ephemeral' as const }, - text: ` -${introPrompt} - -${editingFilesPrompt} - -${knowledgeFilesPrompt} - -${toolsPrompt} - -${getProjectFileTreePrompt(fileContext)} - -${getRelevantFilesPromptPart1(fileContext)} -`.trim(), + text: [ + getProjectFileTreePrompt(fileContext), + getRelevantFilesPromptPart1(fileContext), + ].join('\n\n'), }, - !onlyCachePrefix && { + files.length > 0 && { type: 'text' as const, - text: ` -${getRelevantFilesPromptPart2(fileContext, truncatedFiles)} -${getResponseFormatPrompt(checkFiles ?? false, files)} -`.trimEnd(), + text: [getRelevantFilesPromptPart2(fileContext, truncatedFiles)].join( + '\n\n' + ), } ) return systemPrompt } -export const getCoderPrompt = (fileContext: ProjectFileContext) => { +export const getCoderPrompt = ( + fileContext: ProjectFileContext, + options: { + checkFiles?: boolean + } +) => { + const { checkFiles } = options const truncatedFiles = getTruncatedFilesBasedOnTokenBudget( fileContext, 80_000 ) + const files = Object.keys(truncatedFiles) return [ introPrompt, editingFilesPrompt, knowledgeFilesPrompt, getRelevantFilesPromptPart1(fileContext), getRelevantFilesPromptPart2(fileContext, truncatedFiles), + getResponseFormatPrompt(checkFiles ?? false, files), ].join('\n\n') } @@ -80,6 +71,10 @@ You are assisting the user with one particular coding project to which you have If you are unsure about the answer to a user's question, you should say "I don't have enough information to confidently answer your question." If the scope of the change the user is requesting is too large to implement all at once (e.g. requires greater than 750 lines of code), you can tell the user the scope is too big and ask which sub-problem to focus on first. `.trim() +const patchExample = ` +diff --git a/web/components/feed/comment-on-answer.tsx b/web/components/feed/comment-on-answer.tsx\nindex 81027aad0..8b85b91c1 100644\n--- a/web/components/feed/comment-on-answer.tsx\n+++ b/web/components/feed/comment-on-answer.tsx\n@@ -4,22 +4,16 @@ import { Col } from 'web/components/layout/col'\n import { Row } from 'web/components/layout/row'\n import { UserLink } from 'web/components/widgets/user-link'\n import Curve from 'web/lib/icons/comment-curve.svg'\n-import { getAnswerColor, useChartAnswers } from '../charts/contract/choice'\n+import { getAnswerColor } from '../charts/contract/choice'\n import { useDisplayUserByIdOrAnswer } from 'web/hooks/use-user-supabase'\n import { XCircleIcon } from '@heroicons/react/solid'\n import { RelativeTimestamp } from 'web/components/relative-timestamp'\n import { UserHovercard } from '../user/user-hovercard'\n-import { MultiContract } from 'common/contract'\n \n-export function CommentOnAnswer(props: {\n- answer: Answer\n- contract: MultiContract\n- clear?: () => void\n-}) {\n- const { answer, contract, clear } = props\n+export function CommentOnAnswer(props: { answer: Answer; clear?: () => void }) {\n+ const { answer, clear } = props\n \n- const answersArray = useChartAnswers(contract).map((answer) => answer.text)\n- const color = getAnswerColor(answer, answersArray)\n+ const color = getAnswerColor(answer)\n \n return (\n \n +`.trim() + const editingFilesPrompt = ` # Editing files @@ -88,49 +83,20 @@ The user may have edited files since your last change. Please try to notice and -You implement edits by writing out blocks. The user does not need to copy this code to make the edit, the file change is done automatically by another assistant. +You implement edits by writing a patch file within tags, which are automatically applied once written. -To create a new file, simply provide a file block with the file path as an xml attribute and the file contents: -${createFileBlock('path/to/new/file.tsx', '// Entire file contents here')} +Use this format to create or modify files: +${createFileBlock('path/to/file.tsx', patchExample)} -If the file already exists, this will overwrite the file with the new contents. - -Otherwise, be mindful that you are providing instructions on how to modify an existing file. Another assistant will be taking your instructions and then making the actual edit to the file, so it needs to be clear what you are changing. Shorter instructions are also preferred. - -When modifying an existing file, try to excerpt only the section you are actually changing. Use comments like "// ... existing code ..." to indicate where existing code should be preserved: - -${createFileBlock( - 'path/to/existing/file.tsx', - `// ... existing code ... - -function getDesktopNav() { - console.log('I\'ve just edited in this console.log statement') - - // ... existing code ... -} - -// ... existing code ... -` -)} - -Be sure to give enough lines of context around the code you are editing so that the other assistant can make the edit in the correct place. But adding more than 2-3 lines of context is probably unnecessary. - - -Don't forget to add the placeholder comment "// ... existing code ..." between any sections of code you are editing. If you don't, then all the code in between will be deleted! - - -Do not reproduce long continuous sections of the file which are unchanged. Use the placeholder comment "// ... existing code ..." to abbreviate these sections. +Try to make the patch as small as possible. Do not include more than 3 lines of context around each hunk in the patch. Do not include comments you wouldn't want in the final code. For example, do not add comments like "// Add this check" or "// Add this line". -You should not set a file's contents to the current contents of the file, since that is unnecessary work. - Whenever you modify an exported token like a function or class or variable, you should grep to find all references to it before it was renamed (or had its type/parameters changed) and update the references appropriately. If you want to delete or rename a file, run a terminal command. More details below. -Do not write code to the user except when editing files with blocks. - +Do not write code to the user except for the patch within tags. `.trim() @@ -312,13 +278,12 @@ ${gitChanges.lastCommitMessages} Here are some files that were selected to aid in the user request, ordered by most important first: ${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. `.trim() } +// 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. const getResponseFormatPrompt = (checkFiles: boolean, files: string[]) => { let bulletNumber = 1 From aade5fec876fbd9a7aa2a54fb301ccf268080ab8 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Fri, 13 Sep 2024 10:47:48 -0700 Subject: [PATCH 6/7] Tweaks --- backend/src/code-agent.ts | 23 +++++++++++++++++++---- backend/src/openai-api.ts | 2 +- backend/src/system-prompt.ts | 2 +- common/src/util/changes.ts | 2 +- 4 files changed, 22 insertions(+), 7 deletions(-) diff --git a/backend/src/code-agent.ts b/backend/src/code-agent.ts index e2c78c7a95..1c9928e3c8 100644 --- a/backend/src/code-agent.ts +++ b/backend/src/code-agent.ts @@ -47,8 +47,18 @@ export const codeAgent = async ( 'Last user message must be text' ) + const warningPrompt = ` + +Please preserve as much of the existing code, its comments, and its behavior as possible. Make minimal edits to accomplish only the core of what is requested. Then pause to get more instructions from the user. + +`.trim() const infoPrompt = `Please use the above information to answer the user's question:` - const content = [coderPrompt, infoPrompt, lastMessage.content].join('\n\n') + const content = [ + coderPrompt, + warningPrompt, + infoPrompt, + lastMessage.content, + ].join('\n\n') const messagesWithContext = [ ...messages.slice(0, -1), @@ -60,9 +70,14 @@ export const codeAgent = async ( onResponseChunk('Generating response with o1-preview...\n\n') - const response = await promptOpenAI(userId, messagesWithContext, 'o1-preview', { - temperature: 1, - }) + const response = await promptOpenAI( + userId, + messagesWithContext, + 'o1-preview', + { + temperature: 1, + } + ) onResponseChunk(response + '\n') console.log('response', response) diff --git a/backend/src/openai-api.ts b/backend/src/openai-api.ts index 0595fa8a5d..a4d270acb7 100644 --- a/backend/src/openai-api.ts +++ b/backend/src/openai-api.ts @@ -41,7 +41,7 @@ export async function promptOpenAI( openai.chat.completions.create({ model, messages, - temperature: options.temperature || 1, + temperature: options.temperature ?? 1, }), timeoutPromise(1_000_000) as Promise, ]) diff --git a/backend/src/system-prompt.ts b/backend/src/system-prompt.ts index 83007b8cac..35c32375e1 100644 --- a/backend/src/system-prompt.ts +++ b/backend/src/system-prompt.ts @@ -68,7 +68,7 @@ As Manny, you are friendly, professional, and always eager to help users improve You are assisting the user with one particular coding project to which you have full access. You can see the file tree of all the files in the project. You can request to read any set of files to see their full content. You can run terminal commands on the user's computer within the project directory to compile code, run tests, install packages, and search for relevant code. You will be called on again and again for advice and for direct code changes and other changes to files in this project. -If you are unsure about the answer to a user's question, you should say "I don't have enough information to confidently answer your question." If the scope of the change the user is requesting is too large to implement all at once (e.g. requires greater than 750 lines of code), you can tell the user the scope is too big and ask which sub-problem to focus on first. +If you are unsure about the answer to a user's question, you should say "I don't have enough information to confidently answer your question" but give your best suggestion on what to do next and wait for the user to clarify. If the scope of the change the user is requesting is too large to implement all at once (e.g. requires greater than 750 lines of code), you can tell the user the scope is too big and ask which sub-problem to focus on first. `.trim() const patchExample = ` diff --git a/common/src/util/changes.ts b/common/src/util/changes.ts index 7424be932a..278da840f6 100644 --- a/common/src/util/changes.ts +++ b/common/src/util/changes.ts @@ -15,7 +15,7 @@ export function applyChanges(projectRoot: string, changes: FileChanges) { if (type === 'file') { fs.writeFileSync(fullPath, content) } else { - const oldContent = fs.readFileSync(fullPath, 'utf-8') + const oldContent = fileExists ? fs.readFileSync(fullPath, 'utf-8') : '' const newContent = applyPatch(oldContent, content) fs.writeFileSync(fullPath, newContent) } From e24e0b5a2fca1e7243fdc5a34485def079c0da5f Mon Sep 17 00:00:00 2001 From: James Grugett Date: Fri, 13 Sep 2024 11:31:03 -0700 Subject: [PATCH 7/7] Markdown file blocks. Streamline prompting --- backend/src/code-agent.ts | 34 +++++++------------------- backend/src/system-prompt.ts | 40 +++++++++++-------------------- common/src/util/file.ts | 46 ++++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 52 deletions(-) diff --git a/backend/src/code-agent.ts b/backend/src/code-agent.ts index 1c9928e3c8..f05c73cd95 100644 --- a/backend/src/code-agent.ts +++ b/backend/src/code-agent.ts @@ -1,7 +1,7 @@ import { WebSocket } from 'ws' import { Message } from 'common/actions' -import { parseFileBlocks, ProjectFileContext } from 'common/util/file' +import { parseMarkdownPatchBlocks, ProjectFileContext } from 'common/util/file' import { getCoderPrompt } from './system-prompt' import { assert } from 'common/util/object' import { OpenAIMessage, promptOpenAI } from './openai-api' @@ -47,18 +47,8 @@ export const codeAgent = async ( 'Last user message must be text' ) - const warningPrompt = ` - -Please preserve as much of the existing code, its comments, and its behavior as possible. Make minimal edits to accomplish only the core of what is requested. Then pause to get more instructions from the user. - -`.trim() const infoPrompt = `Please use the above information to answer the user's question:` - const content = [ - coderPrompt, - warningPrompt, - infoPrompt, - lastMessage.content, - ].join('\n\n') + const content = [coderPrompt, infoPrompt, lastMessage.content].join('\n\n') const messagesWithContext = [ ...messages.slice(0, -1), @@ -81,20 +71,12 @@ Please preserve as much of the existing code, its comments, and its behavior as onResponseChunk(response + '\n') console.log('response', response) - const modifiedResponse = response - .split('\n') - .filter((line) => !line.includes('```')) - .join('\n') - - console.log('modifiedResponse', modifiedResponse) - const fileBlocks = parseFileBlocks(modifiedResponse) - const changes: FileChange[] = await Promise.all( - Object.entries(fileBlocks).map(([filePath, fileBlock]) => ({ - filePath, - content: fileBlock, - type: 'patch', - })) - ) + const patches = parseMarkdownPatchBlocks(response) + const changes: FileChange[] = patches.map(({ filePath, patch }) => ({ + filePath, + content: patch, + type: 'patch', + })) console.log('changes', changes) diff --git a/backend/src/system-prompt.ts b/backend/src/system-prompt.ts index 35c32375e1..3326b3bcff 100644 --- a/backend/src/system-prompt.ts +++ b/backend/src/system-prompt.ts @@ -1,11 +1,11 @@ import { ProjectFileContext, - createFileBlock, + createMarkdownFileBlock, + createMarkdownPatchBlock, printFileTree, printFileTreeWithTokens, } from 'common/util/file' import { buildArray } from 'common/util/array' -import { STOP_MARKER } from 'common/constants' import { countTokens, countTokensForFiles } from './util/token-counter' import { debugLog } from './util/debug' import { sortBy, sum } from 'lodash' @@ -83,20 +83,18 @@ The user may have edited files since your last change. Please try to notice and -You implement edits by writing a patch file within tags, which are automatically applied once written. +You implement edits by writing patch files within \`\`\` tags, which are automatically applied once written. -Use this format to create or modify files: -${createFileBlock('path/to/file.tsx', patchExample)} +Use this example format to create or modify a file: +${createMarkdownPatchBlock(patchExample)} -Try to make the patch as small as possible. Do not include more than 3 lines of context around each hunk in the patch. +Please create one patch per file changed. Try to make the patch as small as possible. Do not include more than 3 lines of context around each hunk in the patch. Do not include comments you wouldn't want in the final code. For example, do not add comments like "// Add this check" or "// Add this line". Whenever you modify an exported token like a function or class or variable, you should grep to find all references to it before it was renamed (or had its type/parameters changed) and update the references appropriately. If you want to delete or rename a file, run a terminal command. More details below. - -Do not write code to the user except for the patch within tags. `.trim() @@ -115,7 +113,7 @@ If a user corrects you or contradicts you or gives broad advice, you should upda Each knowledge file should develop over time into a concise but rich repository of knowledge about the files within the directory, subdirectories, or the specific file it's associated with. -Make sure you edit knowledge files by using blocks. Do not write out their contents outside of blocks. +Make sure you edit knowledge files by using \`\`\` tags. Do not write out their contents outside of \`\`\` tags. Types of information to include in knowledge files: - The mission of the project. Goals, purpose, and a high-level overview of the project @@ -178,7 +176,7 @@ You can use the run_terminal_command tool to execute shell commands in the user' 4. Running grep to search code to find references or token definitions 5. Performing git operations (e.g., "git status") -Do not use the run_terminal_command tool to create or edit files. You should instead write out blocks for that as detailed above in the block. +Do not use the run_terminal_command tool to create or edit files. You should instead write out \`\`\` tags for that as detailed above in the block. The current working directory will always reset to project root directory for each command. You can only access files within this directory (or sub-directories). @@ -227,7 +225,7 @@ const getRelevantFilesPromptPart1 = (fileContext: ProjectFileContext) => { ${Object.entries(knowledgeFiles) - .map(([path, content]) => createFileBlock(path, content)) + .map(([path, content]) => createMarkdownFileBlock(path, content)) .join('\n')} @@ -249,7 +247,7 @@ const getRelevantFilesPromptPart2 = ( const fileBlocks = Object.entries(truncatedFilesExceptKnowledgeFiles) .map(([filePath, content]) => - createFileBlock(filePath, content ?? '[FILE_DOES_NOT_EXIST]') + createMarkdownFileBlock(filePath, content ?? '[FILE_DOES_NOT_EXIST]') ) .join('\n') @@ -290,10 +288,6 @@ const getResponseFormatPrompt = (checkFiles: boolean, files: string[]) => { return ` # Response format -The goal is to make as few changes as possible to the codebase to address the user's request. Only do what the user has asked for and no more. - -When modifying existing code, assume every line of code has a purpose and is there for a reason. Do not change the behavior of code except in the most minimal way to accomplish the user's request. - Steps: ${ @@ -304,20 +298,14 @@ ${ ${bulletNumber++}. You may edit files to address the user's request and run commands in the terminal. However, if previous two previous commands have failed, you should not run anymore terminal commands. -If the user corrected you or gave feedback and it helped you understand something better, you must edit a knowledge file with a short note that condenses what you learned and what to do next time you so you don't make the same mistake again. Pure documentation of code doesn't need to be added to knowlege. But if the user says use yarn instead of npm, or to use one function instead of another, or to use a certain style, or that you should always write tests, then this is good information to add to a knoweldge file (create the file if it doesn't exist!). To edit a knowledge file, use a block. +Do not write out code to the user except for the patch within \`\`\` tags. -Do not write code except when editing files with blocks. +If the user corrected you or gave feedback and it helped you understand something better, you must edit a knowledge file with a short note that condenses what you learned and what to do next time you so you don't make the same mistake again. Pure documentation of code doesn't need to be added to knowlege. But if the user says use yarn instead of npm, or to use one function instead of another, or to use a certain style, or that you should always write tests, then this is good information to add to a knoweldge file (create the file if it doesn't exist!). -Confine your edits to only what is directly necessary. Preserve the behavior of all existing code. Change only what you must to accomplish the user's request or add to a knowledge file. +Please preserve as much of the existing code, its comments, and its behavior as possible. Make minimal edits to accomplish only the core of what is requested. Then pause to get more instructions from the user. - -Always end your response with the following marker: -${STOP_MARKER} - -This marker helps ensure that your entire response has been received and processed correctly. -If you don't end with this marker, you will automatically be prompted to continue. However, it is good to stop your response with this token so the user can give further guidence. -`.trim() +`.trim() } const getTruncatedFilesBasedOnTokenBudget = ( diff --git a/common/src/util/file.ts b/common/src/util/file.ts index 80a9f0c9e9..5c4ab73046 100644 --- a/common/src/util/file.ts +++ b/common/src/util/file.ts @@ -47,6 +47,23 @@ ${content} ) } +export const createMarkdownPatchBlock = (content: string) => { + return ` +\`\`\`diff +${content} +\`\`\` +`.trim() +} + +export const createMarkdownFileBlock = (filePath: string, content: string) => { + return ` +${filePath} +\`\`\` +${content} +\`\`\` +`.trim() +} + export const fileRegex = /([\s\S]*?)<\/file>/g export const fileWithNoPathRegex = /([\s\S]*?)<\/file>/g @@ -74,6 +91,35 @@ export const parseFileBlocksWithoutPath = (fileBlocks: string) => { return files } +export const parseMarkdownPatchBlocks = (fileBlocks: string) => { + const lines = fileBlocks.split('\n') + const patches: string[] = [] + let currentPatch = '' + for (const line of lines) { + if (line.startsWith('```diff')) { + currentPatch = '' + } else if (line.startsWith('```')) { + console.log('currentPatch', currentPatch) + patches.push(currentPatch) + currentPatch = '' + } else { + currentPatch += line + '\n' + } + } + const patchWithFilePath = patches.map((patch) => { + const filePath = patch.match(/^\s*diff --git a\/(.+?)\s/m)?.[1] + console.log('filePath', filePath) + if (!filePath) { + throw new Error('Invalid patch') + } + return { + filePath, + patch, + } + }) + return patchWithFilePath +} + export function printFileTree( nodes: FileTreeNode[], depth: number = 0