agentscope.agents

Import all agent related modules in the package.

class agentscope.agents.AgentBase(*args: tuple, **kwargs: dict)[源代码]

基类:Operator

Base class for all agents.

All agents should inherit from this class and implement the reply function.

__init__(name: str, sys_prompt: str | None = None, model_config_name: str | None = None, use_memory: bool = True, memory_config: dict | None = None, to_dist: DistConf | bool | None = False) None[源代码]

Initialize an agent from the given arguments.

参数:
  • name (str) – The name of the agent.

  • sys_prompt (Optional[str]) – The system prompt of the agent, which can be passed by args or hard-coded in the agent.

  • model_config_name (str, defaults to None) – The name of the model config, which is used to load model from configuration.

  • use_memory (bool, defaults to True) – Whether the agent has memory.

  • memory_config (Optional[dict]) – The config of memory.

  • to_dist (Optional[Union[DistConf, bool]], default to False) –

    The configurations passed to to_dist() method. Used in _AgentMeta, when this parameter is provided, the agent will automatically be converted into its distributed version. Below are some examples:

    # run as a sub process
    agent = XXXAgent(
        # ... other parameters
        to_dist=True,
    )
    
    # connect to an existing agent server
    agent = XXXAgent(
        # ... other parameters
        to_dist=DistConf(
            host="<ip of your server>",
            port=<port of your server>,
            # other parameters
        ),
    )
    

    See Tutorial for detail.

classmethod generate_agent_id() str[源代码]

Generate the agent_id of this agent instance

classmethod get_agent_class(agent_class_name: str) Type[AgentBase][源代码]

Get the agent class based on the specific agent class name.

参数:

agent_class_name (str) – the name of the agent class.

抛出:

ValueError – Agent class name not exits.

返回:

the AgentBase sub-class.

返回类型:

Type[AgentBase]

classmethod register_agent_class(agent_class: Type[AgentBase]) None[源代码]

Register the agent class into the registry.

参数:

agent_class (Type[AgentBase]) – the agent class to be registered.

reply(x: dict | None = None) dict[源代码]

Define the actions taken by this agent.

参数:

x (dict, defaults to None) – Dialog history and some environment information

返回:

The agent’s response to the input.

备注

Given that some agents are in an adversarial environment, their input doesn’t include the thoughts of other agents.

load_from_config(config: dict) None[源代码]

Load configuration for this agent.

参数:

config (dict) – model configuration

export_config() dict[源代码]

Return configuration of this agent.

返回:

The configuration of current agent.

load_memory(memory: Sequence[dict]) None[源代码]

Load input memory.

speak(content: str | dict) None[源代码]

Speak out the content generated by the agent.

observe(x: dict | Sequence[dict]) None[源代码]

Observe the input, store it in memory without response to it.

参数:

x (Union[dict, Sequence[dict]]) – The input message to be recorded in memory.

reset_audience(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.

参数:

audience (Sequence[AgentBase]) – The audience of this agent, which will be notified when this agent generates a response message.

clear_audience() None[源代码]

Remove the audience of this agent.

rm_audience(audience: Sequence[AgentBase] | AgentBase) None[源代码]

Remove the given audience from the Sequence

property agent_id: str

The unique id of this agent.

返回:

agent_id

返回类型:

str

to_dist(host: str = 'localhost', port: int | None = None, max_pool_size: int = 8192, max_timeout_seconds: int = 1800, local_mode: bool = True, lazy_launch: bool = True, launch_server: bool | None = None) AgentBase[源代码]

Convert current agent instance into a distributed version.

参数:
  • host (str, defaults to “localhost”) – Hostname of the rpc agent server.

  • port (int, defaults to None) – Port of the rpc agent server.

  • max_pool_size (int, defaults to 8192) – Only takes effect when host and port are not filled in. The max number of agent reply messages that the started agent server can accommodate. Note that the oldest message will be deleted after exceeding the pool size.

  • max_timeout_seconds (int, defaults to 1800) – Only takes effect when host and port are not filled in. Maximum time for reply messages to be cached in the launched agent server. Note that expired messages will be deleted.

  • local_mode (bool, defaults to True) – Only takes effect when host and port are not filled in. Whether the started agent server only listens to local requests.

  • lazy_launch (bool, defaults to True) – Only takes effect when host and port are not filled in. If True, launch the agent server when the agent is called, otherwise, launch the agent server immediately.

  • launch_server (bool, defaults to None) – This field has been deprecated and will be removed in future releases.

返回:

the wrapped agent instance with distributed functionality

返回类型:

AgentBase

class agentscope.agents.Operator[源代码]

基类:ABC

Abstract base class Operator defines a protocol for classes that implement callable behavior. The class is designed to be subclassed with an overridden __call__ method that specifies the execution logic for the operator.

class agentscope.agents.DialogAgent(*args: tuple, **kwargs: dict)[源代码]

基类:AgentBase

A simple agent used to perform a dialogue. Your can set its role by sys_prompt.

__init__(name: str, sys_prompt: str, model_config_name: str, use_memory: bool = True, memory_config: dict | None = None, prompt_type: PromptType | None = None) None[源代码]

Initialize the dialog agent.

参数:
  • name (str) – The name of the agent.

  • sys_prompt (Optional[str]) – The system prompt of the agent, which can be passed by args or hard-coded in the agent.

  • model_config_name (str) – The name of the model config, which is used to load model from configuration.

  • use_memory (bool, defaults to True) – Whether the agent has memory.

  • memory_config (Optional[dict]) – The config of memory.

  • (Optional[PromptType] (prompt_type)

  • to (defaults)

  • PromptType.LIST) – The type of the prompt organization, chosen from PromptType.LIST or PromptType.STRING.

reply(x: dict | None = None) dict[源代码]

Reply function of the agent. Processes the input data, generates a prompt using the current dialogue memory and system prompt, and invokes the language model to produce a response. The response is then formatted and added to the dialogue memory.

参数:

x (dict, defaults to None) – A dictionary representing the user’s input to the agent. This input is added to the dialogue memory if provided. Defaults to None.

返回:

A dictionary representing the message generated by the agent in response to the user’s input.

class agentscope.agents.DictDialogAgent(*args: tuple, **kwargs: dict)[源代码]

基类:AgentBase

An agent that generates response in a dict format, where user can specify the required fields in the response via specifying the parser

About parser, please refer to our [tutorial](https://modelscope.github.io/agentscope/en/tutorial/203-parser.html)

For usage example, please refer to the example of werewolf in examples/game_werewolf

__init__(name: str, sys_prompt: str, model_config_name: str, use_memory: bool = True, memory_config: dict | None = None, max_retries: int | None = 3) None[源代码]

Initialize the dict dialog agent.

参数:
  • name (str) – The name of the agent.

  • sys_prompt (Optional[str], defaults to None) – The system prompt of the agent, which can be passed by args or hard-coded in the agent.

  • model_config_name (str, defaults to None) – The name of the model config, which is used to load model from configuration.

  • use_memory (bool, defaults to True) – Whether the agent has memory.

  • memory_config (Optional[dict], defaults to None) – The config of memory.

  • max_retries (Optional[int], defaults to None) – The maximum number of retries when failed to parse the model output.

set_parser(parser: ParserBase) None[源代码]

Set response parser, which will provide 1) format instruction; 2) response parsing; 3) filtering fields when returning message, storing message in memory. So developers only need to change the parser, and the agent will work as expected.

reply(x: dict | None = None) dict[源代码]

Reply function of the agent. Processes the input data, generates a prompt using the current dialogue memory and system prompt, and invokes the language model to produce a response. The response is then formatted and added to the dialogue memory.

参数:

x (dict, defaults to None) – A dictionary representing the user’s input to the agent. This input is added to the dialogue memory if provided.

返回:

A dictionary representing the message generated by the agent in response to the user’s input. It contains at least a ‘speak’ key with the textual response and may include other keys such as ‘agreement’ if provided by the language model.

抛出:

json.decoder.JSONDecodeError – If the response from the language model is not valid JSON, it defaults to treating the response as plain text.

class agentscope.agents.TextToImageAgent(*args: tuple, **kwargs: dict)[源代码]

基类:AgentBase

A agent used to perform text to image tasks.

TODO: change the agent into a service.

__init__(name: str, model_config_name: str, use_memory: bool = True, memory_config: dict | None = None) None[源代码]

Initialize the text to image agent.

参数:
  • name (str) – The name of the agent.

  • model_config_name (str, defaults to None) – The name of the model config, which is used to load model from configuration.

  • use_memory (bool, defaults to True) – Whether the agent has memory.

  • memory_config (Optional[dict]) – The config of memory.

reply(x: dict | None = None) dict[源代码]

Define the actions taken by this agent.

参数:

x (dict, defaults to None) – Dialog history and some environment information

返回:

The agent’s response to the input.

备注

Given that some agents are in an adversarial environment, their input doesn’t include the thoughts of other agents.

class agentscope.agents.UserAgent(*args: tuple, **kwargs: dict)[源代码]

基类:AgentBase

User agent class

__init__(name: str = 'User', require_url: bool = False) None[源代码]

Initialize a UserAgent object.

参数:
  • name (str, defaults to “User”) – The name of the agent. Defaults to “User”.

  • require_url (bool, defaults to False) – Whether the agent requires user to input a URL. Defaults to False. The URL can lead to a website, a file, or a directory. It will be added into the generated message in field url.

reply(x: dict | None = None, required_keys: list[str] | str | None = None, timeout: int | None = None) dict[源代码]

Processes the input provided by the user and stores it in memory, potentially formatting it with additional provided details.

The method prompts the user for input, then optionally prompts for additional specifics based on the provided format keys. All information is encapsulated in a message object, which is then added to the object’s memory.

参数:
  • x (dict, defaults to None) – A dictionary containing initial data to be added to memory. Defaults to None.

  • required_keys (Optional[Union[list[str], str]], defaults to None) – Strings that requires user to input, which will be used as the key of the returned dict. Defaults to None.

  • timeout (Optional[int], defaults to None) – Raise TimeoutError if user exceed input time, set to None for no limit.

返回:

A dictionary representing the message object that contains the user’s input and any additional details. This is also stored in the object’s memory.

返回类型:

dict

speak(content: str | dict) None[源代码]

Speak the content to the audience.

class agentscope.agents.ReActAgent(*args: tuple, **kwargs: dict)[源代码]

基类:AgentBase

An agent class that implements the ReAct algorithm. More details refer to https://arxiv.org/abs/2210.03629.

Note this is an example implementation of ReAct algorithm in AgentScope. We follow the idea within the paper, but the detailed prompt engineering maybe different. Developers are encouraged to modify the prompt to fit their own needs.

__init__(name: str, model_config_name: str, service_toolkit: ServiceToolkit | None = None, sys_prompt: str = "You're a helpful assistant. Your name is {name}.", max_iters: int = 10, verbose: bool = True, **kwargs: Any) None[源代码]

Initialize the ReAct agent with the given name, model config name and tools.

参数:
  • name (str) – The name of the agent.

  • sys_prompt (str) – The system prompt of the agent.

  • model_config_name (str) – The name of the model config, which is used to load model from configuration.

  • service_toolkit (ServiceToolkit) – A ServiceToolkit object that contains the tool functions.

  • max_iters (int, defaults to 10) – The maximum number of iterations of the reasoning-acting loops.

  • verbose (bool, defaults to True) – Whether to print the detailed information during reasoning and acting steps. If False, only the content in speak field will be print out.

reply(x: dict | None = None) dict[源代码]

The reply function that achieves the ReAct algorithm. The more details please refer to https://arxiv.org/abs/2210.03629

class agentscope.agents.DistConf(host: str = 'localhost', port: int | None = None, max_pool_size: int = 8192, max_timeout_seconds: int = 1800, local_mode: bool = True, lazy_launch: bool = True)[源代码]

基类:dict

Distribution configuration for agents.

__init__(host: str = 'localhost', port: int | None = None, max_pool_size: int = 8192, max_timeout_seconds: int = 1800, local_mode: bool = True, lazy_launch: bool = True)[源代码]

Init the distributed configuration.

参数:
  • host (str, defaults to “localhost”) – Hostname of the rpc agent server.

  • port (int, defaults to None) – Port of the rpc agent server.

  • max_pool_size (int, defaults to 8192) – Max number of task results that the server can accommodate.

  • max_timeout_seconds (int, defaults to 1800) – Timeout for task results.

  • local_mode (bool, defaults to True) – Whether the started rpc server only listens to local requests.

  • lazy_launch (bool, defaults to True) – Only launch the server when the agent is called.

class agentscope.agents.RpcAgent(*args: tuple, **kwargs: dict)[源代码]

基类:AgentBase

A wrapper to extend an AgentBase into a gRPC Client.

__init__(name: str, host: str = 'localhost', port: int | None = None, agent_class: Type[AgentBase] | None = None, agent_configs: dict | None = None, max_pool_size: int = 8192, max_timeout_seconds: int = 1800, local_mode: bool = True, lazy_launch: bool = True, agent_id: str | None = None, connect_existing: bool = False) None[源代码]

Initialize a RpcAgent instance.

参数:
  • name (str) – the name of the agent.

  • host (str, defaults to localhost) – Hostname of the rpc agent server.

  • port (int, defaults to None) – Port of the rpc agent server.

  • agent_class (Type[AgentBase]) – the AgentBase subclass of the source agent.

  • agent_configs (dict) – The args used to initialize the agent, generated by _AgentMeta.

  • max_pool_size (int, defaults to 8192) – Max number of task results that the server can accommodate.

  • max_timeout_seconds (int, defaults to 1800) – Timeout for task results.

  • local_mode (bool, defaults to True) – Whether the started gRPC server only listens to local requests.

  • lazy_launch (bool, defaults to True) – Only launch the server when the agent is called.

  • agent_id (str, defaults to None) – The agent id of this instance. If None, it will be generated randomly.

  • connect_existing (bool, defaults to False) – Set to True, if the agent is already running on the agent server.

reply(x: dict | None = None) dict[源代码]

Define the actions taken by this agent.

参数:

x (dict, defaults to None) – Dialog history and some environment information

返回:

The agent’s response to the input.

备注

Given that some agents are in an adversarial environment, their input doesn’t include the thoughts of other agents.

observe(x: dict | Sequence[dict]) None[源代码]

Observe the input, store it in memory without response to it.

参数:

x (Union[dict, Sequence[dict]]) – The input message to be recorded in memory.

clone_instances(num_instances: int, including_self: bool = True) Sequence[AgentBase][源代码]

Clone a series of this instance with different agent_id and return them as a list.

参数:
  • num_instances (int) – The number of instances in the returned

  • list. (this method in the returned)

  • including_self (bool) – Whether to include the instance calling

  • list.

返回:

A list of agent instances.

返回类型:

Sequence[AgentBase]

stop() None[源代码]

Stop the RpcAgent and the rpc server.