Skip to content

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

Merge branch 'main' into code_interpreter

yzlin38f21137ec27
diff --cc metagpt/actions/__init__.py
index 31de8c04a,29af1dad1..18140b726
--- a/metagpt/actions/__init__.py
+++ b/metagpt/actions/__init__.py
@@@ -22,9 -22,9 +22,9 @@@ from metagpt.actions.write_code_review
from metagpt.actions.write_prd import WritePRD
from metagpt.actions.write_prd_review import WritePRDReview
from metagpt.actions.write_test import WriteTest
- from metagpt.actions.mi.execute_nb_code import ExecuteNbCode
- from metagpt.actions.mi.write_analysis_code import WriteCodeWithTools
- from metagpt.actions.mi.write_plan import WritePlan
+ from metagpt.actions.di.execute_nb_code import ExecuteNbCode
-from metagpt.actions.di.write_analysis_code import WriteCodeWithoutTools, WriteCodeWithTools
++from metagpt.actions.di.write_analysis_code import WriteCodeWithTools
+ from metagpt.actions.di.write_plan import WritePlan
class ActionType(Enum):
diff --cc metagpt/actions/di/write_analysis_code.py
index 55a9a5eb0,0c4980c2b..d704bef24
--- a/metagpt/actions/di/write_analysis_code.py
+++ b/metagpt/actions/di/write_analysis_code.py
@@@ -6,35 -6,131 +6,35 @@@
"""
from __future__ import annotations
-from typing import Tuple
+import json
from metagpt.actions import Action
- from metagpt.prompts.mi.write_analysis_code import (
-from metagpt.logs import logger
+ from metagpt.prompts.di.write_analysis_code import (
- CODE_GENERATOR_WITH_TOOLS,
- SELECT_FUNCTION_TOOLS,
- TOOL_RECOMMENDATION_PROMPT,
- TOOL_USAGE_PROMPT,
+ CHECK_DATA_PROMPT,
+ DEBUG_REFLECTION_EXAMPLE,
+ INTERPRETER_SYSTEM_MSG,
+ REFLECTION_PROMPT,
+ REFLECTION_SYSTEM_MSG,
+ STRUCTUAL_PROMPT,
)
-from metagpt.schema import Message, Plan, SystemMessage
-from metagpt.tools import TOOL_REGISTRY
-from metagpt.tools.tool_registry import validate_tool_names
-from metagpt.utils.common import create_func_call_config
+from metagpt.schema import Message, Plan
+from metagpt.utils.common import CodeParser, process_message, remove_comments
-class BaseWriteAnalysisCode(Action):
- DEFAULT_SYSTEM_MSG: str = """You are Code Interpreter, a world-class programmer that can complete any goal by executing code. Strictly follow the plan and generate code step by step. Each step of the code will be executed on the user's machine, and the user will provide the code execution results to you.**Notice: The code for the next step depends on the code for the previous step. Must reuse variables in the lastest other code directly, dont creat it again, it is very import for you. Use !pip install in a standalone block to install missing packages.Usually the libraries you need are already installed.Dont check if packages already imported.**""" # prompt reference: https://github.com/KillianLucas/open-interpreter/blob/v0.1.4/interpreter/system_message.txt
- # REUSE_CODE_INSTRUCTION = """ATTENTION: DONT include codes from previous tasks in your current code block, include new codes only, DONT repeat codes!"""
-
- def insert_system_message(self, context: list[Message], system_msg: str = None):
- system_msg = system_msg or self.DEFAULT_SYSTEM_MSG
- context.insert(0, SystemMessage(content=system_msg)) if context[0].role != "system" else None
- return context
-
- async def run(self, context: list[Message], plan: Plan = None) -> dict:
- """Run of a code writing action, used in data analysis or modeling
-
- Args:
- context (list[Message]): Action output history, source action denoted by Message.cause_by
- plan (Plan, optional): Overall plan. Defaults to None.
-
- Returns:
- dict: code result in the format of {"code": "print('hello world')", "language": "python"}
- """
- raise NotImplementedError
-
-
-class WriteCodeWithoutTools(BaseWriteAnalysisCode):
- """Ask LLM to generate codes purely by itself without local user-defined tools"""
-
- async def run(self, context: list[Message], plan: Plan = None, system_msg: str = None, **kwargs) -> dict:
- messages = self.insert_system_message(context, system_msg)
- rsp = await self.llm.aask_code(messages, **kwargs)
- return rsp
-
-
-class WriteCodeWithTools(BaseWriteAnalysisCode):
+class WriteCodeWithTools(Action):
"""Write code with help of local available tools. Choose tools first, then generate code to use the tools"""
- # selected tools to choose from, listed by their names. An empty list means selection from all tools.
- selected_tools: list[str] = []
-
- def _get_tools_by_type(self, tool_type: str) -> dict:
- """
- Retreive tools by tool type from registry, but filtered by pre-selected tool list
-
- Args:
- tool_type (str): Tool type to retrieve from the registry
-
- Returns:
- dict: A dict of tool name to Tool object, representing available tools under the type
- """
- candidate_tools = TOOL_REGISTRY.get_tools_by_type(tool_type)
- if self.selected_tools:
- candidate_tool_names = set(self.selected_tools) & candidate_tools.keys()
- candidate_tools = {tool_name: candidate_tools[tool_name] for tool_name in candidate_tool_names}
- return candidate_tools
-
- async def _recommend_tool(
- self,
- task: str,
- available_tools: dict,
- ) -> dict:
- """
- Recommend tools for the specified task.
-
- Args:
- task (str): the task to recommend tools for
- available_tools (dict): the available tools description
-
- Returns:
- dict: schemas of recommended tools for the specified task
- """
- prompt = TOOL_RECOMMENDATION_PROMPT.format(
- current_task=task,
- available_tools=available_tools,
- )
- tool_config = create_func_call_config(SELECT_FUNCTION_TOOLS)
- rsp = await self.llm.aask_code(prompt, **tool_config)
- recommend_tools = rsp["recommend_tools"]
- logger.info(f"Recommended tools: \n{recommend_tools}")
-
- # Parses and validates the recommended tools, for LLM might hallucinate and recommend non-existing tools
- valid_tools = validate_tool_names(recommend_tools, return_tool_object=True)
-
- tool_schemas = {tool.name: tool.schemas for tool in valid_tools}
-
- return tool_schemas
-
- async def _prepare_tools(self, plan: Plan) -> Tuple[dict, str]:
- """Prepare tool schemas and usage instructions according to current task
-
- Args:
- plan (Plan): The overall plan containing task information.
-
- Returns:
- Tuple[dict, str]: A tool schemas ({tool_name: tool_schema_dict}) and a usage prompt for the type of tools selected
- """
- # find tool type from task type through exact match, can extend to retrieval in the future
- tool_type = plan.current_task.task_type
-
- # prepare tool-type-specific instruction
- tool_type_usage_prompt = (
- TOOL_REGISTRY.get_tool_type(tool_type).usage_prompt if TOOL_REGISTRY.has_tool_type(tool_type) else ""
+ async def _debug_with_reflection(self, context: list[Message], working_memory: list[Message]):
+ reflection_prompt = REFLECTION_PROMPT.format(
+ debug_example=DEBUG_REFLECTION_EXAMPLE,
+ context=context,
+ previous_impl=working_memory,
)
- # prepare schemas of available tools
- tool_schemas = {}
- available_tools = self._get_tools_by_type(tool_type)
- if available_tools:
- available_tools = {tool_name: tool.schemas["description"] for tool_name, tool in available_tools.items()}
- tool_schemas = await self._recommend_tool(plan.current_task.instruction, available_tools)
+ rsp = await self._aask(reflection_prompt, system_msgs=[REFLECTION_SYSTEM_MSG])
+ reflection = json.loads(CodeParser.parse_code(block=None, text=rsp))
- return tool_schemas, tool_type_usage_prompt
+ return reflection["improved_impl"]
async def run(
self,
diff --cc metagpt/provider/base_llm.py
index 140ed3570,9850f4cf5..fa14496aa
--- a/metagpt/provider/base_llm.py
+++ b/metagpt/provider/base_llm.py
@@@ -67,9 -81,31 +81,31 @@@ class BaseLLM(ABC)
def _default_system_msg(self):
return self._system_msg(self.system_prompt)
+ def _update_costs(self, usage: Union[dict, BaseModel], model: str = None, local_calc_usage: bool = True):
+ """update each request's token cost
+ Args:
+ model (str): model name or in some scenarios called endpoint
+ local_calc_usage (bool): some models don't calculate usage, it will overwrite LLMConfig.calc_usage
+ """
+ calc_usage = self.config.calc_usage and local_calc_usage
+ model = model or self.model
+ usage = usage.model_dump() if isinstance(usage, BaseModel) else usage
+ if calc_usage and self.cost_manager:
+ try:
+ prompt_tokens = int(usage.get("prompt_tokens", 0))
+ completion_tokens = int(usage.get("completion_tokens", 0))
+ self.cost_manager.update_cost(prompt_tokens, completion_tokens, model)
+ except Exception as e:
+ logger.error(f"{self.__class__.__name__} updates costs failed! exp: {e}")
+
+ def get_costs(self) -> Costs:
+ if not self.cost_manager:
+ return Costs(0, 0, 0, 0)
+ return self.cost_manager.get_costs()
+
async def aask(
self,
- msg: str,
+ msg: Union[str, list[dict[str, str]]],
system_msgs: Optional[list[str]] = None,
format_msgs: Optional[list[dict[str, str]]] = None,
images: Optional[Union[str, list[str]]] = None,
@@@ -105,9 -138,14 +141,13 @@@
context.append(self._assistant_msg(rsp_text))
return self._extract_assistant_rsp(context)
- async def aask_code(self, messages: Union[str, Message, list[dict]], timeout=3) -> dict:
- """FIXME: No code segment filtering has been done here, and all results are actually displayed"""
+ async def aask_code(self, messages: Union[str, Message, list[dict]], timeout=3, **kwargs) -> dict:
raise NotImplementedError
+ @abstractmethod
+ async def _achat_completion(self, messages: list[dict], timeout=3):
+ """_achat_completion implemented by inherited class"""
+
@abstractmethod
async def acompletion(self, messages: list[dict], timeout=3):
"""Asynchronous version of completion
diff --cc metagpt/provider/openai_api.py
index 3616debc4,82206f738..2126505c7
--- a/metagpt/provider/openai_api.py
+++ b/metagpt/provider/openai_api.py
@@@ -28,8 -29,9 +29,13 @@@ from metagpt.logs import log_llm_stream
from metagpt.provider.base_llm import BaseLLM
from metagpt.provider.constant import GENERAL_FUNCTION_SCHEMA
from metagpt.provider.llm_provider_registry import register_provider
- from metagpt.utils.common import CodeParser, decode_image, process_message
- from metagpt.utils.cost_manager import CostManager, Costs
-from metagpt.schema import Message
-from metagpt.utils.common import CodeParser, decode_image, log_and_reraise
++from metagpt.utils.common import (
++ CodeParser,
++ decode_image,
++ log_and_reraise,
++ process_message,
++)
+ from metagpt.utils.cost_manager import CostManager
from metagpt.utils.exceptions import handle_exception
from metagpt.utils.token_counter import (
count_message_tokens,
diff --cc metagpt/roles/di/data_interpreter.py
index a083f7f7d,b3a2e789f..0a149e901
--- a/metagpt/roles/di/data_interpreter.py
+++ b/metagpt/roles/di/data_interpreter.py
@@@ -1,59 -1,42 +1,59 @@@
from __future__ import annotations
-from pydantic import Field
+import json
+from typing import Literal, Union
+
+from pydantic import Field, model_validator
- from metagpt.actions.mi.ask_review import ReviewConst
- from metagpt.actions.mi.execute_nb_code import ExecuteNbCode
- from metagpt.actions.mi.write_analysis_code import CheckData, WriteCodeWithTools
+ from metagpt.actions.di.ask_review import ReviewConst
+ from metagpt.actions.di.execute_nb_code import ExecuteNbCode
-from metagpt.actions.di.write_analysis_code import (
- WriteCodeWithoutTools,
- WriteCodeWithTools,
-)
++from metagpt.actions.di.write_analysis_code import CheckData, WriteCodeWithTools
from metagpt.logs import logger
+from metagpt.prompts.mi.write_analysis_code import DATA_INFO
from metagpt.roles import Role
from metagpt.schema import Message, Task, TaskResult
+from metagpt.strategy.task_type import TaskType
+from metagpt.tools.tool_recommend import BM25ToolRecommender, ToolRecommender
+from metagpt.utils.common import CodeParser
+
+REACT_THINK_PROMPT = """
+# User Requirement
+{user_requirement}
+# Context
+{context}
+
+Output a json following the format:
+```json
+{{
+ "thoughts": str = "Thoughts on current situation, reflect on how you should proceed to fulfill the user requirement",
+ "state": bool = "Decide whether you need to take more actions to complete the user requirement. Return true if you think so. Return false if you think the requirement has been completely fulfilled."
+}}
+```
+"""
- class Interpreter(Role):
- name: str = "Ivy"
- profile: str = "Interpreter"
+ class DataInterpreter(Role):
+ name: str = "David"
+ profile: str = "DataInterpreter"
auto_run: bool = True
- use_tools: bool = False
+ use_plan: bool = True
+ use_reflection: bool = False
execute_code: ExecuteNbCode = Field(default_factory=ExecuteNbCode, exclude=True)
- tools: list[str] = []
-
- def __init__(
- self,
- auto_run=True,
- use_tools=False,
- tools=[],
- **kwargs,
- ):
- super().__init__(auto_run=auto_run, use_tools=use_tools, tools=tools, **kwargs)
- self._set_react_mode(react_mode="plan_and_act", auto_run=auto_run, use_tools=use_tools)
- if use_tools and tools:
- from metagpt.tools.tool_registry import (
- validate_tool_names, # import upon use
- )
-
- self.tools = validate_tool_names(tools)
- logger.info(f"will only use {self.tools} as tools")
+ tools: Union[str, list[str]] = []
+ tool_recommender: ToolRecommender = None
+ react_mode: Literal["plan_and_act", "react"] = "plan_and_act"
+ max_react_loop: int = 10 # used for react mode
+
+ @model_validator(mode="after")
+ def set_plan_and_tool(self) -> "Interpreter":
+ self._set_react_mode(react_mode=self.react_mode, max_react_loop=self.max_react_loop, auto_run=self.auto_run)
+ self.use_plan = (
+ self.react_mode == "plan_and_act"
+ ) # create a flag for convenience, overwrite any passed-in value
+ if self.tools:
+ self.tool_recommender = BM25ToolRecommender(tools=self.tools)
+ self.set_actions([WriteCodeWithTools])
+ return self
@property
def working_memory(self):
diff --cc metagpt/roles/role.py
index e0c33f899,893c5cafd..832a000b1
--- a/metagpt/roles/role.py
+++ b/metagpt/roles/role.py
@@@ -281,9 -281,9 +281,9 @@@ class Role(SerializationMixin, ContextM
i = action
self._init_action(i)
self.actions.append(i)
- self.states.append(f"{len(self.actions)}. {action}")
+ self.states.append(f"{len(self.actions) - 1}. {action}")
- def _set_react_mode(self, react_mode: str, max_react_loop: int = 1, auto_run: bool = True, use_tools: bool = False):
+ def _set_react_mode(self, react_mode: str, max_react_loop: int = 1, auto_run: bool = True):
"""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.
diff --cc metagpt/utils/common.py
index 4f86deab1,b6296c4fa..e9cef69a4
--- a/metagpt/utils/common.py
+++ b/metagpt/utils/common.py
@@@ -668,24 -812,12 +802,35 @@@ def decode_image(img_url_or_b64: str) -
return img
+def process_message(messages: Union[str, Message, list[dict], list[Message], list[str]]) -> list[dict]:
+ """convert messages to list[dict]."""
+ from metagpt.schema import Message
+
+ # 全部转成list
+ if not isinstance(messages, list):
+ messages = [messages]
+
+ # 转成list[dict]
+ processed_messages = []
+ for msg in messages:
+ if isinstance(msg, str):
+ processed_messages.append({"role": "user", "content": msg})
+ elif isinstance(msg, dict):
+ assert set(msg.keys()) == set(["role", "content"])
+ processed_messages.append(msg)
+ elif isinstance(msg, Message):
+ processed_messages.append(msg.to_dict())
+ else:
+ raise ValueError(f"Only support message type are: str, Message, dict, but got {type(messages).__name__}!")
+ return processed_messages
++
++
+ def log_and_reraise(retry_state: RetryCallState):
+ logger.error(f"Retry attempts exhausted. Last exception: {retry_state.outcome.exception()}")
+ logger.warning(
+ """
+ Recommend going to https://deepwisdom.feishu.cn/wiki/MsGnwQBjiif9c3koSJNcYaoSnu4#part-XdatdVlhEojeAfxaaEZcMV3ZniQ
+ See FAQ 5.8
+ """
+ )
+ raise retry_state.outcome.exception()
diff --cc tests/metagpt/actions/di/test_execute_nb_code.py
index 2ecfbd2a2,b491dd212..74757555f
--- a/tests/metagpt/actions/di/test_execute_nb_code.py
+++ b/tests/metagpt/actions/di/test_execute_nb_code.py
@@@ -1,6 -1,6 +1,6 @@@
import pytest
- from metagpt.actions.mi.execute_nb_code import ExecuteNbCode
-from metagpt.actions.di.execute_nb_code import ExecuteNbCode, truncate
++from metagpt.actions.di.execute_nb_code import ExecuteNbCode
@pytest.mark.asyncio