从传统 LangChain Agent 迁移到 LangGraph:实用指南

从传统 LangChain Agent 迁移到 LangGraph:实用指南

引言

随着 AI 技术的快速发展,开发者们正在寻求更灵活、更强大的工具来构建智能应用。LangGraph 作为 LangChain 的一个重要扩展,为开发者提供了更多的可能性。本文将指导您如何从传统的 LangChain Agent 迁移到更灵活的 LangGraph Agent。

1. 基本用法对比

LangChain 方式

在 LangChain 中,我们通常这样创建和使用一个工具调用 Agent:

from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI

model = ChatOpenAI(model="gpt-4")

@tool
def magic_function(input: int) -> int:
    """Applies a magic function to an input."""
    return input + 2

tools = [magic_function]

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant"),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}"),
])

agent = create_tool_calling_agent(model, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools)

query = "what is the value of magic_function(3)?"
result = agent_executor.invoke({"input": query})
print(result["output"])

LangGraph 方式

而在 LangGraph 中,我们可以这样实现相同的功能:

from langgraph.prebuilt import create_react_agent

app = create_react_agent(model, tools)

messages = app.invoke({"messages": [("human", query)]})
print(messages["messages"][-1].content)

2. 内存管理

LangChain 方式

在 LangChain 中,我们使用 RunnableWithMessageHistory 来管理对话历史:

from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory

memory = InMemoryChatMessageHistory(session_id="test-session")

agent_with_chat_history = RunnableWithMessageHistory(
    agent_executor,
    lambda session_id: memory,
    input_messages_key="input",
    history_messages_key="chat_history",
)

config = {"configurable": {"session_id": "test-session"}}
result = agent_with_chat_history.invoke({"input": "Hi, I'm polly!"}, config)

LangGraph 方式

LangGraph 通过使用 checkpointer 来实现内存管理:

from langgraph.checkpoint import MemorySaver

memory = MemorySaver()
app = create_react_agent(model, tools, checkpointer=memory)

config = {"configurable": {"thread_id": "test-thread"}}
result = app.invoke({"messages": [("user", "Hi, I'm polly!")]}, config)

3. 迭代控制

LangChain 方式

LangChain 使用 max_iterations 参数来控制迭代次数:

agent_executor = AgentExecutor(agent=agent, tools=tools, max_iterations=3)

LangGraph 方式

LangGraph 通过 recursion_limit 配置参数来控制迭代:

RECURSION_LIMIT = 2 * 3 + 1

try:
    result = app.invoke(
        {"messages": [("human", query)]},
        {"recursion_limit": RECURSION_LIMIT}
    )
except GraphRecursionError:
    print("Agent stopped due to max iterations.")

4. 执行时间限制

LangChain 方式

LangChain 使用 max_execution_time 参数来限制执行时间:

agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    max_execution_time=2,
    verbose=True,
)

LangGraph 方式

LangGraph 可以通过设置 step_timeout 或使用 asyncio.wait_for 来限制执行时间:

# 设置每个步骤的超时时间
app.step_timeout = 2

# 或者使用 asyncio 设置整个执行的超时时间
import asyncio

async def run_with_timeout():
    task = asyncio.create_task(app.astream({"messages": [("human", query)]}))
    try:
        await asyncio.wait_for(task, timeout=3)
    except asyncio.TimeoutError:
        print("Task Cancelled.")

asyncio.run(run_with_timeout())

5. 中间步骤处理

LangChain 方式

LangChain 使用 trim_intermediate_steps 来处理中间步骤:

def trim_steps(steps: list):
    return steps[-1:]  # 只保留最后一步

agent_executor = AgentExecutor(
    agent=agent, tools=tools, trim_intermediate_steps=trim_steps
)

LangGraph 方式

LangGraph 通过 state_modifier 来实现类似的功能:

def _modify_state_messages(state: AgentState):
    # 只保留原始用户查询和系统消息
    return [("system", "You are a helpful assistant"), state["messages"][0]]

app = create_react_agent(model, tools, state_modifier=_modify_state_messages)

总结

通过本文的对比,我们可以看到 LangGraph 提供了更灵活和强大的方式来构建和管理 AI Agent。它在内存管理、迭代控制、执行时间限制和中间步骤处理等方面都提供了更直观和可控的方法。

迁移到 LangGraph 可能需要一些时间来适应新的概念和 API,但它带来的好处是显而易见的。LangGraph 允许开发者更精细地控制 Agent 的行为,并且提供了更好的可扩展性和可维护性。

进一步学习资源

  1. LangGraph 官方文档:https://python.langchain.com/docs/langgraph
  2. LangChain 官方文档:https://python.langchain.com/docs/get_started/introduction
  3. LangGraph GitHub 仓库:https://github.com/langchain-ai/langgraph

参考资料

  1. LangChain 文档:https://python.langchain.com/docs/modules/agents/
  2. LangGraph 文档:https://python.langchain.com/docs/langgraph/agent_executor
  3. OpenAI API 文档:https://platform.openai.com/docs/api-reference

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

—END—

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值