Sub topic 12
Tuning retrieval: result limits, filters, and file citations
This chapter assumes you have already indexed documents in a vector store and made a basic file_search request. It also assumes you can read the output list of a Responses API reply. The examples use the OpenAI Python SDK. The ideas carry over to other providers, but parameter names differ.
The default retrieval settings often work in a demo and fail on real data. Answers pull in irrelevant chunks, cite the wrong department's policy, or cost more tokens than expected. Three controls fix most of this: how many chunks come back, which files are eligible, and how you verify the sources.
How retrieval fits together
When the model calls file search, the provider turns the model's query into an embedding. It compares that embedding with the chunks in your vector store, filters and ranks the candidates, and passes the top chunks to the model. Each setting in this chapter acts at one stage of that pipeline.
Limiting the number of results
max_num_results caps how many chunks the tool returns to the model. The cap affects three things:
- Cost. Every returned chunk becomes input tokens. With the default chunking of roughly 800 tokens per chunk, ten results can add about 8,000 input tokens.
- Latency. More context means a slower final generation.
- Answer quality. Too few chunks can miss the passage you need. Too many dilute the context with near-misses, and the model may blend them into one wrong answer.
Start low, around 3 to 5, and raise the cap only when you see answers missing facts that are in the documents. Questions that span several documents, such as comparisons, need a higher cap than lookups of a single fact.
Filtering by file attributes
A vector store can hold files from many teams, years, or customers. Without filtering, a question about the 2025 leave policy may retrieve chunks from the 2022 policy. You can attach attributes to each file in the store and then filter on them at query time. An attribute is a key-value pair. Values can be strings, numbers, or booleans, and each file can carry a small number of them (OpenAI allows 16).
Set attributes when you add a file to the store:
from openai import OpenAI
client = OpenAI()
vector_store = client.vector_stores.create(name="company-handbook")
def add_file(path, attributes):
with open(path, "rb") as f:
uploaded = client.files.create(file=f, purpose="assistants")
return client.vector_stores.files.create(
vector_store_id=vector_store.id,
file_id=uploaded.id,
attributes=attributes,
)
add_file("leave_policy_2025.pdf", {"department": "hr", "year": 2025})
add_file("leave_policy_2022.pdf", {"department": "hr", "year": 2022})
add_file("expense_policy.pdf", {"department": "finance", "year": 2025})Indexing runs in the background. Wait until each file's status is completed before querying. Otherwise the new files are silently missing from results.
Then pass a filters object in the tool definition. A comparison filter has a type, a key, and a value. The supported comparison types are eq, ne, gt, gte, lt, lte, in, and nin. Compound filters use and or or with a filters list:
response = client.responses.create(
model="gpt-4.1",
tools=[
{
"type": "file_search",
"vector_store_ids": [vector_store.id],
"max_num_results": 4,
"filters": {
"type": "and",
"filters": [
{"type": "eq", "key": "department", "value": "hr"},
{"type": "gte", "key": "year", "value": 2025},
],
},
}
],
input="How many days of parental leave do employees get?",
)
print(response.output_text)Filters run before ranking, so excluded files can never appear in results. That makes filters the right tool for access control within your own app. For example, build the filter on the server from the signed-in user's department and never let the model or the user supply it.
Score thresholds and ranking
The ranking_options field adds a minimum similarity score between 0 and 1. Chunks below it are dropped even if max_num_results has room left:
tools = [
{
"type": "file_search",
"vector_store_ids": [vector_store.id],
"max_num_results": 5,
"ranking_options": {"score_threshold": 0.5},
}
]A threshold lets the tool return nothing when no chunk matches well. The model can then say the documents do not cover the question, which is better than answering from a weak match. If the threshold is too high, you get empty results for questions that your documents do answer. Tune the value against real questions rather than picking it once.
Inspecting what was retrieved
By default the response shows that a search happened but not what it returned. Add include=["file_search_call.results"] to see the queries the model wrote and the scored chunks:
response = client.responses.create(
model="gpt-4.1",
tools=tools,
include=["file_search_call.results"],
input="What is the expense limit for client dinners?",
)
for item in response.output:
if item.type == "file_search_call":
print("queries:", item.queries)
for r in item.results or []:
print(f"{r.score:.2f} {r.filename} {r.attributes}")
print(" ", r.text[:80].replace("\n", " "))Read this output when tuning:
- Low scores on the top result mean the documents may not contain the answer, or the model's query was poorly worded. Check
queries. - The right file with a low rank suggests raising
max_num_resultsor improving the question wording through instructions. - Wrong files in the list point to a missing filter.
File citations
The final message attaches file_citation annotations to the answer text. Each has the file_id, the filename, and an index, which is the character position in the text where the citation applies. Collect them to show sources next to the answer:
for item in response.output:
if item.type == "message":
for part in item.content:
if part.type != "output_text":
continue
for ann in part.annotations or []:
if ann.type == "file_citation":
print(f"[{ann.index}] {ann.filename} ({ann.file_id})")Two cautions apply to citations:
- A citation tells you which file supplied a chunk that the model saw. It does not prove the model's sentence matches that chunk. Spot-check important claims against
file_search_call.results. - Citations name the file, not the page. If users need page numbers, split long documents into one file per section, or store the section in an attribute and read it from the results.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Answer ignores a recently added file | Indexing not finished | Poll until the file status is `completed` |
| Old policy cited instead of current | No year or version attribute filter | Add attributes and an `eq` or `gte` filter |
| Model says "I don't know" for covered topics | `score_threshold` too high or `max_num_results` too low | Lower the threshold, raise the cap, inspect scores |
| Costs climb with usage | High result cap on every request | Lower `max_num_results`, filter earlier |
| Filter returns nothing | Key or value type mismatch, such as `"2025"` versus `2025` | Match the attribute's stored type exactly |
Exercise
A support bot searches a vector store holding manuals for several product versions. Users on version 3 keep getting answers from version 2 manuals. Name two tuning changes that would help, and say which one would guarantee that version 2 text is never retrieved.
Show answer
Add a version attribute to each file and filter on it, and lower max_num_results so fewer weak matches reach the model. Only the attribute filter guarantees exclusion, because filters run before ranking and remove ineligible files entirely. A smaller result cap only reduces how often old chunks appear.
Exercise
Your request returns a good answer, but you want to know which chunk supported a specific sentence and how well it scored. Which request option and which response fields do you use?
Show answer
Set include=["file_search_call.results"] on the request. Read the file_search_call item's results, which list filename, score, text, and attributes. Match them to the file_citation annotations in the message, using each annotation's file_id and index.