音频理解(仅限语音)

您可以向 Gemini 请求添加音频,以便执行涉及理解所含音频内容的任务。本页面介绍了如何使用Google Cloud 控制台和 Vertex AI API,在 Vertex AI 中向发送给 Gemini 的请求添加音频。

支持的模型

下表列出了支持音频理解的模型:

模型 媒体详情 MIME 类型
Gemini 2.5 Flash
  • 每个提示的音频时长上限:约 8.4 小时或最多 100 万个 token
  • 每个提示的音频文件数量上限: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-Lite
  • 每个提示的音频时长上限:约 8.4 小时或最多 100 万个 token
  • 每个提示的音频文件数量上限: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-Lite
  • 每个提示的音频时长上限:约 8.4 小时或最多 100 万个 token
  • 每个提示的音频文件数量上限: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(支持 Live API 原生音频功能)
  • 对话时长上限:默认时长为 10 分钟,可延长
  • 所需的音频输入格式:16 kHz 的原始 16 位 PCM 音频,小端字节序
  • 所需的音频输出格式:24 kHz 原始 16 位 PCM 音频,小端字节序
  • 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(支持 Live API)
  • 每个提示的音频时长上限:约 8.4 小时或最多 100 万个 token
  • 每个提示的音频文件数量上限:1
  • 语音理解用途:音频总结、转写和翻译
  • 每分钟 token 数 (TPM) 上限:
    • 美国/亚洲:1.7 M
    • 欧盟: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 万个 token
  • 每个提示的音频文件数量上限:1
  • 语音理解用途:音频总结、转写和翻译
  • 每分钟 token 数 (TPM) 上限:
    • 美国/亚洲:1.7 M
    • 欧盟: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 万个 token
  • 每个提示的音频文件数量上限: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 万个 token
  • 每个提示的音频文件数量上限: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 万个 token
  • 每个提示的音频文件数量上限:1
  • 语音理解用途:音频总结、转写和翻译
  • 每分钟 token 数 (TPM) 上限:
    • 美国/亚洲:3.5 M
    • 欧盟:3.5 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-Lite
  • 每个提示的音频时长上限:约 8.4 小时或最多 100 万个 token
  • 每个提示的音频文件数量上限:1
  • 语音理解用途:音频总结、转写和翻译
  • 每分钟 token 数 (TPM) 上限:
    • 美国/亚洲:3.5 M
    • 欧盟:3.5 M
  • 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 模型的模型信息。如需详细了解如何设计多模态提示,请参阅设计多模态提示。如果您正在寻找一种直接在移动应用和 Web 应用中使用 Gemini 的方法,请参阅适用于 Swift、Android、Web、Flutter 和 Unity 应用的 Firebase AI Logic 客户端 SDK

向请求添加音频

您可以在向 Gemini 发送的请求中添加音频文件。

单一音频

下面展示了如何使用音频文件来总结播客。

控制台

如需使用 Google Cloud 控制台发送多模态提示,请执行以下操作:

  1. 在 Google Cloud 控制台的 Vertex AI 部分中,进入 Vertex AI Studio 页面。

    前往 Vertex AI Studio

  2. 点击创建提示

  3. 可选:配置模型和参数:

    • 模型:选择一个模型。
  4. 可选:如需配置高级参数,请点击高级,然后按如下方式进行配置:

    点击即可展开高级配置

    • Top-K:使用滑块或文本框输入 top-K 值。

      Top-K 可更改模型选择输出词元的方式。如果 top-K 设为 1,表示所选词元是模型词汇表的所有词元中概率最高的词元(也称为贪心解码)。如果 top-K 设为 3,则表示系统将从 3 个概率最高的词元(通过温度确定)中选择下一个词元。

      在每个词元选择步骤中,系统都会对概率最高的 top-K 词元进行采样。然后,系统会根据 top-P 进一步过滤词元,并使用温度采样选择最终的词元。

      指定较低的值可获得随机程度较低的回答,指定较高的值可获得随机程度较高的回答。

    • Top-P:使用滑块或文本框输入 top-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. 点击插入媒体,然后为文件选择一个来源。

    上传

    选择您要上传的文件,然后点击打开

    通过网址

    输入要使用的文件的网址,然后点击插入

    Cloud Storage

    选择存储桶,接着从存储桶选择您要导入的文件,然后点击选择

    Google 云端硬盘

    1. 选择一个账号,并在您首次选择此选项时同意 Vertex AI Studio 访问您的账号。您可以上传多个文件,但总大小不得超过 10 MB。单个文件的大小不能超过 7 MB。
    2. 点击要添加的文件。
    3. 点击选择

      文件缩略图会显示在提示窗格中。 系统还会显示 token 总数。如果提示数据超过 token 限制,则 token 会被截断,并且不会用于处理数据。

  6. 提示窗格中输入文本提示。

  7. 可选:如需查看 Token ID 到文本Token ID,请点击提示窗格中的 token 数量

  8. 点击提交

  9. 可选:如需将提示保存到我的提示,请点击 保存

  10. 可选:如需获取提示对应的 Python 代码或 curl 命令,请点击 使用代码构建 > 获取代码

Python

安装

pip install --upgrade google-genai

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# 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.

Go

了解如何安装或更新 Go

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# 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.5-flash"
	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",
			}},
		},
			Role: "user"},
	}

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

	respText := resp.Text()

	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
}

Node.js

安装

npm install @google/genai

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# 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

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function generateText(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const prompt =
    'Provide a concise summary of the main points in the audio file.';

  const response = await client.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: [
      {
        fileData: {
          fileUri: 'gs://cloud-samples-data/generative-ai/audio/pixel.mp3',
          mimeType: 'audio/mpeg',
        },
      },
      {text: prompt},
    ],
  });

  console.log(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.

  return response.text;
}

Java

了解如何安装或更新 Java

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# 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 com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Part;

public class TextGenerationWithGcsAudio {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";
    generateContent(modelId);
  }

  // Generates text with audio input
  public static String generateContent(String modelId) {
    // Client Initialization. Once created, it can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              Content.fromParts(
                  Part.fromUri(
                      "gs://cloud-samples-data/generative-ai/audio/pixel.mp3", "audio/mpeg"),
                  Part.fromText("Provide a concise summary of the main points in the audio file.")),
              null);

      System.out.print(response.text());
      // Example response:
      // The audio features Google product managers Aisha Sharif and D. Carlos Love discussing Pixel
      // Feature Drops, emphasizing their role in continually enhancing devices across the entire
      // Pixel ecosystem...
      return response.text();
    }
  }
}

REST

设置您的环境后,您可以使用 REST 测试文本提示。以下示例会向发布方模型端点发送请求。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的项目 ID
  • FILE_URI:要包含在提示中的文件的 URI 或网址。可接受的值包括:
    • Cloud Storage 存储桶 URI:对象必须可公开读取,或者位于发送请求的同一 Google Cloud 项目中。对于 gemini-2.0-flashgemini-2.0-flash-lite,大小限制为 2 GB。
    • HTTP 网址:文件网址必须可公开读取。您可以为每个请求指定一个视频文件、一个音频文件和最多 10 个图片文件。音频文件、视频文件和文档的大小不得超过 15 MB。
    • YouTube 视频网址:YouTube 视频必须由您用于登录 Google Cloud 控制台的账号所拥有,或者是公开的。每个请求仅支持一个 YouTube 视频网址。

    指定 fileURI 时,您还必须指定文件的媒体类型 (mimeType)。 如果启用了 VPC Service Controls,则不支持为 fileURI 指定媒体文件网址。

    如果您在 Cloud Storage 中没有音频文件,则可以使用以下公开提供的文件:gs://cloud-samples-data/generative-ai/audio/pixel.mp3,MIME 类型为 audio/mp3。如需收听此音频,请打开示例 MP3 文件。

  • MIME_TYPE:在 datafileUri 字段中指定的文件的媒体类型。可接受的值包括:

    点击即可展开 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 响应。

请注意此示例网址中的以下内容:
  • 使用 generateContent 方法请求在回答完全生成后返回回答。 为了降低真人观众对于延迟的感知度,请使用 streamGenerateContent 方法在生成回答时流式传输回答。
  • 多模态模型 ID 位于网址末尾且位于方法之前(例如 gemini-2.0-flash)。此示例可能还支持其他模型。

音频转写

下面展示了如何使用音频文件转写面试内容。如需为仅音频文件启用时间戳理解功能,请在 GenerationConfig 中启用 audioTimestamp 参数。

控制台

如需使用 Google Cloud 控制台发送多模态提示,请执行以下操作:

  1. 在 Google Cloud 控制台的 Vertex AI 部分中,进入 Vertex AI Studio 页面。

    前往 Vertex AI Studio

  2. 点击创建提示

  3. 可选:配置模型和参数:

    • 模型:选择一个模型。
  4. 可选:如需配置高级参数,请点击高级,然后按如下方式进行配置:

    点击即可展开高级配置

    • Top-K:使用滑块或文本框输入 top-K 值。

      Top-K 可更改模型选择输出词元的方式。如果 top-K 设为 1,表示所选词元是模型词汇表的所有词元中概率最高的词元(也称为贪心解码)。如果 top-K 设为 3,则表示系统将从 3 个概率最高的词元(通过温度确定)中选择下一个词元。

      在每个词元选择步骤中,系统都会对概率最高的 top-K 词元进行采样。然后,系统会根据 top-P 进一步过滤词元,并使用温度采样选择最终的词元。

      指定较低的值可获得随机程度较低的回答,指定较高的值可获得随机程度较高的回答。

    • Top-P:使用滑块或文本框输入 top-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. 点击插入媒体,然后为文件选择一个来源。

    上传

    选择您要上传的文件,然后点击打开

    通过网址

    输入要使用的文件的网址,然后点击插入

    Cloud Storage

    选择存储桶,接着从存储桶选择您要导入的文件,然后点击选择

    Google 云端硬盘

    1. 选择一个账号,并在您首次选择此选项时同意 Vertex AI Studio 访问您的账号。您可以上传多个文件,但总大小不得超过 10 MB。单个文件的大小不能超过 7 MB。
    2. 点击要添加的文件。
    3. 点击选择

      文件缩略图会显示在提示窗格中。 系统还会显示 token 总数。如果提示数据超过 token 限制,则 token 会被截断,并且不会用于处理数据。

  6. 提示窗格中输入文本提示。

  7. 可选:如需查看 Token ID 到文本Token ID,请点击提示窗格中的 token 数量

  8. 点击提交

  9. 可选:如需将提示保存到我的提示,请点击 保存

  10. 可选:如需获取提示对应的 Python 代码或 curl 命令,请点击 使用代码构建 > 获取代码

Python

安装

pip install --upgrade google-genai

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# 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. ...
# ...

Go

了解如何安装或更新 Go

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# 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.5-flash"
	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",
			}},
		},
			Role: "user"},
	}

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

	respText := resp.Text()

	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
}

Node.js

安装

npm install @google/genai

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# 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

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function generateText(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const prompt = `Transcribe the interview, in the format of timecode, speaker, caption.
    Use speaker A, speaker B, etc. to identify speakers.`;

  const response = await client.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: [
      {text: prompt},
      {
        fileData: {
          fileUri: 'gs://cloud-samples-data/generative-ai/audio/pixel.mp3',
          mimeType: 'audio/mpeg',
        },
      },
    ],
    // Required to enable timestamp understanding for audio-only files
    config: {
      audioTimestamp: true,
    },
  });

  console.log(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. ...
  // ...

  return response.text;
}

Java

了解如何安装或更新 Java

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# 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 com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Part;

public class TextGenerationTranscriptWithGcsAudio {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";
    generateContent(modelId);
  }

  // Generates transcript with audio input
  public static String generateContent(String modelId) {
    // Client Initialization. Once created, it can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      String prompt =
          "Transcribe the interview, in the format of timecode, speaker, caption.\n"
              + "Use speaker A, speaker B, etc. to identify speakers.";

      // Enable audioTimestamp to generate timestamps for audio-only files.
      GenerateContentConfig contentConfig =
          GenerateContentConfig.builder().audioTimestamp(true).build();

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              Content.fromParts(
                  Part.fromUri(
                      "gs://cloud-samples-data/generative-ai/audio/pixel.mp3", "audio/mpeg"),
                  Part.fromText(prompt)),
              contentConfig);

      System.out.print(response.text());
      // Example response:
      // 00:00 - Speaker A: your devices are getting better over time. And so we think about it...
      // 00:14 - Speaker B: Welcome to the Made by Google Podcast, where we meet the people who...
      // 00:41 - Speaker A: So many features. I am a singer, so I actually think recorder...
      return response.text();
    }
  }
}

REST

设置您的环境后,您可以使用 REST 测试文本提示。以下示例会向发布方模型端点发送请求。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:。
  • FILE_URI:要包含在提示中的文件的 URI 或网址。可接受的值包括:
    • Cloud Storage 存储桶 URI:对象必须可公开读取,或者位于发送请求的同一 Google Cloud 项目中。对于 gemini-2.0-flashgemini-2.0-flash-lite,大小限制为 2 GB。
    • HTTP 网址:文件网址必须可公开读取。您可以为每个请求指定一个视频文件、一个音频文件和最多 10 个图片文件。音频文件、视频文件和文档的大小不得超过 15 MB。
    • YouTube 视频网址:YouTube 视频必须由您用于登录 Google Cloud 控制台的账号所拥有,或者是公开的。每个请求仅支持一个 YouTube 视频网址。

    指定 fileURI 时,您还必须指定文件的媒体类型 (mimeType)。 如果启用了 VPC Service Controls,则不支持为 fileURI 指定媒体文件网址。

    如果您在 Cloud Storage 中没有音频文件,则可以使用以下公开提供的文件:gs://cloud-samples-data/generative-ai/audio/pixel.mp3,MIME 类型为 audio/mp3。如需收听此音频,请打开示例 MP3 文件。

  • MIME_TYPE:在 datafileUri 字段中指定的文件的媒体类型。可接受的值包括:

    点击即可展开 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 响应。

请注意此示例网址中的以下内容:
  • 使用 generateContent 方法请求在回答完全生成后返回回答。 为了降低真人观众对于延迟的感知度,请使用 streamGenerateContent 方法在生成回答时流式传输回答。
  • 多模态模型 ID 位于网址末尾且位于方法之前(例如 gemini-2.0-flash)。此示例可能还支持其他模型。

设置可选模型参数

每个模型都有一组可设置的可选参数。如需了解详情,请参阅内容生成参数

限制

虽然多模态 Gemini 模型在许多多模态应用场景中表现出强大功能,但了解模型的限制非常重要:

  • 非语音声音识别:支持音频的模型可能会在识别非语音声音时犯错。
  • 仅音频的时间戳:如需为仅音频文件准确生成时间戳,您必须在 generation_config 中配置 audio_timestamp 参数。

后续步骤