AS AgentScopeAPI 手册 / API Reference
类class agentscope.agent

Agent

class Agent
源码Source agentscope/agent/_agent.py:118–3942

智能体是 AgentScope 2.x 的核心智能体实现,内部完成推理—行动循环、工具调用、上下文压缩与事件流。它把模型、工具、记忆和中间件组装成一个可持久化的会话执行器。位于 agentscope.agent 包。核心成员包括 reply_stream、reply、observe、compress_context。

The agent class. Declared in agentscope.agent.

核心精讲Deep dive

Agent:状态化的 ReAct 运行时Agent: the stateful ReAct runtime

Agent 是 AgentScope 2.x 的核心智能体实现,内部完成推理—行动循环、工具调用、上下文压缩与事件流。它把模型、工具、记忆和中间件组装成一个可持久化的会话执行器。

Agent is the core agent implementation in AgentScope 2.x. It owns the reasoning-acting loop, tool execution, context compression and event stream, assembling a model, tools, memory and middleware into a persistable session runtime.

  • 一个实例持有一个 AgentState;把同一 state 传给多次 reply 就能跨轮保留上下文。An instance owns an AgentState; passing the same state to multiple replies keeps context across turns.
  • reply 等待最终 Msg,reply_stream 逐事件产出文本增量、工具调用与结果,适合 UI 渲染。reply awaits the final Msg, while reply_stream yields text deltas, tool calls and results as events for UI rendering.
  • ReActConfig 控制迭代上限与中断行为,Middleware 在不改源码的前提下拦截各阶段。ReActConfig controls iteration limits and interruption, and Middleware intercepts each stage without touching source code.

最小可运行智能体Minimal runnable agent

import asyncio
import os

from agentscope.agent import Agent, ReActConfig
from agentscope.credential import OpenAICredential
from agentscope.formatter import OpenAIChatFormatter
from agentscope.message import UserMsg
from agentscope.model import OpenAIChatModel


async def main() -> None:
    model = OpenAIChatModel(
        credential=OpenAICredential(api_key=os.environ["OPENAI_API_KEY"]),
        model="gpt-4.1-mini",
        formatter=OpenAIChatFormatter(),
    )
    agent = Agent(
        name="assistant",
        system_prompt="You are a concise assistant.",
        model=model,
        react_config=ReActConfig(max_iters=8),
    )
    reply = await agent.reply(UserMsg("user", "Explain ReAct in one sentence."))
    print(reply.get_text_content())


asyncio.run(main())

构造器摘要Constructor Summary

构造器Constructor说明Description
def __init__(name: str, system_prompt: str, model: ChatModelBase, toolkit: Toolkit | None = None, middlewares: list[Mid…
创建智能体,绑定模型、工具、状态、中间件与各类配置。
Initialize the agent class in AgentScope.

方法摘要Method Summary

方法Method说明Description
async def reply_stream(inputs: Msg | list[Msg] | UserConfirmResultEvent | UserInterruptEvent | ExternalExecutionResultE…async
流式回复,逐事件产出文本增量、工具调用与结果。
Reply to the given inputs and stream agent events.
async def reply(inputs: Msg | list[Msg] | UserConfirmResultEvent | UserInterruptEvent | ExternalExecutionResultEvent |…async
执行一次完整回复并返回最终消息。
Reply to the given inputs, consuming all streamed events.
async def observe(msgs: Msg | list[Msg] | None = None) -> Noneasync
把外部消息写入上下文,不触发回复。
Receive external observation message(s) and save them into context.
async def compress_context(context_config: ContextConfig | None = None, instructions: HintBlock | None = None) -> Noneasync
按 token 阈值压缩上下文,可附带压缩指令。
Compress the agent's context if the token count exceeds the threshold.

构造器详情Constructor Detail

Agent

def __init__(name: str, system_prompt: str, model: ChatModelBase, toolkit: Toolkit | None = None, middlewares: list[MiddlewareBase] | None = None, state: AgentState | None = None, offloader: Offloader | None = None, model_config: ModelConfig | None = None, context_config: ContextConfig | None = None, react_config: ReActConfig | None = None, injection_config: InjectionConfig | None = None) -> None

初始化 AgentScope 中的智能体。

Initialize the agent class in AgentScope.

参数Parameters
名称Name类型Type说明Description
namestr智能体标识,用于消息与日志。The agent identifier.
system_promptstr系统提示词;运行时可能动态追加指令。The agent's system prompt. Additional instructions may be appended to it dynamically during operation.
modelChatModelBase驱动推理与工具调用的聊天模型。The chat model/llm used for this agent.
toolkit默认default NoneToolkit | None工具、MCP 与技能的统一注册表。The toolkit used for registering tools, MCPs and skills as the sole source.
middlewares默认default Nonelist[MiddlewareBase] | None在回复、推理、行动等阶段介入的中间件。Middlewares applied to the agent to modify its behavior without altering its source code. Supported hook points include: reply, reasoning, permission checking, acting, model call, context compression, and system prompt retrieval.
state默认default NoneAgentState | None会话状态;未提供时自动创建。The agent state. A new state will be created if not provided.
offloader默认default NoneOffloader | Noneoffloader(类型 `Offloader | None`)。The context offloader. If provided, the compressed context and tool result will be offloaded.
model_config默认default NoneModelConfig | None备用模型与重试等模型级配置。The additional chat model configuration including fallback model and retries.
context_config默认default NoneContextConfig | None上下文压缩与工具结果压缩配置。The context config for context compression and tool result compression.
react_config默认default NoneReActConfig | None推理—行动循环配置。The config for the reasoning-acting loop.
injection_config默认default NoneInjectionConfig | None时间、任务与上下文用量等运行时注入配置。The runtime state injection config, which controls how the time, (plan) tasks and context usage are injected into the context to help the agent better reason and act.
源码Source agentscope/agent/_agent.py:121–245

方法详情Method Detail

reply_stream

async def reply_stream(inputs: Msg | list[Msg] | UserConfirmResultEvent | UserInterruptEvent | ExternalExecutionResultEvent | None = None, structured_schema: Type[BaseModel] | None = None, yield_final_msg: bool = False) -> AsyncGenerator[AgentEvent | Msg, None]
async

流式回复输入消息,并逐个产出事件或消息。

Reply to the given inputs and stream agent events.

说明Notes

  • 注意:该行为受运行时配置或底层实现影响,建议结合对应源码与版本说明确认。Note: If requiring outside interaction for multiple tool calls and only receive partial confirmation or execution results, the agent won't re-send the requiring events for the unconfirmed or unexecuted tool calls.
参数Parameters
名称Name类型Type说明Description
inputs默认default NoneMsg | list[Msg] | UserConfirmResultEvent | UserInterruptEvent | ExternalExecutionResultEvent | None输入消息(类型 `Msg | list[Msg] | UserConfirmResultEvent | UserInterruptEvent | ExternalExecutionResultEvent | None`)。The inputs that trigger this reply. See :meth:`reply` for the full list of accepted variants.
structured_schema默认default NoneType[BaseModel] | None结构化输出模式(类型 `Type[BaseModel] | None`)。The Pydantic model class that the reply's structured output must conform to. See :meth:`reply` for details.
yield_final_msg默认default Falseboolyield 最终消息(类型 `bool`)。If yield the final reply message. When requiring structured output, use this option to get the final message, and access it via the `structured_output` attribute.
返回Returns AsyncGenerator[AgentEvent | Msg, None]
以异步流的形式返回AgentEvent|消息,None。`AgentEvent | Msg`:
源码Source agentscope/agent/_agent.py:289–331

reply

async def reply(inputs: Msg | list[Msg] | UserConfirmResultEvent | UserInterruptEvent | ExternalExecutionResultEvent | None = None, structured_schema: Type[BaseModel] | None = None) -> Msg
async

回复输入消息并返回最终消息。

Reply to the given inputs, consuming all streamed events.

参数Parameters
名称Name类型Type说明Description
inputs默认default NoneMsg | list[Msg] | UserConfirmResultEvent | UserInterruptEvent | ExternalExecutionResultEvent | None触发回复的消息、外部执行结果或中断事件。The inputs that trigger this reply. It can be: - a single `Msg` or a list of `Msg` objects to start a new reply, - a `UserConfirmResultEvent` or `ExternalExecutionResultEvent` to continue from the outside interaction required by the previous reply, - a `UserInterruptEvent` to abort a parked reply — the agent closes all pending tool calls with an interrupted tool result and ends the reply without entering the reasoning-acting loop, - `None` if there is nothing new to feed in (e.g. just continue from the current state).
structured_schema默认default NoneType[BaseModel] | None约束结构化输出的 Pydantic 模型。The Pydantic model class that the reply's structured output must conform to, with the validated result carried on the final message's `structured_output` attribute as a dict.
返回Returns Msg
最终回复消息,包含文本、用量与可选的结构化结果。`Msg`:
源码Source agentscope/agent/_agent.py:333–380

observe

async def observe(msgs: Msg | list[Msg] | None = None) -> None
async

接收外部观察消息并写入上下文。

Receive external observation message(s) and save them into context.

参数Parameters
名称Name类型Type说明Description
msgs默认default NoneMsg | list[Msg] | None消息列表(类型 `Msg | list[Msg] | None`)。The msgs.
返回Returns None
无返回值。No value is returned.
源码Source agentscope/agent/_agent.py:382–385

compress_context

async def compress_context(context_config: ContextConfig | None = None, instructions: HintBlock | None = None) -> None
async

在上下文超过阈值时压缩历史消息。

Compress the agent's context if the token count exceeds the threshold.

参数Parameters
名称Name类型Type说明Description
context_config默认default NoneContextConfig | None上下文配置(类型 `ContextConfig | None`)。If provided, compress the context with the given context config. Otherwise, use the default context config in the agent.
instructions默认default NoneHintBlock | None指令(类型 `HintBlock | None`)。Optional hints or instructions injected into the compression context to guide the summarization behavior.
返回Returns None
无返回值。No value is returned.
源码Source agentscope/agent/_agent.py:387–441
基于官方固定版本源码静态生成Generated from pinned official sources · Python 2.0.11 · Java 2.0.4
签名与文档为静态抽取;如有疑问请以源码为准。Signatures and docs are extracted statically; verify against the source when in doubt.