安装与 Hello World
环境要求
- Python 3.9+
- pip 或 uv 包管理器
安装 LangGraph
使用 pip
bash
pip install -U langgraph使用 uv(推荐,更快的包管理器)
bash
uv add langgraph安装可选依赖
bash
# 用于处理消息
pip install langchain-core
# 用于 LLM 调用
pip install langchain-openai # OpenAI
pip install langchain-anthropic # Anthropic
# 用于向量存储
pip install langchain-community chromadb
# 用于持久化
pip install langgraph-checkpoint-postgres验证安装
bash
python -c "import langgraph; print(langgraph.__version__)"Hello World
Graph API 版本
python
from langgraph.graph import StateGraph, MessagesState, START, END
# 1. 定义节点
def hello_node(state: MessagesState):
return {"messages": [{"role": "ai", "content": "Hello World!"}]}
# 2. 构建图
builder = StateGraph(MessagesState)
builder.add_node("hello", hello_node)
builder.add_edge(START, "hello")
builder.add_edge("hello", END)
# 3. 编译
graph = builder.compile()
# 4. 执行
result = graph.invoke({
"messages": [{"role": "user", "content": "Say hello!"}]
})
print(result["messages"][-1].content)
# 输出: Hello World!Functional API 版本(LangGraph 3.0+)
python
from langgraph.func import entrypoint
from langgraph.graph import add_messages
@entrypoint()
def hello_agent():
return "Hello World!"
result = hello_agent.invoke()
print(result) # Hello World!常用依赖组合
bash
# 最小安装
pip install langgraph langchain-core
# 完整开发环境
pip install langgraph langchain-openai langchain-community chromadb jupyter下一步
了解 LangGraph 的 核心概念:StateGraph。