Gemini 모델은 기본 시각 기능을 사용하여 전체 문서 컨텍스트를 이해하고 PDF 형식으로 문서를 처리할 수 있습니다. 이를 통해 단순한 텍스트 추출을 넘어 Gemini가 다음과 같은 작업을 할 수 있습니다.
- 최대 1,000페이지에 달하는 긴 문서에서도 텍스트, 이미지, 다이어그램, 차트, 표 등의 콘텐츠를 분석하고 해석합니다.
- 정보를 구조화된 출력 형식으로 추출합니다.
- 문서의 시각적 요소와 텍스트 요소를 모두 기반으로 요약하고 질문에 답변합니다.
- 다운스트림 애플리케이션에서 사용할 수 있도록 레이아웃과 서식을 유지하면서 문서 콘텐츠를 트랜스크립션합니다 (예: HTML).
인라인 PDF 데이터 전달
generateContent
에 대한 요청에서 인라인 PDF 데이터를 전달할 수 있습니다.
20MB 미만의 PDF 페이로드의 경우 base64로 인코딩된 문서를 업로드하거나 로컬에 저장된 파일을 직접 업로드할 수 있습니다.
다음 예에서는 URL에서 PDF를 가져와 처리할 바이트로 변환하는 방법을 보여줍니다.
Python
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"
# Retrieve and encode the PDF byte
doc_data = httpx.get(doc_url).content
prompt = "Summarize this document"
response = client.models.generate_content(
model="gemini-2.5-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({ apiKey: "GEMINI_API_KEY" });
async function main() {
const pdfResp = await fetch('https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf')
.then((response) => response.arrayBuffer());
const contents = [
{ text: "Summarize this document" },
{
inlineData: {
mimeType: 'application/pdf',
data: Buffer.from(pdfResp).toString("base64")
}
}
];
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: contents
});
console.log(response.text);
}
main();
Go
package main
import (
"context"
"fmt"
"io"
"net/http"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, _ := genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
pdfResp, _ := http.Get("https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf")
var pdfBytes []byte
if pdfResp != nil && pdfResp.Body != nil {
pdfBytes, _ = io.ReadAll(pdfResp.Body)
pdfResp.Body.Close()
}
parts := []*genai.Part{
&genai.Part{
InlineData: &genai.Blob{
MIMEType: "application/pdf",
Data: pdfBytes,
},
},
genai.NewPartFromText("Summarize this document"),
}
contents := []*genai.Content{
genai.NewContentFromParts(parts, genai.RoleUser),
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-2.5-flash",
contents,
nil,
)
fmt.Println(result.Text())
}
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")
# Generate content using the base64 encoded PDF
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_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
# Clean up the downloaded PDF
rm "${DISPLAY_NAME}.pdf"
처리를 위해 로컬 파일에서 PDF를 읽을 수도 있습니다.
Python
from google import genai
from google.genai import types
import pathlib
client = genai.Client()
# Retrieve and encode the PDF byte
filepath = pathlib.Path('file.pdf')
prompt = "Summarize this document"
response = client.models.generate_content(
model="gemini-2.5-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 'fs';
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
async function main() {
const contents = [
{ text: "Summarize this document" },
{
inlineData: {
mimeType: 'application/pdf',
data: Buffer.from(fs.readFileSync("content/343019_3_art_0_py4t4l_convrt.pdf")).toString("base64")
}
}
];
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: contents
});
console.log(response.text);
}
main();
Go
package main
import (
"context"
"fmt"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, _ := genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
pdfBytes, _ := os.ReadFile("path/to/your/file.pdf")
parts := []*genai.Part{
&genai.Part{
InlineData: &genai.Blob{
MIMEType: "application/pdf",
Data: pdfBytes,
},
},
genai.NewPartFromText("Summarize this document"),
}
contents := []*genai.Content{
genai.NewContentFromParts(parts, genai.RoleUser),
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-2.5-flash",
contents,
nil,
)
fmt.Println(result.Text())
}
File API를 사용하여 PDF 업로드
파일 API를 사용하여 더 큰 문서를 업로드할 수 있습니다. 파일, 텍스트 프롬프트, 시스템 안내 등을 포함한 총 요청 크기가 20MB보다 큰 경우 항상 File API를 사용하세요.
파일 API를 사용하여 파일을 업로드하려면 media.upload
를 호출합니다. 다음 코드는 문서 파일을 업로드한 다음 models.generateContent
호출에서 파일을 사용합니다.
URL의 대형 PDF
파일 API를 사용하여 URL에서 대용량 PDF 파일의 업로드 및 처리를 간소화합니다.
Python
from google import genai
from google.genai import types
import io
import httpx
client = genai.Client()
long_context_pdf_path = "https://www.nasa.gov/wp-content/uploads/static/history/alsj/a17/A17_FlightPlan.pdf"
# Retrieve and upload the PDF using the File API
doc_io = io.BytesIO(httpx.get(long_context_pdf_path).content)
sample_doc = client.files.upload(
# You can pass a path or a file-like object here
file=doc_io,
config=dict(
mime_type='application/pdf')
)
prompt = "Summarize this document"
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[sample_doc, prompt])
print(response.text)
자바스크립트
import { createPartFromUri, GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
async function main() {
const pdfBuffer = await fetch("https://www.nasa.gov/wp-content/uploads/static/history/alsj/a17/A17_FlightPlan.pdf")
.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',
},
});
// Wait for the file to be processed.
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.');
}
// Add the file to the contents.
const content = [
'Summarize this document',
];
if (file.uri && file.mimeType) {
const fileContent = createPartFromUri(file.uri, file.mimeType);
content.push(fileContent);
}
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: content,
});
console.log(response.text);
}
main();
Go
package main
import (
"context"
"fmt"
"io"
"net/http"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, _ := genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
pdfURL := "https://www.nasa.gov/wp-content/uploads/static/history/alsj/a17/A17_FlightPlan.pdf"
localPdfPath := "A17_FlightPlan_downloaded.pdf"
respHttp, _ := http.Get(pdfURL)
defer respHttp.Body.Close()
outFile, _ := os.Create(localPdfPath)
defer outFile.Close()
_, _ = io.Copy(outFile, respHttp.Body)
uploadConfig := &genai.UploadFileConfig{MIMEType: "application/pdf"}
uploadedFile, _ := client.Files.UploadFromPath(ctx, localPdfPath, uploadConfig)
promptParts := []*genai.Part{
genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType),
genai.NewPartFromText("Summarize this document"),
}
contents := []*genai.Content{
genai.NewContentFromParts(promptParts, genai.RoleUser), // Specify role
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-2.5-flash",
contents,
nil,
)
fmt.Println(result.Text())
}
REST
PDF_PATH="https://www.nasa.gov/wp-content/uploads/static/history/alsj/a17/A17_FlightPlan.pdf"
DISPLAY_NAME="A17_FlightPlan"
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 "${BASE_URL}/upload/v1beta/files?key=${GOOGLE_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 ".file.uri" file_info.json)
echo "file_uri: ${file_uri}"
# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{"text": "'$PROMPT'"},
{"file_data":{"mime_type": "application/pdf", "file_uri": '$file_uri'}}]
}]
}' 2> /dev/null > response.json
cat response.json
echo
jq ".candidates[].content.parts[].text" response.json
# Clean up the downloaded PDF
rm "${DISPLAY_NAME}.pdf"
로컬에 저장된 대용량 PDF
Python
from google import genai
from google.genai import types
import pathlib
import httpx
client = genai.Client()
# Retrieve and encode the PDF byte
file_path = pathlib.Path('large_file.pdf')
# Upload the PDF using the File API
sample_file = client.files.upload(
file=file_path,
)
prompt="Summarize this document"
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[sample_file, "Summarize this document"])
print(response.text)
자바스크립트
import { createPartFromUri, GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
async function main() {
const file = await ai.files.upload({
file: 'path-to-localfile.pdf'
config: {
displayName: 'A17_FlightPlan.pdf',
},
});
// Wait for the file to be processed.
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.');
}
// Add the file to the contents.
const content = [
'Summarize this document',
];
if (file.uri && file.mimeType) {
const fileContent = createPartFromUri(file.uri, file.mimeType);
content.push(fileContent);
}
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: content,
});
console.log(response.text);
}
main();
Go
package main
import (
"context"
"fmt"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, _ := genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
localPdfPath := "/path/to/file.pdf"
uploadConfig := &genai.UploadFileConfig{MIMEType: "application/pdf"}
uploadedFile, _ := client.Files.UploadFromPath(ctx, localPdfPath, uploadConfig)
promptParts := []*genai.Part{
genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType),
genai.NewPartFromText("Give me a summary of this pdf file."),
}
contents := []*genai.Content{
genai.NewContentFromParts(promptParts, genai.RoleUser),
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-2.5-flash",
contents,
nil,
)
fmt.Println(result.Text())
}
REST
NUM_BYTES=$(wc -c < "${PDF_PATH}")
DISPLAY_NAME=TEXT
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?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 ".file.uri" file_info.json)
echo file_uri=$file_uri
# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{"text": "Can you add a few more lines to this poem?"},
{"file_data":{"mime_type": "application/pdf", "file_uri": '$file_uri'}}]
}]
}' 2> /dev/null > response.json
cat response.json
echo
jq ".candidates[].content.parts[].text" response.json
files.get
를 호출하여 API가 업로드된 파일을 성공적으로 저장했는지 확인하고 메타데이터를 가져올 수 있습니다. name
(및 확장된 uri
)만 고유합니다.
Python
from google import genai
import pathlib
client = genai.Client()
fpath = pathlib.Path('example.txt')
fpath.write_text('hello')
file = client.files.upload(file='example.txt')
file_info = client.files.get(name=file.name)
print(file_info.model_dump_json(indent=4))
REST
name=$(jq ".file.name" file_info.json)
# Get the file of interest to check state
curl https://generativelanguage.googleapis.com/v1beta/files/$name > file_info.json
# Print some information about the file you got
name=$(jq ".file.name" file_info.json)
echo name=$name
file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri
여러 PDF 전달
문서와 텍스트 프롬프트의 결합된 크기가 모델의 컨텍스트 윈도우 내에 있으면 Gemini API는 단일 요청에서 최대 1, 000페이지의 PDF 문서를 여러 개 처리할 수 있습니다.
Python
from google import genai
import io
import httpx
client = genai.Client()
doc_url_1 = "https://arxiv.org/pdf/2312.11805"
doc_url_2 = "https://arxiv.org/pdf/2403.05530"
# Retrieve and upload both PDFs using the File API
doc_data_1 = io.BytesIO(httpx.get(doc_url_1).content)
doc_data_2 = io.BytesIO(httpx.get(doc_url_2).content)
sample_pdf_1 = client.files.upload(
file=doc_data_1,
config=dict(mime_type='application/pdf')
)
sample_pdf_2 = client.files.upload(
file=doc_data_2,
config=dict(mime_type='application/pdf')
)
prompt = "What is the difference between each of the main benchmarks between these two papers? Output these in a table."
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[sample_pdf_1, sample_pdf_2, prompt])
print(response.text)
자바스크립트
import { createPartFromUri, GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
async function uploadRemotePDF(url, displayName) {
const pdfBuffer = await fetch(url)
.then((response) => response.arrayBuffer());
const fileBlob = new Blob([pdfBuffer], { type: 'application/pdf' });
const file = await ai.files.upload({
file: fileBlob,
config: {
displayName: displayName,
},
});
// Wait for the file to be processed.
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.');
}
return file;
}
async function main() {
const content = [
'What is the difference between each of the main benchmarks between these two papers? Output these in a table.',
];
let file1 = await uploadRemotePDF("https://arxiv.org/pdf/2312.11805", "PDF 1")
if (file1.uri && file1.mimeType) {
const fileContent = createPartFromUri(file1.uri, file1.mimeType);
content.push(fileContent);
}
let file2 = await uploadRemotePDF("https://arxiv.org/pdf/2403.05530", "PDF 2")
if (file2.uri && file2.mimeType) {
const fileContent = createPartFromUri(file2.uri, file2.mimeType);
content.push(fileContent);
}
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: content,
});
console.log(response.text);
}
main();
Go
package main
import (
"context"
"fmt"
"io"
"net/http"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, _ := genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
docUrl1 := "https://arxiv.org/pdf/2312.11805"
docUrl2 := "https://arxiv.org/pdf/2403.05530"
localPath1 := "doc1_downloaded.pdf"
localPath2 := "doc2_downloaded.pdf"
respHttp1, _ := http.Get(docUrl1)
defer respHttp1.Body.Close()
outFile1, _ := os.Create(localPath1)
_, _ = io.Copy(outFile1, respHttp1.Body)
outFile1.Close()
respHttp2, _ := http.Get(docUrl2)
defer respHttp2.Body.Close()
outFile2, _ := os.Create(localPath2)
_, _ = io.Copy(outFile2, respHttp2.Body)
outFile2.Close()
uploadConfig1 := &genai.UploadFileConfig{MIMEType: "application/pdf"}
uploadedFile1, _ := client.Files.UploadFromPath(ctx, localPath1, uploadConfig1)
uploadConfig2 := &genai.UploadFileConfig{MIMEType: "application/pdf"}
uploadedFile2, _ := client.Files.UploadFromPath(ctx, localPath2, uploadConfig2)
promptParts := []*genai.Part{
genai.NewPartFromURI(uploadedFile1.URI, uploadedFile1.MIMEType),
genai.NewPartFromURI(uploadedFile2.URI, uploadedFile2.MIMEType),
genai.NewPartFromText("What is the difference between each of the " +
"main benchmarks between these two papers? " +
"Output these in a table."),
}
contents := []*genai.Content{
genai.NewContentFromParts(promptParts, genai.RoleUser),
}
modelName := "gemini-2.5-flash"
result, _ := client.Models.GenerateContent(
ctx,
modelName,
contents,
nil,
)
fmt.Println(result.Text())
}
REST
DOC_URL_1="https://arxiv.org/pdf/2312.11805"
DOC_URL_2="https://arxiv.org/pdf/2403.05530"
DISPLAY_NAME_1="Gemini_paper"
DISPLAY_NAME_2="Gemini_1.5_paper"
PROMPT="What is the difference between each of the main benchmarks between these two papers? Output these in a table."
# Function to download and upload a PDF
upload_pdf() {
local doc_url="$1"
local display_name="$2"
# Download the PDF
wget -O "${display_name}.pdf" "${doc_url}"
local MIME_TYPE=$(file -b --mime-type "${display_name}.pdf")
local NUM_BYTES=$(wc -c < "${display_name}.pdf")
echo "MIME_TYPE: ${MIME_TYPE}"
echo "NUM_BYTES: ${NUM_BYTES}"
local tmp_header_file=upload-header.tmp
# Initial resumable request
curl "${BASE_URL}/upload/v1beta/files?key=${GOOGLE_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
local upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"
# Upload the PDF
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_${display_name}.json"
local file_uri=$(jq ".file.uri" "file_info_${display_name}.json")
echo "file_uri for ${display_name}: ${file_uri}"
# Clean up the downloaded PDF
rm "${display_name}.pdf"
echo "${file_uri}"
}
# Upload the first PDF
file_uri_1=$(upload_pdf "${DOC_URL_1}" "${DISPLAY_NAME_1}")
# Upload the second PDF
file_uri_2=$(upload_pdf "${DOC_URL_2}" "${DISPLAY_NAME_2}")
# Now generate content using both files
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{"file_data": {"mime_type": "application/pdf", "file_uri": '$file_uri_1'}},
{"file_data": {"mime_type": "application/pdf", "file_uri": '$file_uri_2'}},
{"text": "'$PROMPT'"}
]
}]
}' 2> /dev/null > response.json
cat response.json
echo
jq ".candidates[].content.parts[].text" response.json
기술 세부정보
Gemini는 최대 1,000개의 문서 페이지를 지원합니다. 각 문서 페이지는 258개의 토큰에 해당합니다.
모델의 컨텍스트 창 외에 문서의 픽셀 수에는 특별한 제한이 없지만, 큰 페이지는 원래 가로세로 비율을 유지하면서 최대 해상도인 3072x3072로 축소되고 작은 페이지는 768x768픽셀로 확대됩니다. 대역폭을 제외하고 크기가 작은 페이지의 비용 절감이나 해상도가 높은 페이지의 성능 개선은 없습니다.
문서 유형
기술적으로는 TXT, Markdown, HTML, XML 등 문서 이해를 위한 다른 MIME 유형을 전달할 수 있습니다. 하지만 문서 시각화는 PDF만 의미 있게 이해합니다. 다른 유형은 순수 텍스트로 추출되며 모델은 이러한 파일의 렌더링에서 보이는 내용을 해석할 수 없습니다. 차트, 다이어그램, HTML 태그, 마크다운 형식 등 파일 형식 관련 세부정보는 손실됩니다.
권장사항
최상의 결과를 얻는 방법
- 업로드하기 전에 페이지를 올바른 방향으로 회전하세요.
- 흐릿한 페이지는 피하세요.
- 단일 페이지를 사용하는 경우 페이지 뒤에 텍스트 프롬프트를 배치합니다.
다음 단계
자세한 내용은 다음 리소스를 참고하세요.
- 파일 프롬프트 전략: Gemini API는 텍스트, 이미지, 오디오, 동영상 데이터로 프롬프트를 지정하는 것을 지원하며, 이를 멀티모달 프롬프트라고도 합니다.
- 시스템 안내: 시스템 안내를 사용하면 특정 요구사항 및 사용 사례에 따라 모델의 동작을 조정할 수 있습니다.