В этом руководстве описаны различные способы включения медиафайлов, таких как изображения, аудио, видео и документы, при отправке запросов к API Gemini. Новые методы поддерживаются во всех конечных точках API Gemini, включая пакетную обработку, взаимодействие и API в реальном времени. Выбор подходящего метода зависит от размера файла, места хранения данных и частоты использования файла.
The simplest way to include a file as your input is to read a local file and include it in a prompt. The following example shows how to read a local PDF file. PDFs are limited to 50MB for this method. See the Input method comparison table for a complete list of file input types and limits.
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(""));
ОТДЫХ
# 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: $GEMINI_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"
}
]
}'
Сравнение методов ввода
The following table compares each input method with file limits and best use cases. Note that the file size limit may vary depending on the file type and model or tokenizer used to process the file.
| Метод | Лучше всего подходит для | Максимальный размер файла | Упорство |
|---|---|---|---|
| Встроенные данные | Быстрое тестирование, небольшие файлы, приложения для работы в режиме реального времени. | 100 МБ на запрос или полезную нагрузку ( 50 МБ для PDF-файлов ) | Ничего (отправляется с каждым запросом) |
| Загрузка файлов через API | Большие файлы, файлы, используемые многократно. | 2 ГБ на файл. до 20 ГБ на проект | 48 часов |
| Регистрация URI GCS через File API | Большие файлы уже находятся в Google Cloud Storage, и эти файлы используются многократно. | 2 ГБ на файл, без общих ограничений по объему хранилища. | Нет данных (получаются по запросу). Одноразовая регистрация предоставляет доступ на срок до 30 дней. |
| Внешние URL-адреса | Общедоступные данные или данные в облачных хранилищах (AWS, Azure, GCS) без повторной загрузки. | 100 МБ на запрос/полезную нагрузку | Нет данных (получено по запросу) |
Встроенные данные
For smaller files (under 100MB, or 50MB for PDFs), you can pass the data directly in the request payload. This is the simplest method for quick tests or applications handling real-time, transient data. You can provide data as base64 encoded strings or by reading local files directly.
Пример чтения из локального файла можно найти в начале этой страницы.
Получить данные с 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();
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.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
Client client = new Client();
String docUrl = "https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf";
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(docUrl)).build();
byte[] docData = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray()).body();
String base64Pdf = Base64.getEncoder().encodeToString(docData);
String prompt = "Summarize this document";
Content docContent =
DocumentContent.builder()
.data(base64Pdf)
.mimeType(DocumentContentMimeType.APPLICATION_PDF)
.build();
Content textContent = TextContent.builder().text(prompt).build();
List<Content> contents = Arrays.asList(docContent, textContent);
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(""));
ОТДЫХ
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: $GEMINI_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
API для работы с файлами предназначен для файлов больших размеров (до 2 ГБ) или файлов, которые вы планируете использовать в нескольких запросах.
Стандартная загрузка файлов
Загрузите локальный файл в API Gemini. Файлы, загруженные таким образом, хранятся временно (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();
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 com.google.genai.types.File;
import com.google.genai.types.UploadFileConfig;
import java.util.Arrays;
import java.util.List;
Client client = new Client();
File docFile =
client.files.upload(
new java.io.File("path/to/your/sample.pdf"),
UploadFileConfig.builder().mimeType("application/pdf").build());
String prompt = "Summarize this document";
Content textContent = TextContent.builder().text(prompt).build();
Content docContent =
DocumentContent.builder()
.uri(docFile.uri().orElse(""))
.mimeType(DocumentContentMimeType.of(docFile.mimeType().orElse("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(""));
ОТДЫХ
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: $GEMINI_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: $GEMINI_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.
Доступ агента по предоставлению грантов к каждому разделу
Включите API Gemini в своем проекте Google Cloud.
Создайте агента службы:
gcloud beta services identity create --service=generativelanguage.googleapis.com --project=<your_project>Предоставьте агенту службы Gemini API разрешения на чтение ваших хранилищ.
Пользователю необходимо назначить роль IAM «
Storage Object Viewer» этому агенту службы для конкретных сегментов хранилища, которые он планирует использовать.
Этот доступ по умолчанию не истекает, но его можно изменить в любое время. Вы также можете использовать команды SDK IAM Google Cloud Storage для предоставления разрешений.
Подтвердите подлинность вашей услуги.
Предварительные требования
- Включить API
- Создайте учетную запись службы или агента с соответствующими правами доступа.
Сначала необходимо пройти аутентификацию в качестве службы, имеющей права на просмотр объектов хранилища. Способ аутентификации зависит от среды, в которой будет выполняться ваш код управления файлами.
Вне облачной среды Google
Если ваш код выполняется вне Google Cloud, например, на вашем компьютере, загрузите учетные данные из консоли Google Cloud, выполнив следующие действия:
- Перейдите в консоль учетной записи службы.
- Выберите соответствующий сервисный аккаунт
- Выберите вкладку «Клавиши» и выберите «Добавить клавишу», «Создать новую клавишу».
- Выберите тип ключа JSON и запомните, куда был загружен файл на вашем компьютере.
Для получения более подробной информации см. официальную документацию Google Cloud по управлению ключами учетных записей служб .
Затем используйте следующие команды для аутентификации. Эти команды предполагают, что файл учетной записи службы находится в текущем каталоге и называется
service-account.json.Python
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 )JavaScript
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 });CLI
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
If you are running directly in Google Cloud, for example by using Cloud Run functions or a Compute Engine instance , you will have implicit credentials but will need to re-authenticate to grant the appropriate scopes.
Python
Данный код предполагает, что служба работает в среде, где учетные данные приложения по умолчанию могут быть получены автоматически, например, в Cloud Run или Compute Engine.
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)JavaScript
Данный код предполагает, что служба работает в среде, где учетные данные приложения по умолчанию могут быть получены автоматически, например, в Cloud Run или Compute Engine.
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' ] });
Java
java import com.google.auth.oauth2.GoogleCredentials; import java.io.FileInputStream; import java.util.Arrays; import java.util.List; List<String> gcsReadScopes = Arrays.asList( "https://www.googleapis.com/auth/devstorage.read_only", "https://www.googleapis.com/auth/cloud-platform"); String serviceAccountFile = "service-account.json"; GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(serviceAccountFile)) .createScoped(gcsReadScopes); CLI
Это интерактивная команда. Для таких служб, как Compute Engine, вы можете прикреплять области действия к запущенной службе на уровне конфигурации. Пример см. в документации по службам, управляемым пользователем .
gcloud auth application-default login \
--scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/devstorage.read_only"
- Регистрация файлов (Files API) Используйте Files API для регистрации файлов и создания пути Files API, который можно напрямую использовать в Gemini API.
Python
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)JavaScript
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();
Java
import com.google.auth.oauth2.GoogleCredentials;
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 com.google.genai.types.File;
import com.google.genai.types.RegisterFilesResponse;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
GoogleCredentials credentials =
GoogleCredentials.fromStream(new FileInputStream("service-account.json"))
.createScoped(
Arrays.asList(
"https://www.googleapis.com/auth/devstorage.read_only",
"https://www.googleapis.com/auth/cloud-platform"));
Client client = Client.builder().credentials(credentials).build();
RegisterFilesResponse registeredGcsFiles =
client.files.registerFiles(
credentials,
Arrays.asList("gs://my_bucket/some_object.pdf", "gs://bucket2/object2.txt"),
null);
String prompt = "Summarize this file.";
for (File f : registeredGcsFiles.files().orElse(Collections.emptyList())) {
System.out.println(f.name().orElse(""));
Content textContent = TextContent.builder().text(prompt).build();
Content docContent =
DocumentContent.builder()
.uri(f.uri().orElse(""))
.mimeType(DocumentContentMimeType.of(f.mimeType().orElse("application/pdf")))
.build();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.ofContent(Arrays.asList(textContent, docContent)))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
}
CLI
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-адреса
You can pass publicly accessible HTTPS URLs or pre-signed URLs directly in your request. The Gemini API will fetch the content securely during processing. This is ideal for files up to 100MB that you don't want to re-upload.
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();
ОТДЫХ
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": "text", "text": "Summarize this pdf"},
{
"type": "document",
"uri": "https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf",
"mime_type": "application/pdf"
}
]
}'
Доступность
Verify that the URLs you provide don't lead to pages that require a login or are behind a paywall. For private databases, ensure you create a signed URL with the correct access permissions and expiry.
проверки безопасности
The system performs a content moderation check on the URL to confirm they meet safety and policy standards. If the URL fails this check, you will get an url_retrieval_status of URL_RETRIEVAL_STATUS_UNSAFE .
Поддерживаемые типы контента
This list of supported file types and limitations is intended as initial guidance and is not comprehensive. The effective set of supported types is subject to change and can vary based on the specific model and tokenizer version in use. Unsupported types will result in an error. Additionally, content retrieval for these file types only supports publicly accessible URLs.
Типы текстовых файлов
-
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.
Ограничения
- Ограничения на размер файлов различаются в зависимости от метода (см. сравнительную таблицу ) и типа файла.
- Встраивание данных увеличивает размер полезной нагрузки запроса.
- Загрузка файлов через File API носит временный характер и прекращается через 48 часов.
- Загрузка внешних URL-адресов ограничена 100 МБ на один полезный объем данных и поддерживает определенные типы контента.
Что дальше?
- Попробуйте создать собственные мультимодальные подсказки с помощью Google AI Studio .
- Информацию о включении файлов в ваши запросы см. в руководствах по обработке изображений , аудио и документов .