Ir para o conteúdo

Lição 14 · Embeddings and Retrieval

Vector Stores and File Search

Use hosted OpenAI vector stores: upload files, search them, filter by attributes, tune chunking, use the file_search tool and read file citations.

In embeddings you saw the parts of a search system: chunk, embed, store and compare. A vector store is OpenAI's hosted version of that system. When you add a file, the service splits it into chunks, embeds them and indexes them. You can then search it yourself, or let a model search it with the file search tool.

This saves infrastructure work. In exchange, your documents are stored with OpenAI, and you have less control over each step.

Create a store and add a file

Python
# Read-only
store = client.vector_stores.create(name="help-center")

uploaded = client.vector_stores.files.upload_and_poll(
    vector_store_id=store.id,
    file=open("refund-policy.pdf", "rb"),
)
print(uploaded.status)

Adding a file is asynchronous: processing takes time. The helper above waits until it finishes. Check the final status, because a file can fail. For larger sets, there are file batch operations.

You can also upload a file with the Files API first and then attach it to a store. OpenAI's file search guide shows this path.

Search the store yourself

Python
# Read-only
results = client.vector_stores.search(
    vector_store_id=store.id,
    query="How long do I have to return an item?",
    max_num_results=5,
)

for hit in results.data:
    print(hit.filename, round(hit.score, 3))

As of December 2026, the retrieval guide says a search returns up to 10 results by default, and max_num_results can raise this to 50. Options let you rewrite the query (rewrite_query) and adjust ranking, for example a score threshold or the balance between embedding and keyword matching.

The file search tool runs the search during a response.

Python
# Read-only
response = client.responses.create(
    model="gpt-6.2-sol",
    input="How long do I have to return an item?",
    tools=[{"type": "file_search",
            "vector_store_ids": [store.id],
            "max_num_results": 5}],
    include=["file_search_call.results"],
)
print(response.output_text)

By default, the search results are not included in the response. The include setting adds them, which is useful for debugging. The text of the answer can carry file_citation annotations with a file_id and filename. Show these to users and let them open the source.

A citation tells you which file was used. It does not prove that the sentence is a faithful summary of that file.

Attributes and filters

You can attach attributes (metadata) to files and filter searches by them. For example, store the product, language and year.

Python
# Read-only
tools=[{
    "type": "file_search",
    "vector_store_ids": [store.id],
    "filters": {"type": "eq", "key": "language", "value": "en"},
}]

Comparison operators include eq, ne, gt, gte, lt, lte, in and nin, and you can combine filters with and and or. A file can have up to 16 attributes.

Filters are useful for access control too, but the safest design for separate customers is often separate stores. Your server must build the filter or choose the store from the signed-in user. Never let the model or the browser choose it freely.

Practice filtering

This stand-in mimics a filter on hand-made metadata. It is a simplified imitation, not the service's filter engine.

Python Stand-in: filter files by attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The old English file is excluded. Without such a filter, a search might find an outdated policy and the model might quote it confidently.

Chunking, limits and cost

The retrieval guide lists these facts as of December 2026:

  • Default chunking uses 800-token chunks with 400 tokens of overlap. You can change both; chunk size must be 100 to 4,096 tokens and the overlap at most half of it.
  • A file can be up to 512 MB and 5,000,000 tokens.
  • Storage is free up to 1 GB across vector stores, then $0.10 per GB per day.
  • The pricing page lists file search tool calls at $2.50 per 1,000 calls in the Responses API.

Check the pages again before you plan a budget.

Manage the lifecycle

Storage can quietly cost money and keep data longer than you intended.

  • Keep a record of each store and file: owner, source, version and upload date.
  • Delete old versions when a document changes.
  • Set expires_after (for example, days since last activity) on temporary stores.
  • Remember that removal can take a short while to take effect in search.
  • Delete both the store entry and the uploaded file if you need the data gone. Check the data controls page.

Hosted or self-built?

Hosted vector store Your own database
Fast to start Full control of chunking and ranking
Little infrastructure Data stays where you choose
Fees for storage and calls Your own running costs and maintenance
Tied to this service Can serve several model providers

Documents can contain hidden instructions that try to steer the model. Only add files from sources you trust, and do not give a search-based assistant powerful tools without approval steps.

When search results are poor

First, search the store directly and read the returned chunks. This separates retrieval problems from answer problems. If the right file never appears, check that it finished processing, that your filter is not excluding it, and that the document really contains the answer as text. A scanned page or a chart may not give useful text. If the right file appears but the wrong passage ranks first, look at the document structure: long mixed sections and repeated boilerplate often confuse search. Splitting or cleaning the source can help more than changing settings.

Change one thing at a time, such as chunk size, and measure it on the same questions. Keep a small list of questions with the expected file for each, and run it after every change to your documents.

Also test questions that your files cannot answer. The assistant should say so rather than stretch a weak match into an answer, and your instructions should tell it to.

Common mistakes

  • Searching right after an upload without waiting for processing to finish.
  • Keeping every old version of a document in the same store with no date or version attribute.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What happens when you add a file to a vector store?

    The service prepares the file for search. It does not train a model on it as part of this step.
  2. 2. How do you get the raw search results in a file search response?

    Results are not included by default.
  3. 3. Who should decide which store or filter applies to a user?

    Access decisions must come from trusted code.
  4. 4. Why set an expiry on temporary stores?

    Forgotten stores keep costing money and keep data around.

Summary

  • Vector stores handle chunking, embedding and indexing for you.
  • Search them directly or use the file_search tool and show citations.
  • Use attributes and filters, with access decisions made on your server.
  • Watch storage limits, fees and old versions.
  • Treat document content as untrusted.

Next: Images and Files as Input

Seu progresso fica salvo neste navegador. Não precisa de conta.