from typing import NotRequired
from typing_extensions import TypedDict
import uuid
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import StateGraph, START, END
import requests
# 定义一个 TypedDict 表示状态
class State(TypedDict):
url: str
result: NotRequired[str]
def call_api(state: State):
"""示例节点,执行 API 请求。"""
result = requests.get(state['url']).text[:100] # 副作用
return {
"result": result
}
# 创建 StateGraph 构建器并为 call_api 函数添加节点
builder = StateGraph(State)
builder.add_node("call_api", call_api)
# 将开始和结束节点连接到 call_api 节点
builder.add_edge(START, "call_api")
builder.add_edge("call_api", END)
# 指定检查点器
checkpointer = InMemorySaver()
# 使用检查点器编译图
graph = builder.compile(checkpointer=checkpointer)
# 定义包含线程 ID 的配置。
thread_id = uuid.uuid4()
config = {"configurable": {"thread_id": thread_id}}
# 调用图
graph.invoke({"url": "https://www.example.com"}, config)