agentscope.agent

The agent base class.

class AgentBase[source]

Bases: StateModule

Base class for asynchronous agents.

supported_hook_types: list[str] = ['pre_reply', 'post_reply', 'pre_print', 'post_print', 'pre_observe', 'post_observe']

Supported hook types for the agent base class.

__init__()[source]

Initialize the agent.

Return type:

None

id: str

The agent’s unique identifier, generated using shortuuid.

async observe(msg)[source]

Receive the given message(s) without generating a reply.

Parameters:

msg (Msg | list[Msg] | None) – The message(s) to be observed.

Return type:

None

async reply(*args, **kwargs)[source]

The main logic of the agent, which generates a reply based on the current state and input arguments.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

Msg

async print(msg, last=True, speech=None)[source]

The function to display the message.

Parameters:
  • msg (Msg) – The message object to be printed.

  • last (bool, defaults to True) – Whether this is the last one in streaming messages. For non-streaming message, this should always be True.

  • speech (AudioBlock | list[AudioBlock] | None, optional) – The audio content block(s) to be played along with the message.

Return type:

None

async __call__(*args, **kwargs)[source]

Call the reply function with the given arguments.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

Msg

async handle_interrupt(*args, **kwargs)[source]

The post-processing logic when the reply is interrupted by the user or something else.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

Msg

async interrupt(msg=None)[source]

Interrupt the current reply process.

Parameters:

msg (Msg | list[Msg] | None)

Return type:

None

register_instance_hook(hook_type, hook_name, hook)[source]

Register a hook to the agent instance, which only takes effect for the current instance.

Parameters:
  • hook_type (str) – The type of the hook, indicating where the hook is to be triggered.

  • hook_name (str) – The name of the hook. If the name is already registered, the hook will be overwritten.

  • hook (Callable) – The hook function.

Return type:

None

remove_instance_hook(hook_type, hook_name)[source]

Remove an instance-level hook from the agent instance.

Parameters:
  • hook_type (AgentHookTypes) – The type of the hook, indicating where the hook is to be triggered.

  • hook_name (str) – The name of the hook to remove.

Return type:

None

classmethod register_class_hook(hook_type, hook_name, hook)[source]

The universal function to register a hook to the agent class, which will take effect for all instances of the class.

Parameters:
  • hook_type (AgentHookTypes) – The type of the hook, indicating where the hook is to be triggered.

  • hook_name (str) – The name of the hook. If the name is already registered, the hook will be overwritten.

  • hook (Callable) – The hook function.

Return type:

None

classmethod remove_class_hook(hook_type, hook_name)[source]

Remove a class-level hook from the agent class.

Parameters:
  • hook_type (AgentHookTypes) – The type of the hook, indicating where the hook is to be triggered.

  • hook_name (str) – The name of the hook to remove.

Return type:

None

classmethod clear_class_hooks(hook_type=None)[source]

Clear all class-level hooks.

Parameters:

hook_type (AgentHookTypes, optional) – The type of the hook to clear. If not specified, all class-level hooks will be cleared.

Return type:

None

clear_instance_hooks(hook_type=None)[source]

If hook_type is not specified, clear all instance-level hooks. Otherwise, clear the specified type of instance-level hooks.

Parameters:

hook_type (str | Literal['pre_reply', 'post_reply', 'pre_print', 'post_print', 'pre_observe', 'post_observe'] | None)

Return type:

None

reset_subscribers(msghub_name, subscribers)[source]

Reset the subscribers of the agent.

Parameters:
  • msghub_name (str) – The name of the MsgHub that manages the subscribers.

  • subscribers (list[AgentBase]) – A list of agents that will receive the reply message from this agent via their observe method.

Return type:

None

remove_subscribers(msghub_name)[source]

Remove the msghub subscribers by the given msg hub name.

Parameters:

msghub_name (str) – The name of the MsgHub that manages the subscribers.

Return type:

None

disable_console_output()[source]

This function will disable the console output of the agent, e.g. in a production environment to avoid messy logs.

Return type:

None

set_console_output_enabled(enabled)[source]

Enable or disable the console output of the agent. E.g. in a production environment, you may want to disable the console output to avoid messy logs.

Parameters:

enabled (bool) – If True, enable the console output. If False, disable the console output.

Return type:

None

set_msg_queue_enabled(enabled, queue=None)[source]

Enable or disable the message queue for streaming outputs.

Parameters:
  • enabled (bool) – If True, enable the message queue to allow streaming outputs. If False, disable the message queue.

  • queue (Queue | None, optional) – The queue instance that will be used to initialize the message queue when enable is True.

Return type:

None

class ReActAgentBase[source]

Bases: AgentBase

The ReAct agent base class.

To support ReAct algorithm, this class extends the AgentBase class by adding two abstract interfaces: reasoning and acting, while supporting hook functions at four positions: pre-reasoning, post-reasoning, pre-acting, and post-acting by the _ReActAgentMeta metaclass.

supported_hook_types: list[str] = ['pre_reply', 'post_reply', 'pre_print', 'post_print', 'pre_observe', 'post_observe', 'pre_reasoning', 'post_reasoning', 'pre_acting', 'post_acting']

Supported hook types for the agent base class.

__init__()[source]

Initialize the ReAct agent base class.

Return type:

None

class ReActAgent[source]

Bases: ReActAgentBase

A ReAct agent implementation in AgentScope, which supports

  • Realtime steering

  • API-based (parallel) tool calling

  • Hooks around reasoning, acting, reply, observe and print functions

  • Structured output generation

finish_function_name: str = 'generate_response'

The name of the function used to generate structured output. Only registered when structured output model is provided in the reply call.

__init__(name, sys_prompt, model, formatter, toolkit=None, memory=None, long_term_memory=None, long_term_memory_mode='both', enable_meta_tool=False, parallel_tool_calls=False, knowledge=None, enable_rewrite_query=True, plan_notebook=None, print_hint_msg=False, max_iters=10, tts_model=None)[source]

Initialize the ReAct agent

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

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

  • model (ChatModelBase) – The chat model used by the agent.

  • formatter (FormatterBase) – The formatter used to format the messages into the required format of the model API provider.

  • toolkit (Toolkit | None, optional) – A Toolkit object that contains the tool functions. If not provided, a default empty Toolkit will be created.

  • memory (MemoryBase | None, optional) – The memory used to store the dialogue history. If not provided, a default InMemoryMemory will be created, which stores messages in a list in memory.

  • long_term_memory (LongTermMemoryBase | None, optional) – The optional long-term memory, which will provide two tool functions: retrieve_from_memory and record_to_memory, and will attach the retrieved information to the system prompt before each reply.

  • enable_meta_tool (bool, defaults to False) – If True, a meta tool function reset_equipped_tools will be added to the toolkit, which allows the agent to manage its equipped tools dynamically.

  • long_term_memory_mode (Literal[‘agent_control’, ‘static_control’, ‘both’], defaults to both) – The mode of the long-term memory. If agent_control, two tool functions retrieve_from_memory and record_to_memory will be registered in the toolkit to allow the agent to manage the long-term memory. If static_control, retrieving and recording will happen in the beginning and end of each reply respectively.

  • parallel_tool_calls (bool, defaults to False) – When LLM generates multiple tool calls, whether to execute them in parallel.

  • knowledge (KnowledgeBase | list[KnowledgeBase] | None, optional) – The knowledge object(s) used by the agent to retrieve relevant documents at the beginning of each reply.

  • enable_rewrite_query (bool, defaults to True) – Whether ask the agent to rewrite the user input query before retrieving from the knowledge base(s), e.g. rewrite “Who am I” to “{user’s name}” to get more relevant documents. Only works when the knowledge base(s) is provided.

  • plan_notebook (PlanNotebook | None, optional) – The plan notebook instance, allow the agent to finish the complex task by decomposing it into a sequence of subtasks.

  • print_hint_msg (bool, defaults to False) – Whether to print the hint messages, including the reasoning hint from the plan notebook, the retrieved information from the long-term memory and knowledge base(s).

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

  • tts_model (TTSModelBase | None optional) – The TTS model used by the agent.

Return type:

None

property sys_prompt: str

The dynamic system prompt of the agent.

async reply(msg=None, structured_model=None)[source]

Generate a reply based on the current state and input arguments.

Parameters:
  • msg (Msg | list[Msg] | None, optional) – The input message(s) to the agent.

  • structured_model (Type[BaseModel] | None, optional) – The required structured output model. If provided, the agent is expected to generate structured output in the metadata field of the output message.

Returns:

The output message generated by the agent.

Return type:

Msg

async observe(msg)[source]

Receive observing message(s) without generating a reply.

Parameters:

msg (Msg | list[Msg] | None) – The message or messages to be observed.

Return type:

None

async handle_interrupt(msg=None, structured_model=None)[source]

The post-processing logic when the reply is interrupted by the user or something else.

Parameters:
  • msg (Msg | list[Msg] | None, optional) – The input message(s) to the agent.

  • structured_model (Type[BaseModel] | None, optional) – The required structured output model.

Return type:

Msg

generate_response(**kwargs)[source]

Generate required structured output by this function and return it

Parameters:

kwargs (Any)

Return type:

ToolResponse

class UserInputData[source]

Bases: object

The user input data.

blocks_input: List[TextBlock | ImageBlock | AudioBlock | VideoBlock] = None

The text input from the user

structured_input: dict[str, Any] | None = None

The structured input from the user

__init__(blocks_input=None, structured_input=None)
Parameters:
Return type:

None

class UserInputBase[source]

Bases: object

The base class used to handle the user input from different sources.

abstract async __call__(agent_id, agent_name, *args, structured_model=None, **kwargs)[source]

The user input method, which returns the user input and the required structured data.

Parameters:
  • agent_id (str) – The agent identifier.

  • agent_name (str) – The agent name.

  • structured_model (Type[BaseModel] | None, optional) – A base model class that defines the structured input format.

  • args (Any)

  • kwargs (Any)

Returns:

The user input data.

Return type:

UserInputData

class TerminalUserInput[source]

Bases: UserInputBase

The terminal user input.

__init__(input_hint='User Input: ')[source]

Initialize the terminal user input with a hint.

Parameters:

input_hint (str)

Return type:

None

async __call__(agent_id, agent_name, *args, structured_model=None, **kwargs)[source]

Handle the user input from the terminal.

Parameters:
  • agent_id (str) – The agent identifier.

  • agent_name (str) – The agent name.

  • structured_model (Type[BaseModel] | None, optional) – A base model class that defines the structured input format.

  • args (Any)

  • kwargs (Any)

Returns:

The user input data.

Return type:

UserInputData

class StudioUserInput[source]

Bases: UserInputBase

The class that host the user input on the AgentScope Studio.

__init__(studio_url, run_id, max_retries=3, reconnect_attempts=3, reconnection_delay=1, reconnection_delay_max=5)[source]

Initialize the StudioUserInput object.

Parameters:
  • studio_url (str) – The URL of the AgentScope Studio.

  • run_id (str) – The current run identity.

  • max_retries (int, defaults to 3) – The maximum number of retries to get user input.

  • reconnect_attempts (int)

  • reconnection_delay (int)

  • reconnection_delay_max (int)

Return type:

None

async __call__(agent_id, agent_name, *args, structured_model=None)[source]

Get the user input from AgentScope Studio.

Parameters:
  • agent_id (str) – The identity of the agent.

  • agent_name (str) – The name of the agent.

  • structured_model (Type[BaseModel] | None, optional) – The base model class of the structured input.

  • args (Any)

Raises:

RuntimeError – Failed to get user input from AgentScope Studio.

Returns:

The user input.

Return type:

UserInputData

class UserAgent[source]

Bases: AgentBase

The class for user interaction, allowing developers to handle the user input from different sources, such as web UI, cli, and other interfaces.

__init__(name)[source]

Initialize the user agent with a name.

Parameters:

name (str)

Return type:

None

async reply(msg=None, structured_model=None)[source]

Receive input message(s) and generate a reply message from the user.

Parameters:
  • msg (Msg | list[Msg] | None, defaults to None) – The message(s) to be replied. If None, the agent will wait for user input.

  • structured_model (Type[BaseModel] | None, defaults to None) – A child class of pydantic.BaseModel that defines the structured output format. If provided, the user will be prompted to fill in the required fields.

Returns:

The reply message generated by the user.

Return type:

Msg

override_instance_input_method(input_method)[source]

Override the input method of the current UserAgent instance.

Parameters:

input_method (UserInputBase) – The callable input method, which should be an object of a class that inherits from UserInputBase.

Return type:

None

classmethod override_class_input_method(input_method)[source]

Override the input method of the current UserAgent class.

Parameters:

input_method (UserInputBase) – The callable input method, which should be an object of a class that inherits from UserInputBase.

Return type:

None

async handle_interrupt(*args, **kwargs)[source]

The post-processing logic when the reply is interrupted by the user or something else.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

Msg

async observe(msg)[source]

Observe the message(s) from the other agents or the environment.

Parameters:

msg (Msg | list[Msg] | None)

Return type:

None

class A2AAgent[source]

Bases: AgentBase

An A2A agent implementation in AgentScope, which supports

  • Communication with remote agents using the A2A protocol

  • Bidirectional message conversion between AgentScope and A2A formats

  • Task lifecycle management with streaming and polling

  • Artifact handling and status tracking

Note

Due to the limitation of A2A protocol. The A2AAgent class

  • Only support chatbot-scenario (a user and an assistant) interactions.

To support multi-agent interactions requires the server side to handle the name field in the A2A messages properly.

  • Does not support structured output in reply() method due to the lack

of structured output support in A2A protocol.

  • Stores observed messages locally and merges them with input messages

when reply() is called. Observed messages are cleared after processing.

__init__(agent_card, client_config=None, consumers=None, additional_transport_producers=None)[source]

Initialize the A2A agent instance by the given agent card.

Parameters:
  • agent_card (AgentCard) – The agent card that contains the information about the remote agent, such as its URL and capabilities.

  • client_config (ClientConfig | None, optional) – The configuration for the A2A client, including transport preferences and streaming options.

  • consumers (list[Consumer] | None, optional) – The list of consumers for handling A2A client events. These intercept request/response flows for logging, metrics, and security.

  • additional_transport_producers (dict[str, TransportProducer] | None, optional) – Additional transport producers for creating A2A clients with specific transport protocols.

Return type:

None

state_dict()[source]

Get the state dictionary of the A2A agent.

Returns:

The state dictionary containing the observed messages.

Return type:

dict

load_state_dict(state_dict, strict=True)[source]

Load the state dictionary into the module.

Parameters:
  • state_dict (dict) – The state dictionary to load.

  • strict (bool, defaults to True) – If True, raises an error if any key in the module is not found in the state_dict. If False, skips missing keys.

Raises:

KeyError – If a required key is missing in the state_dict when strict is True.

Return type:

None

async observe(msg)[source]

Receive the given message(s) without generating a reply.

The observed messages are stored and will be merged with the input messages when reply is called. After reply completes, the stored messages will be cleared.

Parameters:

msg (Msg | list[Msg] | None) – The message(s) to be observed. If None, no action is taken.

Return type:

None

async reply(msg=None, **kwargs)[source]

Send message(s) to the remote A2A agent and receive a response.

Note

This method merges any previously observed messages with the

input messages, sends them to the remote agent, and clears the observed messages after processing.

Note

The A2A protocol does not support structured output, so the structured_model parameter is not supported in this method.

Parameters:
  • msg (Msg | list[Msg] | None, optional) – The message(s) to send to the remote agent. Can be a single Msg, a list of Msgs, or None. If None, only observed messages will be sent. Defaults to None.

  • kwargs (Any)

Returns:

The response message from the remote agent. For tasks, this may be either a status update message or the final artifacts message, depending on the task state. If no messages are provided (both msg and observed messages are empty), returns a prompt message. If an error occurs during communication, returns an error message.

Return type:

Msg

async handle_interrupt(msg=None, structured_model=None)[source]

The post-processing logic when the reply is interrupted by the user or something else.

Parameters:
  • msg (Msg | list[Msg] | None)

  • structured_model (Type[BaseModel] | None)

Return type:

Msg