Gemini API 可透過檔案搜尋工具啟用檢索增強生成 (RAG) 功能。檔案搜尋會匯入、分塊及建立資料索引,以便根據使用者的提示快速擷取相關資訊。接著,這項資訊會做為模型的背景資訊,讓模型提供更準確且相關的答案。
你可以使用 uploadToFileSearchStore API 直接將現有檔案上傳至檔案搜尋商店,或分開上傳及匯入檔案 (如要同時建立檔案)。
直接上傳至檔案搜尋商店
以下範例說明如何直接將檔案上傳至檔案儲存空間:
Python
from google import genai
from google.genai import types
import time
client = genai.Client()
# Create the file search store with an optional display name that shows in the grounding metadata
file_search_store = client.file_search_stores.create(config={'display_name': 'your-fileSearchStore-name'})
# Upload and import a file into the file search store, supply a unique file name which will be visible in citations
operation = client.file_search_stores.upload_to_file_search_store(
file='path/to/your/file.txt',
file_search_store_name='unique_file_name'
)
# Wait until import is complete
while not operation.done:
time.sleep(5)
operation = client.operations.get(operation)
# Ask a question about the file
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""Can you tell me about Robert Graves""",
config=types.GenerateContentConfig(
tools=[
file_search=(
file_search_store_names=[file_search_store.name]
)
]
)
)
print(response.text)
匯入檔案
或者,你也可以上傳現有檔案,然後匯入檔案儲存空間:
Python
from google import genai
from google.genai import types
import time
client = genai.Client()
# Upload the file using the Files API, supply a unique file name which will be visible in citations
sample_file = client.files.upload(file='sample.txt', config={'name': 'unique_file_name'})
# Create the file search store with an optional display name that shows in the grounding metadata
file_search_store = client.file_search_stores.create(config={'display_name': 'your-fileSearchStore-name'})
# Import the file into the file search store
operation = client.file_search_stores.import_file(
file_search_store_name=file_search_store.name,
file_name=sample_file.name
)
# Wait until import is complete
while not operation.done:
time.sleep(5)
operation = client.operations.get(operation)
# Ask a question about the file
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""Can you tell me about Robert Graves""",
config=types.GenerateContentConfig(
tools=[
file_search=(
file_search_store_names=[file_search_store.name]
)
]
)
)
print(response.text)
分塊設定
將檔案匯入檔案搜尋商店時,系統會自動將檔案分成多個區塊、嵌入、建立索引,然後上傳至檔案搜尋商店。如要進一步控管分塊策略,可以指定 chunking_config 設定,為每個分塊設定詞元數量上限,以及重疊詞元數量上限。
# Upload and import and upload the file into the file search store with a custom chunking configuration
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
}
}
}
)
如要使用檔案搜尋商店,請將其做為工具傳遞至 generateContent 方法,如「上傳」和「匯入」範例所示。
運作方式
檔案搜尋功能會使用語意搜尋技術,找出與使用者提示相關的資訊。與傳統的關鍵字搜尋不同,語意搜尋會解讀查詢的意義和脈絡。
匯入檔案時,系統會將檔案轉換為稱為「嵌入」的數值表示形式,擷取文字的語意。這些嵌入內容會儲存在專門的檔案搜尋資料庫中。 查詢時,系統也會將查詢內容轉換為嵌入。接著,系統會執行檔案搜尋,從檔案搜尋商店找出最相似且相關的文件區塊。
以下說明使用 File Search uploadToFileSearchStore API 的程序:
建立檔案搜尋商店:檔案搜尋商店包含檔案中經過處理的資料。這是語意搜尋運作時使用的嵌入項目永久容器。
上傳檔案並匯入檔案搜尋商店:同時上傳檔案並將結果匯入檔案搜尋商店。這會建立暫時的
File物件,也就是原始文件的參照。然後將資料分塊、轉換為檔案搜尋嵌入,並編入索引。File物件會在 48 小時後刪除,而匯入檔案搜尋儲存空間的資料則會無限期儲存,直到您選擇刪除為止。使用檔案搜尋查詢:最後,您會在
generateContent呼叫中使用FileSearch工具。在工具設定中,您會指定FileSearchRetrievalResource,指向要搜尋的FileSearchStore。這會指示模型對該特定檔案搜尋商店執行語意搜尋,找出相關資訊做為回覆的依據。
在此圖表中,從「文件」到「嵌入模型」(使用 gemini-embedding-001) 的虛線代表 uploadToFileSearchStore API (略過「檔案儲存空間」)。否則,使用 Files API 分別建立及匯入檔案,會將索引程序從「文件」移至「檔案儲存空間」,然後移至「嵌入模型」。
檔案搜尋商店
檔案搜尋儲存空間是文件嵌入的容器。透過 File API 上傳的原始檔案會在 48 小時後刪除,但匯入檔案搜尋商店的資料會無限期儲存,直到您手動刪除為止。您可以建立多個檔案搜尋商店來整理文件。您可以使用 FileSearchStore API 建立、列出、取得及刪除檔案,藉此管理檔案搜尋商店。檔案搜尋商店名稱的範圍為全球。
以下舉例說明如何管理檔案搜尋商店:
# Create a file search store (including optional display_name for easier reference)
file_search_store = client.file_search_stores.create(config={'display_name': 'my-file_search-store-123'})
# List all your file search stores
for file_search_store in client.file_search_stores.list():
print(file_search_store)
# Get a specific file search store by name
my_file_search_store = client.file_search_stores.get(name='fileSearchStores/my-file_search-store-123')
# Delete a file search store
client.file_search_stores.delete(name='fileSearchStores/my-file_search-store-123', config={'force': True})
檔案中繼資料
您可以為檔案新增自訂中繼資料,以便篩選檔案或提供額外背景資訊。中繼資料是一組鍵/值組合。
# Import the file into the file search store with custom metadata
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}
]
)
如果檔案搜尋商店中有多份文件,而您只想搜尋其中一部分,這項功能就非常實用。
# Use the metadata filter to search within a subset of documents
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=Robet Graves',
)
)
]
)
)
print(response.text)
如需實作 metadata_filter 清單篩選器語法的指引,請參閱 google.aip.dev/160。
參考資料
使用檔案搜尋功能時,模型的回覆可能會包含引文,指出生成答案時使用了上傳文件的哪些部分。有助於事實查核和驗證。
您可以透過回應的 grounding_metadata 屬性存取引文資訊。
print(response.candidates[0].grounding_metadata)
支援的模型
下列模型支援檔案搜尋:
支援的檔案類型
檔案搜尋支援多種檔案格式,詳列於下列各節。
應用程式檔案類型
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
頻率限制
為確保服務穩定性,File Search API 設有下列限制:
- 檔案大小上限 / 每份文件限制:100 MB
- 每個專案的檔案搜尋儲存次數:10
- 專案檔案搜尋商店的總大小 (依使用者層級而定):
- 免費:1 GB
- 第 1 級:10 GB
- 第 2 級:100 GB
- 第 3 級:1 TB
- 建議:將每個檔案搜尋商店的大小限制在 20 GB 以下,確保最佳的擷取延遲時間。