agentscope.agent

智能体基类。

class AgentBase[source]

基础类: StateModule

异步智能体的基类。

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

智能体基类支持的钩子类型。

__init__()[source]

初始化智能体。

Return type:

id: str

该智能体的唯一标识符,使用shortuuid生成。

async observe(msg)[source]

接收给定的消息,但不生成回复。

Parameters:

消息 (Msg | list[Msg] | None) – 需要被观察的消息(或多条消息)。

Return type:

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

智能体的主要逻辑,根据当前状态和输入参数生成回复。

Parameters:
  • 参数 (任意类型)

  • kwargs (任何)

Return type:

消息

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

显示消息内容的函数。

Parameters:
  • msg (Msg) – 需要打印的消息对象。

  • last (bool, 默认为 True) – 是否为流式消息中的最后一条。对于非流式消息,此值应始终为 True

Return type:

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

使用给定参数调用reply函数。

Parameters:
  • 参数 (任意类型)

  • kwargs (任何)

Return type:

消息

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

当回复被用户或其他事物打断时的后处理逻辑。

Parameters:
  • 参数 (任意类型)

  • kwargs (任何)

Return type:

消息

async interrupt(msg=None)[source]

中断当前回复流程。

Parameters:

消息 (Msg | 列表[Msg] | 空值)

Return type:

register_instance_hook(hook_type, hook_name, hook)[source]

注册一个钩子到智能体实例,该钩子仅对当前实例生效。

Parameters:
  • hook_type (str) – hook的类型,指示该hook将在何处被触发。

  • hook_name (str) – hook 的名称。如果该名称已被注册,该hook将被覆盖。

  • hookCallable) – 钩子函数。

Return type:

remove_instance_hook(hook_type, hook_name)[source]

从智能体实例中移除一个实例级别的钩子。

Parameters:
  • hook_type (AgentHookTypes) – 钩子类型,表示钩子将在何处被触发。

  • hook_name (str) - 要移除的钩子名称。

Return type:

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

为智能体类注册钩子的通用函数,它将对该类的所有实例生效。

Parameters:
  • hook_type (AgentHookTypes) – 钩子类型,表示钩子触发的位置。

  • hook_name (str) – hook 的名称。如果该名称已被注册,该hook将被覆盖。

  • hook (Callable) – hook函数。

Return type:

classmethod remove_class_hook(hook_type, hook_name)[source]

从智能体类别中移除类层级的挂钩。

Parameters:
  • hook_type (AgentHookTypes) – 钩子类型,表示钩子将触发的位置。

  • hook_name (str) – 要移除的钩子的名称。

Return type:

classmethod clear_class_hooks(hook_type=None)[source]

清除所有类级别的钩子。

Parameters:

hook_type (AgentHookTypes, optional) – 需要清除的钩子类型。若未指定,将清除所有 类级别的钩子。

Return type:

clear_instance_hooks(hook_type=None)[source]

如果未指定 hook_type,则清除所有实例级别的钩子。 否则,清除指定类型的实例级别钩子。

Parameters:

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

Return type:

reset_subscribers(msghub_name, subscribers)[source]

重置智能体的订阅者。

Parameters:
  • msghub_name (str) – 用于管理订阅者的消息中心名称。

  • subscribers (list[AgentBase]) – 一个智能体列表,这些智能体将通过其observe方法接收来自本智能体的回复消息。

Return type:

remove_subscribers(msghub_name)[source]

根据给定的消息中心名称移除该中心的订阅者。

Parameters:

msghub_name (str) – 管理订阅者的MsgHub名称。

Return type:

disable_console_output()[source]

此功能将禁用智能体的控制台输出,例如在生产环境中以避免混乱的日志。

Return type:

class ReActAgentBase[source]

基类: AgentBase

ReAct智能体基类。

为支持ReAct算法,该类通过添加两个抽象接口:reasoning(推理)和acting(行动),同时借助_ReActAgentMeta元类支持四个位置的钩子函数:pre-reasoning(推理前)、post-reasoning(推理后)、pre-acting(行动前)以及post-acting(行动后)。

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']

智能体基类支持的钩子类型。

__init__()[source]

初始化 ReAct 智能体的基类。

Return type:

class ReActAgent[source]

基类:ReActAgentBase

一款在AgentScope中实现的ReAct智能体,它支持

  • 实时引导

  • 基于API(并行)工具调用

  • 围绕推理、行动、回复、观察和打印功能的钩子方法

  • 结构化输出生成

finish_function_name: str = 'generate_response'

用于完成回复并返回给用户的函数名称。

__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, max_iters=10)[source]

初始化 ReAct 智能体

Parameters:
  • name (str) – 智能体的名称。

  • sys_prompt (str) – 智能体的系统提示。

  • model (ChatModelBase) – 智能体使用的聊天模型。

  • formatter (FormatterBase) – 用于将消息格式化为模型API提供者所需格式的格式化工具。

  • 工具包 (Toolkit | None, 可选) – 一个包含工具函数的Toolkit对象。如果未提供,将创建一个默认的空Toolkit

  • memory (MemoryBase | None, 可选参数) – 用于存储对话历史的记忆模块。若未提供, 将创建一个默认的InMemoryMemory,该模块会在内存中以列表形式存储消息。

  • long_term_memory (LongTermMemoryBase | None, optional) – 可选的长时期记忆模块,将提供两个工具 函数:retrieve_from_memoryrecord_to_memory,并 在每次回复前将检索到的信息附加到系统提示中。

  • enable_meta_tool (bool, 默认为 False) – 如果为 True,一个元工具函数 reset_equipped_tools 将被添加到工具包中,使智能体能够动态管理其所装备的工具。

  • long_term_memory_mode (Literal[‘agent_control’, ‘static_control’, ‘both’], 默认为 both) – 长期记忆的模式。如果选择 agent_control,则会注册两个工具函数 retrieve_from_memoryrecord_to_memory 到工具包中,以允许智能体自主管理长期记忆。如果选择 static_control,则记忆的检索和记录将分别在每次回复的开始和结束时自动进行。

  • parallel_tool_calls (bool, 默认为 False) – 当LLM生成多个工具调用时,是否并行执行它们。

  • max_iters (int, 默认值为 10) - 推理-行动循环的最大迭代次数。

Return type:

property sys_prompt: str

智能体的动态系统提示。

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

根据当前状态和输入参数生成回复。

Parameters:
  • msg (Msg | list[Msg] | None, 可选) – 输入给智能体的消息。

  • structured_model (Type[BaseModel] | None, 可选参数) – 所需要的结构化输出模型。如果提供,该智能体将预期在输出消息的metadata字段中生成结构化输出。

Returns:

智能体生成的输出消息。

Return type:

消息

async observe(msg)[source]

接收观察消息而不生成回复

Parameters:

消息 (Msg | list[Msg] | None) – 待观察的一条或多条消息。

Return type:

async handle_interrupt(_msg=None)[source]

当回复被用户或其他事物打断时的后处理逻辑。

Parameters:

_msg (Msg | list[Msg] | None)

Return type:

消息

generate_response(response, **kwargs)[source]

生成一个响应。请注意,只有输入参数response是 对其他部分可见的,你应当将所有的必要信息 包含在response参数中。

Parameters:
  • response (str) – 您对用户的响应。

  • kwargs (任何)

Return type:

工具响应

class UserInputData[source]

基础:object

用户输入数据。

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

用户的文本输入

structured_input: dict[str, Any] | None = None
可以识别用户消息中的变量引用(如 `${var_name}`),并自动用指定的变量值进行替换。
  • *args and **kwargs: 参数列表和参数字典。

  • msg_to_prompt: 一个消息处理器,用于将消息字典转换为代理输入提示,通过指定 func: agentscope.prompt 来使用。

  • 模型:来自 transformers, openai, zhipuai 等等的特定模型实例,通过 agentscope API 实例化。

  • requires (可选): 一个字符串列表,用于指定智能体所需的环境变量。如果这些变量未设置,系统将提示用户进行配置。

  • 示例:以下是一个简单的 agentscope 智能体配置:

    model_config = {
        "config_name": "gpt-4",
        "model_type": "openai",
        "model_name": "gpt-4",
        "api_key": os.environ.get("OPENAI_API_KEY"),
    }
    
    agent = {
        "name": "Assistant",
        "model": model_config,
        "prompt": "你是一个乐于助人的助手。"
    }
    

    🤖 智能体

    智能体是与用户或其他智能体交互的实体,接收消息并生成回复。

    内置智能体

    • DialogAgent: 基本智能体,用于生成对输入消息的回复。
    • UserAgent: 模拟用户,从标准输入中获取用户输入作为回复。
    • TextToImageAgent: 使用模型生成输入文本所描述的图像。

    智能体执行流程

    智能体执行流程图

    1. 消息接收: 智能体收到来自用户或其他智能体的消息。
    2. 消息处理: 使用 prompt_engine 构建输入提示。
    3. 模型调用: 智能体使用指定的模型生成回复。
    4. 回复格式化: 智能体将生成的回复格式化为消息对象。

    💬 消息

    消息是在智能体和用户或其他智能体间传递的数据单元。

    消息类型

    • Msg: 所有消息类型的基类。
    • ThtUserMessage: 表示来自用户的消息。
    • ThtAssistantMessage: 表示来自智能体的消息。
    • ThtSystemMessage: 表示来自系统的消息。

    消息字段

    • name: 消息发送者的名称。
    • content: 消息的内容。
    • url: 消息的链接(如果有)。
    • timestamp: 消息的时间戳。

    🚀 快速开始

    请按照以下步骤启动您的第一个 agentscope 应用:

    import agentscope
    from agentscope.agents import DialogAgent, UserAgent
    from agentscope.message import Msg
    
    # 初始化 agentscope
    agentscope.init(
        project="My First Agent",
        api_key="your_api_key_here"
    )
    
    # 创建智能体
    assistant_agent = DialogAgent(name="Assistant", model_config=model_config)
    user_agent = UserAgent()
    
    # 开始对话
    msg = Msg("user", "你好!")
    while True:
        response = assistant_agent.reply(msg)
        print(f"{response['name']}: {response['content']}")
        msg = user_agent.reply(response)
    

    🧩 模块

    • agents: 智能体类,例如 DialogAgent 和 UserAgent。
    • message: 消息类定义。
    • prompt: 提示引擎,用于构建智能体的输入提示。
    • utils: 实用工具函数。

    📖 文档

    完整的文档和教程可在 https://docs.agentscope.cn 找到。

    🤝 贡献

    欢迎贡献代码、问题报告和功能建议!请阅读我们的 贡献指南 以开始。

    📄 许可证

    此项目采用 MIT 许可证。详情请见 LICENSE 文件。

    🙏 致谢

    感谢所有为 agentscope 做出贡献的开发者和用户!

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

    class UserInputBase[source]

    基础:object

    用于处理来自不同来源用户输入的基类。

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

    用户输入方法,返回用户输入以及所需的结构化数据。

    Parameters:
    • agent_id (str) – 智能体标识符。

    • agent_name (str) – 智能体名称。

    • structured_model (Type[BaseModel] | None, 可选参数) – 一个基础模型类,用于定义结构化输入格式。

    • 参数 (任意类型)

    • kwargs (任何)

    Returns:

    用户输入数据。

    Return type:

    用户输入数据

    class TerminalUserInput[source]

    Bases: UserInputBase

    终端用户输入。

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

    初始化终端用户输入并附带提示。

    Parameters:

    input_hint (str)

    Return type:

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

    处理来自终端的用户输入。

    Parameters:
    • agent_id (str) – 智能体标识符。

    • agent_name (str) – 智能体名称。

    • structured_model (Type[BaseModel] | None, optional) – 一个定义结构化输入格式的基模型类。

    • 参数 (任意类型)

    • kwargs (任何)

    Returns:

    用户输入数据。

    Return type:

    用户输入数据

    class StudioUserInput[source]

    基类: UserInputBase

    在AgentScope Studio中承载用户输入的类。

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

    初始化 StudioUserInput 对象。

    Parameters:
    • studio_url (str) – AgentScope Studio 的 URL 地址。

    • run_id (str) – 当前运行标识。

    • max_retries (int, 默认值为 3) – 获取用户输入的最大重试次数。

    • reconnect_attempts (int)

    • reconnection_delay (int)

    • reconnection_delay_max (int)

    Return type:

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

    从AgentScope Studio获取用户输入。

    Parameters:
    • agent_id (str) – 智能体的标识。

    • agent_name (str) – 智能体的名称。

    • structured_model (Type[BaseModel] | None, 可选) – 结构化输入的基础模型类。

    • 参数 (任意类型)

    Raises:

    运行时错误 – 未能从AgentScope Studio获取用户输入。

    Returns:

    用户输入。

    Return type:

    用户输入数据

    class UserAgent[source]

    基类: AgentBase

    用于用户交互的类,允许开发者处理来自不同源的用户输入,例如 Web 界面、命令行以及其他接口。

    __init__(name)[source]

    使用名称初始化用户智能体。

    Parameters:

    名称 (str)

    Return type:

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

    接收输入消息并从用户处生成回复消息。

    Parameters:
    • msg (Msg | list[Msg] | None, 默认为 None) – 需要回复的消息。如果为 None,智能体将等待用户输入。

    • structured_model (Type[BaseModel] | None, 默认为 None) – 一个 pydantic.BaseModel 的子类,用于定义结构化输出格式。若提供该参数,将提示用户填写必填字段。

    Returns:

    用户生成的回复消息。

    Return type:

    消息

    override_instance_input_method(input_method)[source]

    重写当前用户智能体实例的输入方法。

    Parameters:

    input_method (UserInputBase) – 可调用的输入方法,应为继承自 UserInputBase 类的对象。

    Return type:

    classmethod override_class_input_method(input_method)[source]

    重写当前UserAgent类的输入方法。

    Parameters:

    input_method (UserInputBase) – 可调用的输入方法,应为继承自 UserInputBase 的类的对象。

    Return type:

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

    当回复被用户或其他事物打断时的后处理逻辑。

    Parameters:
    • 参数 (任意类型)

    • kwargs (任何)

    Return type:

    消息

    async observe(msg)[source]

    观察来自其他智能体或环境的消息。

    Parameters:

    消息 (Msg | 列表[Msg] | 空值)

    Return type: