AS AgentScopeAPI 手册 / API Reference
MISSION 00 · Ignition · 80 XP

点火Ignition

让一个 Agent 真正回答你Make an agent answer for real

类比Analog ChatGPT 的最小内核The smallest ChatGPT-style core 技能Skills Agent 运行时Agent runtime模型抽象Model abstraction状态与会话State & sessions生产意识Production readiness

任务简报Brief

一个客服机器人只需要完成一次可靠回答:接管用户消息、调用模型、把回复交给前端,并且前端能逐字渲染。

A support bot only needs one reliable turn: accept a user message, call the model, return the reply, and let the UI render it token by token.

所有花哨的 Agent 都从同一个循环开始:消息进入、模型推理、结果返回。这一关把变量压到最少,让你亲手确认 Agent 不是模型本身,而是包在模型外面的运行时。完成后你会看到 ReActConfig 如何给循环加上上限,以及流式事件为什么比解析字符串更适合做 UI。

Every ambitious agent starts with the same loop: a message goes in, the model reasons, a result comes back. This mission removes every extra variable so you can see that an agent is not the model; it is the runtime around the model. You will see how ReActConfig bounds the loop and why typed stream events beat parsing text in a UI.

学习目标Learning goals

  • 用 Agent / ReActAgent 构造可调用对象,并传入系统提示词。

    Build a callable agent with Agent / ReActAgent and a system prompt.

  • 用一次普通调用拿到 Msg,再用流式事件观察增量文本。

    Get a Msg from a normal call, then observe incremental text with streaming events.

  • 理解 max_iters 是安全阀,不是提示词。

    Understand that max_iters is a safety valve, not a prompt.

  • 跑通 check,拿到第一枚通行码。

    Run check and earn your first pass code.

核心概念Core concepts

Agent

把模型、提示词、工具和状态装进一个可调用对象;它负责循环,不负责生成权重。

Wraps a model, prompt, tools and state into a callable object; it owns the loop, not the weights.

双轨实现Build it twice

先完整跑通一条轨道,再切换重来。两条轨道写出同一种产物,方便直接对照行为。Run one track end to end, then switch and repeat. Both tracks write the same artifact so you can compare behavior directly.

当前轨道Current track
Python 2.0.11 轨道Track

把 workspace 根目录的 .venv-lab 当作解释器;在 lab/ 下运行 python lab.py doctor 确认 agentscope 版本。离线检查不需要任何 API Key。

Use the workspace .venv-lab interpreter; run python lab.py doctor under lab/ to confirm the agentscope version. Offline checks need no API key.

01

构造第一个 AgentBuild the first agent

Agent 接收模型、系统提示词和 ReActConfig。普通调用用 reply,它会返回完整的 Msg。

Agent takes a model, a system prompt and ReActConfig. Use reply for a normal call; it returns a complete Msg.

lab/missions/p0_ignition/mission.py
from agentscope.agent import Agent, ReActConfig
from agentscope.message import UserMsg

agent = Agent(
    name="ignition",
    system_prompt="You are a precise AgentScope tutor.",
    model=model,
    react_config=ReActConfig(max_iters=3),
)
reply = await agent.reply(UserMsg("user", "What did you use to answer me?"))
print(reply.get_text_content())
02

订阅流式事件Subscribe to stream events

reply_stream 产出类型化事件。只处理 TextBlockDeltaEvent 就能做打字机效果,不必解析半截字符串。

reply_stream yields typed events. Handle TextBlockDeltaEvent for a typewriter effect rather than parsing partial strings.

lab/missions/p0_ignition/mission.py
from agentscope.event import TextBlockDeltaEvent, ReplyEndEvent

async for event in agent.reply_stream(UserMsg("user", "Explain reply_stream.")):
    if isinstance(event, TextBlockDeltaEvent):
        print(event.delta, end="")
    elif isinstance(event, ReplyEndEvent):
        print("\n[done]")
03

离线判题Run the offline check

ScriptedModel 把回复写死,保证每次 check 的结论一致。检查会验证回复内容、模型调用次数和事件类型。

ScriptedModel hard-codes replies so every check is deterministic. The check validates the reply, model call count and event types.

shell
# 在 lab/ 目录下
python lab.py check p0

# 期望看到
# PASS CODE: AS-P0-7Q4M
运行判题Run the check
python lab.py check p0

运行 python lab.py run p0 可以看完整演示;加 --online 且配置了 OPENAI_API_KEY 时会改用真实模型。

Run python lab.py run p0 for the full demo; add --online with OPENAI_API_KEY to use a real model.

源码Source lab/missions/p0_ignition/mission.py

判题证明了什么What the check proves

  • Agent 在 max_iters=3 的 ReAct 循环里完成了回复The agent replied through a ReActConfig(max_iters=3) loop
  • reply_stream 发出了 TextBlockDeltaEvent 与 ReplyEndEventreply_stream emitted TextBlockDeltaEvent and ReplyEndEvent
  • 一次用户回合只调用模型一次One user turn called the model exactly once
Java 2.0.4 轨道Track

需要 JDK 17+ 与 Maven。首次编译会从 D:/maven/repository 或你本机的 Maven 仓库解析 agentscope-core。实验室所有检查都使用 FakeChatModel,不访问网络。

Requires JDK 17+ and Maven. The first compile resolves agentscope-core from your local Maven repository. Every lab check uses FakeChatModel and never touches the network.

01

构造 ReActAgentBuild a ReActAgent

Java 用 ReActAgent.builder(),调用是 call,返回 Msg。RuntimeContext 携带 session id,后续关卡会用它做状态持久化。

Java uses ReActAgent.builder(), call returns a Msg, and RuntimeContext carries the session id used later for persistence.

lab/java/src/main/java/lab/m0/P0Ignition.java
ReActAgent agent = ReActAgent.builder()
        .name("ignition")
        .sysPrompt("You are a precise AgentScope tutor.")
        .model(model)
        .maxIters(3)
        .build();

RuntimeContext context = RuntimeContext.builder()
        .sessionId("p0").userId("lab").build();

Msg reply = agent.call("What did you use to answer me?", context).block();
System.out.println(reply.getTextContent());
02

消费 Reactor 事件流Consume the Reactor event stream

streamEvents 返回 Flux<AgentEvent>。事件类型是枚举 AgentEventType,不会因为模型输出而改变。

streamEvents returns Flux<AgentEvent>. Event types are the AgentEventType enum and do not depend on model output.

lab/java/src/main/java/lab/m0/P0Ignition.java
streaming.streamEvents("Explain streamEvents.", context)
        .doOnNext(event -> System.out.println(event.getType().name()))
        .blockLast();
03

编译并判题Compile and check

exec:java 不会自动重新编译,先 compile 可以避免运行旧 class。检查会断言 TEXT_BLOCK_DELTA 与 AGENT_END 都存在。

exec:java does not recompile automatically; run compile first to avoid stale classes. The check asserts both TEXT_BLOCK_DELTA and AGENT_END are present.

shell
cd lab/java
mvn -q -o compile exec:java -Dexec.args="check p0"

# 期望看到
# PASS CODE: AS-P0-7Q4M
运行判题Run the check
cd lab/java && mvn -q -o compile exec:java -Dexec.args="check p0"

-o 表示离线模式;如果你本地还没缓存依赖,去掉 -o 让 Maven 下载一次。

-o means offline; remove it once to let Maven cache dependencies on a fresh machine.

源码Source lab/java/src/main/java/lab/m0/P0Ignition.java

判题证明了什么What the check proves

  • ReActAgent 在有界循环中返回 MsgReActAgent returned a Msg through a bounded loop
  • streamEvents 发出了 TEXT_BLOCK_DELTA 与 AGENT_ENDstreamEvents emitted TEXT_BLOCK_DELTA and AGENT_END
  • RuntimeContext 承载了 session idRuntimeContext carried the session id

Python ↔ Java 差异Python ↔ Java differences

  • Python 用 reply / reply_stream;Java 用 call / streamEvents(Flux)。语义一致,但 Java 需要自己订阅 Reactor。

    Python uses reply / reply_stream; Java uses call / streamEvents(Flux). Same semantics, but Java subscribes to Reactor explicitly.

  • Python 的事件是类(TextBlockDeltaEvent);Java 的事件类型是枚举(AgentEventType.TEXT_BLOCK_DELTA)。

    Python events are classes (TextBlockDeltaEvent); Java event types are enum constants (AgentEventType.TEXT_BLOCK_DELTA).

  • 两边都用 max_iters / maxIters 限制循环;不要用提示词祈祷模型停下。

    Both bound the loop with max_iters / maxIters; never rely on prompt wording to stop a runaway loop.

常见坑Pitfalls

  1. 把 max_iters 当成模型参数:它限制的是循环次数,不是 token 数,也不是超时。生产环境还要加超时和成本上限。

    Treating max_iters as a model parameter: it bounds loop iterations, not tokens or time. Add timeouts and cost caps in production.

  2. 在事件循环里同步等待:Python 用 await,Java 的 .block() 只适合 CLI/测试;Web 服务应返回 Flux 或异步结果。

    Blocking inside an event loop: Python uses await; Java .block() is for CLI/tests only. Web services should return Flux or async results.

  3. 忽略 AGENT_END / ReplyEndEvent:只处理 delta 会让 UI 无法判断何时结束,流式渲染会一直转圈。

    Ignoring AGENT_END / ReplyEndEvent: handling only deltas leaves the UI unable to know when to stop.

领取通行码Claim your pass code

先运行当前轨道的 check。CLI 会打印 PASS CODE、XP 与徽章。粘贴到这里;同一关在每条轨道可各领取一次。Run the check for the current track. The CLI prints PASS CODE plus the exact XP and badge. Paste it here; the same mission can be claimed once on each track.

记录到轨道Record on track

费曼复述Feynman recall

合上教程,用自己的话讲清机制。关键点覆盖 65%、篇幅 20%、结构 15%;60 分通过并一次性获得 20 XP。Explain the mechanism without looking. Coverage 65%, length 20%, structure 15%; 60 passes and earns +20 XP once.

用两三句话解释:Agent 和直接调用模型有什么区别?一次回复里发生了什么?

In two or three sentences: how is an Agent different from calling a model directly? What happens during one reply?

0 chars

查看参考答案Show the model answer

Agent 不是模型本身,而是包在模型外面的运行时:它接住消息,驱动 ReAct 循环,调用模型,并在需要时执行工具。max_iters 给循环加上限;流式接口把回复拆成类型化事件,UI 可以逐字渲染并准确知道何时结束。

An agent is not the model; it is the runtime around it. It accepts messages, drives the ReAct loop, calls the model and executes tools when needed. max_iters bounds the loop, and the streaming API turns a reply into typed events so a UI can render tokens and know exactly when the reply ends.

间隔复习Spaced review

首次领取后会在明天安排复习。按真实感受评分,下一次间隔会自适应。After the first claim a review is scheduled for tomorrow. Rate how it felt; the next interval adapts.

领取通行码后会自动安排第一次复习。Claim the pass code to schedule your first review.
基于官方固定版本源码静态生成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.