从LangChain升级LangGraph,大幅提升智能体性能

大家好,智能体开发领域正在迅速发展,LangChain也随之不断演变进化。虽然传统的LangChain智能体(尤其是基于AgentExecutor构建的)已经提供了稳定的服务,但LangGraph的出现带来了更为强大和灵活的解决方案。

本文将向大家介绍如何将智能体迁移至LangGraph,使迁移后的智能体能够充分利用LangGraph的最新技术优势。

1.传统LangChain与LangGraph

传统LangChain智能体是基于AgentExecutor类构建的,为LangChain平台中的智能体开发提供了一种结构化的方法,并为智能体的行为提供了全面的配置选项。

LangGraph代表了LangChain智能体开发的新纪元。它赋予了开发者构建高度定制化和可控智能体的能力。与之前的版本相比,LangGraph提供了更为精细的控制能力。

2.为什么迁移至LangGraph

迁移至LangGraph可以解锁多个好处:

  • 控制力提升:LangGraph提供了对智能体决策过程的更大控制权,可以更精确地定制其响应和动作。

  • 架构灵活性:LangGraph的架构设计更为灵活,开发者可以根据特定需求设计出完美的智能体。

  • 技术前瞻性:LangChain正在积极推进开发LangGraph,预示着平台内智能体创建的未来方向。及时迁移能够确保智能体技术始终处于行业前沿。

3.代码实现

下面是将传统LangChain智能体迁移到LangGraph所需的代码级别更改。

步骤I:安装库

pip install -U langgraph langchain langchain-openai

步骤II:智能体的基本使用

from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain.memory import ChatMessageHistory
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI

model = ChatOpenAI(model="gpt-4o")
memory = ChatMessageHistory(session_id="test-session")
prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful assistant."),
        # First put the history
        ("placeholder", "{chat_history}"),
        # Then the new input
        ("human", "{input}"),
        # Finally the scratchpad
        ("placeholder", "{agent_scratchpad}"),
    ]
)


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


tools = [magic_function]


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

agent_with_chat_history = RunnableWithMessageHistory(
    agent_executor,
    # 这是必需的,因为在大多数现实场景中,需要一个会话ID
    # 但在这里没有真正使用,因为使用的是简单的内存ChatMessageHistory
    lambda session_id: memory,
    input_messages_key="input",
    history_messages_key="chat_history",
)

config = {"configurable": {"session_id": "test-session"}}
print(
    agent_with_chat_history.invoke(
        {"input": "Hi, I'm polly! What's the output of magic_function of 3?"}, config
    )["output"]
)
print("---")
print(agent_with_chat_history.invoke({"input": "Remember my name?"}, config)["output"])
print("---")
print(
    agent_with_chat_history.invoke({"input": "what was that output again?"}, config)[
        "output"
    ]
)

# 输出
Hi Polly! The output of the magic function for the input 3 is 5.
---
Yes, I remember your name, Polly! How can I assist you further?
---
The output of the magic function for the input 3 is 5. 

步骤III:LangGraph的智能体状态管理

from langchain_core.messages import SystemMessage
from langgraph.checkpoint import MemorySaver  # 内存中的检查点保存器
from langgraph.prebuilt import create_react_agent

system_message = "You are a helpful assistant."
# 这也可以是一个SystemMessage对象
# system_message = SystemMessage(content="You are a helpful assistant. Respond only in Spanish.")

memory = MemorySaver()
app = create_react_agent(
    model, tools, messages_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?")
            ]
        },
        config,
    )["messages"][-1].content
)
print("---")
print(
    app.invoke({"messages": [("user", "Remember my name?")]}, config)["messages"][
        -1
    ].content
)
print("---")
print(
    app.invoke({"messages": [("user", "what was that output again?")]}, config)[
        "messages"
    ][-1].content
)

# 输出
Hi Polly! The output of the magic_function for the input 3 is 5.
---
Yes, your name is Polly!
---
The output of the magic_function for the input 3 was 5.

4.总结

迁移至LangGraph的智能体会获得更深层次的能力和灵活性。按照既定步骤并理解系统消息的概念,将有助于实现平滑过渡,并优化智能体的性能表现。为了获得更全面的迁移指导和掌握高级技术,建议查阅官方LangChain文档。

### 关于 JavaScript 版本的 LangChainLangGraph #### LangChain 是什么? LangChain 是一种用于构建基于大型语言模型 (LLM) 应用程序的框架。它提供了一系列模块化工具,使得开发者能够更轻松地设计复杂的对话系统和其他自然语言处理应用程序[^1]。 #### JavaScript 版本的 LangChain 尽管主要文档和教程可能集中于 Python 实现,但 LangChain 社区也支持 JavaScript/TypeScript 用户群体。以下是关于 JavaScript 版本的关键点: - **安装与初始化** 可以通过 npm 或 yarn 安装 `langchain` 包来使用其功能。例如: ```javascript npm install langchain ``` - **核心模块的支持情况** 虽然大部分功能在 Python 中实现得更为成熟,但在 JavaScript 中同样提供了以下模块的功能接口: - Model I/O:允许定义输入输出模式并集成不同的 LLM 提供商。 - Retrieval:支持向量数据库检索操作。 - Agents & Chains:部分预设链式逻辑已移植到 JS 平台。 - Memory:会话记忆管理机制可用。 - Callbacks:事件监听器可用于调试或扩展行为。 - **局限性** 需要注意的是,某些高级特性如 LCEL(LangChain 表达式语言)、LangServe、以及特定实验性质组件,在当前阶段未必完全适配前端环境或者 Node.js 生态系统。 #### LangGraph 的概述及其 JavaScript 支持 LangGraph 主要作为图结构数据表示的一部分存在,旨在增强知识图谱的应用场景。对于 JavaScript 开发者而言: - 如果计划利用图形算法,则需确认目标库是否已被迁移到 TypeScript 上; - 目前官方并未单独强调针对此子项目的跨平台兼容进度详情。 因此建议关注最新发布说明页面获取最精确的消息源地址。 ```javascript // 示例代码展示如何加载基础配置文件 const { initializeAgentExecutor } = require("langchain"); async function run() { const model = ...; // 初始化您的大模型实例 const tools = [...]; // 添加所需的工具列表 const executor = await initializeAgentExecutor(tools, model); } run(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

python慕遥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值