Gemini API מאפשר יצירה משופרת של מידע (RAG) באמצעות הכלי FileSearch. האפליקציה 'חיפוש קבצים' מייבאת את הנתונים, מחלקת אותם לחלקים ויוצרת אינדקס כדי לאפשר שליפה מהירה של מידע רלוונטי על סמך הנחיה שסופקה. המידע הזה משמש כהקשר למודל, וכך המודל יכול לספק תשובות מדויקות ורלוונטיות יותר.
כדי להפוך את חיפוש הקבצים לפשוט וזול למפתחים, אנחנו מאפשרים אחסון קבצים ויצירת הטמעה בזמן השאילתה ללא תשלום. אתם משלמים רק על יצירת הטמעות כשאתם יוצרים אינדקס לקבצים בפעם הראשונה (במחיר של מודל ההטמעה הרלוונטי) ועל העלות הרגילה של טוקנים של קלט ופלט של מודל Gemini. הפרדיגמה החדשה הזו של חיוב מאפשרת לבנות את הכלי לחיפוש קבצים ולהרחיב אותו בקלות וביעילות.
העלאה ישירה למאגר של חיפוש קבצים
בדוגמה הזו אפשר לראות איך מעלים קובץ ישירות אל מאגר הקבצים לחיפוש:
Python
from google import genai
from google.genai import types
import time
client = genai.Client()
# File name will be visible in citations
file_search_store = client.file_search_stores.create(config={'display_name': 'your-fileSearchStore-name'})
operation = client.file_search_stores.upload_to_file_search_store(
file='sample.txt',
file_search_store_name=file_search_store.name,
config={
'display_name' : 'display-file-name',
}
)
while not operation.done:
time.sleep(5)
operation = client.operations.get(operation)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""Can you tell me about [insert question]""",
config=types.GenerateContentConfig(
tools=[
types.Tool(
file_search=types.FileSearch(
file_search_store_names=[file_search_store.name]
)
)
]
)
)
print(response.text)
JavaScript
const { GoogleGenAI } = require('@google/genai');
const ai = new GoogleGenAI({});
async function run() {
// File name will be visible in citations
const fileSearchStore = await ai.fileSearchStores.create({
config: { displayName: 'your-fileSearchStore-name' }
});
let operation = await ai.fileSearchStores.uploadToFileSearchStore({
file: 'file.txt',
fileSearchStoreName: fileSearchStore.name,
config: {
displayName: 'file-name',
}
});
while (!operation.done) {
await new Promise(resolve => setTimeout(resolve, 5000));
operation = await ai.operations.get({ operation });
}
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "Can you tell me about [insert question]",
config: {
tools: [
{
fileSearch: {
fileSearchStoreNames: [fileSearchStore.name]
}
}
]
}
});
console.log(response.text);
}
run();
מידע נוסף זמין במאמר בנושא uploadToFileSearchStore.
ייבוא קבצים
אפשר גם להעלות קובץ קיים ולייבא אותו למאגר של חיפוש הקבצים:
Python
from google import genai
from google.genai import types
import time
client = genai.Client()
# File name will be visible in citations
sample_file = client.files.upload(file='sample.txt', config={'name': 'display_file_name'})
file_search_store = client.file_search_stores.create(config={'display_name': 'your-fileSearchStore-name'})
operation = client.file_search_stores.import_file(
file_search_store_name=file_search_store.name,
file_name=sample_file.name
)
while not operation.done:
time.sleep(5)
operation = client.operations.get(operation)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""Can you tell me about [insert question]""",
config=types.GenerateContentConfig(
tools=[
types.Tool(
file_search=types.FileSearch(
file_search_store_names=[file_search_store.name]
)
)
]
)
)
print(response.text)
JavaScript
const { GoogleGenAI } = require('@google/genai');
const ai = new GoogleGenAI({});
async function run() {
// File name will be visible in citations
const sampleFile = await ai.files.upload({
file: 'sample.txt',
config: { name: 'file-name' }
});
const fileSearchStore = await ai.fileSearchStores.create({
config: { displayName: 'your-fileSearchStore-name' }
});
let operation = await ai.fileSearchStores.importFile({
fileSearchStoreName: fileSearchStore.name,
fileName: sampleFile.name
});
while (!operation.done) {
await new Promise(resolve => setTimeout(resolve, 5000));
operation = await ai.operations.get({ operation: operation });
}
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "Can you tell me about [insert question]",
config: {
tools: [
{
fileSearch: {
fileSearchStoreNames: [fileSearchStore.name]
}
}
]
}
});
console.log(response.text);
}
run();
מידע נוסף זמין במאמר בנושא importFile.
הגדרות חלוקה לחלקים
כשמייבאים קובץ למאגר חיפוש קבצים, הוא מפורק אוטומטית לחלקים, מוטמע, עובר אינדוקס ועולה למאגר חיפוש הקבצים. אם אתם צריכים שליטה רבה יותר על אסטרטגיית החלוקה לחלקים, אתם יכולים לציין הגדרה של chunking_config כדי להגדיר מספר מקסימלי של טוקנים לכל חלק ומספר מקסימלי של טוקנים חופפים.
Python
from google import genai
from google.genai import types
import time
client = genai.Client()
operation = client.file_search_stores.upload_to_file_search_store(
file_search_store_name=file_search_store.name,
file_name=sample_file.name,
config={
'chunking_config': {
'white_space_config': {
'max_tokens_per_chunk': 200,
'max_overlap_tokens': 20
}
}
}
)
while not operation.done:
time.sleep(5)
operation = client.operations.get(operation)
print("Custom chunking complete.")
JavaScript
const { GoogleGenAI } = require('@google/genai');
const ai = new GoogleGenAI({});
let operation = await ai.fileSearchStores.uploadToFileSearchStore({
file: 'file.txt',
fileSearchStoreName: fileSearchStore.name,
config: {
displayName: 'file-name',
chunkingConfig: {
whiteSpaceConfig: {
maxTokensPerChunk: 200,
maxOverlapTokens: 20
}
}
}
});
while (!operation.done) {
await new Promise(resolve => setTimeout(resolve, 5000));
operation = await ai.operations.get({ operation });
}
console.log("Custom chunking complete.");
כדי להשתמש בחנות שלכם לחיפוש קבצים, מעבירים אותה ככלי לשיטה generateContent, כמו בדוגמאות של העלאה וייבוא.
איך זה עובד
חיפוש קבצים משתמש בטכניקה שנקראת חיפוש סמנטי כדי למצוא מידע שרלוונטי להנחיה של המשתמש. בניגוד לחיפוש רגיל שמבוסס על מילות מפתח, חיפוש סמנטי מבין את המשמעות וההקשר של השאילתה.
כשמייבאים קובץ, הוא מומר לייצוגים מספריים שנקראים הטמעות, שמשקפים את המשמעות הסמנטית של הטקסט. ההטמעות האלה מאוחסנות במסד נתונים ייעודי של חיפוש קבצים. כשמבצעים שאילתה, היא מומרת גם להטמעה. לאחר מכן, המערכת מבצעת חיפוש בקובץ כדי למצוא את חלקי המסמך הדומים והרלוונטיים ביותר ממאגר החיפוש בקובץ.
אין אורך חיים (TTL) להטמעות ולקבצים. הם נשמרים עד למחיקה ידנית, או עד שהמודל יוצא משימוש.
פירוט התהליך לשימוש ב-File Search
uploadToFileSearchStore API:
יצירת מאגר חיפוש קבצים: מאגר חיפוש קבצים מכיל את הנתונים המעובדים מהקבצים שלכם. זהו מאגר קבוע של ההטמעות שהחיפוש הסמנטי יפעל עליהן.
העלאת קובץ וייבוא שלו למאגר של חיפוש קבצים: אפשר להעלות קובץ ולייבא את התוצאות למאגר של חיפוש קבצים בו-זמנית. הפעולה הזו יוצרת אובייקט
Fileזמני, שהוא הפניה למסמך הגולמי. הנתונים האלה מחולקים לחלקים, מומרים להטמעות של חיפוש קבצים ומתווספים לאינדקס. אובייקטFileיימחק אחרי 48 שעות, אבל הנתונים שיובאו למאגר של חיפוש הקבצים יישמרו ללא הגבלת זמן עד שתבחרו למחוק אותם.שאילתה עם חיפוש קבצים: לבסוף, אתם משתמשים בכלי
FileSearchבשיחה ב-generateContent. בהגדרת הכלי, מצייניםFileSearchRetrievalResource, שמפנה אלFileSearchStoreשרוצים לחפש. ההוראה הזו אומרת למודל לבצע חיפוש סמנטי במאגר הספציפי הזה של חיפוש קבצים כדי למצוא מידע רלוונטי שישמש בסיס לתשובה.
בתרשים הזה, הקו המקווקו ממסמכים אל מודל הטמעה (באמצעות gemini-embedding-001) מייצג את uploadToFileSearchStore API (בלי לעבור דרך אחסון קבצים).
אחרת, שימוש ב-Files API כדי ליצור בנפרד ואז לייבא קבצים מעביר את תהליך יצירת האינדקס ממסמכים אל אחסון קבצים ואז אל מודל הטמעה.
מאגרי חיפוש קבצים
מאגר חיפוש קבצים הוא מאגר להטמעות של המסמכים שלכם. קובצי RAW שהועלו דרך File API נמחקים אחרי 48 שעות, אבל הנתונים שיובאו למאגר של חיפוש קבצים נשמרים ללא הגבלת זמן עד שמבצעים מחיקה ידנית. אתם יכולים ליצור כמה מאגרי חיפוש קבצים כדי לארגן את המסמכים שלכם. FileSearchStore API מאפשר לכם ליצור, להציג, לקבל ולמחוק כדי לנהל את חנויות החיפוש של הקבצים. שמות מאגרי חיפוש קבצים הם בהיקף גלובלי.
הנה כמה דוגמאות לניהול מאגרי חיפוש קבצים:
Python
file_search_store = client.file_search_stores.create(config={'display_name': 'my-file_search-store-123'})
for file_search_store in client.file_search_stores.list():
print(file_search_store)
my_file_search_store = client.file_search_stores.get(name='fileSearchStores/my-file_search-store-123')
client.file_search_stores.delete(name='fileSearchStores/my-file_search-store-123', config={'force': True})
JavaScript
const fileSearchStore = await ai.fileSearchStores.create({
config: { displayName: 'my-file_search-store-123' }
});
const fileSearchStores = await ai.fileSearchStores.list();
for await (const store of fileSearchStores) {
console.log(store);
}
const myFileSearchStore = await ai.fileSearchStores.get({
name: 'fileSearchStores/my-file_search-store-123'
});
await ai.fileSearchStores.delete({
name: 'fileSearchStores/my-file_search-store-123',
config: { force: true }
});
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/fileSearchStores?key=${GEMINI_API_KEY}" \
-H "Content-Type: application/json"
-d '{ "displayName": "My Store" }'
curl "https://generativelanguage.googleapis.com/v1beta/fileSearchStores?key=${GEMINI_API_KEY}" \
curl "https://generativelanguage.googleapis.com/v1beta/fileSearchStores/my-file_search-store-123?key=${GEMINI_API_KEY}"
curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/fileSearchStores/my-file_search-store-123?key=${GEMINI_API_KEY}"
חיפוש מסמכים
אפשר לנהל מסמכים ספציפיים במאגרי הקבצים באמצעות File Search Documents API כדי list כל מסמך במאגר קבצים לחיפוש, get מידע על מסמך וdelete מסמך לפי שם.
Python
for document_in_store in client.file_search_stores.documents.list(parent='fileSearchStores/my-file_search-store-123'):
print(document_in_store)
file_search_document = client.file_search_stores.documents.get(name='fileSearchStores/my-file_search-store-123/documents/my_doc')
print(file_search_document)
client.file_search_stores.documents.delete(name='fileSearchStores/my-file_search-store-123/documents/my_doc')
JavaScript
const documents = await ai.fileSearchStores.documents.list({
parent: 'fileSearchStores/my-file_search-store-123'
});
for await (const doc of documents) {
console.log(doc);
}
const fileSearchDocument = await ai.fileSearchStores.documents.get({
name: 'fileSearchStores/my-file_search-store-123/documents/my_doc'
});
await ai.fileSearchStores.documents.delete({
name: 'fileSearchStores/my-file_search-store-123/documents/my_doc'
});
REST
curl "https://generativelanguage.googleapis.com/v1beta/fileSearchStores/my-file_search-store-123/documents?key=${GEMINI_API_KEY}"
curl "https://generativelanguage.googleapis.com/v1beta/fileSearchStores/my-file_search-store-123/documents/my_doc?key=${GEMINI_API_KEY}"
curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/fileSearchStores/my-file_search-store-123/documents/my_doc?key=${GEMINI_API_KEY}"
המטא-נתונים של הקבצים
אתם יכולים להוסיף מטא-נתונים מותאמים אישית לקבצים כדי לסנן אותם או לספק הקשר נוסף. מטא-נתונים הם קבוצה של צמדי מפתח/ערך.
Python
op = client.file_search_stores.import_file(
file_search_store_name=file_search_store.name,
file_name=sample_file.name,
custom_metadata=[
{"key": "author", "string_value": "Robert Graves"},
{"key": "year", "numeric_value": 1934}
]
)
JavaScript
let operation = await ai.fileSearchStores.importFile({
fileSearchStoreName: fileSearchStore.name,
fileName: sampleFile.name,
config: {
customMetadata: [
{ key: "author", stringValue: "Robert Graves" },
{ key: "year", numericValue: 1934 }
]
}
});
האפשרות הזו שימושית אם יש לכם כמה מסמכים במאגר של חיפוש קבצים ואתם רוצים לחפש רק בחלק מהם.
Python
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Tell me about the book 'I, Claudius'",
config=types.GenerateContentConfig(
tools=[
types.Tool(
file_search=types.FileSearch(
file_search_store_names=[file_search_store.name],
metadata_filter="author=Robert Graves",
)
)
]
)
)
print(response.text)
JavaScript
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "Tell me about the book 'I, Claudius'",
config: {
tools: [
{
fileSearch: {
fileSearchStoreNames: [fileSearchStore.name],
metadataFilter: 'author="Robert Graves"',
}
}
]
}
});
console.log(response.text);
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${GEMINI_API_KEY}" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[{"text": "Tell me about the book I, Claudius"}]
}],
"tools": [{
"file_search": {
"file_search_store_names":["'$STORE_NAME'"],
"metadata_filter": "author = \"Robert Graves\""
}
}]
}' 2> /dev/null > response.json
cat response.json
הנחיות להטמעת תחביר של מסנני רשימות ל-metadata_filter זמינות בכתובת google.aip.dev/160
ציטוטים ביבליוגרפיים
כשמשתמשים בחיפוש קבצים, התשובה של המודל עשויה לכלול ציטוטים שמציינים אילו חלקים מהמסמכים שהועלו שימשו ליצירת התשובה. המידע הזה עוזר בבדיקת עובדות ובאימות.
אפשר לגשת לפרטי הציטוט דרך מאפיין grounding_metadata של התשובה.
Python
print(response.candidates[0].grounding_metadata)
JavaScript
console.log(JSON.stringify(response.candidates?.[0]?.groundingMetadata, null, 2));
פלט מובנה
החל ממודלים של Gemini 3, אפשר לשלב את הכלי לחיפוש קבצים עם פלט מובנה.
Python
from pydantic import BaseModel, Field
class Money(BaseModel):
amount: str = Field(description="The numerical part of the amount.")
currency: str = Field(description="The currency of amount.")
response = client.models.generate_content(
model="gemini-3-flash-preview",
contents="What is the minimum hourly wage in Tokyo right now?",
config=types.GenerateContentConfig(
tools=[
types.Tool(
file_search=types.FileSearch(
file_search_store_names=[file_search_store.name]
)
)
],
responseMimeType="application/json",
responseJsonSchema= Money.model_json_schema()
)
)
result = Money.model_validate_json(response.text)
print(result)
JavaScript
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
const moneySchema = z.object({
amount: z.string().describe("The numerical part of the amount."),
currency: z.string().describe("The currency of amount."),
});
async function run() {
const response = await ai.models.generateContent({
model: "gemini-3-flash-preview",
contents: "What is the minimum hourly wage in Tokyo right now?",
config: {
tools: [
{
fileSearch: {
fileSearchStoreNames: [file_search_store.name],
},
},
],
responseMimeType: "application/json",
responseJsonSchema: zodToJsonSchema(moneySchema),
},
});
const result = moneySchema.parse(JSON.parse(response.text));
console.log(result);
}
run();
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d "{
\"contents\": [{
\"parts\": [{\"text\": \"What is the minimum hourly wage in Tokyo right now?\"}]
}],
\"tools\": [
{
\"fileSearch\": {
\"fileSearchStoreNames\": [\"$STORE_NAME\"]
}
}
],
\"generationConfig\": {
\"responseMimeType\": \"application/json\",
\"responseJsonSchema\": {
\"type\": \"object\",
\"properties\": {
\"amount\": {\"type\": \"string\", \"description\": \"The numerical part of the amount.\"},
\"currency\": {\"type\": \"string\", \"description\": \"The currency of amount.\"}
},
\"required\": [\"amount\", \"currency\"]
}
}
}"
מודלים נתמכים
המודלים הבאים תומכים בחיפוש קבצים:
gemini-3-pro-previewgemini-3-flash-previewgemini-2.5-pro-
gemini-2.5-flashוגרסאות טרום-השקה (Preview) שלו -
gemini-2.5-flash-liteוגרסאות טרום-השקה (Preview) שלו
סוגי קבצים נתמכים
חיפוש קבצים תומך במגוון רחב של פורמטים של קבצים, שמפורטים בקטעים הבאים.
סוגי קבצים של אפליקציות
application/dartapplication/ecmascriptapplication/jsonapplication/ms-javaapplication/mswordapplication/pdfapplication/sqlapplication/typescriptapplication/vnd.curlapplication/vnd.dartapplication/vnd.ibm.secure-containerapplication/vnd.jupyterapplication/vnd.ms-excelapplication/vnd.oasis.opendocument.textapplication/vnd.openxmlformats-officedocument.presentationml.presentationapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheetapplication/vnd.openxmlformats-officedocument.wordprocessingml.documentapplication/vnd.openxmlformats-officedocument.wordprocessingml.templateapplication/x-cshapplication/x-hwpapplication/x-hwp-v5application/x-latexapplication/x-phpapplication/x-powershellapplication/x-shapplication/x-shellscriptapplication/x-texapplication/x-zshapplication/xmlapplication/zip
סוגים של קובצי טקסט
text/1d-interleaved-parityfectext/REDtext/SGMLtext/cache-manifesttext/calendartext/cqltext/cql-extensiontext/cql-identifiertext/csstext/csvtext/csv-schematext/dnstext/encaprtptext/enrichedtext/exampletext/fhirpathtext/flexfectext/fwdredtext/gff3text/grammar-ref-listtext/hl7v2text/htmltext/javascripttext/jcr-cndtext/jsxtext/markdowntext/mizartext/n3text/parameterstext/parityfectext/phptext/plaintext/provenance-notationtext/prs.fallenstein.rsttext/prs.lines.tagtext/prs.prop.logictext/raptorfectext/rfc822-headerstext/rtftext/rtp-enc-aescm128text/rtploopbacktext/rtxtext/sgmltext/shaclctext/shextext/spdxtext/stringstext/t140text/tab-separated-valuestext/texmacstext/trofftext/tsvtext/tsxtext/turtletext/ulpfectext/uri-listtext/vcardtext/vnd.DMClientScripttext/vnd.IPTC.NITFtext/vnd.IPTC.NewsMLtext/vnd.atext/vnd.abctext/vnd.ascii-arttext/vnd.curltext/vnd.debian.copyrighttext/vnd.dvb.subtitletext/vnd.esmertec.theme-descriptortext/vnd.exchangeabletext/vnd.familysearch.gedcomtext/vnd.ficlab.flttext/vnd.flytext/vnd.fmi.flexstortext/vnd.gmltext/vnd.graphviztext/vnd.hanstext/vnd.hgltext/vnd.in3d.3dmltext/vnd.in3d.spottext/vnd.latex-ztext/vnd.motorola.reflextext/vnd.ms-mediapackagetext/vnd.net2phone.commcenter.commandtext/vnd.radisys.msml-basic-layouttext/vnd.senx.warpscripttext/vnd.sositext/vnd.sun.j2me.app-descriptortext/vnd.trolltech.linguisttext/vnd.wap.sitext/vnd.wap.sltext/vnd.wap.wmltext/vnd.wap.wmlscripttext/vtttext/wgsltext/x-asmtext/x-bibtextext/x-bootext/x-ctext/x-c++hdrtext/x-c++srctext/x-cassandratext/x-chdrtext/x-coffeescripttext/x-componenttext/x-cshtext/x-csharptext/x-csrctext/x-cudatext/x-dtext/x-difftext/x-dsrctext/x-emacs-lisptext/x-erlangtext/x-gff3text/x-gotext/x-haskelltext/x-javatext/x-java-propertiestext/x-java-sourcetext/x-kotlintext/x-lilypondtext/x-lisptext/x-literate-haskelltext/x-luatext/x-moctext/x-objcsrctext/x-pascaltext/x-pcs-gcdtext/x-perltext/x-perl-scripttext/x-pythontext/x-python-scripttext/x-r-markdowntext/x-rsrctext/x-rsttext/x-ruby-scripttext/x-rusttext/x-sasstext/x-scalatext/x-schemetext/x-script.pythontext/x-scsstext/x-setexttext/x-sfvtext/x-shtext/x-siestatext/x-sostext/x-sqltext/x-swifttext/x-tcltext/x-textext/x-vbasictext/x-vcalendartext/xmltext/xml-dtdtext/xml-external-parsed-entitytext/yaml
מגבלות
- API פעיל: חיפוש קבצים לא נתמך בAPI הפעיל.
- אי-תאימות של הכלי: אי אפשר לשלב את חיפוש הקבצים עם כלים אחרים כמו הארקה באמצעות חיפוש Google, הקשר של כתובת URL וכו' בשלב הזה.
מגבלות קצב
כדי לשמור על יציבות השירות, יש מגבלות על File Search API:
- גודל קובץ מקסימלי / מגבלה לכל מסמך: 100MB
- הגודל הכולל של מאגרי חיפוש הקבצים בפרויקט (על סמך רמת המשתמש):
- בחינם: 1GB
- רמה 1: 10GB
- רמה 2: 100GB
- רמה 3: 1TB
- המלצה: כדי להבטיח חביון אופטימלי של אחזור נתונים, כדאי להגביל את הגודל של כל מאגר קבצים לחיפוש ל-20GB.
תמחור
- מפתחים מחויבים על הטמעות בזמן יצירת האינדקס על סמך תמחור ההטמעות הקיים (0.15$ למיליון טוקנים).
- האחסון הוא בחינם.
- הטמעות בזמן השאילתה הן בחינם.
- האסימונים של המסמכים שאוחזרו מחויבים כאסימוני הקשר רגילים.
המאמרים הבאים
- אפשר לעיין במאמרי העזרה של ה-API בנושא חנויות לחיפוש קבצים ומסמכים לחיפוש קבצים.