# The audience of this agent, which means if this agent generates a# response, it will be passed to all agents in the audience.
- self._audience=None
+ self._audience=None
+
-[docs]
+[docs]@classmethoddefgenerate_agent_id(cls)->str:"""Generate the agent_id of this agent instance"""
@@ -186,7 +191,7 @@
Source code for agentscope.agents.agent
-[docs]
+[docs]defreply(self,x:dict=None)->dict:"""Define the actions taken by this agent.
@@ -208,7 +213,7 @@
Source code for agentscope.agents.agent
-[docs]
+[docs]defload_from_config(self,config:dict)->None:"""Load configuration for this agent.
@@ -218,7 +223,7 @@
Source code for agentscope.agents.agent
-[docs]
+[docs]defexport_config(self)->dict:"""Return configuration of this agent.
@@ -229,7 +234,7 @@
-[docs]
+[docs]defobserve(self,x:Union[dict,Sequence[dict]])->None:"""Observe the input, store it in memory without response to it.
@@ -269,7 +274,7 @@
Source code for agentscope.agents.agent
-[docs]
+[docs]defreset_audience(self,audience:Sequence[AgentBase])->None:"""Set the audience of this agent, which means if this agent generates a response, it will be passed to all audiences.
@@ -285,7 +290,7 @@
Source code for agentscope.agents.agent
-[docs]
+[docs]defclear_audience(self)->None:"""Remove the audience of this agent."""# TODO: we leave the consideration of nested msghub for future.
@@ -294,7 +299,7 @@
logger.warning("The argument `prompt_type` is deprecated and ""will be removed in the future.",
- )
+ )
+
# TODO change typing from dict to MSG
-[docs]
+[docs]defreply(self,x:dict=None)->dict:"""Reply function of the agent. Processes the input data, generates a prompt using the current dialogue memory and system
diff --git a/en/_modules/agentscope/agents/dict_dialog_agent.html b/en/_modules/agentscope/agents/dict_dialog_agent.html
index 6dfdd0581..346ae9e41 100644
--- a/en/_modules/agentscope/agents/dict_dialog_agent.html
+++ b/en/_modules/agentscope/agents/dict_dialog_agent.html
@@ -57,15 +57,17 @@
Source code for agentscope.agents.dict_dialog_agent
from ..utils.toolsimport_convert_to_str
+
+[docs]defparse_dict(response:ModelResponse)->ModelResponse:"""Parse function for DictDialogAgent"""try:
@@ -123,16 +127,20 @@
Source code for agentscope.agents.dict_dialog_agent
# TODO: maybe using a more robust json library to handle this case
response_dict=json.loads(response.text.replace("'",'"'))
- returnModelResponse(raw=response_dict)
+ returnModelResponse(raw=response_dict)
+
+
+[docs]defdefault_response(response:ModelResponse)->ModelResponse:"""The default response of fault_handler"""
- returnModelResponse(raw={"speak":response.text})
+ returnModelResponse(raw={"speak":response.text})
+
-[docs]
+[docs]classDictDialogAgent(AgentBase):"""An agent that generates response in a dict format, where user can specify the required fields in the response via prompt, e.g.
@@ -155,6 +163,8 @@
Source code for agentscope.agents.dict_dialog_agent
For usage example, please refer to the example of werewolf in
`examples/game_werewolf`"""
+
Source code for agentscope.agents.dict_dialog_agent
Whether the agent has memory.
memory_config (`Optional[dict]`, defaults to `None`): The config of memory.
- parse_func (`Optional[Callable[..., Any]]`,
- defaults to `parse_dict`):
+ parse_func (`Optional[Callable[..., Any]]`, defaults to `parse_dict`): The function used to parse the model output, e.g. `json.loads`, which is used to extract json from the output.
- fault_handler (`Optional[Callable[..., Any]]`,
- defaults to `default_response`):
+ fault_handler (`Optional[Callable[..., Any]]`, defaults to `default_response`): The function used to handle the fault when parse_func fails to parse the model output. max_retries (`Optional[int]`, defaults to `None`): The maximum number of retries when failed to parse the model output.
- prompt_type (`Optional[PromptType]`, defaults to
- `PromptType.LIST`):
+ prompt_type (`Optional[PromptType]`, defaults to `PromptType.LIST`): The type of the prompt organization, chosen from `PromptType.LIST` or `PromptType.STRING`.
- """
+ """# noqasuper().__init__(name=name,sys_prompt=sys_prompt,
@@ -216,11 +223,12 @@
Source code for agentscope.agents.dict_dialog_agent
logger.warning("The argument `prompt_type` is deprecated and ""will be removed in the future.",
- )
+ )
+
# TODO change typing from dict to MSG
-[docs]
+[docs]defreply(self,x:dict=None)->dict:"""Reply function of the agent. Processes the input data, generates a prompt using the current
diff --git a/en/_modules/agentscope/agents/operator.html b/en/_modules/agentscope/agents/operator.html
index 0fe7191d3..578821705 100644
--- a/en/_modules/agentscope/agents/operator.html
+++ b/en/_modules/agentscope/agents/operator.html
@@ -57,15 +57,17 @@
-[docs]
+[docs]classOperator(ABC):""" Abstract base class `Operator` defines a protocol for classes that
diff --git a/en/_modules/agentscope/agents/react_agent.html b/en/_modules/agentscope/agents/react_agent.html
index 8aafa83c8..f4e6f655f 100644
--- a/en/_modules/agentscope/agents/react_agent.html
+++ b/en/_modules/agentscope/agents/react_agent.html
@@ -57,15 +57,17 @@
-[docs]
+[docs]classReActAgent(AgentBase):"""An agent class that implements the ReAct algorithm. More details refer to https://arxiv.org/abs/2210.03629.
@@ -173,6 +175,8 @@
)
# Put sys prompt into memory
- self.memory.add(Msg("system",self.sys_prompt,role="system"))
+ self.memory.add(Msg("system",self.sys_prompt,role="system"))
+
-[docs]
+[docs]defreply(self,x:dict=None)->dict:"""The reply function that achieves the ReAct algorithm. The more details please refer to https://arxiv.org/abs/2210.03629"""
@@ -335,7 +340,7 @@
Source code for agentscope.agents.react_agent
-[docs]
+[docs]defexecute_func(self,index:int,func_call:dict)->dict:"""Execute the tool function and return the result.
@@ -380,7 +385,7 @@
Source code for agentscope.agents.react_agent
-[docs]
+[docs]defprepare_funcs_prompt(self,tools:List[Tuple])->Tuple[str,dict]:"""Convert function descriptions from json schema format to string prompt format.
diff --git a/en/_modules/agentscope/agents/rpc_agent.html b/en/_modules/agentscope/agents/rpc_agent.html
index 8c80b5cae..c1d80a69f 100644
--- a/en/_modules/agentscope/agents/rpc_agent.html
+++ b/en/_modules/agentscope/agents/rpc_agent.html
@@ -57,15 +57,17 @@
logger.info(f"rpc server [{agent_class.__name__}] at port [{port}] stopped ""successfully",
- )
+ )
+
+
+[docs]deffind_available_port()->int:"""Get an unoccupied socket port number."""withsocket.socket(socket.AF_INET,socket.SOCK_STREAM)ass:s.bind(("",0))
- returns.getsockname()[1]
+ returns.getsockname()[1]
+
+
+[docs]defcheck_port(port:Optional[int]=None)->int:"""Check if the port is available.
@@ -466,14 +482,17 @@
Source code for agentscope.agents.rpc_agent
f"Port [{port}] is occupied, use [{new_port}] instead",)returnnew_port
- returnport
+ returnport
+
-[docs]
+[docs]classRpcAgentServerLauncher:"""Launcher of rpc agent server."""
+
+[docs]defcall_func(self,request:RpcMsg,_:ServicerContext)->RpcMsg:"""Call the specific servicer function."""ifhasattr(self,request.target_func):
@@ -726,7 +762,8 @@
+# -*- coding: utf-8 -*-
+""" Some constants used in the project"""
+fromnumbersimportNumber
+fromenumimportIntEnum
+
+PACKAGE_NAME="agentscope"
+MSG_TOKEN=f"[{PACKAGE_NAME}_msg]"
+
+
+# default values
+
+# for file manager
+_DEFAULT_DIR="./runs"
+_DEFAULT_LOG_LEVEL="INFO"
+_DEFAULT_SUBDIR_CODE="code"
+_DEFAULT_SUBDIR_FILE="file"
+_DEFAULT_SUBDIR_INVOKE="invoke"
+_DEFAULT_CFG_NAME=".config"
+_DEFAULT_IMAGE_NAME="image_{}_{}.png"
+_DEFAULT_SQLITE_DB_PATH="agentscope.db"
+
+
+# for model wrapper
+_DEFAULT_MAX_RETRIES=3
+_DEFAULT_MESSAGES_KEY="inputs"
+_DEFAULT_RETRY_INTERVAL=1
+_DEFAULT_API_BUDGET=None
+# for execute python
+_DEFAULT_PYPI_MIRROR="http://mirrors.aliyun.com/pypi/simple/"
+_DEFAULT_TRUSTED_HOST="mirrors.aliyun.com"
+# for monitor
+_DEFAULT_MONITOR_TABLE_NAME="monitor_metrics"
+# for summarization
+_DEFAULT_SUMMARIZATION_PROMPT="""
+TEXT: {}
+"""
+_DEFAULT_SYSTEM_PROMPT="""
+You are a helpful agent to summarize the text.
+You need to keep all the key information of the text in the summary.
+"""
+_DEFAULT_TOKEN_LIMIT_PROMPT="""
+Summarize the text after TEXT in less than {} tokens:
+"""
+
+# typing
+Embedding=list[Number]
+
+
+# enums
+
+[docs]
+classResponseFormat(IntEnum):
+"""Enum for model response format."""
+
+ NONE=0
+ JSON=1
+
+
+
+
+[docs]
+classShrinkPolicy(IntEnum):
+"""Enum for shrink strategies when the prompt is too long."""
+
+ TRUNCATE=0
+ SUMMARIZE=1
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/en/_modules/agentscope/memory/memory.html b/en/_modules/agentscope/memory/memory.html
index fc8bbda55..61dbb549a 100644
--- a/en/_modules/agentscope/memory/memory.html
+++ b/en/_modules/agentscope/memory/memory.html
@@ -57,15 +57,17 @@
config (`Optional[dict]`, defaults to `None`): Configuration of this memory. """
- self.config={}ifconfigisNoneelseconfig
+ self.config={}ifconfigisNoneelseconfig
+
-[docs]
+[docs]defupdate_config(self,config:dict)->None:""" Configure memory as specified in config
@@ -137,7 +142,7 @@
-[docs]
+[docs]@abstractmethoddefclear(self)->None:"""Clean memory, depending on how the memory are stored"""
-[docs]
+[docs]@abstractmethoddefsize(self)->int:"""Returns the number of memory segments in memory."""
diff --git a/en/_modules/agentscope/memory/temporary_memory.html b/en/_modules/agentscope/memory/temporary_memory.html
index 8dd03774e..313884ab5 100644
--- a/en/_modules/agentscope/memory/temporary_memory.html
+++ b/en/_modules/agentscope/memory/temporary_memory.html
@@ -57,15 +57,17 @@
+# -*- coding: utf-8 -*-
+"""The base class for message unit"""
+
+fromtypingimportAny,Optional,Union,Sequence,Literal
+fromuuidimportuuid4
+importjson
+
+fromloguruimportlogger
+
+from.rpcimportRpcAgentClient,ResponseStub,call_in_thread
+from.utils.toolsimport_get_timestamp
+
+
+
+[docs]
+classMessageBase(dict):
+"""Base Message class, which is used to maintain information for dialog,
+ memory and used to construct prompt.
+ """
+
+
+[docs]
+ def__init__(
+ self,
+ name:str,
+ content:Any,
+ role:Literal["user","system","assistant"]="assistant",
+ url:Optional[Union[Sequence[str],str]]=None,
+ timestamp:Optional[str]=None,
+ **kwargs:Any,
+ )->None:
+"""Initialize the message object
+
+ Args:
+ name (`str`):
+ The name of who send the message. It's often used in
+ role-playing scenario to tell the name of the sender.
+ content (`Any`):
+ The content of the message.
+ role (`Literal["system", "user", "assistant"]`, defaults to "assistant"):
+ The role of who send the message. It can be one of the
+ `"system"`, `"user"`, or `"assistant"`. Default to
+ `"assistant"`.
+ url (`Optional[Union[list[str], str]]`, defaults to None):
+ A url to file, image, video, audio or website.
+ timestamp (`Optional[str]`, defaults to None):
+ The timestamp of the message, if None, it will be set to
+ current time.
+ **kwargs (`Any`):
+ Other attributes of the message.
+ """# noqa
+ # id and timestamp will be added to the object as its attributes
+ # rather than items in dict
+ self.id=uuid4().hex
+ iftimestampisNone:
+ self.timestamp=_get_timestamp()
+ else:
+ self.timestamp=timestamp
+
+ self.name=name
+ self.content=content
+ self.role=role
+
+ ifurl:
+ self.url=url
+ else:
+ self.url=None
+
+ self.update(kwargs)
+[docs]
+ def__init__(
+ self,
+ name:str,
+ content:Any,
+ role:Literal["system","user","assistant"]=None,
+ url:Optional[Union[Sequence[str],str]]=None,
+ timestamp:Optional[str]=None,
+ echo:bool=False,
+ **kwargs:Any,
+ )->None:
+"""Initialize the message object
+
+ Args:
+ name (`str`):
+ The name of who send the message.
+ content (`Any`):
+ The content of the message.
+ role (`Literal["system", "user", "assistant"]`):
+ Used to identify the source of the message, e.g. the system
+ information, the user input, or the model response. This
+ argument is used to accommodate most Chat API formats.
+ url (`Optional[Union[list[str], str]]`, defaults to `None`):
+ A url to file, image, video, audio or website.
+ timestamp (`Optional[str]`, defaults to `None`):
+ The timestamp of the message, if None, it will be set to
+ current time.
+ **kwargs (`Any`):
+ Other attributes of the message.
+ """
+
+ ifroleisNone:
+ logger.warning(
+ "A new field `role` is newly added to the message. "
+ "Please specify the role of the message. Currently we use "
+ 'a default "assistant" value.',
+ )
+
+ super().__init__(
+ name=name,
+ content=content,
+ role=roleor"assistant",
+ url=url,
+ timestamp=timestamp,
+ **kwargs,
+ )
+ ifecho:
+ logger.chat(self)
+
+
+
+[docs]
+ defto_str(self)->str:
+"""Return the string representation of the message"""
+ returnf"{self.name}: {self.content}"
+[docs]
+classTht(MessageBase):
+"""The Thought message is used to record the thought of the agent to
+ help them make decisions and responses. Generally, it shouldn't be
+ passed to or seen by the other agents.
+
+ In our framework, we formulate the thought in prompt as follows:
+ - For OpenAI API calling:
+
+ .. code-block:: python
+
+ [
+ ...
+ {
+ "role": "assistant",
+ "name": "thought",
+ "content": "I should ..."
+ },
+ ...
+ ]
+
+ - For open-source models that accepts string as input:
+
+ .. code-block:: python
+
+ ...
+ {self.name} thought: I should ...
+ ...
+
+ We admit that there maybe better ways to formulate the thought. Users
+ are encouraged to create their own thought formulation methods by
+ inheriting `MessageBase` class and rewrite the `__init__` and `to_str`
+ function.
+
+ .. code-block:: python
+
+ class MyThought(MessageBase):
+ def to_str(self) -> str:
+ # implement your own thought formulation method
+ pass
+ """
+
+
+[docs]
+ def__init__(
+ self,
+ name:str,
+ content:Any,
+ url:Optional[Union[Sequence[str],str]]=None,
+ timestamp:Optional[str]=None,
+ host:str=None,
+ port:int=None,
+ task_id:int=None,
+ client:Optional[RpcAgentClient]=None,
+ x:dict=None,
+ **kwargs:Any,
+ )->None:
+"""A placeholder message, records the address of the real message.
+
+ Args:
+ name (`str`):
+ The name of who send the message. It's often used in
+ role-playing scenario to tell the name of the sender.
+ However, you can also only use `role` when calling openai api.
+ The usage of `name` refers to
+ https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models.
+ content (`Any`):
+ The content of the message.
+ role (`Literal["system", "user", "assistant"]`, defaults to "assistant"):
+ The role of the message, which can be one of the `"system"`,
+ `"user"`, or `"assistant"`.
+ url (`Optional[Union[list[str], str]]`, defaults to None):
+ A url to file, image, video, audio or website.
+ timestamp (`Optional[str]`, defaults to None):
+ The timestamp of the message, if None, it will be set to
+ current time.
+ host (`str`, defaults to `None`):
+ The hostname of the rpc server where the real message is
+ located.
+ port (`int`, defaults to `None`):
+ The port of the rpc server where the real message is located.
+ task_id (`int`, defaults to `None`):
+ The task id of the real message in the rpc server.
+ client (`RpcAgentClient`, defaults to `None`):
+ An RpcAgentClient instance used to connect to the generator of
+ this placeholder.
+ x (`dict`, defaults to `None`):
+ Input parameters used to call rpc methods on the client.
+ """# noqa
+ super().__init__(
+ name=name,
+ content=content,
+ url=url,
+ timestamp=timestamp,
+ **kwargs,
+ )
+ # placeholder indicates whether the real message is still in rpc server
+ self._is_placeholder=True
+ ifclientisNone:
+ self._stub:ResponseStub=None
+ self._host:str=host
+ self._port:int=port
+ self._task_id:int=task_id
+ else:
+ self._stub=call_in_thread(client,x,"_reply")
+ self._host=client.host
+ self._port=client.port
+ self._task_id=None
+
+
+ def__is_local(self,key:Any)->bool:
+ return(
+ keyinPlaceholderMessage.LOCAL_ATTRSornotself._is_placeholder
+ )
+
+ def__getattr__(self,__name:str)->Any:
+"""Get attribute value from PlaceholderMessage. Get value from rpc
+ agent server if necessary.
+
+ Args:
+ __name (`str`):
+ Attribute name.
+ """
+ ifnotself.__is_local(__name):
+ self.update_value()
+ returnMessageBase.__getattr__(self,__name)
+
+ def__getitem__(self,__key:Any)->Any:
+"""Get item value from PlaceholderMessage. Get value from rpc
+ agent server if necessary.
+
+ Args:
+ __key (`Any`):
+ Item name.
+ """
+ ifnotself.__is_local(__key):
+ self.update_value()
+ returnMessageBase.__getitem__(self,__key)
+
+
+[docs]
+ defupdate_value(self)->MessageBase:
+"""Get attribute values from rpc agent server immediately"""
+ ifself._is_placeholder:
+ # retrieve real message from rpc agent server
+ self.__update_task_id()
+ client=RpcAgentClient(self._host,self._port)
+ result=client.call_func(
+ func_name="_get",
+ value=json.dumps({"task_id":self._task_id}),
+ )
+ msg=deserialize(result)
+ status=msg.pop("__status","OK")
+ ifstatus=="ERROR":
+ raiseRuntimeError(msg.content)
+ self.update(msg)
+ # the actual value has been updated, not a placeholder any more
+ self._is_placeholder=False
+ returnself
f"Model Wrapper [{type(self).__name__}] doesn't "f"need to format the input. Please try to use the "f"model wrapper directly.",
- )
+ )
+
+
-[docs]
+[docs]classDashScopeChatWrapper(DashScopeWrapperBase):"""The model wrapper for DashScope's chat API, refer to https://help.aliyun.com/zh/dashscope/developer-reference/api-details
@@ -310,7 +321,7 @@
-[docs]
+[docs]classDashScopeImageSynthesisWrapper(DashScopeWrapperBase):"""The model wrapper for DashScope Image Synthesis API, refer to https://help.aliyun.com/zh/dashscope/developer-reference/quick-start-1
@@ -524,7 +535,7 @@
Source code for agentscope.models.dashscope_model
-[docs]
+[docs]classDashScopeTextEmbeddingWrapper(DashScopeWrapperBase):"""The model wrapper for DashScope Text Embedding API."""
@@ -628,7 +639,7 @@
Source code for agentscope.models.dashscope_model
-[docs]
+[docs]classDashScopeMultiModalWrapper(DashScopeWrapperBase):"""The model wrapper for DashScope Multimodal API, refer to https://help.aliyun.com/zh/dashscope/developer-reference/tongyi-qianwen-vl-api
@@ -770,7 +781,7 @@
+
def_register_default_metrics(self)->None:"""Register the default metrics for the model."""
@@ -159,6 +166,8 @@
Source code for agentscope.models.gemini_model
"The method `_register_default_metrics` must be implemented.",)
+
+[docs]deflist_models(self)->Sequence:"""List all available models for this API calling."""support_models=list(genai.list_models())
@@ -170,7 +179,8 @@
self.monitor=MonitorFactory.get_monitor()self.config_name=config_name
- logger.info(f"Initialize model [{config_name}]")
+ logger.info(f"Initialize model [{config_name}]")
+
-[docs]
+[docs]@classmethoddefget_wrapper(cls,model_type:str)->Type[ModelWrapperBase]:"""Get the specific model wrapper"""
@@ -331,7 +336,7 @@
-[docs]
+[docs]defupdate_monitor(self,**kwargs:Any)->None:"""Update the monitor with the given values.
diff --git a/en/_modules/agentscope/models/ollama_model.html b/en/_modules/agentscope/models/ollama_model.html
index 0d0b5c065..b31452268 100644
--- a/en/_modules/agentscope/models/ollama_model.html
+++ b/en/_modules/agentscope/models/ollama_model.html
@@ -57,15 +57,17 @@
-[docs]
+[docs]classPostAPIModelWrapperBase(ModelWrapperBase,ABC):"""The base model wrapper for the model deployed on the POST API."""model_type:str="post_api"
+
+
def_parse_response(self,response:dict)->ModelResponse:"""Parse the response json data into ModelResponse"""
@@ -260,7 +265,7 @@
Source code for agentscope.models.post_model
-[docs]
+[docs]classPostAPIChatWrapper(PostAPIModelWrapperBase):"""A post api model wrapper compatilble with openai chat, e.g., vLLM, FastChat."""
@@ -275,7 +280,7 @@
-[docs]
+[docs]classResponseParser:"""A class that contains several static methods to parse the response."""
-[docs]
+[docs]@classmethoddefto_dict(cls,response:ModelResponse)->ModelResponse:"""Parse the response text to a dict, and feed it into the `json`
@@ -193,7 +198,7 @@
Source code for agentscope.models.response
-[docs]
+[docs]@classmethoddefto_list(cls,response:ModelResponse)->ModelResponse:"""Parse the response text to a list, and feed it into the `json`
@@ -221,7 +226,7 @@
Source code for agentscope.models.response
-[docs]
+[docs]classResponseParsingError(Exception):"""Exception raised when parsing the response fails."""
@@ -234,6 +239,8 @@
Source code for agentscope.models.response
response:ModelResponse"""The response that fails to be parsed."""
+
Args: participants (`Sequence[AgentBase]`): The Sequence of participants in the msghub.
- announcement (`Optional[Union[list[dict], dict]]`, defaults to
- `None`):
+ announcement
+ (`Optional[Union[list[dict], dict]]`, defaults to `None`): The message that will be broadcast to all participants at the first without requiring response. """self.participants=participants
- self.announcement=announcement
+ self.announcement=announcement
+
def__enter__(self)->MsgHubManager:"""Will be called when entering the msghub."""
@@ -154,6 +161,8 @@
+[docs]defplaceholder(x:dict=None)->dict:r"""A placeholder that do nothing. Acts as a placeholder in branches that do not require any operations in flow control like if-else/switch """
- returnx
+ returnx
+[docs]def__init__(self,operators:Sequence[Operator])->None:r"""Initialize a Sequential pipeline.
@@ -357,7 +376,8 @@
Source code for agentscope.pipelines.pipeline
A Sequence of operators to be executed sequentially.
"""self.operators=operators
- self.participants=list(self.operators)
+ self.participants=list(self.operators)