🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming
Merge branch 'serialization' into feat_serdes
better629c56a629b40a7
diff --cc metagpt/actions/action.pyindex a538baa77,7bb5a151b..aefe6d39d--- a/metagpt/actions/action.py+++ b/metagpt/actions/action.py@@@ -17,63 -17,32 +17,63 @@@ from metagpt.llm import LLfrom metagpt.logs import loggerfrom metagpt.utils.common import OutputParserfrom metagpt.utils.custom_decoder import CustomDecoder+from metagpt.utils.utils import import_class- class Action(ABC):- def __init__(self, name: str = "", context=None, llm: LLM = None):- self.name: str = name- if llm is None:- llm = LLM()- self.llm = llm- self.context = context- self.prefix = ""- self.profile = ""- self.desc = ""- self.content = ""- self.instruct_content = None-+ class Action(BaseModel):+ name: str = ""+ llm: LLM = Field(default_factory=LLM)+ context = ""+ prefix = ""+ profile = ""+ desc = ""+ content: Optional[str] = None+ instruct_content: Optional[str] = None++ def __init__(self, **kwargs: Any):+ super().__init__(**kwargs)+def set_prefix(self, prefix, profile):"""Set prefix for later usage"""self.prefix = prefixself.profile = profile-+def __str__(self):return self.__class__.__name__-+def __repr__(self):return self.__str__()-++ def serialize(self):+ return {+ "action_class": self.__class__.__name__,+ "module_name": self.__module__,+ "name": self.name+ }++ @classmethod+ def deserialize(cls, action_dict: dict):+ action_class_str = action_dict.pop("action_class")+ module_name = action_dict.pop("module_name")+ action_class = import_class(action_class_str, module_name)+ return action_class(**action_dict)++ @classmethod+ def ser_class(cls):+ """ serialize class type"""+ return {+ "action_class": cls.__name__,+ "module_name": cls.__module__+ }++ @classmethod+ def deser_class(cls, action_dict: dict):+ """ deserialize class type """+ action_class_str = action_dict.pop("action_class")+ module_name = action_dict.pop("module_name")+ action_class = import_class(action_class_str, module_name)+ return action_class+async def _aask(self, prompt: str, system_msgs: Optional[list[str]] = None) -> str:"""Append default prefix"""if not system_msgs:diff --cc metagpt/environment.pyindex d1fa561f0,88ff145e0..e867ad6fc--- a/metagpt/environment.py+++ b/metagpt/environment.py@@@ -30,44 -28,8 +30,44 @@@ class Environment(BaseModel)class Config:arbitrary_types_allowed = True+ def serialize(self, stg_path: Path):+ roles_path = stg_path.joinpath("roles.json")+ roles_info = []+ for role_key, role in self.roles.items():+ roles_info.append({+ "role_class": role.__class__.__name__,+ "module_name": role.__module__,+ "role_name": role.name+ })+ role.serialize(stg_path=stg_path.joinpath(f"roles/{role.__class__.__name__}_{role.name}"))+ write_json_file(roles_path, roles_info)++ self.memory.serialize(stg_path)+ history_path = stg_path.joinpath("history.json")+ write_json_file(history_path, {"content": self.history})++ def deserialize(self, stg_path: Path):+ """ stg_path: ./storage/team/environment/ """+ roles_path = stg_path.joinpath("roles.json")+ roles_info = read_json_file(roles_path)+ for role_info in roles_info:+ role_class = role_info.get("role_class")+ role_name = role_info.get("role_name")++ role_path = stg_path.joinpath(f"roles/{role_class}_{role_name}")+ role = Role.deserialize(role_path)++ self.add_role(role)++ memory = Memory.deserialize(stg_path)+ self.memory = memory++ history_path = stg_path.joinpath("history.json")+ history = read_json_file(history_path)+ self.history = history.get("content")+def add_role(self, role: Role):- """增加一个在当前环境的角色+ """增加一个在当前环境的角色, 默认为profile/role_profileAdd a role in the current environment"""role.set_env(self)diff --cc metagpt/roles/role.pyindex 9b0613fd5,9aae64188..eb5539f43--- a/metagpt/roles/role.py+++ b/metagpt/roles/role.py@@@ -5,13 -5,21 +5,23 @@@@Author : alexanderwu@File : role.py"""- from __future__ import annotations- from typing import Iterable, Type, Union++import sys+from enum import Enum- from pathlib import Path- from pydantic import BaseModel, Field+import importlib+ from __future__ import annotations+-import sys+ from types import SimpleNamespace+ from typing import (+ Dict,+ Optional,+ Union,+ Iterable,+ Type+ )+ import re+ from pydantic import BaseModel, Field+ from importlib import import_module# from metagpt.environment import Environmentfrom metagpt.config import CONFIG@@@ -51,27 -56,18 +61,27 @@@ ROLE_TEMPLATE = """Your response shoul{name}: {result}"""+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):"""Role Settings"""- name: str- profile: str- goal: str- constraints: str- desc: str- is_human: bool-+ name: str = ""+ profile: str = ""+ goal: str = ""+ constraints: str = ""+ desc: str = ""+def __str__(self):return f"{self.name}({self.profile})"-+def __repr__(self):return self.__str__()@@@ -85,12 -81,10 +95,12 @@@ class RoleContext(BaseModel)todo: Action = Field(default=None)watch: set[Type[Action]] = 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 = 1-+class Config:arbitrary_types_allowed = True-+def check(self, role_id: str):if hasattr(CONFIG, "long_term_memory") and CONFIG.long_term_memory:self.long_term_memory.recover_memory(role_id, self)@@@ -106,153 -100,78 +116,200 @@@return self.memory.get()- class Role:+ class Role(BaseModel):"""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)- self._states = []- self._actions = []- self._role_id = str(self._setting)- self._rc = RoleContext()- self._recovered = False+ name: str = ""+ profile: str = ""+ goal: str = ""+ constraints: str = ""+ desc: str = ""+ _setting: RoleSetting = Field(default_factory=RoleSetting, alias="_setting")+ _setting = RoleSetting(name=name, profile=profile, goal=goal, constraints=constraints)+ _role_id: str = ""+ _states: list = Field(default=[])+ _actions: list = Field(default=[])+ _actions_type: list = Field(default=[])+ _rc: RoleContext = RoleContext()++ _private_attributes = {- '_setting': _setting,- '_role_id': _role_id,++ "_setting': _setting,++ "_role_id': _role_id,+ '_states': [],+ '_actions': [],+ '_actions_type': [] # 用于记录和序列化+ }++ class Config:+ arbitrary_types_allowed = True++ def __init__(self, **kwargs):+ super().__init__(**kwargs)+ # 关于私有变量的初始化 https://github.com/pydantic/pydantic/issues/655+ for key in self._private_attributes.keys():+ if key in kwargs:+ object.__setattr__(self, key, kwargs[key])+ if key =="_setting":+ _setting = RoleSetting(**kwargs[key])+ object.__setattr__(self, '_setting', _setting)+ elif key == "_rc":+ _rc = RoleContext+ object.__setattr__(self, '_rc', _rc)+ else:+ object.__setattr__(self, key, self._private_attributes[key])++ def _reset(self):+ object.__setattr__(self, '_states', [])+ object.__setattr__(self, '_actions', [])-+-+ @staticmethod+ def _process_class(class_str, module_name):+ cleaned_string = re.sub(r"[<>']", "", class_str).replace("class ", "")+ package_name = "metagpt"+ file_name = cleaned_string.replace(package_name, "").replace("." + module_name, "")+ print(file_name)+ # print("\n", sys.modules)+ module_file = import_module(file_name, package=package_name)+ module = getattr(module_file, module_name)+ return module-++ def serialize(self, stg_path: Path):+ role_info_path = stg_path.joinpath("role_info.json")+ role_info = {+ "role_class": self.__class__.__name__,+ "module_name": self.__module__+ }+ setting = self._setting.dict()+ setting.pop("desc")+ setting.pop("is_human") # not all inherited roles have this atrr+ role_info.update(setting)+ write_json_file(role_info_path, role_info)++ actions_info_path = stg_path.joinpath("actions/actions_info.json")+ actions_info = []+ for action in self._actions:+ actions_info.append(action.serialize())+ write_json_file(actions_info_path, actions_info)++ watches_info_path = stg_path.joinpath("watches/watches_info.json")+ watches_info = []+ for watch in self._rc.watch:+ watches_info.append(watch.ser_class())+ write_json_file(watches_info_path, watches_info)++ actions_todo_path = stg_path.joinpath("actions/todo.json")+ actions_todo = {+ "cur_state": self._rc.state,+ "react_mode": self._rc.react_mode.value,+ "max_react_loop": self._rc.max_react_loop+ }+ write_json_file(actions_todo_path, actions_todo)++ self._rc.memory.serialize(stg_path)++ @classmethod+ def deserialize(cls, stg_path: Path) -> "Role":+ """ stg_path = ./storage/team/environment/roles/{role_class}_{role_name}"""+ role_info_path = stg_path.joinpath("role_info.json")+ role_info = read_json_file(role_info_path)++ role_class_str = role_info.pop("role_class")+ module_name = role_info.pop("module_name")+ role_class = import_class(class_name=role_class_str, module_name=module_name)++ role = role_class(**role_info) # initiate particular Role+ actions_info_path = stg_path.joinpath("actions/actions_info.json")+ actions = []+ actions_info = read_json_file(actions_info_path)+ for action_info in actions_info:+ action = Action.deserialize(action_info)+ actions.append(action)++ watches_info_path = stg_path.joinpath("watches/watches_info.json")+ watches = []+ watches_info = read_json_file(watches_info_path)+ for watch_info in watches_info:+ action = Action.deser_class(watch_info)+ watches.append(action)++ role.init_actions(actions)+ role.watch(watches)++ actions_todo_path = stg_path.joinpath("actions/todo.json")+ # recover self._rc.state+ actions_todo = read_json_file(actions_todo_path)+ max_react_loop = actions_todo.get("max_react_loop", 1)+ cur_state = actions_todo.get("cur_state", -1)+ role.set_state(cur_state)+ role.set_recovered(True)+ react_mode_str = actions_todo.get("react_mode", RoleReactMode.REACT.value)+ if react_mode_str not in RoleReactMode.values():+ logger.warning(f"ReactMode: {react_mode_str} not in {RoleReactMode.values()}, use react as default")+ react_mode_str = RoleReactMode.REACT.value+ role.set_react_mode(RoleReactMode(react_mode_str), max_react_loop)++ role_memory = Memory.deserialize(stg_path)+ role.set_memory(role_memory)++ return role++ def _reset(self):+ self._states = []+ self._actions = []++ def set_recovered(self, recovered: bool = False):+ self._recovered = recovered++ def set_memory(self, memory: Memory):+ self._rc.memory = memory++ def init_actions(self, actions):+ self._init_actions(actions)+def _init_actions(self, actions):self._reset()for idx, action in enumerate(actions):if not isinstance(action, Action):+ ## 默认初始化- i = action()+ i = action("", llm=self._llm)else:+ if self._setting.is_human and not isinstance(action.llm, HumanProvider):+ logger.warning(f"is_human attribute does not take effect,"+ f"as Role's {str(action)} was initialized using LLM, try passing in Action classes instead of initialized instances")i = actioni.set_prefix(self._get_prefix(), self.profile)self._actions.append(i)self._states.append(f"{idx}. {action}")+ action_title = action.schema()["title"]+ self._actions_type.append(action_title)-++ def set_react_mode(self, react_mode: RoleReactMode, max_react_loop: int = 1):+ self._set_react_mode(react_mode, max_react_loop)++ def _set_react_mode(self, react_mode: str, max_react_loop: int = 1):+ """Set strategy of the Role reacting to observed Message. Variation lies in how+ this Role elects action to perform during the _think stage, especially if it is capable of multiple Actions.++ Args:+ react_mode (str): Mode for choosing action during the _think stage, can be one of:+ "react": standard think-act loop in the ReAct paper, alternating thinking and acting to solve the task, i.e. _think -> _act -> _think -> _act -> ...+ Use llm to select actions in _think dynamically;+ "by_order": switch action each time by order defined in _init_actions, i.e. _act (Action1) -> _act (Action2) -> ...;+ "plan_and_act": first plan, then execute an action sequence, i.e. _think (of a plan) -> _act -> _act -> ...+ Use llm to come up with the plan dynamically.+ Defaults to "react".+ max_react_loop (int): Maximum react cycles to execute, used to prevent the agent from reacting forever.+ Take effect only when react_mode is react, in which we use llm to choose actions, including termination.+ Defaults to 1, i.e. _think -> _act (-> return result and end)+ """+ assert react_mode in RoleReactMode.values(), f"react_mode must be one of {RoleReactMode.values()}"+ self._rc.react_mode = react_mode+ if react_mode == RoleReactMode.REACT:+ self._rc.max_react_loop = max_react_loop++ def watch(self, actions: Iterable[Type[Action]]):+ self._watch(actions)+def _watch(self, actions: Iterable[Type[Action]]):"""Listen to the corresponding behaviors"""self._rc.watch.update(actions)@@@ -266,16 -182,12 +323,16 @@@"""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 None-+def set_env(self, env: 'Environment'):"""Set the environment in which the role works. The role can talk to the environment and can also receive messages by observing."""self._rc.env = env-++ @property+ def name(self):+ return self._setting.name+@propertydef profile(self):"""Get the role description (position)"""@@@ -293,32 -205,17 +350,27 @@@# If there is only one action, then only this one can be performedself._set_state(0)return+ if self._recovered and self._rc.state >= 0:+ self._set_state(self._rc.state) # action to run from recovered state+ self._recovered = False # avoid max_react_loop out of work+ return+prompt = self._get_prefix()prompt += STATE_TEMPLATE.format(history=self._rc.history, states="\n".join(self._states),- n_states=len(self._states) - 1)+ 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() 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))+ 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)-+async 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}")response = await self._rc.todo.run(self._rc.important_memory)# logger.info(response)@@@ -337,14 -234,15 +389,14 @@@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.find_news(- observed) # find news (previously unseen messages) from observed messages+ self._rc.news = self._rc.memory.find_news(observed) # find news (previously unseen messages) from observed messages-+for i in env_msgs:self.recv(i)-+news_text = [f"{i.role}: {i.content[:20]}..." for i in self._rc.news]if news_text:logger.debug(f'{self._setting} observed: {news_text}')@@@ -356,49 -254,13 +408,49 @@@# If env does not exist, do not publish the messagereturnself._rc.env.publish_message(msg)-+async def _react(self) -> Message:- """Think first, then act"""- await self._think()- logger.debug(f"{self._setting}: {self._rc.state=}, will do {self._rc.todo}")- return await self._act()-+ """Think first, then act, until the Role _think it is time to stop and requires no more todo.+ This is the standard think-act loop in the ReAct paper, which alternates thinking and acting in task solving, i.e. _think -> _act -> _think -> _act -> ...+ Use llm to select actions in _think dynamically+ """+ actions_taken = 0+ rsp = Message("No actions taken yet") # will be overwritten after Role _act+ while actions_taken < self._rc.max_react_loop:+ # think+ await self._think()+ if self._rc.todo is None:+ break+ # act+ logger.debug(f"{self._setting}: {self._rc.state=}, will do {self._rc.todo}")+ rsp = await self._act()+ actions_taken += 1+ return rsp # return output from the last action++ async def _act_by_order(self) -> Message:+ """switch action each time by order defined in _init_actions, i.e. _act (Action1) -> _act (Action2) -> ..."""+ start_idx = self._rc.state if self._rc.state >= 0 else 0 # action to run from recovered state+ for i in range(start_idx, len(self._states)):+ self._set_state(i)+ rsp = await self._act()+ return rsp # return output from the last action++ async def _plan_and_act(self) -> Message:+ """first plan, then execute an action sequence, i.e. _think (of a plan) -> _act -> _act -> ... Use llm to come up with the plan dynamically."""+ # TODO: to be implemented+ return Message("")++ async def react(self) -> Message:+ """Entry to one of three strategies by which Role reacts to the observed Message"""+ if self._rc.react_mode == RoleReactMode.REACT:+ rsp = await self._react()+ elif self._rc.react_mode == RoleReactMode.BY_ORDER:+ rsp = await self._act_by_order()+ elif self._rc.react_mode == RoleReactMode.PLAN_AND_ACT:+ rsp = await self._plan_and_act()+ self._set_state(state=-1) # current reaction is complete, reset state to -1 and todo back to None+ return rsp+def recv(self, message: Message) -> None:"""add message to history."""# self._history += f"\n{message}"@@@ -411,13 -273,9 +463,13 @@@"""Receive information and reply with actions"""# logger.debug(f"{self.name=}, {self.profile=}, {message.role=}")self.recv(message)-+return await self._react()-++ def get_memories(self, k=0) -> list[Message]:+ """A wrapper to return the most recent k memories of this role, return all when k=0"""+ return self._rc.memory.get(k=k)-++async def run(self, message=None):"""Observe, and think and act based on the results of the observation"""if message:@@@ -431,8 -289,8 +483,8 @@@# If there is no new information, suspend and waitlogger.debug(f"{self._setting}: no news. waiting.")return-+- rsp = await self._react()+ rsp = await self.react()# Publish the reply to the environment, waiting for the next subscriber to processself._publish_message(rsp)return rsp