引言
在人工智能的领域中,"代理" 是一个具有特定用途的系统,它使用大语言模型(LLM)作为推理引擎来决定哪些动作需要执行及相应的输入。在本教程中,我们将使用 LangChain 构建一个能够和搜索引擎互动的代理,让你可以向它提问,并观察其调用搜索工具的过程。
主要内容
1. 先决条件
确保您对以下概念熟悉:
- 聊天模型:用于处理自然语言输入和响应。
- 工具:可以被代理调用执行特定任务。
- 代理:使用大语言模型来决定所需动作的系统。
2. 安装和设置
我们推荐在 Jupyter Notebook 中运行本教程。首先安装必要的软件包:
%pip install -U langchain-community langgraph langchain-anthropic tavily-python
设置环境变量以启用 LangSmith 的日志跟踪:
import os
import getpass
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = getpass.getpass() # 输入您的 API KEY
os.environ["TAVILY_API_KEY"] = getpass.getpass() # 输入 Tavily API KEY
3. 定义工具
Tavily 是我们将使用的搜索引擎工具。我们需要先创建这个工具:
from langchain_community.tools.tavily_search import TavilySearchResults
search = TavilySearchResults(max_results=2)
tools = [search]
4. 使用语言模型
选择你想使用的语言模型并初始化:
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(model_name="claude-3-sonnet-20240229")
5. 创建和运行代理
合并这些工具并创建代理:
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"])
代码示例
创建一个可以与搜索工具交互的完整示例:
# 使用API代理服务提高访问稳定性
from langchain_anthropic import ChatAnthropic
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.messages import HumanMessage
from langgraph.prebuilt import create_react_agent
# 创建代理
memory = SqliteSaver.from_conn_string(":memory:")
model = ChatAnthropic(model_name="claude-3-sonnet-20240229")
search = TavilySearchResults(max_results=2)
tools = [search]
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! and i live in sf")]}, config
):
print(chunk)
print("----")
for chunk in agent_executor.stream(
{"messages": [HumanMessage(content="whats the weather where I live?")]}, config
):
print(chunk)
print("----")
常见问题和解决方案
- 网络限制:某些地区可能存在网络限制,建议使用 API 代理服务来提高访问稳定性。
- 错误处理:确保 API 密钥设置正确,并且您使用的工具可用。
总结和进一步学习资源
我们介绍了如何构建一个简单的代理,包括流式响应和添加记忆功能以进行对话。代理系统是一个复杂的主题,仍有许多值得学习的内容。
进一步学习资源
参考资料
- LangChain 和 Tavily 官方指南
- LangGraph 概念和教程
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---