《60天AI学习计划启动 | Day 39: Agent 执行过程可视化(思考 / 工具 / 观察 / 回答》
Day 39:Agent 执行过程可视化(思考 / 工具 / 观察 / 回答)
学习目标
- 理解 ReAct / Agent 在“思考→行动→观察→总结”的执行轨迹
- 会设计 一套前端展示结构(Timeline / Steps)
- 实现 简单的「Agent 调用步骤时间线」组件
核心知识点
-
1. Agent 步骤抽象
- 一次 Agent 调用可以拆成若干 Step:
thought:思考/理由action:调用的工具名 + 参数observation:工具执行结果摘要final_answer:最终回答
- 前端抽象:
export type AgentStepType = 'thought' | 'action' | 'observation' | 'final' export interface AgentStep { id: string type: AgentStepType content: string toolName?: string createdAt: number }
- 一次 Agent 调用可以拆成若干 Step:
-
2. 展示形态
- 时间线 / 步骤条:
- 按顺序展示:Step1 思考 → Step2 调用X工具 → Step3 观察 → ... → 最终回答
- 交互:
- 支持折叠「思考」内容(只展开有需要的)
- 在工具步骤里高亮工具名、参数/结果要点
- 时间线 / 步骤条:
实战作业(附代码)
- 作业 1:定义 Agent 执行轨迹类型
export type AgentStepType = 'thought' | 'action' | 'observation' | 'final'
export interface AgentStep {
id: string
type: AgentStepType
content: string
toolName?: string
createdAt: number
}
export interface AgentTrace {
id: string
question: string
steps: AgentStep[]
}
- 作业 2:简单时间线组件(React)
import React from 'react'
import type { AgentStep, AgentStepType } from './types'
const typeLabel: Record<AgentStepType, string> = {
thought: '思考',
action: '调用工具',
observation: '观察结果',
final: '最终回答'
}
const typeColor: Record<AgentStepType, string> = {
thought: '#9e9e9e',
action: '#2196f3',
observation: '#4caf50',
final: '#ff9800'
}
interface AgentTimelineProps {
steps: AgentStep[]
}
export const AgentTimeline: React.FC<AgentTimelineProps> = ({ steps }) => {
return (
<div style={{ borderLeft: '2px solid #eee', paddingLeft: 12 }}>
{steps.map((step) => (
<div key={step.id} style={{ marginBottom: 12, position: 'relative' }}>
<div
style={{
position: 'absolute',
left: -10,
top: 4,
width: 8,
height: 8,
borderRadius: '50%',
background: typeColor[step.type]
}}
/>
<div style={{ fontSize: 12, color: typeColor[step.type] }}>
{typeLabel[step.type]}
{step.toolName && ` · ${step.toolName}`}
</div>
<div style={{ fontSize: 12, whiteSpace: 'pre-wrap' }}>
{step.content}
</div>
<div style={{ fontSize: 10, color: '#aaa', marginTop: 2 }}>
{new Date(step.createdAt).toLocaleTimeString()}
</div>
</div>
))}
</div>
)
}
- 作业 3:将后端 Agent 日志映射为前端
AgentTrace(示例)
// 假设后端返回类似:
/*
{
"question": "...",
"trace": [
{ "type": "thought", "content": "需要先查天气...", "ts": 123 },
{ "type": "action", "tool": "get_weather", "content": "city=Beijing", "ts": 124 },
{ "type": "observation", "content": "返回温度 26℃", "ts": 125 },
{ "type": "final", "content": "北京现在 26℃,建议...", "ts": 126 }
]
}
*/
interface BackendStep {
type: AgentStepType
content: string
tool?: string
ts: number
}
export function mapBackendTrace(
question: string,
raw: BackendStep[]
): AgentTrace {
return {
id: crypto.randomUUID(),
question,
steps: raw.map((s, idx) => ({
id: `${idx}`,
type: s.type,
content: s.content,
toolName: s.tool,
createdAt: s.ts
}))
}
}
明日学习计划预告(Day 40)
- 主题:前端 AI SDK 抽象
- 方向:
- 把
useChat / useSSE / useRetry / useAgentTimeline等封装成一个小 SDK 结构 - 设计一个最小的
aiClient接口方便在不同项目里快速接入
- 把

浙公网安备 33010602011771号