Skip to content

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

feat: Merge geekan:env_refactore

莘权 马20ae74e99d15
diff --cc examples/debate.py
index 597b44e8d,54da73cca..44602a11a
--- a/examples/debate.py
+++ b/examples/debate.py
@@@ -15,8 -13,7 +15,9 @@@ from metagpt.logs import logge
from metagpt.roles import Role
from metagpt.schema import Message
from metagpt.software_company import SoftwareCompany
+
+from metagpt.utils.common import any_to_str
+
class ShoutOut(Action):
"""Action: Shout out loudly in a debate (quarrel)"""
@@@ -60,7 -57,7 +61,8 @@@ class Trump(Role)
async def _observe(self) -> int:
await super()._observe()
# accept messages sent (from opponent) to self, disregard own messages from the last round
- self._rc.news = [msg for msg in self._rc.news if msg.send_to == self.name]
++
+ self._rc.news = [msg for msg in self._rc.news if msg.send_to == {self.name}]
return len(self._rc.news)
async def _act(self) -> Message:
diff --cc metagpt/actions/write_code.py
index aeaa10aec,a922d3694..58499df62
--- a/metagpt/actions/write_code.py
+++ b/metagpt/actions/write_code.py
@@@ -14,7 -12,7 +14,8 @@@ from metagpt.actions.action import Acti
from metagpt.const import WORKSPACE_ROOT
from metagpt.logs import logger
from metagpt.schema import Message
-from metagpt.utils.common import CodeParser
++
+from metagpt.utils.common import CodeParser, any_to_str
PROMPT_TEMPLATE = """
NOTICE
diff --cc metagpt/environment.py
index 02eb3d340,2e2aa152a..a50dbde9e
--- a/metagpt/environment.py
+++ b/metagpt/environment.py
@@@ -29,9 -22,9 +29,10 @@@ class Environment(BaseModel)
"""
roles: dict[str, Role] = Field(default_factory=dict)
- memory: Memory = Field(default_factory=Memory)
- history: str = Field(default="")
+ members: dict[Role, Set] = Field(default_factory=dict)
+ history: str = Field(default="") # For debug
+
+
class Config:
arbitrary_types_allowed = True
@@@ -49,27 -42,13 +50,28 @@@
for role in roles:
self.add_role(role)
- def publish_message(self, message: Message):
- """向当前环境发布信息
- Post information to the current environment
++
+ def publish_message(self, message: Message) -> bool:
"""
- # self.message_queue.put(message)
- self.memory.add(message)
- self.history += f"\n{message}"
+ Distribute the message to the recipients.
+ In accordance with the Message routing structure design in Chapter 2.2.1 of RFC 116, as already planned
+ in RFC 113 for the entire system, the routing information in the Message is only responsible for
+ specifying the message recipient, without concern for where the message recipient is located. How to
+ route the message to the message recipient is a problem addressed by the transport framework designed
+ in RFC 113.
+ """
+ logger.info(f"publish_message: {message.dump()}")
+ found = False
+ # According to the routing feature plan in Chapter 2.2.3.2 of RFC 113
+ for role, subscription in self.members.items():
+ if is_subscribed(message, subscription):
+ role.put_message(message)
+ found = True
+ if not found:
+ logger.warning(f"Message no recipients: {message.dump()}")
+ self.history += f"\n{message}" # For debug
+
+ return True
async def run(self, k=1):
"""处理一次所有信息的运行
diff --cc metagpt/roles/role.py
index 2e3bcbbd5,282431bf7..e1f43ef3a
--- a/metagpt/roles/role.py
+++ b/metagpt/roles/role.py
@@@ -25,13 -12,14 +25,16 @@@ from typing import Iterable, Set, Typ
from pydantic import BaseModel, Field
from metagpt.actions import Action, ActionOutput
+
-# from metagpt.environment import Environment
from metagpt.config import CONFIG
from metagpt.llm import LLM
from metagpt.logs import logger
from metagpt.memory import LongTermMemory, Memory
-from metagpt.schema import Message
++
+from metagpt.schema import Message, MessageQueue
+from metagpt.utils.common import any_to_str
+
+
PREFIX_TEMPLATE = """You are a {profile}, named {name}, your goal is {goal}, and the constraint is {constraints}. """
STATE_TEMPLATE = """Here are your conversation records. You can decide which stage you should enter or stay in based on these records.
diff --cc metagpt/schema.py
index 82a0117ef,19c7a6654..b40d65d5f
--- a/metagpt/schema.py
+++ b/metagpt/schema.py
@@@ -36,53 -25,13 +36,54 @@@ class Message(BaseModel)
"""list[<role>: <content>]"""
content: str
- instruct_content: BaseModel = field(default=None)
- role: str = field(default="user") # system / user / assistant
- cause_by: Type["Action"] = field(default="")
- sent_from: str = field(default="")
- send_to: str = field(default="")
- restricted_to: str = field(default="")
+ instruct_content: BaseModel = Field(default=None)
+ role: str = "user" # system / user / assistant
+ cause_by: str = ""
+ sent_from: str = ""
+ send_to: Set = Field(default_factory={MESSAGE_ROUTE_TO_ALL})
+
+ def __init__(
+ self,
+ content,
+ instruct_content=None,
+ role="user",
+ cause_by="",
+ sent_from="",
+ send_to=MESSAGE_ROUTE_TO_ALL,
+ **kwargs,
+ ):
+ """
+ Parameters not listed below will be stored as meta info, including custom parameters.
+ :param content: Message content.
+ :param instruct_content: Message content struct.
+ :param cause_by: Message producer
+ :param sent_from: Message route info tells who sent this message.
+ :param send_to: Specifies the target recipient or consumer for message delivery in the environment.
+ :param role: Message meta info tells who sent this message.
+ """
+ super().__init__(
+ content=content,
+ instruct_content=instruct_content,
+ role=role,
+ cause_by=any_to_str(cause_by),
+ sent_from=any_to_str(sent_from),
+ send_to=any_to_str_set(send_to),
+ **kwargs,
+ )
+
+ def __setattr__(self, key, val):
+ """Override `@property.setter`, convert non-string parameters into string parameters."""
+ if key == MESSAGE_ROUTE_CAUSE_BY:
+ new_val = any_to_str(val)
+ elif key == MESSAGE_ROUTE_FROM:
+ new_val = any_to_str(val)
+ elif key == MESSAGE_ROUTE_TO:
+ new_val = any_to_str_set(val)
+ else:
+ new_val = val
+ super().__setattr__(key, new_val)
+
+
def __str__(self):
# prefix = '-'.join([self.role, str(self.cause_by)])
return f"{self.role}: {self.content}"
@@@ -91,33 -40,20 +92,35 @@@
return self.__str__()
def to_dict(self) -> dict:
+ """Return a dict containing `role` and `content` for the LLM call.l"""
return {"role": self.role, "content": self.content}
+ def dump(self) -> str:
+ """Convert the object to json string"""
+ return self.json(exclude_none=True)
+
+ @staticmethod
+ def load(val):
+ """Convert the json string to object."""
+ try:
+ d = json.loads(val)
+ return Message(**d)
+ except JSONDecodeError as err:
+ logger.error(f"parse json failed: {val}, error:{err}")
+ return None
+
+
+
-@dataclass
class UserMessage(Message):
"""便于支持OpenAI的消息
Facilitate support for OpenAI messages
"""
def __init__(self, content: str):
- super().__init__(content, "user")
+ super().__init__(content=content, role="user")
+
+
-@dataclass
class SystemMessage(Message):
"""便于支持OpenAI的消息
Facilitate support for OpenAI messages
@@@ -133,70 -70,15 +136,71 @@@ class AIMessage(Message)
"""
def __init__(self, content: str):
- super().__init__(content, "assistant")
-
-
-if __name__ == "__main__":
- test_content = "test_message"
- msgs = [
- UserMessage(test_content),
- SystemMessage(test_content),
- AIMessage(test_content),
- Message(test_content, role="QA"),
- ]
- logger.info(msgs)
+ super().__init__(content=content, role="assistant")
+
+
+class MessageQueue:
+ """Message queue which supports asynchronous updates."""
+
+ def __init__(self):
+ self._queue = Queue()
+
+ def pop(self) -> Message | None:
+ """Pop one message from the queue."""
+ try:
+ item = self._queue.get_nowait()
+ if item:
+ self._queue.task_done()
+ return item
+ except QueueEmpty:
+ return None
+
+ def pop_all(self) -> List[Message]:
+ """Pop all messages from the queue."""
+ ret = []
+ while True:
+ msg = self.pop()
+ if not msg:
+ break
+ ret.append(msg)
+ return ret
+
+ def push(self, msg: Message):
+ """Push a message into the queue."""
+ self._queue.put_nowait(msg)
+
+ def empty(self):
+ """Return true if the queue is empty."""
+ return self._queue.empty()
+
+ async def dump(self) -> str:
+ """Convert the `MessageQueue` object to a json string."""
+ if self.empty():
+ return "[]"
+
+ lst = []
+ try:
+ while True:
+ item = await wait_for(self._queue.get(), timeout=1.0)
+ if item is None:
+ break
+ lst.append(item.dict(exclude_none=True))
+ self._queue.task_done()
+ except asyncio.TimeoutError:
+ logger.debug("Queue is empty, exiting...")
+ return json.dumps(lst)
+
+ @staticmethod
+ def load(self, v) -> "MessageQueue":
+ """Convert the json string to the `MessageQueue` object."""
+ q = MessageQueue()
+ try:
+ lst = json.loads(v)
+ for i in lst:
+ msg = Message(**i)
+ q.push(msg)
+ except JSONDecodeError as e:
+ logger.warning(f"JSON load failed: {v}, error:{e}")
+
+ return q
++
diff --cc tests/metagpt/test_message.py
index 04d85d9e4,ae6708943..f52dfb64c
--- a/tests/metagpt/test_message.py
+++ b/tests/metagpt/test_message.py
@@@ -35,7 -34,3 +35,8 @@@ def test_raw_message()
assert msg["content"] == "raw"
with pytest.raises(KeyError):
assert msg["1"] == 1, "KeyError: '1'"
+
+
+if __name__ == "__main__":
+ pytest.main([__file__, "-s"])
++
diff --cc tests/metagpt/test_role.py
index 8fac2503c,22cfa58a4..f93651303
--- a/tests/metagpt/test_role.py
+++ b/tests/metagpt/test_role.py
@@@ -4,98 -4,11 +4,100 @@@
@Time : 2023/5/11 14:44
@Author : alexanderwu
@File : test_role.py
+@Modified By: mashenquan, 2023-11-1. In line with Chapter 2.2.1 and 2.2.2 of RFC 116, introduce unit tests for
+ the utilization of the new message distribution feature in message handling.
+@Modified By: mashenquan, 2023-11-4. According to the routing feature plan in Chapter 2.2.3.2 of RFC 113, the routing
+ functionality is to be consolidated into the `Environment` class.
"""
+import uuid
+
+import pytest
+from pydantic import BaseModel
+
+from metagpt.actions import Action, ActionOutput
+from metagpt.environment import Environment
from metagpt.roles import Role
+from metagpt.schema import Message
+from metagpt.utils.common import get_class_name
+
+
+class MockAction(Action):
+ async def run(self, messages, *args, **kwargs):
+ assert messages
+ return ActionOutput(content=messages[-1].content, instruct_content=messages[-1])
+
+
+class MockRole(Role):
+ def __init__(self, name="", profile="", goal="", constraints="", desc=""):
+ super().__init__(name=name, profile=profile, goal=goal, constraints=constraints, desc=desc)
+ self._init_actions([MockAction()])
+
+
+async def test_react():
+ class Input(BaseModel):
+ name: str
+ profile: str
+ goal: str
+ constraints: str
+ desc: str
+ subscription: str
+
+ inputs = [
+ {
+ "name": "A",
+ "profile": "Tester",
+ "goal": "Test",
+ "constraints": "constraints",
+ "desc": "desc",
+ "subscription": "start",
+ }
+ ]
+
+ for i in inputs:
+ seed = Input(**i)
+ role = MockRole(
+ name=seed.name, profile=seed.profile, goal=seed.goal, constraints=seed.constraints, desc=seed.desc
+ )
+ role.subscribe({seed.subscription})
+ assert role._rc.watch == set({})
+ assert role.name == seed.name
+ assert role.profile == seed.profile
+ assert role._setting.goal == seed.goal
+ assert role._setting.constraints == seed.constraints
+ assert role._setting.desc == seed.desc
+ assert role.is_idle
+ env = Environment()
+ env.add_role(role)
+ assert env.get_subscription(role) == {seed.subscription}
+ env.publish_message(Message(content="test", msg_to=seed.subscription))
+ assert not role.is_idle
+ while not env.is_idle:
+ await env.run()
+ assert role.is_idle
+ env.publish_message(Message(content="test", cause_by=seed.subscription))
+ assert not role.is_idle
+ while not env.is_idle:
+ await env.run()
+ assert role.is_idle
+ tag = uuid.uuid4().hex
+ role.subscribe({tag})
+ assert env.get_subscription(role) == {tag}
+
+
+async def test_msg_to():
+ m = Message(content="a", send_to=["a", MockRole, Message])
+ assert m.send_to == set({"a", get_class_name(MockRole), get_class_name(Message)})
+
+ m = Message(content="a", cause_by=MockAction, send_to={"a", MockRole, Message})
+ assert m.send_to == set({"a", get_class_name(MockRole), get_class_name(Message)})
+
+ m = Message(content="a", send_to=("a", MockRole, Message))
+ assert m.send_to == set({"a", get_class_name(MockRole), get_class_name(Message)})
+
+
+
+if __name__ == "__main__":
+ pytest.main([__file__, "-s"])
+
-def test_role_desc():
- i = Role(profile="Sales", desc="Best Seller")
- assert i.profile == "Sales"
- assert i._setting.desc == "Best Seller"