오디오 인식(음성만)

Gemini 요청에 오디오를 추가하여 포함된 오디오의 콘텐츠를 이해하는 것과 관련된 작업을 수행할 수 있습니다. 이 페이지에서는Google Cloud 콘솔과 Vertex AI API를 사용하여 Vertex AI의 Gemini에 대한 요청에 오디오를 추가하는 방법을 보여줍니다.

지원되는 모델

다음 표에는 오디오 인식을 지원하는 모델이 나와 있습니다.

모델 미디어 세부정보 MIME 유형
Gemini 2.5 Flash (미리보기)
  • 프롬프트당 최대 오디오 길이: 최대 8.4시간 또는 토큰 최대 100만 개
  • 프롬프트당 최대 오디오 파일 수: 1
  • 음성 이해: 오디오 요약, 스크립트 작성, 번역
  • audio/x-aac
  • audio/flac
  • audio/mp3
  • audio/m4a
  • audio/mpeg
  • audio/mpga
  • audio/mp4
  • audio/ogg
  • audio/pcm
  • audio/wav
  • audio/webm
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/ogg
  • audio/pcm
  • audio/wav
  • audio/webm
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/ogg
  • audio/pcm
  • audio/wav
  • audio/webm
Live API 네이티브 오디오를 사용한 Gemini 2.5 Flash (프리뷰)
  • 최대 대화 길이: 기본값은 10분이며 연장할 수 있습니다.
  • 필수 오디오 입력 형식: 원시 16비트 PCM 오디오(16kHz, little-endian)
  • 필수 오디오 출력 형식: 24kHz의 원시 16비트 PCM 오디오, little-endian
  • audio/x-aac
  • audio/flac
  • audio/mp3
  • audio/m4a
  • audio/mpeg
  • audio/mpga
  • audio/mp4
  • audio/ogg
  • audio/pcm
  • audio/wav
  • audio/webm
실시간 API를 사용한 Gemini 2.0 Flash (프리뷰)
  • 프롬프트당 최대 오디오 길이: 최대 8.4시간 또는 토큰 최대 100만 개
  • 프롬프트당 최대 오디오 파일 수: 1
  • 음성 이해: 오디오 요약, 스크립트 작성, 번역
  • 분당 최대 토큰 수 (TPM):
    • 미국/아시아: 170만
    • EU: 40만
  • audio/x-aac
  • audio/flac
  • audio/mp3
  • audio/m4a
  • audio/mpeg
  • audio/mpga
  • audio/mp4
  • audio/ogg
  • audio/pcm
  • audio/wav
  • audio/webm
이미지 생성을 지원하는 Gemini 2.0 Flash (프리뷰)
  • 프롬프트당 최대 오디오 길이: 최대 8.4시간 또는 토큰 최대 100만 개
  • 프롬프트당 최대 오디오 파일 수: 1
  • 음성 이해: 오디오 요약, 스크립트 작성, 번역
  • 분당 최대 토큰 수 (TPM):
    • 미국/아시아: 170만
    • EU: 40만
Gemini 2.5 Pro
  • 프롬프트당 최대 오디오 길이: 최대 8.4시간 또는 토큰 최대 100만 개
  • 프롬프트당 최대 오디오 파일 수: 1
  • 음성 이해: 오디오 요약, 스크립트 작성, 번역
  • audio/x-aac
  • audio/flac
  • audio/mp3
  • audio/m4a
  • audio/mpeg
  • audio/mpga
  • audio/mp4
  • audio/ogg
  • 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/ogg
  • audio/pcm
  • audio/wav
  • audio/webm
Gemini 2.0 Flash
  • 프롬프트당 최대 오디오 길이: 최대 8.4시간 또는 토큰 최대 100만 개
  • 프롬프트당 최대 오디오 파일 수: 1
  • 음성 이해: 오디오 요약, 스크립트 작성, 번역
  • 분당 최대 토큰 수 (TPM):
    • 미국/아시아: 350만
    • EU: 350만
  • audio/x-aac
  • audio/flac
  • audio/mp3
  • audio/m4a
  • audio/mpeg
  • audio/mpga
  • audio/mp4
  • audio/ogg
  • audio/pcm
  • audio/wav
  • audio/webm
Gemini 2.0 Flash-Lite
  • 프롬프트당 최대 오디오 길이: 최대 8.4시간 또는 토큰 최대 100만 개
  • 프롬프트당 최대 오디오 파일 수: 1
  • 음성 이해: 오디오 요약, 스크립트 작성, 번역
  • 분당 최대 토큰 수 (TPM):
    • 미국/아시아: 350만
    • EU: 350만

할당량 측정항목은 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. 콘솔의 Vertex AI 섹션에서 Google Cloud Vertex AI 스튜디오 페이지로 이동합니다.

    Vertex AI Studio로 이동

  2. 프롬프트 만들기를 클릭합니다.

  3. 선택사항: 모델 및 파라미터를 구성합니다.

    • 모델: 모델을 선택합니다.
  4. 선택사항: 고급 매개변수를 구성하려면 고급을 클릭하고 다음과 같이 구성합니다.

    클릭하여 고급 구성 펼치기

    • Top-K: 슬라이더 또는 텍스트 상자를 사용하여 최상위 K의 값을 입력합니다.

      Top-K는 모델이 출력용 토큰을 선택하는 방식을 변경합니다. Top-K가 1이면 선택된 토큰이 모델의 어휘에 포함된 모든 토큰 중에서 가장 확률이 높다는 의미입니다(그리디 디코딩이라고도 함). 반면에 Top-K가 3이면 강도를 사용하여 가장 확률이 높은 3개 토큰 중에서 다음 토큰이 선택된다는 의미입니다.

      각 토큰 선택 단계에서 확률이 가장 높은 Top-K 토큰이 샘플링됩니다. 그런 다음 Top-P를 기준으로 토큰을 추가로 필터링하고 온도 샘플링을 사용하여 최종 토큰을 선택합니다.

      임의성이 낮은 응답에 낮은 값을 지정하고 임의성이 높은 응답에 높은 값을 지정합니다.

    • Top-P: 슬라이더 또는 텍스트 상자를 사용하여 최상위 P의 값을 입력합니다. 토큰의 확률 합계가 최상위 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 Drive

    1. 계정을 선택하고 이 옵션을 처음 선택할 때 Vertex AI Studio의 계정 액세스를 동의합니다. 총 크기가 10MB인 파일 여러 개를 업로드할 수 있습니다. 단일 파일은 7MB를 초과할 수 없습니다.
    2. 추가하려는 파일을 클릭합니다.
    3. 선택을 클릭합니다.

      파일 썸네일이 프롬프트 창에 표시됩니다. 토큰 총개수도 표시됩니다. 프롬프트 데이터가 토큰 한도를 초과하면 토큰이 잘리고 데이터 처리에 포함되지 않습니다.

  6. 프롬프트 창에 텍스트 프롬프트를 입력합니다.

  7. 선택사항: 텍스트에 대한 토큰 ID토큰 ID를 보려면 프롬프트 창에서 토큰 수를 클릭합니다.

  8. 제출을 클릭합니다.

  9. 선택사항: 프롬프트를 내 프롬프트에 저장하려면 저장을 클릭합니다.

  10. 선택사항: 프롬프트에 대한 Python 코드나 curl 명령어를 가져오려면 코드로 빌드 > 코드 가져오기를 클릭합니다.

Python

설치

pip install --upgrade google-genai

자세한 내용은 SDK 참고 문서를 참조하세요.

Vertex AI에서 생성형 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.

Go

Go를 설치하거나 업데이트하는 방법을 알아보세요.

자세한 내용은 SDK 참고 문서를 참조하세요.

Vertex AI에서 생성형 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.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 참고 문서를 참조하세요.

Vertex AI에서 생성형 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

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 참고 문서를 참조하세요.

Vertex AI에서 생성형 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 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 또는 URL입니다. 허용되는 값은 다음과 같습니다.
    • Cloud Storage 버킷 URI: 객체는 공개적으로 읽을 수 있거나 요청을 보내는 동일한 Google Cloud 프로젝트에 있어야 합니다. gemini-2.0-flashgemini-2.0-flash-lite의 경우 크기 제한은 2GB입니다.
    • HTTP URL: 파일 URL은 공개적으로 읽을 수 있어야 합니다. 요청당 동영상 파일 하나, 오디오 파일 하나, 이미지 파일 최대 10개를 지정할 수 있습니다. 오디오 파일, 동영상 파일, 문서는 15MB를 초과할 수 없습니다.
    • YouTube 동영상 URL: YouTube 동영상은 Google Cloud 콘솔에 로그인하는 데 사용된 계정이 소유한 것이거나 공개된 동영상이어야 합니다. 요청당 하나의 YouTube 동영상 URL만 지원됩니다.

    fileURI를 지정할 때는 파일의 미디어 유형(mimeType)도 지정해야 합니다. VPC 서비스 제어가 사용 설정된 경우 fileURI의 미디어 파일 URL을 지정하는 것은 지원되지 않습니다.

    Cloud Storage에 오디오 파일이 없는 경우 공개적으로 사용 가능한 파일(gs://cloud-samples-data/generative-ai/audio/pixel.mp3)과 audio/mp3의 MIME 유형을 사용할 수 있습니다. 이 오디오를 들으려면 샘플 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). 이 샘플은 다른 모델도 지원할 수 있습니다.

오디오 스크립트 작성

다음은 오디오 파일을 사용하여 인터뷰 스크립트를 작성하는 방법을 보여줍니다. 오디오 전용 파일의 타임스탬프 이해를 사용 설정하려면 GenerationConfig에서 audioTimestamp 매개변수를 사용 설정하세요.

콘솔

Google Cloud 콘솔을 사용하여 멀티모달 프롬프트를 보내려면 다음을 수행합니다.

  1. 콘솔의 Vertex AI 섹션에서 Google Cloud Vertex AI 스튜디오 페이지로 이동합니다.

    Vertex AI Studio로 이동

  2. 프롬프트 만들기를 클릭합니다.

  3. 선택사항: 모델 및 파라미터를 구성합니다.

    • 모델: 모델을 선택합니다.
  4. 선택사항: 고급 매개변수를 구성하려면 고급을 클릭하고 다음과 같이 구성합니다.

    클릭하여 고급 구성 펼치기

    • Top-K: 슬라이더 또는 텍스트 상자를 사용하여 최상위 K의 값을 입력합니다.

      Top-K는 모델이 출력용 토큰을 선택하는 방식을 변경합니다. Top-K가 1이면 선택된 토큰이 모델의 어휘에 포함된 모든 토큰 중에서 가장 확률이 높다는 의미입니다(그리디 디코딩이라고도 함). 반면에 Top-K가 3이면 강도를 사용하여 가장 확률이 높은 3개 토큰 중에서 다음 토큰이 선택된다는 의미입니다.

      각 토큰 선택 단계에서 확률이 가장 높은 Top-K 토큰이 샘플링됩니다. 그런 다음 Top-P를 기준으로 토큰을 추가로 필터링하고 온도 샘플링을 사용하여 최종 토큰을 선택합니다.

      임의성이 낮은 응답에 낮은 값을 지정하고 임의성이 높은 응답에 높은 값을 지정합니다.

    • Top-P: 슬라이더 또는 텍스트 상자를 사용하여 최상위 P의 값을 입력합니다. 토큰의 확률 합계가 최상위 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 Drive

    1. 계정을 선택하고 이 옵션을 처음 선택할 때 Vertex AI Studio의 계정 액세스를 동의합니다. 총 크기가 10MB인 파일 여러 개를 업로드할 수 있습니다. 단일 파일은 7MB를 초과할 수 없습니다.
    2. 추가하려는 파일을 클릭합니다.
    3. 선택을 클릭합니다.

      파일 썸네일이 프롬프트 창에 표시됩니다. 토큰 총개수도 표시됩니다. 프롬프트 데이터가 토큰 한도를 초과하면 토큰이 잘리고 데이터 처리에 포함되지 않습니다.

  6. 프롬프트 창에 텍스트 프롬프트를 입력합니다.

  7. 선택사항: 텍스트에 대한 토큰 ID토큰 ID를 보려면 프롬프트 창에서 토큰 수를 클릭합니다.

  8. 제출을 클릭합니다.

  9. 선택사항: 프롬프트를 내 프롬프트에 저장하려면 저장을 클릭합니다.

  10. 선택사항: 프롬프트에 대한 Python 코드나 curl 명령어를 가져오려면 코드로 빌드 > 코드 가져오기를 클릭합니다.

Python

설치

pip install --upgrade google-genai

자세한 내용은 SDK 참고 문서를 참조하세요.

Vertex AI에서 생성형 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. ...
# ...

Go

Go를 설치하거나 업데이트하는 방법을 알아보세요.

자세한 내용은 SDK 참고 문서를 참조하세요.

Vertex AI에서 생성형 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.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 참고 문서를 참조하세요.

Vertex AI에서 생성형 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

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 참고 문서를 참조하세요.

Vertex AI에서 생성형 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 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 또는 URL입니다. 허용되는 값은 다음과 같습니다.
    • Cloud Storage 버킷 URI: 객체는 공개적으로 읽을 수 있거나 요청을 보내는 동일한 Google Cloud 프로젝트에 있어야 합니다. gemini-2.0-flashgemini-2.0-flash-lite의 경우 크기 제한은 2GB입니다.
    • HTTP URL: 파일 URL은 공개적으로 읽을 수 있어야 합니다. 요청당 동영상 파일 하나, 오디오 파일 하나, 이미지 파일 최대 10개를 지정할 수 있습니다. 오디오 파일, 동영상 파일, 문서는 15MB를 초과할 수 없습니다.
    • YouTube 동영상 URL: YouTube 동영상은 Google Cloud 콘솔에 로그인하는 데 사용된 계정이 소유한 것이거나 공개된 동영상이어야 합니다. 요청당 하나의 YouTube 동영상 URL만 지원됩니다.

    fileURI를 지정할 때는 파일의 미디어 유형(mimeType)도 지정해야 합니다. VPC 서비스 제어가 사용 설정된 경우 fileURI의 미디어 파일 URL을 지정하는 것은 지원되지 않습니다.

    Cloud Storage에 오디오 파일이 없는 경우 공개적으로 사용 가능한 파일(gs://cloud-samples-data/generative-ai/audio/pixel.mp3)과 audio/mp3의 MIME 유형을 사용할 수 있습니다. 이 오디오를 들으려면 샘플 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_config에서 audio_timestamp 파라미터를 구성해야 합니다.

다음 단계