從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的智能體會獲得更深層次的能力和靈活性。按照既定步驟并理解系統消息的概念,將有助于實現平滑過渡,并優化智能體的性能表現。
本文轉載自 ??AI科技論談??,作者: AI科技論談
贊
收藏
回復
分享
微博
QQ
微信
舉報
回復
相關推薦

















