🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming
feat: merge send18:dev
莘权 马7effe7f74ce7
diff --cc .gitignoreindex e03eab3d3,1a9741e91..2f6d85805--- a/.gitignore+++ b/.gitignore@@@ -162,5 -163,9 +162,11 @@@ workspace/*.mmdtmpoutput.wav+metagpt/roles/idea_agent.py+.aider*+ *.bak++ # output folder+ output+ tmp.png+diff --cc config/config.yamlindex b841ee477,71744aa7f..ff1ae769d--- a/config/config.yaml+++ b/config/config.yaml@@@ -7,18 -7,12 +7,19 @@@## Or, you can configure OPENAI_PROXY to access official OPENAI_API_BASE.OPENAI_API_BASE: "https://api.openai.com/v1"#OPENAI_PROXY: "http://127.0.0.1:8118"-#OPENAI_API_KEY: "YOUR_API_KEY"-OPENAI_API_MODEL: "gpt-4"-MAX_TOKENS: 1500+#OPENAI_API_KEY: "YOUR_API_KEY" # set the value to sk-xxx if you host the openai interface for open llm model+OPENAI_API_MODEL: "gpt-4-1106-preview"+MAX_TOKENS: 4096RPM: 10+ LLM_TYPE: OpenAI+#### if Spark+#SPARK_APPID : "YOUR_APPID"+#SPARK_API_SECRET : "YOUR_APISecret"+#SPARK_API_KEY : "YOUR_APIKey"+#DOMAIN : "generalv2"+#SPARK_URL : "ws://spark-api.xf-yun.com/v2.1/chat"+#### if Anthropic#Anthropic_API_KEY: "YOUR_API_KEY"@@@ -87,15 -77,18 +88,32 @@@ SD_T2I_API: "/sdapi/v1/txt2imgMODEL_FOR_RESEARCHER_SUMMARY: gpt-3.5-turboMODEL_FOR_RESEARCHER_REPORT: gpt-3.5-turbo-16k+### choose the engine for mermaid conversion,+# default is nodejs, you can change it to playwright,pyppeteer or ink+# MERMAID_ENGINE: nodejs++### browser path for pyppeteer engine, support Chrome, Chromium,MS Edge+#PYPPETEER_EXECUTABLE_PATH: "/usr/bin/google-chrome-stable"++PROMPT_FORMAT: json #json or markdown++### Agent configurations+# RAISE_NOT_CONFIG_ERROR: true # "true" if the LLM key is not configured, throw a NotConfiguredException, else "false".- # WORKSPACE_PATH_WITH_UID: false # "true" if using `{workspace}/{uid}` as the workspace path; "false" use `{workspace}`.++# WORKSPACE_PATH_WITH_UID: false # "true" if using `{workspace}/{uid}` as the workspace path; "false" use `{workspace}`.+++ ### Meta Models+ #METAGPT_TEXT_TO_IMAGE_MODEL: MODEL_URL++ ### S3 config-S3:- access_key: "YOUR_S3_ACCESS_KEY"- secret_key: "YOUR_S3_SECRET_KEY"- endpoint_url: "YOUR_S3_ENDPOINT_URL"++S3_ACCESS_KEY: "YOUR_S3_ACCESS_KEY"++S3_SECRET_KEY: "YOUR_S3_SECRET_KEY"++S3_ENDPOINT_URL: "YOUR_S3_ENDPOINT_URL"++S3_SECURE: true # true/false++S3_BUCKET: "YOUR_S3_BUCKET"++ ### Redis config-REDIS:- host: "YOUR_REDIS_HOST"- port: YOUR_REDIS_PORT, int- password: "YOUR_REDIS_PASSWORD"- db: "YOUR_REDIS_DB_INDEX, str, 0-based"++REDIS_HOST: "YOUR_REDIS_HOST"++REDIS_PORT: "YOUR_REDIS_PORT"++REDIS_PASSWORD: "YOUR_REDIS_PASSWORD"++REDIS_DB: "YOUR_REDIS_DB_INDEX, str, 0-based"++diff --cc examples/search_kb.pyindex 7a9911ca2,449099380..c2ded1769--- a/examples/search_kb.py+++ b/examples/search_kb.py@@@ -2,10 -2,12 +2,17 @@@# -*- coding: utf-8 -*-"""@File : search_kb.py+ @Modified By: mashenquan, 2023-8-9, fix-bug: cannot find metagpt module."""import asyncio++<<<<<<< HEAD++from metagpt.actions import Action++=======+ from pathlib import Path+ import sys+ sys.path.append(str(Path(__file__).resolve().parent.parent))++>>>>>>> send18/devfrom metagpt.const import DATA_PATHfrom metagpt.document_store import FaissStorefrom metagpt.logs import loggerdiff --cc metagpt/__init__.pyindex 71ddd1aff,2980109dd..aa1965e31--- a/metagpt/__init__.py+++ b/metagpt/__init__.py@@@ -1,7 -1,14 +1,22 @@@-#!/usr/bin/env python+#!/usr/bin/env python# -*- coding: utf-8 -*-++<<<<<<< HEAD+# @Time : 2023/4/24 22:26+# @Author : alexanderwu+# @File : __init__.py++from metagpt import _compat as _ # noqa: F401++=======+ """+ @Time : 2023/4/24 22:26+ @Author : alexanderwu+ @File : __init__.py+ @Desc : mashenquan, 2023/8/22. Add `Message` for importing by external projects.+ """++ from metagpt.schema import Message++ __all__ = [+ "Message",+ ]++>>>>>>> send18/devdiff --cc metagpt/actions/action.pyindex dc96699a9,92608f448..442004e09--- a/metagpt/actions/action.py+++ b/metagpt/actions/action.py@@@ -4,25 -4,29 +4,29 @@@@Time : 2023/5/11 14:43@Author : alexanderwu@File : action.py+ @Modified By: mashenquan, 2023/8/20. Add function return annotations.+ @Modified By: mashenquan, 2023/9/8. Replace LLM with LLMFactory"""-from __future__ import annotations++import re++from __future__ import annotationsfrom abc import ABCfrom typing import Optional--from tenacity import retry, stop_after_attempt, wait_fixed--+from tenacity import retry, stop_after_attempt, wait_random_exponential-from metagpt.actions.action_output import ActionOutput+from metagpt.llm import LLM+from metagpt.logs import logger+from metagpt.utils.common import OutputParser+from metagpt.utils.custom_decoder import CustomDecoder-+ from metagpt.logs import logger+ from metagpt.provider.base_gpt_api import BaseGPTAPI+ from metagpt.utils.common import OutputParser-class Action(ABC):- def __init__(self, name: str = "", context=None, llm: LLM = None):+ def __init__(self, name: str = "", context=None, llm: BaseGPTAPI = None):self.name: str = nameif llm is None:- from metagpt.llm import LLMFactory-- llm = LLMFactory.new_llm()+ llm = LLM()self.llm = llmself.context = contextself.prefix = ""diff --cc metagpt/actions/design_api.pyindex 557ebcbbd,1c31b75fb..bccbc1261--- a/metagpt/actions/design_api.py+++ b/metagpt/actions/design_api.py@@@ -4,85 -4,19 +4,96 @@@@Time : 2023/5/11 19:26@Author : alexanderwu@File : design_api.py++<<<<<<< HEAD+@Modified By: mashenquan, 2023/11/27.+ 1. According to Section 2.2.3.1 of RFC 135, replace file data in the message with the file name.+ 2. According to the design in Section 2.2.3.5.3 of RFC 135, add incremental iteration functionality.+@Modified By: mashenquan, 2023/12/5. Move the generation logic of the project name to WritePRD.+"""+import json+from pathlib import Path+from typing import List++from metagpt.actions import Action, ActionOutput+from metagpt.config import CONFIG+from metagpt.const import (+ DATA_API_DESIGN_FILE_REPO,+ PRDS_FILE_REPO,+ SEQ_FLOW_FILE_REPO,+ SYSTEM_DESIGN_FILE_REPO,+ SYSTEM_DESIGN_PDF_FILE_REPO,+)++=======+ @Modified By: mashenquan, 2023-8-9, align `run` parameters with the parent :class:`Action` class.+ """+ from typing import List++ import aiofiles++ from metagpt.actions import Action+ from metagpt.config import CONFIG++>>>>>>> send18/devfrom metagpt.logs import logger-from metagpt.utils.common import CodeParser+from metagpt.schema import Document, Documents+from metagpt.utils.file_repository import FileRepository+from metagpt.utils.get_template import get_templatefrom metagpt.utils.mermaid import mermaid_to_file-PROMPT_TEMPLATE = """+templates = {+ "json": {+ "PROMPT_TEMPLATE": """+# Context+{context}++## Format example+{format_example}+-----+Role: You are an architect; the goal is to design a SOTA PEP8-compliant python system+Language: Please use the same language as the user requirement, but the title and code should be still in English. For example, if the user speaks Chinese, the specific text of your answer should also be in Chinese.+Requirement: Fill in the following missing information based on the context, each section name is a key in json++## Implementation approach: Provide as Plain text. Analyze the difficult points of the requirements, select appropriate open-source frameworks.++## Project name: Constant text.++## File list: Provided as Python list[str], the list of files needed (including HTML & CSS IF NEEDED) to write the program. Only need relative paths. ALWAYS write a main.py or app.py here++## Data structures and interfaces: Use mermaid classDiagram code syntax, including classes (INCLUDING __init__ method) and functions (with type annotations), CLEARLY MARK the RELATIONSHIPS between classes, and comply with PEP8 standards. The data structures SHOULD BE VERY DETAILED and the API should be comprehensive with a complete design.++## Program call flow: Use sequenceDiagram code syntax, COMPLETE and VERY DETAILED, using CLASSES AND API DEFINED ABOVE accurately, covering the CRUD AND INIT of each object, SYNTAX MUST BE CORRECT.++## Anything UNCLEAR: Provide as Plain text. Try to clarify it.++output a properly formatted JSON, wrapped inside [CONTENT][/CONTENT] like format example,+and only output the json inside this tag, nothing else+""",+ "FORMAT_EXAMPLE": """+[CONTENT]+{{+ "Implementation approach": "We will ...",+ "Project name": "{project_name}",+ "File list": ["main.py"],+ "Data structures and interfaces": '+ classDiagram+ class Game{{+ +int score+ }}+ ...+ Game "1" -- "1" Food: has+ ',+ "Program call flow": '+ sequenceDiagram+ participant M as Main+ ...+ G->>M: end game+ ',+ "Anything UNCLEAR": "The requirement is clear to me."+}}+[/CONTENT]+""",+ },+ "markdown": {+ "PROMPT_TEMPLATE": """# Context{context}@@@ -197,98 -99,26 +208,123 @@@ class WriteDesign(Action)"clearly and in detail.")++<<<<<<< HEAD+ async def run(self, with_messages, format=CONFIG.prompt_format):+ # Use `git diff` to identify which PRD documents have been modified in the `docs/prds` directory.+ prds_file_repo = CONFIG.git_repo.new_file_repository(PRDS_FILE_REPO)+ changed_prds = prds_file_repo.changed_files+ # Use `git diff` to identify which design documents in the `docs/system_designs` directory have undergone+ # changes.+ system_design_file_repo = CONFIG.git_repo.new_file_repository(SYSTEM_DESIGN_FILE_REPO)+ changed_system_designs = system_design_file_repo.changed_files++ # For those PRDs and design documents that have undergone changes, regenerate the design content.+ changed_files = Documents()+ for filename in changed_prds.keys():+ doc = await self._update_system_design(+ filename=filename, prds_file_repo=prds_file_repo, system_design_file_repo=system_design_file_repo+ )+ changed_files.docs[filename] = doc++ for filename in changed_system_designs.keys():+ if filename in changed_files.docs:+ continue+ doc = await self._update_system_design(+ filename=filename, prds_file_repo=prds_file_repo, system_design_file_repo=system_design_file_repo+ )+ changed_files.docs[filename] = doc+ if not changed_files.docs:+ logger.info("Nothing has changed.")+ # Wait until all files under `docs/system_designs/` are processed before sending the publish message,+ # leaving room for global optimization in subsequent steps.+ return ActionOutput(content=changed_files.json(), instruct_content=changed_files)++ async def _new_system_design(self, context, format=CONFIG.prompt_format):+ prompt_template, format_example = get_template(templates, format)+ format_example = format_example.format(project_name=CONFIG.project_name)+ prompt = prompt_template.format(context=context, format_example=format_example)+ system_design = await self._aask_v1(prompt, "system_design", OUTPUT_MAPPING, format=format)++=======+ async def _save_system_design(self, docs_path, resources_path, content):+ data_api_design = CodeParser.parse_code(block="Data structures and interface definitions", text=content)+ seq_flow = CodeParser.parse_code(block="Program call flow", text=content)+ await mermaid_to_file(data_api_design, resources_path / "data_api_design")+ await mermaid_to_file(seq_flow, resources_path / "seq_flow")+ system_design_file = docs_path / "system_design.md"+ logger.info(f"Saving System Designs to {system_design_file}")+ async with aiofiles.open(system_design_file, "w") as f:+ await f.write(content)++ async def _save(self, system_design: str):+ workspace = CONFIG.workspace+ docs_path = workspace / "docs"+ resources_path = workspace / "resources"+ docs_path.mkdir(parents=True, exist_ok=True)+ resources_path.mkdir(parents=True, exist_ok=True)+ await self._save_system_design(docs_path, resources_path, system_design)++ async def run(self, context, **kwargs):+ prompt = PROMPT_TEMPLATE.format(context=context, format_example=FORMAT_EXAMPLE)+ system_design = await self._aask_v1(prompt, "system_design", OUTPUT_MAPPING)+ await self._save(system_design.content)++>>>>>>> send18/devreturn system_design++ async def _merge(self, prd_doc, system_design_doc, format=CONFIG.prompt_format):+ prompt = MERGE_PROMPT.format(+ old_design=system_design_doc.content, context=prd_doc.content, project_name=CONFIG.project_name+ )+ system_design = await self._aask_v1(prompt, "system_design", OUTPUT_MAPPING, format=format)+ # fix Python package name, we can't system_design.instruct_content.python_package_name = "xxx" since "Python+ # package name" contain space, have to use setattr+ system_design_doc.content = system_design.instruct_content.json(ensure_ascii=False)+ return system_design_doc++ async def _update_system_design(self, filename, prds_file_repo, system_design_file_repo) -> Document:+ prd = await prds_file_repo.get(filename)+ old_system_design_doc = await system_design_file_repo.get(filename)+ if not old_system_design_doc:+ system_design = await self._new_system_design(context=prd.content)+ doc = Document(+ root_path=SYSTEM_DESIGN_FILE_REPO,+ filename=filename,+ content=system_design.instruct_content.json(ensure_ascii=False),+ )+ else:+ doc = await self._merge(prd_doc=prd, system_design_doc=old_system_design_doc)+ await system_design_file_repo.save(+ filename=filename, content=doc.content, dependencies={prd.root_relative_path}+ )+ await self._save_data_api_design(doc)+ await self._save_seq_flow(doc)+ await self._save_pdf(doc)+ return doc++ @staticmethod+ async def _save_data_api_design(design_doc):+ m = json.loads(design_doc.content)+ data_api_design = m.get("Data structures and interfaces")+ if not data_api_design:+ return+ pathname = CONFIG.git_repo.workdir / DATA_API_DESIGN_FILE_REPO / Path(design_doc.filename).with_suffix("")+ await WriteDesign._save_mermaid_file(data_api_design, pathname)+ logger.info(f"Save class view to {str(pathname)}")++ @staticmethod+ async def _save_seq_flow(design_doc):+ m = json.loads(design_doc.content)+ seq_flow = m.get("Program call flow")+ if not seq_flow:+ return+ pathname = CONFIG.git_repo.workdir / Path(SEQ_FLOW_FILE_REPO) / Path(design_doc.filename).with_suffix("")+ await WriteDesign._save_mermaid_file(seq_flow, pathname)+ logger.info(f"Saving sequence flow to {str(pathname)}")++ @staticmethod+ async def _save_pdf(design_doc):+ await FileRepository.save_as(doc=design_doc, with_suffix=".md", relative_path=SYSTEM_DESIGN_PDF_FILE_REPO)++ @staticmethod+ async def _save_mermaid_file(data: str, pathname: Path):+ pathname.parent.mkdir(parents=True, exist_ok=True)+ await mermaid_to_file(data, pathname)diff --cc metagpt/actions/project_management.pyindex 95da0d65a,1062f8984..53ef872e2--- a/metagpt/actions/project_management.py+++ b/metagpt/actions/project_management.py@@@ -4,88 -4,16 +4,101 @@@@Time : 2023/5/11 19:12@Author : alexanderwu@File : project_management.py++<<<<<<< HEAD+@Modified By: mashenquan, 2023/11/27.+ 1. Divide the context into three components: legacy code, unit test code, and console log.+ 2. Move the document storage operations related to WritePRD from the save operation of WriteDesign.+ 3. According to the design in Section 2.2.3.5.4 of RFC 135, add incremental iteration functionality.++=======+ @Modified By: mashenquan, 2023-8-9, align `run` parameters with the parent :class:`Action` class.++>>>>>>> send18/dev"""-from typing import List, Tuple+import json+from typing import List++<<<<<<< HEAD+from metagpt.actions import ActionOutput+from metagpt.actions.action import Action+from metagpt.config import CONFIG+from metagpt.const import (+ PACKAGE_REQUIREMENTS_FILENAME,+ SYSTEM_DESIGN_FILE_REPO,+ TASK_FILE_REPO,+ TASK_PDF_FILE_REPO,+)+from metagpt.logs import logger+from metagpt.schema import Document, Documents+from metagpt.utils.file_repository import FileRepository+from metagpt.utils.get_template import get_template++templates = {+ "json": {+ "PROMPT_TEMPLATE": """+# Context+{context}++## Format example+{format_example}+-----+Role: You are a project manager; the goal is to break down tasks according to PRD/technical design, give a task list, and analyze task dependencies to start with the prerequisite modules+Language: Please use the same language as the user requirement, but the title and code should be still in English. For example, if the user speaks Chinese, the specific text of your answer should also be in Chinese.+Requirements: Based on the context, fill in the following missing information, each section name is a key in json. Here the granularity of the task is a file, if there are any missing files, you can supplement them+ATTENTION: Output carefully referenced "Format example" in format.++## Required Python third-party packages: Provide Python list[str] in requirements.txt format++## Required Other language third-party packages: Provide Python list[str] in requirements.txt format++## Logic Analysis: Provided as a Python list[list[str]. the first is filename, the second is class/method/function should be implemented in this file. Analyze the dependencies between the files, which work should be done first++## Task list: Provided as Python list[str]. Each str is a filename, the more at the beginning, the more it is a prerequisite dependency, should be done first++## Full API spec: Use OpenAPI 3.0. Describe all APIs that may be used by both frontend and backend.++## Shared Knowledge: Anything that should be public like utils' functions, config's variables details that should make clear first.++## Anything UNCLEAR: Provide as Plain text. Try to clarify it. For example, don't forget a main entry. don't forget to init 3rd party libs.++output a properly formatted JSON, wrapped inside [CONTENT][/CONTENT] like format example,+and only output the json inside this tag, nothing else+""",+ "FORMAT_EXAMPLE": '''+{+ "Required Python third-party packages": [+ "flask==1.1.2",+ "bcrypt==3.2.0"+ ],+ "Required Other language third-party packages": [+ "No third-party ..."+ ],+ "Logic Analysis": [+ ["game.py", "Contains..."]+ ],+ "Task list": [+ "game.py"+ ],+ "Full API spec": """+ openapi: 3.0.0+ ...+ description: A JSON object ...+ """,+ "Shared Knowledge": """+ 'game.py' contains ...+ """,+ "Anything UNCLEAR": "We need ... how to start."+}+''',+ },+ "markdown": {+ "PROMPT_TEMPLATE": """++=======+ import aiofiles++ from metagpt.actions.action import Action+ from metagpt.config import CONFIG++ PROMPT_TEMPLATE = """++>>>>>>> send18/dev# Context{context}@@@ -104,14 -34,13 +117,18 @@@ Attention: Use '##' to split sections,## Task list: Provided as Python list[str]. Each str is a filename, the more at the beginning, the more it is a prerequisite dependency, should be done first-## Shared Knowledge: Anything that should be public like utils' functions, config's variables details that should make clear first.+## Full API spec: Use OpenAPI 3.0. Describe all APIs that may be used by both frontend and backend.-## Anything UNCLEAR: Provide as Plain text. Make clear here. For example, don't forget a main entry. don't forget to init 3rd party libs.+## Shared Knowledge: Anything that should be public like utils' functions, config's variables details that should make clear first.++<<<<<<< HEAD+## Anything UNCLEAR: Provide as Plain text. Try to clarify it. For example, don't forget a main entry. don't forget to init 3rd party libs.++=======+ """++>>>>>>> send18/dev-FORMAT_EXAMPLE = '''+""",+ "FORMAT_EXAMPLE": '''---## Required Python third-party packages```python@@@ -176,124 -102,28 +193,145 @@@ OUTPUT_MAPPING ="Anything UNCLEAR": (str, ...),}+MERGE_PROMPT = """+# Context+{context}++<<<<<<< HEAD+## Old Tasks+{old_tasks}+-----++## Format example+{format_example}+-----+Role: You are a project manager; The goal is to merge the new PRD/technical design content from 'Context' into 'Old Tasks.' Based on this merged result, break down tasks, give a task list, and analyze task dependencies to start with the prerequisite modules.+Requirements: Based on the context, fill in the following missing information, each section name is a key in json. Here the granularity of the task is a file, if there are any missing files, you can supplement them+Attention: Use '##' to split sections, not '#', and '## <SECTION_NAME>' SHOULD WRITE BEFORE the code and triple quote.++## Required Python third-party packages: Provided in requirements.txt format++## Required Other language third-party packages: Provided in requirements.txt format++## Full API spec: Use OpenAPI 3.0. Describe all APIs that may be used by both frontend and backend.++## Logic Analysis: Provided as a Python list[list[str]. the first is filename, the second is class/method/function should be implemented in this file. Analyze the dependencies between the files, which work should be done first++## Task list: Provided as Python list[str]. Each str is a filename, the more at the beginning, the more it is a prerequisite dependency, should be done first++## Shared Knowledge: Anything that should be public like utils' functions, config's variables details that should make clear first.++## Anything UNCLEAR: Provide as Plain text. Make clear here. For example, don't forget a main entry. don't forget to init 3rd party libs.++output a properly formatted JSON, wrapped inside [CONTENT][/CONTENT] like "Format example" format,+and only output the json inside this tag, nothing else+"""++++=======++>>>>>>> send18/devclass WriteTasks(Action):def __init__(self, name="CreateTasks", context=None, llm=None):super().__init__(name, context, llm)++<<<<<<< HEAD+ async def run(self, with_messages, format=CONFIG.prompt_format):+ system_design_file_repo = CONFIG.git_repo.new_file_repository(SYSTEM_DESIGN_FILE_REPO)+ changed_system_designs = system_design_file_repo.changed_files++ tasks_file_repo = CONFIG.git_repo.new_file_repository(TASK_FILE_REPO)+ changed_tasks = tasks_file_repo.changed_files+ change_files = Documents()+ # Rewrite the system designs that have undergone changes based on the git head diff under+ # `docs/system_designs/`.+ for filename in changed_system_designs:+ task_doc = await self._update_tasks(+ filename=filename, system_design_file_repo=system_design_file_repo, tasks_file_repo=tasks_file_repo+ )+ change_files.docs[filename] = task_doc++ # Rewrite the task files that have undergone changes based on the git head diff under `docs/tasks/`.+ for filename in changed_tasks:+ if filename in change_files.docs:+ continue+ task_doc = await self._update_tasks(+ filename=filename, system_design_file_repo=system_design_file_repo, tasks_file_repo=tasks_file_repo+ )+ change_files.docs[filename] = task_doc++ if not change_files.docs:+ logger.info("Nothing has changed.")+ # Wait until all files under `docs/tasks/` are processed before sending the publish_message, leaving room for+ # global optimization in subsequent steps.+ return ActionOutput(content=change_files.json(), instruct_content=change_files)++ async def _update_tasks(self, filename, system_design_file_repo, tasks_file_repo):+ system_design_doc = await system_design_file_repo.get(filename)+ task_doc = await tasks_file_repo.get(filename)+ if task_doc:+ task_doc = await self._merge(system_design_doc=system_design_doc, task_doc=task_doc)+ else:+ rsp = await self._run_new_tasks(context=system_design_doc.content)+ task_doc = Document(+ root_path=TASK_FILE_REPO, filename=filename, content=rsp.instruct_content.json(ensure_ascii=False)+ )+ await tasks_file_repo.save(+ filename=filename, content=task_doc.content, dependencies={system_design_doc.root_relative_path}+ )+ await self._update_requirements(task_doc)+ await self._save_pdf(task_doc=task_doc)+ return task_doc++ async def _run_new_tasks(self, context, format=CONFIG.prompt_format):+ prompt_template, format_example = get_template(templates, format)+ prompt = prompt_template.format(context=context, format_example=format_example)+ rsp = await self._aask_v1(prompt, "task", OUTPUT_MAPPING, format=format)++=======+ async def _save(self, rsp):+ file_path = CONFIG.workspace / "docs/api_spec_and_tasks.md"+ async with aiofiles.open(file_path, "w") as f:+ await f.write(rsp.content)++ # Write requirements.txt+ requirements_path = CONFIG.workspace / "requirements.txt"++ async with aiofiles.open(requirements_path, "w") as f:+ await f.write(rsp.instruct_content.dict().get("Required Python third-party packages").strip('"\n'))++ async def run(self, context, **kwargs):+ prompt = PROMPT_TEMPLATE.format(context=context, format_example=FORMAT_EXAMPLE)+ rsp = await self._aask_v1(prompt, "task", OUTPUT_MAPPING)+ await self._save(rsp)++>>>>>>> send18/devreturn rsp+ async def _merge(self, system_design_doc, task_doc, format=CONFIG.prompt_format) -> Document:+ _, format_example = get_template(templates, format)+ prompt = MERGE_PROMPT.format(context=system_design_doc.content, old_tasks=task_doc.content,+ format_example=format_example)+ rsp = await self._aask_v1(prompt, "task", OUTPUT_MAPPING, format=format)+ task_doc.content = rsp.instruct_content.json(ensure_ascii=False)+ return task_doc++ @staticmethod+ async def _update_requirements(doc):+ m = json.loads(doc.content)+ packages = set(m.get("Required Python third-party packages", set()))+ file_repo = CONFIG.git_repo.new_file_repository()+ requirement_doc = await file_repo.get(filename=PACKAGE_REQUIREMENTS_FILENAME)+ if not requirement_doc:+ requirement_doc = Document(filename=PACKAGE_REQUIREMENTS_FILENAME, root_path=".", content="")+ lines = requirement_doc.content.splitlines()+ for pkg in lines:+ if pkg == "":+ continue+ packages.add(pkg)+ await file_repo.save(PACKAGE_REQUIREMENTS_FILENAME, content="\n".join(packages))++ @staticmethod+ async def _save_pdf(task_doc):+ await FileRepository.save_as(doc=task_doc, with_suffix=".md", relative_path=TASK_PDF_FILE_REPO)+class AssignTasks(Action):async def run(self, *args, **kwargs):diff --cc metagpt/actions/write_code.pyindex 1dda6466f,fd54ce699..b61e3886c--- a/metagpt/actions/write_code.py+++ b/metagpt/actions/write_code.py@@@ -4,28 -4,13 +4,37 @@@@Time : 2023/5/11 17:45@Author : alexanderwu@File : write_code.py+@Modified By: mashenquan, 2023-11-1. In accordance with Chapter 2.1.3 of RFC 116, modify the data type of the `cause_by`+ value of the `Message` object.+@Modified By: mashenquan, 2023-11-27.+ 1. Mark the location of Design, Tasks, Legacy Code and Debug logs in the PROMPT_TEMPLATE with markdown+ code-block formatting to enhance the understanding for the LLM.+ 2. Following the think-act principle, solidify the task parameters when creating the WriteCode object, rather+ than passing them in when calling the run function.+ 3. Encapsulate the input of RunCode into RunCodeContext and encapsulate the output of RunCode into+ RunCodeResult to standardize and unify parameter passing between WriteCode, RunCode, and DebugError."""++<<<<<<< HEAD+import json++from tenacity import retry, stop_after_attempt, wait_random_exponential++from metagpt.actions.action import Action+from metagpt.config import CONFIG+from metagpt.const import CODE_SUMMARIES_FILE_REPO, TEST_OUTPUTS_FILE_REPO, TASK_FILE_REPO, BUGFIX_FILENAME, \+ DOCS_FILE_REPO++=======+ from tenacity import retry, stop_after_attempt, wait_fixed++ from metagpt.actions.action import Action++>>>>>>> send18/devfrom metagpt.logs import logger-from metagpt.schema import Message+from metagpt.schema import CodingContext, Document, RunCodeResultfrom metagpt.utils.common import CodeParser++<<<<<<< HEAD+from metagpt.utils.file_repository import FileRepository++=======++>>>>>>> send18/devPROMPT_TEMPLATE = """NOTICE@@@ -86,61 -42,22 +95,75 @@@ ATTENTION: Use '##' to SPLIT SECTIONS,class WriteCode(Action):- def __init__(self, name="WriteCode", context: list[Message] = None, llm=None):+ def __init__(self, name="WriteCode", context=None, llm=None):super().__init__(name, context, llm)++<<<<<<< HEAD+ @retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))+ async def write_code(self, prompt) -> str:++=======+ def _is_invalid(self, filename):+ return any(i in filename for i in ["mp3", "wav"])++ @retry(stop=stop_after_attempt(2), wait=wait_fixed(1))+ async def write_code(self, prompt):++>>>>>>> send18/devcode_rsp = await self._aask(prompt)code = CodeParser.parse_code(block="", text=code_rsp)return code++<<<<<<< HEAD+ async def run(self, *args, **kwargs) -> CodingContext:+ bug_feedback = await FileRepository.get_file(filename=BUGFIX_FILENAME, relative_path=DOCS_FILE_REPO)+ coding_context = CodingContext.loads(self.context.content)+ test_doc = await FileRepository.get_file(+ filename="test_" + coding_context.filename + ".json", relative_path=TEST_OUTPUTS_FILE_REPO+ )+ summary_doc = None+ if coding_context.design_doc.filename:+ summary_doc = await FileRepository.get_file(+ filename=coding_context.design_doc.filename, relative_path=CODE_SUMMARIES_FILE_REPO+ )+ logs = ""+ if test_doc:+ test_detail = RunCodeResult.loads(test_doc.content)+ logs = test_detail.stderr+ code_context = await self._get_codes(coding_context.task_doc)+ prompt = PROMPT_TEMPLATE.format(+ design=coding_context.design_doc.content,+ tasks=coding_context.task_doc.content if coding_context.task_doc else "",+ code=code_context,+ logs=logs,+ feedback=bug_feedback.content if bug_feedback else "",+ filename=self.context.filename,+ summary_log=summary_doc.content if summary_doc else "",+ )+ logger.info(f"Writing {coding_context.filename}..")++=======+ async def run(self, context, filename):+ prompt = PROMPT_TEMPLATE.format(context=context, filename=filename)+ logger.info(f"Writing {filename}..")++>>>>>>> send18/devcode = await self.write_code(prompt)- # code_rsp = await self._aask_v1(prompt, "code_rsp", OUTPUT_MAPPING)- # self._save(context, filename, code)- return code+ if not coding_context.code_doc:+ coding_context.code_doc = Document(filename=coding_context.filename, root_path=CONFIG.src_workspace)+ coding_context.code_doc.content = code+ return coding_context++ @staticmethod+ async def _get_codes(task_doc) -> str:+ if not task_doc:+ return ""+ if not task_doc.content:+ task_doc.content = FileRepository.get_file(filename=task_doc.filename, relative_path=TASK_FILE_REPO)+ m = json.loads(task_doc.content)+ code_filenames = m.get("Task list", [])+ codes = []+ src_file_repo = CONFIG.git_repo.new_file_repository(relative_path=CONFIG.src_workspace)+ for filename in code_filenames:+ doc = await src_file_repo.get(filename=filename)+ if not doc:+ continue+ codes.append(doc.content)+ return "\n----------\n".join(codes)+diff --cc metagpt/actions/write_prd.pyindex aad2422ef,97f9138fd..d8042b3ed--- a/metagpt/actions/write_prd.py+++ b/metagpt/actions/write_prd.py@@@ -4,123 -4,19 +4,131 @@@@Time : 2023/5/11 17:45@Author : alexanderwu@File : write_prd.py+@Modified By: mashenquan, 2023/11/27.+ 1. According to Section 2.2.3.1 of RFC 135, replace file data in the message with the file name.+ 2. According to the design in Section 2.2.3.5.2 of RFC 135, add incremental iteration functionality.+ 3. Move the document storage operations related to WritePRD from the save operation of WriteDesign.+@Modified By: mashenquan, 2023/12/5. Move the generation logic of the project name to WritePRD."""-from typing import List, Tuple+from __future__ import annotations++import json+from pathlib import Path+from typing import List+ import aiofiles+from metagpt.actions import Action, ActionOutput+from metagpt.actions.fix_bug import FixBugfrom metagpt.actions.search_and_summarize import SearchAndSummarizefrom metagpt.config import CONFIG++<<<<<<< HEAD+from metagpt.const import (+ COMPETITIVE_ANALYSIS_FILE_REPO,+ DOCS_FILE_REPO,+ PRD_PDF_FILE_REPO,+ PRDS_FILE_REPO,+ REQUIREMENT_FILENAME, BUGFIX_FILENAME,+)+from metagpt.logs import logger+from metagpt.schema import Document, Documents, Message, BugFixContext+from metagpt.utils.common import CodeParser+from metagpt.utils.file_repository import FileRepository+from metagpt.utils.get_template import get_template+from metagpt.utils.mermaid import mermaid_to_file++templates = {+ "json": {+ "PROMPT_TEMPLATE": """+# Context+{{+ "Original Requirements": "{requirements}",+ "Search Information": ""+}}++## Format example+{format_example}+-----+Role: You are a professional product manager; the goal is to design a concise, usable, efficient product+Language: Please use the same language as the user requirement, but the title and code should be still in English. For example, if the user speaks Chinese, the specific text of your answer should also be in Chinese.+Requirements: According to the context, fill in the following missing information, note that each sections are returned in Python code triple quote form seperatedly.+ATTENTION: Output carefully referenced "Format example" in format.++## YOU NEED TO FULFILL THE BELOW JSON DOC++=======+ from metagpt.logs import logger+ from metagpt.utils.common import CodeParser+ from metagpt.utils.mermaid import mermaid_to_file++>>>>>>> send18/dev++{{+ "Language": "", # str, use the same language as the user requirement. en_us / zh_cn etc.+ "Original Requirements": "", # str, place the polished complete original requirements here+ "Project Name": "{project_name}", # str, if it's empty, name it with snake case style, like game_2048 / web_2048 / simple_crm etc.+ "Search Information": "",+ "Requirements": "",+ "Product Goals": [], # Provided as Python list[str], up to 3 clear, orthogonal product goals.+ "User Stories": [], # Provided as Python list[str], up to 5 scenario-based user stories+ "Competitive Analysis": [], # Provided as Python list[str], up to 8 competitive product analyses+ # Use mermaid quadrantChart code syntax. up to 14 competitive products. Translation: Distribute these competitor scores evenly between 0 and 1, trying to conform to a normal distribution centered around 0.5 as much as possible.+ "Competitive Quadrant Chart": "quadrantChart+ title Reach and engagement of campaigns+ x-axis Low Reach --> High Reach+ y-axis Low Engagement --> High Engagement+ quadrant-1 We should expand+ quadrant-2 Need to promote+ quadrant-3 Re-evaluate+ quadrant-4 May be improved+ Campaign A: [0.3, 0.6]+ Campaign B: [0.45, 0.23]+ Campaign C: [0.57, 0.69]+ Campaign D: [0.78, 0.34]+ Campaign E: [0.40, 0.34]+ Campaign F: [0.35, 0.78]",+ "Requirement Analysis": "", # Provide as Plain text.+ "Requirement Pool": [["P0","P0 requirement"],["P1","P1 requirement"]], # Provided as Python list[list[str], the parameters are requirement description, priority(P0/P1/P2), respectively, comply with PEP standards+ "UI Design draft": "", # Provide as Plain text. Be simple. Describe the elements and functions, also provide a simple style description and layout description.+ "Anything UNCLEAR": "", # Provide as Plain text. Try to clarify it.+}}-PROMPT_TEMPLATE = """+output a properly formatted JSON, wrapped inside [CONTENT][/CONTENT] like format example,+and only output the json inside this tag, nothing else+""",+ "FORMAT_EXAMPLE": """+[CONTENT]+{{+ "Language": "",+ "Original Requirements": "",+ "Project Name": "{project_name}",+ "Search Information": "",+ "Requirements": "",+ "Product Goals": [],+ "User Stories": [],+ "Competitive Analysis": [],+ "Competitive Quadrant Chart": "quadrantChart+ title Reach and engagement of campaigns+ x-axis Low Reach --> High Reach+ y-axis Low Engagement --> High Engagement+ quadrant-1 We should expand+ quadrant-2 Need to promote+ quadrant-3 Re-evaluate+ quadrant-4 May be improved+ Campaign A: [0.3, 0.6]+ Campaign B: [0.45, 0.23]+ Campaign C: [0.57, 0.69]+ Campaign D: [0.78, 0.34]+ Campaign E: [0.40, 0.34]+ Campaign F: [0.35, 0.78]",+ "Requirement Analysis": "",+ "Requirement Pool": [["P0","P0 requirement"],["P1","P1 requirement"]],+ "UI Design draft": "",+ "Anything UNCLEAR": "",+}}+[/CONTENT]+""",+ },+ "markdown": {+ "PROMPT_TEMPLATE": """# Context## Original Requirements{requirements}@@@ -237,7 -125,7 +245,11 @@@ OUTPUT_MAPPING ="Competitive Analysis": (List[str], ...),"Competitive Quadrant Chart": (str, ...),"Requirement Analysis": (str, ...),++<<<<<<< HEAD+ "Requirement Pool": (List[List[str]], ...),++=======+ "Requirement Pool": (List[Tuple[str, str]], ...),++>>>>>>> send18/dev"UI Design draft": (str, ...),"Anything UNCLEAR": (str, ...),}@@@ -376,94 -144,31 +388,125 @@@ class WritePRD(Action)logger.info(sas.result)logger.info(rsp)++<<<<<<< HEAD+ # logger.info(format)+ prompt_template, format_example = get_template(templates, format)+ project_name = CONFIG.project_name if CONFIG.project_name else ""+ format_example = format_example.format(project_name=project_name)+ # logger.info(prompt_template)+ # logger.info(format_example)+ prompt = prompt_template.format(+ requirements=requirements, search_information=info, format_example=format_example, project_name=project_name+ )+ # logger.info(prompt)+ # prd = await self._aask_v1(prompt, "prd", OUTPUT_MAPPING)+ prd = await self._aask_v1(prompt, "prd", OUTPUT_MAPPING, format=format)+ await self._rename_workspace(prd)+ return prd++ async def _is_relative_to(self, new_requirement_doc, old_prd_doc) -> bool:+ prompt = IS_RELATIVE_PROMPT.format(old_prd=old_prd_doc.content, requirements=new_requirement_doc.content)+ res = await self._aask(prompt=prompt)+ logger.info(f"REQ-RELATIVE:[{new_requirement_doc.root_relative_path}, {old_prd_doc.root_relative_path}]: {res}")+ if "YES" in res:+ return True+ return False++ async def _merge(self, new_requirement_doc, prd_doc, format=CONFIG.prompt_format) -> Document:+ if not CONFIG.project_name:+ CONFIG.project_name = Path(CONFIG.project_path).name+ prompt = MERGE_PROMPT.format(+ requirements=new_requirement_doc.content, old_prd=prd_doc.content, project_name=CONFIG.project_name+ )+ prd = await self._aask_v1(prompt, "prd", OUTPUT_MAPPING, format=format)+ prd_doc.content = prd.instruct_content.json(ensure_ascii=False)+ await self._rename_workspace(prd)+ return prd_doc++ async def _update_prd(self, requirement_doc, prd_doc, prds_file_repo, *args, **kwargs) -> Document | None:+ if not prd_doc:+ prd = await self._run_new_requirement(requirements=[requirement_doc.content], *args, **kwargs)+ new_prd_doc = Document(+ root_path=PRDS_FILE_REPO,+ filename=FileRepository.new_filename() + ".json",+ content=prd.instruct_content.json(ensure_ascii=False),+ )+ elif await self._is_relative_to(requirement_doc, prd_doc):+ new_prd_doc = await self._merge(requirement_doc, prd_doc)+ else:+ return None+ await prds_file_repo.save(filename=new_prd_doc.filename, content=new_prd_doc.content)+ await self._save_competitive_analysis(new_prd_doc)+ await self._save_pdf(new_prd_doc)+ return new_prd_doc++ @staticmethod+ async def _save_competitive_analysis(prd_doc):+ m = json.loads(prd_doc.content)+ quadrant_chart = m.get("Competitive Quadrant Chart")+ if not quadrant_chart:+ return+ pathname = (+ CONFIG.git_repo.workdir / Path(COMPETITIVE_ANALYSIS_FILE_REPO) / Path(prd_doc.filename).with_suffix("")+ )+ if not pathname.parent.exists():+ pathname.parent.mkdir(parents=True, exist_ok=True)+ await mermaid_to_file(quadrant_chart, pathname)++ @staticmethod+ async def _save_pdf(prd_doc):+ await FileRepository.save_as(doc=prd_doc, with_suffix=".md", relative_path=PRD_PDF_FILE_REPO)++ @staticmethod+ async def _rename_workspace(prd):+ if CONFIG.project_path: # Updating on the old version has already been specified if it's valid. According to+ # Section 2.2.3.10 of RFC 135+ if not CONFIG.project_name:+ CONFIG.project_name = Path(CONFIG.project_path).name+ return++ if not CONFIG.project_name:+ if isinstance(prd, ActionOutput):+ ws_name = prd.instruct_content.dict()["Project Name"]+ else:+ ws_name = CodeParser.parse_str(block="Project Name", text=prd)+ CONFIG.project_name = ws_name+ CONFIG.git_repo.rename_root(CONFIG.project_name)++ async def _is_bugfix(self, content):+ prompt = IS_BUGFIX_PROMPT.format(content=content)+ res = await self._aask(prompt=prompt)+ logger.info(f"IS_BUGFIX:{res}")+ if "YES" in res:+ return True+ return False++=======+ prompt = PROMPT_TEMPLATE.format(+ requirements=requirements, search_information=info, format_example=FORMAT_EXAMPLE+ )+ logger.debug(prompt)+ prd = await self._aask_v1(prompt, "prd", OUTPUT_MAPPING)++ await self._save(prd.content)+ return prd++ async def _save_prd(self, docs_path, resources_path, prd):+ prd_file = docs_path / "prd.md"+ quadrant_chart = CodeParser.parse_code(block="Competitive Quadrant Chart", text=prd)+ await mermaid_to_file(+ mermaid_code=quadrant_chart, output_file_without_suffix=resources_path / "competitive_analysis"+ )+ async with aiofiles.open(prd_file, "w") as f:+ await f.write(prd)+ logger.info(f"Saving PRD to {prd_file}")++ async def _save(self, prd):+ workspace = CONFIG.workspace+ workspace.mkdir(parents=True, exist_ok=True)++ docs_path = workspace / "docs"+ resources_path = workspace / "resources"+ docs_path.mkdir(parents=True, exist_ok=True)+ resources_path.mkdir(parents=True, exist_ok=True)+ await self._save_prd(docs_path, resources_path, prd)++>>>>>>> send18/devdiff --cc metagpt/config.pyindex aabd54c4b,908faaaaf..d3123b1f7--- a/metagpt/config.py+++ b/metagpt/config.py@@@ -1,23 -1,23 +1,23 @@@#!/usr/bin/env python# -*- coding: utf-8 -*-"""-Provide configuration, singleton.-@Modified BY: mashenquan, 2023/8/28. Replace the global variable `CONFIG` with `ContextVar`.+Provide configuration, singleton+@Modified By: mashenquan, 2023/11/27.+ 1. According to Section 2.2.3.11 of RFC 135, add git repository support.+ 2. Add the parameter `src_workspace` for the old version project path."""import datetime+ import jsonimport osfrom copy import deepcopy+from pathlib import Pathfrom typing import Anyfrom uuid import uuid4---import openaiimport yaml---from metagpt.const import OPTIONS, PROJECT_ROOT, WORKSPACE_ROOT+from metagpt.const import DEFAULT_WORKSPACE_ROOT, METAGPT_ROOT, OPTIONSfrom metagpt.logs import loggerfrom metagpt.tools import SearchEngineType, WebBrowserEngineType+ from metagpt.utils.cost_manager import CostManagerfrom metagpt.utils.singleton import Singleton@@@ -42,12 -42,13 +42,14 @@@ class Config(metaclass=Singleton)"""_instance = None- key_yaml_file = PROJECT_ROOT / "config/key.yaml"- default_yaml_file = PROJECT_ROOT / "config/config.yaml"+ home_yaml_file = Path.home() / ".metagpt/config.yaml"+ key_yaml_file = METAGPT_ROOT / "config/key.yaml"+ default_yaml_file = METAGPT_ROOT / "config/config.yaml"-- def __init__(self, yaml_file=default_yaml_file):++ def __init__(self, yaml_file=default_yaml_file, cost_data=""):self._init_with_config_files_and_env(yaml_file)- self.cost_manager = CostManager(**json.loads(self.COST_MANAGER)) if self.COST_MANAGER else CostManager()-++ # The agent needs to be billed per user, so billing information cannot be destroyed when the session ends.++ self.cost_manager = CostManager(**json.loads(cost_data)) if cost_data else CostManager()logger.info("Config loading done.")self._update()@@@ -96,9 -87,7 +97,8 @@@self.long_term_memory = self._get("LONG_TERM_MEMORY", False)if self.long_term_memory:logger.warning("LONG_TERM_MEMORY is True")- self.max_budget = self._get("MAX_BUDGET", 10.0)- self.total_cost = 0.0+ self.cost_manager.max_budget = self._get("MAX_BUDGET", 10.0)+ self.code_review_k_times = 2self.puppeteer_config = self._get("PUPPETEER_CONFIG", "")self.mmdc = self._get("MMDC", "mmdc")diff --cc metagpt/const.pyindex f6f64a27d,2323e3b6d..c2b6c308d--- a/metagpt/const.py+++ b/metagpt/const.py@@@ -3,53 -3,34 +3,51 @@@"""@Time : 2023/5/1 11:59@Author : alexanderwu-@File : const.py'-@Modified By: mashenquan, 2023/8/28. Add 'OPTIONS', 'DEFAULT_LANGUAGE', 'DEFAULT_MAX_TOKENS'...+@File : const.py+@Modified By: mashenquan, 2023-11-1. According to Section 2.2.1 and 2.2.2 of RFC 116, added key definitions for+ common properties in the Message.+@Modified By: mashenquan, 2023-11-27. Defines file repository paths according to Section 2.2.3.4 of RFC 135.+@Modified By: mashenquan, 2023/12/5. Add directories for code summarization.."""import contextvars+import osfrom pathlib import Path-+from loguru import logger-+import metagpt++OPTIONS = contextvars.ContextVar("OPTIONS")+++def get_metagpt_package_root():+ """Get the root directory of the installed package."""+ package_root = Path(metagpt.__file__).parent.parent+ logger.info(f"Package root set to {str(package_root)}")+ return package_root+++def get_metagpt_root():+ """Get the project root directory."""+ # Check if a project root is specified in the environment variable+ project_root_env = os.getenv("METAGPT_PROJECT_ROOT")+ if project_root_env:+ project_root = Path(project_root_env)+ logger.info(f"PROJECT_ROOT set from environment variable to {str(project_root)}")+ else:+ # Fallback to package root if no environment variable is set+ project_root = get_metagpt_package_root()+ return project_root-def get_project_root():- """逐级向上寻找项目根目录"""- current_path = Path.cwd()- while True:- if (- (current_path / ".git").exists()- or (current_path / ".project_root").exists()- or (current_path / ".gitignore").exists()- ):- return current_path- parent_path = current_path.parent- if parent_path == current_path:- raise Exception("Project root not found.")- current_path = parent_path---PROJECT_ROOT = get_project_root()-DATA_PATH = PROJECT_ROOT / "data"-WORKSPACE_ROOT = PROJECT_ROOT / "workspace"-PROMPT_PATH = PROJECT_ROOT / "metagpt/prompts"-UT_PATH = PROJECT_ROOT / "data/ut"+# METAGPT PROJECT ROOT AND VARS+- METAGPT_ROOT = get_metagpt_root()++METAGPT_ROOT = get_metagpt_root() # Dependent on METAGPT_PROJECT_ROOT+DEFAULT_WORKSPACE_ROOT = METAGPT_ROOT / "workspace"++DATA_PATH = METAGPT_ROOT / "data"+RESEARCH_PATH = DATA_PATH / "research"+TUTORIAL_PATH = DATA_PATH / "tutorial_docx"+INVOICE_OCR_TABLE_PATH = DATA_PATH / "invoice_table"+UT_PATH = DATA_PATH / "ut"SWAGGER_PATH = UT_PATH / "files/api/"UT_PY_PATH = UT_PATH / "files/ut/"API_QUESTIONS_PATH = UT_PATH / "files/question/"@@@ -65,31 -40,17 +63,46 @@@ SKILL_DIRECTORY = SOURCE_ROOT / "skillsMEM_TTL = 24 * 30 * 3600-OPTIONS = contextvars.ContextVar("OPTIONS")++MESSAGE_ROUTE_FROM = "sent_from"+MESSAGE_ROUTE_TO = "send_to"+MESSAGE_ROUTE_CAUSE_BY = "cause_by"+MESSAGE_META_ROLE = "role"+MESSAGE_ROUTE_TO_ALL = "<all>"+MESSAGE_ROUTE_TO_NONE = "<none>"++REQUIREMENT_FILENAME = "requirement.txt"+BUGFIX_FILENAME = "bugfix.txt"+PACKAGE_REQUIREMENTS_FILENAME = "requirements.txt"++DOCS_FILE_REPO = "docs"+PRDS_FILE_REPO = "docs/prds"+SYSTEM_DESIGN_FILE_REPO = "docs/system_design"+TASK_FILE_REPO = "docs/tasks"+COMPETITIVE_ANALYSIS_FILE_REPO = "resources/competitive_analysis"+DATA_API_DESIGN_FILE_REPO = "resources/data_api_design"+SEQ_FLOW_FILE_REPO = "resources/seq_flow"+SYSTEM_DESIGN_PDF_FILE_REPO = "resources/system_design"+PRD_PDF_FILE_REPO = "resources/prd"+TASK_PDF_FILE_REPO = "resources/api_spec_and_tasks"+TEST_CODES_FILE_REPO = "tests"+TEST_OUTPUTS_FILE_REPO = "test_outputs"+CODE_SUMMARIES_FILE_REPO = "docs/code_summaries"+CODE_SUMMARIES_PDF_FILE_REPO = "resources/code_summaries"++YAPI_URL = "http://yapi.deepwisdomai.com/"+++ DEFAULT_LANGUAGE = "English"+ DEFAULT_MAX_TOKENS = 1500+ COMMAND_TOKENS = 500+ BRAIN_MEMORY = "BRAIN_MEMORY"+ SKILL_PATH = "SKILL_PATH"+ SERPER_API_KEY = "SERPER_API_KEY"+++ # format+ BASE64_FORMAT = "base64"++ # REDIS+ REDIS_KEY = "REDIS_KEY"++diff --cc metagpt/document_store/faiss_store.pyindex b1faa3538,be4748b50..65685dffa--- a/metagpt/document_store/faiss_store.py+++ b/metagpt/document_store/faiss_store.py@@@ -21,10 -20,11 +21,18 @@@ from metagpt.logs import loggeclass FaissStore(LocalStore):++<<<<<<< HEAD+ def __init__(self, raw_data_path: Path, cache_dir=None, meta_col="source", content_col="output"):+ self.meta_col = meta_col+ self.content_col = content_col+ super().__init__(raw_data_path, cache_dir)++=======+ def __init__(self, raw_data: Path, cache_dir=None, meta_col="source", content_col="output", embedding_conf=None):+ self.meta_col = meta_col+ self.content_col = content_col+ self.embedding_conf = embedding_conf or {}+ super().__init__(raw_data, cache_dir)++>>>>>>> send18/devdef _load(self) -> Optional["FaissStore"]:index_file, store_file = self._get_index_and_store_fname()@@@ -84,6 -81,6 +92,12 @@@if __name__ == "__main__":faiss_store = FaissStore(DATA_PATH / "qcs/qcs_4w.json")++<<<<<<< HEAD+ logger.info(faiss_store.search("Oily Skin Facial Cleanser"))+ faiss_store.add([f"Oily Skin Facial Cleanser-{i}" for i in range(3)])+ logger.info(faiss_store.search("Oily Skin Facial Cleanser"))++=======+ logger.info(faiss_store.search("油皮洗面奶"))+ faiss_store.add([f"油皮洗面奶-{i}" for i in range(3)])+ logger.info(faiss_store.search("油皮洗面奶"))++>>>>>>> send18/devdiff --cc metagpt/llm.pyindex 2ad40cb1c,eeb665872..525d2a65e--- a/metagpt/llm.py+++ b/metagpt/llm.py@@@ -4,30 -4,41 +4,63 @@@@Time : 2023/5/11 14:45@Author : alexanderwu@File : llm.py+ @Modified By: mashenquan, 2023"""-+ from enum import Enum--import openai-from metagpt.config import CONFIG+from metagpt.provider.anthropic_api import Claude2 as Claude+from metagpt.provider.openai_api import OpenAIGPTAPI+from metagpt.provider.zhipuai_api import ZhiPuAIGPTAPI+from metagpt.provider.spark_api import SparkAPI+from metagpt.provider.human_provider import HumanProvider++from metagpt.provider.metagpt_llm_api import MetaGPTLLMAPI++_ = HumanProvider() # Avoid pre-commit error+ class LLMType(Enum):+ OPENAI = "OpenAI"+ METAGPT = "MetaGPT"+ CLAUDE = "Claude"+ UNKNOWN = "UNKNOWN"++ @classmethod+ def get(cls, value):+ for member in cls:+ if member.value == value:+ return member+ return cls.UNKNOWN+++ @classmethod++ def __missing__(cls, value):++ return cls.UNKNOWN+++++# Used in agents+ class LLMFactory:+ @staticmethod- def new_llm() -> object:- from metagpt.provider.anthropic_api import Claude2 as Claude- from metagpt.provider.metagpt_llm_api import MetaGPTLLMAPI as MetaGPT_LLM- from metagpt.provider.openai_api import OpenAIGPTAPI as OpenAI_LLM-- if CONFIG.LLM_TYPE == LLMType.OPENAI.value:- return OpenAI_LLM()- if CONFIG.LLM_TYPE == LLMType.METAGPT.value:- return MetaGPT_LLM()- if CONFIG.LLM_TYPE == LLMType.CLAUDE.value:++ def new_llm() -> "BaseGPTAPI":++ # Determine which type of LLM to use based on the validity of the key.++ if CONFIG.claude_api_key:+ return Claude()++ elif CONFIG.spark_api_key:++ return SparkAPI()++ elif CONFIG.zhipuai_api_key:++ return ZhiPuAIGPTAPI()++++ # MetaGPT uses the same parameters as OpenAI.++ constructors = {++ LLMType.OPENAI.value: OpenAIGPTAPI,++ LLMType.METAGPT.value: MetaGPTLLMAPI,++ }++ constructor = constructors.get(CONFIG.LLM_TYPE)++ if constructor:++ return constructor()++++ raise ValueError(f"Unsupported LLM TYPE: {CONFIG.LLM_TYPE}")+++- raise openai.InvalidRequestError(message=f"Unsupported LLM TYPE: {CONFIG.LLM_TYPE}", param=None)++# Used in metagpt+def LLM() -> "BaseGPTAPI":+ """ initialize different LLM instance according to the key field existence"""- # TODO a little trick, can use registry to initialize LLM instance further- if CONFIG.openai_api_key:- llm = OpenAIGPTAPI()- elif CONFIG.claude_api_key:- llm = Claude()- elif CONFIG.spark_api_key:- llm = SparkAPI()- elif CONFIG.zhipuai_api_key:- llm = ZhiPuAIGPTAPI()- else:- raise RuntimeError("You should config a LLM configuration first")-- return llm++ return LLMFactory.new_llm()diff --cc metagpt/management/skill_manager.pyindex b3181b64e,4f141832a..33f283680--- a/metagpt/management/skill_manager.py+++ b/metagpt/management/skill_manager.py@@@ -15,12 -15,11 +15,17 @@@ Skill = Actioclass SkillManager:- """用来管理所有技能"""+ """Used to manage all skills"""def __init__(self):++<<<<<<< HEAD+ self._llm = LLM()+ self._store = ChromaStore("skill_manager")+ self._skills: dict[str:Skill] = {}++=======+ self._store = ChromaStore('skill_manager')+ self._skills: dict[str: Skill] = {}++>>>>>>> send18/devdef add_skill(self, skill: Skill):"""diff --cc metagpt/provider/base_gpt_api.pyindex 162758527,e334e8a5d..088df5b19--- a/metagpt/provider/base_gpt_api.py+++ b/metagpt/provider/base_gpt_api.py@@@ -4,8 -4,8 +4,9 @@@@Time : 2023/5/5 23:04@Author : alexanderwu@File : base_gpt_api.py+ @Desc : mashenquan, 2023/8/22. + try catch"""+import jsonfrom abc import abstractmethodfrom typing import Optionaldiff --cc metagpt/provider/metagpt_llm_api.pyindex 000000000,7e79f0ae5..925ac6623mode 000000,100644..100644--- a/metagpt/provider/metagpt_llm_api.py+++ b/metagpt/provider/metagpt_llm_api.py@@@ -1,0 -1,16 +1,278 @@@+ # -*- coding: utf-8 -*-+ """+ @Time : 2023/8/30+ @Author : mashenquan+ @File : metagpt_llm_api.py+ @Desc : MetaGPT LLM related APIs+ """+-from metagpt.provider import OpenAIGPTAPI++from metagpt.provider.openai_api import OpenAIGPTAPI++# from metagpt.provider.base_gpt_api import BaseGPTAPI++# from metagpt.provider.openai_api import RateLimiter+++ class MetaGPTLLMAPI(OpenAIGPTAPI):+ """MetaGPT LLM api"""-+++ def __init__(self):- super().__init__()++ super(MetaGPTLLMAPI, self).__init__()++++ # def __init__(self):++ # self.__init_openai(CONFIG)++ # self.llm = openai++ # self.model = CONFIG.openai_api_model++ # self.auto_max_tokens = False++ # self._cost_manager = CostManager()++ # RateLimiter.__init__(self, rpm=self.rpm)++ #++ # def __init_openai(self, config):++ # openai.api_key = config.openai_api_key++ # if config.openai_api_base:++ # openai.api_base = config.openai_api_base++ # if config.openai_api_type:++ # openai.api_type = config.openai_api_type++ # openai.api_version = config.openai_api_version++ # self.rpm = int(config.get("RPM", 10))++ #++ # async def _achat_completion_stream(self, messages: list[dict]) -> str:++ # response = await openai.ChatCompletion.acreate(**self._cons_kwargs(messages), stream=True)++ #++ # # create variables to collect the stream of chunks++ # collected_chunks = []++ # collected_messages = []++ # # iterate through the stream of events++ # async for chunk in response:++ # collected_chunks.append(chunk) # save the event response++ # choices = chunk["choices"]++ # if len(choices) > 0:++ # chunk_message = chunk["choices"][0].get("delta", {}) # extract the message++ # collected_messages.append(chunk_message) # save the message++ # if "content" in chunk_message:++ # print(chunk_message["content"], end="")++ # print()++ #++ # full_reply_content = "".join([m.get("content", "") for m in collected_messages])++ # usage = self._calc_usage(messages, full_reply_content)++ # self._update_costs(usage)++ # return full_reply_content++ #++ # def _cons_kwargs(self, messages: list[dict], **configs) -> dict:++ # kwargs = {++ # "messages": messages,++ # "max_tokens": self.get_max_tokens(messages),++ # "n": 1,++ # "stop": None,++ # "temperature": 0.3,++ # "timeout": 3,++ # }++ # if configs:++ # kwargs.update(configs)++ #++ # if CONFIG.openai_api_type == "azure":++ # if CONFIG.deployment_name and CONFIG.deployment_id:++ # raise ValueError("You can only use one of the `deployment_id` or `deployment_name` model")++ # elif not CONFIG.deployment_name and not CONFIG.deployment_id:++ # raise ValueError("You must specify `DEPLOYMENT_NAME` or `DEPLOYMENT_ID` parameter")++ # kwargs_mode = (++ # {"engine": CONFIG.deployment_name}++ # if CONFIG.deployment_name++ # else {"deployment_id": CONFIG.deployment_id}++ # )++ # else:++ # kwargs_mode = {"model": self.model}++ # kwargs.update(kwargs_mode)++ # return kwargs++ #++ # async def _achat_completion(self, messages: list[dict]) -> dict:++ # rsp = await self.llm.ChatCompletion.acreate(**self._cons_kwargs(messages))++ # self._update_costs(rsp.get("usage"))++ # return rsp++ #++ # def _chat_completion(self, messages: list[dict]) -> dict:++ # rsp = self.llm.ChatCompletion.create(**self._cons_kwargs(messages))++ # self._update_costs(rsp)++ # return rsp++ #++ # def completion(self, messages: list[dict]) -> dict:++ # # if isinstance(messages[0], Message):++ # # messages = self.messages_to_dict(messages)++ # return self._chat_completion(messages)++ #++ # async def acompletion(self, messages: list[dict]) -> dict:++ # # if isinstance(messages[0], Message):++ # # messages = self.messages_to_dict(messages)++ # return await self._achat_completion(messages)++ #++ # @retry(++ # wait=wait_random_exponential(min=1, max=60),++ # stop=stop_after_attempt(6),++ # after=after_log(logger, logger.level("WARNING").name),++ # retry=retry_if_exception_type(APIConnectionError),++ # retry_error_callback=log_and_reraise,++ # )++ # async def acompletion_text(self, messages: list[dict], stream=False) -> str:++ # """when streaming, print each token in place."""++ # if stream:++ # return await self._achat_completion_stream(messages)++ # rsp = await self._achat_completion(messages)++ # return self.get_choice_text(rsp)++ #++ # def _func_configs(self, messages: list[dict], **kwargs) -> dict:++ # """++ # Note: Keep kwargs consistent with the parameters in the https://platform.openai.com/docs/api-reference/chat/create++ # """++ # if "tools" not in kwargs:++ # configs = {++ # "tools": [{"type": "function", "function": GENERAL_FUNCTION_SCHEMA}],++ # "tool_choice": GENERAL_TOOL_CHOICE,++ # }++ # kwargs.update(configs)++ #++ # return self._cons_kwargs(messages, **kwargs)++ #++ # def _chat_completion_function(self, messages: list[dict], **kwargs) -> dict:++ # rsp = self.llm.ChatCompletion.create(**self._func_configs(messages, **kwargs))++ # self._update_costs(rsp.get("usage"))++ # return rsp++ #++ # async def _achat_completion_function(self, messages: list[dict], **chat_configs) -> dict:++ # rsp = await self.llm.ChatCompletion.acreate(**self._func_configs(messages, **chat_configs))++ # self._update_costs(rsp.get("usage"))++ # return rsp++ #++ # def _process_message(self, messages: Union[str, Message, list[dict], list[Message], list[str]]) -> list[dict]:++ # """convert messages to list[dict]."""++ # if isinstance(messages, list):++ # messages = [Message(msg) if isinstance(msg, str) else msg for msg in messages]++ # return [msg if isinstance(msg, dict) else msg.to_dict() for msg in messages]++ #++ # if isinstance(messages, Message):++ # messages = [messages.to_dict()]++ # elif isinstance(messages, str):++ # messages = [{"role": "user", "content": messages}]++ # else:++ # raise ValueError(++ # f"Only support messages type are: str, Message, list[dict], but got {type(messages).__name__}!"++ # )++ # return messages++ #++ # def ask_code(self, messages: Union[str, Message, list[dict]], **kwargs) -> dict:++ # """Use function of tools to ask a code.++ #++ # Note: Keep kwargs consistent with the parameters in the https://platform.openai.com/docs/api-reference/chat/create++ #++ # Examples:++ #++ # >>> llm = OpenAIGPTAPI()++ # >>> llm.ask_code("Write a python hello world code.")++ # {'language': 'python', 'code': "print('Hello, World!')"}++ # >>> msg = [{'role': 'user', 'content': "Write a python hello world code."}]++ # >>> llm.ask_code(msg)++ # {'language': 'python', 'code': "print('Hello, World!')"}++ # """++ # messages = self._process_message(messages)++ # rsp = self._chat_completion_function(messages, **kwargs)++ # return self.get_choice_function_arguments(rsp)++ #++ # async def aask_code(self, messages: Union[str, Message, list[dict]], **kwargs) -> dict:++ # """Use function of tools to ask a code.++ #++ # Note: Keep kwargs consistent with the parameters in the https://platform.openai.com/docs/api-reference/chat/create++ #++ # Examples:++ #++ # >>> llm = OpenAIGPTAPI()++ # >>> rsp = await llm.ask_code("Write a python hello world code.")++ # >>> rsp++ # {'language': 'python', 'code': "print('Hello, World!')"}++ # >>> msg = [{'role': 'user', 'content': "Write a python hello world code."}]++ # >>> rsp = await llm.aask_code(msg) # -> {'language': 'python', 'code': "print('Hello, World!')"}++ # """++ # messages = self._process_message(messages)++ # rsp = await self._achat_completion_function(messages, **kwargs)++ # return self.get_choice_function_arguments(rsp)++ #++ # def _calc_usage(self, messages: list[dict], rsp: str) -> dict:++ # usage = {}++ # if CONFIG.calc_usage:++ # try:++ # prompt_tokens = count_message_tokens(messages, self.model)++ # completion_tokens = count_string_tokens(rsp, self.model)++ # usage["prompt_tokens"] = prompt_tokens++ # usage["completion_tokens"] = completion_tokens++ # return usage++ # except Exception as e:++ # logger.error("usage calculation failed!", e)++ # else:++ # return usage++ #++ # async def acompletion_batch(self, batch: list[list[dict]]) -> list[dict]:++ # """Return full JSON"""++ # split_batches = self.split_batches(batch)++ # all_results = []++ #++ # for small_batch in split_batches:++ # logger.info(small_batch)++ # await self.wait_if_needed(len(small_batch))++ #++ # future = [self.acompletion(prompt) for prompt in small_batch]++ # results = await asyncio.gather(*future)++ # logger.info(results)++ # all_results.extend(results)++ #++ # return all_results++ #++ # async def acompletion_batch_text(self, batch: list[list[dict]]) -> list[str]:++ # """Only return plain text"""++ # raw_results = await self.acompletion_batch(batch)++ # results = []++ # for idx, raw_result in enumerate(raw_results, start=1):++ # result = self.get_choice_text(raw_result)++ # results.append(result)++ # logger.info(f"Result of task {idx}: {result}")++ # return results++ #++ # def _update_costs(self, usage: dict):++ # if CONFIG.calc_usage:++ # try:++ # prompt_tokens = int(usage["prompt_tokens"])++ # completion_tokens = int(usage["completion_tokens"])++ # self._cost_manager.update_cost(prompt_tokens, completion_tokens, self.model)++ # except Exception as e:++ # logger.error("updating costs failed!", e)++ #++ # def get_costs(self) -> Costs:++ # return self._cost_manager.get_costs()++ #++ # def get_max_tokens(self, messages: list[dict]):++ # if not self.auto_max_tokens:++ # return CONFIG.max_tokens_rsp++ # return get_max_completion_tokens(messages, self.model, CONFIG.max_tokens_rsp)++ #++ # def moderation(self, content: Union[str, list[str]]):++ # try:++ # if not content:++ # logger.error("content cannot be empty!")++ # else:++ # rsp = self._moderation(content=content)++ # return rsp++ # except Exception as e:++ # logger.error(f"moderating failed:{e}")++ #++ # def _moderation(self, content: Union[str, list[str]]):++ # rsp = self.llm.Moderation.create(input=content)++ # return rsp++ #++ # async def amoderation(self, content: Union[str, list[str]]):++ # try:++ # if not content:++ # logger.error("content cannot be empty!")++ # else:++ # rsp = await self._amoderation(content=content)++ # return rsp++ # except Exception as e:++ # logger.error(f"moderating failed:{e}")++ #++ # async def _amoderation(self, content: Union[str, list[str]]):++ # rsp = await self.llm.Moderation.acreate(input=content)++ # return rspdiff --cc metagpt/provider/openai_api.pyindex a24748e41,953043912..58d04cf84--- a/metagpt/provider/openai_api.py+++ b/metagpt/provider/openai_api.py@@@ -5,32 -5,27 +5,31 @@@@File : openai.py@Modified By: mashenquan, 2023/8/20. Remove global configuration `CONFIG`, enable configuration support for business isolation;Change cost control from global to company level.+@Modified By: mashenquan, 2023/11/21. Fix bug: ReadTimeout.+@Modified By: mashenquan, 2023/12/1. Fix bug: Unclosed connection caused by openai 0.x."""- import asyncio- import time- from typing import NamedTuple, Union+- import openai++from typing import Union+from openai import APIConnectionError, AsyncAzureOpenAI, AsyncOpenAI, RateLimitError+from openai.types import CompletionUsage+ import asyncio+ import time-+ import openai-from openai.error import APIConnectionError, RateLimitErrorfrom tenacity import (after_log,retry,retry_if_exception_type,stop_after_attempt,- wait_exponential,- wait_fixed,+ wait_random_exponential,)--from metagpt.config import CONFIG+ from metagpt.llm import LLMTypefrom metagpt.logs import loggerfrom metagpt.provider.base_gpt_api import BaseGPTAPI+from metagpt.provider.constant import GENERAL_FUNCTION_SCHEMA, GENERAL_TOOL_CHOICE+from metagpt.schema import Message- from metagpt.utils.singleton import Singleton+ from metagpt.utils.cost_manager import Costsfrom metagpt.utils.token_counter import (- TOKEN_COSTS,count_message_tokens,count_string_tokens,get_max_completion_tokens,@@@ -151,64 -77,65 +81,63 @@@ class OpenAIGPTAPI(BaseGPTAPI, RateLimiself.model = CONFIG.openai_api_modelself.auto_max_tokens = Falseself.rpm = int(CONFIG.get("RPM", 10))+ if CONFIG.openai_api_type == "azure":+ # https://learn.microsoft.com/zh-cn/azure/ai-services/openai/how-to/migration?tabs=python-new%2Cdalle-fix+ self._client = AsyncAzureOpenAI(+ api_key=CONFIG.openai_api_key,+ api_version=CONFIG.openai_api_version,+ azure_endpoint=CONFIG.openai_api_base,+ )+ else:+ # https://github.com/openai/openai-python#async-usage+ self._client = AsyncOpenAI(api_key=CONFIG.openai_api_key, base_url=CONFIG.openai_api_base)- self._cost_manager = CostManager()RateLimiter.__init__(self, rpm=self.rpm)- async def _achat_completion_stream(self, messages: list[dict]) -> str:- response = await openai.ChatCompletion.acreate(**self._cons_kwargs(messages), stream=True)+ async def _achat_completion_stream(self, messages: list[dict], timeout=3) -> str:+ kwargs = self._cons_kwargs(messages, timeout=timeout)+ response = await self._client.chat.completions.create(**kwargs, stream=True)# iterate through the stream of eventsasync for chunk in response:- chunk_message = chunk["choices"][0]["delta"] # extract the message- if "content" in chunk_message:- yield chunk_message["content"]+ chunk_message = chunk.choices[0].delta.content or "" # extract the message+ yield chunk_message++ def _cons_kwargs(self, messages: list[dict], timeout=3, **configs) -> dict:+ kwargs = {+ "messages": messages,+ "max_tokens": self.get_max_tokens(messages),+ "n": 1,+ "stop": None,+ "temperature": 0.3,+ }+ if configs:+ kwargs.update(configs)- def _cons_kwargs(self, messages: list[dict]) -> dict:if CONFIG.openai_api_type == "azure":- kwargs = {- "deployment_id": CONFIG.deployment_id,- "messages": messages,- "max_tokens": self.get_max_tokens(messages),- "n": 1,- "stop": None,- "temperature": 0.3,- }+ kwargs["model"] = CONFIG.deployment_idelse:- kwargs = {- "model": self.model,- "messages": messages,- "max_tokens": self.get_max_tokens(messages),- "n": 1,- "stop": None,- "temperature": 0.3,- }- kwargs["timeout"] = 3- kwargs["api_base"] = CONFIG.openai_api_base- kwargs["api_key"] = CONFIG.openai_api_key- kwargs["api_type"] = CONFIG.openai_api_type- kwargs["api_version"] = CONFIG.openai_api_version- return kwargs+ kwargs["model"] = self.model+ kwargs["timeout"] = max(CONFIG.TIMEOUT, timeout) if CONFIG.TIMEOUT is not None else timeout- async def _achat_completion(self, messages: list[dict]) -> dict:- rsp = await openai.ChatCompletion.acreate(**self._cons_kwargs(messages))- self._update_costs(rsp.get("usage"))- return rsp+ return kwargs- def _chat_completion(self, messages: list[dict]) -> dict:- rsp = openai.ChatCompletion.create(**self._cons_kwargs(messages))- self._update_costs(rsp)- return rsp+ async def _achat_completion(self, messages: list[dict], timeout=3) -> dict:+ kwargs = self._cons_kwargs(messages, timeout=timeout)+ rsp = await self._client.chat.completions.create(**kwargs)+ self._update_costs(rsp.usage)+ return rsp.dict()- def completion(self, messages: list[dict]) -> dict:- # if isinstance(messages[0], Message):- # messages = self.messages_to_dict(messages)- return self._chat_completion(messages)+ def completion(self, messages: list[dict], timeout=3) -> dict:+ loop = self.get_event_loop()+ return loop.run_until_complete(self.acompletion(messages, timeout=timeout))- async def acompletion(self, messages: list[dict]) -> dict:+ async def acompletion(self, messages: list[dict], timeout=3) -> dict:# if isinstance(messages[0], Message):# messages = self.messages_to_dict(messages)- return await self._achat_completion(messages)+ return await self._achat_completion(messages, timeout=timeout)@retry(- stop=stop_after_attempt(3),- wait=wait_fixed(1),+ wait=wait_random_exponential(min=1, max=60),+ stop=stop_after_attempt(6),after=after_log(logger, logger.level("WARNING").name),retry=retry_if_exception_type(APIConnectionError),retry_error_callback=log_and_reraise,@@@ -360,53 -207,25 +289,63 @@@logger.info(f"Result of task {idx}: {result}")return results- def _update_costs(self, usage: dict):+ def _update_costs(self, usage: CompletionUsage):if CONFIG.calc_usage:- prompt_tokens = usage.prompt_tokens- completion_tokens = usage.completion_tokens- self._cost_manager.update_cost(prompt_tokens, completion_tokens, self.model)+ try:- prompt_tokens = int(usage["prompt_tokens"])- completion_tokens = int(usage["completion_tokens"])++ prompt_tokens = usage.prompt_tokens++ completion_tokens = usage.completion_tokens+ CONFIG.cost_manager.update_cost(prompt_tokens, completion_tokens, self.model)+ except Exception as e:+ logger.error("updating costs failed!", e)def get_costs(self) -> Costs:- return self._cost_manager.get_costs()+ return CONFIG.cost_manager.get_costs()def get_max_tokens(self, messages: list[dict]):if not self.auto_max_tokens:return CONFIG.max_tokens_rspreturn get_max_completion_tokens(messages, self.model, CONFIG.max_tokens_rsp)+ def moderation(self, content: Union[str, list[str]]):+ loop = self.get_event_loop()+ loop.run_until_complete(self.amoderation(content=content))++ async def amoderation(self, content: Union[str, list[str]]):+ try:+ if not content:+ logger.error("content cannot be empty!")+ else:+ rsp = await self._amoderation(content=content)+ return rsp+ except Exception as e:+ logger.error(f"moderating failed:{e}")++ async def _amoderation(self, content: Union[str, list[str]]):+ rsp = await self._client.moderations.create(input=content)+ return rsp++ async def close(self):+ """Close connection"""+ if not self._client:+ return+ await self._client.close()+ self._client = None++ @staticmethod+ def get_event_loop():+ try:+ return asyncio.get_event_loop()+ except RuntimeError as e:+ if "There is no current event loop in thread" in str(e):+ loop = asyncio.new_event_loop()+ asyncio.set_event_loop(loop)+ return loop+ else:+ raise e+++ async def get_summary(self, text: str, max_words=200, keep_language: bool = False, **kwargs) -> str:+ from metagpt.memory.brain_memory import BrainMemory++ memory = BrainMemory(llm_type=LLMType.OPENAI.value, historical_summary=text, cacheable=False)+ return await memory.summarize(llm=self, max_words=max_words, keep_language=keep_language)++diff --cc metagpt/roles/engineer.pyindex 4f7f0b796,97d0af087..e1ab3b06b--- a/metagpt/roles/engineer.py+++ b/metagpt/roles/engineer.py@@@ -4,302 -4,201 +4,466 @@@@Time : 2023/5/11 14:43@Author : alexanderwu@File : engineer.py+@Modified By: mashenquan, 2023-11-1. In accordance with Chapter 2.2.1 and 2.2.2 of RFC 116:+ 1. Modify the data type of the `cause_by` value in the `Message` to a string, and utilize the new message+ distribution feature for message filtering.+ 2. Consolidate message reception and processing logic within `_observe`.+ 3. Fix bug: Add logic for handling asynchronous message processing when messages are not ready.+ 4. Supplemented the external transmission of internal messages.+@Modified By: mashenquan, 2023-11-27.+ 1. According to Section 2.2.3.1 of RFC 135, replace file data in the message with the file name.+ 2. According to the design in Section 2.2.3.5.5 of RFC 135, add incremental iteration functionality.+@Modified By: mashenquan, 2023-12-5. Enhance the workflow to navigate to WriteCode or QaEngineer based on the results+ of SummarizeCode."""++<<<<<<< HEAD+from __future__ import annotations++import json+from collections import defaultdict++=======+ import asyncio+ from collections import OrderedDict++>>>>>>> send18/devfrom pathlib import Path+from typing import Set++<<<<<<< HEAD+from metagpt.actions import Action, WriteCode, WriteCodeReview, WriteTasks+from metagpt.actions.fix_bug import FixBug+from metagpt.actions.summarize_code import SummarizeCode+from metagpt.config import CONFIG+from metagpt.const import (+ CODE_SUMMARIES_FILE_REPO,+ CODE_SUMMARIES_PDF_FILE_REPO,+ SYSTEM_DESIGN_FILE_REPO,+ TASK_FILE_REPO,+)+from metagpt.logs import logger+from metagpt.roles import Role+from metagpt.schema import (+ CodeSummarizeContext,+ CodingContext,+ Document,+ Documents,+ Message,+)+from metagpt.utils.common import any_to_name, any_to_str, any_to_str_set++=======+ import aiofiles++ from metagpt.actions import WriteCode, WriteCodeReview, WriteDesign, WriteTasks+ from metagpt.config import CONFIG+ from metagpt.logs import logger+ from metagpt.roles import Role+ from metagpt.schema import Message+ from metagpt.utils.common import CodeParser+ from metagpt.utils.special_tokens import FILENAME_CODE_SEP, MSG_SEP+++>>>>>>> send18/dev-async def gather_ordered_k(coros, k) -> list:- tasks = OrderedDict()- results = [None] * len(coros)- done_queue = asyncio.Queue()+IS_PASS_PROMPT = """+{context}- for i, coro in enumerate(coros):- if len(tasks) >= k:- done, _ = await asyncio.wait(tasks.keys(), return_when=asyncio.FIRST_COMPLETED)- for task in done:- index = tasks.pop(task)- await done_queue.put((index, task.result()))- task = asyncio.create_task(coro)- tasks[task] = i-- if tasks:- done, _ = await asyncio.wait(tasks.keys())- for task in done:- index = tasks[task]- await done_queue.put((index, task.result()))+----+Does the above log indicate anything that needs to be done?+If there are any tasks to be completed, please answer 'NO' along with the to-do list in JSON format;+otherwise, answer 'YES' in JSON format.+"""- while not done_queue.empty():- index, result = await done_queue.get()- results[index] = result- return results+class Engineer(Role):+ """+ Represents an Engineer role responsible for writing and possibly reviewing code.+ Attributes:+ name (str): Name of the engineer.+ profile (str): Role profile, default is 'Engineer'.+ goal (str): Goal of the engineer.+ constraints (str): Constraints for the engineer.+ n_borg (int): Number of borgs.+ use_code_review (bool): Whether to use code review.+ """++<<<<<<< HEAD+ def __init__(+ self,+ name: str = "Alex",+ profile: str = "Engineer",+ goal: str = "Write elegant, readable, extensible, efficient code",+ constraints: str = "The code should conform to standards like PEP8 and be modular and maintainable",+ n_borg: int = 1,+ use_code_review: bool = False,+ ) -> None:+ """Initializes the Engineer role with given attributes."""++=======+ class Engineer(Role):+ def __init__(+ self,+ name="Alex",+ profile="Engineer",+ goal="Write elegant, readable, extensible, efficient code",+ constraints="The code you write should conform to code standard like PEP8, be modular, easy to read and maintain",+ n_borg=1,+ use_code_review=False,+ ):++>>>>>>> send18/devsuper().__init__(name, profile, goal, constraints)- self._init_actions([WriteCode])self.use_code_review = use_code_review- if self.use_code_review:- self._init_actions([WriteCode, WriteCodeReview])- self._watch([WriteTasks])- self.todos = []+ self._watch([WriteTasks, SummarizeCode, WriteCode, WriteCodeReview, FixBug])+ self.code_todos = []+ self.summarize_todos = []self.n_borg = n_borg+ self._next_todo = any_to_name(WriteCode)++ @staticmethod+ def _parse_tasks(task_msg: Document) -> list[str]:+ m = json.loads(task_msg.content)+ return m.get("Task list")++<<<<<<< HEAD+ async def _act_sp_with_cr(self, review=False) -> Set[str]:+ changed_files = set()+ src_file_repo = CONFIG.git_repo.new_file_repository(CONFIG.src_workspace)+ for todo in self.code_todos:+ """+ # Select essential information from the historical data to reduce the length of the prompt (summarized from human experience):+ 1. All from Architect+ 2. All from ProjectManager+ 3. Do we need other codes (currently needed)?+ TODO: The goal is not to need it. After clear task decomposition, based on the design idea, you should be able to write a single file without needing other codes. If you can't, it means you need a clearer definition. This is the key to writing longer code.+ """+ coding_context = await todo.run()+ # Code review+ if review:+ coding_context = await WriteCodeReview(context=coding_context, llm=self._llm).run()+ await src_file_repo.save(+ coding_context.filename,+ dependencies={coding_context.design_doc.root_relative_path, coding_context.task_doc.root_relative_path},+ content=coding_context.code_doc.content,+ )+ msg = Message(+ content=coding_context.json(), instruct_content=coding_context, role=self.profile, cause_by=WriteCode+ )++=======+ @classmethod+ def parse_tasks(self, task_msg: Message) -> list[str]:+ if task_msg.instruct_content:+ return task_msg.instruct_content.dict().get("Task list")+ return CodeParser.parse_file_list(block="Task list", text=task_msg.content)++ @classmethod+ def parse_code(self, code_text: str) -> str:+ return CodeParser.parse_code(block="", text=code_text)++ @classmethod+ def parse_workspace(cls, system_design_msg: Message) -> str:+ if system_design_msg.instruct_content:+ return system_design_msg.instruct_content.dict().get("Python package name").strip().strip("'").strip('"')+ return CodeParser.parse_str(block="Python package name", text=system_design_msg.content)++ def get_workspace(self) -> Path:+ msg = self._rc.memory.get_by_action(WriteDesign)[-1]+ if not msg:+ return CONFIG.workspace / "src"+ workspace = self.parse_workspace(msg)+ # Codes are written in workspace/{package_name}/{package_name}+ return CONFIG.workspace / workspace++ async def write_file(self, filename: str, code: str):+ workspace = self.get_workspace()+ filename = filename.replace('"', "").replace("\n", "")+ file = workspace / filename+ file.parent.mkdir(parents=True, exist_ok=True)+ async with aiofiles.open(file, "w") as f:+ await f.write(code)+ return file++ def recv(self, message: Message) -> None:+ self._rc.memory.add(message)+ if message in self._rc.important_memory:+ self.todos = self.parse_tasks(message)++ async def _act_mp(self) -> Message:+ # self.recreate_workspace()+ todo_coros = []+ for todo in self.todos:+ todo_coro = WriteCode().run(+ context=self._rc.memory.get_by_actions([WriteTasks, WriteDesign]), filename=todo+ )+ todo_coros.append(todo_coro)++ rsps = await gather_ordered_k(todo_coros, self.n_borg)+ for todo, code_rsp in zip(self.todos, rsps):+ _ = self.parse_code(code_rsp)+ logger.info(todo)+ logger.info(code_rsp)+ # self.write_file(todo, code)+ msg = Message(content=code_rsp, role=self.profile, cause_by=type(self._rc.todo))self._rc.memory.add(msg)+ del self.todos[0]+ logger.info(f"Done {self.get_workspace()} generating.")+ msg = Message(content="all done.", role=self.profile, cause_by=type(self._rc.todo))+ return msg++ async def _act_sp(self) -> Message:+ code_msg_all = [] # gather all code info, will pass to qa_engineer for tests later+ instruct_content = {}+ for todo in self.todos:+ code = await WriteCode().run(context=self._rc.history, filename=todo)+ # logger.info(todo)+ # logger.info(code_rsp)+ # code = self.parse_code(code_rsp)+ file_path = await self.write_file(todo, code)+ msg = Message(content=code, role=self.profile, cause_by=type(self._rc.todo))++>>>>>>> send18/dev+ self._rc.memory.add(msg)+ instruct_content[todo] = code+++<<<<<<< HEAD+ changed_files.add(coding_context.code_doc.filename)+ if not changed_files:+ logger.info("Nothing has changed.")+ return changed_files++ async def _act(self) -> Message | None:+ """Determines the mode of action based on whether code review is used."""+ if self._rc.todo is None:+ return None+ if isinstance(self._rc.todo, WriteCode):+ self._next_todo = any_to_name(SummarizeCode)+ return await self._act_write_code()+ if isinstance(self._rc.todo, SummarizeCode):+ self._next_todo = any_to_name(WriteCode)+ return await self._act_summarize()+ return None++ async def _act_write_code(self):+ changed_files = await self._act_sp_with_cr(review=self.use_code_review)+ return Message(+ content="\n".join(changed_files),+ role=self.profile,+ cause_by=WriteCodeReview if self.use_code_review else WriteCode,+ send_to=self,+ sent_from=self,++=======+ # code_msg = todo + FILENAME_CODE_SEP + str(file_path)+ code_msg = (todo, file_path)+ code_msg_all.append(code_msg)++ logger.info(f"Done {self.get_workspace()} generating.")+ msg = Message(+ content=MSG_SEP.join(todo + FILENAME_CODE_SEP + str(file_path) for todo, file_path in code_msg_all),+ instruct_content=instruct_content,+ role=self.profile,+ cause_by=type(self._rc.todo),+ send_to="QaEngineer",++>>>>>>> send18/dev)- return msg++<<<<<<< HEAD+ async def _act_summarize(self):+ code_summaries_file_repo = CONFIG.git_repo.new_file_repository(CODE_SUMMARIES_FILE_REPO)+ code_summaries_pdf_file_repo = CONFIG.git_repo.new_file_repository(CODE_SUMMARIES_PDF_FILE_REPO)+ tasks = []+ src_relative_path = CONFIG.src_workspace.relative_to(CONFIG.git_repo.workdir)+ for todo in self.summarize_todos:+ summary = await todo.run()+ summary_filename = Path(todo.context.design_filename).with_suffix(".md").name+ dependencies = {todo.context.design_filename, todo.context.task_filename}+ for filename in todo.context.codes_filenames:+ rpath = src_relative_path / filename+ dependencies.add(str(rpath))+ await code_summaries_pdf_file_repo.save(+ filename=summary_filename, content=summary, dependencies=dependencies+ )+ is_pass, reason = await self._is_pass(summary)+ if not is_pass:+ todo.context.reason = reason+ tasks.append(todo.context.dict())+ await code_summaries_file_repo.save(+ filename=Path(todo.context.design_filename).name,+ content=todo.context.json(),+ dependencies=dependencies,+ )+ else:+ await code_summaries_file_repo.delete(filename=Path(todo.context.design_filename).name)++ logger.info(f"--max-auto-summarize-code={CONFIG.max_auto_summarize_code}")+ if not tasks or CONFIG.max_auto_summarize_code == 0:+ return Message(+ content="",+ role=self.profile,+ cause_by=SummarizeCode,+ sent_from=self,+ send_to="Edward", # The name of QaEngineer+ )+ # The maximum number of times the 'SummarizeCode' action is automatically invoked, with -1 indicating unlimited.+ # This parameter is used for debugging the workflow.+ CONFIG.max_auto_summarize_code -= 1 if CONFIG.max_auto_summarize_code > 0 else 0+ return Message(+ content=json.dumps(tasks), role=self.profile, cause_by=SummarizeCode, send_to=self, sent_from=self+ )++ async def _is_pass(self, summary) -> (str, str):+ rsp = await self._llm.aask(msg=IS_PASS_PROMPT.format(context=summary), stream=False)+ logger.info(rsp)+ if "YES" in rsp:+ return True, rsp+ return False, rsp++ async def _think(self) -> Action | None:+ if not CONFIG.src_workspace:+ CONFIG.src_workspace = CONFIG.git_repo.workdir / CONFIG.git_repo.workdir.name+ write_code_filters = any_to_str_set([WriteTasks, SummarizeCode, FixBug])+ summarize_code_filters = any_to_str_set([WriteCode, WriteCodeReview])+ if not self._rc.news:+ return None+ msg = self._rc.news[0]+ if msg.cause_by in write_code_filters:+ logger.info(f"TODO WriteCode:{msg.json()}")+ await self._new_code_actions(bug_fix=msg.cause_by == any_to_str(FixBug))+ return self._rc.todo+ if msg.cause_by in summarize_code_filters and msg.sent_from == any_to_str(self):+ logger.info(f"TODO SummarizeCode:{msg.json()}")+ await self._new_summarize_actions()+ return self._rc.todo+ return None++ @staticmethod+ async def _new_coding_context(+ filename, src_file_repo, task_file_repo, design_file_repo, dependency+ ) -> CodingContext:+ old_code_doc = await src_file_repo.get(filename)+ if not old_code_doc:+ old_code_doc = Document(root_path=str(src_file_repo.root_path), filename=filename, content="")+ dependencies = {Path(i) for i in await dependency.get(old_code_doc.root_relative_path)}+ task_doc = None+ design_doc = None+ for i in dependencies:+ if str(i.parent) == TASK_FILE_REPO:+ task_doc = await task_file_repo.get(i.name)+ elif str(i.parent) == SYSTEM_DESIGN_FILE_REPO:+ design_doc = await design_file_repo.get(i.name)+ context = CodingContext(filename=filename, design_doc=design_doc, task_doc=task_doc, code_doc=old_code_doc)+ return context++ @staticmethod+ async def _new_coding_doc(filename, src_file_repo, task_file_repo, design_file_repo, dependency):+ context = await Engineer._new_coding_context(+ filename, src_file_repo, task_file_repo, design_file_repo, dependency++=======+ async def _act_sp_precision(self) -> Message:+ code_msg_all = [] # gather all code info, will pass to qa_engineer for tests later+ instruct_content = {}+ for todo in self.todos:+ """+ # 从历史信息中挑选必须的信息,以减少prompt长度(人工经验总结)+ 1. Architect全部+ 2. ProjectManager全部+ 3. 是否需要其他代码(暂时需要)?+ TODO:目标是不需要。在任务拆分清楚后,根据设计思路,不需要其他代码也能够写清楚单个文件,如果不能则表示还需要在定义的更清晰,这个是代码能够写长的关键+ """+ context = []+ msg = self._rc.memory.get_by_actions([WriteDesign, WriteTasks, WriteCode])+ for m in msg:+ context.append(m.content)+ context_str = "\n".join(context)+ # 编写code+ code = await WriteCode().run(context=context_str, filename=todo)+ # code review+ if self.use_code_review:+ try:+ rewrite_code = await WriteCodeReview().run(context=context_str, code=code, filename=todo)+ code = rewrite_code+ except Exception as e:+ logger.error("code review failed!", e)+ pass+ file_path = await self.write_file(todo, code)+ msg = Message(content=code, role=self.profile, cause_by=WriteCode)+ self._rc.memory.add(msg)+ instruct_content[todo] = code++ code_msg = (todo, file_path)+ code_msg_all.append(code_msg)++ logger.info(f"Done {self.get_workspace()} generating.")+ msg = Message(+ content=MSG_SEP.join(todo + FILENAME_CODE_SEP + str(file_path) for todo, file_path in code_msg_all),+ instruct_content=instruct_content,+ role=self.profile,+ cause_by=type(self._rc.todo),+ send_to="QaEngineer",++>>>>>>> send18/dev)- return msg+ coding_doc = Document(root_path=str(src_file_repo.root_path), filename=filename, content=context.json())+ return coding_doc++ async def _new_code_actions(self, bug_fix=False):+ # Prepare file repos+ src_file_repo = CONFIG.git_repo.new_file_repository(CONFIG.src_workspace)+ changed_src_files = src_file_repo.all_files if bug_fix else src_file_repo.changed_files+ task_file_repo = CONFIG.git_repo.new_file_repository(TASK_FILE_REPO)+ changed_task_files = task_file_repo.changed_files+ design_file_repo = CONFIG.git_repo.new_file_repository(SYSTEM_DESIGN_FILE_REPO)++ changed_files = Documents()+ # Recode caused by upstream changes.+ for filename in changed_task_files:+ design_doc = await design_file_repo.get(filename)+ task_doc = await task_file_repo.get(filename)+ task_list = self._parse_tasks(task_doc)+ for task_filename in task_list:+ old_code_doc = await src_file_repo.get(task_filename)+ if not old_code_doc:+ old_code_doc = Document(root_path=str(src_file_repo.root_path), filename=task_filename, content="")+ context = CodingContext(+ filename=task_filename, design_doc=design_doc, task_doc=task_doc, code_doc=old_code_doc+ )+ coding_doc = Document(+ root_path=str(src_file_repo.root_path), filename=task_filename, content=context.json()+ )+ if task_filename in changed_files.docs:+ logger.warning(+ f"Log to expose potential conflicts: {coding_doc.json()} & "+ f"{changed_files.docs[task_filename].json()}"+ )+ changed_files.docs[task_filename] = coding_doc+ self.code_todos = [WriteCode(context=i, llm=self._llm) for i in changed_files.docs.values()]+ # Code directly modified by the user.+ dependency = await CONFIG.git_repo.get_dependency()+ for filename in changed_src_files:+ if filename in changed_files.docs:+ continue+ coding_doc = await self._new_coding_doc(+ filename=filename,+ src_file_repo=src_file_repo,+ task_file_repo=task_file_repo,+ design_file_repo=design_file_repo,+ dependency=dependency,+ )+ changed_files.docs[filename] = coding_doc+ self.code_todos.append(WriteCode(context=coding_doc, llm=self._llm))++ if self.code_todos:+ self._rc.todo = self.code_todos[0]++ async def _new_summarize_actions(self):+ src_file_repo = CONFIG.git_repo.new_file_repository(CONFIG.src_workspace)+ src_files = src_file_repo.all_files+ # Generate a SummarizeCode action for each pair of (system_design_doc, task_doc).+ summarizations = defaultdict(list)+ for filename in src_files:+ dependencies = await src_file_repo.get_dependency(filename=filename)+ ctx = CodeSummarizeContext.loads(filenames=dependencies)+ summarizations[ctx].append(filename)+ for ctx, filenames in summarizations.items():+ ctx.codes_filenames = filenames+ self.summarize_todos.append(SummarizeCode(context=ctx, llm=self._llm))+ if self.summarize_todos:+ self._rc.todo = self.summarize_todos[0]- async def _act(self) -> Message:- if self.use_code_review:- return await self._act_sp_precision()- return await self._act_sp()+ @property+ def todo(self) -> str:+ return self._next_tododiff --cc metagpt/roles/qa_engineer.pyindex 15a01b9e9,491f5f997..c8bca8c42--- a/metagpt/roles/qa_engineer.py+++ b/metagpt/roles/qa_engineer.py@@@ -4,30 -4,17 +4,38 @@@@Time : 2023/5/11 14:43@Author : alexanderwu@File : qa_engineer.py+@Modified By: mashenquan, 2023-11-1. In accordance with Chapter 2.2.1 and 2.2.2 of RFC 116, modify the data+ type of the `cause_by` value in the `Message` to a string, and utilize the new message filtering feature.+@Modified By: mashenquan, 2023-11-27.+ 1. Following the think-act principle, solidify the task parameters when creating the+ WriteTest/RunCode/DebugError object, rather than passing them in when calling the run function.+ 2. According to Section 2.2.3.5.7 of RFC 135, change the method of transferring files from using the Message+ to using file references.+@Modified By: mashenquan, 2023-12-5. Enhance the workflow to navigate to WriteCode or QaEngineer based on the results+ of SummarizeCode."""++<<<<<<< HEAD+from metagpt.actions import DebugError, RunCode, WriteCode, WriteCodeReview, WriteTest++# from metagpt.const import WORKSPACE_ROOT+from metagpt.actions.summarize_code import SummarizeCode+from metagpt.config import CONFIG+from metagpt.const import (+ MESSAGE_ROUTE_TO_NONE,+ TEST_CODES_FILE_REPO,+ TEST_OUTPUTS_FILE_REPO,+)++=======+ import os+ from pathlib import Path++ from metagpt.actions import DebugError, RunCode, WriteCode, WriteDesign, WriteTest+ from metagpt.config import CONFIG++>>>>>>> send18/devfrom metagpt.logs import loggerfrom metagpt.roles import Role-from metagpt.schema import Message-from metagpt.utils.common import CodeParser, parse_recipient-from metagpt.utils.special_tokens import FILENAME_CODE_SEP, MSG_SEP+from metagpt.schema import Document, Message, RunCodeContext, TestingContext+from metagpt.utils.common import any_to_str_set, parse_recipientclass QaEngineer(Role):@@@ -47,99 -34,116 +55,125 @@@self.test_round = 0self.test_round_allowed = test_round_allowed++<<<<<<< HEAD++=======+ @classmethod+ def parse_workspace(cls, system_design_msg: Message) -> str:+ if not system_design_msg.instruct_content:+ return system_design_msg.instruct_content.dict().get("Python package name")+ return CodeParser.parse_str(block="Python package name", text=system_design_msg.content)++ def get_workspace(self, return_proj_dir=True) -> Path:+ msg = self._rc.memory.get_by_action(WriteDesign)[-1]+ if not msg:+ return CONFIG.workspace / "src"+ workspace = self.parse_workspace(msg)+ # project directory: workspace/{package_name}, which contains package source code folder, tests folder, resources folder, etc.+ if return_proj_dir:+ return CONFIG.workspace / workspace+ # development codes directory: workspace/{package_name}/{package_name}+ return CONFIG.workspace / workspace / workspace++ def write_file(self, filename: str, code: str):+ workspace = self.get_workspace() / "tests"+ file = workspace / filename+ file.parent.mkdir(parents=True, exist_ok=True)+ file.write_text(code)+++>>>>>>> send18/devasync def _write_test(self, message: Message) -> None:- code_msgs = message.content.split(MSG_SEP)- # result_msg_all = []- for code_msg in code_msgs:+ src_file_repo = CONFIG.git_repo.new_file_repository(CONFIG.src_workspace)+ changed_files = set(src_file_repo.changed_files.keys())+ # Unit tests only.+ if CONFIG.reqa_file and CONFIG.reqa_file not in changed_files:+ changed_files.add(CONFIG.reqa_file)+ tests_file_repo = CONFIG.git_repo.new_file_repository(TEST_CODES_FILE_REPO)+ for filename in changed_files:# write tests- file_name, file_path = code_msg.split(FILENAME_CODE_SEP)- code_to_test = open(file_path, "r").read()- if "test" in file_name:- continue # Engineer might write some test files, skip testing a test file- test_file_name = "test_" + file_name- test_file_path = self.get_workspace() / "tests" / test_file_name- logger.info(f"Writing {test_file_name}..")- test_code = await WriteTest().run(- code_to_test=code_to_test,- test_file_name=test_file_name,- # source_file_name=file_name,- source_file_path=file_path,- workspace=self.get_workspace(),+ if not filename or "test" in filename:+ continue+ code_doc = await src_file_repo.get(filename)+ test_doc = await tests_file_repo.get("test_" + code_doc.filename)+ if not test_doc:+ test_doc = Document(+ root_path=str(tests_file_repo.root_path), filename="test_" + code_doc.filename, content=""+ )+ logger.info(f"Writing {test_doc.filename}..")+ context = TestingContext(filename=test_doc.filename, test_doc=test_doc, code_doc=code_doc)+ context = await WriteTest(context=context, llm=self._llm).run()+ await tests_file_repo.save(+ filename=context.test_doc.filename,+ content=context.test_doc.content,+ dependencies={context.code_doc.root_relative_path},)- self.write_file(test_file_name, test_code)# prepare context for run tests in next round- command = ["python", f"tests/{test_file_name}"]- file_info = {- "file_name": file_name,- "file_path": str(file_path),- "test_file_name": test_file_name,- "test_file_path": str(test_file_path),- "command": command,- }- msg = Message(- content=str(file_info),- role=self.profile,- cause_by=WriteTest,- sent_from=self.profile,- send_to=self.profile,+ run_code_context = RunCodeContext(+ command=["python", context.test_doc.root_relative_path],+ code_filename=context.code_doc.filename,+ test_filename=context.test_doc.filename,+ working_directory=str(CONFIG.git_repo.workdir),+ additional_python_paths=[str(CONFIG.src_workspace)],+ )+ self.publish_message(+ Message(+ content=run_code_context.json(),+ role=self.profile,+ cause_by=WriteTest,+ sent_from=self,+ send_to=self,+ ))- self._publish_message(msg)- logger.info(f"Done {self.get_workspace()}/tests generating.")+ logger.info(f"Done {str(tests_file_repo.workdir)} generating.")async def _run_code(self, msg):- file_info = eval(msg.content)- development_file_path = file_info["file_path"]- test_file_path = file_info["test_file_path"]- if not os.path.exists(development_file_path) or not os.path.exists(test_file_path):+ run_code_context = RunCodeContext.loads(msg.content)+ src_doc = await CONFIG.git_repo.new_file_repository(CONFIG.src_workspace).get(run_code_context.code_filename)+ if not src_doc:return-- development_code = open(development_file_path, "r").read()- test_code = open(test_file_path, "r").read()- proj_dir = self.get_workspace()- development_code_dir = self.get_workspace(return_proj_dir=False)-- result_msg = await RunCode().run(- mode="script",- code=development_code,- code_file_name=file_info["file_name"],- test_code=test_code,- test_file_name=file_info["test_file_name"],- command=file_info["command"],- working_directory=proj_dir, # workspace/package_name, will run tests/test_xxx.py here- additional_python_paths=[development_code_dir], # workspace/package_name/package_name,- # import statement inside package code needs this+ test_doc = await CONFIG.git_repo.new_file_repository(TEST_CODES_FILE_REPO).get(run_code_context.test_filename)+ if not test_doc:+ return+ run_code_context.code = src_doc.content+ run_code_context.test_code = test_doc.content+ result = await RunCode(context=run_code_context, llm=self._llm).run()+ run_code_context.output_filename = run_code_context.test_filename + ".json"+ await CONFIG.git_repo.new_file_repository(TEST_OUTPUTS_FILE_REPO).save(+ filename=run_code_context.output_filename,+ content=result.json(),+ dependencies={src_doc.root_relative_path, test_doc.root_relative_path},+ )+ run_code_context.code = None+ run_code_context.test_code = None+ recipient = parse_recipient(result.summary) # the recipient might be Engineer or myself+ mappings = {"Engineer": "Alex", "QaEngineer": "Edward"}+ self.publish_message(+ Message(+ content=run_code_context.json(),+ role=self.profile,+ cause_by=RunCode,+ sent_from=self,+ send_to=mappings.get(recipient, MESSAGE_ROUTE_TO_NONE),+ ))-- recipient = parse_recipient(result_msg) # the recipient might be Engineer or myself- content = str(file_info) + FILENAME_CODE_SEP + result_msg- msg = Message(content=content, role=self.profile, cause_by=RunCode, sent_from=self.profile, send_to=recipient)- self._publish_message(msg)async def _debug_error(self, msg):- file_info, context = msg.content.split(FILENAME_CODE_SEP)- file_name, code = await DebugError().run(context)- if file_name:- self.write_file(file_name, code)- recipient = msg.sent_from # send back to the one who ran the code for another run, might be one's self- msg = Message(- content=file_info, role=self.profile, cause_by=DebugError, sent_from=self.profile, send_to=recipient+ run_code_context = RunCodeContext.loads(msg.content)+ code = await DebugError(context=run_code_context, llm=self._llm).run()+ await CONFIG.git_repo.new_file_repository(CONFIG.src_workspace).save(+ filename=run_code_context.code_filename, content=code+ )+ run_code_context.output = None+ self.publish_message(+ Message(+ content=run_code_context.json(),+ role=self.profile,+ cause_by=DebugError,+ sent_from=self,+ send_to=self,)- self._publish_message(msg)-- async def _observe(self) -> int:- await super()._observe()- self._rc.news = [- msg for msg in self._rc.news if msg.send_to == self.profile- ] # only relevant msgs count as observed news- return len(self._rc.news)+ )async def _act(self) -> Message:if self.test_round > self.test_round_allowed:diff --cc metagpt/roles/researcher.pyindex 6a76b1a40,cb4d28c33..576e57969--- a/metagpt/roles/researcher.py+++ b/metagpt/roles/researcher.py@@@ -1,9 -1,8 +1,15 @@@#!/usr/bin/env python"""++<<<<<<< HEAD+@Modified By: mashenquan, 2023-11-1. According to Chapter 2.2.1 and 2.2.2 of RFC 116, change the data type of+ the `cause_by` value in the `Message` to a string to support the new message distribution feature.+"""+++=======+ @Modified By: mashenquan, 2023/8/22. A definition has been provided for the return value of _think: returning false indicates that further reasoning cannot continue.++ """++>>>>>>> send18/devimport asyncio@@@ -41,6 -39,17 +47,20 @@@ class Researcher(Role)if language not in ("en-us", "zh-cn"):logger.warning(f"The language `{language}` has not been tested, it may not work.")++<<<<<<< HEAD++=======+ async def _think(self) -> bool:+ if self._rc.todo is None:+ self._set_state(0)+ return True++ if self._rc.state + 1 < len(self._states):+ self._set_state(self._rc.state + 1)+ else:+ self._rc.todo = None+ return False+++>>>>>>> send18/devasync def _act(self) -> Message:logger.info(f"{self._setting}: ready to {self._rc.todo}")todo = self._rc.tododiff --cc metagpt/roles/role.pyindex e34daa307,6d774b0b4..9f2cb7753--- a/metagpt/roles/role.py+++ b/metagpt/roles/role.py@@@ -4,19 -4,8 +4,24 @@@@Time : 2023/5/11 14:42@Author : alexanderwu@File : role.py++<<<<<<< HEAD+@Modified By: mashenquan, 2023-11-1. According to Chapter 2.2.1 and 2.2.2 of RFC 116:+ 1. Merge the `recv` functionality into the `_observe` function. Future message reading operations will be+ consolidated within the `_observe` function.+ 2. Standardize the message filtering for string label matching. Role objects can access the message labels+ they've subscribed to through the `subscribed_tags` property.+ 3. Move the message receive buffer from the global variable `self._rc.env.memory` to the role's private variable+ `self._rc.msg_buffer` for easier message identification and asynchronous appending of messages.+ 4. Standardize the way messages are passed: `publish_message` sends messages out, while `put_message` places+ messages into the Role object's private message receive buffer. There are no other message transmit methods.+ 5. Standardize the parameters for the `run` function: the `test_message` parameter is used for testing purposes+ only. In the normal workflow, you should use `publish_message` or `put_message` to transmit messages.+@Modified By: mashenquan, 2023-11-4. According to the routing feature plan in Chapter 2.2.3.2 of RFC 113, the routing+ functionality is to be consolidated into the `Environment` class.++=======+ @Modified By: mashenquan, 2023-8-7, Support template-style variables, such as '{teaching_language} Teacher'.+ @Modified By: mashenquan, 2023/8/22. A definition has been provided for the return value of _think: returning false indicates that further reasoning cannot continue.++>>>>>>> send18/dev"""from __future__ import annotations@@@ -27,11 -15,11 +32,19 @@@ from pydantic import BaseModel, Fielfrom metagpt.actions import Action, ActionOutputfrom metagpt.config import CONFIG++<<<<<<< HEAD+from metagpt.llm import LLM, HumanProvider+from metagpt.logs import logger+from metagpt.memory import Memory+from metagpt.schema import Message, MessageQueue+from metagpt.utils.common import any_to_name, any_to_str++=======+ from metagpt.const import OPTIONS+ from metagpt.llm import LLMFactory+ from metagpt.logs import logger+ from metagpt.memory import LongTermMemory, Memory+ from metagpt.schema import Message, MessageTag++>>>>>>> send18/devPREFIX_TEMPLATE = """You are a {profile}, named {name}, your goal is {goal}, and the constraint is {constraints}. """@@@ -63,18 -49,8 +76,22 @@@ ROLE_TEMPLATE = """Your response shoul"""+class RoleReactMode(str, Enum):+ REACT = "react"+ BY_ORDER = "by_order"+ PLAN_AND_ACT = "plan_and_act"++ @classmethod+ def values(cls):+ return [item.value for item in cls]++class RoleSetting(BaseModel):++<<<<<<< HEAD+ """Role Settings"""++=======+ """Role properties"""++>>>>>>> send18/devname: strprofile: str@@@ -91,20 -66,15 +108,26 @@@class RoleContext(BaseModel):++<<<<<<< HEAD+ """Role Runtime Context"""++ env: "Environment" = Field(default=None)+ msg_buffer: MessageQueue = Field(default_factory=MessageQueue) # Message Buffer with Asynchronous Updates++=======+ """Runtime role context"""++ env: "Environment" = Field(default=None)++>>>>>>> send18/devmemory: Memory = Field(default_factory=Memory)- long_term_memory: LongTermMemory = Field(default_factory=LongTermMemory)- state: int = Field(default=0)+ # long_term_memory: LongTermMemory = Field(default_factory=LongTermMemory)+ state: int = Field(default=-1) # -1 indicates initial or termination state where todo is Nonetodo: Action = Field(default=None)- watch: set[Type[Action]] = Field(default_factory=set)+ watch: set[str] = Field(default_factory=set)news: list[Type[Message]] = Field(default=[])+ react_mode: RoleReactMode = (+ RoleReactMode.REACT+ ) # see `Role._set_react_mode` for definitions of the following two attributes+ max_react_loop: int = 1class Config:arbitrary_types_allowed = True@@@ -116,22 -86,35 +139,49 @@@@propertydef important_memory(self) -> list[Message]:++<<<<<<< HEAD+ """Get the information corresponding to the watched actions"""++=======+ """Retrieve information corresponding to the attention action."""++>>>>>>> send18/devreturn self.memory.get_by_actions(self.watch)@propertydef history(self) -> list[Message]:return self.memory.get()+ @property+ def prerequisite(self):+ """Retrieve information with `prerequisite` tag"""+ if self.memory and hasattr(self.memory, "get_by_tags"):+ vv = self.memory.get_by_tags([MessageTag.Prerequisite.value])+ return vv[-1:] if len(vv) > 1 else vv+ return []+class Role:++<<<<<<< HEAD+ """Role/Agent"""++ def __init__(self, name="", profile="", goal="", constraints="", desc="", is_human=False):+ self._llm = LLM() if not is_human else HumanProvider()+ self._setting = RoleSetting(+ name=name, profile=profile, goal=goal, constraints=constraints, desc=desc, is_human=is_human+ )++=======+ """Role/Proxy"""++ def __init__(self, name="", profile="", goal="", constraints="", desc="", *args, **kwargs):+ # Replace template-style variables, such as '{teaching_language} Teacher'.+ name = Role.format_value(name)+ profile = Role.format_value(profile)+ goal = Role.format_value(goal)+ constraints = Role.format_value(constraints)+ desc = Role.format_value(desc)++ self._llm = LLMFactory.new_llm()+ self._setting = RoleSetting(name=name, profile=profile, goal=goal, constraints=constraints, desc=desc)++>>>>>>> send18/devself._states = []self._actions = []self._role_id = str(self._setting)@@@ -205,14 -145,11 +255,18 @@@"""Update the current state."""self._rc.state = statelogger.debug(self._actions)- self._rc.todo = self._actions[self._rc.state]+ self._rc.todo = self._actions[self._rc.state] if state >= 0 else Nonedef set_env(self, env: "Environment"):++<<<<<<< HEAD+ """Set the environment in which the role works. The role can talk to the environment and can also receive+ messages by observing."""++=======+ """设置角色工作所处的环境,角色可以向环境说话,也可以通过观察接受环境消息"""++>>>>>>> send18/devself._rc.env = env+ if env:+ env.set_subscription(self, self._subscription)@propertydef profile(self):@@@ -221,77 -158,89 +275,146 @@@@propertydef name(self):++<<<<<<< HEAD+ """Get virtual user name"""+ return self._setting.name++ @property+ def subscription(self) -> Set:+ """The labels for messages to be consumed by the Role object."""+ return self._subscription++=======+ """Return role `name`, read only"""+ return self._setting.name++ @property+ def desc(self):+ """Return role `desc`, read only"""+ return self._setting.desc++ @property+ def goal(self):+ """Return role `goal`, read only"""+ return self._setting.goal++ @property+ def constraints(self):+ """Return role `constraints`, read only"""+ return self._setting.constraints++ @property+ def action_count(self):+ """Return number of action"""+ return len(self._actions)++>>>>>>> send18/devdef _get_prefix(self):- """获取角色前缀"""+ """Get the role prefix"""if self._setting.desc:return self._setting.descreturn PREFIX_TEMPLATE.format(**self._setting.dict())++<<<<<<< HEAD+ async def _think(self) -> None:+ """Think about what to do and decide on the next action"""++=======+ async def _think(self) -> bool:+ """Consider what to do and decide on the next course of action. Return false if nothing can be done."""++>>>>>>> send18/devif len(self._actions) == 1:- # 如果只有一个动作,那就只能做这个+ # If there is only one action, then only this one can be performedself._set_state(0)- return+ return Trueprompt = self._get_prefix()prompt += STATE_TEMPLATE.format(++<<<<<<< HEAD+ history=self._rc.history,+ states="\n".join(self._states),+ n_states=len(self._states) - 1,+ previous_state=self._rc.state,+ )+ # print(prompt)+ next_state = await self._llm.aask(prompt)+ logger.debug(f"{prompt=}")+ if (not next_state.isdigit() and next_state != "-1") or int(next_state) not in range(-1, len(self._states)):+ logger.warning(f"Invalid answer of state, {next_state=}, will be set to -1")+ next_state = -1+ else:+ next_state = int(next_state)+ if next_state == -1:+ logger.info(f"End actions with {next_state=}")+ self._set_state(next_state)++=======+ history=self._rc.history, states="\n".join(self._states), n_states=len(self._states) - 1+ )+ next_state = await self._llm.aask(prompt)+ logger.debug(f"{prompt=}")+ if not next_state.isdigit() or int(next_state) not in range(len(self._states)):+ logger.warning(f"Invalid answer of state, {next_state=}")+ next_state = "0"+ self._set_state(int(next_state))+ return True++>>>>>>> send18/devasync def _act(self) -> Message:- # prompt = self.get_prefix()- # prompt += ROLE_TEMPLATE.format(name=self.profile, state=self.states[self.state], result=response,- # history=self.history)-logger.info(f"{self._setting}: ready to {self._rc.todo}")++<<<<<<< HEAD+ response = await self._rc.todo.run(self._rc.important_memory)++=======+ requirement = self._rc.important_memory or self._rc.prerequisite+ response = await self._rc.todo.run(requirement)+ # logger.info(response)++>>>>>>> send18/devif isinstance(response, ActionOutput):msg = Message(content=response.content,instruct_content=response.instruct_content,role=self.profile,++<<<<<<< HEAD+ cause_by=self._rc.todo,+ sent_from=self,+ )+ elif isinstance(response, Message):+ msg = response++=======+ cause_by=type(self._rc.todo),+ )++>>>>>>> send18/develse:- msg = Message(content=response, role=self.profile, cause_by=type(self._rc.todo))+ msg = Message(content=response, role=self.profile, cause_by=self._rc.todo, sent_from=self)self._rc.memory.add(msg)- # logger.debug(f"{response}")return msg++<<<<<<< HEAD+ async def _observe(self, ignore_memory=False) -> int:+ """Prepare new messages for processing from the message buffer and other sources."""+ # Read unprocessed messages from the msg buffer.+ news = self._rc.msg_buffer.pop_all()+ # Store the read messages in your own memory to prevent duplicate processing.+ old_messages = [] if ignore_memory else self._rc.memory.get()+ self._rc.memory.add_batch(news)+ # Filter out messages of interest.+ self._rc.news = [n for n in news if n.cause_by in self._rc.watch and n not in old_messages]++ # Design Rules:+ # If you need to further categorize Message objects, you can do so using the Message.set_meta function.+ # msg_buffer is a receiving buffer, avoid adding message data and operations to msg_buffer.++=======+ async def _observe(self) -> int:+ """从环境中观察,获得重要信息,并加入记忆"""+ if not self._rc.env:+ return 0+ env_msgs = self._rc.env.memory.get()++ observed = self._rc.env.memory.get_by_actions(self._rc.watch)++ self._rc.news = self._rc.memory.remember(observed) # remember recent exact or similar memories++ for i in env_msgs:+ self.recv(i)+++>>>>>>> send18/devnews_text = [f"{i.role}: {i.content[:20]}..." for i in self._rc.news]if news_text:logger.debug(f"{self._setting} observed: {news_text}")@@@ -375,17 -289,33 +498,43 @@@returnrsp = await self._react()- # 将回复发布到环境,等待下一个订阅者处理- self._publish_message(rsp)++ # Reset the next action to be taken.+ self._rc.todo = None+ # Send the response message to the Environment object to have it relay the message to the subscribers.+ self.publish_message(rsp)return rsp++<<<<<<< HEAD+ @property+ def is_idle(self) -> bool:+ """If true, all actions have been executed."""+ return not self._rc.news and not self._rc.todo and self._rc.msg_buffer.empty()++=======+ @staticmethod+ def format_value(value):+ """Fill parameters inside `value` with `options`."""+ if not isinstance(value, str):+ return value+ if "{" not in value:+ return value++ merged_opts = OPTIONS.get() or {}+ try:+ return value.format(**merged_opts)+ except KeyError as e:+ logger.warning(f"Parameter is missing:{e}")++ for k, v in merged_opts.items():+ value = value.replace("{" + f"{k}" + "}", str(v))+ return value++ def add_action(self, act):+ self._actions.append(act)++ def add_to_do(self, act):+ self._rc.todo = act++>>>>>>> send18/devasync def think(self) -> Action:"""The exported `think` function"""@@@ -398,7 -328,9 +547,16 @@@return ActionOutput(content=msg.content, instruct_content=msg.instruct_content)@property++<<<<<<< HEAD+ def todo(self) -> str:+ if self._actions:+ return any_to_name(self._actions[0])+ return ""++=======+ def todo_description(self):+ if not self._rc or not self._rc.todo:+ return ""+ if self._rc.todo.desc:+ return self._rc.todo.desc+ return f"{type(self._rc.todo).__name__}"++>>>>>>> send18/devdiff --cc metagpt/schema.pyindex 25281e399,9bf85174b..70e84ff15--- a/metagpt/schema.py+++ b/metagpt/schema.py@@@ -14,28 -8,17 +14,26 @@@"""from __future__ import annotations-from dataclasses import dataclass, field-from enum import Enum-from typing import Optional, Set, Type, TypedDict--from pydantic import BaseModel-+import asyncio+import json+import os.path+import uuid+from asyncio import Queue, QueueEmpty, wait_for+from json import JSONDecodeError+from pathlib import Path+from typing import Dict, List, Optional, Set, TypedDict-+from pydantic import BaseModel, Field-+from metagpt.config import CONFIG+from metagpt.const import (+ MESSAGE_ROUTE_CAUSE_BY,+ MESSAGE_ROUTE_FROM,+ MESSAGE_ROUTE_TO,+ MESSAGE_ROUTE_TO_ALL,+ SYSTEM_DESIGN_FILE_REPO,+ TASK_FILE_REPO,+)from metagpt.logs import logger---class MessageTag(Enum):- Prerequisite = "prerequisite"+from metagpt.utils.common import any_to_str, any_to_str_setclass RawMessage(TypedDict):@@@ -188,160 -113,15 +186,161 @@@ class AIMessage(Message)"""def __init__(self, content: str):- super().__init__(content, "assistant")---if __name__ == "__main__":- test_content = "test_message"- msgs = [- UserMessage(test_content),- SystemMessage(test_content),- AIMessage(test_content),- Message(test_content, role="QA"),- ]- logger.info(msgs)+ super().__init__(content=content, role="assistant")+++class MessageQueue:+ """Message queue which supports asynchronous updates."""++ def __init__(self):+ self._queue = Queue()++ def pop(self) -> Message | None:+ """Pop one message from the queue."""+ try:+ item = self._queue.get_nowait()+ if item:+ self._queue.task_done()+ return item+ except QueueEmpty:+ return None++ def pop_all(self) -> List[Message]:+ """Pop all messages from the queue."""+ ret = []+ while True:+ msg = self.pop()+ if not msg:+ break+ ret.append(msg)+ return ret++ def push(self, msg: Message):+ """Push a message into the queue."""+ self._queue.put_nowait(msg)++ def empty(self):+ """Return true if the queue is empty."""+ return self._queue.empty()++ async def dump(self) -> str:+ """Convert the `MessageQueue` object to a json string."""+ if self.empty():+ return "[]"++ lst = []+ try:+ while True:+ item = await wait_for(self._queue.get(), timeout=1.0)+ if item is None:+ break+ lst.append(item.dict(exclude_none=True))+ self._queue.task_done()+ except asyncio.TimeoutError:+ logger.debug("Queue is empty, exiting...")+ return json.dumps(lst)++ @staticmethod+ def load(self, v) -> "MessageQueue":+ """Convert the json string to the `MessageQueue` object."""+ q = MessageQueue()+ try:+ lst = json.loads(v)+ for i in lst:+ msg = Message(**i)+ q.push(msg)+ except JSONDecodeError as e:+ logger.warning(f"JSON load failed: {v}, error:{e}")++ return q+++class CodingContext(BaseModel):+ filename: str+ design_doc: Document+ task_doc: Optional[Document]+ code_doc: Optional[Document]++ @staticmethod+ def loads(val: str) -> CodingContext | None:+ try:+ m = json.loads(val)+ return CodingContext(**m)+ except Exception:+ return None+++class TestingContext(BaseModel):+ filename: str+ code_doc: Document+ test_doc: Optional[Document]++ @staticmethod+ def loads(val: str) -> TestingContext | None:+ try:+ m = json.loads(val)+ return TestingContext(**m)+ except Exception:+ return None+++class RunCodeContext(BaseModel):+ mode: str = "script"+ code: Optional[str]+ code_filename: str = ""+ test_code: Optional[str]+ test_filename: str = ""+ command: List[str] = Field(default_factory=list)+ working_directory: str = ""+ additional_python_paths: List[str] = Field(default_factory=list)+ output_filename: Optional[str]+ output: Optional[str]++ @staticmethod+ def loads(val: str) -> RunCodeContext | None:+ try:+ m = json.loads(val)+ return RunCodeContext(**m)+ except Exception:+ return None+++class RunCodeResult(BaseModel):+ summary: str+ stdout: str+ stderr: str++ @staticmethod+ def loads(val: str) -> RunCodeResult | None:+ try:+ m = json.loads(val)+ return RunCodeResult(**m)+ except Exception:+ return None+++class CodeSummarizeContext(BaseModel):+ design_filename: str = ""+ task_filename: str = ""+ codes_filenames: List[str] = Field(default_factory=list)+ reason: str = ""++ @staticmethod+ def loads(filenames: List) -> CodeSummarizeContext:+ ctx = CodeSummarizeContext()+ for filename in filenames:+ if Path(filename).is_relative_to(SYSTEM_DESIGN_FILE_REPO):+ ctx.design_filename = str(filename)+ continue+ if Path(filename).is_relative_to(TASK_FILE_REPO):+ ctx.task_filename = str(filename)+ continue+ return ctx++ def __hash__(self):+ return hash((self.design_filename, self.task_filename))+++class BugFixContext(BaseModel):+ filename: str = ""++diff --cc metagpt/team.pyindex 152ad24f0,000000000..91587655fmode 100644,000000..100644--- a/metagpt/team.py+++ b/metagpt/team.py@@@ -1,72 -1,0 +1,74 @@@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""+@Time : 2023/5/12 00:30+@Author : alexanderwu+@File : software_company.py+@Modified By: mashenquan, 2023/11/27. Add an archiving operation after completing the project, as specified in+ Section 2.2.3.3 of RFC 135.+"""+from pydantic import BaseModel, Field++from metagpt.actions import UserRequirement+from metagpt.config import CONFIG+from metagpt.const import MESSAGE_ROUTE_TO_ALL+from metagpt.environment import Environment+from metagpt.logs import logger+from metagpt.roles import Role+from metagpt.schema import Message+from metagpt.utils.common import NoMoneyException+++class Team(BaseModel):+ """+ Team: Possesses one or more roles (agents), SOP (Standard Operating Procedures), and a platform for instant messaging,+ dedicated to perform any multi-agent activity, such as collaboratively writing executable code.+ """++ env: Environment = Field(default_factory=Environment)+ investment: float = Field(default=10.0)+ idea: str = Field(default="")++ class Config:+ arbitrary_types_allowed = True++ def hire(self, roles: list[Role]):+ """Hire roles to cooperate"""+ self.env.add_roles(roles)++ def invest(self, investment: float):+ """Invest company. raise NoMoneyException when exceed max_budget."""+ self.investment = investment+ CONFIG.max_budget = investment+ logger.info(f"Investment: ${investment}.")+- def _check_balance(self):- if CONFIG.total_cost > CONFIG.max_budget:- raise NoMoneyException(CONFIG.total_cost, f"Insufficient funds: {CONFIG.max_budget}")++ @staticmethod++ def _check_balance():++ if CONFIG.cost_manager.total_cost > CONFIG.cost_manager.max_budget:++ raise NoMoneyException(CONFIG.cost_manager.total_cost,++ f'Insufficient funds: {CONFIG.cost_manager.max_budget}')++ def run_project(self, idea, send_to: str = ""):+ """Start a project from publishing user requirement."""+ self.idea = idea++ # Human requirement.+ self.env.publish_message(+ Message(role="Human", content=idea, cause_by=UserRequirement, send_to=send_to or MESSAGE_ROUTE_TO_ALL),+ peekable=False,+ )++ def _save(self):+ logger.info(self.json(ensure_ascii=False))++ async def run(self, n_round=3, auto_archive=True):+ """Run company until target round or no money"""+ while n_round > 0:+ # self._save()+ n_round -= 1+ logger.debug(f"{n_round=}")+ self._check_balance()+ await self.env.run()+ if auto_archive and CONFIG.git_repo:+ CONFIG.git_repo.archive()+ return self.env.historydiff --cc metagpt/tools/sd_engine.pyindex a84812f7c,c33f67a51..479f83c63--- a/metagpt/tools/sd_engine.py+++ b/metagpt/tools/sd_engine.py@@@ -13,10 -13,10 +13,15 @@@ from typing import Lisfrom aiohttp import ClientSessionfrom PIL import Image, PngImagePlugin++<<<<<<< HEAD+from metagpt.config import CONFIG++=======+ from metagpt.config import Config+ from metagpt.logs import logger++>>>>>>> send18/dev-config = Config()+# from metagpt.const import WORKSPACE_ROOT+from metagpt.logs import loggerpayload = {"prompt": "",@@@ -79,7 -80,7 +84,11 @@@ class SDEnginereturn self.payloaddef _save(self, imgs, save_name=""):++<<<<<<< HEAD+ save_dir = CONFIG.workspace_path / "resources" / "SD_Output"++=======+ save_dir = CONFIG.get_workspace() / "resources" / "SD_Output"++>>>>>>> send18/devif not os.path.exists(save_dir):os.makedirs(save_dir, exist_ok=True)batch_decode_base64_to_image(imgs, save_dir, save_name=save_name)diff --cc metagpt/utils/common.pyindex 8d4d8eaf9,791bb2767..b627316cd--- a/metagpt/utils/common.py+++ b/metagpt/utils/common.py@@@ -15,11 -10,12 +15,13 @@@ import asimport contextlibimport inspectimport os+import platformimport re+from typing import List, Tuple, Union-+from metagpt.const import MESSAGE_ROUTE_TO_ALL+ from pathlib import Path+ from typing import List, Tuple-+ import yaml-from metagpt.logs import logger@@@ -154,56 -151,9 +156,56 @@@ class OutputParserparsed_data[block] = contentreturn parsed_data+ @classmethod+ def extract_struct(cls, text: str, data_type: Union[type(list), type(dict)]) -> Union[list, dict]:+ """Extracts and parses a specified type of structure (dictionary or list) from the given text.+ The text only contains a list or dictionary, which may have nested structures.++ Args:+ text: The text containing the structure (dictionary or list).+ data_type: The data type to extract, can be "list" or "dict".++ Returns:+ - If extraction and parsing are successful, it returns the corresponding data structure (list or dictionary).+ - If extraction fails or parsing encounters an error, it throw an exception.++ Examples:+ >>> text = 'xxx [1, 2, ["a", "b", [3, 4]], {"x": 5, "y": [6, 7]}] xxx'+ >>> result_list = OutputParser.extract_struct(text, "list")+ >>> print(result_list)+ >>> # Output: [1, 2, ["a", "b", [3, 4]], {"x": 5, "y": [6, 7]}]++ >>> text = 'xxx {"x": 1, "y": {"a": 2, "b": {"c": 3}}} xxx'+ >>> result_dict = OutputParser.extract_struct(text, "dict")+ >>> print(result_dict)+ >>> # Output: {"x": 1, "y": {"a": 2, "b": {"c": 3}}}+ """+ # Find the first "[" or "{" and the last "]" or "}"+ start_index = text.find("[" if data_type is list else "{")+ end_index = text.rfind("]" if data_type is list else "}")++ if start_index != -1 and end_index != -1:+ # Extract the structure part- structure_text = text[start_index : end_index + 1]++ structure_text = text[start_index: end_index + 1]-class CodeParser:+ try:+ # Attempt to convert the text to a Python data type using ast.literal_eval+ result = ast.literal_eval(structure_text)++ # Ensure the result matches the specified data type+ if isinstance(result, list) or isinstance(result, dict):+ return result+ raise ValueError(f"The extracted structure is not a {data_type}.")++ except (ValueError, SyntaxError) as e:+ raise Exception(f"Error while extracting and parsing the {data_type}: {e}")+ else:+ logger.error(f"No {data_type} found in the text.")+ return [] if data_type is list else {}+++class CodeParser:@classmethoddef parse_block(cls, block: str, text: str) -> str:blocks = cls.parse_blocks(text)diff --cc metagpt/utils/cost_manager.pyindex 000000000,21b37d552..f0fea44cemode 000000,100644..100644--- a/metagpt/utils/cost_manager.py+++ b/metagpt/utils/cost_manager.py@@@ -1,0 -1,79 +1,79 @@@+ # -*- coding: utf-8 -*-+ """+ @Time : 2023/8/28+ @Author : mashenquan+ @File : openai.py+ @Desc : mashenquan, 2023/8/28. Separate the `CostManager` class to support user-level cost accounting.+ """++ from pydantic import BaseModel+ from metagpt.logs import logger+ from metagpt.utils.token_counter import TOKEN_COSTS+ from typing import NamedTuple+++ class Costs(NamedTuple):+ total_prompt_tokens: int+ total_completion_tokens: int+ total_cost: float+ total_budget: float+++ class CostManager(BaseModel):+ """Calculate the overhead of using the interface."""++ total_prompt_tokens: int = 0+ total_completion_tokens: int = 0+ total_budget: float = 0+ max_budget: float = 10.0+ total_cost: float = 0++ def update_cost(self, prompt_tokens, completion_tokens, model):+ """+ Update the total cost, prompt tokens, and completion tokens.++ Args:+ prompt_tokens (int): The number of tokens used in the prompt.+ completion_tokens (int): The number of tokens used in the completion.+ model (str): The model used for the API call.+ """+ self.total_prompt_tokens += prompt_tokens+ self.total_completion_tokens += completion_tokens+ cost = (prompt_tokens * TOKEN_COSTS[model]["prompt"] + completion_tokens * TOKEN_COSTS[model][+ "completion"]) / 1000+ self.total_cost += cost+ logger.info(+ f"Total running cost: ${self.total_cost:.3f} | Max budget: ${self.max_budget:.3f} | "+ f"Current cost: ${cost:.3f}, prompt_tokens: {prompt_tokens}, completion_tokens: {completion_tokens}"+ )++ def get_total_prompt_tokens(self):+ """+ Get the total number of prompt tokens.++ Returns:+ int: The total number of prompt tokens.+ """+ return self.total_prompt_tokens++ def get_total_completion_tokens(self):+ """+ Get the total number of completion tokens.++ Returns:+ int: The total number of completion tokens.+ """+ return self.total_completion_tokens++ def get_total_cost(self):+ """+ Get the total cost of API calls.++ Returns:+ float: The total cost of API calls.+ """+ return self.total_cost++ def get_costs(self) -> Costs:- """获得所有开销"""++ """Get all costs"""+ return Costs(self.total_prompt_tokens, self.total_completion_tokens, self.total_cost, self.total_budget)diff --cc metagpt/utils/mermaid.pyindex eb85a3f90,15fd08625..bf7e6c4a7--- a/metagpt/utils/mermaid.py+++ b/metagpt/utils/mermaid.py@@@ -2,17 -2,19 +2,27 @@@# -*- coding: utf-8 -*-"""@Time : 2023/7/4 10:53-@Author : alexanderwu+@Author : alexanderwu alitrack@File : mermaid.py+ @Modified By: mashenquan, 2023/8/20. Remove global configuration `CONFIG`, enable configuration support for business isolation."""import asyncio++<<<<<<< HEAD+import os+from pathlib import Path++from metagpt.config import CONFIG+from metagpt.const import METAGPT_ROOT++=======+ from pathlib import Path++ # from metagpt.utils.common import check_cmd_exists+ import aiofiles++ from metagpt.config import CONFIG, Config+ from metagpt.const import PROJECT_ROOT++>>>>>>> send18/devfrom metagpt.logs import logger- from metagpt.utils.common import check_cmd_existsasync def mermaid_to_file(mermaid_code, output_file_without_suffix, width=2048, height=2048) -> int:@@@ -22,125 -24,91 +32,161 @@@:param output_file_without_suffix: output filename:param width::param height:- :return: 0 if succed, -1 if failed+ :return: 0 if succeed, -1 if failed"""# Write the Mermaid code to a temporary file+ dir_name = os.path.dirname(output_file_without_suffix)+ if dir_name and not os.path.exists(dir_name):+ os.makedirs(dir_name)tmp = Path(f"{output_file_without_suffix}.mmd")- tmp.write_text(mermaid_code, encoding="utf-8")+ async with aiofiles.open(tmp, "w", encoding="utf-8") as f:+ await f.write(mermaid_code)+ # tmp.write_text(mermaid_code, encoding="utf-8")++<<<<<<< HEAD+ engine = CONFIG.mermaid_engine.lower()+ if engine == "nodejs":+ if check_cmd_exists(CONFIG.mmdc) != 0:+ logger.warning(+ "RUN `npm install -g @mermaid-js/mermaid-cli` to install mmdc,"+ "or consider changing MERMAID_ENGINE to `playwright`, `pyppeteer`, or `ink`."+ )+ return -1++ for suffix in ["pdf", "svg", "png"]:+ output_file = f"{output_file_without_suffix}.{suffix}"+ # Call the `mmdc` command to convert the Mermaid code to a PNG+ logger.info(f"Generating {output_file}..")++ if CONFIG.puppeteer_config:+ commands = [+ CONFIG.mmdc,+ "-p",+ CONFIG.puppeteer_config,+ "-i",+ str(tmp),+ "-o",+ output_file,+ "-w",+ str(width),+ "-H",+ str(height),+ ]+ else:+ commands = [CONFIG.mmdc, "-i", str(tmp), "-o", output_file, "-w", str(width), "-H", str(height)]+ process = await asyncio.create_subprocess_shell(+ " ".join(commands), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE+ )++ stdout, stderr = await process.communicate()+ if stdout:+ logger.info(stdout.decode())+ if stderr:+ logger.warning(stderr.decode())+ else:+ if engine == "playwright":+ from metagpt.utils.mmdc_playwright import mermaid_to_file++ return await mermaid_to_file(mermaid_code, output_file_without_suffix, width, height)+ elif engine == "pyppeteer":+ from metagpt.utils.mmdc_pyppeteer import mermaid_to_file++ return await mermaid_to_file(mermaid_code, output_file_without_suffix, width, height)+ elif engine == "ink":+ from metagpt.utils.mmdc_ink import mermaid_to_file++ return await mermaid_to_file(mermaid_code, output_file_without_suffix)+ else:+ logger.warning(f"Unsupported mermaid engine: {engine}")+ return 0+++=======+ # if check_cmd_exists("mmdc") != 0:+ # logger.warning("RUN `npm install -g @mermaid-js/mermaid-cli` to install mmdc")+ # return -1- MMC1 = """classDiagram- class Main {- -SearchEngine search_engine- +main() str- }- class SearchEngine {- -Index index- -Ranking ranking- -Summary summary- +search(query: str) str- }- class Index {- -KnowledgeBase knowledge_base- +create_index(data: dict)- +query_index(query: str) list- }- class Ranking {- +rank_results(results: list) list- }- class Summary {- +summarize_results(results: list) str- }- class KnowledgeBase {- +update(data: dict)- +fetch_data(query: str) dict- }- Main --> SearchEngine- SearchEngine --> Index- SearchEngine --> Ranking- SearchEngine --> Summary- Index --> KnowledgeBase"""-- MMC2 = """sequenceDiagram- participant M as Main- participant SE as SearchEngine- participant I as Index- participant R as Ranking- participant S as Summary- participant KB as KnowledgeBase- M->>SE: search(query)- SE->>I: query_index(query)- I->>KB: fetch_data(query)- KB-->>I: return data- I-->>SE: return results- SE->>R: rank_results(results)- R-->>SE: return ranked_results- SE->>S: summarize_results(ranked_results)- S-->>SE: return summary- SE-->>M: return summary"""+ # for suffix in ["pdf", "svg", "png"]:+ for suffix in ["png"]:+ output_file = f"{output_file_without_suffix}.{suffix}"+ # Call the `mmdc` command to convert the Mermaid code to a PNG+ logger.info(f"Generating {output_file}..")+ cmds = [CONFIG.mmdc, "-i", str(tmp), "-o", output_file, "-w", str(width), "-H", str(height)]+ if CONFIG.puppeteer_config:+ cmds.extend(["-p", CONFIG.puppeteer_config])+ process = await asyncio.create_subprocess_exec(*cmds)+ await process.wait()+ return process.returncode++>>>>>>> send18/dev++ if __name__ == "__main__":+ MMC1 = """classDiagram+ class Main {+ -SearchEngine search_engine+ +main() str+ }+ class SearchEngine {+ -Index index+ -Ranking ranking+ -Summary summary+ +search(query: str) str+ }+ class Index {+ -KnowledgeBase knowledge_base+ +create_index(data: dict)+ +query_index(query: str) list+ }+ class Ranking {+ +rank_results(results: list) list+ }+ class Summary {+ +summarize_results(results: list) str+ }+ class KnowledgeBase {+ +update(data: dict)+ +fetch_data(query: str) dict+ }+ Main --> SearchEngine+ SearchEngine --> Index+ SearchEngine --> Ranking+ SearchEngine --> Summary+ Index --> KnowledgeBase"""++ MMC2 = """sequenceDiagram+ participant M as Main+ participant SE as SearchEngine+ participant I as Index+ participant R as Ranking+ participant S as Summary+ participant KB as KnowledgeBase+ M->>SE: search(query)+ SE->>I: query_index(query)+ I->>KB: fetch_data(query)+ KB-->>I: return data+ I-->>SE: return results+ SE->>R: rank_results(results)+ R-->>SE: return ranked_results+ SE->>S: summarize_results(ranked_results)+ S-->>SE: return summary+ SE-->>M: return summary"""+++<<<<<<< HEAD+if __name__ == "__main__":+ loop = asyncio.new_event_loop()+ result = loop.run_until_complete(mermaid_to_file(MMC1, METAGPT_ROOT / f"{CONFIG.mermaid_engine}/1"))+ result = loop.run_until_complete(mermaid_to_file(MMC2, METAGPT_ROOT / f"{CONFIG.mermaid_engine}/1"))+ loop.close()++=======+ conf = Config()+ asyncio.run(+ mermaid_to_file(+ options=conf.runtime_options, mermaid_code=MMC1, output_file_without_suffix=PROJECT_ROOT / "tmp/1.png"+ )+ )+ asyncio.run(+ mermaid_to_file(+ options=conf.runtime_options, mermaid_code=MMC2, output_file_without_suffix=PROJECT_ROOT / "tmp/2.png"+ )+ )++>>>>>>> send18/devdiff --cc metagpt/utils/redis.pyindex 000000000,48a18e7c9..c344b67acmode 000000,100644..100644--- a/metagpt/utils/redis.py+++ b/metagpt/utils/redis.py@@@ -1,0 -1,222 +1,219 @@@+ # !/usr/bin/python3+ # -*- coding: utf-8 -*-+ # @Author: Hui+ # @Desc: { redis client }+ # @Date: 2022/11/28 10:12+ import json+ import traceback+ from datetime import timedelta+ from enum import Enum+ from typing import Awaitable, Callable, Dict, Optional, Union++ from redis import asyncio as aioredis++ from metagpt.config import CONFIG+ from metagpt.logs import logger+++ class RedisTypeEnum(Enum):+ """Redis 数据类型"""++ String = "String"+ List = "List"+ Hash = "Hash"+ Set = "Set"+ ZSet = "ZSet"+++ def make_url(+ dialect: str,+ *,+ user: Optional[str] = None,+ password: Optional[str] = None,+ host: Optional[str] = None,+ port: Optional[Union[str, int]] = None,+ name: Optional[Union[str, int]] = None,+ ) -> str:+ url_parts = [f"{dialect}://"]+ if user or password:+ if user:+ url_parts.append(user)+ if password:+ url_parts.append(f":{password}")+ url_parts.append("@")++ if not host and not dialect.startswith("sqlite"):+ host = "127.0.0.1"++ if host:+ url_parts.append(f"{host}")+ if port:+ url_parts.append(f":{port}")++ # 比如redis可能传入0+ if name is not None:+ url_parts.append(f"/{name}")+ return "".join(url_parts)+++ class RedisAsyncClient(aioredis.Redis):+ """异步的客户端+ 例子::++ rdb = RedisAsyncClient()+ print(rdb.url)++ Args:+ host: 服务器地址+ port: 服务器端口+ user: 用户名+ db: 数据库+ password: 密码+ decode_responses: 字符串输入被编码成utf8存储在Redis里了,而取出来的时候还是被编码后的bytes,需要显示的decode才能变成字符串+ health_check_interval: 定时检测连接,防止出现ConnectionErrors (104, Connection reset by peer)+ """++ def __init__(+ self,+ host: str = "localhost",+ port: int = 6379,+ db: int = 0,+ password: str = None,+ decode_responses=True,+ health_check_interval=10,+ socket_connect_timeout=5,+ retry_on_timeout=True,+ socket_keepalive=True,+ **kwargs,+ ):+ super().__init__(+ host=host,+ port=port,+ db=db,+ password=password,+ decode_responses=decode_responses,+ health_check_interval=health_check_interval,+ socket_connect_timeout=socket_connect_timeout,+ retry_on_timeout=retry_on_timeout,+ socket_keepalive=socket_keepalive,+ **kwargs,+ )+ self.url = make_url("redis", host=host, port=port, name=db, password=password)+++ class RedisCacheInfo(object):+ """统一缓存信息类"""++ def __init__(self, key, timeout: Union[int, timedelta] = timedelta(seconds=60), data_type=RedisTypeEnum.String):+ """+ 缓存信息类初始化+ Args:+ key: 缓存的key+ timeout: 缓存过期时间, 单位秒+ data_type: 缓存采用的数据结构 (不传并不影响,用于标记业务采用的是什么数据结构)+ """+ self.key = key+ self.timeout = timeout+ self.data_type = data_type++ def __str__(self):+ return f"cache key {self.key} timeout {self.timeout}s"+++ class RedisManager:+ client: RedisAsyncClient = None++ @classmethod+ def init_redis_conn(cls, host, port, password, db):+ """初始化redis 连接"""+ if cls.client is None:+ cls.client = RedisAsyncClient(host=host, port=port, password=password, db=db)++ @classmethod+ async def set_with_cache_info(cls, redis_cache_info: RedisCacheInfo, value):+ """+ 根据 RedisCacheInfo 设置 Redis 缓存+ :param redis_cache_info: RedisCacheInfo缓存信息对象+ :param value: 缓存的值+ :return:+ """+ await cls.client.setex(redis_cache_info.key, redis_cache_info.timeout, value)++ @classmethod+ async def get_with_cache_info(cls, redis_cache_info: RedisCacheInfo):+ """+ 根据 RedisCacheInfo 获取 Redis 缓存+ :param redis_cache_info: RedisCacheInfo 缓存信息对象+ :return:+ """+ cache_info = await cls.client.get(redis_cache_info.key)+ return cache_info++ @classmethod+ async def del_with_cache_info(cls, redis_cache_info: RedisCacheInfo):+ """+ 根据 RedisCacheInfo 删除 Redis 缓存+ :param redis_cache_info: RedisCacheInfo缓存信息对象+ :return:+ """+ await cls.client.delete(redis_cache_info.key)++ @staticmethod+ async def get_or_set_cache(cache_info: RedisCacheInfo, fetch_data_func: Callable[[], Awaitable[dict]]) -> dict:+ """+ 获取缓存数据,如果缓存不存在,则从提供的函数中获取并设置缓存+ 当前版本仅支持 json 形式的 string 格式数据+ """++ serialized_data = await RedisManager.get_with_cache_info(cache_info)++ if serialized_data:+ return json.loads(serialized_data)++ data = await fetch_data_func()+ try:+ serialized_data = json.dumps(data)+ await RedisManager.set_with_cache_info(cache_info, serialized_data)+ except Exception as e:+ logger.warning(f"数据 {data} 通过 json 进行序列化缓存失败:{e}")++ return data++ @classmethod+ def is_valid(cls):+ return cls.client is not None+++ class Redis:+ def __init__(self, conf: Dict = None):- self._config = conf or CONFIG.REDIS- if not self._config:- return+ try:- host = self._config["host"]- port = int(self._config["port"])- pwd = self._config["password"]- db = self._config["db"]++ host = CONFIG.REDIS_HOST++ port = int(CONFIG.REDIS_PORT)++ pwd = CONFIG.REDIS_PASSWORD++ db = CONFIG.REDIS_DB+ RedisManager.init_redis_conn(host=host, port=port, password=pwd, db=db)+ except Exception as e:+ logger.warning(f"Redis initialization has failed:{e}")++ def is_valid(self):+ return RedisManager.is_valid()++ async def get(self, key: str) -> str:+ if not self.is_valid() or not key:+ return None+ try:+ v = await RedisManager.get_with_cache_info(redis_cache_info=RedisCacheInfo(key=key))+ return v+ except Exception as e:+ logger.exception(f"{e}, stack:{traceback.format_exc()}")+ return None++ async def set(self, key: str, data: str, timeout_sec: int):+ if not self.is_valid() or not key:+ return+ try:+ await RedisManager.set_with_cache_info(+ redis_cache_info=RedisCacheInfo(key=key, timeout=timeout_sec), value=data+ )+ except Exception as e:+ logger.exception(f"{e}, stack:{traceback.format_exc()}")diff --cc metagpt/utils/s3.pyindex 000000000,dde68f720..4c3533d5bmode 000000,100644..100644--- a/metagpt/utils/s3.py+++ b/metagpt/utils/s3.py@@@ -1,0 -1,155 +1,154 @@@+ import base64+ import os.path+ import traceback+ import uuid+ from pathlib import Path+ from typing import Optional++ import aioboto3+ import aiofiles++ from metagpt.config import CONFIG+ from metagpt.const import BASE64_FORMAT+ from metagpt.logs import logger+++ class S3:+ """A class for interacting with Amazon S3 storage."""++ def __init__(self):+ self.session = aioboto3.Session()- self.s3_config = CONFIG.S3+ self.auth_config = {+ "service_name": "s3",- "aws_access_key_id": self.s3_config["access_key"],- "aws_secret_access_key": self.s3_config["secret_key"],- "endpoint_url": self.s3_config["endpoint_url"],++ "aws_access_key_id": CONFIG.S3_ACCESS_KEY,++ "aws_secret_access_key": CONFIG.S3_SECRET_KEY,++ "endpoint_url": CONFIG.S3_ENDPOINT_URL,+ }++ async def upload_file(+ self,+ bucket: str,+ local_path: str,+ object_name: str,+ ) -> None:+ """Upload a file from the local path to the specified path of the storage bucket specified in s3.++ Args:+ bucket: The name of the S3 storage bucket.+ local_path: The local file path, including the file name.+ object_name: The complete path of the uploaded file to be stored in S3, including the file name.++ Raises:+ Exception: If an error occurs during the upload process, an exception is raised.+ """+ try:+ async with self.session.client(**self.auth_config) as client:+ async with aiofiles.open(local_path, mode="rb") as reader:+ body = await reader.read()+ await client.put_object(Body=body, Bucket=bucket, Key=object_name)+ logger.info(f"Successfully uploaded the file to path {object_name} in bucket {bucket} of s3.")+ except Exception as e:+ logger.error(f"Failed to upload the file to path {object_name} in bucket {bucket} of s3: {e}")+ raise e++ async def get_object_url(+ self,+ bucket: str,+ object_name: str,+ ) -> str:+ """Get the URL for a downloadable or preview file stored in the specified S3 bucket.++ Args:+ bucket: The name of the S3 storage bucket.+ object_name: The complete path of the file stored in S3, including the file name.++ Returns:+ The URL for the downloadable or preview file.++ Raises:+ Exception: If an error occurs while retrieving the URL, an exception is raised.+ """+ try:+ async with self.session.client(**self.auth_config) as client:+ file = await client.get_object(Bucket=bucket, Key=object_name)+ return str(file["Body"].url)+ except Exception as e:+ logger.error(f"Failed to get the url for a downloadable or preview file: {e}")+ raise e++ async def get_object(+ self,+ bucket: str,+ object_name: str,+ ) -> bytes:+ """Get the binary data of a file stored in the specified S3 bucket.++ Args:+ bucket: The name of the S3 storage bucket.+ object_name: The complete path of the file stored in S3, including the file name.++ Returns:+ The binary data of the requested file.++ Raises:+ Exception: If an error occurs while retrieving the file data, an exception is raised.+ """+ try:+ async with self.session.client(**self.auth_config) as client:+ s3_object = await client.get_object(Bucket=bucket, Key=object_name)+ return await s3_object["Body"].read()+ except Exception as e:+ logger.error(f"Failed to get the binary data of the file: {e}")+ raise e++ async def download_file(+ self, bucket: str, object_name: str, local_path: str, chunk_size: Optional[int] = 128 * 1024+ ) -> None:+ """Download an S3 object to a local file.++ Args:+ bucket: The name of the S3 storage bucket.+ object_name: The complete path of the file stored in S3, including the file name.+ local_path: The local file path where the S3 object will be downloaded.+ chunk_size: The size of data chunks to read and write at a time. Default is 128 KB.++ Raises:+ Exception: If an error occurs during the download process, an exception is raised.+ """+ try:+ async with self.session.client(**self.auth_config) as client:+ s3_object = await client.get_object(Bucket=bucket, Key=object_name)+ stream = s3_object["Body"]+ async with aiofiles.open(local_path, mode="wb") as writer:+ while True:+ file_data = await stream.read(chunk_size)+ if not file_data:+ break+ await writer.write(file_data)+ except Exception as e:+ logger.error(f"Failed to download the file from S3: {e}")+ raise e++ async def cache(self, data: str, file_ext: str, format: str = "") -> str:+ """Save data to remote S3 and return url"""+ object_name = uuid.uuid4().hex + file_ext+ path = Path(__file__).parent+ pathname = path / object_name+ try:+ async with aiofiles.open(str(pathname), mode="wb") as file:+ if format == BASE64_FORMAT:+ data = base64.b64decode(data)+ await file.write(data)+- bucket = CONFIG.S3.get("bucket")- object_pathname = CONFIG.S3.get("path") or "system"++ bucket = CONFIG.S3_BUCKET++ object_pathname = CONFIG.S3_BUCKET or "system"+ object_pathname += f"/{object_name}"+ object_pathname = os.path.normpath(object_pathname)+ await self.upload_file(bucket=bucket, local_path=str(pathname), object_name=object_pathname)+ pathname.unlink(missing_ok=True)++ return await self.get_object_url(bucket=bucket, object_name=object_pathname)+ except Exception as e:+ logger.exception(f"{e}, stack:{traceback.format_exc()}")+ pathname.unlink(missing_ok=True)+ return Nonediff --cc requirements.txtindex c3a8cb44f,3b2dc3106..cf7d8d519--- a/requirements.txt+++ b/requirements.txt@@@ -37,20 -35,12 +37,22 @@@ tqdm==4.64.anthropic==0.3.6typing-inspect==0.8.0typing_extensions==4.5.0+ aiofileslibcst==1.0.1qdrant-client==1.4.0+pytest-mock==3.11.1+open-interpreter==0.1.7; python_version>"3.9"+ta==0.10.2+semantic-kernel==0.4.0.dev0+wrapt==1.15.0+#aiohttp_jinja2+#azure-cognitiveservices-speech~=1.31.0+#aioboto3~=11.3.0+#redis==4.3.5+websocket-client==1.6.2+aiofiles==23.2.1+gitpython==3.1.40+zhipuai==1.0.7+socksio~=1.0.0+gitignore-parser==0.1.9+ connexion[swagger-ui]-aiohttp_jinja2-azure-cognitiveservices-speech==1.31.0-aioboto3~=11.3.0-redis==4.3.5-websocket-client==1.6.2diff --cc tests/conftest.pyindex b22e43e79,98b45de7b..2709b38ae--- a/tests/conftest.py+++ b/tests/conftest.py@@@ -6,18 -6,15 +6,16 @@@@File : conftest.py"""+import asyncio+import logging+import refrom unittest.mock import Mock--import pytest---from metagpt.config import Config+from metagpt.config import CONFIG+from metagpt.const import DEFAULT_WORKSPACE_ROOTfrom metagpt.logs import loggerfrom metagpt.provider.openai_api import OpenAIGPTAPI as GPTAPI-import asyncio-import re+from metagpt.utils.git_repository import GitRepositoryclass Context:@@@ -73,26 -70,7 +71,31 @@@ def proxy()server = asyncio.get_event_loop().run_until_complete(asyncio.start_server(handle_client, "127.0.0.1", 0))return "http://{}:{}".format(*server.sockets[0].getsockname())++# see https://github.com/Delgan/loguru/issues/59#issuecomment-466591978+def loguru_caplog(caplog):+ class PropogateHandler(logging.Handler):+ def emit(self, record):+ logging.getLogger(record.name).handle(record)++ logger.add(PropogateHandler(), format="{message}")+ yield caplog+++# init & dispose git repo[email protected](scope="session", autouse=True)+def setup_and_teardown_git_repo(request):+ CONFIG.git_repo = GitRepository(local_path=DEFAULT_WORKSPACE_ROOT / "unittest")++ # Destroy git repo at the end of the test session.+ def fin():+ CONFIG.git_repo.delete_repository()++ # Register the function for destroying the environment.+ request.addfinalizer(fin)+++ @pytest.fixture(scope="session", autouse=True)+ def init_config():+ Config()+diff --cc tests/metagpt/actions/test_ui_design.pyindex 83590ec7d,dedd0b30e..b9c91d21f--- a/tests/metagpt/actions/test_ui_design.py+++ b/tests/metagpt/actions/test_ui_design.py@@@ -98,9 -98,9 +98,10 @@@ bodyleft: 50%;transform: translate(-50%, -50%);font-size: 3em;- '''+ """++def test_ui_design_parse_css():ui_design_work = UIDesign(name="UI design action")diff --cc tests/metagpt/actions/test_write_code.pyindex 54229089c,d53e37243..0bd6633cd--- a/tests/metagpt/actions/test_write_code.py+++ b/tests/metagpt/actions/test_write_code.py@@@ -4,14 -4,15 +4,13 @@@@Time : 2023/5/11 17:45@Author : alexanderwu@File : test_write_code.py-@Modified By: mashenquan, 2023-8-1, fix-bug: `filename` of `write_code.run()` is missing.-@Modified By: mashenquan, 2023/8/20. Remove global configuration `CONFIG`, enable configuration support for business isolation.+@Modifiled By: mashenquan, 2023-12-6. According to RFC 135"""import pytest---from metagpt.config import Config-from metagpt.provider.openai_api import OpenAIGPTAPI as LLM, CostManager++from metagpt.provider.openai_api import OpenAIGPTAPI as LLMfrom metagpt.actions.write_code import WriteCode- from metagpt.llm import LLMfrom metagpt.logs import logger+from metagpt.schema import CodingContext, Documentfrom tests.metagpt.actions.mock import TASKS_2, WRITE_CODE_PROMPT_SAMPLEdiff --cc tests/metagpt/memory/test_longterm_memory.pyindex b6ae0ac79,b77e9a955..1f07d74e3--- a/tests/metagpt/memory/test_longterm_memory.py+++ b/tests/metagpt/memory/test_longterm_memory.py@@@ -2,11 -2,11 +2,12 @@@# -*- coding: utf-8 -*-"""@Desc : unittest of `metagpt/memory/longterm_memory.py`+ @Modified By: mashenquan, 2023/8/20. Remove global configuration `CONFIG`, enable configuration support for business isolation."""-from metagpt.actions import BossRequirement-from metagpt.config import Config-from metagpt.memory import LongTermMemory++from metagpt.actions import UserRequirement+from metagpt.config import CONFIG- from metagpt.memory import LongTermMemory++from metagpt.memory.longterm_memory import LongTermMemoryfrom metagpt.roles.role import RoleContextfrom metagpt.schema import Message@@@ -28,8 -29,8 +29,9 @@@ def test_ltm_search()ltm.add(message)sim_idea = "Write a game of cli snake"- sim_message = Message(role="BOSS", content=sim_idea, cause_by=BossRequirement)- news = ltm.remember([sim_message])+++ sim_message = Message(role="User", content=sim_idea, cause_by=UserRequirement)+ news = ltm.find_news([sim_message])assert len(news) == 0ltm.add(sim_message)diff --cc tests/metagpt/test_environment.pyindex b27bc3da7,57650d145..29ca38f5a--- a/tests/metagpt/test_environment.py+++ b/tests/metagpt/test_environment.py@@@ -7,11 -9,12 +9,9 @@@"""import pytest---from metagpt.actions import BossRequirement-from metagpt.config import Config+from metagpt.actions import UserRequirementfrom metagpt.environment import Environmentfrom metagpt.logs import logger- from metagpt.manager import Manager-from metagpt.provider.openai_api import CostManagerfrom metagpt.roles import Architect, ProductManager, Rolefrom metagpt.schema import Message@@@ -22,35 -25,47 +22,34 @@@ def env()def test_add_role(env: Environment):- role = ProductManager("Alice", "product manager", "create a new product", "limited resources")- conf = Config()- cost_manager = CostManager(**conf.runtime_options)- role = ProductManager(options=conf.runtime_options,- cost_manager=cost_manager,- name="Alice",++ role = ProductManager(name="Alice",+ profile="product manager",+ goal="create a new product",+ constraints="limited resources")env.add_role(role)assert env.get_role(role.profile) == roledef test_get_roles(env: Environment):- role1 = Role("Alice", "product manager", "create a new product", "limited resources")- role2 = Role("Bob", "engineer", "develop the new product", "short deadline")- conf = Config()- cost_manager = CostManager(**conf.runtime_options)- role1 = Role(options=conf.runtime_options, cost_manager=cost_manager, name="Alice", profile="product manager",++ role1 = Role(name="Alice", profile="product manager",+ goal="create a new product", constraints="limited resources")- role2 = Role(options=conf.runtime_options, cost_manager=cost_manager, name="Bob", profile="engineer",++ role2 = Role(name="Bob", profile="engineer",+ goal="develop the new product", constraints="short deadline")env.add_role(role1)env.add_role(role2)roles = env.get_roles()assert roles == {role1.profile: role1, role2.profile: role2}- def test_set_manager(env: Environment):- manager = Manager()- env.set_manager(manager)- assert env.manager == manager--@pytest.mark.asyncioasync def test_publish_and_process_message(env: Environment):- product_manager = ProductManager("Alice", "Product Manager", "做AI Native产品", "资源有限")- architect = Architect("Bob", "Architect", "设计一个可用、高效、较低成本的系统,包括数据结构与接口", "资源有限,需要节省成本")- conf = Config()- cost_manager = CostManager(**conf.runtime_options)- product_manager = ProductManager(options=conf.runtime_options,- cost_manager=cost_manager,- name="Alice", profile="Product Manager",++ product_manager = ProductManager(name="Alice", profile="Product Manager",+ goal="做AI Native产品", constraints="资源有限")- architect = Architect(options=conf.runtime_options,- cost_manager=cost_manager,- name="Bob", profile="Architect", goal="设计一个可用、高效、较低成本的系统,包括数据结构与接口",++ architect = Architect(name="Bob", profile="Architect", goal="设计一个可用、高效、较低成本的系统,包括数据结构与接口",+ constraints="资源有限,需要节省成本")env.add_roles([product_manager, architect])- env.set_manager(Manager())- env.publish_message(Message(role="BOSS", content="需要一个基于LLM做总结的搜索引擎", cause_by=BossRequirement))-+ env.publish_message(Message(role="User", content="需要一个基于LLM做总结的搜索引擎", cause_by=UserRequirement))-await env.run(k=2)logger.info(f"{env.history=}")assert len(env.history) > 10diff --cc tests/metagpt/tools/test_sd_tool.pyindex e457101a9,89c97f5e8..9003dbe9c--- a/tests/metagpt/tools/test_sd_tool.py+++ b/tests/metagpt/tools/test_sd_tool.py@@@ -22,5 -22,5 +22,6 @@@ def test_sd_engine_generate_prompt()async def test_sd_engine_run_t2i():sd_engine = SDEngine()await sd_engine.run_t2i(prompts=["test"])- img_path = CONFIG.workspace / "resources" / "SD_Output" / "output_0.png"- assert os.path.exists(img_path) == True+ img_path = CONFIG.workspace_path / "resources" / "SD_Output" / "output_0.png"+ assert os.path.exists(img_path)++diff --cc tests/metagpt/utils/test_config.pyindex b68a535f9,510892c2f..f38cddb0d--- a/tests/metagpt/utils/test_config.py+++ b/tests/metagpt/utils/test_config.py@@@ -25,7 -21,17 +21,18 @@@ def test_config_class_get_key_exceptiondef test_config_yaml_file_not_exists():+ config = Config("wtf.yaml")with pytest.raises(Exception) as exc_info:- Config(Path('wtf.yaml'))+ config.get("OPENAI_BASE_URL")- assert str(exc_info.value) == "Key 'OPENAI_BASE_URL' not found in environment variables or in the YAML file"+ assert str(exc_info.value) == "Set OPENAI_API_KEY or Anthropic_API_KEY first"+++ def test_options():+ filename = Path(__file__).resolve().parent.parent.parent.parent / "config/config.yaml"+ config = Config(filename)- opts = config.runtime_options- assert opts++ assert config.options+++ if __name__ == '__main__':+ test_options()++