当前位置:   article > 正文

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

langchain graph

大家好,智能体开发领域正在迅速发展,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:智能体的基本使用

  1. from langchain.agents import AgentExecutor, create_tool_calling_agent
  2. from langchain.memory import ChatMessageHistory
  3. from langchain_core.prompts import ChatPromptTemplate
  4. from langchain_core.runnables.history import RunnableWithMessageHistory
  5. from langchain_core.tools import tool
  6. from langchain_openai import ChatOpenAI
  7. model = ChatOpenAI(model="gpt-4o")
  8. memory = ChatMessageHistory(session_id="test-session")
  9. prompt = ChatPromptTemplate.from_messages(
  10.     [
  11.         ("system""You are a helpful assistant."),
  12.         # First put the history
  13.         ("placeholder""{chat_history}"),
  14.         # Then the new input
  15.         ("human""{input}"),
  16.         # Finally the scratchpad
  17.         ("placeholder""{agent_scratchpad}"),
  18.     ]
  19. )
  20. @tool
  21. def magic_function(inputint) -> int:
  22.     """Applies a magic function to an input."""
  23.     return input + 2
  24. tools = [magic_function]
  25. agent = create_tool_calling_agent(model, tools, prompt)
  26. agent_executor = AgentExecutor(agent=agent, tools=tools)
  27. agent_with_chat_history = RunnableWithMessageHistory(
  28.     agent_executor,
  29.     # 这是必需的,因为在大多数现实场景中,需要一个会话ID
  30.     # 但在这里没有真正使用,因为使用的是简单的内存ChatMessageHistory
  31.     lambda session_id: memory,
  32.     input_messages_key="input",
  33.     history_messages_key="chat_history",
  34. )
  35. config = {"configurable": {"session_id""test-session"}}
  36. print(
  37.     agent_with_chat_history.invoke(
  38.         {"input""Hi, I'm polly! What's the output of magic_function of 3?"}, config
  39.     )["output"]
  40. )
  41. print("---")
  42. print(agent_with_chat_history.invoke({"input""Remember my name?"}, config)["output"])
  43. print("---")
  44. print(
  45.     agent_with_chat_history.invoke({"input""what was that output again?"}, config)[
  46.         "output"
  47.     ]
  48. )
  49. # 输出
  50. Hi Polly! The output of the magic function for the input 3 is 5.
  51. ---
  52. Yes, I remember your name, Polly! How can I assist you further?
  53. ---
  54. The output of the magic function for the input 3 is 5. 

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

  1. from langchain_core.messages import SystemMessage
  2. from langgraph.checkpoint import MemorySaver  # 内存中的检查点保存器
  3. from langgraph.prebuilt import create_react_agent
  4. system_message = "You are a helpful assistant."
  5. # 这也可以是一个SystemMessage对象
  6. # system_message = SystemMessage(content="You are a helpful assistant. Respond only in Spanish.")
  7. memory = MemorySaver()
  8. app = create_react_agent(
  9.     model, tools, messages_modifier=system_message, checkpointer=memory
  10. )
  11. config = {"configurable": {"thread_id""test-thread"}}
  12. print(
  13.     app.invoke(
  14.         {
  15.             "messages": [
  16.                 ("user""Hi, I'm polly! What's the output of magic_function of 3?")
  17.             ]
  18.         },
  19.         config,
  20.     )["messages"][-1].content
  21. )
  22. print("---")
  23. print(
  24.     app.invoke({"messages": [("user""Remember my name?")]}, config)["messages"][
  25.         -1
  26.     ].content
  27. )
  28. print("---")
  29. print(
  30.     app.invoke({"messages": [("user""what was that output again?")]}, config)[
  31.         "messages"
  32.     ][-1].content
  33. )
  34. # 输出
  35. Hi Polly! The output of the magic_function for the input 3 is 5.
  36. ---
  37. Yes, your name is Polly!
  38. ---
  39. The output of the magic_function for the input 3 was 5.

4.总结

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/965707
推荐阅读
相关标签
  

闽ICP备14008679号