🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming
merge main
geekanb89746b9c761
diff --cc metagpt/actions/project_management.pyindex fb086d5c2,ea5e4016e..7988dd4e8--- a/metagpt/actions/project_management.py+++ b/metagpt/actions/project_management.py@@@ -82,10 -97,12 +82,10 @@@ class WriteTasks(Action)task_doc.content = node.instruct_content.model_dump_json()return task_doc- @staticmethod- async def _update_requirements(doc):+ async def _update_requirements(self, doc):m = json.loads(doc.content)- packages = set(m.get("Required Python third-party packages", set()))+ packages = set(m.get("Required Python packages", set()))- file_repo = CONFIG.git_repo.new_file_repository()- requirement_doc = await file_repo.get(filename=PACKAGE_REQUIREMENTS_FILENAME)+ requirement_doc = await self.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()diff --cc metagpt/actions/write_code_review.pyindex 8b85608ee,3973d089b..ec56afc61--- a/metagpt/actions/write_code_review.py+++ b/metagpt/actions/write_code_review.py@@@ -160,12 -157,14 +160,14 @@@ class WriteCodeReview(Action)cr_prompt = EXAMPLE_AND_INSTRUCTION.format(format_example=format_example,)+ len1 = len(iterative_code) if iterative_code else 0+ len2 = len(self.context.code_doc.content) if self.context.code_doc.content else 0logger.info(- f"Code review and rewrite {self.i_context.code_doc.filename}: {i + 1}/{k} | {len(iterative_code)=}, "- f"{len(self.i_context.code_doc.content)=}"- f"Code review and rewrite {self.context.code_doc.filename}: {i + 1}/{k} | len(iterative_code)={len1}, "- f"len(self.context.code_doc.content)={len2}"++ f"Code review and rewrite {self.i_context.code_doc.filename}: {i + 1}/{k} | len(iterative_code)={len1}, "++ f"len(self.i_context.code_doc.content)={len2}")result, rewrited_code = await self.write_code_review_and_rewrite(- context_prompt, cr_prompt, self.context.code_doc.filename+ context_prompt, cr_prompt, self.i_context.code_doc.filename)if "LBTM" in result:iterative_code = rewrited_codediff --cc metagpt/provider/zhipuai_api.pyindex 67ec6fb8d,a6f77477a..9108a1fba--- a/metagpt/provider/zhipuai_api.py+++ b/metagpt/provider/zhipuai_api.py@@@ -35,27 -34,25 +34,27 @@@ class ZhiPuEvent(Enum)class ZhiPuAILLM(BaseLLM):"""Refs to `https://open.bigmodel.cn/dev/api#chatglm_turbo`- From now, there is only one model named `chatglm_turbo`+ From now, support glm-3-turbo、glm-4, and also system_prompt."""- def __init__(self):- self.__init_zhipuai(CONFIG)- self.llm = ZhiPuModelAPI(api_key=self.api_key)+ def __init__(self, config: LLMConfig):+ self.__init_zhipuai(config)+ self.llm = ZhiPuModelAPI+ self.model = "chatglm_turbo" # so far only one model, just use it+ self.use_system_prompt: bool = False # zhipuai has no system prompt when use api+ self.config = config- def __init_zhipuai(self, config: CONFIG):- assert config.zhipuai_api_key- self.api_key = config.zhipuai_api_key- self.model = config.zhipuai_api_model # so far, it support glm-3-turbo、glm-4+ def __init_zhipuai(self, config: LLMConfig):+ assert config.api_key+ zhipuai.api_key = config.api_key# due to use openai sdk, set the api_key but it will't be used.# openai.api_key = zhipuai.api_key # due to use openai sdk, set the api_key but it will't be used.- if config.openai_proxy:+ if config.proxy:# FIXME: openai v1.x sdk has no proxy support- openai.proxy = config.openai_proxy+ openai.proxy = config.proxy- def _const_kwargs(self, messages: list[dict]) -> dict:- kwargs = {"model": self.model, "prompt": messages, "temperature": 0.3}+ def _const_kwargs(self, messages: list[dict], stream: bool = False) -> dict:+ kwargs = {"model": self.model, "messages": messages, "stream": stream, "temperature": 0.3}return kwargsdef _update_costs(self, usage: dict):@@@ -68,21 -65,15 +67,15 @@@except Exception as e:logger.error(f"zhipuai updats costs failed! exp: {e}")- def get_choice_text(self, resp: dict) -> str:- """get the first text of choice from llm response"""- assist_msg = resp.get("data", {}).get("choices", [{"role": "error"}])[-1]- assert assist_msg["role"] == "assistant"- return assist_msg.get("content")-def completion(self, messages: list[dict], timeout=3) -> dict:- resp = self.llm.invoke(**self._const_kwargs(messages))- usage = resp.get("data").get("usage")- resp: Completion = self.llm.chat.completions.create(**self._const_kwargs(messages))++ resp = self.llm.chat.completions.create(**self._const_kwargs(messages))+ usage = resp.usage.model_dump()self._update_costs(usage)- return resp+ return resp.model_dump()async def _achat_completion(self, messages: list[dict], timeout=3) -> dict:- resp = await self.llm.ainvoke(**self._const_kwargs(messages))- usage = resp.get("data").get("usage")+ resp = await self.llm.acreate(**self._const_kwargs(messages))+ usage = resp.get("usage", {})self._update_costs(usage)return respdiff --cc metagpt/roles/qa_engineer.pyindex 0666a63db,0e323893e..42faa0cd4--- a/metagpt/roles/qa_engineer.py+++ b/metagpt/roles/qa_engineer.py@@@ -54,10 -63,12 +55,12 @@@ class QaEngineer(Role)if not filename or "test" in filename:continuecode_doc = await src_file_repo.get(filename)+ if not code_doc:+ continue- test_doc = await tests_file_repo.get("test_" + code_doc.filename)+ test_doc = await self.project_repo.tests.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=""+ root_path=str(self.project_repo.tests.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)diff --cc metagpt/team.pyindex 96a27d482,aad24efa0..aec72970b--- a/metagpt/team.py+++ b/metagpt/team.py@@@ -79,12 -82,16 +79,12 @@@ class Team(BaseModel)def invest(self, investment: float):"""Invest company. raise NoMoneyException when exceed max_budget."""self.investment = investment- CONFIG.max_budget = investment- CONFIG.cost_manager.max_budget = investment+ self.cost_manager.max_budget = investmentlogger.info(f"Investment: ${investment}.")- @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 _check_balance(self):- if self.cost_manager.total_cost > self.cost_manager.max_budget:++ if self.cost_manager.total_cost >= self.cost_manager.max_budget:+ raise NoMoneyException(self.cost_manager.total_cost, f"Insufficient funds: {self.cost_manager.max_budget}")def run_project(self, idea, send_to: str = ""):"""Run a project from publishing user requirement."""diff --cc tests/metagpt/provider/test_zhipuai_api.pyindex c4a40c23d,8f06fc717..ad2ececa2--- a/tests/metagpt/provider/test_zhipuai_api.py+++ b/tests/metagpt/provider/test_zhipuai_api.py@@@ -3,10 -3,11 +3,9 @@@# @Desc : the unittest of ZhiPuAILLMimport pytest- from zhipuai.utils.sse_client import Event-from metagpt.config import CONFIGfrom metagpt.provider.zhipuai_api import ZhiPuAILLM--CONFIG.zhipuai_api_key = "xxx.xxx"+from tests.metagpt.provider.mock_llm_config import mock_llm_config_zhipuprompt_msg = "who are you"messages = [{"role": "user", "content": prompt_msg}]@@@ -57,16 -39,19 +37,19 @@@ async def mock_zhipuai_acreate_stream(sreturn MockResponse()+ async def mock_zhipuai_acreate(self, **kwargs) -> dict:+ return default_resp++@pytest.mark.asyncioasync def test_zhipuai_acompletion(mocker):- mocker.patch("metagpt.provider.zhipuai.zhipu_model_api.ZhiPuModelAPI.invoke", mock_zhipuai_invoke)- mocker.patch("metagpt.provider.zhipuai.zhipu_model_api.ZhiPuModelAPI.ainvoke", mock_zhipuai_ainvoke)- mocker.patch("metagpt.provider.zhipuai.zhipu_model_api.ZhiPuModelAPI.asse_invoke", mock_zhipuai_asse_invoke)+ mocker.patch("metagpt.provider.zhipuai.zhipu_model_api.ZhiPuModelAPI.acreate", mock_zhipuai_acreate)+ mocker.patch("metagpt.provider.zhipuai.zhipu_model_api.ZhiPuModelAPI.acreate_stream", mock_zhipuai_acreate_stream)- zhipu_gpt = ZhiPuAILLM()+ zhipu_gpt = ZhiPuAILLM(mock_llm_config_zhipu)resp = await zhipu_gpt.acompletion(messages)- assert resp["data"]["choices"][0]["content"] == resp_content+ assert resp["choices"][0]["message"]["content"] == resp_contentresp = await zhipu_gpt.aask(prompt_msg, stream=False)assert resp == resp_contentdiff --cc tests/metagpt/provider/zhipuai/test_zhipu_model_api.pyindex daae65ab7,15673c51c..abaafb402--- a/tests/metagpt/provider/zhipuai/test_zhipu_model_api.py+++ b/tests/metagpt/provider/zhipuai/test_zhipu_model_api.py@@@ -23,20 -21,13 +23,20 @@@ async def mock_requestor_arequest(self@pytest.mark.asyncioasync def test_zhipu_model_api(mocker):- url_prefix, url_suffix = ZhiPuModelAPI(api_key=api_key).split_zhipu_api_url()+ header = ZhiPuModelAPI.get_header()+ zhipuai_default_headers.update({"Authorization": api_key})+ assert header == zhipuai_default_headers++ ZhiPuModelAPI.get_sse_header()+ # assert len(sse_header["Authorization"]) == 191++ url_prefix, url_suffix = ZhiPuModelAPI.split_zhipu_api_url(InvokeType.SYNC, kwargs={"model": "chatglm_turbo"})assert url_prefix == "https://open.bigmodel.cn/api"- assert url_suffix == "/paas/v3/model-api/chatglm_turbo/invoke"+ assert url_suffix == "/paas/v4/chat/completions"mocker.patch("metagpt.provider.general_api_requestor.GeneralAPIRequestor.arequest", mock_requestor_arequest)- result = await ZhiPuModelAPI.arequest(- InvokeType.SYNC, stream=False, method="get", headers={}, kwargs={"model": "chatglm_turbo"}+ result = await ZhiPuModelAPI(api_key=api_key).arequest(+ stream=False, method="get", headers={}, kwargs={"model": "glm-3-turbo"})assert result == default_resp