Blog / AI
AI

使用 LangChain 和 Bright Data 进行网络搜索

了解如何通过使用 LangChain 和 Bright Data 的集成网络搜索为您的人工智能应用程序增添动力,以获得最新结果和更智能的代理。
7 分钟阅读
使用 LangChain 和 Bright Data 进行网络搜索 博客图片

构建人工智能代理变得越来越容易。在这篇文章中,我们将介绍如何使用LangChain 的新工具BrightDataSERP。如果您对这个缩写不熟悉,SERP 是 “搜索引擎结果页面 “的缩写。

本教程对初学者非常友好。您只需对 Python 有基本的了解。完成本指南后,您就可以在工具箱中添加以下技能。

  • 使用 BrightDataSERP 进行基本搜索
  • 自定义 SERP 输出
  • 简洁输出,方便 LLM 使用
  • 创建具有搜索功能的人工智能代理

介绍:人工智能的知识局限

如果你对法律硕士足够熟悉,就会知道他们的知识是静态的。当他们被公之于众时,他们已经完成了培训和微调–无法再增加更多的知识。

在 OpenAI 增加搜索功能之前,ChatGPT 有一个知识截止日期。LLM 仍然有截止日期,基于其最后一次微调期。也就是说,模型能够使用零镜头推理。您可以在这里了解有关整个训练过程的更多信息。

人工智能模型在部署时会有一个静态知识库。通过零点推理,模型可以理解新数据,但不会永久保留信息。

LangChain 如何解决局限性

LangChain 允许我们创建工具,并将它们连接到不同的 LLM。如果你能编写 Python 函数,你就能让 LLM 自行调用这些函数。你可以让 LLM 访问工具。其他的事情都由它来做。如果你问它一个它通过预训练就能回答的问题,它就不会使用工具。如果你问它一个它不知道的问题,它就会使用自己的工具来寻找答案。

LangChain 甚至还为以下所有需求提供预制工具。

  • 搜索
  • 代码
  • 生产率
  • 网页浏览
  • 数据库
  • 财务

您可以在这里查看 LangChain 集成工具的完整列表。我们还有更好的消息。Bright Data 就是其中之一!

使用 LangChain 和 Bright Data

既然我们已经了解了 LangChain 的功能,下面就让我们来看看如何在 Bright Data 中实际使用 LangChain。我们假设您已经基本熟悉 Python。我们将介绍如何从 OpenAI 和 Bright Data 获取 API 密钥。在继续之前,请务必先阅读我们的 “使用 LangChain 和 Bright Data 进行网络刮擦 “指南

先决条件

首先,您需要安装 LangChain 的 Bright Data 工具。下面的pip install命令就能实现这一目的。

pip install langchain-brightdata

接下来,您需要一个 Bright Data API 密钥和一个名为serp 的 SERP 实例。您可以在此处注册免费试用我们的 SERP API。确保您的区域名为serp。准备就绪后,单击 “添加 “按钮,完成工具设置。

添加 SERP 区域

接下来,您可以从新 SERP 区域的仪表板上获取 API 密钥。

查找您的 Bright Data API 密钥

要获取 OpenAI 密钥,请打开其API 密钥页面并点击 “创建新密钥 “按钮。

获取新的 OpenAI 密钥

一个基本例子

我们先从一个简单的例子开始,了解工具是如何工作的。将下面的 API 密钥换成你自己的。BrightDataSERP类在这里做了大量工作。我们只需设置配置并打印结果。通常不需要使用.encode("utf-8"),但我们在使用 Windows 时遇到了一些打印问题,这就解决了。

from langchain_brightdata import BrightDataSERP

api_key = "your-bright-data-api-key"

tool = BrightDataSERP(bright_data_api_key=api_key)

results = tool.invoke("Latest AI News")

print(results.encode("utf-8"))

下面是一段输出示例。如果你看到这个(或类似内容),说明你走对了路。

https://api.brightdata.com/request {'zone': 'serp', 'url': 'https://www.google.com/search?q=Latest%20AI%20News&gl=us&hl=en&num=10', 'format': 'raw'} {'Authorization': 'Bearer your-api-key', 'Content-Type': 'application/json'}
b'<!doctype html><html itemscope="" itemtype="http://schema.org/SearchResultsPage" lang="en-MX"><head><meta charset="UTF-8"><meta content="origin" name="referrer"><link href="//www.gstatic.com/images/branding/searchlogo/ico/favicon.ico" rel="icon"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Latest AI News - Google Search</title><script nonce="IBYZiM7epIs5U67-92qXVg">window._hst=Date.now();</script><script nonce="IBYZiM7epIs5U67-92qXVg">
...

高级使用

在下面的示例中,我们使用 kwargs 来设置BrightDataSERP 的自定义配置。您可以在此处查看有关自定义的完整文档。我们将搜索类型设为购物,这样就能得到更多相关的购物结果。

from langchain_brightdata import BrightDataSERP


api_key = "your-bright-data-api-key"


#initialize the tool
serp_tool = BrightDataSERP(
    bright_data_api_key=api_key,
    search_engine="google",
    country="us",
    language="en",
    results_count=10,
    parse_results=True
)

#perform the search
results = serp_tool.invoke(
    {
        "query": "best electric vehicles",
        "country": "us",
        "language": "en",
        "search_type": "shop",
        "device_type": "mobile",
        "results_count": 15,
    }
)

print(results)

您可以自定义以下任何一项,以完善搜索结果。

  • 询问
  • 国家
  • 语言
  • 搜索类型
  • 设备类型
  • 结果数

利用光明数据和 OpenAI 创建人工智能代理

现在您已经对如何使用BrightDataSERP 有了基本的了解,让我们来看看真正的人工智能代理是如何使用它的。我们将通过代码片断来展示它是如何整体运作的。

作品

在我们开始之前,你还需要安装一些东西。

安装 LangChain 本身。

pip install langchain

为 LangChain 安装 OpenAI 支持。

pip install langchain-openai

安装 LangGraph 以创建代理。

pip install langgraph

在人工智能时代,这可能会让人有点吃惊,但我们也会安装 BeautifulSoup。你很快就会知道为什么了。

pip install beautifulsoup4

创建搜索功能

下面的函数将检索我们的搜索结果–就像前面的例子一样。收到结果后,我们使用 BeautifulSoup 提取其中的文本。现在,我们在将结果传入 LLM 时使用的标记要少得多。它看到的只是网站文本。我们保留了换行符这样代理就能更好地理解页面布局。

提取文本后,我们将其返回。

#create a function to return only the text from search results
def get_cleaned_search_results(query):

    #initialize the tool
    serp_tool = BrightDataSERP(
        bright_data_api_key=bright_data_api_key,
        search_engine="google",
        country="us",
        language="en",
        results_count=5,
        parse_results=False,
    )

    #get the results
    results = serp_tool.invoke({
        "query": query,
        "country": "us",
        "language": "en",
        "results_count": 5,
    })

    #parse the text the old fashioned way----save on input tokens
    soup = BeautifulSoup(results, "html.parser")

    #return the results but keep the newlines, this lets the model see the layout without all the extra code
    return soup.get_text(separator="\n")

将功能转化为工具

现在,我们将使用 LangChain 的工具类来封装函数。这样,我们的代理就可以把它作为一个工具来调用。如下所示,这非常简单。我们给它一个名称和描述。我们还使用func参数将工具指向一个函数。

#turn the function into a langchain tool
cleaned_search_tool = Tool.from_function(
    name="CleanedBrightDataSearch",
    func=get_cleaned_search_results,
    description=(
        "Use this tool to retrieve up-to-date Google search results when answering "
        "questions that require recent information, product details, or current events. "
        "Pass in the user's natural-language query."
    ),
)

创建代理

下面的代码将创建我们的代理。ChatOpenAI 会创建一个 LLM 实例。我们将 LLM 和工具传递给create_react_agent(),以创建实际的代理。

#start the llm
llm = ChatOpenAI(
    model="gpt-4o",
    openai_api_key=openai_api_key,
    streaming=False,
    #set the token limit arbitrarily, we used 512 because it's a small task
    max_tokens=512
)


#give the llm access to the tool
agent = create_react_agent(llm, tools=[cleaned_search_tool])

无聊但实用的用户界面

无论多么原始,每个程序都需要一个运行时。在这里,我们只需创建一个基本的终端设置,让用户与代理进行交互。用户输入一个提示。提示信息会传入信息流,然后我们再将代理的输出信息流化。

#the user can ask the agent anything--like the chatgpt webapp
user_prompt = input("Ask me anything: ")
messages = [{"role": "user", "content": user_prompt}]

#stream the model output, the model should perform searches when necessary
for step in agent.stream({"messages": messages}, stream_mode="values"):
    step["messages"][-1].pretty_print()

将所有内容整合在一起

完整代码

下面是我们的完整代码示例。

from langchain_openai import ChatOpenAI
from langchain_brightdata import BrightDataSERP
from langgraph.prebuilt import create_react_agent
from langchain.tools import Tool
from bs4 import BeautifulSoup

#put your creds here
openai_api_key = "your-openai-api-key"
bright_data_api_key = "your-bright-data-api-key"

#create a function to return only the text from search results
def get_cleaned_search_results(query):

    #initialize the tool
    serp_tool = BrightDataSERP(
        bright_data_api_key=bright_data_api_key,
        search_engine="google",
        country="us",
        language="en",
        results_count=5,
        parse_results=False,
    )

    #get the results
    results = serp_tool.invoke({
        "query": query,
        "country": "us",
        "language": "en",
        "results_count": 5,
    })

    #parse the text the old fashioned way----save on input tokens
    soup = BeautifulSoup(results, "html.parser")

    #return the results but keep the newlines, this lets the model see the layout without all the extra code
    return soup.get_text(separator="\n")

#turn the function into a langchain tool
cleaned_search_tool = Tool.from_function(
    name="CleanedBrightDataSearch",
    func=get_cleaned_search_results,
    description=(
        "Use this tool to retrieve up-to-date Google search results when answering "
        "questions that require recent information, product details, or current events. "
        "Pass in the user's natural-language query."
    ),
)

#start the llm
llm = ChatOpenAI(
    model="gpt-4o",
    openai_api_key=openai_api_key,
    temperature=0.7,
    streaming=False,
    max_tokens=512
)

#give the llm access to the tool
agent = create_react_agent(llm, tools=[cleaned_search_tool])

#the user can ask the agent anything--like the chatgpt webapp
user_prompt = input("Ask me anything: ")
messages = [{"role": "user", "content": user_prompt}]

#stream the model output, the model should perform searches when necessary
for step in agent.stream({"messages": messages}, stream_mode="values"):
    step["messages"][-1].pretty_print()

我们的代理看到了什么

这里的代码段就是代理看到的内容。其中包含我们的提示和它获取的参考页面。

python bd-agent-example.py
Ask me anything: give me the latest spacex news
================================ Human Message =================================

give me the latest spacex news
================================== Ai Message ==================================
Tool Calls:
  CleanedBrightDataSearch (call_IKoaponXVrNfVSRTfonU4ewo)
 Call ID: call_IKoaponXVrNfVSRTfonU4ewo
  Args:
    __arg1: latest SpaceX news
https://api.brightdata.com/request {'zone': 'serp', 'url': 'https://www.google.com/search?q=latest%20SpaceX%20news&gl=us&hl=en&num=5', 'format': 'raw'} {'Authorization': 'Bearer d791e32cedf2d9657eaafd7a76b333f67ce5836c89d85691b4d6c07060b07b84', 'Content-Type': 'application/json'}
================================= Tool Message =================================
Name: CleanedBrightDataSearch

latest SpaceX news - Google Search

Please click
here
 if you are not redirected within a few seconds.
Accessibility Links
Skip to main content
Accessibility help
Accessibility feedback


Press
/
 to jump to the search box
latest SpaceX news
















Sign in
Filters and Topics
AI Mode
All
News
Videos
Images
Short videos
Forums
More
About 85,800,000 results
 (0.38 seconds) 


Search Results
SpaceX - Updates
SpaceX
https://www.spacex.com
 › updates
SpaceX
https://www.spacex.com
 › updates
As early as this year,
Falcon 9 will launch Dragon's sixth commercial astronaut mission, Fram2
, which will be the first human spaceflight mission to explore ...
Videos
12:03
YouTube
 ·
 GREAT SPACEX
SpaceX's Solution to Launch Starship Again after Test Site ...
YouTube
 ·
 GREAT SPACEX
2 days ago
47:39
YouTube
 ·
 GREAT SPACEX
COPV Destroyed Starship S36, What next? Honda's Hopper ...
YouTube
 ·
 GREAT SPACEX
1 day ago
3:10
YouTube
 ·
 CBS News
Watch: SpaceX Starship explodes, causes massive fiery burst ...
YouTube
 ·
 CBS News
3 days ago
Feedback
View all
Top stories
USA Today
SpaceX Starship exploded again. What's next for Elon Musk's company after latest setback?
3 days ago
Soap Central
Everything to know about Elon Musk's latest SpaceX starship explosion during static fire test in Texas
3 days ago
The Guardian
SpaceX Starship breaks up over Indian Ocean in latest bumpy test
4 weeks ago
CBS News
SpaceX loses contact with its Starship on 9th test flight after last 2 went down in flames
4 weeks ago
More news
Twitter Results
SpaceX (@SpaceX) · X
X (Twitter)
https://x.com/SpaceX
Watch Falcon 9 launch Dragon and Ax-4 to the @Space_Station x.com/i/broadcasts/1YpJ…
2 hours ago
Falcon 9 delivers 27 @Starlink satellites to orbit from Florida
9 hours ago
Deployment of 27 @Starlink satellites confirmed
9 hours ago
Elon Musk promises more risky launches after sixth ...
Space
https://www.space.com
 › ... › Private Spaceflight
Space
https://www.space.com
 › ... › Private Spaceflight
1 day ago
 —
Until
last
 year, the FAA allowed
SpaceX
 to try up to five Starship launches a year. This month, the figure was increased to 25. A lot can go ...
People also search for
Latest spacex news
nasa
Latest spacex news
live
SpaceX
launch today live
SpaceX
Starship
 news
today
SpaceX
Starship launch date
SpaceX
launch tonight
SpaceX
launch today live countdown
SpaceX
recent landing
Page Navigation
1
2
3
4
5
6
7
8
9
10
Next




Footer Links
Google apps

模型输出

在下面的代码段中,我们的模型已经完成了对搜索结果的审核。正如您所看到的,搜索结果的摘要非常清晰。

================================== Ai Message ==================================

Here are some of the latest updates on SpaceX:

1. **Falcon 9 Launches**: SpaceX's Falcon 9 recently launched 27 Starlink satellites into orbit from Florida. The deployment of these satellites was confirmed about 9 hours ago.

2. **Starship Setbacks**: SpaceX's Starship program has faced some challenges recently. A Starship exploded during a test, which has been a setback for the company. Despite this, Elon Musk has indicated plans for more risky launches following the sixth astronaut mission.

3. **Increased Launch Capacity**: The FAA has increased the number of Starship launches SpaceX is permitted to conduct per year from 5 to 25, allowing for more frequent test launches.

These developments highlight ongoing progress and challenges within SpaceX's operations.

结论

人工智能开发越来越容易。借助 LangChain 和 Bright Data,您可以使用一些最好的搜索引擎–谷歌、必应等!我们这里的例子非常简单,就是一个自动搜索助手。

您可以将此项目提升到更高水平,尝试为 LangChain 添加多种工具。现在,您已经知道如何创建工具、修剪 SERP 结果以及如何将其反馈给人工智能代理以增强输出。运用你的新技能,去创造点什么吧。

LangChain 还提供与以下工具的集成。

在 Bright Data,我们提供各种形状和尺寸的产品,以满足您的数据采集需求。注册免费试用,立即开始使用!

支持支付宝等多种支付方式