From bed741aa8dd6299d8d0446cfe23e01d30dfed802 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Thu, 10 Oct 2024 13:21:21 -0700 Subject: [PATCH 01/12] Add plan requirement check for user requests This commit introduces a new feature to determine if a user's request requires a plan before processing. It adds a new file 'check-plan-required.ts' with a function to analyze the request and updates 'main-prompt.ts' to integrate this check into the existing workflow. The plan requirement is based on complexity, number of steps, and verification needs. --- backend/src/check-plan-required.ts | 42 ++++++++++++++++++++++++++++++ backend/src/main-prompt.ts | 19 ++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 backend/src/check-plan-required.ts diff --git a/backend/src/check-plan-required.ts b/backend/src/check-plan-required.ts new file mode 100644 index 0000000000..139d4330a0 --- /dev/null +++ b/backend/src/check-plan-required.ts @@ -0,0 +1,42 @@ +import { Message } from 'common/actions' +import { System } from './claude' +import { promptClaude } from './claude' +import { claudeModels } from 'common/constants' + +export async function checkIfPlanRequired( + messages: Message[], + system: System, + clientSessionId: string, + fingerprintId: string, + userInputId: string, + userId?: string +): Promise { + const planCheckPrompt = ` +Given the user's request, determine if it requires a plan. A plan is needed if the request: +1. Requires at least 3 steps to complete +2. Is complex in nature +3. Requires verification of multiple parts + +Analyze the request and respond with just the string: +"[REQUIRES_PLAN]" if a plan is needed, or +"[PLAN_UNNECESSARY]" if a plan is not needed. + +Do not include any other text. + +User request: ${messages[messages.length - 1].content} +`.trim() + + const response = await promptClaude( + [...messages, { role: 'user', content: planCheckPrompt }], + { + model: claudeModels.sonnet, + system, + clientSessionId, + fingerprintId, + userInputId, + userId, + } + ) + + return response.trim() === '[REQUIRES_PLAN]' +} diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index b0bd3a58ea..1ea078bd95 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -18,6 +18,7 @@ import { processStreamWithTags } from './process-stream' import { generateKnowledgeFiles } from './generate-knowledge-files' import { countTokens } from './util/token-counter' import { logger } from './util/logger' +import { checkIfPlanRequired } from './check-plan-required' /** * Prompt claude, handle tool calls, and generate file changes. @@ -38,10 +39,20 @@ export async function mainPrompt( const fileProcessingPromises: Promise[] = [] const lastMessage = messages[messages.length - 1] const messagesWithoutLastMessage = messages.slice(0, -1) + let planRequired = false if (!didClientUseTool(lastMessage)) { // Step 1: Read more files. const system = getSearchSystemPrompt(fileContext) + + const planRequiredPromise = checkIfPlanRequired( + messages, + system, + clientSessionId, + fingerprintId, + userInputId, + userId + ) // If the fileContext.files is empty, use prompts to select files and add them to context. const responseChunk = await updateFileContext( ws, @@ -67,6 +78,14 @@ export async function mainPrompt( userId ) } + + planRequired = await planRequiredPromise + if (planRequired) { + // If a plan is required, you can add logic here to generate and execute a plan + // For now, we'll just log that a plan is required + logger.info('A plan is required for this request') + // You can add more logic here to handle plan generation and execution + } } const hasKnowledgeFiles = Object.keys(fileContext.knowledgeFiles).length > 0 From 44c12f23f1f5966242c6f8ddd1c1195e415ccae6 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Thu, 10 Oct 2024 13:27:09 -0700 Subject: [PATCH 02/12] Add plan generation for complex requests This commit introduces a new feature to generate and execute plans for complex user requests. Key changes include: - Add generatePlan function to create detailed, step-by-step plans - Integrate plan generation into main-prompt.ts workflow - Update knowledge.md with information about the new feature - Enhance request handling to break down complex tasks systematically - Implement real-time streaming of generated plans to the client This feature improves the system's ability to handle complex requests with proper verification steps, enhancing overall functionality. --- backend/knowledge.md | 17 +++++++++++ backend/src/generate-plan.ts | 58 ++++++++++++++++++++++++++++++++++++ backend/src/main-prompt.ts | 15 +++++++++- 3 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 backend/src/generate-plan.ts diff --git a/backend/knowledge.md b/backend/knowledge.md index 79bc8170f6..7f1963e46e 100644 --- a/backend/knowledge.md +++ b/backend/knowledge.md @@ -194,3 +194,20 @@ This project uses Bun for testing instead of Jest. When writing tests, keep the - Bun's test API is similar to Jest's, but there are some differences in implementation. - When mocking methods, use `mock(object.method)` instead of Jest's `jest.spyOn(object, 'method')`. - Bun's `mock` function expects 0-1 arguments, not 2 like Jest's `spyOn`. + +## Plan Generation for Complex Requests + +The backend now includes a feature to generate plans for complex user requests. This feature is designed to break down complex tasks into manageable steps and include appropriate verification processes. + +Key components: +1. `check-plan-required.ts`: Determines if a plan is needed based on the complexity of the user's request. +2. `generate-plan.ts`: Creates a detailed plan with numbered steps and verification processes. +3. `main-prompt.ts`: Integrates plan generation into the main request handling flow. + +The plan generation process: +1. `main-prompt.ts` calls `checkIfPlanRequired()` to determine if a plan is needed. +2. If a plan is required, `generatePlan()` is called to create a detailed plan. +3. The generated plan is streamed to the client using the `onResponseChunk` function, providing real-time updates. +4. The plan includes numbered steps, sub-steps, and appropriate verification steps (e.g., running type checkers, creating and running unit tests). + +This feature enhances the system's ability to handle complex requests systematically and with proper verification. When working on request handling or AI prompts, consider whether the request might benefit from this plan generation feature. diff --git a/backend/src/generate-plan.ts b/backend/src/generate-plan.ts new file mode 100644 index 0000000000..663d3fe654 --- /dev/null +++ b/backend/src/generate-plan.ts @@ -0,0 +1,58 @@ +import { Message } from 'common/actions' +import { System } from './claude' +import { promptClaudeStream } from './claude' +import { claudeModels } from 'common/constants' + +export async function generatePlan( + messages: Message[], + system: System, + clientSessionId: string, + fingerprintId: string, + userInputId: string, + onResponseChunk: (chunk: string) => void, + userId?: string +): Promise { + const planGenerationPrompt = ` +Based on the user's request, create a detailed plan with numbered steps to accomplish the task. Include appropriate verification steps where necessary, such as running type checkers, creating and running unit tests, or any other relevant checks. + +Please follow these guidelines: +1. Break down the task into clear, actionable steps. +2. Include verification steps where appropriate. +3. Consider potential edge cases or complications. +4. If any step requires significant changes, break it down further. +5. Aim for a comprehensive plan that covers all aspects of the request. + +User request: ${messages[messages.length - 1].content} + +Please provide the plan in the following format: +1. [First step] +2. [Second step] + a. [Sub-step if necessary] + b. [Another sub-step if necessary] +3. [Verification step (if applicable)] +4. [Next step] +... + +Ensure that the plan is thorough and covers all necessary aspects of the user's request. +` + + let fullPlan = '' + const stream = promptClaudeStream( + [...messages, { role: 'user', content: planGenerationPrompt }], + { + model: claudeModels.sonnet, + system, + clientSessionId, + fingerprintId, + userInputId, + userId, + } + ) + + for await (const chunk of stream) { + fullPlan += chunk + onResponseChunk(chunk) + } + + return fullPlan.trim() +} diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index 1ea078bd95..6ede0affff 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -19,6 +19,7 @@ import { generateKnowledgeFiles } from './generate-knowledge-files' import { countTokens } from './util/token-counter' import { logger } from './util/logger' import { checkIfPlanRequired } from './check-plan-required' +import { generatePlan } from './generate-plan' /** * Prompt claude, handle tool calls, and generate file changes. @@ -84,7 +85,19 @@ export async function mainPrompt( // If a plan is required, you can add logic here to generate and execute a plan // For now, we'll just log that a plan is required logger.info('A plan is required for this request') - // You can add more logic here to handle plan generation and execution + onResponseChunk("\n\nI've created a plan to address your request:\n\n") + const plan = await generatePlan( + messages, + system, + clientSessionId, + fingerprintId, + userInputId, + onResponseChunk, + userId + ) + logger.info({ plan }, 'Generated plan') + fullResponse += `\n\nI've created a plan to address your request:\n\n${plan}\n\nI'll now proceed with executing this plan step by step.` + onResponseChunk("\n\nI'll now proceed with executing this plan step by step.") } } From e9977692af78047042b2b74180e69b79c5085288 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Thu, 10 Oct 2024 13:36:52 -0700 Subject: [PATCH 03/12] Improve plan generation and response handling This commit enhances the plan generation process and optimizes response handling in the main prompt function. Key changes include: - Update plan generation prompt to start with user notification - Recreate system prompt before plan generation for up-to-date context - Optimize warm cache call to only fire when no plan is required - Increase assistant message threshold for pausing from 3 to 10 - Update knowledge.md with new implementation details These changes improve the system's ability to handle complex requests and provide more efficient caching and response generation. --- backend/knowledge.md | 5 +++++ backend/src/generate-plan.ts | 2 ++ backend/src/main-prompt.ts | 33 +++++++++++++++------------------ 3 files changed, 22 insertions(+), 18 deletions(-) diff --git a/backend/knowledge.md b/backend/knowledge.md index 7f1963e46e..c3574026c2 100644 --- a/backend/knowledge.md +++ b/backend/knowledge.md @@ -210,4 +210,9 @@ The plan generation process: 3. The generated plan is streamed to the client using the `onResponseChunk` function, providing real-time updates. 4. The plan includes numbered steps, sub-steps, and appropriate verification steps (e.g., running type checkers, creating and running unit tests). +Important implementation details: +- The system prompt for plan generation is recreated to ensure it has the most up-to-date context. +- The warm cache call is only fired if no plan was required, optimizing performance by avoiding unnecessary caching when a plan is generated. + This feature enhances the system's ability to handle complex requests systematically and with proper verification. When working on request handling or AI prompts, consider whether the request might benefit from this plan generation feature. + diff --git a/backend/src/generate-plan.ts b/backend/src/generate-plan.ts index 663d3fe654..23f9d07b3c 100644 --- a/backend/src/generate-plan.ts +++ b/backend/src/generate-plan.ts @@ -34,6 +34,8 @@ Please provide the plan in the following format: ... Ensure that the plan is thorough and covers all necessary aspects of the user's request. + +Please start by telling the user you will create a plan to address their request. ` let fullPlan = '' diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index 6ede0affff..4f73db6dff 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -68,36 +68,33 @@ export async function mainPrompt( if (responseChunk !== null) { onResponseChunk(responseChunk.readFilesMessage) fullResponse += `\n\n${responseChunk.toolCallMessage}\n\n${responseChunk.readFilesMessage}` - - // Prompt cache the new files. - const system = getSearchSystemPrompt(fileContext) - warmCacheForRequestRelevantFiles( - system, - clientSessionId, - fingerprintId, - userInputId, - userId - ) } + const updatedSystem = getSearchSystemPrompt(fileContext) + planRequired = await planRequiredPromise + if (planRequired) { - // If a plan is required, you can add logic here to generate and execute a plan - // For now, we'll just log that a plan is required - logger.info('A plan is required for this request') - onResponseChunk("\n\nI've created a plan to address your request:\n\n") const plan = await generatePlan( messages, - system, + updatedSystem, clientSessionId, fingerprintId, userInputId, onResponseChunk, userId ) + fullResponse += plan logger.info({ plan }, 'Generated plan') - fullResponse += `\n\nI've created a plan to address your request:\n\n${plan}\n\nI'll now proceed with executing this plan step by step.` - onResponseChunk("\n\nI'll now proceed with executing this plan step by step.") + } else { + // Prompt cache the new files. + warmCacheForRequestRelevantFiles( + updatedSystem, + clientSessionId, + fingerprintId, + userInputId, + userId + ) } } @@ -130,7 +127,7 @@ export async function mainPrompt( const numAssistantMessages = messages .slice(lastUserMessageIndex) .filter((message) => message.role === 'assistant').length - const shouldPause = numAssistantMessages >= 3 + const shouldPause = numAssistantMessages >= 10 if (shouldPause) { const response = `\nI'll pause to get more instructions from the user.\n` onResponseChunk(response) From 54cd42dba7b31280d16777c8f0c51612c7b93c65 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Thu, 10 Oct 2024 13:50:10 -0700 Subject: [PATCH 04/12] Improve plan requirement check and add logging This commit enhances the checkIfPlanRequired function by: - Changing the check to use 'includes' instead of exact match - Adding logging to capture the response and decision - Importing the logger utility These changes will improve reliability and debugging capabilities. --- backend/src/check-plan-required.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/backend/src/check-plan-required.ts b/backend/src/check-plan-required.ts index 139d4330a0..95bdd5cd6b 100644 --- a/backend/src/check-plan-required.ts +++ b/backend/src/check-plan-required.ts @@ -2,6 +2,7 @@ import { Message } from 'common/actions' import { System } from './claude' import { promptClaude } from './claude' import { claudeModels } from 'common/constants' +import { logger } from './util/logger' export async function checkIfPlanRequired( messages: Message[], @@ -38,5 +39,8 @@ User request: ${messages[messages.length - 1].content} } ) - return response.trim() === '[REQUIRES_PLAN]' + const requiresPlan = response.trim().includes('[REQUIRES_PLAN]') + logger.info({ response, requiresPlan }, 'Plan check response') + + return requiresPlan } From 4fc81b31d19cff5fc81a372821a206a0eaa94e51 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Thu, 10 Oct 2024 14:09:40 -0700 Subject: [PATCH 05/12] Implement planning system for complex tasks This commit introduces a planning system for handling complex tasks: - Add Planning System section to knowledge.md - Update generate-plan.ts to use STOP_MARKER - Modify main-prompt.ts to remove STOP_MARKER from plan - Add planningPrompt to system-prompt.ts The planning system allows for structured implementation of multi-step tasks, providing clear checkpoints for progress tracking. --- backend/knowledge.md | 16 ++++++++++++++++ backend/src/generate-plan.ts | 4 ++-- backend/src/main-prompt.ts | 2 +- backend/src/system-prompt.ts | 24 ++++++++++++++++++++++++ 4 files changed, 43 insertions(+), 3 deletions(-) diff --git a/backend/knowledge.md b/backend/knowledge.md index c3574026c2..7cc45dab74 100644 --- a/backend/knowledge.md +++ b/backend/knowledge.md @@ -16,6 +16,7 @@ This document provides an overview of the Manicode backend architecture, key com 10. [Security Considerations](#security-considerations) 11. [TODO List](#todo-list) 12. [Automatic URL Detection and Scraping](#automatic-url-detection-and-scraping) +13. [Planning System](#planning-system) ## Architecture Overview @@ -216,3 +217,18 @@ Important implementation details: This feature enhances the system's ability to handle complex requests systematically and with proper verification. When working on request handling or AI prompts, consider whether the request might benefit from this plan generation feature. +## Planning System + +The agent system prompt now includes a section explaining the planning process. Key points: + +- The assistant is given a plan to implement for complex tasks. +- The assistant should implement one or more steps from the plan. +- After completing steps, the assistant reports progress using a specific format: + - Example: [STEP 1 COMPLETE] or [STEPS 2-4 COMPLETE] +- The progress report should not include the end token "[END]". + +This planning system allows for more structured and trackable task implementation, especially for complex requests. It provides clear checkpoints for both the assistant and the user to understand the progress of a given task. + +When implementing features or fixing bugs, consider whether the task would benefit from this structured planning approach, particularly for multi-step or complex changes to the codebase. + + diff --git a/backend/src/generate-plan.ts b/backend/src/generate-plan.ts index 23f9d07b3c..cfb6ec49a4 100644 --- a/backend/src/generate-plan.ts +++ b/backend/src/generate-plan.ts @@ -1,7 +1,7 @@ import { Message } from 'common/actions' import { System } from './claude' import { promptClaudeStream } from './claude' -import { claudeModels } from 'common/constants' +import { claudeModels, STOP_MARKER } from 'common/constants' export async function generatePlan( messages: Message[], @@ -35,7 +35,7 @@ Please provide the plan in the following format: Ensure that the plan is thorough and covers all necessary aspects of the user's request. -Please start by telling the user you will create a plan to address their request. +Please start by telling the user you will create a plan to address their request. Finish your message with "${STOP_MARKER}". ` let fullPlan = '' diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index 4f73db6dff..a590718115 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -84,7 +84,7 @@ export async function mainPrompt( onResponseChunk, userId ) - fullResponse += plan + fullResponse += plan.replaceAll(STOP_MARKER, '') logger.info({ plan }, 'Generated plan') } else { // Prompt cache the new files. diff --git a/backend/src/system-prompt.ts b/backend/src/system-prompt.ts index d6b8d57ba5..16e7d4fbce 100644 --- a/backend/src/system-prompt.ts +++ b/backend/src/system-prompt.ts @@ -74,6 +74,7 @@ export const getAgentSystemPrompt = ( editingFilesPrompt, knowledgeFilesPrompt, toolsPrompt, + planningPrompt, // For large projects, don't include file tree in agent context. projectFileTreePrompt.length < 40_000 ? projectFileTreePrompt : null, getRelevantFilesPromptPart1(fileContext) @@ -112,6 +113,29 @@ 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 planningPrompt = ` +# Planning and Implementation + +For complex tasks, you will be given a plan to implement. This plan will consist of numbered steps, and may include sub-steps. Your job is to implement these steps in order. + +When implementing the plan: +1. Focus on one or more steps at a time. +2. Make the necessary code changes to implement each step. +3. Do not be afraid to deviate from the plan where it makes sense to do so. If you do, please explain how you are deviating from the plan. +4. After completing one or more steps, indicate which steps you've completed using the format: "[STEP X COMPLETE]" or "[STEPS X-Y COMPLETE]". +5. Do not write any text after you signaled you completed some step(s). In particular, do not write "${STOP_MARKER}". + +Example: +After implementing steps 1 and 2 of a plan, you would write: +[STEPS 1-2 COMPLETE] + +Then stop. Do not output the "${STOP_MARKER}" marker. This helps track progress and allows for easier review of your work. + +If the plan is complete or you cannot make further progress on the plan, then at that point you should write "${STOP_MARKER}". + +Remember to be thorough but concise in your implementations, and always adhere to the project's coding standards and best practices. +`.trim() + const editingFilesPrompt = ` # Editing files From c537400bbc8b621cd09628446f5fa59c18e5ef0f Mon Sep 17 00:00:00 2001 From: James Grugett Date: Thu, 10 Oct 2024 14:19:52 -0700 Subject: [PATCH 06/12] Refine plan generation and response formatting Improve plan generation by adding stop marker to plan format Update main prompt to handle plan-based responses Adjust system prompt for conditional stop marker usage --- backend/src/generate-plan.ts | 3 ++- backend/src/main-prompt.ts | 18 +++++++++++------- backend/src/system-prompt.ts | 2 +- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/backend/src/generate-plan.ts b/backend/src/generate-plan.ts index cfb6ec49a4..68b47c2265 100644 --- a/backend/src/generate-plan.ts +++ b/backend/src/generate-plan.ts @@ -32,10 +32,11 @@ Please provide the plan in the following format: 3. [Verification step (if applicable)] 4. [Next step] ... +End the plan with "${STOP_MARKER}". Ensure that the plan is thorough and covers all necessary aspects of the user's request. -Please start by telling the user you will create a plan to address their request. Finish your message with "${STOP_MARKER}". +Please start by telling the user you will create a plan to address their request. ` let fullPlan = '' diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index a590718115..23a5a95183 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -20,6 +20,7 @@ import { countTokens } from './util/token-counter' import { logger } from './util/logger' import { checkIfPlanRequired } from './check-plan-required' import { generatePlan } from './generate-plan' +import { buildArray } from 'common/util/array' /** * Prompt claude, handle tool calls, and generate file changes. @@ -75,6 +76,7 @@ export async function mainPrompt( planRequired = await planRequiredPromise if (planRequired) { + onResponseChunk('\n\n') const plan = await generatePlan( messages, updatedSystem, @@ -84,7 +86,7 @@ export async function mainPrompt( onResponseChunk, userId ) - fullResponse += plan.replaceAll(STOP_MARKER, '') + fullResponse += plan.replaceAll(STOP_MARKER, '').trim() logger.info({ plan }, 'Generated plan') } else { // Prompt cache the new files. @@ -150,15 +152,17 @@ export async function mainPrompt( if (lastMessage.role === 'user' && typeof lastMessage.content === 'string') { newLastMessage = { ...lastMessage, - content: `${lastMessage.content} - - + content: buildArray( + lastMessage.content, + ` 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. - - +`, + !planRequired && + ` Always end your response with the following marker: ${STOP_MARKER} -`, +` + ).join('\n\n'), } } diff --git a/backend/src/system-prompt.ts b/backend/src/system-prompt.ts index 16e7d4fbce..ffc2f15b48 100644 --- a/backend/src/system-prompt.ts +++ b/backend/src/system-prompt.ts @@ -415,7 +415,7 @@ Whenever you modify an exported token like a function or class or variable, you 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. -Always end your response with the following marker: +Always end your response with the following marker, unless you are on an intermediate step of a plan: ${STOP_MARKER} This marker helps ensure that your entire response has been received and processed correctly. From 7cd47f2bff312fde76f624ad2775f54a2fc6e69b Mon Sep 17 00:00:00 2001 From: James Grugett Date: Thu, 10 Oct 2024 14:47:37 -0700 Subject: [PATCH 07/12] Implement plan execution and markers This commit introduces plan execution functionality and adds new markers for plan start and stop. It modifies the main prompt logic to handle plan execution, updates the generate-plan function, and adds new constants for plan markers. These changes improve the structure and flow of plan-based interactions. --- backend/src/generate-plan.ts | 1 - backend/src/main-prompt.ts | 38 ++++++++++++++++++++++++++++-------- common/src/constants.ts | 2 ++ 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/backend/src/generate-plan.ts b/backend/src/generate-plan.ts index 68b47c2265..059e27e17f 100644 --- a/backend/src/generate-plan.ts +++ b/backend/src/generate-plan.ts @@ -32,7 +32,6 @@ Please provide the plan in the following format: 3. [Verification step (if applicable)] 4. [Next step] ... -End the plan with "${STOP_MARKER}". Ensure that the plan is thorough and covers all necessary aspects of the user's request. diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index 23a5a95183..88b403cc78 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -5,7 +5,12 @@ import { promptClaudeStream } from './claude' import { ProjectFileContext } from 'common/util/file' import { didClientUseTool } from 'common/util/tools' import { getSearchSystemPrompt, getAgentSystemPrompt } from './system-prompt' -import { STOP_MARKER, TOOL_RESULT_MARKER } from 'common/constants' +import { + PLAN_START_MARKER, + PLAN_STOP_MARKER, + STOP_MARKER, + TOOL_RESULT_MARKER, +} from 'common/constants' import { FileChange, Message } from 'common/actions' import { ToolCall } from 'common/actions' import { requestFiles, requestFile } from './websockets/websocket-action' @@ -36,12 +41,16 @@ export async function mainPrompt( userId?: string ) { let fullResponse = '' + let continuedMessages: Message[] = fullResponse + ? [{ role: 'assistant', content: fullResponse }] + : [] let genKnowledgeFilesPromise: Promise[]> = Promise.resolve([]) const fileProcessingPromises: Promise[] = [] const lastMessage = messages[messages.length - 1] const messagesWithoutLastMessage = messages.slice(0, -1) let planRequired = false + const isPlanInProgress = false if (!didClientUseTool(lastMessage)) { // Step 1: Read more files. @@ -87,6 +96,17 @@ export async function mainPrompt( userId ) fullResponse += plan.replaceAll(STOP_MARKER, '').trim() + fullResponse += `\n\n${PLAN_START_MARKER}` + continuedMessages = [ + { + role: 'assistant', + content: fullResponse, + }, + { + role: 'user', + content: 'Please execute the plan.', + }, + ] logger.info({ plan }, 'Generated plan') } else { // Prompt cache the new files. @@ -141,9 +161,6 @@ export async function mainPrompt( } let toolCall: ToolCall | null = null - let continuedMessages: Message[] = fullResponse - ? [{ role: 'assistant', content: fullResponse }] - : [] let isComplete = false let iterationCount = 0 const MAX_ITERATIONS = 10 @@ -155,10 +172,13 @@ export async function mainPrompt( content: buildArray( lastMessage.content, ` -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. +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.${planRequired ? '' : 'Then pause to get more instructions from the user.'} `, - !planRequired && - ` + planRequired + ? ` + When the plan is complete, end your response with the following marker: ${PLAN_STOP_MARKER} +` + : ` Always end your response with the following marker: ${STOP_MARKER} ` @@ -326,7 +346,9 @@ ${STOP_MARKER} }, { role: 'user', - content: `You got cut off, but please continue from the very next line of your response. Do not repeat anything you have just said. Just continue as if there were no interruption from the very last character of your last response. (Alternatively, just end your response with the following marker if you were done generating and want to allow the user to give further guidance: ${STOP_MARKER})`, + content: planRequired + ? 'Please continue to execute the plan' + : `You got cut off, but please continue from the very next line of your response. Do not repeat anything you have just said. Just continue as if there were no interruption from the very last character of your last response. (Alternatively, just end your response with the following marker if you were done generating and want to allow the user to give further guidance: ${STOP_MARKER})`, }, ] } diff --git a/common/src/constants.ts b/common/src/constants.ts index c0749d29a7..b191eff422 100644 --- a/common/src/constants.ts +++ b/common/src/constants.ts @@ -1,4 +1,6 @@ export const STOP_MARKER = '[' + 'END]' +export const PLAN_STOP_MARKER = '[' + 'PLAN_END]' +export const PLAN_START_MARKER = '[' + 'PLAN_START]' export const FIND_FILES_MARKER = '[' + 'FIND_FILES_PLEASE]' export const TOOL_RESULT_MARKER = '[' + 'TOOL_RESULT]' From f7892653496df67271892c1250edaedd8a7189de Mon Sep 17 00:00:00 2001 From: James Grugett Date: Thu, 10 Oct 2024 15:35:29 -0700 Subject: [PATCH 08/12] Improve plan execution and reduce scope This commit enhances the plan generation and execution process: - Update generate-plan.ts to focus on minimal necessary steps - Modify main-prompt.ts to handle continuous plan execution - Adjust client.ts and tool-handlers.ts to support plan continuation - Refine logic for determining if a plan is in progress These changes aim to make the planning process more efficient and focused, while allowing for seamless execution of multi-step plans. --- backend/src/generate-plan.ts | 13 ++++++----- backend/src/main-prompt.ts | 45 ++++++++++++++++++++++++++++-------- npm-app/src/client.ts | 5 +++- npm-app/src/tool-handlers.ts | 1 + 4 files changed, 47 insertions(+), 17 deletions(-) diff --git a/backend/src/generate-plan.ts b/backend/src/generate-plan.ts index 059e27e17f..d1c2daa806 100644 --- a/backend/src/generate-plan.ts +++ b/backend/src/generate-plan.ts @@ -1,7 +1,7 @@ import { Message } from 'common/actions' import { System } from './claude' import { promptClaudeStream } from './claude' -import { claudeModels, STOP_MARKER } from 'common/constants' +import { claudeModels } from 'common/constants' export async function generatePlan( messages: Message[], @@ -16,11 +16,12 @@ export async function generatePlan( Based on the user's request, create a detailed plan with numbered steps to accomplish the task. Include appropriate verification steps where necessary, such as running type checkers, creating and running unit tests, or any other relevant checks. Please follow these guidelines: -1. Break down the task into clear, actionable steps. -2. Include verification steps where appropriate. -3. Consider potential edge cases or complications. -4. If any step requires significant changes, break it down further. -5. Aim for a comprehensive plan that covers all aspects of the request. +1. Reduce the scope of the plan to the minimum necessary to accomplish the task. Try to avoid unnecessary steps and do not modify more files or run more terminal commands than absolutely necessary. +2. Break down the task into clear, actionable steps. +3. Include verification steps where appropriate. +4. Consider potential edge cases or complications. +5. If any step requires significant changes, break it down further. +6. Aim for a comprehensive plan that covers all aspects of the request. User request: ${messages[messages.length - 1].content} diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index 88b403cc78..b8fd5d022b 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -49,10 +49,9 @@ export async function mainPrompt( const fileProcessingPromises: Promise[] = [] const lastMessage = messages[messages.length - 1] const messagesWithoutLastMessage = messages.slice(0, -1) - let planRequired = false - const isPlanInProgress = false + let isPlanInProgress = checkIfPlanInProgress(messages) - if (!didClientUseTool(lastMessage)) { + if (!didClientUseTool(lastMessage) && !isPlanInProgress) { // Step 1: Read more files. const system = getSearchSystemPrompt(fileContext) @@ -82,7 +81,7 @@ export async function mainPrompt( const updatedSystem = getSearchSystemPrompt(fileContext) - planRequired = await planRequiredPromise + const planRequired = await planRequiredPromise if (planRequired) { onResponseChunk('\n\n') @@ -108,6 +107,7 @@ export async function mainPrompt( }, ] logger.info({ plan }, 'Generated plan') + isPlanInProgress = true } else { // Prompt cache the new files. warmCacheForRequestRelevantFiles( @@ -172,11 +172,11 @@ export async function mainPrompt( content: buildArray( lastMessage.content, ` -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.${planRequired ? '' : 'Then pause to get more instructions from the user.'} +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.${isPlanInProgress ? '' : ' Then pause to get more instructions from the user.'} `, - planRequired + isPlanInProgress ? ` - When the plan is complete, end your response with the following marker: ${PLAN_STOP_MARKER} + You should attempt to execute the entire plan.When the plan is complete or it is hard to make progress, end your response with the following marker: ${PLAN_STOP_MARKER} ` : ` Always end your response with the following marker: @@ -300,6 +300,10 @@ ${STOP_MARKER} if (foundEndOfResponse) { fullResponse += '\n[END]' } + isPlanInProgress = checkIfPlanInProgress([ + ...messages, + { role: 'assistant', content: fullResponse }, + ]) const maybeToolCall = toolCall as ToolCall | null @@ -331,9 +335,18 @@ ${STOP_MARKER} } else if (maybeToolCall !== null) { isComplete = true logger.debug(maybeToolCall, 'tool call') - } else if (fullResponse.includes(STOP_MARKER)) { + } else if (isPlanInProgress) { + toolCall = { + id: Math.random().toString(36).slice(2), + name: 'continue_plan', + input: {}, + } + isComplete = true + } else if ( + fullResponse.includes(STOP_MARKER) || + fullResponse.endsWith(PLAN_STOP_MARKER) + ) { isComplete = true - fullResponse = fullResponse.replace(STOP_MARKER, '') logger.debug('Reached STOP_MARKER') } else { logger.debug('Continuing to generate') @@ -346,7 +359,7 @@ ${STOP_MARKER} }, { role: 'user', - content: planRequired + content: isPlanInProgress ? 'Please continue to execute the plan' : `You got cut off, but please continue from the very next line of your response. Do not repeat anything you have just said. Just continue as if there were no interruption from the very last character of your last response. (Alternatively, just end your response with the following marker if you were done generating and want to allow the user to give further guidance: ${STOP_MARKER})`, }, @@ -376,6 +389,18 @@ ${STOP_MARKER} } } +function checkIfPlanInProgress(messages: Message[]): boolean { + const messagesString = JSON.stringify(messages) + const lastStartMarkerIndex = messagesString.lastIndexOf(PLAN_START_MARKER) + const lastStopMarkerIndex = messagesString.lastIndexOf(PLAN_STOP_MARKER) + + if (lastStartMarkerIndex === -1 && lastStopMarkerIndex === -1) { + return false + } + + return lastStartMarkerIndex > lastStopMarkerIndex +} + function getRelevantFileInfoMessage(filePaths: string[]) { const readFilesMessage = `Reading the following files...${filePaths.join(', ')}` const toolCallMessage = `Please find the files relevant to the user request` diff --git a/npm-app/src/client.ts b/npm-app/src/client.ts index e561444467..af78c23747 100644 --- a/npm-app/src/client.ts +++ b/npm-app/src/client.ts @@ -112,7 +112,10 @@ export class Client { const content = await handler(input, id) const toolResultMessage: Message = { role: 'user', - content: `${TOOL_RESULT_MARKER}\n${content}`, + content: `${TOOL_RESULT_MARKER}\n${content}`.replace( + 'continue_plan', + '' + ), } this.chatStorage.addMessage( this.chatStorage.getCurrentChat(), diff --git a/npm-app/src/tool-handlers.ts b/npm-app/src/tool-handlers.ts index 2a48c9f1ca..b4e2e8b423 100644 --- a/npm-app/src/tool-handlers.ts +++ b/npm-app/src/tool-handlers.ts @@ -135,4 +135,5 @@ export const toolHandlers: Record = { search_manifold_markets: handleSearchManifoldMarkets, run_terminal_command: ((input, id) => handleRunTerminalCommand(input, id, 'assistant')) as ToolHandler, + continue_plan: () => Promise.resolve('Please continue executing the plan.'), } From efbb22645d9faa10cce0099c43f4e2321df29a80 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Thu, 10 Oct 2024 16:01:55 -0700 Subject: [PATCH 09/12] Refactor plan generation and execution process This commit improves the plan generation and execution workflow: - Simplify plan generation prompt for clearer instructions - Adjust plan execution logic in main-prompt.ts - Enhance response handling and markers for better flow control - Improve continuation logic for interrupted responses These changes aim to streamline the planning process and make the execution more robust and efficient. --- backend/src/generate-plan.ts | 12 +++--------- backend/src/main-prompt.ts | 19 +++++++++---------- 2 files changed, 12 insertions(+), 19 deletions(-) diff --git a/backend/src/generate-plan.ts b/backend/src/generate-plan.ts index d1c2daa806..22fdca1b45 100644 --- a/backend/src/generate-plan.ts +++ b/backend/src/generate-plan.ts @@ -13,15 +13,12 @@ export async function generatePlan( userId?: string ): Promise { const planGenerationPrompt = ` -Based on the user's request, create a detailed plan with numbered steps to accomplish the task. Include appropriate verification steps where necessary, such as running type checkers, creating and running unit tests, or any other relevant checks. +Based on the user's request, create a detailed plan for the assistant to follow with numbered steps to accomplish the task. Please follow these guidelines: 1. Reduce the scope of the plan to the minimum necessary to accomplish the task. Try to avoid unnecessary steps and do not modify more files or run more terminal commands than absolutely necessary. -2. Break down the task into clear, actionable steps. -3. Include verification steps where appropriate. -4. Consider potential edge cases or complications. -5. If any step requires significant changes, break it down further. -6. Aim for a comprehensive plan that covers all aspects of the request. +2. Break down the task into clear, actionable steps for the assistant to follow. The assistant can only edit files and run terminal commands as part of the plan. Do not include steps for the user to do. +3. Include appropriate verification steps along the way and at the end, such as running a command to do type checking and fixing errors, creating and running unit tests, or any other relevant checks. User request: ${messages[messages.length - 1].content} @@ -31,11 +28,8 @@ Please provide the plan in the following format: a. [Sub-step if necessary] b. [Another sub-step if necessary] 3. [Verification step (if applicable)] -4. [Next step] ... -Ensure that the plan is thorough and covers all necessary aspects of the user's request. - Please start by telling the user you will create a plan to address their request. ` diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index b8fd5d022b..8225d0e6a4 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -96,6 +96,7 @@ export async function mainPrompt( ) fullResponse += plan.replaceAll(STOP_MARKER, '').trim() fullResponse += `\n\n${PLAN_START_MARKER}` + onResponseChunk('\n\n') continuedMessages = [ { role: 'assistant', @@ -174,13 +175,13 @@ export async function mainPrompt( ` 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.${isPlanInProgress ? '' : ' Then pause to get more instructions from the user.'} `, - isPlanInProgress - ? ` - You should attempt to execute the entire plan.When the plan is complete or it is hard to make progress, end your response with the following marker: ${PLAN_STOP_MARKER} -` - : ` + ` Always end your response with the following marker: ${STOP_MARKER} +`, + isPlanInProgress && + ` + You should attempt to execute the entire plan. When the plan is complete or it is hard to make progress, end your response with the following marker: ${PLAN_STOP_MARKER} ` ).join('\n\n'), } @@ -335,7 +336,7 @@ ${STOP_MARKER} } else if (maybeToolCall !== null) { isComplete = true logger.debug(maybeToolCall, 'tool call') - } else if (isPlanInProgress) { + } else if (isPlanInProgress && fullResponse.includes(STOP_MARKER)) { toolCall = { id: Math.random().toString(36).slice(2), name: 'continue_plan', @@ -344,7 +345,7 @@ ${STOP_MARKER} isComplete = true } else if ( fullResponse.includes(STOP_MARKER) || - fullResponse.endsWith(PLAN_STOP_MARKER) + fullResponse.includes(PLAN_STOP_MARKER) ) { isComplete = true logger.debug('Reached STOP_MARKER') @@ -359,9 +360,7 @@ ${STOP_MARKER} }, { role: 'user', - content: isPlanInProgress - ? 'Please continue to execute the plan' - : `You got cut off, but please continue from the very next line of your response. Do not repeat anything you have just said. Just continue as if there were no interruption from the very last character of your last response. (Alternatively, just end your response with the following marker if you were done generating and want to allow the user to give further guidance: ${STOP_MARKER})`, + content: `You got cut off, but please continue from the very next line of your response. Do not repeat anything you have just said. Just continue as if there were no interruption from the very last character of your last response. (Alternatively, just end your response with the following marker if you were done generating and want to allow the user to give further guidance: ${STOP_MARKER})`, }, ] } From 3b5fa17a9a9d69564deadd8209c47156bbdf8b97 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Fri, 11 Oct 2024 10:34:25 -0700 Subject: [PATCH 10/12] Ignore node_modules by default --- common/src/project-file-tree.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/common/src/project-file-tree.ts b/common/src/project-file-tree.ts index ac22cf8ab1..1696af7e2d 100644 --- a/common/src/project-file-tree.ts +++ b/common/src/project-file-tree.ts @@ -12,6 +12,7 @@ export function getProjectFileTree( const defaultIgnore = ignore.default() defaultIgnore.add('.git') defaultIgnore.add('*.min.*') + defaultIgnore.add('node_modules') if (projectRoot === os.homedir()) { defaultIgnore.add('.*') From 48c3ac7f50b6a136eb33f0c7a9042a906c4ce65d Mon Sep 17 00:00:00 2001 From: James Grugett Date: Fri, 11 Oct 2024 11:41:50 -0700 Subject: [PATCH 11/12] Add make to list of skipped commands --- common/src/constants.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/common/src/constants.ts b/common/src/constants.ts index b191eff422..e23fb9aa76 100644 --- a/common/src/constants.ts +++ b/common/src/constants.ts @@ -37,6 +37,7 @@ export const SKIPPED_TERMINAL_COMMANDS = [ 'add', 'hey', 'diff', + 'make', ] export const MAX_DATE = new Date(86399999999999) From c4103396db0350da040943aba70b1578cc8684f1 Mon Sep 17 00:00:00 2001 From: James Grugett Date: Fri, 11 Oct 2024 13:12:53 -0700 Subject: [PATCH 12/12] Tweak incomplete sketch prompt --- backend/src/generate-patch.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/generate-patch.ts b/backend/src/generate-patch.ts index db129ce653..a2d1fbcc41 100644 --- a/backend/src/generate-patch.ts +++ b/backend/src/generate-patch.ts @@ -88,7 +88,7 @@ ${newContent} Are there any comments in the sketch that indicate surrounding code should remain as it is in the original file? For example, comments like "// ... existing code ..." or "# .... rest of the function ...". If so, please write "YES". Otherwise, write "NO". If "YES", don't write anything else. -If "NO", please also consider the following question. In rare cases, the new content focuses on the change of a single function or section of code with the intention to edit just this section, but the assistant forgot to add placeholder comments above and below the section to indicate the rest of the file is preserved. Without these placeholder comments the sketch of the updated file is incomplete. One clue this is the case is if the new content is much shorter than the original file. If they are about the same length, the sketch is probably complete and does not require modification. +If "NO", please also consider the following question. In rare cases, the new content focuses on the change of a single function or section of code with the intention to edit just this section, but the assistant forgot to add placeholder comments above and below the section to indicate the rest of the file is preserved. Without these placeholder comments the sketch of the updated file is incomplete. One clue this is the case is if the new content is just a single function whereas the original file has multiple functions. If you strongly believe this is the scenario, please write "INCOMPLETE_SKETCH". Otherwise (most likely), write "COMPLETE_SKETCH". `.trim()