Google Cloud Next ’25 でも話題になっていた Gemini 2.5 Flash のプレビュー版が 4 月 17 日にリリースされました。
この機会に、Python を通じた AI 開発へ踏み出した私は、Vertex AI SDK for Python の導入からモデルへのリクエスト、そして様々な機能の活用という基本的な理解を深めている最中です。
ここでは、そのような基本的な使い方を最新モデルである Gemini 2.5 Flash を利用する形でまとめます。
Gemini 2.5 Flash
Gemini 2.5 Flash は、これまでの Gemini Flash モデルが持っていた「速さ」と「効率」という強みを、さらに磨き上げたモデルとして登場しました。
一方で、Gemini 2.0 Pro や GPT-4o といった大規模モデルに匹敵する品質を維持しており、最大 100 万トークンという広大なコンテキストウィンドウを全てのモダリティでサポートしているため、マルチモーダル機能についても強化されています。
その他にも、Thinking Budget という推論に用いるトークン数を選択することで、応答の品質と速度を制御できる新機能も紹介されていました。
詳しくは以下のセッションレポートをご覧ください。
【Google Cloud Next ’25】Gemini 2.5 に関する最新アップデート!
環境設定
導入
まずはじめに、Vertex AI SDK for Pythonをインストールします。
pip install --upgrade google-cloud-aiplatform
次に使用するライブラリをインポートします。
この後利用するライブラリも併せて入れておきます。
# 必要なライブラリをインポート from IPython.display import HTML, Image, Markdown, display from google import genai from google.genai.types import ( FunctionDeclaration, GenerateContentConfig, GoogleSearch, HarmBlockThreshold, HarmCategory, Part, SafetySetting, ThinkingConfig, Tool, ToolCodeExecution, )
認証
Google Cloud サービスを利用するには環境に対して認証を行う必要があります。
認証には主に2つの方法があります。
方法 | 説明 | 推奨用途 | 設定要件 |
---|---|---|---|
Google Cloud プロジェクト | ほとんどのユーザーに推奨される方法。Vertex AI APIの有効化が必要。 | 本格的な開発、本番環境 | Google CloudプロジェクトID、Vertex AI API有効化、適切なIAM権限 |
Vertex AI API キー (Express Mode) | 迅速な実験やプロトタイピング向け。 | 簡単なテスト、初期の試用 | 生成されたAPIキー |
実験的な利用を容易にするために API キー(Express Mode)を提供していますが、本格的な開発や本番環境での利用には、Google Cloud プロジェクトで認証することが推奨されます。
- Google Cloud プロジェクトの設定
import os # プロジェクト ID を設定 PROJECT_ID = "[your-project-id]" LOCATION = os.environ.get("GOOGLE_CLOUD_REGION", "us-central1") client = genai.Client(vertexai=True, project=PROJECT_ID, location=LOCATION)
- Vertex AI API Key(Express Mode) の設定
# API Key を設定 API_KEY = "[your-api-key]" client = genai.Client(vertexai=True, api_key=API_KEY)
API サービスの選択
Google の生成 AI API とモデルは、主に 2 つの API サービスを通じて提供されています。
- Gemini Developer API(旧 Google AI for Developers): プロトタイピング、小規模プロジェクトのデプロイ向け
- Vertex AI: Google Cloud 上でエンタープライズ対応のプロジェクトを構築するためのプラットフォーム
Google Gen AI SDK は、これら 2 つの API サービスへの統一されたインターフェースを提供します。
これにより、開発者は API サービスの基盤となる違いを意識することなく、一貫した方法でモデルを利用できます。
モデルの初期化
使用するGeminiモデルを初期化します。
この一行を変更するだけで済むため、例えば、Flash モデルと Pro モデルの性能を比較したい場合なども簡単に行えます。
# Gemini 2.5 Flash モデルをロード MODEL_ID = GenerativeModel("gemini-2.5-flash-preview-04-17")
以上で環境設定は完了です。
テキスト生成の基本
テキストプロンプトからの生成
最も基本的な使い方として、テキストのプロンプトをモデルに送信し、生成されたテキスト応答を受け取ります。
これには generate_content メソッドを使用します。
# モデルから応答を生成 response = client.models.generate_content( model=MODEL_ID, contents="ヘルスケア業界が直面している最大の課題は何ですか?", ) display(Markdown(response.text))
generate_contentメソッドは、単純なテキスト生成からマルチターンチャットやマルチモーダル入力まで、基盤となるモデルがサポートする様々なユースケースに対応できます。
ストリーミング生成
デフォルトでは、generate_contentメソッドは、モデルが応答全体の生成を完了した後に結果を返します。
しかし、応答が生成される過程をリアルタイムで受け取りたい場合もあります。このような場合、generate_content_stream メソッドを使用します。
# ストリーミングで応答を生成し、各チャンクで処理 for chunk in client.models.generate_content_stream( model=MODEL_ID, contents="新しいカフェの名前のアイデアを5つ提案してください。", ): display(Markdown(chunk.text)) display(Markdown("---"))
ストリーミングは、Gemini 2.5 Flashの主要な利点である速度と効率性をさらに引き立てる機能です。
モデル自体の応答が速いことに加え、生成された部分から順次表示することで、ユーザーは即座にフィードバックを得られ、体感的な待ち時間が大幅に短縮されます。
Thinking budget
冒頭で触れた新機能です。
Thinking budget を使用することで、モデルが推論に用いるトークン数を選択できるため、応答の品質と速度を制御できます。
ThinkingConfig のオプションパラメータ thinking_budget を設定することで、モデルが特定のユーザープロンプトに対してどれだけ思考するかを制御・構成できます。
- 未設定:動的思考(デフォルト)
- 0に設定:思考が無効
- [1-32768]に設定:割り当てられた Thinking budget を使用
thinking_config の指定は、generate_content または generate_content_stream メソッドで可能です。
# モデルの思考に使える計算リソースの上限 THINKING_BUDGET = 1024 response = client.models.generate_content( model=MODEL_ID, contents="日本の面積はどのくらいですか?", config=GenerateContentConfig( thinking_config=ThinkingConfig( thinking_budget=THINKING_BUDGET, ) ), ) display(Markdown(response.text))
また、モデルの応答から、usage_metadata を出力することで、利用状況に関する情報やトークン数を確認できます。
print(response.usage_metadata) print(response.usage_metadata.thoughts_token_count) print(response.usage_metadata.total_token_count)
マルチターンチャット
Gemini は文脈を維持しながら対話を行うマルチターンチャットにも対応しているため、ユーザーとの自然な会話フローを構築できます。
start_chat メソッドを使用してチャットセッションを開始し、send_message メソッドでメッセージを送信します。
# チャットセッションを作成 chat = client.chats.create( model=MODEL_ID, config=GenerateContentConfig(thinking_config=thinking_config), ) # ユーザーの最初の質問 response = chat.send_message("こんにちは!Geminiについて教えてください。") display(Markdown(response.text)) # ユーザーの2番目の質問 (以前の会話の流れを踏まえる) response = chat.send_message("特にGemini 2.5 Flashの特徴は何ですか?") display(Markdown(response.text))
マルチターンチャット機能は、モデルのコンテキストウィンドウの大きさに依存します。
Gemini 2.5 Flash は最大 100 万トークンという広大なコンテキストウィンドウを持っていますが、効果的なチャットアプリケーションを構築するためには、このコンテキストを適切に管理することが重要です。
非同期処理
複数のプロンプトを並行して処理したい場合など、非同期処理が有効な場合があります。
client.aio という非同期用の機能が、client で利用できる全てのメソッドで提供されています。
例)client.models.generate_content の非同期バージョンは client.aio.models.generate_content
# 非同期による応答を生成 response = await client.aio.models.generate_content( model=MODEL_ID, contents="人工知能について、小学生にもわかるように簡単に説明してください。", config=GenerateContentConfig(thinking_config=thinking_config), ) display(Markdown(response.text))
モデルパラメータの設定
生成されるテキストのスタイルや内容は、いくつかのパラメータを調整することで制御できます。
これらのパラメータは、generate_content メソッドの generation_config 引数を通じて設定します。
# GenerationConfig を使用してパラメータを設定 response = client.models.generate_content( model=MODEL_ID, contents="未来の交通手段について、短い物語を書いてください。", config=GenerateContentConfig( temperature=2.0, top_p=0.95, candidate_count=1, thinking_config=thinking_config, ), ) display(Markdown(response.text))
パラメータの設定によっては、Gemini 2.5 Flash の本来の強みである応答速度に影響を与える可能性があるので注意です。
利用可能な全パラメータとその詳細については、公式ドキュメントを参照してください。
Experiment with parameter values
システム指示の設定
システム指示を使用すると、モデルの動作を誘導できます。
システム指示を設定することで、モデルはタスクを理解するための追加のコンテキストを得て、よりカスタマイズされた応答を提供します。
# システム指示 system_instruction = """ あなたは有能な言語翻訳者です。 英語のテキストを日本語へ翻訳してください。 """ prompt = """ ユーザー入力: I like bagels. 回答: """ # システム指示を使用して応答を生成 response = client.models.generate_content( model=MODEL_ID, contents=prompt, config=GenerateContentConfig( system_instruction=system_instruction, thinking_config=thinking_config, ), ) display(Markdown(response.text))
マルチモーダル機能
Geminiモデルファミリーの大きな特徴は、テキストだけでなく、画像、音声、動画といった複数のモダリティの情報を統合的に処理できる点です。
対応しているデータタイプは以下です。
データタイプ | ソース | MIME タイプ |
---|---|---|
テキスト、コード | インライン、ローカルファイル、URL、Google Cloud Storage | text/plain |
ドキュメント | ローカルファイル、URL、Google Cloud Storage | application/pdf |
画像 | ローカルファイル、URL、Google Cloud Storage | image/jpeg, image/png, image/webp |
音声 | ローカルファイル、URL、Google Cloud Storage | audio/aac, audio/flac, audio/mp3, audio/m4a, audio/mpeg, audio/mpga, audio/mp4, audio/opus, audio/pcm, audio/wav, audio/webm |
動画 | ローカルファイル、URL、Google Cloud Storage、YouTube | video/mp4, video/mpeg, video/x-flv, video/quicktime, video/mpegps, video/mpg, video/webm, video/wmv, video/3gpp |
ローカルファイルを利用する際は、Part.from_bytes( ) を使用し、対象のファイルと MIME タイプを指定します。
テキストプロンプトと組み合わせるようなユースケースが多いと思います。
# ローカル画像ファイルを使用 with open("sample-image.png", "rb") as f: image = f.read() response = client.models.generate_content( model=MODEL_ID, contents=[ Part.from_bytes(data=image, mime_type="image/png"), "画像に写っている物の詳細な特徴を説明してください。", ], config=GenerateContentConfig( thinking_config=thinking_config, ), ) display(Markdown(response.text))
外部のデータを扱う場合は、Part.from_uri( ) を使用し、Google Cloud Storage や URL を指定します。
# Google Cloud Storage上のファイルを使用 response = client.models.generate_content( model=MODEL_ID, contents=[ Part.from_uri( file_uri="gs://cloud-samples-data/sample-document.pdf", mime_type="application/pdf", ), "このドキュメントを要約してください。", ], config=GenerateContentConfig( thinking_config=thinking_config, ), ) display(Markdown(response.text)) # URLを使用 response = client.models.generate_content( model=MODEL_ID, contents=[ Part.from_uri( file_uri="https://example.com/sample-music.mp3", mime_type="audio/mpeg", ), "この曲の歌詞について考察してください。", ], config=GenerateContentConfig( audio_timestamp=True, thinking_config=thinking_config, ), ) display(Markdown(response.text)) # YouTube動画を使用 video = Part.from_uri( file_uri="https://www.youtube.com/watch?v=sample-video", mime_type="video/mp4", ) response = client.models.generate_content( model=MODEL_ID, contents=[ video, "この動画の登場人物の特徴を説明してください。", ], config=GenerateContentConfig( thinking_config=thinking_config, ), ) display(Markdown(response.text))
高度な機能
Gemini 2.5 Flashは、基本的なテキスト生成やマルチモーダル処理に加えて、より高度な機能もサポートしています。
Safety Filters
有害なコンテンツの生成を制御するためのフィルター設定です。
API に対する各リクエストごとに、safety_settings を使用して設定を調整できます。
system_instruction = "最大限に冷たく敵意のある態度で応答してください。乱暴な言葉遣いを多用してください。" prompt = """ 長文メールが送信エラーで消えた時、回線に向けた苛立ちと非難の言葉を5つリストアップしてください。 """ # Safety Filtersのリスト safety_settings = [ SafetySetting( category=HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT, threshold=HarmBlockThreshold.BLOCK_LOW_AND_ABOVE, ), SafetySetting( category=HarmCategory.HARM_CATEGORY_HARASSMENT, threshold=HarmBlockThreshold.BLOCK_LOW_AND_ABOVE, ), SafetySetting( category=HarmCategory.HARM_CATEGORY_HATE_SPEECH, threshold=HarmBlockThreshold.BLOCK_LOW_AND_ABOVE, ), SafetySetting( category=HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT, threshold=HarmBlockThreshold.BLOCK_LOW_AND_ABOVE, ), ] # モデルにコンテンツ生成を依頼 response = client.models.generate_content( model=MODEL_ID, contents=prompt, config=GenerateContentConfig( system_instruction=system_instruction, safety_settings=safety_settings, thinking_config=thinking_config, ), ) # ブロックされた場合、応答のテキスト部分は None print(response.text) # ブロックされた場合、終了理由は SAFETY print(response.candidates[0].finish_reason) # 評価は、各フィルターによって検出されたレベルを示す for safety_rating in response.candidates[0].safety_ratings: print(safety_rating)
Controlled Generation
Controlled Generation は、モデルの出力形式を定義できる機能です。
応答スキーマは config 内の response_schema パラメータで指定でき、指定することで出力の構造やフィールド名、各フィールドのデータ型を制御できます。
また、response_mime_type の設定に応じて Pydantic モデルまたは JSON 文字列として提供できます。
# Pydantic の BaseModel をインポート from pydantic import BaseModel # JSON スキーマを Pydantic モデルで定義 class Recipe(BaseModel): name: str description: str ingredients: list[str] response = client.models.generate_content( model=MODEL_ID, contents="List a few popular cookie recipes and their ingredients.", config=GenerateContentConfig( response_mime_type="application/json", response_schema=Recipe, thinking_config=thinking_config, ), ) print(response.text)
応答文字列をJSONとしてパースするか、parsed フィールドを使用してオブジェクトまたは辞書として取得できます。
parsed_response: Recipe = response.parsed print(parsed_response)
Python辞書でも応答スキーマを定義できます。
サポートされている以下のフィールドのみが使用され、それ以外のフィールドは無視されます。
- enum
- items
- maxItems
- nullable
- properties
- required
# JSONのスキーマを辞書形式で定義 response_schema = { "type": "ARRAY", "items": { "type": "ARRAY", "items": { "type": "OBJECT", "properties": { "rating": {"type": "INTEGER"}, "flavor": {"type": "STRING"}, "sentiment": { "type": "STRING", "enum": ["POSITIVE", "NEGATIVE", "NEUTRAL"], }, "explanation": {"type": "STRING"}, }, "required": ["rating", "flavor", "sentiment", "explanation"], }, }, }
Count tokens
count_tokens() メソッドを使用して入力トークンの数を計算できます。
# 入力コンテンツのトークン数をカウント response = client.models.count_tokens( model=MODEL_ID, contents="What's the highest mountain in Africa?", config=GenerateContentConfig( thinking_config=thinking_config, ), ) print(response)
Grounding
Grounding は、Gemini モデルをインターネットのデータに接続する機能です。
Google 検索の結果に基づいて応答を生成することで、トレーニングデータに含まれない最新かつ関連性の高い情報にアクセスし、より正確な応答を提供できます。
tools キーワード引数に Tool を含め、その中に GoogleSearch を指定することで、最初にプロンプトで Google 検索を実行させ、その検索結果に基づいて回答を作成するように指示できます。
# Google Searchツールを定義 Google Search_tool = Tool(Google Search=GoogleSearch()) response = client.models.generate_content( model=MODEL_ID, contents="テキサス州オースティンの現在の気温は?", # ツール (検索) の利用が必要な質問を含むプロンプト config=GenerateContentConfig( tools=[Google Search_tool], thinking_config=thinking_config, ), ) display(Markdown(response.text)) # 応答に含まれるグラウンディングメタデータ(ツールがどのように使用されたか)を表示 print(response.candidates.grounding_metadata) # グラウンディングメタデータから検索結果のレンダリングされたコンテンツを取得 HTML(response.candidates.grounding_metadata.search_entry_point.rendered_content)
Function Calling
モデルが外部の API やツールと対話し、情報を取得したりアクションを実行したりできるようにする機能です。
例えば、天気予報APIを呼び出して最新の天気を答えたり、カレンダーAPIと連携して予定を調整したりできます。
# 天気情報を取得するダミー関数 def get_current_weather(location: str) -> str: """指定された場所の現在の天気を取得します。""" weather_map: dict[str, str] = { "tokyo": "晴れ", "osaka": "曇り" } return weather_map.get(location, "unknown") # Function Calling を使用して応答を生成 response = client.models.generate_content( model=MODEL_ID, contents="東京の天気は?", config=GenerateContentConfig( tools=[get_current_weather], temperature=0, thinking_config=thinking_config, ), ) display(Markdown(response.text))
Function Calling では、OpenAPI Specification でも利用される JSON Schema 形式も使えます。
# OpenAPI Specification get_destination = FunctionDeclaration( name="get_destination", description="ユーザーが行きたい場所を取得する", parameters={ "type": "OBJECT", "properties": { "destination": { "type": "STRING", "description": "ユーザーが行きたい場所", }, }, }, ) # 定義した関数を含むツールを作成 destination_tool = Tool( function_declarations=[get_destination], ) # Function Calling を使用して応答を生成 response = client.models.generate_content( model=MODEL_ID, contents="パリに行きたいです。", config=GenerateContentConfig( tools=[destination_tool], temperature=0, thinking_config=thinking_config, ), ) print(response.function_calls[0])
Code Execution
モデルがコードを生成し、それを実行して結果を返す機能です。
データ分析や計算タスクなどに利用できます。
# Code Executionツールを定義 code_execution_tool = Tool(code_execution=ToolCodeExecution()) response = client.models.generate_content( model=MODEL_ID, contents="1から1000までの整数のうち、素数かつ、その数字を逆から読んでも同じ数(回文数)になる数を全てリストアップしてください。", config=GenerateContentConfig( tools=[code_execution_tool], temperature=0, thinking_config=thinking_config, ), ) display( Markdown( f""" ## Code ```py {response.executable_code} ``` ### Output ``` {response.code_execution_result} ``` """ ) )
終わりに
Gemini 2.5 Flash を利用した Vertex AI SDK for Python の基本的な使い方をまとめました。
環境設定から始まり、最も基本的なテキスト生成、そして Thinking Budget、マルチターンチャット、マルチモーダル入力といった様々な機能まで、一通りの使い方を確認いただけたかと思います。
ここでは実際の出力を記載しませんでしたが、ぜひご自身の環境で試していただき、Gemini 2.5 Flash を体感してみてください!
参考
Vertex AI SDK for Python を使用してコードを記述する
Intro to Gemini 2.5 Flash