Skip to content

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

merge main

geekan193fc5535af3
diff --cc .gitignore
index a6f45d894,c10191dcc..4b522674e
--- a/.gitignore
+++ b/.gitignore
@@@ -175,4 -176,4 +176,4 @@@ htmlcov.
*.pkl
*-structure.csv
*-structure.json
- *.dot
-
++*.dot
diff --cc metagpt/actions/write_code.py
index 0c34bd670,7377442b5..2b8f91a1d
--- a/metagpt/actions/write_code.py
+++ b/metagpt/actions/write_code.py
@@@ -132,8 -129,8 +132,8 @@@ class WriteCode(Action)
code = await self.write_code(prompt)
if not coding_context.code_doc:
# avoid root_path pydantic ValidationError if use WriteCode alone
- root_path = CONFIG.src_workspace if CONFIG.src_workspace else ""
+ root_path = self.g_context.src_workspace if self.g_context.src_workspace else ""
- coding_context.code_doc = Document(filename=coding_context.filename, root_path=root_path)
+ coding_context.code_doc = Document(filename=coding_context.filename, root_path=str(root_path))
coding_context.code_doc.content = code
return coding_context
diff --cc metagpt/config.py
index 524c95256,d633c7d28..0c7b54f83
--- a/metagpt/config.py
+++ b/metagpt/config.py
@@@ -93,8 -111,13 +93,13 @@@ class Config(metaclass=Singleton)
if v:
provider = k
break
+ if provider is None:
+ if self.DEFAULT_PROVIDER:
- provider = LLMProviderEnum(self.DEFAULT_PROVIDER)
++ provider = LLMType(self.DEFAULT_PROVIDER)
+ else:
+ raise NotConfiguredException("You should config a LLM configuration first")
- if provider is LLMProviderEnum.GEMINI and not require_python_version(req_version=(3, 10)):
+ if provider is LLMType.GEMINI and not require_python_version(req_version=(3, 10)):
warnings.warn("Use Gemini requires Python >= 3.10")
model_name = self.get_model_name(provider=provider)
if model_name:
diff --cc metagpt/configs/llm_config.py
index c1a8bc4d3,000000000..620827630
mode 100644,000000..100644
--- a/metagpt/configs/llm_config.py
+++ b/metagpt/configs/llm_config.py
@@@ -1,74 -1,0 +1,77 @@@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+@Time : 2024/1/4 16:33
+@Author : alexanderwu
+@File : llm_config.py
+"""
+from enum import Enum
+from typing import Optional
+
+from pydantic import field_validator
+
+from metagpt.utils.yaml_model import YamlModel
+
+
+class LLMType(Enum):
+ OPENAI = "openai"
+ ANTHROPIC = "anthropic"
+ SPARK = "spark"
+ ZHIPUAI = "zhipuai"
+ FIREWORKS = "fireworks"
+ OPEN_LLM = "open_llm"
+ GEMINI = "gemini"
+ METAGPT = "metagpt"
+ AZURE = "azure"
+ OLLAMA = "ollama"
+
++ def __missing__(self, key):
++ return self.OPENAI
++
+
+class LLMConfig(YamlModel):
+ """Config for LLM
+
+ OpenAI: https://github.com/openai/openai-python/blob/main/src/openai/resources/chat/completions.py#L681
+ Optional Fields in pydantic: https://docs.pydantic.dev/latest/migration/#required-optional-and-nullable-fields
+ """
+
+ api_key: str
+ api_type: LLMType = LLMType.OPENAI
+ base_url: str = "https://api.openai.com/v1"
+ api_version: Optional[str] = None
+ model: Optional[str] = None # also stands for DEPLOYMENT_NAME
+
+ # For Spark(Xunfei), maybe remove later
+ app_id: Optional[str] = None
+ api_secret: Optional[str] = None
+ domain: Optional[str] = None
+
+ # For Chat Completion
+ max_token: int = 4096
+ temperature: float = 0.0
+ top_p: float = 1.0
+ top_k: int = 0
+ repetition_penalty: float = 1.0
+ stop: Optional[str] = None
+ presence_penalty: float = 0.0
+ frequency_penalty: float = 0.0
+ best_of: Optional[int] = None
+ n: Optional[int] = None
+ stream: bool = False
+ logprobs: Optional[bool] = None # https://cookbook.openai.com/examples/using_logprobs
+ top_logprobs: Optional[int] = None
+ timeout: int = 60
+
+ # For Network
+ proxy: Optional[str] = None
+
+ # Cost Control
+ calc_usage: bool = True
+
+ @field_validator("api_key")
+ @classmethod
+ def check_llm_key(cls, v):
+ if v in ["", None, "YOUR_API_KEY"]:
+ raise ValueError("Please set your API key in config.yaml")
+ return v
diff --cc tests/conftest.py
index 71afdff9f,6f5c04f06..fab1fa198
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@@ -15,55 -15,17 +15,17 @@@ import uui
import pytest
- from metagpt.config2 import config
-from metagpt.config import CONFIG, Config
from metagpt.const import DEFAULT_WORKSPACE_ROOT, TEST_DATA_PATH
+from metagpt.context import context
from metagpt.llm import LLM
from metagpt.logs import logger
- from metagpt.provider.openai_api import OpenAILLM
from metagpt.utils.git_repository import GitRepository
+ from tests.mock.mock_llm import MockLLM
-
- class MockLLM(OpenAILLM):
- rsp_cache: dict = {}
-
- async def original_aask(
- self,
- msg: str,
- system_msgs: Optional[list[str]] = None,
- format_msgs: Optional[list[dict[str, str]]] = None,
- timeout=3,
- stream=True,
- ):
- """A copy of metagpt.provider.base_llm.BaseLLM.aask, we can't use super().aask because it will be mocked"""
- if system_msgs:
- message = self._system_msgs(system_msgs)
- else:
- message = [self._default_system_msg()] if self.use_system_prompt else []
- if format_msgs:
- message.extend(format_msgs)
- message.append(self._user_msg(msg))
- rsp = await self.acompletion_text(message, stream=stream, timeout=timeout)
- return rsp
-
- async def aask(
- self,
- msg: str,
- system_msgs: Optional[list[str]] = None,
- format_msgs: Optional[list[dict[str, str]]] = None,
- timeout=3,
- stream=True,
- ) -> str:
- logger.debug(f"MockLLM.aask: {msg}")
- if msg not in self.rsp_cache:
- # Call the original unmocked method
- rsp = await self.original_aask(msg, system_msgs, format_msgs, timeout, stream)
- logger.info(f"Added '{rsp[:20]}' ... to response cache")
- self.rsp_cache[msg] = rsp
- return rsp
- else:
- logger.info("Use response cache")
- return self.rsp_cache[msg]
+ RSP_CACHE_NEW = {} # used globally for producing new and useful only response cache
+ ALLOW_OPENAI_API_CALL = int(
+ os.environ.get("ALLOW_OPENAI_API_CALL", 1)
+ ) # NOTE: should change to default 0 (False) once mock is complete
@pytest.fixture(scope="session")
@@@ -154,10 -139,10 +139,10 @@@ def loguru_caplog(caplog)
# init & dispose git repo
- @pytest.fixture(scope="session", autouse=True)
+ @pytest.fixture(scope="function", autouse=True)
def setup_and_teardown_git_repo(request):
- context.git_repo = GitRepository(local_path=DEFAULT_WORKSPACE_ROOT / "unittest")
- CONFIG.git_repo = GitRepository(local_path=DEFAULT_WORKSPACE_ROOT / f"unittest/{uuid.uuid4().hex}")
- CONFIG.git_reinit = True
++ context.git_repo = GitRepository(local_path=DEFAULT_WORKSPACE_ROOT / f"unittest/{uuid.uuid4().hex}")
+ context.config.git_reinit = True
# Destroy git repo at the end of the test session.
def fin():
@@@ -169,4 -154,49 +154,49 @@@
@pytest.fixture(scope="session", autouse=True)
def init_config():
- Config()
+ pass
+
+
+ @pytest.fixture(scope="function")
+ def new_filename(mocker):
+ # NOTE: Mock new filename to make reproducible llm aask, should consider changing after implementing requirement segmentation
+ mocker.patch("metagpt.utils.file_repository.FileRepository.new_filename", lambda: "20240101")
+ yield mocker
+
+
+ @pytest.fixture
+ def aiohttp_mocker(mocker):
+ class MockAioResponse:
+ async def json(self, *args, **kwargs):
+ return self._json
+
+ def set_json(self, json):
+ self._json = json
+
+ response = MockAioResponse()
+
+ class MockCTXMng:
+ async def __aenter__(self):
+ return response
+
+ async def __aexit__(self, *args, **kwargs):
+ pass
+
+ def __await__(self):
+ yield
+ return response
+
+ def mock_request(self, method, url, **kwargs):
+ return MockCTXMng()
+
+ def wrap(method):
+ def run(self, url, **kwargs):
+ return mock_request(self, method, url, **kwargs)
+
+ return run
+
+ mocker.patch("aiohttp.ClientSession.request", mock_request)
+ for i in ["get", "post", "delete", "patch"]:
+ mocker.patch(f"aiohttp.ClientSession.{i}", wrap(i))
+
+ yield response
diff --cc tests/metagpt/actions/test_debug_error.py
index e6dc0f3b6,6258aa6d4..ff9e9cd81
--- a/tests/metagpt/actions/test_debug_error.py
+++ b/tests/metagpt/actions/test_debug_error.py
@@@ -116,9 -117,8 +116,8 @@@ if __name__ == '__main__'
@pytest.mark.asyncio
- @pytest.mark.usefixtures("llm_mock")
async def test_debug_error():
- CONFIG.src_workspace = CONFIG.git_repo.workdir / uuid.uuid4().hex
+ context.src_workspace = context.git_repo.workdir / uuid.uuid4().hex
ctx = RunCodeContext(
code_filename="player.py",
test_filename="test_player.py",
diff --cc tests/metagpt/actions/test_design_api.py
index ca9dabc76,8d4720570..88cb612fc
--- a/tests/metagpt/actions/test_design_api.py
+++ b/tests/metagpt/actions/test_design_api.py
@@@ -16,12 -15,12 +16,11 @@@ from metagpt.schema import Messag
@pytest.mark.asyncio
- @pytest.mark.usefixtures("llm_mock")
async def test_design_api():
- inputs = ["我们需要一个音乐播放器,它应该有播放、暂停、上一曲、下一曲等功能。", PRD_SAMPLE]
+ inputs = ["我们需要一个音乐播放器,它应该有播放、暂停、上一曲、下一曲等功能。"] # PRD_SAMPLE
+ repo = context.file_repo
for prd in inputs:
- await FileRepository.save_file("new_prd.txt", content=prd, relative_path=PRDS_FILE_REPO)
+ await repo.save_file("new_prd.txt", content=prd, relative_path=PRDS_FILE_REPO)
design_api = WriteDesign()
diff --cc tests/metagpt/actions/test_project_management.py
index 8f91f78ee,88263ff29..a462319b8
--- a/tests/metagpt/actions/test_project_management.py
+++ b/tests/metagpt/actions/test_project_management.py
@@@ -17,11 -18,10 +17,10 @@@ from tests.metagpt.actions.mock_json im
@pytest.mark.asyncio
- @pytest.mark.usefixtures("llm_mock")
async def test_design_api():
- await FileRepository.save_file("1.txt", content=str(PRD), relative_path=PRDS_FILE_REPO)
- await FileRepository.save_file("1.txt", content=str(DESIGN), relative_path=SYSTEM_DESIGN_FILE_REPO)
- logger.info(CONFIG.git_repo)
+ await context.file_repo.save_file("1.txt", content=str(PRD), relative_path=PRDS_FILE_REPO)
+ await context.file_repo.save_file("1.txt", content=str(DESIGN), relative_path=SYSTEM_DESIGN_FILE_REPO)
+ logger.info(context.git_repo)
action = WriteTasks()
diff --cc tests/metagpt/actions/test_summarize_code.py
index 68320c4c7,7ecb67afd..1c14d256d
--- a/tests/metagpt/actions/test_summarize_code.py
+++ b/tests/metagpt/actions/test_summarize_code.py
@@@ -177,17 -177,16 +177,16 @@@ class Snake
@pytest.mark.asyncio
- @pytest.mark.usefixtures("llm_mock")
async def test_summarize_code():
- CONFIG.src_workspace = CONFIG.git_repo.workdir / "src"
- await FileRepository.save_file(filename="1.json", relative_path=SYSTEM_DESIGN_FILE_REPO, content=DESIGN_CONTENT)
- await FileRepository.save_file(filename="1.json", relative_path=TASK_FILE_REPO, content=TASK_CONTENT)
- await FileRepository.save_file(filename="food.py", relative_path=CONFIG.src_workspace, content=FOOD_PY)
- await FileRepository.save_file(filename="game.py", relative_path=CONFIG.src_workspace, content=GAME_PY)
- await FileRepository.save_file(filename="main.py", relative_path=CONFIG.src_workspace, content=MAIN_PY)
- await FileRepository.save_file(filename="snake.py", relative_path=CONFIG.src_workspace, content=SNAKE_PY)
-
- src_file_repo = CONFIG.git_repo.new_file_repository(relative_path=CONFIG.src_workspace)
+ context.src_workspace = context.git_repo.workdir / "src"
+ await context.file_repo.save_file(filename="1.json", relative_path=SYSTEM_DESIGN_FILE_REPO, content=DESIGN_CONTENT)
+ await context.file_repo.save_file(filename="1.json", relative_path=TASK_FILE_REPO, content=TASK_CONTENT)
+ await context.file_repo.save_file(filename="food.py", relative_path=CONFIG.src_workspace, content=FOOD_PY)
+ await context.file_repo.save_file(filename="game.py", relative_path=CONFIG.src_workspace, content=GAME_PY)
+ await context.file_repo.save_file(filename="main.py", relative_path=CONFIG.src_workspace, content=MAIN_PY)
+ await context.file_repo.save_file(filename="snake.py", relative_path=CONFIG.src_workspace, content=SNAKE_PY)
+
+ src_file_repo = context.git_repo.new_file_repository(relative_path=CONFIG.src_workspace)
all_files = src_file_repo.all_files
ctx = CodeSummarizeContext(design_filename="1.json", task_filename="1.json", codes_filenames=all_files)
action = SummarizeCode(context=ctx)
diff --cc tests/metagpt/actions/test_talk_action.py
index c46814a9b,953fdf44a..6d01dcc3f
--- a/tests/metagpt/actions/test_talk_action.py
+++ b/tests/metagpt/actions/test_talk_action.py
@@@ -33,12 -33,10 +33,11 @@@ from metagpt.schema import Messag
),
],
)
- @pytest.mark.usefixtures("llm_mock")
async def test_prompt(agent_description, language, context, knowledge, history_summary):
# Prerequisites
- CONFIG.agent_description = agent_description
- CONFIG.language = language
+ g_context = Context()
+ g_context.kwargs["agent_description"] = agent_description
+ g_context.kwargs["language"] = language
action = TalkAction(context=context, knowledge=knowledge, history_summary=history_summary)
assert "{" not in action.prompt
diff --cc tests/metagpt/actions/test_write_code.py
index 5f9bcd9d9,249145c92..2a7b8e696
--- a/tests/metagpt/actions/test_write_code.py
+++ b/tests/metagpt/actions/test_write_code.py
@@@ -27,12 -28,11 +27,11 @@@ from tests.metagpt.actions.mock_markdow
@pytest.mark.asyncio
- @pytest.mark.usefixtures("llm_mock")
async def test_write_code():
- context = CodingContext(
+ ccontext = CodingContext(
filename="task_filename.py", design_doc=Document(content="设计一个名为'add'的函数,该函数接受两个整数作为输入,并返回它们的和。")
)
- doc = Document(content=context.model_dump_json())
+ doc = Document(content=ccontext.model_dump_json())
write_code = WriteCode(context=doc)
code = await write_code.run()
@@@ -53,12 -52,11 +51,11 @@@ async def test_write_code_directly()
@pytest.mark.asyncio
- @pytest.mark.usefixtures("llm_mock")
async def test_write_code_deps():
# Prerequisites
- CONFIG.src_workspace = CONFIG.git_repo.workdir / "snake1/snake1"
+ context.src_workspace = context.git_repo.workdir / "snake1/snake1"
demo_path = Path(__file__).parent / "../../data/demo_project"
- await FileRepository.save_file(
+ await context.file_repo.save_file(
filename="test_game.py.json",
content=await aread(str(demo_path / "test_game.py.json")),
relative_path=TEST_OUTPUTS_FILE_REPO,
diff --cc tests/metagpt/actions/test_write_prd.py
index cb8b286cb,7317bba76..1f92c079b
--- a/tests/metagpt/actions/test_write_prd.py
+++ b/tests/metagpt/actions/test_write_prd.py
@@@ -8,12 -8,15 +8,15 @@@
"""
import pytest
- from metagpt.actions import UserRequirement
+ from metagpt.actions import UserRequirement, WritePRD
-from metagpt.config import CONFIG
from metagpt.const import DOCS_FILE_REPO, PRDS_FILE_REPO, REQUIREMENT_FILENAME
+from metagpt.context import context
from metagpt.logs import logger
from metagpt.roles.product_manager import ProductManager
+ from metagpt.roles.role import RoleReactMode
from metagpt.schema import Message
+ from metagpt.utils.common import any_to_str
+ from metagpt.utils.file_repository import FileRepository
@pytest.mark.asyncio
@@@ -29,4 -33,8 +33,8 @@@ async def test_write_prd(new_filename)
# Assert the prd is not None or empty
assert prd is not None
assert prd.content != ""
- assert CONFIG.git_repo.new_file_repository(relative_path=PRDS_FILE_REPO).changed_files
+ assert context.git_repo.new_file_repository(relative_path=PRDS_FILE_REPO).changed_files
+
+
+ if __name__ == "__main__":
+ pytest.main([__file__, "-s"])
diff --cc tests/metagpt/utils/test_redis.py
index e6e2c2ce2,d499418ac..95eff4f61
--- a/tests/metagpt/utils/test_redis.py
+++ b/tests/metagpt/utils/test_redis.py
@@@ -6,17 -6,37 +6,26 @@@
@File : test_redis.py
"""
+ import mock
import pytest
-from metagpt.config import CONFIG
+from metagpt.config2 import Config
from metagpt.utils.redis import Redis
+ async def async_mock_from_url(*args, **kwargs):
+ mock_client = mock.AsyncMock()
+ mock_client.set.return_value = None
+ mock_client.get.side_effect = [b"test", b""]
+ return mock_client
+
+
@pytest.mark.asyncio
+ @mock.patch("aioredis.from_url", return_value=async_mock_from_url())
-async def test_redis(mock_from_url):
- # Mock
- # mock_client = mock.AsyncMock()
- # mock_client.set.return_value=None
- # mock_client.get.side_effect = [b'test', b'']
- # mock_from_url.return_value = mock_client
-
- # Prerequisites
- CONFIG.REDIS_HOST = "MOCK_REDIS_HOST"
- CONFIG.REDIS_PORT = "MOCK_REDIS_PORT"
- CONFIG.REDIS_PASSWORD = "MOCK_REDIS_PASSWORD"
- CONFIG.REDIS_DB = 0
-
- conn = Redis()
- assert not conn.is_valid
+async def test_redis():
+ redis = Config.default().redis
+
+ conn = Redis(redis)
await conn.set("test", "test", timeout_sec=0)
assert await conn.get("test") == b"test"
await conn.close()
diff --cc tests/metagpt/utils/test_s3.py
index 708f4b9c3,132aa0635..4dc3b1e42
--- a/tests/metagpt/utils/test_s3.py
+++ b/tests/metagpt/utils/test_s3.py
@@@ -9,27 -9,48 +9,44 @@@ import uui
from pathlib import Path
import aiofiles
+ import mock
import pytest
-from metagpt.config import CONFIG
+from metagpt.config2 import Config
+ from metagpt.utils.common import aread
from metagpt.utils.s3 import S3
@pytest.mark.asyncio
- async def test_s3():
+ @mock.patch("aioboto3.Session")
+ async def test_s3(mock_session_class):
+ # Set up the mock response
+ data = await aread(__file__, "utf-8")
+ mock_session_object = mock.Mock()
+ reader_mock = mock.AsyncMock()
+ reader_mock.read.side_effect = [data.encode("utf-8"), b"", data.encode("utf-8")]
+ type(reader_mock).url = mock.PropertyMock(return_value="https://mock")
+ mock_client = mock.AsyncMock()
+ mock_client.put_object.return_value = None
+ mock_client.get_object.return_value = {"Body": reader_mock}
+ mock_client.__aenter__.return_value = mock_client
+ mock_client.__aexit__.return_value = None
+ mock_session_object.client.return_value = mock_client
+ mock_session_class.return_value = mock_session_object
+
# Prerequisites
- # assert CONFIG.S3_ACCESS_KEY and CONFIG.S3_ACCESS_KEY != "YOUR_S3_ACCESS_KEY"
- # assert CONFIG.S3_SECRET_KEY and CONFIG.S3_SECRET_KEY != "YOUR_S3_SECRET_KEY"
- # assert CONFIG.S3_ENDPOINT_URL and CONFIG.S3_ENDPOINT_URL != "YOUR_S3_ENDPOINT_URL"
- # assert CONFIG.S3_BUCKET and CONFIG.S3_BUCKET != "YOUR_S3_BUCKET"
-
- conn = S3()
- assert conn.is_valid
+ s3 = Config.default().s3
+ assert s3
+ conn = S3(s3)
object_name = "unittest.bak"
- await conn.upload_file(bucket=CONFIG.S3_BUCKET, local_path=__file__, object_name=object_name)
+ await conn.upload_file(bucket=s3.bucket, local_path=__file__, object_name=object_name)
pathname = (Path(__file__).parent / uuid.uuid4().hex).with_suffix(".bak")
pathname.unlink(missing_ok=True)
- await conn.download_file(bucket=CONFIG.S3_BUCKET, object_name=object_name, local_path=str(pathname))
+ await conn.download_file(bucket=s3.bucket, object_name=object_name, local_path=str(pathname))
assert pathname.exists()
- url = await conn.get_object_url(bucket=CONFIG.S3_BUCKET, object_name=object_name)
+ url = await conn.get_object_url(bucket=s3.bucket, object_name=object_name)
assert url
- bin_data = await conn.get_object(bucket=CONFIG.S3_BUCKET, object_name=object_name)
+ bin_data = await conn.get_object(bucket=s3.bucket, object_name=object_name)
assert bin_data
async with aiofiles.open(__file__, mode="r", encoding="utf-8") as reader:
data = await reader.read()
@@@ -37,14 -58,21 +54,17 @@@
assert "http" in res
# Mock session env
+ s3.access_key = "ABC"
+ type(reader_mock).url = mock.PropertyMock(return_value="")
- old_options = CONFIG.options.copy()
- new_options = old_options.copy()
- new_options["S3_ACCESS_KEY"] = "YOUR_S3_ACCESS_KEY"
- CONFIG.set_context(new_options)
try:
- conn = S3()
- assert not conn.is_valid
+ conn = S3(s3)
res = await conn.cache("ABC", ".bak", "script")
assert not res
- finally:
- CONFIG.set_context(old_options)
+ except Exception:
+ pass
+ await reader.close()
+
if __name__ == "__main__":
pytest.main([__file__, "-s"])