🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming
feat: merge geekan:main
莘权 马9a1909bb95c3
diff --cc .gitignoreindex 89e00e59a,c12506b0e..93e24ba48--- a/.gitignore+++ b/.gitignore@@@ -160,14 -156,6 +156,12 @@@ examples/nb.chroma*~$*workspace/*- *.mmdtmp- output.wavmetagpt/roles/idea_agent.py.aider*+*.bak++# output folder+output+tmp.png+diff --cc examples/search_kb.pyindex 85d99854e,5d61bbe02..0afd7ad15--- a/examples/search_kb.py+++ b/examples/search_kb.py@@@ -2,11 -2,10 +2,10 @@@# -*- coding: utf-8 -*-"""@File : search_kb.py- @Modified By: mashenquan, 2023-8-9, fix-bug: cannot find metagpt module.++@Modified By: mashenquan, 2023-12-22. Delete useless codes."""import asyncio--from metagpt.actions import Actionfrom metagpt.const import DATA_PATHfrom metagpt.document_store import FaissStorefrom metagpt.logs import logger@@@ -30,10 -29,10 +29,9 @@@ from metagpt.schema import Messagasync def search():store = FaissStore(DATA_PATH / "example.json")role = Sales(profile="Sales", store=store)-- role._watch({Action})queries = [- Message("Which facial cleanser is good for oily skin?", cause_by=Action),- Message("Is L'Oreal good to use?", cause_by=Action),- Message(content="Which facial cleanser is good for oily skin?", cause_by=Action),- Message(content="Is L'Oreal good to use?", cause_by=Action),++ Message(content="Which facial cleanser is good for oily skin?"),++ Message(content="Is L'Oreal good to use?"),]for query in queries:logger.info(f"User: {query}")diff --cc examples/search_with_specific_engine.pyindex 97db1624a,923f538ed..adb5665cb--- a/examples/search_with_specific_engine.py+++ b/examples/search_with_specific_engine.py@@@ -1,8 -1,3 +1,7 @@@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""- @Modified By: mashenquan, 2023-8-9, fix-bug: cannot find metagpt module.+"""import asynciofrom metagpt.roles import Searcherdiff --cc metagpt/actions/skill_action.pyindex f629cfcbf,000000000..c95a83cbbmode 100644,000000..100644--- a/metagpt/actions/skill_action.py+++ b/metagpt/actions/skill_action.py@@@ -1,109 -1,0 +1,106 @@@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""+@Time : 2023/8/28+@Author : mashenquan+@File : skill_action.py+@Desc : Call learned skill+"""+from __future__ import annotations++import ast+import importlib+import traceback+from copy import deepcopy++from typing import Dict, Optional++from metagpt.actions import Action, ActionOutput+from metagpt.learn.skill_loader import Skill+from metagpt.logs import logger+++class ArgumentsParingAction(Action):- def __init__(self, last_talk: str, skill: Skill, context=None, llm=None, **kwargs):- super(ArgumentsParingAction, self).__init__(name="", context=context, llm=llm)- self.skill = skill- self.ask = last_talk- self.rsp = None- self.args = None++ skill: Skill++ ask: str++ rsp: Optional[ActionOutput]++ args: Optional[Dict]++ @property+ def prompt(self):+ prompt = f"{self.skill.name} function parameters description:\n"+ for k, v in self.skill.arguments.items():+ prompt += f"parameter `{k}`: {v}\n"+ prompt += "\n"+ prompt += "Examples:\n"+ for e in self.skill.examples:+ prompt += f"If want you to do `{e.ask}`, return `{e.answer}` brief and clear.\n"+ prompt += f"\nNow I want you to do `{self.ask}`, return in examples format above, brief and clear."+ return prompt++ async def run(self, *args, **kwargs) -> ActionOutput:+ prompt = self.prompt+ rsp = await self.llm.aask(msg=prompt, system_msgs=[])+ logger.debug(f"SKILL:{prompt}\n, RESULT:{rsp}")+ self.args = ArgumentsParingAction.parse_arguments(skill_name=self.skill.name, txt=rsp)+ self.rsp = ActionOutput(content=rsp)+ return self.rsp++ @staticmethod+ def parse_arguments(skill_name, txt) -> dict:+ prefix = skill_name + "("+ if prefix not in txt:+ logger.error(f"{skill_name} not in {txt}")+ return None+ if ")" not in txt:+ logger.error(f"')' not in {txt}")+ return None+ begin_ix = txt.find(prefix)+ end_ix = txt.rfind(")")+ args_txt = txt[begin_ix + len(prefix) : end_ix]+ logger.info(args_txt)+ fake_expression = f"dict({args_txt})"+ parsed_expression = ast.parse(fake_expression, mode="eval")+ args = {}+ for keyword in parsed_expression.body.keywords:+ key = keyword.arg+ value = ast.literal_eval(keyword.value)+ args[key] = value+ return args+++class SkillAction(Action):- def __init__(self, skill: Skill, args: dict, context=None, llm=None, **kwargs):- super(SkillAction, self).__init__(name="", context=context, llm=llm)- self._skill = skill- self._args = args- self.rsp = None++ skill: Skill++ args: Dict++ rsp: str = ""++ async def run(self, *args, **kwargs) -> str | ActionOutput | None:+ """Run action"""+ options = deepcopy(kwargs)- if self._args:- for k in self._args.keys():++ if self.args:++ for k in self.args.keys():+ if k in options:+ options.pop(k)+ try:- self.rsp = await self.find_and_call_function(self._skill.name, args=self._args, **options)++ self.rsp = await self.find_and_call_function(self.skill.name, args=self.args, **options)+ except Exception as e:+ logger.exception(f"{e}, traceback:{traceback.format_exc()}")+ self.rsp = f"Error: {e}"- return ActionOutput(content=self.rsp, instruct_content=self._skill.json())++ return ActionOutput(content=self.rsp, instruct_content=self.skill.json())++ @staticmethod+ async def find_and_call_function(function_name, args, **kwargs):+ try:+ module = importlib.import_module("metagpt.learn")+ function = getattr(module, function_name)+ # 调用函数并返回结果+ result = await function(**args, **kwargs)+ return result+ except (ModuleNotFoundError, AttributeError):+ logger.error(f"{function_name} not found")+ return None+++if __name__ == "__main__":+ ArgumentsParingAction.parse_arguments(+ skill_name="text_to_image", txt='`text_to_image(text="Draw an apple", size_type="512x512")`'+ )diff --cc metagpt/config.pyindex fae2622db,5176a7677..3c773d780--- a/metagpt/config.py+++ b/metagpt/config.py@@@ -6,20 -6,19 +6,23 @@@ Provide configuration, singleto1. According to Section 2.2.3.11 of RFC 135, add git repository support.2. Add the parameter `src_workspace` for the old version project path."""+import datetime+import jsonimport os+ import warningsfrom copy import deepcopy+ from enum import Enumfrom pathlib import Pathfrom typing import Any+from uuid import uuid4import yamlfrom metagpt.const import DEFAULT_WORKSPACE_ROOT, METAGPT_ROOT, OPTIONSfrom metagpt.logs import loggerfrom metagpt.tools import SearchEngineType, WebBrowserEngineType+ from metagpt.utils.common import require_python_version+from metagpt.utils.cost_manager import CostManagerfrom metagpt.utils.singleton import Singleton@@@ -35,6 -34,16 +38,18 @@@ class NotConfiguredException(Exception)super().__init__(self.message)+ class LLMProviderEnum(Enum):+ OPENAI = "openai"+ ANTHROPIC = "anthropic"+ SPARK = "spark"+ ZHIPUAI = "zhipuai"+ FIREWORKS = "fireworks"+ OPEN_LLM = "open_llm"+ GEMINI = "gemini"++ METAGPT = "metagpt"++ AZURE_OPENAI = "azure_openai"++class Config(metaclass=Singleton):"""Regular usage method:@@@ -48,13 -57,41 +63,43 @@@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=""):+ global_options = OPTIONS.get()+ # cli paras+ self.project_path = ""+ self.project_name = ""+ self.inc = False+ self.reqa_file = ""+ self.max_auto_summarize_code = 0+self._init_with_config_files_and_env(yaml_file)+ # 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}")+ global_options.update(OPTIONS.get())+ logger.debug("Config loading done.")++ def get_default_llm_provider_enum(self) -> LLMProviderEnum:+ for k, v in [+ (self.openai_api_key, LLMProviderEnum.OPENAI),+ (self.anthropic_api_key, LLMProviderEnum.ANTHROPIC),+ (self.zhipuai_api_key, LLMProviderEnum.ZHIPUAI),+ (self.fireworks_api_key, LLMProviderEnum.FIREWORKS),+ (self.open_llm_api_base, LLMProviderEnum.OPEN_LLM),+ (self.gemini_api_key, LLMProviderEnum.GEMINI), # reuse logic. but not a key+ ]:+ if self._is_valid_llm_key(k):+ # logger.debug(f"Use LLMProvider: {v.value}")+ if v == LLMProviderEnum.GEMINI and not require_python_version(req_version=(3, 10)):+ warnings.warn("Use Gemini requires Python >= 3.10")+ if self.openai_api_key and self.openai_api_model:+ logger.info(f"OpenAI API Model: {self.openai_api_model}")+ return v+ raise NotConfiguredException("You should config a LLM configuration first")++ @staticmethod+ def _is_valid_llm_key(k: str) -> bool:+ return k and k != "YOUR_API_KEY"def _update(self):self.global_proxy = self._get("GLOBAL_PROXY")@@@ -124,18 -148,24 +155,31 @@@self.mermaid_engine = self._get("MERMAID_ENGINE", "nodejs")self.pyppeteer_executable_path = self._get("PYPPETEER_EXECUTABLE_PATH", "")- self.prompt_format = self._get("PROMPT_FORMAT", "json")+ workspace_uid = (+ self._get("WORKSPACE_UID") or f"{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid4().hex[-8:]}"+ )self.repair_llm_output = self._get("REPAIR_LLM_OUTPUT", False)- self.prompt_schema = self._get("PROMPT_FORMAT", "json")++ self.prompt_format = self._get("PROMPT_FORMAT", "json")self.workspace_path = Path(self._get("WORKSPACE_PATH", DEFAULT_WORKSPACE_ROOT))+ val = self._get("WORKSPACE_PATH_WITH_UID")+ if val and val.lower() == "true": # for agent+ self.workspace_path = self.workspace_path / workspace_uidself._ensure_workspace_exists()+ self.max_auto_summarize_code = self.max_auto_summarize_code or self._get("MAX_AUTO_SUMMARIZE_CODE", 1)+ def update_via_cli(self, project_path, project_name, inc, reqa_file, max_auto_summarize_code):+ """update config via cli"""++ # Use in the PrepareDocuments action according to Section 2.2.3.5.1 of RFC 135.+ if project_path:+ inc = True+ project_name = project_name or Path(project_path).name+ self.project_path = project_path+ self.project_name = project_name+ self.inc = inc+ self.reqa_file = reqa_file+ self.max_auto_summarize_code = max_auto_summarize_code+def _ensure_workspace_exists(self):self.workspace_path.mkdir(parents=True, exist_ok=True)logger.debug(f"WORKSPACE_PATH set to {self.workspace_path}")@@@ -158,12 -188,11 +202,12 @@@@staticmethoddef _get(*args, **kwargs):- m = OPTIONS.get()- return m.get(*args, **kwargs)+ i = OPTIONS.get()+ return i.get(*args, **kwargs)def get(self, key, *args, **kwargs):- """Search for a value in config/key.yaml, config/config.yaml, and env; raise an error if not found"""+ """Retrieve values from config/key.yaml, config/config.yaml, and environment variables.+ Throw an error if not found."""value = self._get(key, *args, **kwargs)if value is None:raise ValueError(f"Key '{key}' not found in environment variables or in the YAML file")diff --cc metagpt/const.pyindex 53f797001,3b4f2ae4b..76ddc077c--- a/metagpt/const.py+++ b/metagpt/const.py@@@ -97,23 -100,5 +100,23 @@@ TEST_CODES_FILE_REPO = "testsTEST_OUTPUTS_FILE_REPO = "test_outputs"CODE_SUMMARIES_FILE_REPO = "docs/code_summaries"CODE_SUMMARIES_PDF_FILE_REPO = "resources/code_summaries"+RESOURCES_FILE_REPO = "resources"+SD_OUTPUT_FILE_REPO = "resources/SD_Output"+GRAPH_REPO_FILE_REPO = "docs/graph_repo"+CLASS_VIEW_FILE_REPO = "docs/class_views"YAPI_URL = "http://yapi.deepwisdomai.com/"++DEFAULT_LANGUAGE = "English"+DEFAULT_MAX_TOKENS = 1500+COMMAND_TOKENS = 500+BRAIN_MEMORY = "BRAIN_MEMORY"+SKILL_PATH = "SKILL_PATH"+SERPER_API_KEY = "SERPER_API_KEY"-++DEFAULT_TOKEN_SIZE = 500++# format+BASE64_FORMAT = "base64"++# REDIS+REDIS_KEY = "REDIS_KEY"diff --cc metagpt/environment.pyindex 5c3a6f97f,58569ec08..e0b5010d9--- a/metagpt/environment.py+++ b/metagpt/environment.py@@@ -16,10 -17,10 +17,11 @@@ from typing import Iterable, Sefrom pydantic import BaseModel, Field++from metagpt.config import CONFIGfrom metagpt.logs import logger- from metagpt.roles import Role+ from metagpt.roles.role import Role, role_subclass_registryfrom metagpt.schema import Message- from metagpt.utils.common import is_subscribed+ from metagpt.utils.common import is_subscribed, read_json_file, write_json_fileclass Environment(BaseModel):@@@ -111,3 -166,3 +167,8 @@@def set_subscription(self, obj, tags):"""Set the labels for message to be consumed by the object"""self.members[obj] = tags++++ @staticmethod++ def archive(auto_archive=True):++ if auto_archive and CONFIG.git_repo:++ CONFIG.git_repo.archive()diff --cc metagpt/memory/longterm_memory.pyindex 5e68e99e5,710074f81..1497b8910--- a/metagpt/memory/longterm_memory.py+++ b/metagpt/memory/longterm_memory.py@@@ -2,9 -2,12 +2,13 @@@# -*- coding: utf-8 -*-"""@Desc : the implement of Long-term memory+@Modified By: mashenquan, 2023/8/20. Remove global configuration `CONFIG`, enable configuration support for business isolation."""+ from typing import Optional++ from pydantic import Field+from metagpt.logs import loggerfrom metagpt.memory import Memoryfrom metagpt.memory.memory_storage import MemoryStoragediff --cc metagpt/provider/azure_openai_api.pyindex 000000000,000000000..ec5eed3f6new file mode 100644--- /dev/null+++ b/metagpt/provider/azure_openai_api.py@@@ -1,0 -1,0 +1,77 @@@++# -*- coding: utf-8 -*-++"""++@Time : 2023/5/5 23:08++@Author : alexanderwu++@File : openai.py++@Modified By: mashenquan, 2023/8/20. Remove global configuration `CONFIG`, enable configuration support for business isolation;++ Change cost control from global to company level.++@Modified By: mashenquan, 2023/11/21. Fix bug: ReadTimeout.++@Modified By: mashenquan, 2023/12/1. Fix bug: Unclosed connection caused by openai 0.x.++"""++++++from openai import AsyncAzureOpenAI, AzureOpenAI++from openai._base_client import AsyncHttpxClientWrapper, SyncHttpxClientWrapper++++from metagpt.config import CONFIG, Config, LLMProviderEnum++from metagpt.provider.llm_provider_registry import register_provider++from metagpt.provider.openai_api import OpenAIGPTAPI, RateLimiter++++++@register_provider(LLMProviderEnum.AZURE_OPENAI)++class AzureOpenAIGPTAPI(OpenAIGPTAPI):++ """++ Check https://platform.openai.com/examples for examples++ """++++ def __init__(self):++ self.config: Config = CONFIG++ self.__init_openai()++ self.auto_max_tokens = False++ # https://learn.microsoft.com/zh-cn/azure/ai-services/openai/how-to/migration?tabs=python-new%2Cdalle-fix++ self._client = AsyncAzureOpenAI(++ api_key=CONFIG.openai_api_key,++ api_version=CONFIG.openai_api_version,++ azure_endpoint=CONFIG.openai_api_base,++ )++ RateLimiter.__init__(self, rpm=self.rpm)++++ def _make_client(self):++ kwargs, async_kwargs = self._make_client_kwargs()++ self.client = AzureOpenAI(**kwargs)++ self.async_client = AsyncAzureOpenAI(**async_kwargs)++++ def _make_client_kwargs(self) -> (dict, dict):++ kwargs = dict(++ api_key=self.config.openai_api_key,++ api_version=self.config.openai_api_version,++ azure_endpoint=self.config.openai_base_url,++ )++ async_kwargs = kwargs.copy()++++ # to use proxy, openai v1 needs http_client++ proxy_params = self._get_proxy_params()++ if proxy_params:++ kwargs["http_client"] = SyncHttpxClientWrapper(**proxy_params)++ async_kwargs["http_client"] = AsyncHttpxClientWrapper(**proxy_params)++++ return kwargs, async_kwargs++++ def _cons_kwargs(self, messages: list[dict], timeout=3, **configs) -> dict:++ kwargs = {++ "messages": messages,++ "max_tokens": self.get_max_tokens(messages),++ "n": 1,++ "stop": None,++ "temperature": 0.3,++ "model": CONFIG.deployment_id,++ }++ if configs:++ kwargs.update(configs)++ try:++ default_timeout = int(CONFIG.TIMEOUT) if CONFIG.TIMEOUT else 0++ except ValueError:++ default_timeout = 0++ kwargs["timeout"] = max(default_timeout, timeout)++++ return kwargsdiff --cc metagpt/provider/fireworks_api.pyindex 6625cda97,a76151666..bfe85f490--- a/metagpt/provider/fireworks_api.py+++ b/metagpt/provider/fireworks_api.py@@@ -4,18 -4,19 +4,18 @@@import openai- from metagpt.config import CONFIG+ from metagpt.config import CONFIG, LLMProviderEnum+ from metagpt.provider.llm_provider_registry import register_provider-from metagpt.provider.openai_api import CostManager, OpenAIGPTAPI, RateLimiter+from metagpt.provider.openai_api import OpenAIGPTAPI, RateLimiter- from metagpt.utils.cost_manager import CostManager+ @register_provider(LLMProviderEnum.FIREWORKS)class FireWorksGPTAPI(OpenAIGPTAPI):def __init__(self):self.__init_fireworks(CONFIG)self.llm = openaiself.model = CONFIG.fireworks_api_modelself.auto_max_tokens = False-- self._cost_manager = CostManager()RateLimiter.__init__(self, rpm=self.rpm)def __init_fireworks(self, config: "Config"):diff --cc metagpt/provider/google_gemini_api.pyindex 000000000,682f7b507..eb91cc32bmode 000000,100644..100644--- a/metagpt/provider/google_gemini_api.py+++ b/metagpt/provider/google_gemini_api.py@@@ -1,0 -1,142 +1,141 @@@+ #!/usr/bin/env python+ # -*- coding: utf-8 -*-+ # @Desc : Google Gemini LLM from https://ai.google.dev/tutorials/python_quickstart++ import google.generativeai as genai+ from google.ai import generativelanguage as glm+ from google.generativeai.generative_models import GenerativeModel+ from google.generativeai.types import content_types+ from google.generativeai.types.generation_types import (+ AsyncGenerateContentResponse,+ GenerateContentResponse,+ GenerationConfig,+ )+ from tenacity import (+ after_log,+ retry,+ retry_if_exception_type,+ stop_after_attempt,+ wait_random_exponential,+ )++ from metagpt.config import CONFIG, LLMProviderEnum+ from metagpt.logs import logger+ from metagpt.provider.base_gpt_api import BaseGPTAPI+ from metagpt.provider.llm_provider_registry import register_provider-from metagpt.provider.openai_api import CostManager, log_and_reraise++from metagpt.provider.openai_api import log_and_reraise+++ class GeminiGenerativeModel(GenerativeModel):+ """+ Due to `https://github.com/google/generative-ai-python/pull/123`, inherit a new class.+ Will use default GenerativeModel if it fixed.+ """++ def count_tokens(self, contents: content_types.ContentsType) -> glm.CountTokensResponse:+ contents = content_types.to_contents(contents)+ return self._client.count_tokens(model=self.model_name, contents=contents)++ async def count_tokens_async(self, contents: content_types.ContentsType) -> glm.CountTokensResponse:+ contents = content_types.to_contents(contents)+ return await self._async_client.count_tokens(model=self.model_name, contents=contents)+++ @register_provider(LLMProviderEnum.GEMINI)+ class GeminiGPTAPI(BaseGPTAPI):+ """+ Refs to `https://ai.google.dev/tutorials/python_quickstart`+ """++ def __init__(self):+ self.use_system_prompt = False # google gemini has no system prompt when use api++ self.__init_gemini(CONFIG)+ self.model = "gemini-pro" # so far only one model+ self.llm = GeminiGenerativeModel(model_name=self.model)- self._cost_manager = CostManager()++ def __init_gemini(self, config: CONFIG):+ genai.configure(api_key=config.gemini_api_key)++ def _user_msg(self, msg: str) -> dict[str, str]:+ # Not to change BaseGPTAPI default functions but update with Gemini's conversation format.+ # You should follow the format.+ return {"role": "user", "parts": [msg]}++ def _assistant_msg(self, msg: str) -> dict[str, str]:+ return {"role": "model", "parts": [msg]}++ def _const_kwargs(self, messages: list[dict], stream: bool = False) -> dict:+ kwargs = {"contents": messages, "generation_config": GenerationConfig(temperature=0.3), "stream": stream}+ return kwargs++ def _update_costs(self, usage: dict):+ """update each request's token cost"""+ if CONFIG.calc_usage:+ 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, self.model)++ CONFIG.cost_manager.update_cost(prompt_tokens, completion_tokens, self.model)+ except Exception as e:+ logger.error(f"google gemini updats costs failed! exp: {e}")++ def get_choice_text(self, resp: GenerateContentResponse) -> str:+ return resp.text++ def get_usage(self, messages: list[dict], resp_text: str) -> dict:+ req_text = messages[-1]["parts"][0] if messages else ""+ prompt_resp = self.llm.count_tokens(contents={"role": "user", "parts": [{"text": req_text}]})+ completion_resp = self.llm.count_tokens(contents={"role": "model", "parts": [{"text": resp_text}]})+ usage = {"prompt_tokens": prompt_resp.total_tokens, "completion_tokens": completion_resp.total_tokens}+ return usage++ async def aget_usage(self, messages: list[dict], resp_text: str) -> dict:+ req_text = messages[-1]["parts"][0] if messages else ""+ prompt_resp = await self.llm.count_tokens_async(contents={"role": "user", "parts": [{"text": req_text}]})+ completion_resp = await self.llm.count_tokens_async(contents={"role": "model", "parts": [{"text": resp_text}]})+ usage = {"prompt_tokens": prompt_resp.total_tokens, "completion_tokens": completion_resp.total_tokens}+ return usage++ def completion(self, messages: list[dict]) -> "GenerateContentResponse":+ resp: GenerateContentResponse = self.llm.generate_content(**self._const_kwargs(messages))+ usage = self.get_usage(messages, resp.text)+ self._update_costs(usage)+ return resp++ async def _achat_completion(self, messages: list[dict]) -> "AsyncGenerateContentResponse":+ resp: AsyncGenerateContentResponse = await self.llm.generate_content_async(**self._const_kwargs(messages))+ usage = await self.aget_usage(messages, resp.text)+ self._update_costs(usage)+ return resp++ async def acompletion(self, messages: list[dict]) -> dict:+ return await self._achat_completion(messages)++ async def _achat_completion_stream(self, messages: list[dict]) -> str:+ resp: AsyncGenerateContentResponse = await self.llm.generate_content_async(+ **self._const_kwargs(messages, stream=True)+ )+ collected_content = []+ async for chunk in resp:+ content = chunk.text+ print(content, end="")+ collected_content.append(content)++ full_content = "".join(collected_content)+ usage = await self.aget_usage(messages, full_content)+ self._update_costs(usage)+ return full_content++ @retry(+ stop=stop_after_attempt(3),+ wait=wait_random_exponential(min=1, max=60),+ after=after_log(logger, logger.level("WARNING").name),+ retry=retry_if_exception_type(ConnectionError),+ retry_error_callback=log_and_reraise,+ )+ async def acompletion_text(self, messages: list[dict], stream=False) -> str:+ """response in async with stream or non-stream mode"""+ if stream:+ return await self._achat_completion_stream(messages)+ resp = await self._achat_completion(messages)+ return self.get_choice_text(resp)diff --cc metagpt/provider/metagpt_api.pyindex 000000000,000000000..00a42ee2anew file mode 100644--- /dev/null+++ b/metagpt/provider/metagpt_api.py@@@ -1,0 -1,0 +1,16 @@@++# -*- coding: utf-8 -*-++"""++@Time : 2023/5/5 23:08++@Author : alexanderwu++@File : metagpt_api.py++@Desc : MetaGPT LLM provider.++"""++from metagpt.config import LLMProviderEnum++from metagpt.provider import OpenAIGPTAPI++from metagpt.provider.llm_provider_registry import register_provider++++++@register_provider(LLMProviderEnum.METAGPT)++class METAGPTAPI(OpenAIGPTAPI):++ def __init__(self):++ super().__init__()diff --cc metagpt/provider/open_llm_api.pyindex cd30c4a58,bada0e294..2e8c03ba1--- a/metagpt/provider/open_llm_api.py+++ b/metagpt/provider/open_llm_api.py@@@ -2,40 -2,44 +2,39 @@@# -*- coding: utf-8 -*-# @Desc : self-host open llm model with openai-compatible interface- from metagpt.config import CONFIG- from metagpt.logs import logger- from metagpt.provider.openai_api import OpenAIGPTAPI, RateLimiter- from metagpt.utils.cost_manager import CostManager--- class OpenLLMCostManager(CostManager):- """open llm model is self-host, it's free and without cost"""-- def update_cost(self, prompt_tokens, completion_tokens, model):- """- Update the total cost, prompt tokens, and completion tokens.-- Args:- prompt_tokens (int): The number of tokens used in the prompt.- completion_tokens (int): The number of tokens used in the completion.- model (str): The model used for the API call.- """- self.total_prompt_tokens += prompt_tokens- self.total_completion_tokens += completion_tokens-- logger.info(- f"Max budget: ${CONFIG.max_budget:.3f} | "- f"prompt_tokens: {prompt_tokens}, completion_tokens: {completion_tokens}"- )- CONFIG.total_cost = self.total_cost-import openai+ from metagpt.config import CONFIG, LLMProviderEnum-from metagpt.logs import logger+ from metagpt.provider.llm_provider_registry import register_provider-from metagpt.provider.openai_api import CostManager, OpenAIGPTAPI, RateLimiter---class OpenLLMCostManager(CostManager):- """open llm model is self-host, it's free and without cost"""-- def update_cost(self, prompt_tokens, completion_tokens, model):- """- Update the total cost, prompt tokens, and completion tokens.-- Args:- prompt_tokens (int): The number of tokens used in the prompt.- completion_tokens (int): The number of tokens used in the completion.- model (str): The model used for the API call.- """- self.total_prompt_tokens += prompt_tokens- self.total_completion_tokens += completion_tokens-- logger.info(- f"Max budget: ${CONFIG.max_budget:.3f} | "- f"prompt_tokens: {prompt_tokens}, completion_tokens: {completion_tokens}"- )- CONFIG.total_cost = self.total_cost++from metagpt.provider.openai_api import OpenAIGPTAPI, RateLimiter+++# class OpenLLMCostManager(CostManager):++# """open llm model is self-host, it's free and without cost"""++#++# def update_cost(self, prompt_tokens, completion_tokens, model):++# """++# Update the total cost, prompt tokens, and completion tokens.++#++# Args:++# prompt_tokens (int): The number of tokens used in the prompt.++# completion_tokens (int): The number of tokens used in the completion.++# model (str): The model used for the API call.++# """++# self.total_prompt_tokens += prompt_tokens++# self.total_completion_tokens += completion_tokens++#++# logger.info(++# f"Max budget: ${CONFIG.max_budget:.3f} | "++# f"prompt_tokens: {prompt_tokens}, completion_tokens: {completion_tokens}"++# )++# CONFIG.total_cost = self.total_cost+++ @register_provider(LLMProviderEnum.OPEN_LLM)class OpenLLMGPTAPI(OpenAIGPTAPI):def __init__(self):self.__init_openllm(CONFIG)- self.llm = openaiself.model = CONFIG.open_llm_api_modelself.auto_max_tokens = False-- self._cost_manager = OpenLLMCostManager()RateLimiter.__init__(self, rpm=self.rpm)def __init_openllm(self, config: "Config"):diff --cc metagpt/provider/openai_api.pyindex 5e9c9fc4d,8fd8959b2..ca130ce15--- a/metagpt/provider/openai_api.py+++ b/metagpt/provider/openai_api.py@@@ -3,19 -3,23 +3,22 @@@@Time : 2023/5/5 23:08@Author : alexanderwu@File : openai.py+@Modified By: mashenquan, 2023/8/20. Remove global configuration `CONFIG`, enable configuration support for business isolation;+ Change cost control from global to company level.+@Modified By: mashenquan, 2023/11/21. Fix bug: ReadTimeout.+@Modified By: mashenquan, 2023/12/1. Fix bug: Unclosed connection caused by openai 0.x."""+import asyncio+ import jsonimport time- from typing import Union-from typing import NamedTuple, Union--from openai import (- APIConnectionError,- AsyncAzureOpenAI,- AsyncOpenAI,- AsyncStream,- AzureOpenAI,- OpenAI,-)++from typing import List, Union++import openai- from openai import APIConnectionError, AsyncAzureOpenAI, AsyncOpenAI, RateLimitError++from openai import APIConnectionError, AsyncOpenAI, AsyncStream, OpenAI, RateLimitError+ from openai._base_client import AsyncHttpxClientWrapper, SyncHttpxClientWrapperfrom openai.types import CompletionUsage+ from openai.types.chat import ChatCompletion, ChatCompletionChunkfrom tenacity import (after_log,retry,@@@ -24,14 -28,16 +27,16 @@@wait_random_exponential,)- from metagpt.config import CONFIG+ from metagpt.config import CONFIG, Config, LLMProviderEnum++from metagpt.const import DEFAULT_MAX_TOKENSfrom metagpt.logs import logger- from metagpt.provider import LLMTypefrom metagpt.provider.base_gpt_api import BaseGPTAPIfrom metagpt.provider.constant import GENERAL_FUNCTION_SCHEMA, GENERAL_TOOL_CHOICE+ from metagpt.provider.llm_provider_registry import register_providerfrom metagpt.schema import Message+from metagpt.utils.cost_manager import Costs+ from metagpt.utils.exceptions import handle_exception-from metagpt.utils.singleton import Singletonfrom metagpt.utils.token_counter import (- TOKEN_COSTS,count_message_tokens,count_string_tokens,get_max_completion_tokens,@@@ -80,66 -156,110 +86,105 @@@ class OpenAIGPTAPI(BaseGPTAPI, RateLimi"""def __init__(self):- self.model = CONFIG.openai_api_model+ self.config: Config = CONFIG+ self.__init_openai()self.auto_max_tokens = False- self.rpm = int(CONFIG.get("RPM", 10))- if CONFIG.openai_api_type == "azure":- # https://learn.microsoft.com/zh-cn/azure/ai-services/openai/how-to/migration?tabs=python-new%2Cdalle-fix- self._client = AsyncAzureOpenAI(- api_key=CONFIG.openai_api_key,- api_version=CONFIG.openai_api_version,- azure_endpoint=CONFIG.openai_api_base,- )- else:- # https://github.com/openai/openai-python#async-usage- self._client = AsyncOpenAI(api_key=CONFIG.openai_api_key, base_url=CONFIG.openai_api_base)- self._cost_manager = CostManager()++ # https://github.com/openai/openai-python#async-usage++ self._client = AsyncOpenAI(api_key=CONFIG.openai_api_key, base_url=CONFIG.openai_api_base)RateLimiter.__init__(self, rpm=self.rpm)+ async def _achat_completion_stream(self, messages: list[dict], timeout=3) -> str:+ kwargs = self._cons_kwargs(messages, timeout=timeout)+ response = await self._client.chat.completions.create(**kwargs, stream=True)+ # iterate through the stream of events+ async for chunk in response:+ chunk_message = chunk.choices[0].delta.content or "" # extract the message+ yield chunk_message++ def __init_openai(self):- self.is_azure = self.config.openai_api_type == "azure"- self.model = self.config.deployment_name if self.is_azure else self.config.openai_api_model+ self.rpm = int(self.config.get("RPM", 10))+ self._make_client()++ def _make_client(self):+ kwargs, async_kwargs = self._make_client_kwargs()-- if self.is_azure:- self.client = AzureOpenAI(**kwargs)- self.async_client = AsyncAzureOpenAI(**async_kwargs)- else:- self.client = OpenAI(**kwargs)- self.async_client = AsyncOpenAI(**async_kwargs)++ self.client = OpenAI(**kwargs)++ self.async_client = AsyncOpenAI(**async_kwargs)++ def _make_client_kwargs(self) -> (dict, dict):- if self.is_azure:- kwargs = dict(- api_key=self.config.openai_api_key,- api_version=self.config.openai_api_version,- azure_endpoint=self.config.openai_base_url,- )- else:- kwargs = dict(api_key=self.config.openai_api_key, base_url=self.config.openai_base_url)-++ kwargs = dict(api_key=self.config.openai_api_key, base_url=self.config.openai_base_url)+ async_kwargs = kwargs.copy()++ # to use proxy, openai v1 needs http_client+ proxy_params = self._get_proxy_params()+ if proxy_params:+ kwargs["http_client"] = SyncHttpxClientWrapper(**proxy_params)+ async_kwargs["http_client"] = AsyncHttpxClientWrapper(**proxy_params)++ return kwargs, async_kwargs++ def _get_proxy_params(self) -> dict:+ params = {}+ if self.config.openai_proxy:+ params = {"proxies": self.config.openai_proxy}+ if self.config.openai_base_url:+ params["base_url"] = self.config.openai_base_url++ return params++ async def _achat_completion_stream(self, messages: list[dict]) -> str:+ response: AsyncStream[ChatCompletionChunk] = await self.async_client.chat.completions.create(+ **self._cons_kwargs(messages), stream=True+ )++ # create variables to collect the stream of chunks+ collected_chunks = []+ collected_messages = []+ # iterate through the stream of events+ async for chunk in response:+ collected_chunks.append(chunk) # save the event response+ if chunk.choices:+ chunk_message = chunk.choices[0].delta # extract the message+ collected_messages.append(chunk_message) # save the message+ if chunk_message.content:+ print(chunk_message.content, end="")+ print()++ full_reply_content = "".join([m.content for m in collected_messages if m.content])+ usage = self._calc_usage(messages, full_reply_content)+ self._update_costs(usage)+ return full_reply_content+- def _cons_kwargs(self, messages: list[dict], **configs) -> dict:+ def _cons_kwargs(self, messages: list[dict], timeout=3, **configs) -> dict:kwargs = {"messages": messages,"max_tokens": self.get_max_tokens(messages),"n": 1,"stop": None,"temperature": 0.3,- "timeout": 3,- "model": self.model,++ "model": self.config.openai_api_model,}if configs:kwargs.update(configs)-- if CONFIG.openai_api_type == "azure":- kwargs["model"] = CONFIG.deployment_id- else:- kwargs["model"] = self.model+ try:+ default_timeout = int(CONFIG.TIMEOUT) if CONFIG.TIMEOUT else 0+ except ValueError:+ default_timeout = 0+ kwargs["timeout"] = max(default_timeout, timeout)return kwargs- async def _achat_completion(self, messages: list[dict], timeout=3) -> dict:- async def _achat_completion(self, messages: list[dict]) -> ChatCompletion:- rsp: ChatCompletion = await self.async_client.chat.completions.create(**self._cons_kwargs(messages))- self._update_costs(rsp.usage)- return rsp-- def _chat_completion(self, messages: list[dict]) -> ChatCompletion:- rsp: ChatCompletion = self.client.chat.completions.create(**self._cons_kwargs(messages))++ async def _achat_completion(self, messages: list[dict], timeout=3) -> ChatCompletion:+ kwargs = self._cons_kwargs(messages, timeout=timeout)- rsp = await self._client.chat.completions.create(**kwargs)++ rsp: ChatCompletion = await self._client.chat.completions.create(**kwargs)self._update_costs(rsp.usage)- return rsp.dict()+ return rsp- def completion(self, messages: list[dict], timeout=3) -> dict:- def completion(self, messages: list[dict]) -> ChatCompletion:- return self._chat_completion(messages)++ def completion(self, messages: list[dict], timeout=3) -> ChatCompletion:+ loop = self.get_event_loop()+ return loop.run_until_complete(self.acompletion(messages, timeout=timeout))- async def acompletion(self, messages: list[dict], timeout=3) -> dict:- # if isinstance(messages[0], Message):- # messages = self.messages_to_dict(messages)- async def acompletion(self, messages: list[dict]) -> ChatCompletion:- return await self._achat_completion(messages)++ async def acompletion(self, messages: list[dict], timeout=3) -> ChatCompletion:+ return await self._achat_completion(messages, timeout=timeout)@retry(wait=wait_random_exponential(min=1, max=60),@@@ -186,17 -286,19 +231,17 @@@}kwargs.update(configs)- return self._cons_kwargs(messages, **kwargs)+ return self._cons_kwargs(messages=messages, timeout=timeout, **kwargs)- def _chat_completion_function(self, messages: list[dict], timeout=3, **kwargs) -> dict:- def _chat_completion_function(self, messages: list[dict], **kwargs) -> ChatCompletion:- rsp: ChatCompletion = self.client.chat.completions.create(**self._func_configs(messages, **kwargs))- self._update_costs(rsp.usage)- return rsp++ def _chat_completion_function(self, messages: list[dict], timeout=3, **kwargs) -> ChatCompletion:+ loop = self.get_event_loop()+ return loop.run_until_complete(self._achat_completion_function(messages=messages, timeout=timeout, **kwargs))- async def _achat_completion_function(self, messages: list[dict], timeout=3, **chat_configs) -> dict:- async def _achat_completion_function(self, messages: list[dict], **chat_configs) -> ChatCompletion:- rsp: ChatCompletion = await self.async_client.chat.completions.create(- **self._func_configs(messages, **chat_configs)- )++ async def _achat_completion_function(self, messages: list[dict], timeout=3, **chat_configs) -> ChatCompletion:+ kwargs = self._func_configs(messages=messages, timeout=timeout, **chat_configs)- rsp = await self._client.chat.completions.create(**kwargs)++ rsp: ChatCompletion = await self._client.chat.completions.create(**kwargs)self._update_costs(rsp.usage)- return rsp.dict()+ return rspdef _process_message(self, messages: Union[str, Message, list[dict], list[Message], list[str]]) -> list[dict]:"""convert messages to list[dict]."""@@@ -247,29 -349,38 +292,57 @@@>>> rsp = await llm.aask_code(msg) # -> {'language': 'python', 'code': "print('Hello, World!')"}"""messages = self._process_message(messages)- rsp = await self._achat_completion_function(messages, **kwargs)- return self.get_choice_function_arguments(rsp)+ try:+ rsp = await self._achat_completion_function(messages, **kwargs)+ return self.get_choice_function_arguments(rsp)+ except openai.NotFoundError as e:+ logger.error(f"API TYPE:{CONFIG.openai_api_type}, err:{e}")+ raise e++ def _calc_usage(self, messages: list[dict], rsp: str) -> CompletionUsage:+ if CONFIG.calc_usage:+ try:+ prompt_tokens = count_message_tokens(messages, self.model)+ completion_tokens = count_string_tokens(rsp, self.model)+ usage = CompletionUsage(+ prompt_tokens=prompt_tokens,+ completion_tokens=completion_tokens,+ total_tokens=prompt_tokens + completion_tokens,+ )+ return usage+ except Exception as e:+ logger.error(f"{self.model} usage calculation failed!", e)+ return CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0)- async def acompletion_batch(self, batch: list[list[dict]], timeout=3) -> list[dict]:+ def get_choice_function_arguments(self, rsp: ChatCompletion) -> dict:+ """Required to provide the first function arguments of choice.++ :return dict: return the first function arguments of choice, for example,+ {'language': 'python', 'code': "print('Hello, World!')"}+ """+ try:+ return json.loads(rsp.choices[0].message.tool_calls[0].function.arguments)+ except json.JSONDecodeError:+ return {}++ def get_choice_text(self, rsp: ChatCompletion) -> str:+ """Required to provide the first text of choice"""+ return rsp.choices[0].message.content if rsp.choices else ""++ def _calc_usage(self, messages: list[dict], rsp: str) -> CompletionUsage:+ usage = CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0)+ if not CONFIG.calc_usage:+ return usage++ try:+ usage.prompt_tokens = count_message_tokens(messages, self.model)+ usage.completion_tokens = count_string_tokens(rsp, self.model)+ except Exception as e:+ logger.error(f"usage calculation failed!: {e}")++ return usage+- async def acompletion_batch(self, batch: list[list[dict]]) -> list[ChatCompletion]:++ async def acompletion_batch(self, batch: list[list[dict]], timeout=3) -> list[ChatCompletion]:"""Return full JSON"""split_batches = self.split_batches(batch)all_results = []@@@ -296,11 -407,9 +369,9 @@@return resultsdef _update_costs(self, usage: CompletionUsage):- if CONFIG.calc_usage:+ if CONFIG.calc_usage and usage:try:- prompt_tokens = usage.prompt_tokens- completion_tokens = usage.completion_tokens- CONFIG.cost_manager.update_cost(prompt_tokens, completion_tokens, self.model)- self._cost_manager.update_cost(usage.prompt_tokens, usage.completion_tokens, self.model)++ CONFIG.cost_manager.update_cost(usage.prompt_tokens, usage.completion_tokens, self.model)except Exception as e:logger.error("updating costs failed!", e)@@@ -312,45 -421,6 +383,100 @@@return CONFIG.max_tokens_rspreturn get_max_completion_tokens(messages, self.model, CONFIG.max_tokens_rsp)+ def moderation(self, content: Union[str, list[str]]):+ loop = self.get_event_loop()+ loop.run_until_complete(self.amoderation(content=content))++ @handle_exceptionasync def amoderation(self, content: Union[str, list[str]]):- try:- if not content:- logger.error("content cannot be empty!")- else:- rsp = await self._amoderation(content=content)- return rsp- except Exception as e:- logger.error(f"moderating failed:{e}")-- async def _amoderation(self, content: Union[str, list[str]]):- rsp = await self._client.moderations.create(input=content)- return rsp- return await self.async_client.moderations.create(input=content)++ return await self._client.moderations.create(input=content)++ async def close(self):+ """Close connection"""+ if not self._client:+ return+ await self._client.close()+ self._client = None++ @staticmethod+ def get_event_loop():+ try:+ return asyncio.get_event_loop()+ except RuntimeError as e:+ if "There is no current event loop in thread" in str(e):+ loop = asyncio.new_event_loop()+ asyncio.set_event_loop(loop)+ return loop+ else:+ raise e+- async def get_summary(self, text: str, max_words=200, keep_language: bool = False, **kwargs) -> str:- from metagpt.memory.brain_memory import BrainMemory++ async def summarize(self, text: str, max_words=200, keep_language: bool = False, limit: int = -1, **kwargs) -> str:++ max_token_count = DEFAULT_MAX_TOKENS++ max_count = 100++ text_length = len(text)++ if limit > 0 and text_length < limit:++ return text++ summary = ""++ while max_count > 0:++ if text_length < max_token_count:++ summary = await self._get_summary(text=text, max_words=max_words, keep_language=keep_language)++ break++++ padding_size = 20 if max_token_count > 20 else 0++ text_windows = self.split_texts(text, window_size=max_token_count - padding_size)++ part_max_words = min(int(max_words / len(text_windows)) + 1, 100)++ summaries = []++ for ws in text_windows:++ response = await self._get_summary(text=ws, max_words=part_max_words, keep_language=keep_language)++ summaries.append(response)++ if len(summaries) == 1:++ summary = summaries[0]++ break++++ # Merged and retry++ text = "\n".join(summaries)++ text_length = len(text)++++ max_count -= 1 # safeguard++ return summary++++ async def _get_summary(self, text: str, max_words=20, keep_language: bool = False):++ """Generate text summary"""++ if len(text) < max_words:++ return text++ if keep_language:++ command = f".Translate the above content into a summary of less than {max_words} words in language of the content strictly."++ else:++ command = f"Translate the above content into a summary of less than {max_words} words."++ msg = text + "\n\n" + command++ logger.debug(f"summary ask:{msg}")++ response = await self.aask(msg=msg, system_msgs=[])++ logger.debug(f"summary rsp: {response}")++ return response+- memory = BrainMemory(llm_type=LLMType.OPENAI.value, historical_summary=text, cacheable=False)- return await memory.summarize(llm=self, max_words=max_words, keep_language=keep_language)++ @staticmethod++ def split_texts(text: str, window_size) -> List[str]:++ """Splitting long text into sliding windows text"""++ if window_size <= 0:++ window_size = DEFAULT_TOKEN_SIZE++ total_len = len(text)++ if total_len <= window_size:++ return [text]++++ padding_size = 20 if window_size > 20 else 0++ windows = []++ idx = 0++ data_len = window_size - padding_size++ while idx < total_len:++ if window_size + idx > total_len: # 不足一个滑窗++ windows.append(text[idx:])++ break++ # 每个窗口少算padding_size自然就可实现滑窗功能, 比如: [1, 2, 3, 4, 5, 6, 7, ....]++ # window_size=3, padding_size=1:++ # [1, 2, 3], [3, 4, 5], [5, 6, 7], ....++ # idx=2, | idx=5 | idx=8 | ...++ w = text[idx : idx + window_size]++ windows.append(w)++ idx += data_len++++ return windowsdiff --cc metagpt/provider/zhipuai_api.pyindex ff8e5531e,60d9a0777..54f0ddcbb--- a/metagpt/provider/zhipuai_api.py+++ b/metagpt/provider/zhipuai_api.py@@@ -15,12 -16,12 +15,12 @@@ from tenacity importwait_random_exponential,)- from metagpt.config import CONFIG+ from metagpt.config import CONFIG, LLMProviderEnumfrom metagpt.logs import loggerfrom metagpt.provider.base_gpt_api import BaseGPTAPI+ from metagpt.provider.llm_provider_registry import register_provider-from metagpt.provider.openai_api import CostManager, log_and_reraise+from metagpt.provider.openai_api import log_and_reraisefrom metagpt.provider.zhipuai.zhipu_model_api import ZhiPuModelAPI- from metagpt.utils.cost_manager import CostManagerclass ZhiPuEvent(Enum):@@@ -42,7 -44,7 +43,6 @@@ class ZhiPuAIGPTAPI(BaseGPTAPI)self.__init_zhipuai(CONFIG)self.llm = ZhiPuModelAPIself.model = "chatglm_turbo" # so far only one model, just use it-- self._cost_manager = CostManager()def __init_zhipuai(self, config: CONFIG):assert config.zhipuai_api_key@@@ -60,9 -61,9 +60,9 @@@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, self.model)++ CONFIG.cost_manager.update_cost(prompt_tokens, completion_tokens, self.model)except Exception as e:- logger.error("zhipuai updats costs failed!", e)+ logger.error(f"zhipuai updats costs failed! exp: {e}")def get_choice_text(self, resp: dict) -> str:"""get the first text of choice from llm response"""diff --cc metagpt/roles/engineer.pyindex f5286e450,e0234f378..12deaa5bb--- a/metagpt/roles/engineer.py+++ b/metagpt/roles/engineer.py@@@ -67,25 -68,23 +68,26 @@@ class Engineer(Role)use_code_review (bool): Whether to use code review."""- def __init__(- self,- name: str = "Alex",- profile: str = "Engineer",- goal: str = "write elegant, readable, extensible, efficient code",- constraints: str = "the code should conform to standards like google-style and be modular and maintainable. "- "Use same language as user requirement",- n_borg: int = 1,- use_code_review: bool = False,- ) -> None:- """Initializes the Engineer role with given attributes."""- super().__init__(name, profile, goal, constraints)- self.use_code_review = use_code_review+ name: str = "Alex"+ profile: str = "Engineer"+ goal: str = "write elegant, readable, extensible, efficient code"+ constraints: str = (+ "the code should conform to standards like google-style and be modular and maintainable. "+ "Use same language as user requirement"+ )+ n_borg: int = 1+ use_code_review: bool = False+ code_todos: list = []+ summarize_todos = []++ def __init__(self, **kwargs) -> None:+ super().__init__(**kwargs)+self._init_actions([WriteCode])self._watch([WriteTasks, SummarizeCode, WriteCode, WriteCodeReview, FixBug])+ self.code_todos = []+ self.summarize_todos = []- self.n_borg = n_borg+ self._next_todo = any_to_name(WriteCode)@staticmethoddef _parse_tasks(task_msg: Document) -> list[str]:@@@ -304,7 -301,3 +306,8 @@@self.summarize_todos.append(SummarizeCode(context=ctx, llm=self._llm))if self.summarize_todos:self._rc.todo = self.summarize_todos[0]++ @property+ def todo(self) -> str:++ """AgentStore uses this attribute to display to the user what actions the current role should take."""+ return self._next_tododiff --cc metagpt/roles/product_manager.pyindex f022237f5,c794ad2eb..0f18c9cb2--- a/metagpt/roles/product_manager.py+++ b/metagpt/roles/product_manager.py@@@ -10,8 -11,7 +11,8 @@@from metagpt.actions import UserRequirement, WritePRDfrom metagpt.actions.prepare_documents import PrepareDocumentsfrom metagpt.config import CONFIG- from metagpt.roles import Role+ from metagpt.roles.role import Role+from metagpt.utils.common import any_to_nameclass ProductManager(Role):@@@ -57,8 -45,4 +48,9 @@@return self._rc.todoasync def _observe(self, ignore_memory=False) -> int:- return await super()._observe(ignore_memory=True)+ return await super(ProductManager, self)._observe(ignore_memory=True)++ @property+ def todo(self) -> str:++ """AgentStore uses this attribute to display to the user what actions the current role should take."""+ return self._tododiff --cc metagpt/roles/role.pyindex 757c6b8e3,b9fde7d05..9636a1f30--- a/metagpt/roles/role.py+++ b/metagpt/roles/role.py@@@ -31,8 -35,15 +36,16 @@@ from metagpt.const import SERDESER_PATfrom metagpt.llm import LLM, HumanProviderfrom metagpt.logs import loggerfrom metagpt.memory import Memory+ from metagpt.provider.base_gpt_api import BaseGPTAPIfrom metagpt.schema import Message, MessageQueue- from metagpt.utils.common import any_to_name, any_to_str+ from metagpt.utils.common import (++ any_to_name,+ any_to_str,+ import_class,+ read_json_file,+ role_raise_decorator,+ write_json_file,+ )from metagpt.utils.repair_llm_raw_output import extract_state_value_from_outputPREFIX_TEMPLATE = """You are a {profile}, named {name}, your goal is {goal}, and the constraint is {constraints}. """@@@ -127,27 -125,140 +127,145 @@@ class RoleContext(BaseModel)return self.memory.get()- class Role:+ role_subclass_registry = {}+++ 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- )+ name: str = ""+ profile: str = ""+ goal: str = ""+ constraints: str = ""+ desc: str = ""+ is_human: bool = False++ _llm: BaseGPTAPI = Field(default_factory=LLM)+ _role_id: str = ""+ _states: list[str] = []+ _actions: list[Action] = []+ _rc: RoleContext = Field(default_factory=RoleContext)+ _subscription: tuple[str] = set()++ # builtin variables+ recovered: bool = False # to tag if a recovered role+ latest_observed_msg: Message = None # record the latest observed message when interrupted+ builtin_class_name: str = ""++ _private_attributes = {+ "_llm": LLM() if not is_human else HumanProvider(),+ "_role_id": _role_id,+ "_states": [],+ "_actions": [],+ "_rc": RoleContext(),+ "_subscription": set(),+ }++ __hash__ = object.__hash__ # support Role as hashable type in `Environment.members`++ class Config:+ arbitrary_types_allowed = True+ exclude = ["_llm"]++ def __init__(self, **kwargs: Any):+ for index in range(len(kwargs.get("_actions", []))):+ current_action = kwargs["_actions"][index]+ if isinstance(current_action, dict):+ item_class_name = current_action.get("builtin_class_name", None)+ for name, subclass in action_subclass_registry.items():+ registery_class_name = subclass.__fields__["builtin_class_name"].default+ if item_class_name == registery_class_name:+ current_action = subclass(**current_action)+ break+ kwargs["_actions"][index] = current_action++ super().__init__(**kwargs)++ # 关于私有变量的初始化 https://github.com/pydantic/pydantic/issues/655+ self._private_attributes["_llm"] = LLM() if not self.is_human else HumanProvider()+ self._private_attributes["_role_id"] = str(self._setting)+ self._private_attributes["_subscription"] = {any_to_str(self), self.name} if self.name else {any_to_str(self)}++ for key in self._private_attributes.keys():+ if key in kwargs:+ object.__setattr__(self, key, kwargs[key])+ if key == "_rc":+ _rc = RoleContext(**kwargs["_rc"])+ object.__setattr__(self, "_rc", _rc)+ else:+ if key == "_rc":+ # # Warning, if use self._private_attributes["_rc"],+ # # self._rc will be a shared object between roles, so init one or reset it inside `_reset`+ object.__setattr__(self, key, RoleContext())+ else:+ object.__setattr__(self, key, self._private_attributes[key])+self._llm.system_prompt = self._get_prefix()- self._states = []- self._actions = []- self._role_id = str(self._setting)- self._rc = RoleContext(watch={any_to_str(UserRequirement)})- self._subscription = {any_to_str(self), name} if name else {any_to_str(self)}++ # deserialize child classes dynamically for inherited `role`+ object.__setattr__(self, "builtin_class_name", self.__class__.__name__)+ self.__fields__["builtin_class_name"].default = self.__class__.__name__+++ if "actions" in kwargs:++ self._init_actions(kwargs["actions"])++++ self._watch(kwargs.get("watch") or [UserRequirement])+++ def __init_subclass__(cls, **kwargs: Any) -> None:+ super().__init_subclass__(**kwargs)+ role_subclass_registry[cls.__name__] = clsdef _reset(self):- self._states = []- self._actions = []+ object.__setattr__(self, "_states", [])+ object.__setattr__(self, "_actions", [])++ @property+ def _setting(self):+ return f"{self.name}({self.profile})"++ def serialize(self, stg_path: Path = None):+ stg_path = (+ SERDESER_PATH.joinpath(f"team/environment/roles/{self.__class__.__name__}_{self.name}")+ if stg_path is None+ else stg_path+ )++ role_info = self.dict(exclude={"_rc": {"memory": True, "msg_buffer": True}, "_llm": True})+ role_info.update({"role_class": self.__class__.__name__, "module_name": self.__module__})+ role_info_path = stg_path.joinpath("role_info.json")+ write_json_file(role_info_path, role_info)++ self._rc.memory.serialize(stg_path) # serialize role's memory alone++ @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+ role.set_recovered(True) # set True to make a tag++ role_memory = Memory.deserialize(stg_path)+ role.set_memory(role_memory)++ return roledef _init_action_system_message(self, action: Action):- action.set_prefix(self._get_prefix(), self.profile)+ action.set_prefix(self._get_prefix())++ 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()@@@ -224,50 -333,27 +343,34 @@@@propertydef subscription(self) -> Set:"""The labels for messages to be consumed by the Role object."""-- return self._subscription-- @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++ return set(self._subscription)++ @property+ def action_count(self):+ """Return number of action"""+ return len(self._actions)def _get_prefix(self):"""Get the role prefix"""- if self._setting.desc:- return self._setting.desc- return PREFIX_TEMPLATE.format(**self._setting.dict())+ if self.desc:+ return self.desc+ return PREFIX_TEMPLATE.format(+ **{"profile": self.profile, "name": self.name, "goal": self.goal, "constraints": self.constraints}+ )- async def _think(self) -> None:- """Think about what to do and decide on the next action"""+ async def _think(self) -> bool:+ """Consider what to do and decide on the next course of action. Return false if nothing can be done."""if len(self._actions) == 1:# If there is only one action, then only this one can be performedself._set_state(0)- return++++ return True+++ 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+ return True+prompt = self._get_prefix()prompt += STATE_TEMPLATE.format(history=self._rc.history,@@@ -417,19 -537,3 +538,20 @@@def is_idle(self) -> bool:"""If true, all actions have been executed."""return not self._rc.news and not self._rc.todo and self._rc.msg_buffer.empty()++ async def think(self) -> Action:+ """The exported `think` function"""+ await self._think()+ return self._rc.todo++ async def act(self) -> ActionOutput:+ """The exported `act` function"""+ msg = await self._act()+ return ActionOutput(content=msg.content, instruct_content=msg.instruct_content)++ @property+ def todo(self) -> str:++ """AgentStore uses this attribute to display to the user what actions the current role should take."""+ if self._actions:+ return any_to_name(self._actions[0])+ return ""diff --cc metagpt/schema.pyindex b17565979,d3c836d8e..60b9a6998--- a/metagpt/schema.py+++ b/metagpt/schema.py@@@ -145,8 -142,24 +142,26 @@@ class Message(BaseModel)new_val = valsuper().__setattr__(key, new_val)+ def dict(self, *args, **kwargs) -> "DictStrAny":+ """overwrite the `dict` to dump dynamic pydantic model"""+ obj_dict = super(Message, self).dict(*args, **kwargs)+ ic = self.instruct_content+ if ic:+ # compatible with custom-defined ActionOutput+ schema = ic.schema()+ # `Documents` contain definitions+ if "definitions" not in schema:+ # TODO refine with nested BaseModel+ mapping = actionoutout_schema_to_mapping(schema)+ mapping = actionoutput_mapping_to_str(mapping)++ obj_dict["instruct_content"] = {"class": schema["title"], "mapping": mapping, "value": ic.dict()}+ return obj_dict+def __str__(self):# prefix = '-'.join([self.role, str(self.cause_by)])++ if self.instruct_content:++ return f"{self.role}: {self.instruct_content.dict()}"return f"{self.role}: {self.content}"def __repr__(self):@@@ -164,18 -177,8 +179,19 @@@@handle_exception(exception_type=JSONDecodeError, default_return=None)def load(val):"""Convert the json string to object."""- i = json.loads(val)- return Message(**i)+++ 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 Noneclass UserMessage(Message):diff --cc metagpt/team.pyindex d613a04ef,8b92ed47a..ed370fd16--- a/metagpt/team.py+++ b/metagpt/team.py@@@ -77,14 -112,16 +116,15 @@@ class Team(BaseModel)def _save(self):logger.info(self.json(ensure_ascii=False))+ @serialize_decorator- async def run(self, n_round=3):+ async def run(self, n_round=3, auto_archive=True):"""Run company until target round or no money"""while n_round > 0:# self._save()n_round -= 1logger.debug(f"max {n_round=} left.")self._check_balance()+await self.env.run()- if auto_archive and CONFIG.git_repo:- if CONFIG.git_repo:-- CONFIG.git_repo.archive()++ self.env.archive(auto_archive)return self.env.historydiff --cc metagpt/tools/azure_tts.pyindex 6864faf10,e59d98016..8fdb10c13--- a/metagpt/tools/azure_tts.py+++ b/metagpt/tools/azure_tts.py@@@ -1,21 -1,13 +1,21 @@@#!/usr/bin/env python# -*- coding: utf-8 -*-"""- @Time : 2023/8/17- @Author : mashenquan+ @Time : 2023/6/9 22:22+ @Author : Leo Xiao@File : azure_tts.py- @Desc : azure TTS OAS3 api, which provides text-to-speech functionality++@Modified by: mashenquan, 2023/8/17. Azure TTS OAS3 api, which provides text-to-speech functionality"""+import asyncio+import base64+from pathlib import Path+from uuid import uuid4++import aiofilesfrom azure.cognitiveservices.speech import AudioConfig, SpeechConfig, SpeechSynthesizer-from metagpt.config import CONFIG+from metagpt.config import CONFIG, Config+from metagpt.logs import loggerclass AzureTTS:diff --cc metagpt/utils/common.pyindex a5d2100cc,8db7a80a1..a1cb71c6f--- a/metagpt/utils/common.py+++ b/metagpt/utils/common.py@@@ -17,14 -19,17 +19,18 @@@ import jsoimport osimport platformimport re+ import sys+ import traceback+ import typingfrom pathlib import Path- from typing import Callable, List, Tuple, Union-from typing import Any, List, Tuple, Union, get_args, get_origin++from typing import Any, Callable, List, Tuple, Union, get_args, get_originimport aiofilesimport loguru+ from pydantic.json import pydantic_encoderfrom tenacity import RetryCallState, _utils+from metagpt.config import CONFIGfrom metagpt.const import MESSAGE_ROUTE_TO_ALLfrom metagpt.logs import loggerfrom metagpt.utils.exceptions import handle_exceptiondiff --cc requirements.txtindex c4e674569,eaff5c4b2..d221dc3c5--- a/requirements.txt+++ b/requirements.txt@@@ -36,8 -36,7 +36,8 @@@ tqdm==4.64.# webdriver_manager<3.9anthropic==0.3.6typing-inspect==0.8.0- typing_extensions==4.5.0+aiofiles+ typing_extensions==4.7.0libcst==1.0.1qdrant-client==1.4.0pytest-mock==3.11.1@@@ -53,9 -48,5 +53,10 @@@ websocket-client==1.6.aiofiles==23.2.1gitpython==3.1.40zhipuai==1.0.7+socksio~=1.0.0gitignore-parser==0.1.9- connexion[swagger-ui]++# connexion[swagger-ui]+websockets~=12.0+networkx~=3.2.1- pylint~=3.0.3++pylint~=3.0.3+ google-generativeai==0.3.1diff --cc tests/metagpt/roles/ui_role.pyindex 5c2d64a58,0932efa1f..51b346821--- a/tests/metagpt/roles/ui_role.py+++ b/tests/metagpt/roles/ui_role.py@@@ -8,6 -8,9 +8,7 @@@ from functools import wrapfrom importlib import import_modulefrom metagpt.actions import Action, ActionOutput, WritePRD--# from metagpt.const import WORKSPACE_ROOT+ from metagpt.actions.action_node import ActionNodefrom metagpt.config import CONFIGfrom metagpt.logs import loggerfrom metagpt.roles import Rolediff --cc tests/metagpt/test_environment.pyindex bc88eb742,56e2b4fc3..3a899d6ff--- a/tests/metagpt/test_environment.py+++ b/tests/metagpt/test_environment.py@@@ -4,10 -4,10 +4,12 @@@@Time : 2023/5/12 00:47@Author : alexanderwu@File : test_environment.py+@Modified By: mashenquan, 2023/8/20. Remove global configuration `CONFIG`, enable configuration support for business isolation.+"""+ from pathlib import Path+import pytestfrom metagpt.actions import UserRequirement@@@ -52,7 -50,10 +56,8 @@@ async def test_publish_and_process_mess)env.add_roles([product_manager, architect])+- env.set_manager(Manager())env.publish_message(Message(role="User", content="需要一个基于LLM做总结的搜索引擎", cause_by=UserRequirement))-await env.run(k=2)logger.info(f"{env.history=}")assert len(env.history) > 10diff --cc tests/metagpt/test_schema.pyindex a6c84d32a,1742757e8..897d203c7--- a/tests/metagpt/test_schema.py+++ b/tests/metagpt/test_schema.py@@@ -7,11 -7,14 +7,12 @@@@Modified By: mashenquan, 2023-11-1. In line with Chapter 2.2.1 and 2.2.2 of RFC 116, introduce unit tests forthe utilization of the new feature of `Message` class."""- import json- import pytest+ import json-import pytest-from metagpt.actions import Action+ from metagpt.actions.action_node import ActionNode+ from metagpt.actions.write_code import WriteCodefrom metagpt.schema import AIMessage, Message, SystemMessage, UserMessagefrom metagpt.utils.common import any_to_str@@@ -29,8 -33,9 +30,8 @@@ def test_messages()assert all([i in text for i in roles])def test_message():- m = Message("a", role="v1")+ m = Message(content="a", role="v1")v = m.dump()d = json.loads(v)assert d@@@ -59,8 -64,9 +60,8 @@@assert m.content == "b"def test_routes():- m = Message("a", role="b", cause_by="c", x="d", send_to="c")+ m = Message(content="a", role="b", cause_by="c", x="d", send_to="c")m.send_to = "b"assert m.send_to == {"b"}m.send_to = {"e", Action}