Penelusuran File

Gemini API memungkinkan Retrieval Augmented Generation ("RAG") melalui alat Penelusuran File. Penelusuran File mengimpor, membagi, dan mengindeks data Anda untuk memungkinkan pengambilan informasi yang relevan dengan cepat berdasarkan perintah yang diberikan. Informasi ini kemudian digunakan sebagai konteks untuk model, sehingga model dapat memberikan jawaban yang lebih akurat dan relevan.

Untuk membuat Penelusuran File sederhana dan terjangkau bagi developer, kami menggratiskan penyimpanan file dan pembuatan embedding pada waktu kueri. Anda hanya membayar pembuatan embedding saat pertama kali mengindeks file (dengan biaya model embedding yang berlaku) dan biaya token input / output model Gemini yang normal. Paradigma penagihan baru ini membuat Alat Penelusuran File lebih mudah dan hemat biaya untuk dibangun dan diskalakan.

Mengupload langsung ke penyimpanan Penelusuran File

Contoh ini menunjukkan cara mengupload file secara langsung ke penyimpanan penelusuran file:

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();

Lihat referensi API untuk uploadToFileSearchStore untuk mengetahui informasi selengkapnya.

Mengimpor file

Atau, Anda dapat mengupload file yang ada dan mengimpornya ke penyimpanan penelusuran file Anda:

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();

Lihat referensi API untuk importFile untuk mengetahui informasi selengkapnya.

Konfigurasi pemotongan

Saat Anda mengimpor file ke penyimpanan Penelusuran File, file tersebut akan otomatis dipecah menjadi beberapa bagian, disematkan, diindeks, dan diupload ke penyimpanan Penelusuran File Anda. Jika Anda membutuhkan kontrol yang lebih besar atas strategi chunking, Anda dapat menentukan setelan chunking_config untuk menetapkan jumlah maksimum token per chunk dan jumlah maksimum token yang tumpang-tindih.

Python

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
          }
        }
    }
)

JavaScript

let operation = await ai.fileSearchStores.uploadToFileSearchStore({
  file: 'file.txt',
  fileSearchStoreName: fileSearchStore.name,
  config: {
    displayName: 'file-name',
    chunkingConfig: {
      whiteSpaceConfig: {
        maxTokensPerChunk: 200,
        maxOverlapTokens: 20
      }
    }
  }
});

Untuk menggunakan penyimpanan Penelusuran File, teruskan sebagai alat ke metode generateContent, seperti yang ditunjukkan dalam contoh Upload dan Impor.

Cara kerjanya

Penelusuran File menggunakan teknik yang disebut penelusuran semantik untuk menemukan informasi yang relevan dengan perintah pengguna. Tidak seperti penelusuran berbasis kata kunci standar, penelusuran semantik memahami makna dan konteks kueri Anda.

Saat Anda mengimpor file, file tersebut akan dikonversi menjadi representasi numerik yang disebut embedding, yang menangkap makna semantik teks. Embedding ini disimpan dalam database Penelusuran File khusus. Saat Anda membuat kueri, kueri tersebut juga dikonversi menjadi embedding. Kemudian, sistem melakukan Penelusuran File untuk menemukan potongan dokumen yang paling mirip dan relevan dari penyimpanan Penelusuran File.

Berikut perincian proses penggunaan File Search uploadToFileSearchStore API:

  1. Membuat penyimpanan Penelusuran File: Penyimpanan Penelusuran File berisi data yang diproses dari file Anda. Ini adalah penampung persisten untuk sematan yang akan dioperasikan oleh penelusuran semantik.

  2. Mengupload file dan mengimpor ke penyimpanan Penelusuran File: Mengupload file dan mengimpor hasilnya ke penyimpanan Penelusuran File secara bersamaan. Tindakan ini akan membuat objek File sementara, yang merupakan referensi ke dokumen mentah Anda. Data tersebut kemudian dibagi-bagi, dikonversi menjadi embedding Penelusuran File, dan diindeks. Objek akan dihapus setelah 48 jam, sedangkan data yang diimpor ke penyimpanan Penelusuran File akan disimpan tanpa batas waktu hingga Anda memilih untuk menghapusnya.File

  3. Kueri dengan Penelusuran File: Terakhir, Anda menggunakan alat FileSearch dalam panggilan generateContent. Dalam konfigurasi alat, Anda menentukan FileSearchRetrievalResource, yang mengarah ke FileSearchStore yang ingin Anda cari. Hal ini memberi tahu model untuk melakukan penelusuran semantik di penyimpanan Penelusuran File tertentu tersebut guna menemukan informasi yang relevan untuk mendasari responsnya.

Proses pengindeksan dan pembuatan kueri Penelusuran File
Proses pengindeksan dan kueri Penelusuran File

Dalam diagram ini, garis putus-putus dari Documents ke Embedding model (menggunakan gemini-embedding-001) merepresentasikan uploadToFileSearchStore API (melewati File storage). Jika tidak, penggunaan Files API untuk membuat dan mengimpor file secara terpisah akan memindahkan proses pengindeksan dari Dokumen ke Penyimpanan file, lalu ke Model sematan.

Penyimpanan Penelusuran File

Penyimpanan Penelusuran File adalah penampung untuk embedding dokumen Anda. Meskipun file mentah yang diupload melalui File API akan dihapus setelah 48 jam, data yang diimpor ke penyimpanan Penelusuran File akan disimpan tanpa batas waktu hingga Anda menghapusnya secara manual. Anda dapat membuat beberapa toko Penelusuran File untuk mengatur dokumen Anda. FileSearchStore API memungkinkan Anda membuat, mencantumkan, mendapatkan, dan menghapus untuk mengelola penyimpanan penelusuran file Anda. Nama toko Penelusuran File memiliki cakupan global.

Berikut beberapa contoh cara mengelola toko Penelusuran File Anda:

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}"

Referensi API File Search Documents untuk metode dan kolom yang terkait dengan pengelolaan dokumen di penyimpanan file Anda.

Metadata file

Anda dapat menambahkan metadata kustom ke file untuk membantu memfilter atau memberikan konteks tambahan. Metadata adalah sekumpulan key-value pair.

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 }
    ]
  }
});

Hal ini berguna jika Anda memiliki beberapa dokumen di penyimpanan Penelusuran File dan ingin menelusuri hanya sebagian dokumen tersebut.

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

Panduan tentang penerapan sintaksis filter daftar untuk metadata_filter dapat ditemukan di google.aip.dev/160

Kutipan

Saat Anda menggunakan Penelusuran File, respons model dapat menyertakan kutipan yang menentukan bagian dokumen yang Anda upload yang digunakan untuk membuat jawaban. Hal ini membantu dalam pengecekan fakta dan verifikasi.

Anda dapat mengakses informasi kutipan melalui atribut grounding_metadata respons.

Python

print(response.candidates[0].grounding_metadata)

JavaScript

console.log(JSON.stringify(response.candidates?.[0]?.groundingMetadata, null, 2));

Model yang didukung

Model berikut mendukung Penelusuran File:

Jenis file yang didukung

Penelusuran File mendukung berbagai format file, yang tercantum di bagian berikut.

Jenis file aplikasi

  • application/dart
  • application/ecmascript
  • application/json
  • application/ms-java
  • application/msword
  • application/pdf
  • application/sql
  • application/typescript
  • application/vnd.curl
  • application/vnd.dart
  • application/vnd.ibm.secure-container
  • application/vnd.jupyter
  • application/vnd.ms-excel
  • application/vnd.oasis.opendocument.text
  • application/vnd.openxmlformats-officedocument.presentationml.presentation
  • application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
  • application/vnd.openxmlformats-officedocument.wordprocessingml.document
  • application/vnd.openxmlformats-officedocument.wordprocessingml.template
  • application/x-csh
  • application/x-hwp
  • application/x-hwp-v5
  • application/x-latex
  • application/x-php
  • application/x-powershell
  • application/x-sh
  • application/x-shellscript
  • application/x-tex
  • application/x-zsh
  • application/xml
  • application/zip

Jenis file teks

  • text/1d-interleaved-parityfec
  • text/RED
  • text/SGML
  • text/cache-manifest
  • text/calendar
  • text/cql
  • text/cql-extension
  • text/cql-identifier
  • text/css
  • text/csv
  • text/csv-schema
  • text/dns
  • text/encaprtp
  • text/enriched
  • text/example
  • text/fhirpath
  • text/flexfec
  • text/fwdred
  • text/gff3
  • text/grammar-ref-list
  • text/hl7v2
  • text/html
  • text/javascript
  • text/jcr-cnd
  • text/jsx
  • text/markdown
  • text/mizar
  • text/n3
  • text/parameters
  • text/parityfec
  • text/php
  • text/plain
  • text/provenance-notation
  • text/prs.fallenstein.rst
  • text/prs.lines.tag
  • text/prs.prop.logic
  • text/raptorfec
  • text/rfc822-headers
  • text/rtf
  • text/rtp-enc-aescm128
  • text/rtploopback
  • text/rtx
  • text/sgml
  • text/shaclc
  • text/shex
  • text/spdx
  • text/strings
  • text/t140
  • text/tab-separated-values
  • text/texmacs
  • text/troff
  • text/tsv
  • text/tsx
  • text/turtle
  • text/ulpfec
  • text/uri-list
  • text/vcard
  • text/vnd.DMClientScript
  • text/vnd.IPTC.NITF
  • text/vnd.IPTC.NewsML
  • text/vnd.a
  • text/vnd.abc
  • text/vnd.ascii-art
  • text/vnd.curl
  • text/vnd.debian.copyright
  • text/vnd.dvb.subtitle
  • text/vnd.esmertec.theme-descriptor
  • text/vnd.exchangeable
  • text/vnd.familysearch.gedcom
  • text/vnd.ficlab.flt
  • text/vnd.fly
  • text/vnd.fmi.flexstor
  • text/vnd.gml
  • text/vnd.graphviz
  • text/vnd.hans
  • text/vnd.hgl
  • text/vnd.in3d.3dml
  • text/vnd.in3d.spot
  • text/vnd.latex-z
  • text/vnd.motorola.reflex
  • text/vnd.ms-mediapackage
  • text/vnd.net2phone.commcenter.command
  • text/vnd.radisys.msml-basic-layout
  • text/vnd.senx.warpscript
  • text/vnd.sosi
  • text/vnd.sun.j2me.app-descriptor
  • text/vnd.trolltech.linguist
  • text/vnd.wap.si
  • text/vnd.wap.sl
  • text/vnd.wap.wml
  • text/vnd.wap.wmlscript
  • text/vtt
  • text/wgsl
  • text/x-asm
  • text/x-bibtex
  • text/x-boo
  • text/x-c
  • text/x-c++hdr
  • text/x-c++src
  • text/x-cassandra
  • text/x-chdr
  • text/x-coffeescript
  • text/x-component
  • text/x-csh
  • text/x-csharp
  • text/x-csrc
  • text/x-cuda
  • text/x-d
  • text/x-diff
  • text/x-dsrc
  • text/x-emacs-lisp
  • text/x-erlang
  • text/x-gff3
  • text/x-go
  • text/x-haskell
  • text/x-java
  • text/x-java-properties
  • text/x-java-source
  • text/x-kotlin
  • text/x-lilypond
  • text/x-lisp
  • text/x-literate-haskell
  • text/x-lua
  • text/x-moc
  • text/x-objcsrc
  • text/x-pascal
  • text/x-pcs-gcd
  • text/x-perl
  • text/x-perl-script
  • text/x-python
  • text/x-python-script
  • text/x-r-markdown
  • text/x-rsrc
  • text/x-rst
  • text/x-ruby-script
  • text/x-rust
  • text/x-sass
  • text/x-scala
  • text/x-scheme
  • text/x-script.python
  • text/x-scss
  • text/x-setext
  • text/x-sfv
  • text/x-sh
  • text/x-siesta
  • text/x-sos
  • text/x-sql
  • text/x-swift
  • text/x-tcl
  • text/x-tex
  • text/x-vbasic
  • text/x-vcalendar
  • text/xml
  • text/xml-dtd
  • text/xml-external-parsed-entity
  • text/yaml

Batas kapasitas

File Search API memiliki batas berikut untuk menerapkan stabilitas layanan:

  • Ukuran file maksimum / batas per dokumen: 100 MB
  • Total ukuran penyimpanan Penelusuran File project (berdasarkan tingkat pengguna):
    • Gratis: 1 GB
    • Tingkat 1: 10 GB
    • Paket 2: 100 GB
    • Tingkat 3: 1 TB
  • Rekomendasi: Batasi ukuran setiap toko Penelusuran File hingga di bawah 20 GB untuk memastikan latensi pengambilan yang optimal.

Harga

  • Developer dikenai biaya untuk penyematan pada waktu pengindeksan berdasarkan harga penyematan yang ada ($0,15 per 1 juta token).
  • Penyimpanan tidak dikenai biaya.
  • Penyematan waktu kueri tidak dikenai biaya.
  • Token dokumen yang diambil akan ditagih sebagai token konteks reguler.

Langkah berikutnya