Sub topic 11
File search: retrieval over your own documents
This chapter covers the file search tool in the OpenAI Responses API. It assumes you can call the Responses API with an API key, read JSON request and response bodies, and understand basic tool calling. It also assumes you know what a vector store is, from the previous chapter on preparing documents. Details such as parameter names and defaults can change, so check the provider's current documentation before you ship.
What file search does
File search is a built-in tool that lets the model look up passages in documents you uploaded. The provider runs the retrieval for you. Your code sends one request and receives one response that already contains the retrieved evidence and the final answer.
The tool is a form of retrieval-augmented generation (RAG). RAG means the system fetches relevant text first and gives it to the model as context. The model then answers from that text instead of relying only on what it learned in training.
Use file search when the answer lives in your own material, such as a handbook, product manuals, or support notes. It fits poorly when the data is live, small enough to paste into the prompt, or needs exact structured queries. Those cases are covered in the chapter on choosing tools.
How a file search request flows
Several steps happen inside one API call.
- You index documents in a vector store ahead of time. The provider splits each file into chunks and turns each chunk into an embedding. An embedding is a list of numbers that represents the meaning of the text.
- At request time, the model decides it needs to search and writes a query.
- The provider embeds the query and finds the chunks whose embeddings are closest to it. It can also use keyword matching alongside this.
- The top chunks are placed in the model's context.
- The model writes the answer and attaches citations to the files it used.
Step 1: build the vector store
The index must exist before any request can use it. Create the store, then upload a file and wait for processing to finish.
from openai import OpenAI
client = OpenAI()
vector_store = client.vector_stores.create(name="company-handbook")
with open("handbook.pdf", "rb") as f:
client.vector_stores.files.upload_and_poll(
vector_store_id=vector_store.id,
file=f,
)
print("vector store id:", vector_store.id)The upload_and_poll helper uploads the file and then polls until chunking and embedding complete. If you skip the wait, a search made right away can return nothing, because the file is not yet searchable. Save the store ID. You create the store once and reuse it across many requests.
Step 2: query with the tool
Declare the tool in the tools list and point it at the store.
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-4.1",
tools=[
{
"type": "file_search",
"vector_store_ids": ["vs_your_store_id"],
"max_num_results": 3,
}
],
input="How many vacation days do new employees get?",
)
print(response.output_text)Replace vs_your_store_id with the ID you saved earlier. The vector_store_ids field takes a list, so one request can search more than one store. The max_num_results field caps how many chunks come back. A lower cap means fewer input tokens and faster answers, but it raises the chance that the right passage is left out.
Step 3: read the output items
The response output is a list of items. For file search, you normally see a file_search_call item followed by a message item. Reading both lets you audit what the tool did.
for item in response.output:
if item.type == "file_search_call":
print("search status:", item.status)
print("queries:", item.queries)
elif item.type == "message":
for part in item.content:
for ann in getattr(part, "annotations", []) or []:
if ann.type == "file_citation":
print("cited file:", ann.filename, ann.file_id)The queries field shows what the model actually searched for. This is often the quickest way to debug a bad answer. If the query is vague or misses a key term, the retrieval will be poor no matter how good the index is. The file_citation annotations tell you which files support the text, so you can show sources to the user.
To see the raw retrieved chunks and their scores, ask for them explicitly with the include parameter.
response = client.responses.create(
model="gpt-4.1",
tools=[
{
"type": "file_search",
"vector_store_ids": ["vs_your_store_id"],
"max_num_results": 3,
}
],
include=["file_search_call.results"],
input="How many vacation days do new employees get?",
)
for item in response.output:
if item.type == "file_search_call":
for result in item.results or []:
print(result.filename, round(result.score, 3))
print(result.text[:120])Results are left out by default to keep responses small. Request them while debugging, and turn them off in production if you do not need them.
Tuning retrieval
Three settings affect quality most.
| Setting | Effect | Trade-off |
|---|---|---|
| `max_num_results` | Number of chunks given to the model | More chunks improve recall but cost more tokens and time |
| `filters` | Restricts search to files with matching attributes | Needs attributes set when files are added |
| `ranking_options` | Sets a score threshold for chunks | A high threshold removes noise but can return nothing |
Filters rely on attributes, which are key-value metadata you attach to a file in the vector store. A common use is separating documents by department or by version so users only see the right ones.
client.vector_stores.files.upload_and_poll(
vector_store_id=vector_store.id,
file=open("handbook.pdf", "rb"),
attributes={"department": "hr", "year": 2025},
)At query time, add a filter to the tool definition.
tools = [
{
"type": "file_search",
"vector_store_ids": [vector_store.id],
"filters": {"type": "eq", "key": "department", "value": "hr"},
}
]Check the current API reference for the exact attribute and filter syntax, because it has changed between releases.
Common errors and edge cases
- Empty or weak results right after upload. The file was still processing. Use the polling helper, or check the file status before querying.
- The model answers without searching. With the default tool choice, the model decides whether to search. Add an instruction such as "Answer only from the provided documents," or set
tool_choiceto require the tool. - Answers are close but wrong. Chunks may split a table or a definition across boundaries. Review how your documents are laid out, and consider cleaner source files.
- The answer ignores a document that clearly has the data. The model's query may use different words. Inspect
queries, and try a more specific instruction. - Scanned PDFs return nothing. Text must be extractable. Image-only pages are not searchable without OCR first.
- Stale answers. The index does not update by itself. When a source file changes, upload the new version and remove the old one.
- Wrong users see the wrong files. A vector store has no per-user permissions inside it. Use separate stores or attribute filters, and enforce them in your code, not in the prompt.
Cost and latency
Vector stores usually bill for storage by size and time, and chunks you retrieve count as input tokens on every request. The file search call itself may carry a per-call charge as well. Lowering max_num_results, filtering to the right subset, and keeping stores small all reduce cost. Retrieval also adds a round trip inside the provider, so expect higher latency than a plain request. Check current pricing, since these rates change.
Other providers
File search as described here is OpenAI's hosted tool. Other providers handle retrieval differently. Some offer a comparable hosted feature, and others expect you to run your own retrieval and expose it as a function tool. If you need portability, a custom function tool that wraps your own search keeps the logic under your control, at the price of building and hosting the index yourself.
Exercise
A user asks about the refund policy and the answer is wrong. The file_search_call item shows the model searched for "policy" and nothing else. Name two things you would check or change, and say which part of the response you would inspect first.
Show answer
Inspect the queries field of the file_search_call item first, since the query "policy" is too vague to find the refund passage. Then add an instruction telling the model to search with specific terms, or require the tool with tool_choice. You can also request file_search_call.results through include to see which chunks came back and their scores, and raise max_num_results if the right chunk ranked just below the cutoff.
Exercise
Your company stores HR and finance documents in one vector store. How do you make sure an HR assistant never returns finance files?
Show answer
Attach a department attribute to each file when you upload it, and add a filters entry such as {"type": "eq", "key": "department", "value": "hr"} to the file_search tool. Your server must set this filter, not the user or the prompt. Separate vector stores for each department are a stricter option.