파일 입력 방법

파일 입력 방법

이 가이드는 Gemini API에 요청할 때 이미지, 오디오, 비디오, 문서 같은 미디어 파일을 포함할 수 있는 여러 방법을 설명해요. 새 방법은 Batch, Interactions, Live API를 포함한 모든 Gemini API 엔드포인트에서 지원돼요.

올바른 방법을 선택하는 것은 파일 크기, 데이터가 현재 저장된 위치, 파일을 사용할 계획의 빈도에 따라 달라져요.

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

from google import genai
from google.genai import types
import pathlib

client = genai.Client()

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

prompt = "Summarize this document"
response = client.models.generate_content(
  model="gemini-3.8-flash",
  contents=[
      types.Part.from_bytes(
        data=filepath.read_bytes(),
        mime_type='application/pdf',
      ),
      prompt
  ]
)
print(response.text)
import { GoogleGenAI } from "@google/genai";
import * as fs from 'node:fs';

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

async function main() {
    const filePath = path.join('content', 'my_local_file.pdf'); // Adjust path as needed

    const contents = [
        { text: prompt },
        {
            inlineData: {
                mimeType: 'application/pdf',
                data: fs.readFileSync(filePath).toString("base64")
            }
        }
    ];

    const response = await ai.models.generateContent({
        model: "gemini-3.8-flash",
        contents: contents
    });
    console.log(response.text);
}

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

curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \
  -H "x-goog-api-key: *** \
  -H 'Content-Type: application/json' \
  -d '{
    "contents": [
      {
        "parts": [
          {"text": "Summarize this document"}
        ]
      },
      {
        "parts": [
          {
            "inlineData": {
              "mimeType": "application/pdf",
              "data": "'"${B64_CONTENT}"'"
            }
          }
        ]
      }
    ]
  }'

출처: 원문

본문

입력 방법 비교

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

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

인라인 데이터

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

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

URL에서 가져오기

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

from google import genai
from google.genai import types
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"

response = client.models.generate_content(
  model="gemini-3.8-flash",
  contents=[
      types.Part.from_bytes(
        data=doc_data,
        mime_type='application/pdf',
      ),
      prompt
  ]
)
print(response.text)
import { GoogleGenAI } from "@google/genai";

const ai = 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 contents = [
        { text: prompt },
        {
            inlineData: {
                mimeType: 'application/pdf',
                data: Buffer.from(pdfResp).toString("base64")
            }
        }
    ];

    const response = await ai.models.generateContent({
        model: "gemini-3.8-flash",
        contents: contents
    });
    console.log(response.text);
}

main();
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")

# Generate content using the base64 encoded PDF
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \
    -H "x-goog-api-key: *** \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"inline_data": {"mime_type": "application/pdf", "data": "'"$ENCODED_PDF"'"}},
          {"text": "'$PROMPT'"}
        ]
      }]
    }' 2> /dev/null > response.json

cat response.json
echo

jq ".candidates[].content.parts[].text" response.json

Gemini File API

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

표준 파일 업로드

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

from google import genai
client = genai.Client()

# Upload the file
audio_file = client.files.upload(file="path/to/your/sample.mp3")
prompt = "Describe this audio clip"

# Use the uploaded file in a prompt
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=[prompt, audio_file]
)
print(response.text)
import {
  GoogleGenAI,
  createUserContent,
  createPartFromUri,
} from "@google/genai";

const ai = new GoogleGenAI({});
const prompt = "Describe this audio clip";

async function main() {
  const filePath = "path/to/your/sample.mp3"; // Adjust path as needed

  const myfile = await ai.files.upload({
    file: filePath,
    config: { mimeType: "audio/mpeg" },
  });

  const response = await ai.models.generateContent({
    model: "gemini-3.8-flash",
    contents: createUserContent([
      prompt,
      createPartFromUri(myfile.uri, myfile.mimeType),
    ]),
  });
  console.log(response.text);

}
await main();
AUDIO_PATH="path/to/sample.mp3"
MIME_TYPE=$(file -b --mime-type "${AUDIO_PATH}")
NUM_BYTES=$(wc -c < "${AUDIO_PATH}")
DISPLAY_NAME=AUDIO

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files" \
  -H "x-goog-api-key: *** \
  -D "${tmp_header_file}" \
  -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 "@${AUDIO_PATH}" 2> /dev/null > file_info.json

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

# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \
    -H "x-goog-api-key: *** \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Describe this audio clip"},
          {"file_data":{"mime_type": "${MIME_TYPE}", "file_uri": '$file_uri'}}]
        }]
      }' 2> /dev/null > response.json

cat response.json
echo

jq ".candidates[].content.parts[].text" response.json

Google Cloud Storage 파일 등록

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

  1. 각 버킷에 Service Agent 접근 권한 부여. Google Cloud 프로젝트에서 Gemini API를 활성화하세요. Service Agent를 만드세요: 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 명령으로 권한을 부여할 수도 있어요.

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

    Google Cloud 외부에서. 데스크톱 같은 Google Cloud 외부에서 코드가 실행되는 경우 Google Cloud Console에서 계정 자격증명을 다운로드하세요: Service Account 콘솔로 이동 → 관련 서비스 계정 선택 → Keys 탭에서 Add key, Create new key 선택 → JSON 키 유형 선택 후 다운로드 위치를 확인하세요. 자세한 내용은 공식 Google Cloud의 서비스 계정 키 관리 문서를 참조하세요. 그런 다음 다음 명령으로 인증하세요(서비스 계정 파일이 현재 디렉토리에 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 함수나 Compute Engine 인스턴스처럼 Google Cloud에서 직접 실행하는 경우 환경에서 제공되는 기본 자격증명을 사용할 수 있어요.

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

    from google import genai
    from google.genai.types import Part
    
    # Note that you must provide an API key in the GEMINI_API_KEY
    # environment variable, but it is unused for the registration endpoint.
    client = genai.Client()
    
    registered_gcs_files = client.files.register_files(
        uris=["gs://my_bucket/some_object.pdf", "gs://bucket2/object2.txt"],
        # Use the credentials obtained in the previous step.
        auth=credentials
    )
    
    prompt = "Summarize this file."
    
    # call generateContent for each file
    for f in registered_gcs_files.files:
      print(f.name)
      response = client.models.generate_content(
        model="gemini-3.8-flash",
        contents=[Part.from_uri(
          file_uri=f.uri,
          mime_type=f.mime_type,
        ),
        prompt],
      )
      print(response.text)
    
    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 $access_token" \
        -H "x-goog-user-project: ${project_id}" \
        -d '{"uris": ["gs://bucket/object1", "gs://bucket/object2"]}'
    

외부 HTTP / 서명된 URL

공개적으로 접근 가능한 HTTPS URL이나 사전 서명된 URL(S3 Presigned URL 및 Azure SAS 호환)을 생성 요청에 직접 전달할 수 있어요. Gemini API는 처리 중에 콘텐츠를 안전하게 가져와요. 재업로드하고 싶지 않은 최대 100MB 파일에 이상적이에요.

file_uri 필드에 URL을 사용해 공개 또는 서명된 URL을 입력으로 사용할 수 있어요.

from google import genai
from google.genai.types import Part

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

client = genai.Client()

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=[
        Part.from_uri(
            file_uri=uri,
            mime_type="application/pdf",
        ),
        prompt
    ],
)
print(response.text)
import { GoogleGenAI, createPartFromUri } from '@google/genai';

const client = new GoogleGenAI({});

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

async function main() {
  const response = await client.models.generateContent({
    model: 'gemini-3.8-flash',
    contents: [
      // equivalent to Part.from_uri(file_uri=uri, mime_type="...")
      createPartFromUri(uri, "application/pdf"),
      "summarize this file",
    ],
  });

  console.log(response.text);
}

main();
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent \
      -H 'x-goog-api-key: *** \
      -H 'Content-Type: application/json' \
      -d '{
          "contents":[
            {
              "parts":[
                {"text": "Summarize this pdf"},
                {
                  "file_data": {
                    "mime_type":"application/pdf",
                    "file_uri": "https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf"
                  }
                }
              ]
            }
          ]
        }'

접근성

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

안전 검사

시스템은 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

모범 사례

  • 올바른 방법 선택: 작고 일시적인 파일에는 인라인 데이터를, 더 크거나 자주 사용하는 파일에는 File API를, 이미 온라인에 호스팅된 데이터에는 외부 URL을 사용하세요.
  • MIME 유형 지정: 파일 데이터에 항상 올바른 MIME 유형을 제공해 적절히 처리되도록 하세요.
  • 오류 처리: 네트워크 실패, 파일 접근 문제, API 오류 같은 잠재적 문제를 관리하는 오류 처리를 코드에 구현하세요.
  • GCS 권한 관리: GCS 등록을 사용할 때 특정 버킷에 Gemini API Service Agent에게 필요한 Storage Object Viewer 역할만 부여하세요.
  • 서명된 URL 보안: 서명된 URL이 적절한 만료 시간과 제한된 권한을 갖도록 하세요.

제한 사항

  • 파일 크기 한도는 방법(비교표 참조)과 파일 유형에 따라 달라져요.
  • 인라인 데이터는 요청 페이로드 크기를 늘려요.
  • File API 업로드는 일시적이며 48시간 후 만료돼요.
  • 외부 URL 가져오기는 페이로드당 100MB로 제한되고 특정 콘텐츠 유형을 지원해요.
  • Google Cloud Storage 등록은 적절한 IAM 설정과 OAuth 토큰 관리가 필요해요.

다음 단계

  • Google AI Studio로 직접 멀티모달 프롬프트를 작성해 보세요.
  • 프롬프트에 파일을 포함하는 방법은 Vision, Audio, 문서 처리 가이드를 참조하세요.
  • 샘플링 매개변수 조정 같은 프롬프트 설계에 대한 더 많은 안내는 프롬프트 전략 가이드를 참조하세요.

더 알아보기 (Learn more)