AI

ウェブ検索にLangChainとBright Dataを使う

LangChainとBright Dataを使用した統合ウェブ検索でAIアプリを強化し、最新の検索結果とスマートなエージェントを実現する方法をご覧ください。
7 分読
Using Langchain and Bright Data for Web Search blog image

AIエージェントの構築は日に日に容易になっています。この記事では、LangChainの新しいBrightDataSERPツールの使い方を説明します。SERPとは、”Search Engine Results Page”(検索エンジンの結果ページ)の略語です。

このチュートリアルは初心者にやさしい。必要なのはPythonの基本的な理解だけです。このガイドを終える頃には、以下のスキルをあなたのツールボックスに追加することができます。

  • BrightDataSERPを使用した基本的な検索の実行
  • SERP出力をカスタマイズする
  • LLMに適したクリーンな出力
  • 検索機能を備えたAIエージェントを作る

はじめにAIの知識的限界

LLMのことをよくご存知の方なら、彼らの知識が静的なものであることはすでにご存知だろう。一般に公開される頃には、彼らはトレーニングと微調整を終えており、それ以上知識を追加することはできない。

OpenAIが検索機能を追加する以前は、ChatGPTには知識の締め切り日がありました。LLMはまだ、最後の微調整期間に基づいて、カットオフの日付を持っています。とはいえ、モデルはゼロショット推論を使うことができます。全体的なトレーニングプロセスについてはこちらをご覧ください。

AIモデルは静的な知識ベースとともに展開される。ゼロショット推論によって、モデルは新しいデータを理解することができるが、情報を永久に保持することはできない。

LangChainはどのように限界に対処するか

LangChainを使えば、ツールを作成し、それをさまざまなLLMに接続することができる。Python関数を書くことができれば、LLMにその関数を呼び出させることができる。あなたはLLMにツールへのアクセス権を与える。それ以外のことはすべてLLMが行う。もしLLMに事前トレーニングで答えられるような質問をすれば、LLMはツールを使わない。もしLLMが知らないことを質問すれば、LLMはツールを使って答えを見つけようとします。

LangChainは、以下のすべてのニーズに対応するビルド済みのツールも提供しています。

  • 検索
  • コード
  • 生産性
  • ウェブ閲覧
  • データベース
  • ファイナンス

LangChainの統合ツール一覧はこちらでご覧いただけます。さらに良いニュースがあります。Bright Dataもその一つです!

ブライトデータでLangChainを使う

さて、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 の無料トライアルはこちらからサインアップできます。serp1では動作しません。準備ができたら、”Add” ボタンをクリックし、ツールの設定を完了します。

SERPゾーンの追加

次に、新しいSERPゾーンのダッシュボードからAPIキーを取得します。

Bright Data APIキーの検索

OpenAIのキーを取得するには、APIキーのページを開き、”Create new secret key “ボタンをクリックします。

新しいOpenAIキーの取得

基本的な例

まずは、このツールがどのように機能するか、簡単な例から見ていこう。以下の API キーを自分の 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のカスタム設定を行います。カスタマイズに関する完全なドキュメントはこちらをご覧ください。検索タイプをshopに設定することで、より関連性の高いショッピング結果を得ることができます。

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でAIエージェントを作る

BrightDataSERPの基本的な使い方を理解したところで、実際のAIエージェントがBrightDataSERPをどのように使用しているかを見てみましょう。コードの断片を確認し、全体としてどのように動作するかを示します。

ピース

始める前に、もういくつかインストールするものがある。

LangChain自体をインストールする。

pip install langchain

OpenAIのLangChainサポートをインストールする。

pip install langchain-openai

エージェントを作成するためにLangGraphをインストールする。

pip install langgraph

AIの時代にこれはちょっとショックかもしれないが、BeautifulSoupもインストールしよう。その理由はすぐにわかるだろう。

pip install beautifulsoup4

検索機能の作成

以下の関数は、先ほどの例と同じように検索結果を取得する。これらの結果を受け取った後、BeautifulSoupを使ってテキストを取り出します。さて、結果をLLMに渡すときに使うトークンはずっと少なくなる。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のToolクラスを使って関数をラップします。これにより、エージェントはこの関数をツールとして呼び出すことができます。下にあるように、とてもシンプルです。名前と説明をつけます。また、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])

退屈だが機能的なUI

すべてのプログラムは、どんなに原始的であってもランタイムを必要とする。ここでは、ユーザがエージェントと対話するための基本的な端末を作成します。ユーザはプロンプトを入力します。プロンプトはメッセージに渡され、エージェントの出力をストリームします。

#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.

結論

AI開発は常に簡単になっています。LangChainとBright Dataを使えば、GoogleやBingなどの最高の検索エンジンを使うことができます!ここでの例は、自動化された検索アシスタントという、とてもミニマルなものでした。

このプロジェクトを次のレベルに進め、LangChainに複数のツールを追加してみることができる。あなたは今、ツールの作成方法、SERP結果のトリミング方法、そしてそれらをAIエージェントに送り込んで出力を強化する方法を知っている。新しいスキルを持って、何かを作ってみよう。

LangChainは以下のツールとの統合も提供しています。

ブライトデータでは、お客様のデータ収集のニーズに合わせて、あらゆる形やサイズの製品をご用意しています。まずは無料トライアルにお申し込みください!