Skip to content

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

feat: merge geekan:env_refactor

莘权 马be832c9995a6
diff --cc config/config.yaml
index 3aeabf251,8fd208c59..dfcbeab25
--- a/config/config.yaml
+++ b/config/config.yaml
@@@ -95,25 -103,9 +104,30 @@@ LLM_TYPE: OpenA
### browser path for pyppeteer engine, support Chrome, Chromium,MS Edge
#PYPPETEER_EXECUTABLE_PATH: "/usr/bin/google-chrome-stable"
- PROMPT_FORMAT: json #json or markdown
+ ### for repair non-openai LLM's output when parse json-text if PROMPT_FORMAT=json
+ ### due to non-openai LLM's output will not always follow the instruction, so here activate a post-process
+ ### repair operation on the content extracted from LLM's raw output. Warning, it improves the result but not fix all cases.
+ # REPAIR_LLM_OUTPUT: false
+
-# PROMPT_FORMAT: json #json or markdown
++# 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}`.
+
+### Meta Models
+#METAGPT_TEXT_TO_IMAGE_MODEL: MODEL_URL
+
+### S3 config
+#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"
+#REDIS_PORT: "YOUR_REDIS_PORT"
+#REDIS_PASSWORD: "YOUR_REDIS_PASSWORD"
+#REDIS_DB: "YOUR_REDIS_DB_INDEX, str, 0-based"
+
diff --cc metagpt/actions/action.py
index 2b4317736,1534b1f4d..369a33373
--- a/metagpt/actions/action.py
+++ b/metagpt/actions/action.py
@@@ -4,13 -4,8 +4,12 @@@
@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 abc import ABC
from typing import Optional
@@@ -19,9 -14,9 +18,10 @@@ from tenacity import retry, stop_after_
from metagpt.actions.action_output import ActionOutput
from metagpt.llm import LLM
from metagpt.logs import logger
+from metagpt.provider.base_gpt_api import BaseGPTAPI
+ from metagpt.provider.postprecess.llm_output_postprecess import llm_output_postprecess
from metagpt.utils.common import OutputParser
- from metagpt.utils.custom_decoder import CustomDecoder
+ from metagpt.utils.utils import general_after_log
class Action(ABC):
diff --cc metagpt/actions/project_management.py
index 40965ab5c,1f14e7944..780d87a03
--- a/metagpt/actions/project_management.py
+++ b/metagpt/actions/project_management.py
@@@ -24,189 -24,17 +24,13 @@@ from metagpt.const import
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": """
- # 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
- Requirements: Based on the context, fill in the following missing information, note that all sections are returned in Python code triple quote form seperatedly. 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
-
- ## 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.
-
- """,
- "FORMAT_EXAMPLE": '''
- ---
- ## Required Python third-party packages
- ```python
- """
- flask==1.1.2
- bcrypt==3.2.0
- """
- ```
-
- ## Required Other language third-party packages
- ```python
- """
- No third-party ...
- """
- ```
-
- ## Full API spec
- ```python
- """
- openapi: 3.0.0
- ...
- description: A JSON object ...
- """
- ```
-
- ## Logic Analysis
- ```python
- [
- ["index.js", "Contains ..."],
- ["main.py", "Contains ..."],
- ]
- ```
-
- ## Task list
- ```python
- [
- "index.js",
- "main.py",
- ]
- ```
-
- ## Shared Knowledge
- ```python
- """
- 'game.py' contains ...
- """
- ```
-
- ## Anything UNCLEAR
- We need ... how to start.
- ---
- ''',
- },
- }
- OUTPUT_MAPPING = {
- "Required Python third-party packages": (List[str], ...),
- "Required Other language third-party packages": (List[str], ...),
- "Full API spec": (str, ...),
- "Logic Analysis": (List[List[str]], ...),
- "Task list": (List[str], ...),
- "Shared Knowledge": (str, ...),
- "Anything UNCLEAR": (str, ...),
- }
-# from typing import List
--
- MERGE_PROMPT = """
- # Context
- {context}
-# from metagpt.utils.get_template import get_template
--
- ## Old Tasks
+ NEW_REQ_TEMPLATE = """
+ ### Legacy Content
{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
+ ### New Requirements
+ {context}
"""
diff --cc metagpt/config.py
index 92980ec4e,19bd02c87..b31a166b8
--- a/metagpt/config.py
+++ b/metagpt/config.py
@@@ -64,12 -62,13 +67,19 @@@ class Config(metaclass=Singleton)
(not self.openai_api_key or "YOUR_API_KEY" == self.openai_api_key)
and (not self.anthropic_api_key or "YOUR_API_KEY" == self.anthropic_api_key)
and (not self.zhipuai_api_key or "YOUR_API_KEY" == self.zhipuai_api_key)
+ and (not self.open_llm_api_base)
+ and (not self.fireworks_api_key or "YOUR_API_KEY" == self.fireworks_api_key)
):
- raise NotConfiguredException(
++ error_info = (
+ "Set OPENAI_API_KEY or Anthropic_API_KEY or ZHIPUAI_API_KEY first "
+ "or FIREWORKS_API_KEY or OPEN_LLM_API_BASE"
+ )
+ val = self._get("RAISE_NOT_CONFIG_ERROR")
+ if val is None or val.lower() == "true":
- raise NotConfiguredException("Set OPENAI_API_KEY or Anthropic_API_KEY or ZHIPUAI_API_KEY first")
++ raise NotConfiguredException(error_info)
+ else: # for agent
- logger.warning("Set OPENAI_API_KEY or Anthropic_API_KEY or ZHIPUAI_API_KEY first")
++ logger.warning(error_info)
++
self.openai_api_base = self._get("OPENAI_API_BASE")
self.openai_proxy = self._get("OPENAI_PROXY") or self.global_proxy
self.openai_api_type = self._get("OPENAI_API_TYPE")
@@@ -110,16 -113,10 +123,17 @@@
self.mermaid_engine = self._get("MERMAID_ENGINE", "nodejs")
self.pyppeteer_executable_path = self._get("PYPPETEER_EXECUTABLE_PATH", "")
- self.prompt_format = self._get("PROMPT_FORMAT", "markdown")
- self.repair_llm_output = self._get("REPAIR_LLM_OUTPUT", False)
+ self.prompt_format = self._get("PROMPT_FORMAT", "json")
+ workspace_uid = (
+ self._get("WORKSPACE_UID") or f"{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid4().hex[-8:]}"
+ )
++ self.repair_llm_output = self._get("REPAIR_LLM_OUTPUT", False)
self.workspace_path = Path(self._get("WORKSPACE_PATH", DEFAULT_WORKSPACE_ROOT))
+ val = self._get("WORKSPACE_PATH_WITH_UID")
+ if val and val.lower() == "true": # for agent
+ self.workspace_path = self.workspace_path / workspace_uid
self._ensure_workspace_exists()
+ self.max_auto_summarize_code = self.max_auto_summarize_code or self._get("MAX_AUTO_SUMMARIZE_CODE", 1)
def _ensure_workspace_exists(self):
self.workspace_path.mkdir(parents=True, exist_ok=True)
diff --cc metagpt/llm.py
index 7701ebec2,7c0ad7975..e4ae81735
--- a/metagpt/llm.py
+++ b/metagpt/llm.py
@@@ -8,10 -7,10 +8,12 @@@
"""
from metagpt.config import CONFIG
+from metagpt.provider import LLMType
- from metagpt.provider.anthropic_api import Claude2 as Claude
+ from metagpt.provider.base_gpt_api import BaseGPTAPI
+ from metagpt.provider.fireworks_api import FireWorksGPTAPI
from metagpt.provider.human_provider import HumanProvider
+from metagpt.provider.metagpt_llm_api import MetaGPTLLMAPI
+ from metagpt.provider.open_llm_api import OpenLLMGPTAPI
from metagpt.provider.openai_api import OpenAIGPTAPI
from metagpt.provider.spark_api import SparkAPI
from metagpt.provider.zhipuai_api import ZhiPuAIGPTAPI
@@@ -19,31 -18,20 +21,33 @@@
_ = HumanProvider() # Avoid pre-commit error
-def LLM() -> BaseGPTAPI:
+# Used in agents
+class LLMFactory:
+ @staticmethod
+ 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:
++ if CONFIG.spark_api_key:
+ return SparkAPI()
+ elif CONFIG.zhipuai_api_key:
+ return ZhiPuAIGPTAPI()
++ elif CONFIG.open_llm_api_base:
++ return OpenLLMGPTAPI()
++ elif CONFIG.fireworks_api_key:
++ return FireWorksGPTAPI()
+
+ # 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}")
+
+
+# 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.spark_api_key:
- llm = SparkAPI()
- elif CONFIG.zhipuai_api_key:
- llm = ZhiPuAIGPTAPI()
- elif CONFIG.open_llm_api_base:
- llm = OpenLLMGPTAPI()
- elif CONFIG.fireworks_api_key:
- llm = FireWorksGPTAPI()
- else:
- raise RuntimeError("You should config a LLM configuration first")
-
- return llm
+ return LLMFactory.new_llm()
diff --cc metagpt/provider/base_gpt_api.py
index 088df5b19,c38576806..f650305e3
--- a/metagpt/provider/base_gpt_api.py
+++ b/metagpt/provider/base_gpt_api.py
@@@ -10,7 -9,7 +10,6 @@@ import jso
from abc import abstractmethod
from typing import Optional
--from metagpt.logs import logger
from metagpt.provider.base_chatbot import BaseChatbot
@@@ -34,29 -33,24 +33,28 @@@ class BaseGPTAPI(BaseChatbot)
def _default_system_msg(self):
return self._system_msg(self.system_prompt)
- def ask(self, msg: str) -> str:
+ def ask(self, msg: str, timeout=3) -> str:
message = [self._default_system_msg(), self._user_msg(msg)] if self.use_system_prompt else [self._user_msg(msg)]
- rsp = self.completion(message)
+ rsp = self.completion(message, timeout=timeout)
return self.get_choice_text(rsp)
- async def aask(self, msg: str, system_msgs: Optional[list[str]] = None, stream=True) -> str:
+ async def aask(
+ self,
+ msg: str,
+ system_msgs: Optional[list[str]] = None,
+ format_msgs: Optional[list[dict[str, str]]] = None,
+ generator: bool = False,
+ timeout=3,
+ stream=True,
+ ) -> str:
if system_msgs:
- message = (
- self._system_msgs(system_msgs) + [self._user_msg(msg)]
- if self.use_system_prompt
- else [self._user_msg(msg)]
- )
+ message = self._system_msgs(system_msgs)
else:
- message = (
- [self._default_system_msg(), self._user_msg(msg)] if self.use_system_prompt else [self._user_msg(msg)]
- )
- logger.debug(message)
- rsp = await self.acompletion_text(message, stream=stream)
+ message = [self._default_system_msg()]
+ if format_msgs:
+ message.extend(format_msgs)
+ message.append(self._user_msg(msg))
+ rsp = await self.acompletion_text(message, stream=stream, generator=generator, timeout=timeout)
- logger.debug(message)
# logger.debug(rsp)
return rsp
diff --cc metagpt/roles/engineer.py
index 4f7f0b796,f1e65b177..f5286e450
--- a/metagpt/roles/engineer.py
+++ b/metagpt/roles/engineer.py
@@@ -71,8 -71,9 +71,9 @@@ class Engineer(Role)
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",
+ goal: str = "write elegant, readable, extensible, efficient code",
+ constraints: str = "the code should conform to standards like google-style and be modular and maintainable. "
- "Use same language as user requirement",
++ "Use same language as user requirement",
n_borg: int = 1,
use_code_review: bool = False,
) -> None:
diff --cc metagpt/roles/role.py
index 1f28e3c57,b07541b09..06c00a670
--- a/metagpt/roles/role.py
+++ b/metagpt/roles/role.py
@@@ -31,7 -31,8 +32,8 @@@ from metagpt.llm import LLM, HumanProvi
from metagpt.logs import logger
from metagpt.memory import Memory
from metagpt.schema import Message, MessageQueue
-from metagpt.utils.common import any_to_str
+from metagpt.utils.common import any_to_name, any_to_str
+ from metagpt.utils.repair_llm_raw_output import extract_state_value_from_output
PREFIX_TEMPLATE = """You are a {profile}, named {name}, your goal is {goal}, and the constraint is {constraints}. """
diff --cc metagpt/team.py
index 6a3fae0d9,a5c405f80..ed406ee4c
--- a/metagpt/team.py
+++ b/metagpt/team.py
@@@ -67,9 -63,9 +67,9 @@@ class Team(BaseModel)
while n_round > 0:
# self._save()
n_round -= 1
- logger.debug(f"{n_round=}")
+ logger.debug(f"max {n_round=} left.")
self._check_balance()
await self.env.run()
- if CONFIG.git_repo:
+ if auto_archive and CONFIG.git_repo:
CONFIG.git_repo.archive()
return self.env.history