5.1 ReAct 的可见行动轨迹
本节把已有工具循环的可见文本、动作和结果分成 thought/action/observation。它不提取隐藏推理,也不要求供应商输出完整思维过程。
实现选择
ReActAgent 调用第三章 run,再为工具步骤整理轨迹;停止和失败保护继续生效。可见说明只用于观察与调试,不能证明模型真实内部思考与说明一致。
天气数据为固定教学值,FakeModel 决定两次查询和最终回答。增加 thought 日志不自动提高模型准确率;是否改善任务效果需要独立评测。
minagent/react.py
# file: minagent/react.py | write
from .loop import run
from .types import Step
class ReActAgent:
def __init__(self, model, registry, system="", max_steps=8):
self.model, self.registry, self.system, self.max_steps = model, registry, system, max_steps
def run(self, user_input):
result = run(self.model, self.registry, user_input, system=self.system, max_steps=self.max_steps)
steps = []
for step in result.steps:
if step.kind == "tool_call":
action, observation = step.detail.split(" -> ", 1)
msg = [m for m in result.messages if m.role == "assistant" and m.tool_calls][step.index]
if msg.content: steps.append(Step(step.index, "thought", msg.content))
steps.extend([Step(step.index, "action", action), Step(step.index, "observation", observation)])
else: steps.append(step)
result.steps = steps
return result
demo_react.py
# file: demo_react.py | write
# demo_react.py
from minagent.fake import FakeModel
from minagent.types import Message, ModelResponse, ToolCall
from minagent.tools import Tool, ToolRegistry
from minagent.loop import run, AgentLoopError
from minagent.react import ReActAgent
def weather(city: str) -> str:
data = {"北京": "晴 24°C", "上海": "多云 27°C"}
return data.get(city, "未知")
reg = ToolRegistry()
reg.add(Tool(name="weather", description="查询某城市当前天气",
parameters={"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]},
func=weather))
def thought(text: str, *calls: ToolCall) -> ModelResponse:
return ModelResponse(
message=Message(role="assistant", content=text, tool_calls=list(calls)),
stop_reason="tool_use" if calls else "end_turn",
)
model = FakeModel([
thought("Thought: 用户要比两城天气,先查北京。",
ToolCall(id="c1", name="weather", arguments={"city": "北京"})),
thought("Thought: 北京拿到了,再查上海。",
ToolCall(id="c2", name="weather", arguments={"city": "上海"})),
"北京晴 24°C,上海多云 27°C,两地都适合出行。",
])
agent = ReActAgent(model, reg, system="你是一个天气助手,先想再做。")
result = agent.run("对比北京和上海的天气")
for s in result.steps:
print(f"[{s.index}] {s.kind:<11} {s.detail}")
print(f"最终回答: {result.final}")
print(f"消息条数: {len(result.messages)}")
运行与练习
运行 demo_react.py,核对两次不同城市调用、各自结果与最终回答。练习注入 max_tokens,仍应受控失败;参考 TeachingModeTests.test_react_preserves_truncation_failure。
下载全卷项目 。在项目根运行本节 demo 文件;练习检查与故障用例见 tests/test_book.py、tests/test_extensions.py 和附录 B。
阅读导航:上一节:4.3 并行工具调用与结果合并 · 下一节:5.2 Plan-and-Solve:先出计划再执行 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。