import { StateGraph, StateSchema, GraphNode, START, END, MemorySaver, task } from "@langchain/langgraph";
import { v7 as uuid7 } from "uuid";
import * as z from "zod";
// 定义一个 StateSchema 来表示状态
const State = new StateSchema({
urls: z.array(z.string()),
results: z.array(z.string()).optional(),
});
const makeRequest = task("makeRequest", async (url: string) => {
const response = await fetch(url);
const text = await response.text();
return text.slice(0, 100);
});
const callApi: GraphNode<typeof State> = async (state) => {
const requests = state.urls.map((url) => makeRequest(url));
const results = await Promise.all(requests);
return {
results,
};
};
// 创建一个 StateGraph 构建器并为 callApi 函数添加一个节点
const builder = new StateGraph(State)
.addNode("callApi", callApi)
.addEdge(START, "callApi")
.addEdge("callApi", END);
// 指定一个检查点器
const checkpointer = new MemorySaver();
// 使用检查点器编译图
const graph = builder.compile({ checkpointer });
// 定义一个带有线程 ID 的配置。
const threadId = uuid7();
const config = { configurable: { thread_id: threadId } };
// 调用图
await graph.invoke({ urls: ["https://www.example.com"] }, config);