agentscope.agentAgent
class Agent
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.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
name | str | 智能体标识,用于消息与日志。The agent identifier. |
system_prompt | str | 系统提示词;运行时可能动态追加指令。The agent's system prompt. Additional instructions may be appended to it dynamically during operation. |
model | ChatModelBase | 驱动推理与工具调用的聊天模型。The chat model/llm used for this agent. |
toolkit默认default None | Toolkit | None | 工具、MCP 与技能的统一注册表。The toolkit used for registering tools, MCPs and skills as the sole source. |
middlewares默认default None | list[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 None | AgentState | None | 会话状态;未提供时自动创建。The agent state. A new state will be created if not provided. |
offloader默认default None | Offloader | None | offloader(类型 `Offloader | None`)。The context offloader. If provided, the compressed context and tool result will be offloaded. |
model_config默认default None | ModelConfig | None | 备用模型与重试等模型级配置。The additional chat model configuration including fallback model and retries. |
context_config默认default None | ContextConfig | None | 上下文压缩与工具结果压缩配置。The context config for context compression and tool result compression. |
react_config默认default None | ReActConfig | None | 推理—行动循环配置。The config for the reasoning-acting loop. |
injection_config默认default None | InjectionConfig | 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. |
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]
流式回复输入消息,并逐个产出事件或消息。
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.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
inputs默认default None | Msg | 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 None | Type[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 False | bool | yield 最终消息(类型 `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. |
agentscope/agent/_agent.py:289–331reply
async def reply(inputs: Msg | list[Msg] | UserConfirmResultEvent | UserInterruptEvent | ExternalExecutionResultEvent | None = None, structured_schema: Type[BaseModel] | None = None) -> Msg
回复输入消息并返回最终消息。
Reply to the given inputs, consuming all streamed events.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
inputs默认default None | Msg | 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 None | Type[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. |
agentscope/agent/_agent.py:333–380observe
async def observe(msgs: Msg | list[Msg] | None = None) -> None
接收外部观察消息并写入上下文。
Receive external observation message(s) and save them into context.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
msgs默认default None | Msg | list[Msg] | None | 消息列表(类型 `Msg | list[Msg] | None`)。The msgs. |
agentscope/agent/_agent.py:382–385compress_context
async def compress_context(context_config: ContextConfig | None = None, instructions: HintBlock | None = None) -> None
在上下文超过阈值时压缩历史消息。
Compress the agent's context if the token count exceeds the threshold.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
context_config默认default None | ContextConfig | None | 上下文配置(类型 `ContextConfig | None`)。If provided, compress the context with the given context config. Otherwise, use the default context config in the agent. |
instructions默认default None | HintBlock | None | 指令(类型 `HintBlock | None`)。Optional hints or instructions injected into the compression context to guide the summarization behavior. |
agentscope/agent/_agent.py:387–441