langgraph-graph-api
БесплатноБез исполняемых скриптовНе проверен使用 StateGraph、节点、边、START/END 节点和 Command API 构建图,结合控制流与状态更新
от majiayu000★ 31 звезда на GitHubОб этом скилле
langgraph-graph-api (JavaScript/TypeScript)
name: langgraph-graph-api description: 使用 StateGraph、节点、边、START/END 节点和 Command API 构建图,结合控制流与状态更新
概述
LangGraph Graph API 允许您将 Agent 工作流定义为由节点(函数)和边(控制流)组成的有向图。这提供了对 Agent 编排的细粒度控制。
核心组件:
- StateGraph:构建有状态图的主要类
- 节点:执行工作并更新状态的函数
- 边:定义执行顺序(静态或条件)
- START/END:标记图入口和出口点的特殊节点
- Command:结合状态更新与动态路由
决策表:边类型
| 需求 | 边类型 | 何时使用 |
|---|---|---|
| 始终转到同一节点 | addEdge() |
固定、确定性流 |
| 基于状态路由 | addConditionalEdges() |
动态分支逻辑 |
| 扩散到多个节点 | Send API |
Map-reduce、并行执行 |
| 更新状态并路由 | Command |
在单个节点中组合逻辑 |
核心概念
1. 图执行模型
LangGraph 使用受 Google Pregel 启发的消息传递模型:
- 执行以超级步(离散迭代)进行
- 并行节点属于同一超级步
- 顺序节点属于不同的超级步
- 当所有节点不活跃且没有消息在传输时,图结束
2. 节点
节点是异步函数,它们:
- 接收当前状态作为输入
- 执行计算或副作用
- 返回状态更新(部分或全部)
const myNode = async (state: State): Promise<Partial<State>> => {
// 节点只是异步函数!
return { key: "updated_value" };
};
3. 边
| 边类型 | 描述 | 示例 |
|---|---|---|
| 静态 | 始终路由到同一节点 | addEdge("A", "B") |
| 条件 | 基于状态/逻辑路由 | addConditionalEdges("A", router) |
| 动态 (Send) | 扩散到多个节点 | new Send("worker", {...}) |
| Command | 状态更新 + 路由 | new Command({ goto: "B" }) |
4. 特殊节点
- START:图的入口点(虚拟节点)
- END:终端节点(图停止)
代码示例
带静态边的基本图
import { StateGraph, StateSchema, START, END } from "@langchain/langgraph";
import { z } from "zod";
// 1. 定义状态
const State = new StateSchema({
input: z.string(),
output: z.string(),
});
// 2. 定义节点
const processInput = async (state: typeof State.State) => {
return { output: `Processed: ${state.input}` };
};
const finalize = async (state: typeof State.State) => {
return { output: state.output.toUpperCase() };
};
// 3. 构建图
const graph = new StateGraph(State)
.addNode("process", processInput)
.addNode("finalize", finalize)
.addEdge(START, "process") // 入口点
.addEdge("process", "finalize") // 静态边
.addEdge("finalize", END) // 出口点
.compile();
// 4. 执行
const result = await graph.invoke({ input: "hello" });
console.log(result.output); // "PROCESSED: HELLO"
条件边(分支)
import { StateGraph, StateSchema, ConditionalEdgeRouter, START, END } from "@langchain/langgraph";
import { z } from "zod";
const State = new StateSchema({
query: z.string(),
route: z.string(),
result: z.string().optional(),
});
const classify = async (state: typeof State.State) => {
if (state.query.toLowerCase().includes("weather")) {
return { route: "weather" };
}
return { route: "general" };
};
const weatherNode = async (state: typeof State.State) => {
return { result: "Sunny, 72°F" };
};
const generalNode = async (state: typeof State.State) => {
return { result: "General response" };
};
// 路由器函数
const routeQuery: ConditionalEdgeRouter<typeof State, "weather" | "general"> = (state) => {
return state.route as "weather" | "general";
};
const graph = new StateGraph(State)
.addNode("classify", classify)
.addNode("weather", weatherNode)
.addNode("general", generalNode)
.addEdge(START, "classify")
// 基于状态的条件边
.addConditionalEdges(
"classify",
routeQuery,
["weather", "general"] // 可能的目标
)
.addEdge("weather", END)
.addEdge("general", END)
.compile();
const result = await graph.invoke({ query: "What's the weather?" });
使用 Command 进行状态 + 路由
import { StateGraph, StateSchema, Command, START, END } from "@langchain/langgraph";
import { z } from "zod";
const State = new StateSchema({
count: z.number(),
result: z.string(),
});
const nodeA = async (state: typeof State.State) => {
const newCount = state.count + 1;
if (newCount > 5) {
// 转到 nodeC
return new Command({
update: { count: newCount, result: "Going to C" },
goto: "nodeC"
});
} else {
// 转到 nodeB
return new Command({
update: { count: newCount, result: "Going to B" },
goto: "nodeB"
});
}
};
const nodeB = async (state: typeof State.State) => {
return { result: `B executed, count=${state.count}` };
};
const nodeC = async (state: typeof State.State) => {
return { result: `C executed, count=${state.count}` };
};
const graph = new StateGraph(State)
.addNode("nodeA", nodeA, { ends: ["nodeB", "nodeC"] }) // 指定可能的路由
.addNode("nodeB", nodeB)
.addNode("nodeC", nodeC)
.addEdge(START, "nodeA")
.addEdge("nodeB", END)
.addEdge("nodeC", END)
.compile();
const result1 = await graph.invoke({ count: 0 });
console.log(result1.result); // "B executed, count=1"
const result2 = await graph.invoke({ count: 5 });
console.log(result2.result); // "C executed, count=6"
使用 Send API 的 Map-Reduce
import { StateGraph, StateSchema, Send, ReducedValue, START, END } from "@langchain/langgraph";
import { z } from "zod";
const State = new StateSchema({
items: z.array(z.string()),
results: new ReducedValue(
z.array(z.string()).default(() => []),
{ redu
Установить langgraph-graph-api в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл langgraph-graph-api?
使用 StateGraph、节点、边、START/END 节点和 Command API 构建图,结合控制流与状态更新
Как установить скилл langgraph-graph-api?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл langgraph-graph-api запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic