构建多智能体AI🤖👱🏼🤖-第一章-LangChain与LangGraph
LangGraph和LangChain都是⽤于构建和管理⼤型语⾔模型应⽤的⼯具,它们都提供了⼀种简单易⽤的⽅式来构建和管理复杂的应⽤程序。只不过,LangChain更关注于应⽤程序的整体流程,⽽LangGraph更关注于如何处理特定的任务。
关于LangGraph的细节,在后续章节中会详细介绍。 这⾥,我们先⽤最简单直⽩的⽅式来对⽐⼀下LangChain和LangGraph在和⼤语⾔模型做交互时的基础思想有什么区别。
要使⽤LangGraph,⾸先需要安装LangGraph的依赖库
! pip install langgraph
## 后⾯的案例中会⽤到langchain,所以同时也安装下langchain的依赖
! pip install langchain
! pip install langchain_community
! pip install -U langchain-deepseek实际上,从依赖库的安装过程就能看到,LangGraph是依赖于LangChain库的。
然后,先从基础的访问⼤模型的API开始。⽐较⼀下LangChain和LangGraph的访问⼤模型的API的区别。
使⽤LangChain访问⼤模型最基础的⽅式是使⽤init_chat_model创建⼀个ChatModel,⼤模型对象。通过这个⼤模型对象完成与⼤模型的交互。
import os
os.environ["DEEPSEEK_API_KEY"] = "key"
def load_key(key_name: str) -> str:
key = os.environ.get(key_name)
if key is None:
raise ValueError(f"环境变量 {key_name} 未设置")
return key
# 设置 DeepSeek API Key(如果未设置则加载)
if not os.environ.get("DEEPSEEK_API_KEY"):
os.environ["DEEPSEEK_API_KEY"] = load_key("DEEPSEEK_API_KEY")
from langchain.chat_models import init_chat_model
# 初始化 DeepSeek 模型
model = init_chat_model(
model="deepseek-chat", # 或 "deepseek-coder",取决于你用哪个模型
model_provider="deepseek",
base_url="https://api.deepseek.com", # 官方默认地址,如有代理请替换
api_key=os.environ["DEEPSEEK_API_KEY"]
)
# 测试调用
response = model.invoke("你是谁?你能帮我解决什么问题?")
print(response)然后,使用LangGraph访问大模型的代码如下:
import os
from langchain.chat_models import init_chat_model
from langgraph.prebuilt import create_react_agent
# 1. 设置 API key
os.environ["DEEPSEEK_API_KEY"] = "key"
# 2. 初始化 DeepSeek 模型
model = init_chat_model(
model="deepseek-chat",
model_provider="deepseek",
base_url="https://api.deepseek.com",
api_key=os.environ["DEEPSEEK_API_KEY"]
)
# 3. 创建 agent
agent = create_react_agent(
model=model,
tools=[],
prompt="You are a helpful assistant",
)
# 4. 测试调用
result = agent.invoke({
"messages": [{"role": "user", "content": "你是谁?能帮我解决什么问题?"}]
})
print(result)而如果要个⼤模型提供⼀些⾃定义的辅助⼯具,使⽤LangChain⽅式是这样的:
import os
import datetime
from langchain.tools import tool
from langchain_community.chat_models import ChatTongyi
def load_key(key_name: str) -> str:
key = os.environ.get(key_name)
if key is None:
raise ValueError(f"环境变量 {key_name} 未设置")
return key
# 构建阿里云百炼大模型客户端
llm = ChatTongyi(
model="qwen-plus",
api_key="key",
)
@tool
def get_current_date():
"""获取今天日期"""
return datetime.datetime.today().strftime("%Y-%m-%d")
llm_with_tools = llm.bind_tools([get_current_date])
all_tools = {"get_current_date": get_current_date}
query = "今天是几月几号"
messages = [query]
ai_msg = llm_with_tools.invoke(messages)
print(ai_msg)
messages.append(ai_msg)
print(ai_msg.tool_calls)
if ai_msg.tool_calls:
for tool_call in ai_msg.tool_calls:
selected_tool = all_tools[tool_call["name"].lower()]
tool_msg = selected_tool.invoke(tool_call)
messages.append(tool_msg)
print(llm_with_tools.invoke(messages).content)使用LangGraph后,使⽤的⽅式是这样的:
from langgraph.prebuilt import create_react_agent
agent = create_react_agent(
model=llm,
tools=[get_current_date],
prompt="You are a helpful assistant",
)
agent.invoke({"messages":[{"role":"user","content":"今天是⼏⽉⼏号"}]})从这个案例⼤概可以简单的感受到,LangGraph的⼀部分核⼼功能就是要在LangChain的基础上,以Agent智能体的⽅式,提供更简单实⽤的功能封装,从⽽让我们可以更⽅便的使⽤LangChain的功能。
当然,Agent的功能封装远不⽌这个案例中这么简单。通过LangGraph的Agent功能,可以将与⼤⼤模型交互的各种基础功能统⼀封装成独⽴的Agent,⽽不⽤过多关注Agent内部的实现细节。
接下来,有了Agent之后,LangGraph还通过Graph图的⽅式,可以将多个Agent智能体串联起来,实现更加复杂的应⽤。
例如,我们之前实现了⼀个查询今天⽇期的Agent,接下来可以再实现航班信息的Agent,将这两个Agent串联起来,就可以完成⼀个出⾏规划的复合任务。
这些在后⾯章节会逐步介绍。
