從LangChain升級LangGraph,大幅提升智能體性能
智能體開發(fā)領(lǐng)域正在迅速發(fā)展,LangChain也隨之不斷演變進(jìn)化。雖然傳統(tǒng)的LangChain智能體(尤其是基于AgentExecutor構(gòu)建的)已經(jīng)提供了穩(wěn)定的服務(wù),但LangGraph的出現(xiàn)帶來了更為強(qiáng)大和靈活的解決方案。
本文指導(dǎo)讀者如何將智能體遷移至LangGraph,使遷移后的智能體能夠充分利用LangGraph的最新技術(shù)優(yōu)勢。
1 傳統(tǒng)LangChain與LangGraph
傳統(tǒng)LangChain智能體是基于AgentExecutor類構(gòu)建的,為LangChain平臺中的智能體開發(fā)提供了一種結(jié)構(gòu)化的方法,并為智能體的行為提供了全面的配置選項(xiàng)。
LangGraph代表了LangChain智能體開發(fā)的新紀(jì)元。它賦予了開發(fā)者構(gòu)建高度定制化和可控智能體的能力。與之前的版本相比,LangGraph提供了更為精細(xì)的控制能力。
2 為什么遷移至LangGraph
遷移至LangGraph可以解鎖多個(gè)好處:
- 控制力提升:LangGraph提供了對智能體決策過程的更大控制權(quán),可以更精確地定制其響應(yīng)和動作。
- 架構(gòu)靈活性:LangGraph的架構(gòu)設(shè)計(jì)更為靈活,開發(fā)者可以根據(jù)特定需求設(shè)計(jì)出完美的智能體。
- 技術(shù)前瞻性:LangChain正在積極推進(jìn)開發(fā)LangGraph,預(yù)示著平臺內(nèi)智能體創(chuàng)建的未來方向。及時(shí)遷移能夠確保智能體技術(shù)始終處于行業(yè)前沿。
3 代碼實(shí)現(xiàn)
下面是將傳統(tǒng)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,
# 這是必需的,因?yàn)樵诖蠖鄶?shù)現(xiàn)實(shí)場景中,需要一個(gè)會話ID
# 但在這里沒有真正使用,因?yàn)槭褂玫氖呛唵蔚膬?nèi)存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的智能體狀態(tài)管理
from langchain_core.messages import SystemMessage
from langgraph.checkpoint import MemorySaver # 內(nèi)存中的檢查點(diǎn)保存器
from langgraph.prebuilt import create_react_agent
system_message = "You are a helpful assistant."
# 這也可以是一個(gè)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 結(jié)語
遷移至LangGraph的智能體會獲得更深層次的能力和靈活性。按照既定步驟并理解系統(tǒng)消息的概念,將有助于實(shí)現(xiàn)平滑過渡,并優(yōu)化智能體的性能表現(xiàn)。
本文轉(zhuǎn)載自 ??AI科技論談??,作者: AI科技論談
