見出し画像

Gemini 2.0 の Search as a tool を試す

「Gemini 2.0」の「Search as a tool」を試したのでまとめました。


1. Search as a tool

Search as a tool」は、ユーザーの質問に対してWeb検索を用いて最新かつ正確な情報を取得し、それを基に回答を生成する機能です。

2. Gemini API の準備

「Google Colab」で Gemini API を準備する手順は、次のとおりです。

(1) パッケージのインストール。

# パッケージのインストール
!pip install -U -q google-genai

(2) 「Google AI Studio」からAPIキーを取得し、Colabのシークレットマネージャーに登録し、以下のセルを実行。

【注意】「Search as a tool」を使用するには、有料版のAPIキーが必要です。

from google.colab import userdata
import os

# APIキーの準備
os.environ['GOOGLE_API_KEY'] = userdata.get("GOOGLE_API_KEY")

(3) 推論の実行。
クライアントバージョンを「v1alpha」を設定し、「gemini-2.0-flash-exp」を使用する必要があります。

from google import genai

# クライアントの準備
client = genai.Client(http_options= {'api_version': 'v1alpha'})

# 推論の実行
response = client.models.generate_content(
    model="gemini-2.0-flash-exp", 
    contents="こんにちは"
)
print(response.text)

こんにちは!何かお手伝いできることはありますか?

3. Search as a tool を試す

「Google Colab」で「Search as a tool」を試す手順は、次のとおりです。

(1) Geminiのレスポンスを表示する関数の準備。
テキストはMarkdown、実行コードはコードブロック、その他はJSONで表示します。grounding_metadataが存在する場合はHTMLで表示します。

import json
from IPython.display import display, HTML, Markdown

# Partsの表示
def show_parts(r):
  parts = r.candidates[0].content.parts
  if parts is None:
    finish_reason = r.candidates[0].finish_reason
    print(f'{finish_reason=}')
    return

  # Partの種類に応じて表示
  for part in r.candidates[0].content.parts:
    # テキストはMarkdownで表示
    if part.text:
      display(Markdown(part.text))
    # 実行コードはコードブロックで表示
    elif part.executable_code:
      display(Markdown(f'```python\n{part.executable_code.code}\n```'))
    # その他はJSONで表示
    else:
      print(json.dumps(part.model_dump(exclude_none=True), indent=2))

  # grounding_metadataが存在する場合はHTMLで表示
  grounding_metadata = r.candidates[0].grounding_metadata
  if grounding_metadata and grounding_metadata.search_entry_point:
    display(HTML(grounding_metadata.search_entry_point.rendered_content))

(2) 「Search as a tool」なしでの質問応答。

# クライアントの準備
chat = client.chats.create(
    model='gemini-2.0-flash-exp'
)

# 推論の実行
response = chat.send_message('機動戦士Gundam GQuuuuuuXの劇場公開日は?')
show_parts(response)

(3) 「Search as a tool」ありでの質問応答。

# クライアントの準備
chat = client.chats.create(
    model='gemini-2.0-flash-exp', 
    config={
        'tools': [{'google_search': {}}]
    }
)

# 推論の実行
response = chat.send_message('機動戦士Gundam GQuuuuuuXの劇場公開日は?')
show_parts(response)

関連



いいなと思ったら応援しよう!