🔍
Responses API のWeb検索の使い方
Web検索をつかってカレーの材料を表示してみる
新しくリリースされた OpenAI の Responses API を使用し、Web検索結果の取得や加工を試してみました。
この記事では、Responses API を使用して「バナナを使ったカレーの材料」を検索・取得する例を実装し、結果をさらに絞り込む方法をご紹介します。
バナナカレーの材料リストを検索してみる
コード
from openai import OpenAI
client = OpenAI(api_key="<put_your_openai_key>") # APIキーを設定する
response = client.responses.create(
model="gpt-4o-mini",
tools=[{"type": "web_search_preview"}], # Web検索ツールを有効化
tool_choice={"type": "web_search_preview"}, # Web検索を強制的に使う(指定しないとAPI側で利用の有無を自動判定する)
input="バナナを使ったカレーのレシピの材料一覧だけ教えて。複数のサイトから検索してください。",
store=True # 結果を保存する
)
# レスポンスの確認と結果の表示
if response.status == "completed":
print("結果を取得しました")
if response.output[0].type == "web_search_call":
print("Web検索をしています。")
else:
print("Web検索をしていません。")
else:
print("失敗しました。")
# 検索結果を表示
print(response.output_text)
どのサイトが参照されたのか一覧を表示
annotations = response.output[1].content[0].annotations
print("参照したページの情報: ")
for annotation in annotations:
if annotation.type == "url_citation":
print(f" title: {annotation.title}")
print(f" url : {annotation.url}")
会話履歴を使う
前回取得した検索結果から特定条件で絞り込むことも可能です。以下のコードでは、「ヨーグルトを使ったレシピ」に絞り込むよう指示しています。
実装コード
response = client.responses.create(
model="gpt-4o-mini",
input="ヨーグルトを使っているものだけに絞り込んで",
store=True,
previous_response_id=response.id # 前回のレスポンスIDを指定
)
実行時の注意
-
previous_response_id
にresponse.id
を指定することで、前回の結果を踏まえて処理を行います。
まとめ
Responses API を使えば、簡単に Web 検索機能を組み込むことが可能です。Enjoy!!
Discussion