Модели Gemini могут обрабатывать документы в формате PDF, используя нативное машинное зрение для понимания всего контекста документа. Это выходит за рамки простого извлечения текста, позволяя Gemini:
- Анализ и интерпретация контента, включая текст, изображения, диаграммы, графики и таблицы, даже в длинных документах объемом до 1000 страниц.
- Извлечение информации в структурированные выходные форматы.
- Кратко изложите суть вопроса и ответьте на вопросы, основываясь как на визуальных, так и на текстовых элементах документа.
- Преобразовать содержимое документа (например, в HTML), сохраняя макет и форматирование, для использования в последующих приложениях.
Таким же образом можно передавать и документы, не в формате PDF, но Gemini будет рассматривать их как обычный текст, исключая контекст, такой как диаграммы или форматирование.
Передача данных PDF непосредственно в код.
Вы можете передавать данные PDF непосредственно в запросе. Это лучше всего подходит для небольших документов или временной обработки, когда вам не нужно ссылаться на файл в последующих запросах. Для больших документов, на которые вам нужно ссылаться в многоэтапных взаимодействиях, мы рекомендуем использовать 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.8-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.8-flash",
input: [
{ type: "text", text: "Summarize this document" },
{
type: "document",
data: pdfData,
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.util.Arrays;
import java.util.List;
Client client = new Client();
Content textContent = TextContent.builder().text("Summarize this document.").build();
Content docContent =
DocumentContent.builder()
.uri("gs://cloud-samples-data/generative-ai/pdf/sample.pdf")
.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(""));
ОТДЫХ
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.8-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.8-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.8-flash",
input: [
{ type: "text", text: "Summarize this document" },
{
type: "document",
uri: uploadedFile.uri,
mime_type: uploadedFile.mime_type
}
]
});
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.util.Arrays;
import java.util.List;
Client client = new Client();
Content textContent = TextContent.builder().text("Summarize this document.").build();
Content docContent =
DocumentContent.builder()
.uri("gs://cloud-samples-data/generative-ai/pdf/sample.pdf")
.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