문서 이해

문서(PDF 및 TXT 파일)를 Gemini 요청에 추가하여 포함된 문서의 콘텐츠 이해와 관련된 태스크를 수행할 수 있습니다. 이 페이지에서는 Google Cloud 콘솔과 Vertex AI API를 사용하여 Vertex AI의 Gemini에 대한 요청에 PDF를 추가하는 방법을 보여줍니다.

지원되는 모델

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

모델 미디어 세부정보 MIME 유형
Gemini 2.5 Flash Image Preview
  • 프롬프트당 최대 파일 수: 3개
  • 파일당 최대 페이지 수: 3개
  • 파일당 최대 파일 크기: 50MB
  • application/pdf
  • text/plain
Gemini 2.5 Flash-Lite
  • 프롬프트당 최대 파일 수: 3,000개
  • 파일당 최대 페이지 수: 1,000개
  • 파일당 최대 파일 크기: 50MB
  • application/pdf
  • text/plain
이미지 생성을 지원하는 Gemini 2.0 Flash
  • 프롬프트당 최대 파일 수: 3,000개
  • 파일당 최대 페이지 수: 1,000개
  • 파일당 최대 파일 크기: 50MB
  • application/pdf
  • text/plain
Gemini 2.5 Pro
  • 프롬프트당 최대 파일 수: 3,000개
  • 파일당 최대 페이지 수: 1,000개
  • 파일당 최대 파일 크기: 50MB
  • application/pdf
  • text/plain
Gemini 2.5 Flash
  • 프롬프트당 최대 파일 수: 3,000개
  • 파일당 최대 페이지 수: 1,000개
  • API 또는 Cloud Storage 가져오기의 파일당 최대 파일 크기: 50MB
  • 콘솔을 통한 직접 업로드의 파일당 최대 파일 크기: 7MB
  • application/pdf
  • text/plain
Gemini 2.0 Flash
  • 프롬프트당 최대 파일 수: 3,000개
  • 파일당 최대 페이지 수: 1,000개
  • 파일당 최대 파일 크기: 50MB
  • 프로젝트별 분당 최대 토큰 수(TPM)1:
    • 미국/아시아: 340만개
    • EU: 340만개
  • application/pdf
  • text/plain
Gemini 2.0 Flash-Lite
  • 프롬프트당 최대 파일 수: 3,000개
  • 파일당 최대 페이지 수: 1,000개
  • 파일당 최대 파일 크기: 50MB
  • 분당 최대 토큰 수(TPM):
    • 미국/아시아: 340만개
    • EU: 340만개
  • application/pdf
  • text/plain

1프로젝트의 모든 요청에서 문서 입력의 최대 TPM입니다. 다른 모달리티에도 최대 TPM을 사용하세요.

할당량 측정항목은 generate_content_document_input_per_base_model_id_and_resolution입니다.

Gemini 모델에서 지원되는 언어 목록은 모델 정보 Google 모델을 참조하세요. 멀티모달 프롬프트를 설계하는 방법에 대한 자세한 내용은 멀티모달 프롬프트 설계를 참조하세요. 모바일 및 웹 앱에서 Gemini를 직접 사용할 수 있는 방법을 찾는 경우 Swift, Android, 웹, Flutter, Unity 앱의 Firebase AI Logic 클라이언트 SDK를 참조하세요.

요청에 문서 추가

다음 코드 샘플은 프롬프트 요청에 PDF를 포함하는 방법을 보여줍니다. 이 PDF 샘플은 모든 Gemini 멀티모달 모델에서 작동합니다.

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"))
model_id = "gemini-2.5-flash"

prompt = """
You are a highly skilled document summarization specialist.
Your task is to provide a concise executive summary of no more than 300 words.
Please summarize the given document for a general audience.
"""

pdf_file = Part.from_uri(
    file_uri="gs://cloud-samples-data/generative-ai/pdf/1706.03762v7.pdf",
    mime_type="application/pdf",
)

response = client.models.generate_content(
    model=model_id,
    contents=[pdf_file, prompt],
)

print(response.text)
# Example response:
# Here is a summary of the document in 300 words.
#
# The paper introduces the Transformer, a novel neural network architecture for
# sequence transduction tasks like machine translation. Unlike existing models that rely on recurrent or
# convolutional layers, the Transformer is based entirely on attention mechanisms.
# ...

Go

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"

	"google.golang.org/genai"
)

// generateTextWithPDF shows how to generate text using a PDF file input.
func generateTextWithPDF(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: `You are a highly skilled document summarization specialist.
	Your task is to provide a concise executive summary of no more than 300 words.
	Please summarize the given document for a general audience.`},
			{FileData: &genai.FileData{
				FileURI:  "gs://cloud-samples-data/generative-ai/pdf/1706.03762v7.pdf",
				MIMEType: "application/pdf",
			}},
		},
			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:
	// "Attention Is All You Need" introduces the Transformer,
	// a groundbreaking neural network architecture designed for...
	// ...

	return nil
}

Java

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

자세한 내용은 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 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 TextGenerationWithPdf {

  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 PDF file input
  public static String generateContent(String modelId) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      String prompt =
          "You are a highly skilled document summarization specialist.\n"
              + " Your task is to provide a concise executive summary of no more than 300 words.\n"
              + " Please summarize the given document for a general audience";

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              Content.fromParts(
                  Part.fromUri(
                      "gs://cloud-samples-data/generative-ai/pdf/1706.03762v7.pdf",
                      "application/pdf"),
                  Part.fromText(prompt)),
              null);

      System.out.print(response.text());
      // Example response:
      // The document introduces the Transformer, a novel neural network architecture designed for
      // sequence transduction tasks, such as machine translation. Unlike previous dominant models
      // that rely on complex recurrent or convolutional neural networks, the Transformer proposes a
      // simpler, more parallelizable design based *solely* on attention mechanisms, entirely
      // dispensing with recurrence and convolutions...

      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에 PDF 파일이 없으면 application/pdf MIME 유형이 있는 gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf와 같은 공개적으로 사용 가능한 파일을 사용할 수 있습니다. 이 PDF를 보려면 샘플 PDF 파일을 엽니다.

  • 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: 프롬프트에 포함할 텍스트 안내입니다. 예를 들면 You are a very professional document summarization specialist. Please summarize the given document.입니다.

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

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). 이 샘플은 다른 모델도 지원할 수 있습니다.

콘솔

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 명령어를 가져오려면 코드로 빌드 > 코드 가져오기를 클릭합니다.

선택적 모델 파라미터 설정

각 모델에는 설정할 수 있는 선택적 파라미터 집합이 있습니다. 자세한 내용은 콘텐츠 생성 파라미터를 참조하세요.

문서 토큰화

PDF 토큰화

PDF는 이미지로 취급되므로 PDF의 각 페이지가 이미지와 동일한 방법으로 토큰화됩니다.

또한 PDF 비용은 Gemini 이미지 가격 책정을 따릅니다. 예를 들어 Gemini API 호출에 2페이지 PDF를 포함하면 두 개의 이미지 처리에 대한 입력 수수료가 발생합니다.

PDF 권장사항

PDF를 사용할 때 최상의 결과를 얻으려면 다음 권장사항과 정보를 사용하세요.

  • 프롬프트에 단일 PDF가 포함된 경우 요청에서 텍스트 프롬프트 앞에 PDF를 배치합니다.
  • 문서가 긴 경우 여러 PDF로 분할하여 처리하는 것이 좋습니다.
  • 스캔한 이미지에 텍스트를 사용하는 대신 텍스트로 렌더링된 텍스트로 생성된 PDF를 사용합니다. 이 형식은 머신이 텍스트를 읽을 수 있으므로 스캔한 이미지 PDF에 비해 모델이 더 쉽게 수정, 검색, 조작할 수 있습니다. 따라서 계약서와 같이 텍스트가 많은 문서를 작업할 때 최적의 결과를 얻을 수 있습니다.

제한사항

Gemini 멀티모달 모델은 많은 멀티모달 사용 사례에서 강력하지만 모델의 제한사항을 이해하는 것이 중요합니다.

  • 공간 추론: 이 모델은 PDF에 있는 텍스트 또는 객체 수를 정확하게 맞히지 못합니다. 대략적인 객체 수만 반환할 수 있습니다.
  • 정확성: 이 모델은 PDF 문서에서 필기 텍스를 해석할 때 할루시네이션이 발생할 수 있습니다.

다음 단계