音声理解(音声のみ)

Gemini リクエストに音声を追加して、含まれる音声の内容を理解するタスクを実行できます。このページでは、Google Cloud コンソールと Vertex AI API を使用して、Vertex AI の Gemini へのリクエストに音声を追加する方法について説明します。

サポートされているモデル

次の表に、音声理解をサポートするモデルを示します。

モデル メディアの詳細 MIME タイプ
Gemini 2.5 Flash-Lite
  • プロンプトあたりの音声の最大長: 約 8.4 時間、または最大 100 万トークン
  • プロンプトあたりの音声ファイルの最大数: 1
  • audio/x-aac
  • audio/flac
  • audio/mp3
  • audio/m4a
  • audio/mpeg
  • audio/mpga
  • audio/mp4
  • audio/opus
  • audio/pcm
  • audio/wav
  • audio/webm
Live API ネイティブ音声を使用した Gemini 2.5 Flash
  • 会話の最大長: 約 10 分
  • 音声理解(音声の要約、文字起こし、翻訳)
  • audio/x-aac
  • audio/flac
  • audio/mp3
  • audio/m4a
  • audio/mpeg
  • audio/mpga
  • audio/mp4
  • audio/opus
  • audio/pcm
  • audio/wav
  • audio/webm
Live API を使用した Gemini 2.0 Flash
  • プロンプトあたりの音声の最大長: 約 8.4 時間、または最大 100 万トークン
  • プロンプトあたりの音声ファイルの最大数: 1
  • 音声理解(音声の要約、文字起こし、翻訳)
  • 1 分あたりの最大トークン数(TPM):
    • 米国/アジア: 170 万
    • EU: 0.4 M
  • audio/x-aac
  • audio/flac
  • audio/mp3
  • audio/m4a
  • audio/mpeg
  • audio/mpga
  • audio/mp4
  • audio/opus
  • audio/pcm
  • audio/wav
  • audio/webm
画像生成機能を備えた Gemini 2.0 Flash
  • プロンプトあたりの音声の最大長: 約 8.4 時間、または最大 100 万トークン
  • プロンプトあたりの音声ファイルの最大数: 1
  • 音声理解(音声の要約、文字起こし、翻訳)
  • 1 分あたりの最大トークン数(TPM):
    • 米国/アジア: 170 万
    • EU: 0.4 M
  • audio/x-aac
  • audio/flac
  • audio/mp3
  • audio/m4a
  • audio/mpeg
  • audio/mpga
  • audio/mp4
  • audio/opus
  • audio/pcm
  • audio/wav
  • audio/webm
Gemini 2.5 Pro
  • プロンプトあたりの音声の最大長: 約 8.4 時間、または最大 100 万トークン
  • プロンプトあたりの音声ファイルの最大数: 1
  • 音声理解(音声の要約、文字起こし、翻訳)
  • audio/x-aac
  • audio/flac
  • audio/mp3
  • audio/m4a
  • audio/mpeg
  • audio/mpga
  • audio/mp4
  • audio/opus
  • audio/pcm
  • audio/wav
  • audio/webm
Gemini 2.5 Flash
  • プロンプトあたりの音声の最大長: 約 8.4 時間、または最大 100 万トークン
  • プロンプトあたりの音声ファイルの最大数: 1
  • 音声理解(音声の要約、文字起こし、翻訳)
  • audio/x-aac
  • audio/flac
  • audio/mp3
  • audio/m4a
  • audio/mpeg
  • audio/mpga
  • audio/mp4
  • audio/opus
  • audio/pcm
  • audio/wav
  • audio/webm
Gemini 2.0 Flash
  • プロンプトあたりの音声の最大長: 約 8.4 時間、または最大 100 万トークン
  • プロンプトあたりの音声ファイルの最大数: 1
  • 音声理解(音声の要約、文字起こし、翻訳)
  • 1 分あたりの最大トークン数(TPM):
    • 米国/アジア: 350 万
    • EU: 350 万
  • audio/x-aac
  • audio/flac
  • audio/mp3
  • audio/m4a
  • audio/mpeg
  • audio/mpga
  • audio/mp4
  • audio/opus
  • audio/pcm
  • audio/wav
  • audio/webm
Gemini 2.0 Flash-Lite
  • プロンプトあたりの音声の最大長: 約 8.4 時間、または最大 100 万トークン
  • プロンプトあたりの音声ファイルの最大数: 1
  • 音声理解(音声の要約、文字起こし、翻訳)
  • 1 分あたりの最大トークン数(TPM):
    • 米国/アジア: 350 万
    • EU: 350 万
  • audio/x-aac
  • audio/flac
  • audio/mp3
  • audio/m4a
  • audio/mpeg
  • audio/mpga
  • audio/mp4
  • audio/opus
  • audio/pcm
  • audio/wav
  • audio/webm

割り当て指標は generate_content_audio_input_per_base_model_id_and_resolution です。

Gemini モデルでサポートされている言語の一覧については、モデル情報の Google モデルをご覧ください。マルチモーダル プロンプトの設計方法について詳しくは、マルチモーダル プロンプトを設計するをご覧ください。モバイルアプリやウェブアプリから Gemini を直接使用することをお考えの場合は、Swift、Android、ウェブ、Flutter、Unity アプリの Firebase AI Logic クライアント SDK をご覧ください。

リクエストに音声を追加する

Gemini へのリクエストに音声ファイルを追加できます。

単一の音声

以下で、音声ファイルを使用してポッドキャストを要約する方法について説明します。

コンソール

Google Cloud コンソールでマルチモーダル プロンプトを送信する手順は次のとおりです。

  1. Google Cloud コンソールの [Vertex AI] セクションで、[Vertex AI Studio] ページに移動します。

    Vertex AI Studio に移動

  2. [Create prompt] をクリックします。

  3. 省略可: モデルとパラメータを構成します。

    • Model: モデルを選択します。
  4. 省略可: 詳細パラメータを構成するには、[詳細] をクリックして、次のように構成します。

    クリックして [高度な構成] を開く

    • Top-K: スライダーまたはテキスト ボックスを使用して、Top-K の値を入力します。

      Top-K は、モデルが出力用にトークンを選択する方法を変更します。Top-K が 1 の場合、次に選択されるトークンは、モデルの語彙内のすべてのトークンで最も確率の高いものであることになります(グリーディ デコードとも呼ばれます)。Top-K が 3 の場合は、最も確率が高い上位 3 つのトークンから次のトークン選択されることになります(温度を使用します)。

      トークン選択のそれぞれのステップで、最も高い確率を持つ Top-K のトークンがサンプリングされます。その後、トークンはトップ P に基づいてさらにフィルタリングされ、最終的なトークンは温度サンプリングを用いて選択されます。

      ランダムなレスポンスを減らしたい場合は小さい値を、ランダムなレスポンスを増やしたい場合は大きい値を指定します。

    • トップ P: スライダーまたはテキスト ボックスを使用して、トップ P の値を入力します。確率の合計が Top-P の値と等しくなるまで、最も確率が高いものから最も確率が低いものの順に、トークンが選択されます。結果を最小にするには、Top-P を 0 に設定します。
    • 最大レスポンス数: スライダーまたはテキスト ボックスを使用して、生成するレスポンスの数の値を入力します。
    • ストリーミング レスポンス: 有効にすると、レスポンスが生成されたときに出力されます。
    • 安全フィルタのしきい値: 有害なおそれのあるレスポンスが表示される可能性のしきい値を選択します。
    • グラウンディングを有効にする: マルチモーダル プロンプトでは、グラウンティングはサポートされていません。
    • リージョン: 使用するリージョンを選択します。
    • 温度: スライダーまたはテキスト ボックスを使用して、温度の値を入力します。

          
      The temperature is used for sampling during response generation, which occurs when topP
      and topK are applied. Temperature controls the degree of randomness in token selection.
      Lower temperatures are good for prompts that require a less open-ended or creative response, while
      higher temperatures can lead to more diverse or creative results. A temperature of 0
      means that the highest probability tokens are always selected. In this case, responses for a given
      prompt are mostly deterministic, but a small amount of variation is still possible.
      
      

      If the model returns a response that's too generic, too short, or the model gives a fallback response, try increasing the temperature.

      </li> <li>**Output token limit**: Use the slider or textbox to enter a value for the max output limit. Maximum number of tokens that can be generated in the response. A token is approximately four characters. 100 tokens correspond to roughly 60-80 words.

      Specify a lower value for shorter responses and a higher value for potentially longer responses.

      </li> <li>**Add stop sequence**: Optional. Enter a stop sequence, which is a series of characters that includes spaces. If the model encounters a stop sequence, the response generation stops. The stop sequence isn't included in the response, and you can add up to five stop sequences.</li> </ul>

  5. [メディアを挿入] をクリックし、ファイルのソースを選択します。

    アップロード

    アップロードするファイルを選択して [開く] をクリックします。

    URL

    使用するファイルの URL を入力し、[挿入] をクリックします。

    Cloud Storage

    バケットを選択してから、バケット内のインポートするファイルを選択し、[選択] をクリックします。

    Google ドライブ

    1. このオプションを初めて選択するときに、アカウントを選択して Vertex AI Studio がアカウントにアクセスできるように同意します。合計サイズが最大 10 MB の複数のファイルをアップロードできます。1 つのファイルのサイズが 7 MB を超えないようにしてください。
    2. 追加するファイルをクリックします。
    3. [選択] をクリックします。

      ファイルのサムネイルが [プロンプト] ペインに表示されます。トークンの合計数も表示されます。プロンプト データがトークンの上限を超えると、トークンは切り捨てられ、データの処理には含まれません。

  6. [プロンプト] ペインにテキスト プロンプトを入力します。

  7. 省略可: [テキストのトークン ID] と [トークン ID] を表示するには、[プロンプト] ペインで [トークン数] をクリックします。

  8. [送信] をクリックします。

  9. 省略可: プロンプトを [マイプロンプト] に保存するには、[ 保存] をクリックします。

  10. 省略可: プロンプトの Python コードまたは curl コマンドを取得するには、[ コードで構築 > コードを取得] をクリックします。

Gen AI SDK for Python

インストール

pip install --upgrade google-genai

詳しくは、 SDK リファレンス ドキュメントをご覧ください。

Vertex AI で Gen AI SDK を使用するための環境変数を設定します。

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import HttpOptions, Part

client = genai.Client(http_options=HttpOptions(api_version="v1"))
prompt = """
Provide a concise summary of the main points in the audio file.
"""
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents=[
        prompt,
        Part.from_uri(
            file_uri="gs://cloud-samples-data/generative-ai/audio/pixel.mp3",
            mime_type="audio/mpeg",
        ),
    ],
)
print(response.text)
# Example response:
# Here's a summary of the main points from the audio file:

# The Made by Google podcast discusses the Pixel feature drops with product managers Aisha Sheriff and De Carlos Love.  The key idea is that devices should improve over time, with a connected experience across phones, watches, earbuds, and tablets.

Gen AI SDK for Go

Gen AI SDK for Go をインストールまたは更新する方法をご確認ください。

詳しくは、 SDK リファレンス ドキュメントをご覧ください。

Vertex AI で Gen AI SDK を使用するための環境変数を設定します。

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

import (
	"context"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateWithAudio shows how to generate text using an audio input.
func generateWithAudio(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	modelName := "gemini-2.0-flash-001"
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: `Provide the summary of the audio file.
Summarize the main points of the audio concisely.
Create a chapter breakdown with timestamps for key sections or topics discussed.`},
			{FileData: &genai.FileData{
				FileURI:  "gs://cloud-samples-data/generative-ai/audio/pixel.mp3",
				MIMEType: "audio/mpeg",
			}},
		}},
	}

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, nil)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	respText, err := resp.Text()
	if err != nil {
		return fmt.Errorf("failed to convert model response to text: %w", err)
	}
	fmt.Fprintln(w, respText)

	// Example response:
	// Here is a summary and chapter breakdown of the audio file:
	//
	// **Summary:**
	//
	// The audio file is a "Made by Google" podcast episode discussing the Pixel Feature Drops, ...
	//
	// **Chapter Breakdown:**
	//
	// *   **0:00 - 0:54:** Introduction to the podcast and guests, Aisha Sharif and DeCarlos Love.
	// ...

	return nil
}

REST

環境をセットアップしたら、REST を使用してテキスト プロンプトをテストできます。次のサンプルは、パブリッシャー モデルのエンドポイントにリクエストを送信します。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: 実際のプロジェクト ID
  • FILE_URI: プロンプトに含めるファイルの URI または URL。指定できる値は以下のとおりです。
    • Cloud Storage バケット URI: オブジェクトは一般公開されているか、リクエストを送信する Google Cloud プロジェクトと同じプロジェクトに存在している必要があります。gemini-2.0-flashgemini-2.0-flash-lite の場合、サイズの上限は 2 GB です。
    • HTTP URL: ファイルの URL は一般公開されている必要があります。リクエストごとに 1 つの動画ファイル、1 つの音声ファイル、最大 10 個の画像ファイルを指定できます。音声ファイル、動画ファイル、ドキュメントのサイズは 15 MB 以下にする必要があります。
    • YouTube 動画の URL: YouTube 動画は、 Google Cloud コンソールのログインに使用したアカウントが所有しているか、公開されている必要があります。リクエストごとにサポートされる YouTube 動画の URL は 1 つだけです。

    fileURI を指定する場合は、ファイルのメディアタイプ(mimeType)も指定する必要があります。VPC Service Controls が有効になっている場合、fileURI のメディア ファイル URL の指定はサポートされていません。

    Cloud Storage に音声ファイルがない場合は、MIME タイプが audio/mp3 の一般公開ファイル gs://cloud-samples-data/generative-ai/audio/pixel.mp3 を使用できます。この音声を聴くには、サンプル MP3 ファイルを開きます

  • MIME_TYPE: data フィールドまたは fileUri フィールドで指定されたファイルのメディアタイプ。指定できる値は以下のとおりです。

    クリックして MIME タイプを開く

    • application/pdf
    • audio/mpeg
    • audio/mp3
    • audio/wav
    • image/png
    • image/jpeg
    • image/webp
    • text/plain
    • video/mov
    • video/mpeg
    • video/mp4
    • video/mpg
    • video/avi
    • video/wmv
    • video/mpegps
    • video/flv
  • TEXT
    プロンプトに含める指示のテキスト。例: Please provide a summary for the audio. Provide chapter titles, be concise and short, no need to provide chapter summaries. Do not make up any information that is not part of the audio and do not be verbose.

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存します。ターミナルで次のコマンドを実行して、このファイルを現在のディレクトリに作成または上書きします。

cat > request.json << 'EOF'
{
  "contents": {
    "role": "USER",
    "parts": [
      {
        "fileData": {
          "fileUri": "FILE_URI",
          "mimeType": "MIME_TYPE"
        }
      },
      {
        "text": "TEXT"
      }
    ]
  }
}
EOF

その後、次のコマンドを実行して REST リクエストを送信します。

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/publishers/google/models/gemini-2.0-flash:generateContent"

PowerShell

リクエスト本文を request.json という名前のファイルに保存します。ターミナルで次のコマンドを実行して、このファイルを現在のディレクトリに作成または上書きします。

@'
{
  "contents": {
    "role": "USER",
    "parts": [
      {
        "fileData": {
          "fileUri": "FILE_URI",
          "mimeType": "MIME_TYPE"
        }
      },
      {
        "text": "TEXT"
      }
    ]
  }
}
'@  | Out-File -FilePath request.json -Encoding utf8

その後、次のコマンドを実行して REST リクエストを送信します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/publishers/google/models/gemini-2.0-flash:generateContent" | Select-Object -Expand Content

次のような JSON レスポンスが返されます。

このサンプルの URL にある次の点に注意してください。
  • generateContent メソッドを使用して、レスポンスが完全に生成された後に返されるようにリクエストします。ユーザーが認識するレイテンシを短縮するには、streamGenerateContent メソッドを使用して、生成時にレスポンスをストリーミングします。
  • マルチモーダル モデル ID は、URL の末尾のメソッドの前に配置されます(例: gemini-2.0-flash)。このサンプルでは、他のモデルもサポートされている場合があります。

音声文字起こし

以下で、音声ファイルを使用してインタビューを文字に変換する方法について説明します。音声のみのファイルでタイムスタンプの認識を有効にするには、GenerationConfigaudioTimestamp パラメータを有効にします。

コンソール

Google Cloud コンソールでマルチモーダル プロンプトを送信する手順は次のとおりです。

  1. Google Cloud コンソールの [Vertex AI] セクションで、[Vertex AI Studio] ページに移動します。

    Vertex AI Studio に移動

  2. [Create prompt] をクリックします。

  3. 省略可: モデルとパラメータを構成します。

    • Model: モデルを選択します。
  4. 省略可: 詳細パラメータを構成するには、[詳細] をクリックして、次のように構成します。

    クリックして [高度な構成] を開く

    • Top-K: スライダーまたはテキスト ボックスを使用して、Top-K の値を入力します。

      Top-K は、モデルが出力用にトークンを選択する方法を変更します。Top-K が 1 の場合、次に選択されるトークンは、モデルの語彙内のすべてのトークンで最も確率の高いものであることになります(グリーディ デコードとも呼ばれます)。Top-K が 3 の場合は、最も確率が高い上位 3 つのトークンから次のトークン選択されることになります(温度を使用します)。

      トークン選択のそれぞれのステップで、最も高い確率を持つ Top-K のトークンがサンプリングされます。その後、トークンはトップ P に基づいてさらにフィルタリングされ、最終的なトークンは温度サンプリングを用いて選択されます。

      ランダムなレスポンスを減らしたい場合は小さい値を、ランダムなレスポンスを増やしたい場合は大きい値を指定します。

    • トップ P: スライダーまたはテキスト ボックスを使用して、トップ P の値を入力します。確率の合計が Top-P の値と等しくなるまで、最も確率が高いものから最も確率が低いものの順に、トークンが選択されます。結果を最小にするには、Top-P を 0 に設定します。
    • 最大レスポンス数: スライダーまたはテキスト ボックスを使用して、生成するレスポンスの数の値を入力します。
    • ストリーミング レスポンス: 有効にすると、レスポンスが生成されたときに出力されます。
    • 安全フィルタのしきい値: 有害なおそれのあるレスポンスが表示される可能性のしきい値を選択します。
    • グラウンディングを有効にする: マルチモーダル プロンプトでは、グラウンティングはサポートされていません。
    • リージョン: 使用するリージョンを選択します。
    • 温度: スライダーまたはテキスト ボックスを使用して、温度の値を入力します。

          
      The temperature is used for sampling during response generation, which occurs when topP
      and topK are applied. Temperature controls the degree of randomness in token selection.
      Lower temperatures are good for prompts that require a less open-ended or creative response, while
      higher temperatures can lead to more diverse or creative results. A temperature of 0
      means that the highest probability tokens are always selected. In this case, responses for a given
      prompt are mostly deterministic, but a small amount of variation is still possible.
      
      

      If the model returns a response that's too generic, too short, or the model gives a fallback response, try increasing the temperature.

      </li> <li>**Output token limit**: Use the slider or textbox to enter a value for the max output limit. Maximum number of tokens that can be generated in the response. A token is approximately four characters. 100 tokens correspond to roughly 60-80 words.

      Specify a lower value for shorter responses and a higher value for potentially longer responses.

      </li> <li>**Add stop sequence**: Optional. Enter a stop sequence, which is a series of characters that includes spaces. If the model encounters a stop sequence, the response generation stops. The stop sequence isn't included in the response, and you can add up to five stop sequences.</li> </ul>

  5. [メディアを挿入] をクリックし、ファイルのソースを選択します。

    アップロード

    アップロードするファイルを選択して [開く] をクリックします。

    URL

    使用するファイルの URL を入力し、[挿入] をクリックします。

    Cloud Storage

    バケットを選択してから、バケット内のインポートするファイルを選択し、[選択] をクリックします。

    Google ドライブ

    1. このオプションを初めて選択するときに、アカウントを選択して Vertex AI Studio がアカウントにアクセスできるように同意します。合計サイズが最大 10 MB の複数のファイルをアップロードできます。1 つのファイルのサイズが 7 MB を超えないようにしてください。
    2. 追加するファイルをクリックします。
    3. [選択] をクリックします。

      ファイルのサムネイルが [プロンプト] ペインに表示されます。トークンの合計数も表示されます。プロンプト データがトークンの上限を超えると、トークンは切り捨てられ、データの処理には含まれません。

  6. [プロンプト] ペインにテキスト プロンプトを入力します。

  7. 省略可: [テキストのトークン ID] と [トークン ID] を表示するには、[プロンプト] ペインで [トークン数] をクリックします。

  8. [送信] をクリックします。

  9. 省略可: プロンプトを [マイプロンプト] に保存するには、[ 保存] をクリックします。

  10. 省略可: プロンプトの Python コードまたは curl コマンドを取得するには、[ コードで構築 > コードを取得] をクリックします。

Gen AI SDK for Python

インストール

pip install --upgrade google-genai

詳しくは、 SDK リファレンス ドキュメントをご覧ください。

Vertex AI で Gen AI SDK を使用するための環境変数を設定します。

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import GenerateContentConfig, HttpOptions, Part

client = genai.Client(http_options=HttpOptions(api_version="v1"))
prompt = """
Transcribe the interview, in the format of timecode, speaker, caption.
Use speaker A, speaker B, etc. to identify speakers.
"""
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents=[
        prompt,
        Part.from_uri(
            file_uri="gs://cloud-samples-data/generative-ai/audio/pixel.mp3",
            mime_type="audio/mpeg",
        ),
    ],
    # Required to enable timestamp understanding for audio-only files
    config=GenerateContentConfig(audio_timestamp=True),
)
print(response.text)
# Example response:
# [00:00:00] **Speaker A:** your devices are getting better over time. And so ...
# [00:00:14] **Speaker B:** Welcome to the Made by Google podcast where we meet ...
# [00:00:20] **Speaker B:** Here's your host, Rasheed Finch.
# [00:00:23] **Speaker C:** Today we're talking to Aisha Sharif and DeCarlos Love. ...
# ...

Gen AI SDK for Go

Gen AI SDK for Go をインストールまたは更新する方法をご確認ください。

詳しくは、 SDK リファレンス ドキュメントをご覧ください。

Vertex AI で Gen AI SDK を使用するための環境変数を設定します。

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

import (
	"context"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateAudioTranscript shows how to generate an audio transcript.
func generateAudioTranscript(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	modelName := "gemini-2.0-flash-001"
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: `Transcribe the interview, in the format of timecode, speaker, caption.
Use speaker A, speaker B, etc. to identify speakers.`},
			{FileData: &genai.FileData{
				FileURI:  "gs://cloud-samples-data/generative-ai/audio/pixel.mp3",
				MIMEType: "audio/mpeg",
			}},
		}},
	}

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, nil)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	respText, err := resp.Text()
	if err != nil {
		return fmt.Errorf("failed to convert model response to text: %w", err)
	}
	fmt.Fprintln(w, respText)

	// Example response:
	// 00:00:00, A: your devices are getting better over time.
	// 00:01:13, A: And so we think about it across the entire portfolio from phones to watch, ...
	// ...

	return nil
}

REST

環境をセットアップしたら、REST を使用してテキスト プロンプトをテストできます。次のサンプルは、パブリッシャー モデルのエンドポイントにリクエストを送信します。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: 実際のプロジェクト ID
  • FILE_URI: プロンプトに含めるファイルの URI または URL。指定できる値は以下のとおりです。
    • Cloud Storage バケット URI: オブジェクトは一般公開されているか、リクエストを送信する Google Cloud プロジェクトと同じプロジェクトに存在している必要があります。gemini-2.0-flashgemini-2.0-flash-lite の場合、サイズの上限は 2 GB です。
    • HTTP URL: ファイルの URL は一般公開されている必要があります。リクエストごとに 1 つの動画ファイル、1 つの音声ファイル、最大 10 個の画像ファイルを指定できます。音声ファイル、動画ファイル、ドキュメントのサイズは 15 MB 以下にする必要があります。
    • YouTube 動画の URL: YouTube 動画は、 Google Cloud コンソールのログインに使用したアカウントが所有しているか、公開されている必要があります。リクエストごとにサポートされる YouTube 動画の URL は 1 つだけです。

    fileURI を指定する場合は、ファイルのメディアタイプ(mimeType)も指定する必要があります。VPC Service Controls が有効になっている場合、fileURI のメディア ファイル URL の指定はサポートされていません。

    Cloud Storage に音声ファイルがない場合は、MIME タイプが audio/mp3 の一般公開ファイル gs://cloud-samples-data/generative-ai/audio/pixel.mp3 を使用できます。この音声を聴くには、サンプル MP3 ファイルを開きます

  • MIME_TYPE: data フィールドまたは fileUri フィールドで指定されたファイルのメディアタイプ。指定できる値は以下のとおりです。

    クリックして MIME タイプを開く

    • application/pdf
    • audio/mpeg
    • audio/mp3
    • audio/wav
    • image/png
    • image/jpeg
    • image/webp
    • text/plain
    • video/mov
    • video/mpeg
    • video/mp4
    • video/mpg
    • video/avi
    • video/wmv
    • video/mpegps
    • video/flv
  • TEXT
    プロンプトに含める指示のテキスト。例: Can you transcribe this interview, in the format of timecode, speaker, caption. Use speaker A, speaker B, etc. to identify speakers.

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存します。ターミナルで次のコマンドを実行して、このファイルを現在のディレクトリに作成または上書きします。

cat > request.json << 'EOF'
{
  "contents": {
    "role": "USER",
    "parts": [
      {
        "fileData": {
          "fileUri": "FILE_URI",
          "mimeType": "MIME_TYPE"
        }
      },
      {
        "text": "TEXT"
      }
    ]
  },
  "generatationConfig": {
    "audioTimestamp": true
  }
}
EOF

その後、次のコマンドを実行して REST リクエストを送信します。

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/publishers/google/models/gemini-2.0-flash:generateContent"

PowerShell

リクエスト本文を request.json という名前のファイルに保存します。ターミナルで次のコマンドを実行して、このファイルを現在のディレクトリに作成または上書きします。

@'
{
  "contents": {
    "role": "USER",
    "parts": [
      {
        "fileData": {
          "fileUri": "FILE_URI",
          "mimeType": "MIME_TYPE"
        }
      },
      {
        "text": "TEXT"
      }
    ]
  },
  "generatationConfig": {
    "audioTimestamp": true
  }
}
'@  | Out-File -FilePath request.json -Encoding utf8

その後、次のコマンドを実行して REST リクエストを送信します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/publishers/google/models/gemini-2.0-flash:generateContent" | Select-Object -Expand Content

次のような JSON レスポンスが返されます。

このサンプルの URL にある次の点に注意してください。
  • generateContent メソッドを使用して、レスポンスが完全に生成された後に返されるようにリクエストします。ユーザーが認識するレイテンシを短縮するには、streamGenerateContent メソッドを使用して、生成時にレスポンスをストリーミングします。
  • マルチモーダル モデル ID は、URL の末尾のメソッドの前に配置されます(例: gemini-2.0-flash)。このサンプルでは、他のモデルもサポートされている場合があります。

オプションのモデル パラメータを設定する

各モデルには、設定可能な一連のオプション パラメータがあります。詳細については、コンテンツ生成パラメータをご覧ください。

制限事項

Gemini マルチモーダル モデルは多くのマルチモーダル ユースケースに対応していますが、モデルの制限事項も理解しておく必要があります。

  • 非音声の認識: 音声をサポートするモデルでは、音声以外の音を認識する際に誤りが発生する可能性があります。
  • 音声のみのタイムスタンプ: 音声のみのファイルのタイムスタンプを正確に生成するには、generation_configaudio_timestamp パラメータを構成する必要があります。

次のステップ