Lección 13 · 5 min · Gratis

Búsqueda de archivos con Gemini

Copyright 2026 Google LLC.
# @title Licensed under the Apache License, Version 2.0 (the "License");
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

La herramienta File Search te permite crear potentes aplicaciones de generación aumentada por recuperación (RAG) usando Gemini. Te permite subir documentos a un almacén gestionado y luego usarlos como herramienta durante la generación del modelo, lo que permite a Gemini responder preguntas basándose en tus datos específicos con citas precisas.

En esta guía rápida, aprenderás a:

  • Crear un File Search Store.
  • Subir documentos al almacén.
  • Usar el almacén como herramienta en interactions.create.
  • Citar las fuentes usadas durante la generación.
  • Filtrar los resultados de búsqueda usando metadatos personalizados.
  • Gestionar tus documentos y almacenes.

Para obtener información sobre cómo funciona el precio de File Search, incluyendo detalles sobre lo que está disponible de forma gratuita, consulta la información de precios.

Nota: Este notebook usa la API de Interacciones, la forma más reciente de interactuar con los modelos Gemini. ¿Buscas la versión generateContent? Consulta la rama de archivo.

Instalar dependencias

Primero, instala el SDK de Google Gen AI.

# SDK 1.75.0 has latest multimodal File Search features
%pip install -U -q "google-genai>=2.9.0"  # 1.75+ for Interactions API + File Search

Autenticación

Importante: La API de File Search usa claves de API para la autenticación y el acceso. Los archivos subidos se asocian con el proyecto en la nube de la clave de API. A diferencia de otras API de Gemini que usan claves de API, tu clave de API también otorga acceso a todos los datos que has subido a los almacenes de archivos, así que ten especial cuidado en mantener tu clave de API segura. Para conocer las mejores prácticas sobre cómo proteger las claves de API, consulta la documentación de Google.

Configura tu clave de API

Para ejecutar la siguiente celda, tu clave de API debe estar almacenada en un Secreto de Colab llamado GEMINI_API_KEY. Si aún no tienes una clave de API, o no estás seguro de cómo crear un Secreto de Colab, consulta Autenticación para ver un tutorial.

from google import genai
from google.colab import userdata
from google.genai import types

GEMINI_API_KEY = userdata.get("GEMINI_API_KEY")
client = genai.Client(api_key=GEMINI_API_KEY)

Búsqueda básica de archivos

En esta sección, descargarás un documento de ejemplo, crearás un File Search Store y lo usarás para responder preguntas.

Crear un File Search Store

Crea un nuevo File Search Store para guardar tus documentos.

file_search_store = client.file_search_stores.create(
    config=types.CreateFileSearchStoreConfig(
        display_name='My File Search Store'
    )
)

print(f"Created store: {file_search_store.name}")
Created store: fileSearchStores/my-file-search-store-zl14xbhbfu41

Descargar un documento de ejemplo

Descarga "A Survey of Modernist Poetry" de Project Gutenberg como un archivo de texto de ejemplo.

!wget -q https://www.gutenberg.org/cache/epub/76401/pg76401.txt -O sample_poetry.txt
!head sample_poetry.txt

Subir un archivo al almacén

Sube el archivo de texto directamente al almacén. El proceso de ingesta incluye cierto procesamiento, por lo que debes esperar a que se complete antes de poder buscar.

import time

upload_op = client.file_search_stores.upload_to_file_search_store(
    file_search_store_name=file_search_store.name,
    file='sample_poetry.txt',
    config=types.UploadToFileSearchStoreConfig(
        display_name='A Survey of Modernist Poetry',
    )
)

print(f"Upload started: {upload_op.name}")


while not (upload_op := client.operations.get(upload_op)).done:
    time.sleep(1)
    print(".", end="")

print()
print("Processing complete.")
Upload started: fileSearchStores/my-file-search-store-zl14xbhbfu41/upload/operations/a-survey-of-modernist-poetr-pahgkrfkxior
...................................................................................................................................................................
Processing complete.

Alternativa: Importar desde la API de archivos

Si ya has subido documentos a la API de archivos, puedes importarlos directamente a un File Store. Esto puede ser útil si un usuario ya ha realizado alguna interacción con un archivo, como generar un resumen, y ha aprobado el archivo para su uso en un almacén.

file_ref = client.files.upload(
    file='sample_poetry.txt',
    config=types.UploadFileConfig(
        display_name='A Survey of Modernist Poetry',
        mime_type='text/plain',
    )
)
print(f"Uploaded via File API: {file_ref.name}")

import_op = client.file_search_stores.import_file(
    file_search_store_name=file_search_store.name,
    file_name=file_ref.name,
)

print(f"File import started: {import_op.name}")

while not (import_op := client.operations.get(import_op)).done:
    time.sleep(1)
    print(".", end="")

print()
print("Processing complete.")
Uploaded via File API: files/d9jsb1hxh364
File import started: fileSearchStores/my-file-search-store-zl14xbhbfu41/operations/d9jsb1hxh364-340ginvi1as3
......
Processing complete.

Generar contenido con File Search

Ahora, usa la herramienta file_search en una solicitud interactions.create para hacer una pregunta que requiera información del documento subido.

MODEL_ID = "gemini-3.7-flash" # @param ["gemini-3.1-pro-preview", "gemini-3.7-flash", "gemini-3.5-flash-lite", "gemini-2.5-pro"] {"allow-input":true, isTemplate: true}
interaction = client.interactions.create(
    model=MODEL_ID,
    input='What does the text say about E.E. Cummings?',
    tools=[{"type": "file_search", "file_search_store_names": [file_search_store.name]}],
)

print(interaction.steps[-1].content[0].text)
The text discusses E.E. Cummings as a significant and challenging modernist poet whose work requires readers to adopt a new critical attitude. According to the documents, particularly *A Survey of Modernist Poetry*, the following points are made about him:

### **1. Relationship with the Reader**
*   **Demanding Style:** Cummings is described as a poet who uses "exceptional means" to force readers to move beyond "lazy reading habits" and common intelligence. His poetry demands a "vigorous imaginative effort" that the average reader may be unwilling to apply.
*   **Lack of Obligation:** Unlike some earlier modernists who aimed for simplicity for the sake of the "plain reader," Cummings represents a modernism that feels no obligation to the average reader, focusing instead on the interests of poetry itself.
*   **Critical Hostility:** His work often excites hostility. Even critics like Louis Untermeyer, who included Cummings in his *Anthology of Modern American Poetry*, are described as being "personally hostile" to his work but were compelled by "advanced critical opinion" to recognize him.

### **2. Stylistic Innovations**
The text highlights several of Cummings' signature idiosyncrasies:
*   **Use of lowercase "i":** Cummings famously used the lowercase "i" instead of "I." The text explains this as a protest against the "upper case" being used for the self. It suggests he did this to affect "casualness" and "humility," and to dissociate the author from the speaker of the poem.
*   **Capitalization and Punctuation:** He refused the convention of starting every line with a capital letter, viewing it as an unnecessary and ancient habit.
*   **Personification:** The text notes his tendency to give personal qualities to objects, such as using the relative pronoun "who" instead of "which" when referring to roses.
*   **Visual Layout:** His "innovations" are seen as a way of "inventing a new kind of poem" where the visual and structural layout are integral to the meaning.

### **3. Historical Significance**
The text argues that Cummings must be accepted not just for his individual poems, but for his **lasting effect on the future of reading**. His work challenges the depth of a reader's understanding of all poetry, including classics like Shakespeare, by pushing the boundaries of what poetry can be.

Campos adicionales

La herramienta FileSearch ofrece algunas opciones para configurar cómo funciona la herramienta, top_k y metadata_filter.

top_k controla cuántos fragmentos se devolverán de la herramienta de búsqueda y se pasarán al paso de generación. Este es el mismo ejemplo de antes, pero solo se usará 1 fragmento para generar la respuesta. Este control puede ser útil para guiar al modelo si sabes que solo hay un fragmento correcto a considerar (k=1), o si esperas que los fragmentos tengan más superposición y quieres incluir más contexto (un top_k más alto).

El filtrado de metadatos se describe en la siguiente sección, y puedes encontrar la especificación completa en la referencia de la API.

top_K = 1 # @param {"allow-input":true, isTemplate: true}

interaction = client.interactions.create(
    model=MODEL_ID,
    input='What does the text say about E.E. Cummings?',
    tools=[{"type": "file_search", "file_search_store_names": [file_search_store.name], "top_k": top_K}],
)

print(interaction.steps[-1].content[0].text)
Based on the text, E.E. Cummings is presented as a modern poet whose work requires a significant shift in critical attitude and a "vigorous imaginative effort" from the reader. The text characterizes his poetry and its reception in several ways:

### **Critical Perspective and Innovations**
*   **A "New Kind of Poem":** Cummings is described as a poet who uses "exceptional means" and has essentially invented a "new kind of poem" to force readers to do justice to his work, rather than indulging "lazy reading habits" fostered by simple anthologies.
*   **Influence on Reading:** Even if not accepted for his own sake, the text argues that he must be accepted for his impact on how poetry—regardless of age or style—will be read in the future.
*   **Modernism:** His work represents a form of modernism that feels no obligation to the "plain reader." This contrasts with the modernism of earlier movements like Imagism, which sought simplicity and everyday language. Cummings’ modernism is instead "undertaken... in the interests of poetry."

### **Analysis of the Poem "SUNSET"**
The text provides a detailed analysis of Cummings' poem **"SUNSET"** to illustrate his style and the demands he places on the reader:
*   **Avoidance of "Stale Phrases":** Cummings avoids clichés like "vesper wind," "silver seas," or "salt air." Instead, he uses evocative, single words to build these associations. For example, "stinging," "sea," and "wind" combine to suggest "salt air" without explicitly naming it.
*   **Sensory and Emotional Associations:**
    *   **"Stinging":** Prepares the reader and provides an emotional source for the subsequent "s" sounds.
    *   **"Gold swarms":** Suggests golden bees and a softening "buzzing" sound through alliteration.
    *   **"Silver":** Acts as a contrast to the warmth of gold, suggesting the coldness of water.
    *   **"Sea" and "Sun":** These are described as "suppressed" words that play behind the scenes of the poem’s imagery before the "sea" eventually becomes a central image.
*   **Catholic Symbolism:** The text notes that words like "monks," "spires," and "litanies" are bound up with Catholic symbolism, specifically the "rose" idea.
*   **Reader Participation:** Cummings "disdains" giving hints that the poem is not to be taken literally (e.g., calling it "imaginary"). He leaves connections—such as the link between "bells and waves"—for the reader to deduce on their own.

### **Relationship with Critics**
*   **Louis Untermeyer:** The text mentions that Cummings' work appeared in Untermeyer’s *Anthology of Modern American Poetry*. However, it notes that Untermeyer seemed "personally hostile" to Cummings’ work and only included it due to the pressure of advanced critical opinion. This highlights the "hostility" Cummings' work often excited due to its departure from traditional simplicity.

Inspeccionar metadatos de fundamentación y números de página

La respuesta incluye grounding_metadata que contiene citas y referencias al documento fuente. Los fragmentos del documento usados en el contexto de generación están disponibles en grounding_metadata.grounding_chunks, y se ven así.

Cada fragmento también incluye un campo page_number, que te indica la página exacta del documento fuente de donde proviene el fragmento. Esto es especialmente útil para la verificación de hechos y la comprobación en documentos grandes.

[
  GroundingChunk(
    retrieved_context=GroundingChunkRetrievedContext(
      text="""(the snippet of text contained in this chunk)""",
      title='(the title of the document)',
      page_number=5
    )
  ), ...
]
import textwrap

# Note: Grounding metadata with detailed chunk information is not yet
# available in the Interactions API. Use generate_content API for grounding
print("File Search grounding metadata not yet available in Interactions API")
print("The response text is available via interaction.steps[-1].content[0].text")
File Search grounding metadata not yet available in Interactions API
The response text is available via interaction.steps[-1].content[0].text

Además, grounding_metadata incluye grounding_supports que proporcionan referencias del texto de la respuesta a los documentos de apoyo, y se pueden usar para proporcionar anotaciones.

Los soportes se ven así.

[
  GroundingSupport(
    grounding_chunk_indices=[
      0,  # The index in `grounding_chunks` to which this corresponds
    ],
    segment=Segment(
      start_index=123,  # Indices into the generated text
      end_index=456,
      text='(the span of generated text being supported)'
    )
  ), ...
]
from IPython.display import Markdown, display

# Annotated response display requires grounding metadata.
print("Annotated response display requires grounding metadata (not yet in Interactions API)")
Annotated response display requires grounding metadata (not yet in Interactions API)

Filtrado de metadatos

Al añadir documentos, puedes adjuntar metadatos personalizados a tus archivos y usarlos para filtrar los resultados de búsqueda.

Subir un archivo con metadatos

Descarga otro libro, "Las aventuras de Alicia en el País de las Maravillas", y súbelo con información sobre el género y el autor.

!wget -q https://www.gutenberg.org/files/11/11-0.txt -O alice_in_wonderland.txt
!head alice_in_wonderland.txt
upload_op = client.file_search_stores.upload_to_file_search_store(
    file_search_store_name=file_search_store.name,
    file='alice_in_wonderland.txt',
    config=types.UploadToFileSearchStoreConfig(
        display_name='Alice in Wonderland',
        custom_metadata=[
            types.CustomMetadata(key='genre', string_value='fiction'),
            types.CustomMetadata(key='author', string_value='Lewis Carroll'),
        ]
    )
)

while not (upload_op := client.operations.get(upload_op)).done:
    time.sleep(1)
    print(".", end="")

print()
print("Upload complete.")
..
Upload complete.

Los metadatos personalizados se pueden proporcionar como tipos string_value, numeric_value o string_list_value.

types.CustomMetadata.model_fields.keys() - {'key'}

Consultar con filtro de metadatos

Ahora, haz una pregunta que podría aplicarse a cualquiera de los dos libros, pero usa un filtro para restringirla a solo uno. Por ejemplo, pregunta sobre una "Reina" pero filtra por "ficción".

interaction = client.interactions.create(
    model=MODEL_ID,
    input='Who is the Queen?',
    tools=[{"type": "file_search", "file_search_store_names": [file_search_store.name], "metadata_filter": 'genre = "fiction"'}],
)

print(interaction.steps[-1].content[0].text)
The term "the Queen" can refer to several different figures depending on the context:

### 1. **Queen Camilla (United Kingdom and Commonwealth)**
As of 2026, the most prominent figure with this title is **Queen Camilla**. She is the wife of King Charles III. 
*   **Status:** She became **Queen Consort** upon accession of King Charles III on September 8, 2022, following the death of Queen Elizabeth II.
*   **Title:** Since the Coronation on May 6, 2023, she has been officially styled as **Queen Camilla**.

### 2. **Queen Elizabeth II (Historical context)**
For many, "the Queen" still refers to **Queen Elizabeth II**, who reigned for 70 years from 1952 until 2022. She was a **Queen Regnant**, meaning she reigned in her own right with full sovereign powers. Her long reign made her the most recognized "Queen" globally for decades.

### 3. **Other Current Queens (Consorts)**
Currently, there are no **Queens Regnant** (female monarchs who rule in their own right) in the world. However, there are several **Queens Consort** (wives of reigning Kings), including:
*   **Queen Mary** of Denmark (wife of King Frederik X)
*   **Queen Máxima** of the Netherlands (wife of King Willem-Alexander)
*   **Queen Letizia** of Spain (wife of King Felipe VI)
*   **Queen Mathilde** of Belgium (wife of King Philippe)
*   **Queen Silvia** of Sweden (wife of King Carl XVI Gustaf)

### 4. **Fictional Context (e.g., *Alice in Wonderland*)**
If you are asking in the context of literature, specifically Lewis Carroll's ***Alice's Adventures in Wonderland***, "the Queen" refers to the **Queen of Hearts**. She is a primary antagonist known for her favorite command, "Off with their heads!" and her volatile temper during the game of croquet.

**Summary:** In a modern political context, "the Queen" refers to **Queen Camilla** of the United Kingdom. In a historical context, it usually refers to **Queen Elizabeth II**.

Para obtener más información sobre cómo construir filtros complejos, lee la especificación AIP-160.

Búsqueda multimodal de archivos

Con la búsqueda multimodal de archivos, puedes incrustar y buscar de forma nativa tanto documentos como imágenes. Al usar el modelo de incrustación gemini-embedding-2, las imágenes se incrustan directamente (no a través de OCR), lo que permite una verdadera recuperación visual.

En esta sección, crearás un File Search Store multimodal, subirás imágenes, las consultarás con Gemini y recuperarás citas de medios.

Crear un File Search Store multimodal

Para habilitar la búsqueda multimodal, especifica gemini-embedding-2 como el embedding_model al crear un almacén. Si se omite, el almacén por defecto es gemini-embedding-001, que está optimizado para cargas de trabajo solo de texto.

Modelo de incrustación Mejor para
gemini-embedding-001 (por defecto) Cargas de trabajo con mucho texto, optimizado para costos
gemini-embedding-2 Recuperación multimodal (texto e imágenes)
mm_file_search_store = client.file_search_stores.create(
    config=types.CreateFileSearchStoreConfig(
        display_name='Multimodal Store',
        embedding_model='models/gemini-embedding-2'
    )
)

print(f"Created multimodal store: {mm_file_search_store.name}")
Created multimodal store: fileSearchStores/multimodal-store-qxos6g9bw4dx

Subir imágenes

Sube archivos al almacén usando upload_to_file_search_store. Con gemini-embedding-2, esto funciona tanto para documentos como para imágenes (PNG, JPEG). Las imágenes dentro de los PDF también se incrustan de forma nativa junto con el texto.

from IPython.display import Image, display

# Download a sample image
!curl -so sample_image.jpg "https://storage.googleapis.com/generativeai-downloads/images/jetpack.jpg"

display(Image("sample_image.jpg", width=300))
n execute_notebook
    result = exec(compile(prepared, f"{name}:cell_{i}", 'exec'), ns)
                  ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "File_Search.ipynb:cell_39", line 4
    os.system("""curl -so sample_image.jpg "https://storage.googleapis.com/generativeai-downloads/images/jetpack.jpg"""")
                                                                                                                       ^
SyntaxError: unterminated string literal (detected at line 4)
# Upload the image to the multimodal store
upload_op = client.file_search_stores.upload_to_file_search_store(
    file_search_store_name=mm_file_search_store.name,
    file='sample_image.jpg',
    config=types.UploadToFileSearchStoreConfig(
        display_name='Jetpack Image',
    )
)

print(f"Upload started: {upload_op.name}")

while not (upload_op := client.operations.get(upload_op)).done:
    time.sleep(1)
    print(".", end="")

print()
print("Processing complete.")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        user_mime_type=user_config_dict.get('mime_type'),
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/usr/local/google/home/giom/.gemini/jetski/scratch/cookbook-agentB-interactions/.venv/lib/python3.13/site-packages/google/genai/_extra_utils.py", line 642, in prepare_resumable_upload
    raise FileNotFoundError(f'{file} is not a valid file path.')
FileNotFoundError: sample_image.jpg is not a valid file path.

Consultar con la búsqueda multimodal de archivos

Usa la herramienta file_search para consultar el almacén multimodal. El modelo realiza una búsqueda semántica sobre datos de texto e imagen para generar una respuesta fundamentada.

interaction = client.interactions.create(
    model=MODEL_ID,
    input='Describe what is in the image stored in the file search store.',
    tools=[{"type": "file_search", "file_search_store_names": [mm_file_search_store.name]}],
)

print(interaction.steps[-1].content[0].text)
actions/.venv/lib/python3.13/site-packages/google/genai/_interactions/_base_client.py", line 1080, in request
    raise self._make_status_error_from_response(err.response) from None
google.genai._interactions.BadRequestError: Error code: 400 - {'error': {'message': 'Model generated too many tool calls. Please retry the request. If the issue persists, include this error message in the retry prompt to allow the model to call a valid number of tools.', 'code': 'Model generated function call(s).'}}

Recuperar citas de medios y números de página

Cuando el modelo hace referencia a un fragmento de imagen, los metadatos de fundamentación incluyen un campo media_id. Puedes usar esto para descargar la imagen exacta que el modelo usó para su respuesta.

Para las citas de texto, los metadatos también incluyen un campo page_number, que te indica la página exacta del documento fuente de donde proviene el fragmento. Esto es especialmente útil para la verificación de hechos y la comprobación en documentos grandes.

# Grounding metadata for file search is not yet available in the Interactions API.
print("Grounding metadata not yet available in Interactions API")
Grounding metadata not yet available in Interactions API

Gestionar documentos

También puedes gestionar documentos individuales dentro de un almacén.

Listar documentos

Lista todos los documentos que se encuentran actualmente en el almacén.

print(f"Documents in {file_search_store.name}:")

for doc in client.file_search_stores.documents.list(parent=file_search_store.name):
    print(f"- {doc.display_name} ({doc.name})")
Documents in fileSearchStores/my-file-search-store-zl14xbhbfu41:
- A Survey of Modernist Poetry (fileSearchStores/my-file-search-store-zl14xbhbfu41/documents/a-survey-of-modernist-poetr-pahgkrfkxior)
- d9jsb1hxh364 (fileSearchStores/my-file-search-store-zl14xbhbfu41/documents/d9jsb1hxh364-340ginvi1as3)
- Alice in Wonderland (fileSearchStores/my-file-search-store-zl14xbhbfu41/documents/alice-in-wonderland-tz6xws9klm4r)

Obtener un documento

Recupera los detalles de un documento específico, como su estado de procesamiento o metadatos.

# Get a document by ID
doc_id = doc.name  # Or set a specific ID here.
sample_doc = client.file_search_stores.documents.get(name=doc_id)

if sample_doc:
    print(f"Document details for {sample_doc.display_name}:")
    print(f"  Name: {sample_doc.name}")
    print(f"  Custom Metadata: {sample_doc.custom_metadata}")
Document details for Alice in Wonderland:
  Name: fileSearchStores/my-file-search-store-zl14xbhbfu41/documents/alice-in-wonderland-tz6xws9klm4r
  Custom Metadata: [CustomMetadata(
  key='genre',
  string_value='fiction'
), CustomMetadata(
  key='author',
  string_value='Lewis Carroll'
)]

Eliminar un documento

Elimina un documento específico del almacén sin borrar todo el almacén.

# Delete a specific document.
doc_to_be_deleted = doc_id

client.file_search_stores.documents.delete(
    name=doc_to_be_deleted,
    config=types.DeleteDocumentConfig(
        # Set force to delete a non-empty document.
        force=True
    )
)
print(f"Deleted document: {doc_to_be_deleted}")

# Verify deletion
print("\nRemaining documents:")
for doc in client.file_search_stores.documents.list(parent=file_search_store.name):
    print(f"- {doc.display_name}")
Deleted document: fileSearchStores/my-file-search-store-zl14xbhbfu41/documents/alice-in-wonderland-tz6xws9klm4r

Remaining documents:
- A Survey of Modernist Poetry
- d9jsb1hxh364

Gestionar File Search Stores

Puedes listar, obtener y eliminar tus File Search Stores.

print("Stores:")

for store in client.file_search_stores.list():
    print(f"- {store.name} ({store.display_name})")
Stores:
- fileSearchStores/linkedinlivedemo-kz1t09dt27ty (linkedin_live_demo)
- fileSearchStores/myexamplestore-t0kby8lqatxp (my_example_store)
- fileSearchStores/linkedinlivedemostore-0hk474x2klnn (linkedin_live_demo_store)
- fileSearchStores/myexamplestore-ewfrht3ddbr9 (my_example_store)
- fileSearchStores/linkedinlivedemostore-p5zvredysq71 (linkedin_live_demo_store)
- fileSearchStores/myexamplestore-mvryze3utwrl (my_example_store)
- fileSearchStores/linkedinlivedemostore-76txfj2jemza (linkedin_live_demo_store)
- fileSearchStores/yourfilesearchstorename-kkntkxscsa22 (your-fileSearchStore-name)
- fileSearchStores/yourfilesearchstorename-hr6xgqu0ge6v (your-fileSearchStore-name)
- fileSearchStores/yourfilesearchstorename-u61bp32tqnpj (your-fileSearchStore-name)
- fileSearchStores/yourfilesearchstorename-2miaspfrlcwi (your-fileSearchStore-name)
- fileSearchStores/yourfilesearchstorename-jlma4n6bygmz (your-fileSearchStore-name)
- fileSearchStores/yourfilesearchstorename-rantys2z0h2s (your-fileSearchStore-name)
- fileSearchStores/yourfilesearchstorename-rvx2de45gkpe (your-fileSearchStore-name)
- fileSearchStores/yourfilesearchstorename-fcn7lyn91mjc (your-fileSearchStore-name)
- fileSearchStores/aisdkindex-vcypy3ifaray (AI_SDK_Index)
- fileSearchStores/teststore-f2vcc3c8yv31 (test_store)
- fileSearch/teststore2-ra447ez94hc5 (test_store_2)
- fileSearchStores/aisdkindex-7x8y8a1g8to0 (AI_SDK_Index)
- fileSearchStores/devbisectstore-7rne8qa4ybmp (dev_bisect_store)
- fileSearchStores/myfilesearchstore-i2o4ge9a4jjl (MyFileSearchStore)
- fileSearchStores/project-gutenberg-collectio-xx0r134b2unm (Project Gutenberg Collection)
- fileSearchStores/chatsession1776770881253-kyvzlustf2ge (chat-session-1776770881253)
- fileSearchStores/chatsession1776787757144-bgbtrafsv8pu (chat-session-1776787757144)
- fileSearchStores/yourfilesearchstorename-sa18yn9eqxj3 (your-fileSearchStore-name)
- fileSearchStores/multimodal-catalog-from-ai--d6zydlij0psg (Multimodal Catalog from AI Studio App)
- fileSearchStores/myfilesearchstore1-btmlu1ytfbp0 (my-file-search-store1)
- fileSearchStores/myfilesearchstore1-w19wiuzy9dgf (my-file-search-store1)
- fileSearchStores/multimodal-store-4st3tgk6j2lz (Multimodal Store)
- fileSearchStores/deleteme-wornot6kzhzh (deleteme)
- fileSearchStores/my-file-search-store-v4lzv0eupi5p (My File Search Store)
- fileSearchStores/yourfilesearchstorename-kge8av83rt0z (your-fileSearchStore-name)
- fileSearchStores/yourfilesearchstorename-9qvx4lz3orxn (your-fileSearchStore-name)
- fileSearchStores/yourfilesearchstorename-bk6azq4xxiq2 (your-fileSearchStore-name)
- fileSearchStores/jetski-test-store-2-gql45p56illy (Jetski Test Store 2)
- fileSearchStores/my-file-search-store-av72wjfwj28p (My File Search Store)
- fileSearchStores/my-file-search-store-9qoiqbya8za3 (My File Search Store)
- fileSearchStores/my-file-search-store-28hudeinm7iy (My File Search Store)
- fileSearchStores/my-file-search-store-ey6ri8m4z3so (My File Search Store)
- fileSearchStores/my-file-search-store-zl14xbhbfu41 (My File Search Store)
- fileSearchStores/my-file-search-store-v5kyvdzn4hdh (My File Search Store)
- fileSearchStores/multimodal-store-qxos6g9bw4dx (Multimodal Store)

Limpieza

Es una buena práctica eliminar los File Search Stores cuando hayas terminado de usarlos para evitar costos de almacenamiento innecesarios.

client.file_search_stores.delete(name=file_search_store.name, config=types.DeleteFileSearchStoreConfig(force=True))
print(f"Deleted store: {file_search_store.name}")

client.file_search_stores.delete(name=mm_file_search_store.name, config=types.DeleteFileSearchStoreConfig(force=True))
print(f"Deleted store: {mm_file_search_store.name}")
Deleted store: fileSearchStores/my-file-search-store-zl14xbhbfu41
Deleted store: fileSearchStores/multimodal-store-qxos6g9bw4dx

¿Qué sigue?

Para obtener más información sobre la herramienta File Search, asegúrate de consultar estos recursos.

Lección del curso «Gemini API Cookbook (quickstarts)» de Google, publicado con licencia Apache 2.0. Traducción y adaptación al español de IA con Clase. IA con Clase no está afiliado a Google. Ver el original · Licencia
Esta lección es gratuita. El resto del curso se abre con la Membresía de IA con Clase, que incluye todos los cursos del catálogo. Ver precios