图执行看板(Graph execution)
使用单节点状态和流式内容可视化多步图流水线
LangGraph 智能体不是黑盒。每个图都由按顺序或并行执行的命名节点组成:分类、调研、分析、综合。图执行卡片通过为每个节点呈现一张卡片,显示其状态、实时流式传输其内容并跟踪整个工作流的完成情况,使该流水线变得清晰可见。用户可以确切地看到智能体在做什么、它处于哪一步以及每一步产生了什么。
这种模式对于生产智能体特别有用,因为它将图结构转化为产品用户体验。你可以暴露 LangGraph 内部使用的相同检查点、节点名称、状态键和流元数据,而不是将运行视为单一的助手响应。
图节点如何映射到 UI 卡片
LangGraph 图定义了一系列节点,每个节点负责特定的任务。例如,调研流水线可能包括:
- Classify:对用户的查询进行分类
- Research:收集相关信息
- Analyze:从调研中得出结论
- Synthesize:产生最终打磨的回复
每个节点将其输出写入图状态中的特定键。在前端,你不需要对该映射进行硬编码,因为 useStream 会在每个节点运行时通过 stream.subgraphs 自动发现它,并为每个观察到的步骤公开一个 SubgraphDiscoverySnapshot:
// 节点会自动发现 — 无需硬编码列表
const graphNodes = [...stream.subgraphs.values()];
// 每个快照都带有节点名称和当前状态
graphNodes.forEach((node) => {
console.log(node.nodeName, node.status); // "classify", "running"
});使用 node.nodeName 作为进度条和卡片标题中的标签。将每个快照传递给 useMessages(stream, node) 以呈现节点范围的流式内容,而无需将 UI 与图状态键名称耦合。
这种映射成为图和 UI 之间的契约。后端作者可以有意识地添加、重命名或重新排序节点,而前端作者决定如何可视化每个状态键:状态徽章、Markdown 面板、表格、图表、跟踪视图或审批卡片。
设置 useStream
照常设置 useStream。你将使用的关键属性是 messages(用于对话)和 subgraphs(用于在当前运行中发现的图节点)。将每个发现的子图快照传递给选择器,以读取作用于该节点的消息。
INFO
代码示例使用 useStream<typeof myAgent> 来实现类型安全的流状态。请参阅用于 Python 或 JavaScript 后端的类型推断。
import { useStream } from "@langchain/react";
const AGENT_URL = "http://localhost:2024";
export function PipelineChat() {
const stream = useStream<typeof myAgent>({
apiUrl: AGENT_URL,
assistantId: "graph_execution_cards",
});
const graphNodes = [...stream.subgraphs.values()];
return (
<div>
<PipelineProgress nodes={graphNodes} isLoading={stream.isLoading} />
<NodeCardList nodes={graphNodes} stream={stream} isLoading={stream.isLoading} />
</div>
);
}<script setup lang="ts">
import { useStream } from "@langchain/vue";
const AGENT_URL = "http://localhost:2024";
const stream = useStream<typeof myAgent>({
apiUrl: AGENT_URL,
assistantId: "graph_execution_cards",
});
</script>
<template>
<div>
<PipelineProgress
:nodes="[...stream.subgraphs.value.values()]"
:is-loading="stream.isLoading.value"
/>
<NodeCardList
:nodes="[...stream.subgraphs.value.values()]"
:stream="stream"
:is-loading="stream.isLoading.value"
/>
</div>
</template><script lang="ts">
import { useStream } from "@langchain/svelte";
const AGENT_URL = "http://localhost:2024";
const stream = useStream<typeof myAgent>({
apiUrl: AGENT_URL,
assistantId: "graph_execution_cards",
});
</script>
<div>
<PipelineProgress nodes={[...stream.subgraphs.values()]} isLoading={stream.isLoading} />
<NodeCardList
nodes={[...stream.subgraphs.values()]}
{stream}
isLoading={stream.isLoading}
/>
</div>import { Component, computed } from "@angular/core";
import { injectStream } from "@langchain/angular";
const AGENT_URL = "http://localhost:2024";
@Component({
selector: "app-pipeline-chat",
template: `
<div>
<app-pipeline-progress
[nodes]="graphNodes()"
[isLoading]="stream.isLoading()"
/>
<app-node-card-list
[nodes]="graphNodes()"
[stream]="stream"
[isLoading]="stream.isLoading()"
/>
</div>
`,
})
export class PipelineChatComponent {
stream = injectStream<typeof myAgent>({
apiUrl: AGENT_URL,
assistantId: "graph_execution_cards",
});
graphNodes = computed(() => [...this.stream.subgraphs().values()]);
}将流式 Token 路由到节点
随着图的流式传输,每个发现的子图快照都会标识它所属的节点。将该快照传递给选择器 Hook 或组合式函数以读取限定于该节点的消息:
import { AIMessage } from "langchain";
import { useMessages, type AnyStream, type SubgraphDiscoverySnapshot } from "@langchain/react";
function NodeCard({
node,
stream,
}: {
node: SubgraphDiscoverySnapshot;
stream: AnyStream;
}) {
const messages = useMessages(stream, node);
const lastAIMessage = messages.find(AIMessage.isInstance);
const streamingContent = lastAIMessage?.text ?? "";
return <NodeCardBody node={node} content={streamingContent} />;
}第一个挂载的选择器会为该节点命名空间打开作用域订阅。当节点卡片卸载时,订阅会自动释放。
确定节点状态
每个发现的节点都带有其当前状态。直接使用 node.status;发现快照会报告 "pending"、"running"、"complete" 或 "error":
type NodeStatus = SubgraphDiscoverySnapshot["status"];
const status: NodeStatus = node.status;构建流水线进度条
顶部的水平进度条让用户可以鸟瞰整个流水线。每个步骤都是一个标记的线段,随着节点的完成而填满:
function PipelineProgress({
nodes,
isLoading,
}: {
nodes: SubgraphDiscoverySnapshot[];
isLoading: boolean;
}) {
const firstIncompleteIdx = nodes.findIndex((node) => node.status !== "complete");
return (
<div className="flex items-center gap-1">
{nodes.map((node, i) => {
const isRunning =
isLoading && node.status !== "complete" && firstIncompleteIdx === i;
const colors = {
pending: "bg-gray-200 text-gray-500",
running: "bg-blue-400 text-white animate-pulse",
complete: "bg-green-500 text-white",
error: "bg-red-500 text-white",
};
const status = isRunning ? "running" : node.status;
return (
<div key={node.id} className="flex items-center">
<div
className={`rounded-full px-3 py-1 text-xs font-medium ${colors[status]}`}
>
{node.nodeName}
</div>
{i < nodes.length - 1 && (
<div
className={`mx-1 h-0.5 w-6 ${
status === "complete" ? "bg-green-500" : "bg-gray-200"
}`}
/>
)}
</div>
);
})}
</div>
);
}构建可折叠 NodeCard 组件
每个节点都有自己的卡片,显示状态徽章、内容(流式或最终内容)以及用于长输出的可折叠正文:
function NodeCard({
node,
stream,
}: {
node: SubgraphDiscoverySnapshot;
stream: AnyStream;
}) {
const [open, setOpen] = useState(node.status === "running");
const messages = useMessages(stream, node);
const lastAIMessage = messages.find(AIMessage.isInstance);
useEffect(() => {
if (node.status === "running") setOpen(true);
if (node.status === "complete") setOpen(false);
}, [node.status]);
return (
<div className="rounded-lg border bg-white shadow-sm">
<button
onClick={() => setOpen(!open)}
className="flex w-full items-center justify-between p-4"
>
<div className="flex items-center gap-3">
<h3 className="font-semibold">{node.nodeName}</h3>
<StatusBadge status={node.status} />
</div>
<span className={open ? "rotate-90" : ""}>▶</span>
</button>
{open && (
<div className="border-t px-4 py-3">
<div className="prose prose-sm max-w-none">
{lastAIMessage?.text?.trim()
? <Markdown>{lastAIMessage.text}</Markdown>
: <p className="italic text-gray-500">Processing...</p>}
</div>
</div>
)}
</div>
);
}流式内容 vs. 已完成内容
节点卡片读取限定作用域的消息以获取流式和最终内容。这避免了假定图节点名称与其写入的状态键匹配(例如,在示例图中 do_research 写入 research):
| 来源 | 适用场景 |
|---|---|
useMessages(stream, node) | 呈现节点范围的流式和最终消息 |
stream.values | 使用实际的状态键读取整个图的状态,例如最终的 synthesis 字段 |
该模式为:在节点卡片中显示最新的作用域 AI 消息,并且仅在你有意需要图状态字段时才使用 stream.values。
因为作用域消息与生成节点相关联,所以 UI 可以支持并行图路径,而无需从消息顺序进行推测。每张卡片都会根据属于其节点的流事件进行更新,并且已完成的值仍然可以通过 stream.values 获得。
function NodeContent({ stream, node }: { stream: AnyStream; node: SubgraphDiscoverySnapshot }) {
const messages = useMessages(stream, node);
const content = messages.find(AIMessage.isInstance)?.text ?? "";
return <Markdown>{content}</Markdown>;
}TIP
流式内容可能包括部分 Token 或尚未完全格式化的 Markdown。如果你呈现 Markdown,请确保渲染器能够妥善处理不完整的语法(例如未闭合的粗体标记 **)。
完整代码组装
以下是将路由、状态检测和卡片呈现相结合的完整卡片列表:
function NodeCardList({
nodes,
stream,
isLoading,
}: {
nodes: SubgraphDiscoverySnapshot[];
stream: AnyStream;
isLoading: boolean;
}) {
const firstIncompleteIdx = nodes.findIndex((node) => node.status !== "complete");
return (
<div className="space-y-3">
{nodes.map((node, i) => {
const isComplete = node.status === "complete";
const isRunning = isLoading && !isComplete && firstIncompleteIdx === i;
if (!isComplete && !isRunning) return null;
return <NodeCard key={node.id} node={node} stream={stream} />;
})}
</div>
);
}使用案例
图执行卡片非常适合可见性至关重要的任何多步流水线:
- 调研流水线:分类 → 收集来源 → 分析 → 综合报告
- 内容生成:大纲 → 初稿 → 事实核查 → 编辑 → 发布
- 数据处理:提取 → 验证 → 转换 → 聚合 → 导出
- 代码生成:理解需求 → 规划架构 → 编写代码 → 审查 → 测试
- 决策工作流:收集上下文 → 评估选项 → 对替代方案评分 → 提出建议
处理动态流水线
并非所有图都具有固定的一组节点。某些流水线会根据输入添加或跳过节点。发现映射仅包含针对当前线程观察到的节点:
const activeNodes = [...stream.subgraphs.values()];这确保你的 UI 仅显示与当前执行相关的节点的卡片,从而避免出现空的占位符卡片。
INFO
如果你的图具有条件分支(例如对于简单的事实查询跳过“调研”),则跳过的节点将不会出现在 stream.subgraphs 中。你的流水线进度条可以仅呈现发现的节点,或者变暗显示没有匹配快照的预期节点。
最佳实践
- 从流中发现节点:根据
stream.subgraphs呈现卡片,而不是硬编码预期节点;条件或跳过的步骤在运行之前不会出现。 - 将状态键视为 UI 契约:决定哪些图输出应足够稳定以便前端呈现,并在图定义旁边记录这些键。
- 为节点卡片使用限定范围的消息:它们在节点流式传输时和完成后均可工作,而无需将 UI 卡片与状态键名称耦合。
- 自动折叠已完成的节点:在长流水线中,自动折叠已完成的卡片,以便用户可以专注于当前活动的步骤。
- 显示预估时间:如果你有每个节点耗时的历史数据,请显示预估时间以设定用户预期。
- 添加全局进度指示器:在流水线视图顶部补充一个整体进度条(例如“第 2 步,共 4 步”),以作为每节点卡片的补充。
- 逐节点处理错误:如果节点发生故障,请在其卡片中显示错误,而不要折叠整个流水线。其他节点可能仍会成功完成。
