파일 입력 방법(File input methods)

파일 입력 방법(File input methods)

이 가이드는 Gemini API에 요청할 때 이미지, 오디오, 비디오, 문서 같은 미디어 파일을 포함하는 다양한 방법을 설명해요. 새 메서드는 Batch, Interactions, Live API를 포함한 모든 Gemini API 엔드포인트에서 지원돼요. 올바른 방법을 선택하는 것은 파일 크기, 데이터가 저장된 위치, 파일을 사용할 빈도에 따라 달라져요.

파일을 입력으로 포함하는 가장 간단한 방법은 로컬 파일을 읽어 프롬프트에 포함하는 거예요. 다음 예시는 로컬 PDF 파일을 읽는 방법을 보여줘요. 이 메서드의 PDF 한도는 50MB예요. 파일 입력 유형과 한도의 전체 목록은 입력 방법 비교 표를 참고하세요.

출처: 원문

본문

Python

from google import genai
import pathlib
import base64

client = genai.Client()

filepath = pathlib.Path('my_local_file.pdf')

prompt = "Summarize this document"
interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {"type": "text", "text": prompt},
        {"type": "document", "data": base64.b64encode(filepath.read_bytes()).decode('utf-8'), "mime_type": "application/pdf"}
    ]
)
print(interaction.output_text)

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from 'node:fs';

const client = new GoogleGenAI({});
const prompt = "Summarize this document";

async function main() {
    const filePath = 'my_local_file.pdf';

    const interaction = await client.interactions.create({
        model: "gemini-3.8-flash",
        input: [
            { type: "text", text: prompt },
            {
                type: "document",
                data: fs.readFileSync(filePath).toString("base64"),
                mime_type: "application/pdf"
            }
        ]
    });
    console.log(interaction.output_text);
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.DocumentContent;
import com.google.genai.gaos.models.interactions.DocumentContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] pdfBytes = Files.readAllBytes(Paths.get("my_local_file.pdf"));
String base64Pdf = Base64.getEncoder().encodeToString(pdfBytes);

String prompt = "Summarize this document";

Content textContent = TextContent.builder().text(prompt).build();
Content docContent =
    DocumentContent.builder()
        .data(base64Pdf)
        .mimeType(DocumentContentMimeType.APPLICATION_PDF)
        .build();

List<Content> contents = Arrays.asList(textContent, docContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    pdfBytes, err := os.ReadFile("my_local_file.pdf")
    if err != nil {
        log.Fatal(err)
    }
    base64Pdf := base64.StdEncoding.EncodeToString(pdfBytes)

    prompt := "Summarize this document"

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-3.8-flash"),
            Input: interactions.NewInteractionsInput([]interactions.Content{
                interactions.NewContent(interactions.TextContent{
                    Text: prompt,
                }),
                interactions.NewContent(interactions.DocumentContent{
                    Data:     genai.Ptr(base64Pdf),
                    MimeType: interactions.DocumentContentMimeTypeApplicationPdf.ToPointer(),
                }),
            }),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }
    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }
}

REST

# Encode the local file to base64
B64_CONTENT=$(base64 -w 0 my_local_file.pdf)

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: *** \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.8-flash",
    "input": [
      {"type": "text", "text": "Summarize this document"},
      {
        "type": "document",
        "data": "'${B64_CONTENT}'",
        "mime_type": "application/pdf"
      }
    ]
  }'

입력 방법 비교(Input method comparison)

다음 표는 각 입력 방법을 파일 한도와 최적 사용 사례와 함께 비교해요. 파일 크기 한도는 파일 유형과 파일 처리에 사용되는 모델 또는 토크나이저에 따라 달라질 수 있어요.

방법 최적 대상 최대 파일 크기 영속성
인라인 데이터(Inline data) 빠른 테스트, 작은 파일, 실시간 애플리케이션. 요청/페이로드당 100 MB (PDF의 경우 50 MB) 없음(모든 요청과 함께 전송됨)
File API 업로드 대용량 파일, 여러 번 사용하는 파일. 파일당 2 GB, 프로젝트당 최대 20GB 48시간
File API GCS URI 등록 Google Cloud Storage에 이미 있는 대용량 파일, 여러 번 사용하는 파일. 파일당 2 GB, 전체 저장 한도 없음 없음(요청별 fetch). 일회 등록 시 최대 30일 동안 접근 가능.
외부 URL 재업로드 없이 공개 데이터 또는 클라우드 버킷(AWS, Azure, GCS)의 데이터. 요청/페이로드당 100 MB 없음(요청별 fetch)

인라인 데이터(Inline data)

더 작은 파일(100MB 미만, PDF는 50MB 미만)의 경우 데이터를 요청 페이로드에 직접 전달할 수 있어요. 이는 빠른 테스트나 실시간·일시적 데이터를 처리하는 애플리케이션에 가장 간단한 방법이에요. 데이터를 base64 인코딩 문자열로 제공하거나 로컬 파일을 직접 읽어 제공할 수 있어요.

로컬 파일에서 읽는 예시는 이 페이지 시작 부분의 예시를 참고하세요.

URL에서 가져오기

파일을 URL에서 가져와 바이트로 변환하고 입력에 포함할 수도 있어요.

Python
from google import genai
import httpx

client = genai.Client()

doc_url = "https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf"
doc_data = httpx.get(doc_url).content

prompt = "Summarize this document"

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {"type": "document", "data": base64.b64encode(doc_data).decode('utf-8'), "mime_type": "application/pdf"},
        {"type": "text", "text": prompt}
    ]
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});
const docUrl = 'https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf';
const prompt = "Summarize this document";

async function main() {
    const pdfResp = await fetch(docUrl)
      .then((response) => response.arrayBuffer());

    const interaction = await client.interactions.create({
        model: "gemini-3.8-flash",
        input: [
            { type: "text", text: prompt },
            {
                type: "document",
                data: Buffer.from(pdfResp).toString("base64"),
                mime_type: "application/pdf"
            }
        ]
    });
    console.log(interaction.output_text);
}

main();
REST
DOC_URL="https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf"
PROMPT="Summarize this document"
DISPLAY_NAME="base64_pdf"

# Download the PDF
wget -O "${DISPLAY_NAME}.pdf" "${DOC_URL}"

# Check for FreeBSD base64 and set flags accordingly
if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
  B64FLAGS="--input"
else
  B64FLAGS="-w0"
fi

# Base64 encode the PDF
ENCODED_PDF=$(base64 $B64FLAGS "${DISPLAY_NAME}.pdf")

# Create JSON payload file
cat <<EOF > payload.json
{
"model": "gemini-3.8-flash",
"input": [
{"type": "document", "data": "${ENCODED_PDF}", "mime_type": "application/pdf"},
{"type": "text", "text": "${PROMPT}"}
]
}
EOF

# Generate content using interactions
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: *** \
    -H 'Content-Type: application/json' \
    -d @payload.json 2> /dev/null > response.json

cat response.json
echo

jq ".outputs[] | select(.type == \"text\") | .text" response.json

Gemini File API

File API는 더 큰 파일(최대 2GB) 또는 여러 요청에서 사용하려는 파일을 위해 설계됐어요.

표준 파일 업로드

로컬 파일을 Gemini API에 업로드해요. 이렇게 업로드된 파일은 임시로 저장(48시간)되며 모델이 효율적으로 검색할 수 있도록 처리돼요.

Python
from google import genai

client = genai.Client()

doc_file = client.files.upload(file="path/to/your/sample.pdf")
prompt = "Summarize this document"

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {"type": "text", "text": prompt},
        {"type": "document", "uri": doc_file.uri, "mime_type": doc_file.mime_type}
    ]
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});
const prompt = "Summarize this document";

async function main() {
  const filePath = "path/to/your/sample.pdf";

  const myfile = await client.files.upload({
    file: filePath,
    config: { mime_type: "application/pdf" },
  });

  const interaction = await client.interactions.create({
    model: "gemini-3.8-flash",
    input: [
        { type: "text", text: prompt },
        { type: "document", uri: myfile.uri, mime_type: myfile.mimeType }
    ]
  });
  console.log(interaction.output_text);
}

await main();
REST
FILE_PATH="path/to/sample.pdf"
MIME_TYPE=$(file -b --mime-type "${FILE_PATH}")
NUM_BYTES=$(wc -c < "${FILE_PATH}")
DISPLAY_NAME=DOCUMENT

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
curl "https://generativelanguage.googleapis.com/upload/v1beta/files" \
  -D "${tmp_header_file}" \
  -H "x-goog-api-key: *** \
  -H "X-Goog-Upload-Protocol: resumable" \
  -H "X-Goog-Upload-Command: start" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null

upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"

# Upload the actual bytes.
curl "${upload_url}" \
  -H "Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Offset: 0" \
  -H "X-Goog-Upload-Command: upload, finalize" \
  --data-binary "@${FILE_PATH}" 2> /dev/null > file_info.json

file_uri=$(jq ".file.uri" file_info.json)

# Now use in an interaction
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: *** \
    -H 'Content-Type: application/json' \
    -d '{
      "model": "gemini-3.8-flash",
      "input": [
        {"type": "text", "text": "Summarize this document"},
        {"type": "document", "uri": '$file_uri', "mime_type": "'${MIME_TYPE}'"}
      ]
    }'

Google Cloud Storage 파일 등록

데이터가 이미 Google Cloud Storage에 있다면 다운로드·재업로드할 필요 없이 File API에 직접 등록할 수 있어요.

  1. 각 버킷에 서비스 에이전트(Service Agent) 접근 부여

Google Cloud 프로젝트에서 Gemini API를 활성화해요. 서비스 에이전트를 생성해요: gcloud beta services identity create --service=generativelanguage.googleapis.com --project=<your_project>. 사용할 스토리지 버킷을 읽도록 Gemini API Service Agent 권한을 부여해야 해요. 사용자는 특정 스토리지 버킷에서 이 서비스 에이전트에 Storage Object Viewer IAM 역할을 할당해야 해요.

이 접근은 기본적으로 만료되지 않지만 언제든지 변경할 수 있어요. Google Cloud Storage IAM SDK 명령으로 권한을 부여할 수도 있어요.

  1. 서비스 인증 사전 요구 사항 — API 활성화, 적절한 권한의 서비스 계정 또는 에이전트 생성.

먼저 스토리지 객체 뷰어 권한이 있는 서비스로 인증해야 해요. 파일 관리 코드가 실행되는 환경에 따라 달라져요.

Google Cloud 외부에서 — 데스크톱 등 Google Cloud 외부에서 코드를 실행한다면 Google Cloud Console에서 계정 자격 증명을 다음 단계로 다운로드해요: 서비스 계정 콘솔로 이동 → 관련 서비스 계정 선택 → Keys 탭에서 Add key, Create new key 선택 → JSON 키 유형을 선택하고 파일이 다운로드된 위치를 기록해요. 자세한 내용은 서비스 계정 키 관리 공식 문서를 참고하세요. 그런 다음 다음 명령으로 인증해요. 현재 디렉터리에 service-account.json으로 서비스 계정 파일이 있다고 가정해요.

from google.oauth2.service_account import Credentials

GCS_READ_SCOPES = [
  'https://www.googleapis.com/auth/devstorage.read_only',
  'https://www.googleapis.com/auth/cloud-platform'
]

SERVICE_ACCOUNT_FILE = 'service-account.json'

credentials = Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE,
    scopes=GCS_READ_SCOPES
)
const { GoogleAuth } = require('google-auth-library');

const GCS_READ_SCOPES = [
  'https://www.googleapis.com/auth/devstorage.read_only',
  'https://www.googleapis.com/auth/cloud-platform'
];

const SERVICE_ACCOUNT_FILE = 'service-account.json';

const auth = new GoogleAuth({
  keyFile: SERVICE_ACCOUNT_FILE,
  scopes: GCS_READ_SCOPES
});
gcloud auth application-default login \
  --client-id-file=service-account.json \
  --scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/devstorage.read_only'

Google Cloud에서 — Cloud Run functions이나 Compute Engine 인스턴스처럼 Google Cloud에서 직접 실행된다면 암시적 자격 증명이 있지만 적절한 스코프를 부여하기 위해 재인증이 필요해요.

import google.auth

GCS_READ_SCOPES = [
  'https://www.googleapis.com/auth/devstorage.read_only',
  'https://www.googleapis.com/auth/cloud-platform'
]

credentials, project = google.auth.default(scopes=GCS_READ_SCOPES)
const { GoogleAuth } = require('google-auth-library');

const auth = new GoogleAuth({
  scopes: [
    'https://www.googleapis.com/auth/devstorage.read_only',
    'https://www.googleapis.com/auth/cloud-platform'
  ]
});
gcloud auth application-default login \
--scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/devstorage.read_only"
  1. 파일 등록(Files API)

Files API를 사용해 파일을 등록하고 Gemini API에서 직접 사용할 수 있는 Files API 경로를 생성해요.

from google import genai

client = genai.Client(credentials=credentials)

registered_gcs_files = client.files.register_files(
    uris=["gs://my_bucket/some_object.pdf", "gs://bucket2/object2.txt"]
)
prompt = "Summarize this file."

for f in registered_gcs_files.files:
  print(f.name)
  interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
      {"type": "text", "text": prompt},
      {"type": "document", "uri": f.uri, "mime_type": f.mime_type}
    ],
  )
  print(interaction.output_text)
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ auth: auth });

async function main() {
    const registeredGcsFiles = await ai.files.registerFiles({
        uris: ["gs://my_bucket/some_object.pdf", "gs://bucket2/object2.txt"]
    });

    const prompt = "Summarize this file.";

    for (const file of registeredGcsFiles.files) {
        console.log(file.name);
        const interaction = await ai.interactions.create({
            model: "gemini-3.8-flash",
            input: [
                { type: "text", text: prompt },
                { type: "document", uri: file.uri, mime_type: file.mimeType }
            ]
        });

        console.log(interaction.output_text);
    }
}

main();
access_token=$(gcloud auth application-default print-access-token)
project_id=$(gcloud config get-value project)
curl -X POST https://generativelanguage.googleapis.com/v1beta/files:register \
    -H 'Content-Type: application/json' \
    -H "Authorization: Bearer ***" \
    -H "x-goog-user-project: ${project_id}" \
    -d '{"uris": ["gs://bucket/object1", "gs://bucket/object2"]}'

외부 HTTP / 서명된 URL(External HTTP / Signed URLs)

공개적으로 접근 가능한 HTTPS URL 또는 사전 서명된(pre-signed) URL을 요청에 직접 전달할 수 있어요. Gemini API는 처리 중 콘텐츠를 안전하게 fetch해요. 재업로드하고 싶지 않은 최대 100MB 파일에 이상적이에요.

참고: Gemini 2.0 제품군 모델은 지원되지 않아요.

Python

from google import genai

uri = "https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf"
prompt = "Summarize this file"

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {"type": "document", "uri": uri, "mime_type": "application/pdf"},
        {"type": "text", "text": prompt}
    ]
)
print(interaction.output_text)

Javascript

import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

const uri = "https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf";

async function main() {
  const interaction = await client.interactions.create({
    model: 'gemini-3.8-flash',
    input: [
      { type: "document", uri: uri, mime_type: "application/pdf" },
      { type: "text", text: "summarize this file" }
    ]
  });

  console.log(interaction.output_text);
}

main();

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
      -H 'x-goog-api-key: *** \
      -H 'Content-Type: application/json' \
      -d '{
          "model": "gemini-3.8-flash",
          "input": [
            {"type": "text", "text": "Summarize this pdf"},
            {
              "type": "document",
              "uri": "https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf",
              "mime_type": "application/pdf"
            }
          ]
        }'

접근성(Accessibility)

제공하는 URL이 로그인이 필요하거나 페이월 뒤에 있는 페이지로 이어지지 않는지 확인하세요. 비공개 데이터베이스의 경우 올바른 접근 권한과 만료가 있는 서명된 URL을 만드세요.

안전 검사(Safety checks)

시스템은 안전 및 정책 기준을 충족하는지 확인하기 위해 URL에 콘텐츠 검토를 수행해요. URL이 이 검사에 실패하면 url_retrieval_status로 URL_RETRIEVAL_STATUS_UNSAFE를 받게 돼요.

지원 콘텐츠 유형

이 지원 파일 유형 및 제한 목록은 초기 안내용이며 완전하지 않아요. 유효한 지원 유형 세트는 변경될 수 있고 사용 중인 특정 모델 및 토크나이저 버전에 따라 달라질 수 있어요. 지원되지 않는 유형은 오류를 반환해요. 또한 이러한 파일 유형의 콘텐츠 검색은 공개적으로 접근 가능한 URL만 지원해요.

텍스트 파일 유형
  • text/html
  • text/css
  • text/plain
  • text/xml
  • text/csv
  • text/rtf
  • text/javascript
애플리케이션 파일 유형
  • application/json
  • application/pdf
이미지 파일 유형
  • image/bmp
  • image/jpeg
  • image/png
  • image/webp
비디오 파일 유형
  • video/mp4
  • video/mpeg
  • video/quicktime
  • video/avi
  • video/x-flv
  • video/mpg
  • video/webm
  • video/wmv
  • video/3gpp

모범 사례(Best practices)

  • 올바른 방법 선택: 작고 일시적인 파일에는 인라인 데이터를 사용해요. 더 크거나 자주 사용하는 파일에는 File API를 사용해요. 이미 온라인에 호스팅된 데이터에는 외부 URL을 사용해요.
  • MIME 유형 지정: 파일 데이터에 항상 올바른 MIME 유형을 제공해 올바른 처리를 보장하세요.
  • 오류 처리: 코드에 오류 처리를 구현해 네트워크 실패, 파일 접근 문제, API 오류 같은 잠재적 문제를 관리하세요.

제한 사항(Limitations)

  • 파일 크기 한도는 방법(비교 표 참고)과 파일 유형에 따라 달라져요.
  • 인라인 데이터는 요청 페이로드 크기를 늘려요.
  • File API 업로드는 임시이며 48시간 후 만료돼요.
  • 외부 URL fetch는 페이로드당 100MB로 제한되며 특정 콘텐츠 유형을 지원해요.

더 알아보기 (Learn more)