Gemini 모델은 기본 비전을 사용하여 전체 문서 컨텍스트를 이해함으로써 PDF 형식의 문서를 처리할 수 있습니다. 이는 단순한 텍스트 추출을 넘어 Gemini가 다음 작업을 할 수 있도록 합니다.
- 최대 1,000페이지의 긴 문서에서도 텍스트, 이미지, 다이어그램, 차트, 표를 비롯한 콘텐츠를 분석하고 해석합니다.
- 정보를 구조화된 출력 형식으로 추출합니다.
- 문서의 시각적 요소와 텍스트 요소를 모두 기반으로 질문에 요약하고 답변합니다.
- 다운스트림 애플리케이션에서 사용할 수 있도록 레이아웃과 서식을 유지하면서 문서 콘텐츠를 트랜스크립션합니다 (예: HTML로).
동일한 방식으로 PDF가 아닌 문서를 전달할 수도 있지만 Gemini는 이를 일반 텍스트로 인식하므로 차트나 서식과 같은 컨텍스트가 삭제됩니다.
PDF 데이터 인라인 전달
요청에서 PDF 데이터를 인라인으로 전달할 수 있습니다. 이는 후속 요청에서 파일을 참조할 필요가 없는 소규모 문서 또는 임시 처리에 가장 적합합니다. 여러 차례의 멀티턴 상호작용에서 참조해야 하는 대용량 문서의 경우 Files API 를 사용하여 요청 지연 시간을 개선하고 대역폭 사용량을 줄이는 것이 좋습니다.
다음 예에서는 PDF 데이터를 인라인으로 전달하는 방법을 보여줍니다.
Python
from google import genai
import base64
client = genai.Client()
with open('path/to/document.pdf', 'rb') as f:
pdf_bytes = f.read()
interaction = client.interactions.create(
model="gemini-3.6-flash",
input=[
{
"type": "document",
"data": base64.b64encode(pdf_bytes).decode('utf-8'),
"mime_type": "application/pdf"
},
{"type": "text", "text": "Summarize this document"}
]
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
const ai = new GoogleGenAI({});
async function main() {
const pdfData = fs.readFileSync("path/to/document.pdf", {
encoding: "base64"
});
const interaction = await ai.interactions.create({
model: "gemini-3.6-flash",
input: [
{ type: "text", text: "Summarize this document" },
{
type: "document",
data: pdfData,
mime_type: "application/pdf"
}
]
});
console.log(interaction.output_text);
}
main();
REST
PDF_PATH="path/to/document.pdf"
if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
B64FLAGS="--input"
else
B64FLAGS="-w0"
fi
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.6-flash",
"input": [
{
"type": "document",
"data": "'$(base64 $B64FLAGS $PDF_PATH)'",
"mime_type": "application/pdf"
},
{"type": "text", "text": "Summarize this document"}
]
}'
처리를 위해 로컬 PDF 파일을 업로드할 수도 있습니다.
Python
from google import genai
client = genai.Client()
uploaded_file = client.files.upload(file="file.pdf")
interaction = client.interactions.create(
model="gemini-3.6-flash",
input=[
{"type": "document", "uri": uploaded_file.uri, "mime_type": uploaded_file.mime_type},
{"type": "text", "text": "Summarize this document"}
]
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const uploadedFile = await ai.files.upload({
file: "file.pdf",
config: { mime_type: "application/pdf" }
});
const interaction = await ai.interactions.create({
model: "gemini-3.6-flash",
input: [
{ type: "text", text: "Summarize this document" },
{
type: "document",
uri: uploadedFile.uri,
mime_type: uploadedFile.mime_type
}
]
});
console.log(interaction.output_text);
}
main();
REST
PDF_PATH="file.pdf"
NUM_BYTES=$(wc -c < "${PDF_PATH}")
DISPLAY_NAME="file.pdf"
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 "https://generativelanguage.googleapis.com/upload/v1beta/files?key=${GEMINI_API_KEY}" \
-D upload-header.tmp \
-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: application/pdf" \
-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 "@${PDF_PATH}" 2> /dev/null > file_info.json
file_uri=$(jq -r ".file.uri" file_info.json)
echo file_uri=$file_uri
# Now create an interaction using that file
curl "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"model": "gemini-3.6-flash",
"input": [
{"type": "document", "uri": "'$file_uri'", "mime_type": "application/pdf"},
{"type": "text", "text": "Summarize this document"}
]
}' 2> /dev/null > response.json
cat response.json
echo
jq -r ".steps[-1].content[0].text" response.json
Files API를 사용하여 PDF 업로드
대용량 파일의 경우 또는 여러 요청에서 문서를 재사용하려는 경우 Files API를 사용하는 것이 좋습니다. 이렇게 하면 파일 업로드를 모델 요청과 분리하여 요청 지연 시간이 개선되고 대역폭 사용량이 줄어듭니다.
URL의 대용량 PDF
File API를 사용하여 URL에서 대용량 PDF 파일을 간편하게 업로드하고 처리합니다.
Python
from google import genai
import io
import httpx
client = genai.Client()
long_context_pdf_path = "https://arxiv.org/pdf/2312.11805"
doc_io = io.BytesIO(httpx.get(long_context_pdf_path).content)
sample_doc = client.files.upload(
file=doc_io,
config=dict(
mime_type='application/pdf')
)
prompt = "Summarize this document"
interaction = client.interactions.create(
model="gemini-3.6-flash",
input=[
{"type": "document", "uri": sample_doc.uri, "mime_type": sample_doc.mime_type},
{"type": "text", "text": prompt}
]
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const pdfBuffer = await fetch("https://arxiv.org/pdf/2312.11805")
.then((response) => response.arrayBuffer());
const fileBlob = new Blob([pdfBuffer], { type: 'application/pdf' });
const file = await ai.files.upload({
file: fileBlob,
config: {
displayName: 'A17_FlightPlan.pdf',
},
});
let getFile = await ai.files.get({ name: file.name });
while (getFile.state === 'PROCESSING') {
getFile = await ai.files.get({ name: file.name });
console.log(`current file status: ${getFile.state}`);
console.log('File is still processing, retrying in 5 seconds');
await new Promise((resolve) => {
setTimeout(resolve, 5000);
});
}
if (file.state === 'FAILED') {
throw new Error('File processing failed.');
}
const interaction = await ai.interactions.create({
model: 'gemini-3.6-flash',
input: [
{ type: "document", uri: file.uri, mime_type: file.mime_type },
{ type: "text", text: "Summarize this document" }
],
});
console.log(interaction.output_text);
}
main();
REST
PDF_PATH="https://arxiv.org/pdf/2312.11805"
DISPLAY_NAME="Gemini_paper"
PROMPT="Summarize this document"
# Download the PDF from the provided URL
wget -O "${DISPLAY_NAME}.pdf" "${PDF_PATH}"
MIME_TYPE=$(file -b --mime-type "${DISPLAY_NAME}.pdf")
NUM_BYTES=$(wc -c < "${DISPLAY_NAME}.pdf")
echo "MIME_TYPE: ${MIME_TYPE}"
echo "NUM_BYTES: ${NUM_BYTES}"
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 "https://generativelanguage.googleapis.com/upload/v1beta/files?key=${GEMINI_API_KEY}" \
-D upload-header.tmp \
-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 "@${DISPLAY_NAME}.pdf" 2> /dev/null > file_info.json
file_uri=$(jq -r ".file.uri" file_info.json)
echo "file_uri: ${file_uri}"
# Create payload JSON file for safety
cat << EOF > payload.json
{
"model": "gemini-3.6-flash",
"input": [
{"type": "text", "text": "${PROMPT}"},
{"type": "document", "uri": "${file_uri}", "mime_type": "application/pdf"}
]
}
EOF
# Now create an interaction using that file
curl "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d @payload.json 2> /dev/null > response.json
cat response.json
echo
jq ".steps[-1].content[0].text" response.json
# Clean up
rm "${DISPLAY_NAME}.pdf"
rm payload.json
로컬에 저장된 대용량 PDF
Python
from google import genai
import pathlib
client = genai.Client()
file_path = pathlib.Path('large_file.pdf')
sample_file = client.files.upload(
file=file_path,
)
interaction = client.interactions.create(
model="gemini-3.6-flash",
input=[
{"type": "document", "uri": sample_file.uri, "mime_type": sample_file.mime_type},
{"type": "text", "text": "Summarize this document"}
]
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const file = await ai.files.upload({
file: 'large_file.pdf',
config: {
displayName: 'A17_FlightPlan.pdf',
},
});
let getFile = await ai.files.get({ name: file.name });
while (getFile.state === 'PROCESSING') {
getFile = await ai.files.get({ name: file.name });
console.log(`current file status: ${getFile.state}`);
console.log('File is still processing, retrying in 5 seconds');
await new Promise((resolve) => {
setTimeout(resolve, 5000);
});
}
if (file.state === 'FAILED') {
throw new Error('File processing failed.');
}
const interaction = await ai.interactions.create({
model: 'gemini-3.6-flash',
input: [
{ type: "document", uri: file.uri,