Skip to content

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

feat: merge geekan/dev

莘权 马4ffac9c39186
diff --cc metagpt/actions/action.py
index 369a33373,7bb26ea91..147975f18
--- a/metagpt/actions/action.py
+++ b/metagpt/actions/action.py
@@@ -18,10 -14,8 +18,9 @@@ from tenacity import retry, stop_after_
from metagpt.actions.action_output import ActionOutput
from metagpt.llm import LLM
from metagpt.logs import logger
+from metagpt.provider.base_gpt_api import BaseGPTAPI
from metagpt.provider.postprecess.llm_output_postprecess import llm_output_postprecess
- from metagpt.utils.common import OutputParser
- from metagpt.utils.utils import general_after_log
+ from metagpt.utils.common import OutputParser, general_after_log
class Action(ABC):
diff --cc metagpt/config.py
index b31a166b8,629a5b797..fae2622db
--- a/metagpt/config.py
+++ b/metagpt/config.py
@@@ -48,14 -44,14 +48,15 @@@ class Config(metaclass=Singleton)
key_yaml_file = METAGPT_ROOT / "config/key.yaml"
default_yaml_file = METAGPT_ROOT / "config/config.yaml"
- def __init__(self, yaml_file=default_yaml_file):
+ def __init__(self, yaml_file=default_yaml_file, cost_data=""):
self._init_with_config_files_and_env(yaml_file)
- logger.debug("Config loading done.")
+ # The agent needs to be billed per user, so billing information cannot be destroyed when the session ends.
+ self.cost_manager = CostManager(**json.loads(cost_data)) if cost_data else CostManager()
+ logger.info("Config loading done.")
self._update()
+ logger.info(f"OpenAI API Model: {self.openai_api_model}")
def _update(self):
- # logger.info("Config loading done.")
self.global_proxy = self._get("GLOBAL_PROXY")
self.openai_api_key = self._get("OPENAI_API_KEY")
self.anthropic_api_key = self._get("Anthropic_API_KEY")
diff --cc metagpt/provider/openai_api.py
index 493f88153,86054881e..5e9c9fc4d
--- a/metagpt/provider/openai_api.py
+++ b/metagpt/provider/openai_api.py
@@@ -259,17 -325,16 +259,17 @@@ class OpenAIGPTAPI(BaseGPTAPI, RateLimi
try:
prompt_tokens = count_message_tokens(messages, self.model)
completion_tokens = count_string_tokens(rsp, self.model)
- usage["prompt_tokens"] = prompt_tokens
- usage["completion_tokens"] = completion_tokens
+ usage = CompletionUsage(
+ prompt_tokens=prompt_tokens,
+ completion_tokens=completion_tokens,
+ total_tokens=prompt_tokens + completion_tokens,
+ )
return usage
except Exception as e:
- logger.error("usage calculation failed!", e)
+ logger.error(f"{self.model} usage calculation failed!", e)
- return {}
- else:
- return usage
+ return CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0)
- async def acompletion_batch(self, batch: list[list[dict]]) -> list[dict]:
+ async def acompletion_batch(self, batch: list[list[dict]], timeout=3) -> list[dict]:
"""Return full JSON"""
split_batches = self.split_batches(batch)
all_results = []
diff --cc metagpt/repo_parser.py
index 65c2959e4,9a1218ef1..975ead8cd
--- a/metagpt/repo_parser.py
+++ b/metagpt/repo_parser.py
@@@ -51,12 -51,8 +51,13 @@@ class RepoParser(BaseModel)
def generate_symbols(self):
files_classes = []
directory = self.base_directory
- for path in directory.rglob("*.py"):
- tree = self._parse_file(path)
++
+ matching_files = []
+ extensions = ["*.py", "*.js"]
+ for ext in extensions:
+ matching_files += directory.rglob(ext)
+ for path in matching_files:
+ tree = self.parse_file(path)
file_info = self.extract_class_and_function_info(tree, path)
files_classes.append(file_info)
diff --cc metagpt/schema.py
index 9916bffff,b24f114b0..b17565979
--- a/metagpt/schema.py
+++ b/metagpt/schema.py
@@@ -160,20 -161,11 +161,21 @@@ class Message(BaseModel)
return self.json(exclude_none=True)
@staticmethod
+ @handle_exception(exception_type=JSONDecodeError, default_return=None)
def load(val):
"""Convert the json string to object."""
- d = json.loads(val)
- return Message(**d)
+ try:
+ m = json.loads(val)
+ id = m.get("id")
+ if "id" in m:
+ del m["id"]
+ msg = Message(**m)
+ if id:
+ msg.id = id
+ return msg
+ except JSONDecodeError as err:
+ logger.error(f"parse json failed: {val}, error:{err}")
+ return None
class UserMessage(Message):
diff --cc metagpt/utils/common.py
index 575c77b5e,bf435b74f..8fa729556
--- a/metagpt/utils/common.py
+++ b/metagpt/utils/common.py
@@@ -17,11 -17,16 +17,17 @@@ import inspec
import os
import platform
import re
+ import typing
from typing import List, Tuple, Union
+ import aiofiles
+ import loguru
+ from tenacity import RetryCallState, _utils
+
+from metagpt.config import CONFIG
from metagpt.const import MESSAGE_ROUTE_TO_ALL
from metagpt.logs import logger
+ from metagpt.utils.exceptions import handle_exception
def check_cmd_exists(command) -> int:
@@@ -366,34 -370,42 +371,75 @@@ def is_subscribed(message: "Message", t
return False
+def any_to_name(val):
+ """
+ Convert a value to its name by extracting the last part of the dotted path.
+
+ :param val: The value to convert.
+
+ :return: The name of the value.
+ """
+ return any_to_str(val).split(".")[-1]
+
+
+def format_value(value):
+ """Fill parameters inside `value` with `options`."""
+ if not isinstance(value, str):
+ return value
+ if "{" not in value:
+ return value
+
+ merged_opts = CONFIG.options or {}
+ try:
+ return value.format(**merged_opts)
+ except KeyError as e:
+ logger.warning(f"Parameter is missing:{e}")
+
+ for k, v in merged_opts.items():
+ value = value.replace("{" + f"{k}" + "}", str(v))
+ return value
+
+
+def concat_namespace(*args) -> str:
+ return ":".join(str(value) for value in args)
++
++
+ def general_after_log(i: "loguru.Logger", sec_format: str = "%0.3f") -> typing.Callable[["RetryCallState"], None]:
+ """
+ Generates a logging function to be used after a call is retried.
+
+ This generated function logs an error message with the outcome of the retried function call. It includes
+ the name of the function, the time taken for the call in seconds (formatted according to `sec_format`),
+ the number of attempts made, and the exception raised, if any.
+
+ :param i: A Logger instance from the loguru library used to log the error message.
+ :param sec_format: A string format specifier for how to format the number of seconds since the start of the call.
+ Defaults to three decimal places.
+ :return: A callable that accepts a RetryCallState object and returns None. This callable logs the details
+ of the retried call.
+ """
+
+ def log_it(retry_state: "RetryCallState") -> None:
+ # If the function name is not known, default to "<unknown>"
+ if retry_state.fn is None:
+ fn_name = "<unknown>"
+ else:
+ # Retrieve the callable's name using a utility function
+ fn_name = _utils.get_callback_name(retry_state.fn)
+
+ # Log an error message with the function name, time since start, attempt number, and the exception
+ i.error(
+ f"Finished call to '{fn_name}' after {sec_format % retry_state.seconds_since_start}(s), "
+ f"this was the {_utils.to_ordinal(retry_state.attempt_number)} time calling it. "
+ f"exp: {retry_state.outcome.exception()}"
+ )
+
+ return log_it
+
+
+ @handle_exception
+ async def aread(file_path: str) -> str:
+ """Read file asynchronously."""
+ async with aiofiles.open(str(file_path), mode="r") as reader:
+ content = await reader.read()
+ return content
diff --cc tests/metagpt/test_schema.py
index 40b18e0f4,79421fab2..a6c84d32a
--- a/tests/metagpt/test_schema.py
+++ b/tests/metagpt/test_schema.py
@@@ -13,9 -13,10 +13,9 @@@ import pytes
from metagpt.actions import Action
from metagpt.schema import AIMessage, Message, SystemMessage, UserMessage
- from metagpt.utils.common import get_class_name
+ from metagpt.utils.common import any_to_str
def test_messages():
test_content = "test_message"
msgs = [