😎

google custom search api

2023/10/15に公開

この数年来、グーグルの各種手続きが極端に煩雑化した。
openai chatcompletion api と組み合わせるのに、gogole search API を使おうと思って調べてみた。

google custom search api は手続きは判りづらいが使い方は簡単だった。

事務手続き

apiの登録だけでは使えず、”検索エンジン”の定義を指定する必要がある。

アカウント作成、支払い設定等については割愛する。

APIの利用登録

本件のためのgoogle cloudプロジェクトを作成する。
作成済みのものを流用してもいいが、管理が煩雑かつ密結合なので、API専用のものを作成することを薦める。

https://console.cloud.google.com/projectcreate

プロジェクトに対してカスタムサーチAPIを有効化する。

https://console.cloud.google.com/apis/library/customsearch.googleapis.com

当該APIキーを控えておくこと。

https://console.cloud.google.com/apis/credentials

”検索エンジン”の作成

https://programmablesearchengine.google.com/controlpanel/create

本件では、openai chatcompletion api から使うため、”ウェブ全体を検索”できるようにする。

ドメイン絞り込みおよび、scriptletは、自前のサイトの検索機能とするためのものだ。

”検索エンジンID”を控えておくこと。

python3

ググると boto3等を使ったソースが見当たるが、どうやら内蔵ライブラリだけで動いてしまうらしい。

#!python3

import requests
import json

def run_query(search_term, api_key, cx):
    # Specify the base
    base_url = 'https://www.googleapis.com/customsearch/v1'

    # Specify the parameters
    params = {
        'q': search_term,
        'key': api_key,
        'cx': cx,
    }

    # Perform the request and get the response
    response = requests.get(base_url, params=params)

    # Parse the response
    response_json = json.loads(response.text)

    return response_json

if __name__ == '__main__':
    import os
    api_key = os.environ.get("YOUR_API_KEY")
    cx = os.environ.get("YOUR_SEARCH_ENGINE_ID")
    search_term = 'OpenAI'
    results = run_query(search_term, api_key, cx)
    print(json.dumps(results, indent=4))

環境変数 YOUR_API_KEY=APIキー YOUR_SEARCH_ENGINE_ID=検索エンジンID を適切に設定すれば動く。

Discussion