🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming
feat: merge role_option
莘权 马ec20629561af
diff --cc metagpt/actions/design_api.pyindex cf23e6ad1,eb08cb9f0..a01e1c753--- a/metagpt/actions/design_api.py+++ b/metagpt/actions/design_api.py@@@ -4,7 -4,7 +4,8 @@@@Time : 2023/5/11 19:26@Author : alexanderwu@File : design_api.py+@Modified By: mashenquan, 2023-8-9, align `run` parameters with the parent :class:`Action` class.+ @Modified By: mashenquan, 2023/8/20. Remove global configuration `CONFIG`, enable configuration support for business isolation."""import shutilfrom pathlib import Pathdiff --cc metagpt/actions/project_management.pyindex 16473ff01,3d8aa9322..d17bf6b03--- a/metagpt/actions/project_management.py+++ b/metagpt/actions/project_management.py@@@ -4,7 -4,7 +4,8 @@@@Time : 2023/5/11 19:12@Author : alexanderwu@File : project_management.py+@Modified By: mashenquan, 2023-8-9, align `run` parameters with the parent :class:`Action` class.+ @Modified By: mashenquan, 2023/8/20. Remove global configuration `CONFIG`, enable configuration support for business isolation."""from typing import List, Tuplediff --cc metagpt/provider/openai_api.pyindex 88343373f,2e951b36f..40aa3848e--- a/metagpt/provider/openai_api.py+++ b/metagpt/provider/openai_api.py@@@ -131,33 -141,26 +141,34 @@@ class OpenAIGPTAPI(BaseGPTAPI, RateLimiCheck https://platform.openai.com/examples for examples"""- def __init__(self):- self.__init_openai(CONFIG)+ def __init__(self, options, cost_manager):+ self._options = options+ self.__init_openai()self.llm = openai- self.model = CONFIG.openai_api_model+ self.model = self.openai_api_modelself.auto_max_tokens = False- self._cost_manager = CostManager()+ self._cost_manager = cost_managerRateLimiter.__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))+ def __init_openai(self):+ openai.api_key = self.openai_api_key+ if self.openai_api_base:+ openai.api_base = self.openai_api_base+ if self.openai_api_type:+ openai.api_type = self.openai_api_type+ openai.api_version = self.openai_api_version+ self.rpm = int(self._options.get("RPM", 10))async def _achat_completion_stream(self, messages: list[dict]) -> str:- response = await openai.ChatCompletion.acreate(**self._cons_kwargs(messages), stream=True)+ try:+ response = await openai.ChatCompletion.acreate(+ **self._cons_kwargs(messages),+ stream=True+ )+ except Exception as e:+ error_str = traceback.format_exc()+ logger.error(f"Exception:{e}, stack:{error_str}")+ raise e# create variables to collect the stream of chunkscollected_chunks = []diff --cc metagpt/roles/role.pyindex 68baeccf5,3c72876a5..5397893eb--- a/metagpt/roles/role.py+++ b/metagpt/roles/role.py@@@ -4,7 -4,8 +4,9 @@@@Time : 2023/5/11 14:42@Author : alexanderwu@File : role.py+@Modified By: mashenquan, 2023-8-7, :class:`Role` + properties.+ @Modified By: mashenquan, 2023/8/20. Remove global configuration `CONFIG`, enable configuration support for business isolation;+ Change cost control from global to company level."""from __future__ import annotations@@@ -50,7 -47,7 +48,7 @@@ ROLE_TEMPLATE = """Your response shoulclass RoleSetting(BaseModel):-- """角色设定"""++ """Role properties"""name: strprofile: strgoal: str@@@ -65,7 -62,7 +63,7 @@@class RoleContext(BaseModel):-- """角色运行时上下文"""++ """Runtime role context"""env: 'Environment' = Field(default=None)memory: Memory = Field(default_factory=Memory)long_term_memory: LongTermMemory = Field(default_factory=LongTermMemory)@@@ -84,7 -82,7 +83,7 @@@@propertydef important_memory(self) -> list[Message]:-- """获得关注动作对应的信息"""++ """Retrieve information corresponding to the attention action."""return self.memory.get_by_actions(self.watch)@property@@@ -93,24 -91,17 +92,25 @@@class Role:-- """角色/代理"""-- def __init__(self, name="", profile="", goal="", constraints="", desc="", *args, **kwargs):- # Enable parameter configurability- name = Role.format_value(name, kwargs)- profile = Role.format_value(profile, kwargs)- goal = Role.format_value(goal, kwargs)- constraints = Role.format_value(constraints, kwargs)- desc = Role.format_value(desc, kwargs)-- # Initialize- self._llm = LLM()++ """Role/Proxy"""++++ def __init__(self, options, cost_manager, name="", profile="", goal="", constraints="", desc="", *args, **kwargs):++ self._options = Role.supply_options(options=kwargs, default_options=options)++++ name = Role.format_value(name, self._options)++ profile = Role.format_value(profile, self._options)++ goal = Role.format_value(goal, self._options)++ constraints = Role.format_value(constraints, self._options)++ desc = Role.format_value(desc, self._options)+- def __init__(self, options, cost_manager, name="", profile="", goal="", constraints="", desc=""):- self._options = options if options else {}+ self._cost_manager = cost_manager+ self._llm = LLM(options=self._options, cost_manager=cost_manager)++self._setting = RoleSetting(name=name, profile=profile, goal=goal, constraints=constraints, desc=desc)self._states = []self._actions = []self._role_id = str(self._setting)- self._rc = RoleContext()- self._options = Role.supply_options(kwargs)- self._rc = RoleContext(options=options)++ self._rc = RoleContext(options=self._options)def _reset(self):self._states = []@@@ -149,30 -140,13 +149,37 @@@return self._setting.profile@property+ def name(self):+ """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)++ def options(self):+ return self._options++ @options.setter+ def options(self, opts):+ self._options.update(opts)+def _get_prefix(self):"""获取角色前缀"""if self._setting.desc:@@@ -219,9 -192,9 +226,9 @@@if not self._rc.env:return 0env_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 memoriesfor i in env_msgs:@@@ -278,34 -251,3 +285,30 @@@# 将回复发布到环境,等待下一个订阅者处理self._publish_message(rsp)return rsp++ @staticmethod- def supply_options(options):++ def supply_options(options, default_options=None):+ """Supply missing options"""- ret = Role.__DEFAULT_OPTIONS__.copy()++ ret = default_options.copy() if default_options else {}+ if not options:+ return ret+ ret.update(options)+ return ret++ @staticmethod- def format_value(value, options):++ def format_value(value, opts, default_opts=None):+ """Fill parameters inside `value` with `options`."""+ if not isinstance(value, str):+ return value+ if "{" not in value:+ return value+- options = Role.supply_options(options)++ merged_opts = Role.supply_options(opts, default_opts)+ try:- return value.format(**options)++ return value.format(**merged_opts)+ except KeyError as e:+ logger.warning(f"Parameter is missing:{e}")- for k, v in options.items():- value = value.replace("{" + f"{k}" + "}", str(v))- return value+- __DEFAULT_OPTIONS__ = {- "teaching_language": "English",- "language": "Chinese"- }++ for k, v in merged_opts.items():++ value = value.replace("{" + f"{k}" + "}", str(v))++ return valuediff --cc metagpt/software_company.pyindex 10fb025d6,3f6f484b4..0e10fc2d9--- a/metagpt/software_company.py+++ b/metagpt/software_company.py@@@ -4,8 -4,11 +4,12 @@@@Time : 2023/5/12 00:30@Author : alexanderwu@File : software_company.py+@Modified By: mashenquan, 2023-07-27, Add `role` & `cause_by` parameters to `start_project()`.+ @Modified By: mashenquan, 2023/8/20. Remove global configuration `CONFIG`, enable configuration support for business isolation;+ Change cost control from global to company level."""+ from typing import Dict+from pydantic import BaseModel, Fieldfrom metagpt.actions import BossRequirement@@@ -40,13 -46,13 +47,13 @@@ class SoftwareCompany(BaseModel)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}')+ if self.total_cost > self.max_budget:+ raise NoMoneyException(self.total_cost, f'Insufficient funds: {self.max_budget}')- def start_project(self, idea):+ def start_project(self, idea, role="BOSS", cause_by=BossRequirement):"""Start a project from publishing boss requirement."""self.idea = idea- self.environment.publish_message(Message(role="BOSS", content=idea, cause_by=BossRequirement))+ self.environment.publish_message(Message(role=role, content=idea, cause_by=cause_by))def _save(self):logger.info(self.json())diff --cc tests/metagpt/actions/test_write_code.pyindex 2d4c496e1,04216ad7c..3480734e0--- a/tests/metagpt/actions/test_write_code.py+++ b/tests/metagpt/actions/test_write_code.py@@@ -4,7 -4,7 +4,8 @@@@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."""import pytest@@@ -17,9 -18,12 +19,11 @@@ from tests.metagpt.actions.mock import@pytest.mark.asyncioasync def test_write_code():api_design = "设计一个名为'add'的函数,该函数接受两个整数作为输入,并返回它们的和。"- write_code = WriteCode("write_code")-+ conf = Config()+ cost_manager = CostManager(conf.runtime_options)+ llm = LLM(options=conf.runtime_options, cost_manager=cost_manager)+ write_code = WriteCode(options=conf.runtime_options, name="write_code", llm=llm)-- code = await write_code.run(api_design, "filename")+ code = await write_code.run(context=api_design, filename="test")logger.info(code)# 我们不能精确地预测生成的代码,但我们可以检查某些关键字