طُرق إدخال الملفات
يوضّح هذا الدليل الطرق المختلفة التي يمكنك من خلالها تضمين ملفات وسائط، مثل الصور والصوت والفيديو والمستندات، عند إرسال طلبات إلى Gemini API. تتوفّر الطرق الجديدة في جميع نقاط نهاية Gemini API، بما في ذلك Batch وInteractions وLive API. يعتمد اختيار الطريقة المناسبة على حجم ملفك ومكان تخزين بياناتك ومعدّل تكرار استخدامك للملف.
أبسط طريقة لتضمين ملف كمدخل هي قراءة ملف محلي وتضمينه في طلب. يوضّح المثال التالي كيفية قراءة ملف PDF محلي. يقتصر حجم ملفات PDF على 50 ميغابايت عند استخدام هذه الطريقة. راجِع جدول مقارنة طرق الإدخال للحصول على قائمة كاملة بأنواع الملفات والقيود المفروضة على إدخالها.
Python
from google import genai
import pathlib
client = genai.Client()
filepath = pathlib.Path('my_local_file.pdf')
prompt = "Summarize this document"
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": prompt},
{"type": "document", "data": filepath.read_bytes(), "mime_type": "application/pdf"}
]
)
# Print the model's text response
for step in interaction.steps:
if step.type == "model_output":
for content_block in step.content:
if content_block.type == "text":
print(content_block.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-flash-preview",
input: [
{ type: "text", text: prompt },
{
type: "document",
data: fs.readFileSync(filePath).toString("base64"),
mimeType: "application/pdf"
}
]
});
const modelStep = interaction.steps.find(s => s.type === 'model_output');
if (modelStep) {
for (const contentBlock of modelStep.content) {
if (contentBlock.type === 'text') console.log(contentBlock.text);
}
}
}
main();
REST
# 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-flash-preview",
"input": [
{"type": "text", "text": "Summarize this document"},
{
"type": "document",
"data": "'${B64_CONTENT}'",
"mimeType": "application/pdf"
}
]
}'
مقارنة طرق الإدخال
يقارن الجدول التالي بين كل طريقة إدخال من حيث حدود الملفات وحالات الاستخدام الأفضل. يُرجى العِلم أنّ الحدّ الأقصى المسموح به لحجم الملف قد يختلف حسب نوع الملف والنموذج أو أداة تقسيم النص المستخدَمة لمعالجة الملف.
| الطريقة | الأفضل لـ | الحجم الأقصى للملف | الاستمرارية |
|---|---|---|---|
| البيانات المضمّنة | اختبار سريع، وملفات صغيرة، وتطبيقات في الوقت الفعلي | 100 ميغابايت لكل طلب أو حمولة (50 ميغابايت لملفات PDF) |
بلا قيمة (يتم إرسالها مع كل طلب) |
| تحميل الملفات من خلال واجهة برمجة التطبيقات | الملفات الكبيرة والملفات المستخدَمة عدة مرات | 2 غيغابايت لكل ملف، ما يصل إلى 20 غيغابايت لكل مشروع |
48 ساعة |
| تسجيل معرّف الموارد المنتظم (URI) في File API على "خدمة التخزين السحابي من Google" | الملفات الكبيرة المخزَّنة في Google Cloud Storage، والملفات المستخدَمة عدة مرات | 2 غيغابايت لكل ملف، بدون حدود إجمالية لمساحة التخزين | لا شيء (يتم استرجاعها لكل طلب). يمكن أن يتيح التسجيل لمرة واحدة الوصول إلى التطبيق لمدة تصل إلى 30 يومًا. |
| عناوين URL الخارجية | البيانات العامة أو البيانات في حِزم السحابة الإلكترونية (AWS وAzure وGCS) بدون إعادة التحميل | 100 ميغابايت لكل طلب/حمولة | لا شيء (يتم استردادها لكل طلب) |
البيانات المضمّنة
بالنسبة إلى الملفات الأصغر حجمًا (أقل من 100 ميغابايت، أو 50 ميغابايت لملفات PDF)، يمكنك تمرير البيانات مباشرةً في حمولة الطلب. هذه هي أبسط طريقة لإجراء اختبارات سريعة أو تطبيقات تعالج بيانات مؤقتة في الوقت الفعلي. يمكنك تقديم البيانات كسلاسل مشفّرة بنظام base64 أو من خلال قراءة الملفات المحلية مباشرةً.
للاطّلاع على مثال على القراءة من ملف محلي، راجِع المثال في بداية هذه الصفحة.
الجلب من عنوان 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-flash-preview",
input=[
{"type": "document", "data": doc_data, "mime_type": "application/pdf"},
{"type": "text", "text": prompt}
]
)
# Print the model's text response
for step in interaction.steps:
if step.type == "model_output":
for content_block in step.content:
if content_block.type == "text":
print(content_block.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-flash-preview",
input: [
{ type: "text", text: prompt },
{
type: "document",
data: Buffer.from(pdfResp).toString("base64"),
mimeType: "application/pdf"
}
]
});
const modelStep = interaction.steps.find(s => s.type === 'model_output');
if (modelStep) {
for (const contentBlock of modelStep.content) {
if (contentBlock.type === 'text') console.log(contentBlock.text);
}
}
}
main();
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 interactions
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-flash-preview",
"input": [
{"type": "document", "data": "'$ENCODED_PDF'", "mimeType": "application/pdf"},
{"type": "text", "text": "'$PROMPT'"}
]
}' 2> /dev/null > response.json
cat response.json
echo
jq ".steps[] | select(.type == \"model_output\") | .content[] | select(.type == \"text\") | .text" response.json
Gemini File API
تم تصميم File API للملفات الأكبر حجمًا (حتى 2 غيغابايت) أو الملفات التي تنوي استخدامها في طلبات متعددة.
تحميل الملفات العادي
حمِّل ملفًا محليًا إلى Gemini API. يتم تخزين الملفات التي يتم تحميلها بهذه الطريقة بشكل مؤقت (لمدة 48 ساعة) ومعالجتها ليتمكّن النموذج من استرجاعها بكفاءة.
Python
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 an interaction
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": prompt},
{"type": "audio", "uri": audio_file.uri, "mime_type": audio_file.mime_type}
]
)
# Print the model's text response
for step in interaction.steps:
if step.type == "model_output":
for content_block in step.content:
if content_block.type == "text":
print(content_block.text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const prompt = "Describe this audio clip";
async function main() {
const filePath = "path/to/your/sample.mp3";
const myfile = await client.files.upload({
file: filePath,
config: { mimeType: "audio/mpeg" },
});
const interaction = await client.interactions.create({
model: "gemini-3-flash-preview",
input: [
{ type: "text", text: prompt },
{ type: "audio", uri: myfile.uri, mimeType: myfile.mimeType }
]
});
const modelStep = interaction.steps.find(s => s.type === 'model_output');
if (modelStep) {
for (const contentBlock of modelStep.content) {
if (contentBlock.type === 'text') console.log(contentBlock.text);
}
}
}
await main();
REST
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.
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 "@${AUDIO_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-flash-preview",
"input": [
{"type": "text", "text": "Describe this audio clip"},
{"type": "audio", "uri": '$file_uri', "mimeType": "'${MIME_TYPE}'"}
]
}'
تسجيل ملفات Google Cloud Storage
إذا كانت بياناتك متوفّرة في Google Cloud Storage، لن تحتاج إلى تنزيلها وإعادة تحميلها. يمكنك تسجيلها مباشرةً باستخدام File API.
منح وكيل الخدمة إذن الوصول إلى كل حزمة
فعِّل Gemini API في مشروعك على Google Cloud.
إنشاء وكيل الخدمة:
gcloud beta services identity create --service=generativelanguage.googleapis.com --project=<your_project>امنح وكيل خدمة Gemini API الأذونات اللازمة لقراءة حِزم التخزين.
على المستخدم منح
Storage Object Viewerدور IAM لوكيل الخدمة هذا في حِزم التخزين المحدّدة التي ينوي استخدامها.
لا تنتهي صلاحية هذا الإذن بالوصول تلقائيًا، ولكن يمكن تغييره في أي وقت. يمكنك أيضًا استخدام أوامر Google Cloud Storage IAM SDK لمنح الأذونات.
مصادقة خدمتك
المتطلبات الأساسية
- تفعيل واجهة برمجة التطبيقات
- أنشئ حساب خدمة أو وكيلًا لديه الأذونات المناسبة.
عليك أولاً المصادقة بصفتك الخدمة التي لديها أذونات عارض كائنات التخزين. وتختلف طريقة فعل ذلك حسب البيئة التي سيتم فيها تشغيل رمز إدارة الملفات.
خارج Google Cloud
إذا كان الرمز البرمجي يعمل من خارج 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 Cloud
إذا كنت تستخدم Google Cloud مباشرةً، مثلاً من خلال استخدام وظائف Cloud Run أو مثيل Compute Engine، ستتوفّر لك بيانات اعتماد ضمنية، ولكن عليك إعادة المصادقة لمنح النطاقات المناسبة.
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' ] });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 # 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(credentials=credentials) registered_gcs_files = client.files.register_files( uris=["gs://my_bucket/some_object.pdf", "gs://bucket2/object2.txt"] ) prompt = "Summarize this file." # call interactions.create for each file for f in registered_gcs_files.files: print(f.name) interaction = client.interactions.create( model="gemini-3-flash-preview", input=[ {"type": "text", "text": prompt}, {"type": "document", "uri": f.uri, "mime_type": f.mime_type} ], ) # Print the model's text response for step in interaction.steps: if step.type == "model_output": for content_block in step.content: if content_block.type == "text": print(content_block.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-flash-preview", input: [ { type: "text", text: prompt }, { type: "document", uri: file.uri, mimeType: file.mimeType } ] }); const modelStep = interaction.steps.find(s => s.type === 'model_output'); if (modelStep) { for (const contentBlock of modelStep.content) { if (contentBlock.type === 'text') console.log(contentBlock.text); } } } } main();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"]}'
عناوين URL الخارجية التي تستخدم HTTP أو عناوين URL الموقَّعة
يمكنك تمرير عناوين URL تستخدم HTTPS ومتاحة للجميع أو عناوين URL موقّعة مسبقًا مباشرةً في طلبك. ستجلب Gemini API المحتوى بشكل آمن أثناء المعالجة. هذه الطريقة مثالية للملفات التي يصل حجمها إلى 100 ميغابايت والتي لا تريد إعادة تحميلها.
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-flash-preview",
input=[
{"type": "document", "uri": uri, "mime_type": "application/pdf"},
{"type": "text", "text": prompt}
]
)
# Print the model's text response
for step in interaction.steps:
if step.type == "model_output":
for content_block in step.content:
if content_block.type == "text":
print(content_block.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-flash-preview',
input: [
{ type: "document", uri: uri, mimeType: "application/pdf" },
{ type: "text", text: "summarize this file" }
]
});
const modelStep = interaction.steps.find(s => s.type === 'model_output');
if (modelStep) {
for (const contentBlock of modelStep.content) {
if (contentBlock.type === 'text') console.log(contentBlock.text);
}
}
}
main();
REST
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-flash-preview",
"input": [
{"type": "text", "text": "Summarize this pdf"},
{
"type": "document",
"uri": "https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf",
"mimeType": "application/pdf"
}
]
}'
تسهيل الاستخدام
تأكَّد من أنّ عناوين URL التي تقدّمها لا تؤدي إلى صفحات تتطلّب تسجيل الدخول أو تستخدم حاجز الدفع. بالنسبة إلى قواعد البيانات الخاصة، تأكَّد من إنشاء عنوان URL موقَّع مع أذونات الوصول وتاريخ انتهاء الصلاحية الصحيحَين.
عمليات التحقّق من الأمان
يُجري النظام عملية التحقّق من الإشراف على المحتوى في عنوان URL للتأكّد من استيفائه لمعايير الأمان والسياسات. إذا لم يجتَز عنوان URL عملية التحقّق هذه، سيظهر لك
url_retrieval_status من URL_RETRIEVAL_STATUS_UNSAFE.
أنواع المحتوى المتوافقة
هذه القائمة بأنواع الملفات المتوافقة والقيود هي إرشادات أولية وليست شاملة. يمكن أن يتغيّر مجموعة الأنواع المتوافقة الفعّالة، وقد تختلف حسب الطراز وإصدار أداة الترميز المحدّدين المستخدَمان. وستؤدي الأنواع غير المتوافقة إلى حدوث خطأ. بالإضافة إلى ذلك، لا يمكن استرداد المحتوى من أنواع الملفات هذه إلا باستخدام عناوين URL متاحة للجميع.
أنواع الملفات النصية
text/htmltext/csstext/plaintext/xmltext/csvtext/rtftext/javascript
أنواع ملفات التطبيقات
application/jsonapplication/pdf
أنواع ملفات الصور
image/bmpimage/jpegimage/pngimage/webp
أفضل الممارسات
- اختيار الطريقة المناسبة: استخدِم البيانات المضمّنة للملفات الصغيرة والمؤقتة. استخدِم File API للملفات الأكبر حجمًا أو الملفات المستخدَمة بشكل متكرّر. استخدِم عناوين URL خارجية للبيانات المستضافة على الإنترنت.
- تحديد أنواع MIME: احرص دائمًا على تقديم نوع MIME الصحيح لبيانات الملف لضمان معالجتها بشكل سليم.
- معالجة الأخطاء: نفِّذ إجراءات معالجة الأخطاء في الرمز البرمجي لإدارة المشاكل المحتملة، مثل أعطال الشبكة أو مشاكل الوصول إلى الملفات أو أخطاء واجهة برمجة التطبيقات.
القيود
- تختلف حدود حجم الملف حسب الطريقة (راجِع جدول المقارنة) ونوع الملف.
- تؤدي البيانات المضمّنة إلى زيادة حجم حمولة الطلب.
- تكون عمليات التحميل باستخدام File API مؤقتة وتنتهي صلاحيتها بعد 48 ساعة.
- يقتصر جلب عناوين URL الخارجية على 100 ميغابايت لكل حمولة، ويتوافق مع أنواع محتوى معيّنة.
الخطوات التالية
- يمكنك تجربة كتابة طلبات متعددة الوسائط باستخدام Google AI Studio.
- للحصول على معلومات حول تضمين الملفات في طلباتك، يُرجى الاطّلاع على أدلة Vision و الصوت و معالجة المستندات.