Skip to content

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

Merge branch 'mgx_ops' into swe_editer

seeker-jieb394fed52b8c
diff --cc metagpt/tools/libs/cr.py
index 1f42bfe3a,e3509591b..87a686eb1
--- a/metagpt/tools/libs/cr.py
+++ b/metagpt/tools/libs/cr.py
@@@ -27,30 -28,29 +28,28 @@@ class CodeReview
) -> str:
"""Review a PR and save code review comments.
+ Notes:
+ If the user does not specify an output path, saved it using a relative path in the current working directory.
+
Args:
- patch_path: The local path of the patch file or the url of the pull request. Example: "/data/xxx-pr-1.patch", "https://github.com/xx/XX/pull/1362"
- cr_output_file: Output file path where code review comments will be saved. Example: "cr/xxx-pr-1.json"
- cr_point_file: File path for specifying code review points. If not specified, this parameter is not passed..
+ patch_path: The local path of the patch file or the URL of the pull request.
+ output_file: Output file path where code review comments will be saved.
+ point_file: File path for specifying code review points. If not specified, this parameter does not need to be passed.
+
+ Examples:
+
+ >>> cr = CodeReview()
+ >>> await cr.review(patch_path="https://github.com/geekan/MetaGPT/pull/136", output_file="cr/MetaGPT_136.json")
+ >>> await cr.review(patch_path="/data/uploads/dev-master.diff", output_file="cr/dev-master.json")
+ >>> await cr.review(patch_path="/data/uploads/main.py", output_file="cr/main.json")
"""
patch = await self._get_patch_content(patch_path)
- cr_point_file = cr_point_file if cr_point_file else Path(metagpt.ext.cr.__file__).parent / "points.json"
- async with aiofiles.open(cr_point_file, "rb") as f:
+ point_file = point_file if point_file else Path(metagpt.ext.cr.__file__).parent / "points.json"
+ async with aiofiles.open(point_file, "rb") as f:
cr_point_content = await f.read()
cr_points = [Point(**i) for i in json.loads(cr_point_content)]
-
- async with FileIOOperatorReporter(enable_llm_stream=True) as reporter:
- src_path = cr_output_file
- cr_output_path = Path(cr_output_file)
- await reporter.async_report(
- {"type": "CodeReview", "src_path": src_path, "filename": cr_output_path.name}, "meta"
- )
- comments = await CodeReview_().run(patch, cr_points)
- cr_output_path.parent.mkdir(exist_ok=True, parents=True)
- async with aiofiles.open(cr_output_path, "w", encoding="utf-8") as f:
- await f.write(json.dumps(comments, ensure_ascii=False))
- await reporter.async_report(cr_output_path)
--
- return f"The number of defects: {len(comments)} and the comments are stored in {cr_output_file}"
+ comments = await CodeReview_().run(patch, cr_points, output_file)
+ return f"The number of defects: {len(comments)} and the comments are stored in {output_file}"
async def fix(
self,
@@@ -87,7 -87,13 +86,13 @@@
else:
async with aiofiles.open(patch_path, encoding="utf-8") as f:
patch_file_content = await f.read()
- await EditorReporter().async_report(patch_path)
+ await FileIOOperatorReporter().async_report(patch_path)
+ if not patch_path.endswith((".diff", ".patch")):
+ name = Path(patch_path).name
+ patch_file_content = "".join(
+ difflib.unified_diff([], patch_file_content.splitlines(keepends=True), "/dev/null", f"b/{name}"),
+ )
+ patch_file_content = f"diff --git a/{name} b/{name}\n{patch_file_content}"
patch: PatchSet = PatchSet(patch_file_content)
return patch
diff --cc metagpt/tools/libs/file_io_operator.py
index f30d2d4fd,000000000..29578789d
mode 100644,000000..100644
--- a/metagpt/tools/libs/file_io_operator.py
+++ b/metagpt/tools/libs/file_io_operator.py
@@@ -1,147 -1,0 +1,149 @@@
+import base64
+import os
+from pathlib import Path
- from typing import List, Optional, Union
++from typing import List, Optional, Tuple, Union
+
+from pydantic import BaseModel, ConfigDict
+
+from metagpt.config2 import Config
+from metagpt.logs import logger
+from metagpt.tools.tool_registry import register_tool
+from metagpt.utils import read_docx
+from metagpt.utils.common import aread, aread_bin, awrite_bin, check_http_endpoint
+from metagpt.utils.repo_to_markdown import is_text_file
+from metagpt.utils.report import FileIOOperatorReporter
+
+
+class FileBlock(BaseModel):
+ """A block of content in a file"""
+
+ file_path: str
+ block_content: str
+
+
+class LineNumberError(Exception):
+ pass
+
+
+@register_tool()
+class FileOperator(BaseModel):
+ """
+ A state-of-state tool for reading, understanding, and writing files.
+ """
+
+ model_config = ConfigDict(arbitrary_types_allowed=True)
+ resource: FileIOOperatorReporter = FileIOOperatorReporter()
+
+ def write(self, path: str, content: str):
+ """Write the whole content to a file. When used, make sure content arg contains the full content of the file."""
+ if "\n" not in content and "\\n" in content:
+ # A very raw rule to correct the content: If 'content' lacks actual newlines ('\n') but includes '\\n', consider
+ # replacing them with '\n' to potentially correct mistaken representations of newline characters.
+ content = content.replace("\\n", "\n")
+ directory = os.path.dirname(path)
+ if directory and not os.path.exists(directory):
+ os.makedirs(directory)
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(content)
+ # self.resource.report(path, "path")
+ return f"The writing/coding the of the file {os.path.basename(path)}' is now completed. The file '{os.path.basename(path)}' has been successfully created."
+
+ async def read(self, path: str) -> FileBlock:
+ """Read the whole content of a file. Using absolute paths as the argument for specifying the file location."""
+ is_text, mime_type = await is_text_file(path)
+ if is_text:
+ lines = await self._read_text(path)
+ elif mime_type == "application/pdf":
+ lines = await self._read_pdf(path)
+ elif mime_type in {
+ "application/msword",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ "application/vnd.ms-word.document.macroEnabled.12",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
+ "application/vnd.ms-word.template.macroEnabled.12",
+ }:
+ lines = await self._read_docx(path)
+ else:
+ return FileBlock(file_path=str(path), block_content="")
+ self.resource.report(str(path), "path")
+
+ lines_with_num = [f"{i + 1:03}|{line}" for i, line in enumerate(lines)]
+ result = FileBlock(
+ file_path=str(path),
+ block_content="".join(lines_with_num),
+ )
+ return result
+
+ @staticmethod
+ async def _read_text(path: Union[str, Path]) -> List[str]:
+ content = await aread(path)
+ lines = content.split("\n")
+ return lines
+
+ @staticmethod
+ async def _read_pdf(path: Union[str, Path]) -> List[str]:
+ result = await FileOperator._omniparse_read_file(path)
+ if result:
+ return result
+
+ from llama_index.readers.file import PDFReader
+
+ reader = PDFReader()
+ lines = reader.load_data(file=Path(path))
+ return [i.text for i in lines]
+
+ @staticmethod
+ async def _read_docx(path: Union[str, Path]) -> List[str]:
+ result = await FileOperator._omniparse_read_file(path)
+ if result:
+ return result
+ return read_docx(str(path))
+
+ @staticmethod
+ async def _omniparse_read_file(path: Union[str, Path]) -> Optional[List[str]]:
+ from metagpt.tools.libs import get_env_default
+ from metagpt.utils.omniparse_client import OmniParseClient
+
- base_url = await get_env_default(key="base_url", app_name="OmniParse", default_value="")
- if not base_url:
- base_url = await FileOperator._read_omniparse_config()
++ env_base_url = await get_env_default(key="base_url", app_name="OmniParse", default_value="")
++ env_timeout = await get_env_default(key="timeout", app_name="OmniParse", default_value="")
++ conf_base_url, conf_timeout = await FileOperator._read_omniparse_config()
++
++ base_url = env_base_url or conf_base_url
+ if not base_url:
+ return None
+ api_key = await get_env_default(key="api_key", app_name="OmniParse", default_value="")
- v = await get_env_default(key="timeout", app_name="OmniParse", default_value="120")
++ timeout = env_timeout or conf_timeout or 600
+ try:
- timeout = int(v) or 120
++ timeout = int(timeout)
+ except ValueError:
- timeout = 120
++ timeout = 600
+
+ try:
+ if not await check_http_endpoint(url=base_url):
+ logger.warning(f"{base_url}: NOT AVAILABLE")
+ return None
+ client = OmniParseClient(api_key=api_key, base_url=base_url, max_timeout=timeout)
+ file_data = await aread_bin(filename=path)
+ ret = await client.parse_document(file_input=file_data, bytes_filename=str(path))
+ except (ValueError, Exception) as e:
+ logger.exception(f"{path}: {e}")
+ return None
+ if not ret.images:
+ return [ret.text] if ret.text else None
+
+ result = [ret.text]
+ img_dir = Path(path).parent / (Path(path).name.replace(".", "_") + "_images")
+ img_dir.mkdir(parents=True, exist_ok=True)
+ for i in ret.images:
+ byte_data = base64.b64decode(i.image)
+ filename = img_dir / i.image_name
+ await awrite_bin(filename=filename, data=byte_data)
+ result.append(f"![{i.image_name}]({str(filename)})")
+ return result
+
+ @staticmethod
- async def _read_omniparse_config() -> str:
++ async def _read_omniparse_config() -> Tuple[str, int]:
+ config = Config.default()
+ if config.omniparse and config.omniparse.url:
- return config.omniparse.url
- return ""
++ return config.omniparse.url, config.omniparse.timeout
++ return "", 0