Skip to content

🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming

Merge branch 'mgx_ops' into add_swe_agent_ablilities_to_engineer2

黄伟韬166eb2db79bf
diff --cc metagpt/prompts/di/engineer2.py
index afe904c92,0501b4d33..2e8d2872e
--- a/metagpt/prompts/di/engineer2.py
+++ b/metagpt/prompts/di/engineer2.py
@@@ -1,94 -1,32 +1,89 @@@
from metagpt.prompts.di.role_zero import ROLE_INSTRUCTION
-EXTRA_INSTRUCTION_DEPRECATED = """
-4. Each time you write a code in your response, write with the Editor directly without preparing a repetitive code block beforehand.
-5. Take on ONE task and write ONE code file in each response. DON'T attempt all tasks in one response.
-6. When not specified, you should write files in a folder named "src". If you know the project path, then write in a "src" folder under the project path.
-7. When provided system design or project schedule, you MUST read them first before making a plan, then adhere to them in your implementation, especially in the programming language, package, or framework. You MUST implement all code files prescribed in the system design or project schedule. You can create a plan first with each task corresponding to implementing one code file.
-8. Write at most one file per task, do your best to implement THE ONLY ONE FILE. CAREFULLY CHECK THAT YOU DONT MISS ANY NECESSARY CLASS/FUNCTION IN THIS FILE.
-9. COMPLETE CODE: Your code will be part of the entire project, so please implement complete, reliable, reusable code snippets.
-10. When provided system design, YOU MUST FOLLOW "Data structures and interfaces". DONT CHANGE ANY DESIGN. Do not use public member functions that do not exist in your design.
-11. Write out EVERY CODE DETAIL, DON'T LEAVE TODO.
-12. To modify code in a file, read the entire file, make changes, and update the file with the complete code, ensuring that no line numbers are included in the final write.
-13. When a system design or project schedule is provided, at the end of the plan, add a Validate Task for each file; for example, if there are three files, add three Validate Tasks. For each Validate Task, just call ValidateAndRewriteCode.run.
-14. When planning, initially list the files for coding, then outline all coding and review tasks in your first response.
-15. Note 'Task for {file_name} completed.' — signifies the {file_name} coding task is done.
-16. Avoid re-reviewing or re-coding the same code. When you decide to take a write or review action, include the command 'finish current task' in the same response.
-17. When coding JavaScript, avoid using '\'' in strings.
-18. If you plan to read a file, do not include other plans in the same response.
-"""
-
EXTRA_INSTRUCTION = """
-6. When not specified, you should write files in a folder named "src". If you know the project path, then write in a "src" folder under the project path.
-7. When provided system design or project schedule, you MUST read them first before making a plan, then adhere to them in your implementation, especially in the programming language, package, or framework. You MUST implement all code files prescribed in the system design or project schedule. You can create a plan first with each task corresponding to implementing one code file.
-8. When planning, initially list the files for coding, then outline all coding and review tasks in your first response.
-9. If you plan to read a file, do not include other plans in the same response.
-10. Use Engineer2.write_new_code to create or modify a file. Write only one code file each time.
-11. When the requirement is simple, you don't need to create a plan, just do it right away.
-"""
+You are an autonomous programmer
+
+The special interface consists of a file editor that shows you 100 lines of a file at a time.
+
+You can use terminal commands (e.g., cat, ls, cd) by calling Terminal.run_command.
+
+
+You should carefully observe the behavior and results of the previous action, and avoid triggering repeated errors.
+
+In addition to the terminal, I also provide additional tools. If provided an issue link, you MUST navigate to the issue page using Browser tool to understand the issue, before starting your fix.
+
+Your first action must be to check if the repository exists at the current path. If it exists, navigate to the repository path. If the repository doesn't exist, please download it and then navigate to it.
+All subsequent actions must be performed within this repository path. Do not leave this directory to execute any actions at any time.
+
+Note:
+1. If you open a file and need to get to an area around a specific line that is not in the first 100 lines, say line 583, don't just use the scroll_down command multiple times. Instead, use the Editor.goto_line command. It's much quicker.
+2. Always make sure to look at the currently open file and the current working directory (which appears right after the currently open file). The currently open file might be in a different directory than the working directory! Note that some commands, such as 'create', open files, so they might change the current open file.
+3. When using Editor.edit_file_by_replace, if there is no exact match, take the difference in indentation into consideration.
+4. After editing, verify the changes to ensure correct line numbers and proper indentation. Adhere to PEP8 standards for Python code.
+5. NOTE ABOUT THE EDIT COMMAND: Indentation really matters! When editing a file, make sure to insert appropriate indentation before each line! Ensuring the code adheres to PEP8 standards. If a edit command fails, you can try to edit the file again to correct the indentation, but don't repeat the same command without changes.
+6. To avoid syntax errors when editing files multiple times, consider opening the file to view the surrounding code related to the error line and make modifications based on this context.
+7. Ensure to observe the currently open file and the current working directory, which is displayed right after the open file. The open file might be in a different directory than the working directory. Remember, commands like 'create' open files and might alter the current open file.
+8. Effectively using Use search commands (`search_dir`, `search_file`, `find_file`) and navigation commands (`open_file`, `goto_line`) to locate and modify files efficiently. The Editor tool can fully satisfy the requirements. Follow these steps and considerations for optimal results:
+ **General Search Guidelines:**
+ - Ensure you are in the repository's root directory before starting your search.
+ - Always double-check the current working directory and the currently open file to avoid confusion.
+ - Avoid repeating failed search commands without modifications to improve efficiency.
+
+ **Strategies for Searching and Navigating Files:**
+
+ 1. **If you know the file's location:**
+ - Use the `open_file` command directly to open the file.
+ - Use `search_file` to find the `search_term` within the currently open file.
+ - Alternatively, use the `goto_line` command to jump to the specified line.
+ - **Boundary Consideration:** Ensure the file path is correctly specified and accessible.
+
+ 2. **If you know the filename but not the exact location:**
+ - Use `find_file` to locate the file in the directory.
+ - Use `open_file` to open the file once located.
+ - Use `search_file` to find the `search_term` within the file.
+ - Use `goto_line` to jump to the specified line if needed.
+ - **Boundary Consideration:** Handle cases where the file may exist in multiple directories by verifying the correct path before opening.
+
+ 3. **If you know the symbol but not the file's location:**
+ - Use "search_dir" to find files containing the symbol within the directory.
+ - Review the search results to identify the relevant file(s).
+ - Use `open_file` to open the identified file.
+ - Use `search_file` to locate the `search_term` within the open file.
+ - Use `goto_line` to jump to the specified line.
+ - **Boundary Consideration:** Be thorough in reviewing multiple search results to ensure you open the correct file. Consider using more specific search terms if initial searches return too many results.
+
+ **Search Tips:**
+ - The `<search_term>` for `search_dir`, `find_file`, or `search_file` should be an existing class name, function name, or file name.
+ - Enclose terms like `def` or `class` in quotes when searching for functions or classes (e.g., `search_dir 'def apow'` or `search_file 'class Pow'`).
+ - Use wildcard characters (`*`, `?`) in search terms to broaden or narrow down your search scope.
+ - If search commands return too many results, refine your search criteria or use more specific terms.
+ - If a search command fails, modify the search criteria, check for search_term or paths, and then try again.
+ - Based on feedback of observation or Terminal command in trajectory to guide adjustments in your search strategy.
+
+9. When the edit fails, try to enlarge the range of code.
+10. You must use the Editor.open_file command to open a file before using the Editor tool's edit command to modify it. When you open a file, any currently open file will be automatically closed.
+11. Remember, when you use Editor.insert_content_at_line or Editor.edit_file_by_replace, the line numbers will change after the operation. Therefore, if there are multiple operations, perform only the first operation in the current response, and defer the subsequent operations to the next turn.
+11.1 Do not use Editor.insert_content_at_line or Editor.edit_file_by_replace more than once per command list.
+12. If you choose Editor.insert_content_at_line, you must ensure that there is no duplication between the inserted content and the original code. If there is overlap between the new code and the original code, use Editor.edit_file_by_replace instead.
+13. If you choose Editor.edit_file_by_replace, the original code that needs to be replaced must start at the beginning of the line and end at the end of the line
+
+14. When not specified, you should write files in a folder named "src". If you know the project path, then write in a "src" folder under the project path.
+15. When provided system design or project schedule, you MUST read them first before making a plan, then adhere to them in your implementation, especially in the programming language, package, or framework. You MUST implement all code files prescribed in the system design or project schedule. You can create a plan first with each task corresponding to implementing one code file.
+16. When planning, initially list the files for coding, then outline all coding tasks based on the file organization in your first response.
+17. If you plan to read a file, do not include other plans in the same response.
+18. Use Engineer2.write_new_code to create or modify a file. Write only one code file each time. If you only need to code one file, provide all the necessary information in one response.
+19. When the requirement is simple, you don't need to create a plan, just do it right away.
+20. If the code exists, use the Editor tool's open and edit commands to modify it. Since it is not a new code, do not use write_new_code.
-
- 22. When using the editor, pay attention to the editor's current directory. When you use editor tools, the paths must be either absolute or relative to the editor's current directory.
- """
- """
- 21. Forbidden to run code in the terminal.
- Do Not run the code.
++21. When using the editor, pay attention to the editor's current directory. When you use editor tools, the paths must be either absolute or relative to the editor's current directory.
+"""
+CURRENT_STATE = """
+The current editor state is:
+(Editor current directory: {editor_current_directory})
+(Editor open file: {editor_open_file})
+The current terminal state is:
+(Terminal current directory: {terminal_current_directory})
+"""
ENGINEER2_INSTRUCTION = ROLE_INSTRUCTION + EXTRA_INSTRUCTION.strip()
WRITE_CODE_SYSTEM_PROMPT = """
diff --cc metagpt/roles/di/engineer2.py
index 9ec22c077,bcd5f5738..5b264e85e
--- a/metagpt/roles/di/engineer2.py
+++ b/metagpt/roles/di/engineer2.py
@@@ -14,9 -11,9 +14,10 @@@ from metagpt.prompts.di.engineer2 impor
WRITE_CODE_SYSTEM_PROMPT,
)
from metagpt.roles.di.role_zero import RoleZero
-from metagpt.schema import UserMessage
+from metagpt.schema import Message, UserMessage
from metagpt.strategy.experience_retriever import ENGINEER_EXAMPLE
+ from metagpt.tools.libs.cr import CodeReview
+from metagpt.tools.libs.git import git_create_pull
from metagpt.tools.libs.terminal import Terminal
from metagpt.tools.tool_registry import register_tool
from metagpt.utils.common import CodeParser, awrite
@@@ -29,46 -26,20 +30,51 @@@ class Engineer2(RoleZero)
profile: str = "Engineer"
goal: str = "Take on game, app, and web development."
instruction: str = ENGINEER2_INSTRUCTION
-
terminal: Terminal = Field(default_factory=Terminal, exclude=True)
- tools: list[str] = ["Plan", "Editor:read", "RoleZero", "Terminal:run_command", "Engineer2", "SearchEnhancedQA", "CodeReview"]
+ tools: list[str] = [
+ "Plan",
+ "Editor",
+ "RoleZero",
+ "Terminal:run_command",
+ "Browser:goto,scroll",
+ "git_create_pull",
+ "SearchEnhancedQA",
+ "Engineer2",
++ "CodeReview",
+ ]
+ # SWE Agent parameter
+ run_eval: bool = False
+ output_diff: str = ""
+ max_react_loop: int = 40
+
+ async def _think(self) -> bool:
+ await self._format_instruction()
+ res = await super()._think()
+ return res
+
+ async def _format_instruction(self):
+ """
+ Display the current terminal and editor state.
+ This information will be dynamically added to the command prompt.
+ """
+ state = {
+ "editor_open_file": self.editor.current_file,
+ "editor_current_directory": self.editor.working_dir,
+ "terminal_current_directory": await self.terminal.run_command("pwd"),
+ }
+ self.cmd_prompt_current_state = CURRENT_STATE.format(**state).strip()
def _update_tool_execution(self):
+ # validate = ValidateAndRewriteCode()
+ cr = CodeReview()
self.tool_execution_map.update(
{
"Terminal.run_command": self.terminal.run_command,
+ "git_create_pull": git_create_pull,
"Engineer2.write_new_code": self.write_new_code,
+ "CodeReview.review": cr.review,
+ "CodeReview.fix": cr.fix,
# "ValidateAndRewriteCode.run": validate.run,
# "ValidateAndRewriteCode": validate.run,
}
diff --cc metagpt/roles/di/swe_agent.py
index 3d3ce4b57,d54c9dd44..731b00b0b
--- a/metagpt/roles/di/swe_agent.py
+++ b/metagpt/roles/di/swe_agent.py
@@@ -41,21 -46,7 +46,6 @@@ class SWEAgent(RoleZero)
async def _format_instruction(self):
"""
Formats the instruction message for the SWE agent.
--
Runs the "state" command in the terminal, parses its output as JSON,
and uses it to format the `_instruction` template.
"""
@@@ -72,10 -63,10 +62,8 @@@
async def _parse_commands_for_eval(self):
"""
Handles actions based on parsed commands.
--
Parses commands, checks for a "submit" action, and generates a patch using `git diff`.
Stores the cleaned patch in `output_diff`. Logs any exceptions.
--
This function is specifically added for SWE bench evaluation.
"""
# If todo switches to None, it indicates that this is the final round of reactions, and the Swe-Agent will stop. Use git diff to store any changes made.
@@@ -88,7 -79,7 +76,6 @@@
logger.info(f"Diff output: \n{clear_diff}")
if clear_diff:
self.output_diff = clear_diff
--
except Exception as e:
logger.error(f"Error during submission: {e}")