Vertex AIのGemini 2.0 FlashがGAされたので触ってみる

公式から配布されているColabノートブックを和訳しながら進めてみます。

SDKのインストール

Gemini 2.0から利用するSDKが変わっているので注意。

%pip install --upgrade --quiet google-genai==1.0.0 pandas

認証を通す

Colabの場合ログインしているGoogleアカウントで認証して、そのアカウントにGoogle Cloudプロジェクトの利用権限を与えておくと楽です。

import sys

if "google.colab" in sys.modules:
    from google.colab import auth

    auth.authenticate_user()

簡単なプロンプトを実行してみる

import datetime

from google import genai
from google.genai.types import (
    GenerateContentConfig,
    GoogleSearch,
)


PROJECT_ID = "my-project"
LOCATION = "us-central1"

client = genai.Client(vertexai=True, project=PROJECT_ID, location=LOCATION)
MODEL_ID = "gemini-2.0-flash-001"

response = client.models.generate_content(
    model=MODEL_ID, contents="私たちの太陽系で最大の惑星は何ですか?"
)

print(response.text)

マルチモーダルなプロンプト実行

from PIL import Image
import requests

image = Image.open(
    requests.get(
        "https://storage.googleapis.com/cloud-samples-data/generative-ai/image/meal.png",
        stream=True,
    ).raw
)

response = client.models.generate_content(
    model=MODEL_ID,
    contents=[
        image,
        "この写真に基づいて、短くて魅力的なブログ記事を書いてください。",
    ],
)

print(response.text)

チャットを行う

system_instruction = """
  あなたは熟練したソフトウェア開発者であり、役に立つコーディングアシスタントです。
  あらゆるプログラミング言語で高品質のコードを生成できます。
"""

chat = client.chats.create(
    model=MODEL_ID,
    config=GenerateContentConfig(
        system_instruction=system_instruction,
        temperature=0.5,
    ),
)

response = chat.send_message("ある年がうるう年であるかどうかを確認する関数を記述します。")
print(response.text)

response = chat.send_message("OK、では生成された関数の単体テストを記述します。")
print(response.text)

履歴からチャットを開始する

history = [
    Content(role='user', parts=[Part.from_text(text='しりとりしましょう。リンゴ')]),
    Content(role='model', parts=[Part.from_text(text='ゴリラ')]),
    Content(role='user', parts=[Part.from_text(text='ラッコ')]),
    Content(role='model', parts=[Part.from_text(text='コアラ')]),
]

chat = client.chats.create(model='gemini-2.0-flash-001', history=history)
response = chat.send_message('ラクダ')

print(response.text)

Grounding with Google Search

from IPython.display import HTML

google_search_tool = Tool(
    google_search = GoogleSearch()
)

response = client.models.generate_content(
    model=MODEL_ID,
    contents="アメリカで次に皆既日食が起こるのはいつですか?Webを検索して",
    config=GenerateContentConfig(
        tools=[google_search_tool],
        response_modalities=["TEXT"],
    )
)

for each in response.candidates[0].content.parts:
    print(each.text)

HTML(response.candidates[0].grounding_metadata.search_entry_point.rendered_content)

全文を和訳してGrounding with Google Searchなどの利用法を付け足したものはこちら