Sub topic 10
Preparing Documents with Vector Stores
File search can only answer from documents that have been indexed first. This chapter covers that preparation step: what a vector store is, how files get into one, how to tell when they are ready, and the mistakes that cause empty or stale answers.
This chapter assumes you can call the Responses API with an API key, read JSON, and write basic Python. It uses the OpenAI Python SDK. Other providers handle document search differently, as the provider differences chapter explains.
What a vector store is
A vector store is a provider-hosted index of your documents. When you add a file, the provider does the following:
- Parses the file and extracts its text.
- Splits the text into chunks, which are short passages of a few hundred tokens each.
- Converts each chunk into an embedding, which is a list of numbers that represents the chunk's meaning.
- Stores the embeddings so that a question can be compared with them later.
At query time, the file search tool turns the question into an embedding too. It then returns the chunks whose embeddings are closest in meaning. This is called semantic search, and it can match a question like "How many vacation days do new hires get?" to a passage that says "Employees accrue 15 days of paid time off." The two texts share almost no words.
You never handle embeddings or chunks yourself. You create the store, add files, and later point the tool at the store's ID.
Creating a store and adding a file
The steps are to create the store, upload the file, and wait until indexing finishes.
from openai import OpenAI
client = OpenAI()
vector_store = client.vector_stores.create(name="company-handbook")
with open("handbook.pdf", "rb") as f:
vs_file = client.vector_stores.files.upload_and_poll(
vector_store_id=vector_store.id,
file=f,
)
print("store:", vector_store.id)
print("file status:", vs_file.status)upload_and_poll uploads the file, attaches it to the store, and blocks until processing ends. Without it, a search sent right after the upload may find nothing, because the file is still being indexed.
The store ID, which starts with vs_, is the value you pass to the file search tool in later requests. Save it. Creating a new store for every request is a common waste, since indexing costs time and money.
File status
Each file in a store has a status.
| Status | Meaning | What to do |
|---|---|---|
| `in_progress` | Parsing and embedding are still running. | Wait, or poll again. |
| `completed` | The file is searchable. | Use the store. |
| `failed` | Indexing did not succeed. | Read `last_error` and fix the cause. |
| `cancelled` | Processing was stopped before it finished. | Add the file again. |
Always check the status after uploading. A failed file does not raise an error in later search requests. The file is simply absent from the results, and the model answers from whatever else it finds, or from nothing.
if vs_file.status != "completed":
raise RuntimeError(f"Indexing failed: {vs_file.last_error}")Uploading several files
To index a folder of documents, use a batch. A batch uploads and attaches many files in one operation.
from pathlib import Path
paths = sorted(Path("docs").glob("*.pdf"))
streams = [p.open("rb") for p in paths]
try:
batch = client.vector_stores.file_batches.upload_and_poll(
vector_store_id=vector_store.id,
files=streams,
)
finally:
for s in streams:
s.close()
print(batch.status)
print(batch.file_counts)file_counts reports how many files are completed, in progress, failed, or cancelled. If failed is above zero, list the store's files and check which ones failed.
for f in client.vector_stores.files.list(vector_store_id=vector_store.id):
if f.status == "failed":
print(f.id, f.last_error)Using the store in a request
Once the files are completed, reference the store from the tool declaration.
response = client.responses.create(
model="gpt-4.1",
tools=[
{
"type": "file_search",
"vector_store_ids": [vector_store.id],
}
],
input="How many vacation days do new employees get?",
)
print(response.output_text)The next chapters cover reading the results and tuning retrieval. Here the point is only that the store ID connects the indexing step to the query step.
Choosing what to index
The quality of answers depends heavily on what goes into the store.
- Prefer text-based files. Formats such as PDF, Markdown, plain text, DOCX, and HTML are parsed for text. A scanned PDF that is only page images has no text layer. It can produce an empty or poor index unless you run OCR first.
- Keep documents focused. One 500-page file that mixes unrelated topics gives less precise chunks than several files that each cover one subject.
- Use descriptive file names. Citations show the file name, so
leave-policy-2025.pdfis more useful to readers thandoc_17.pdf. - Remove duplicates and outdated versions. If two files disagree, the model may retrieve either one.
- Check size limits. Providers cap file size and the total storage per store. Look up the current numbers in the provider documentation, because they change.
Keeping a store up to date
A vector store holds a snapshot. Editing the original file on your disk does not change the index. To update a document, take these steps:
- Remove the old file from the store.
- Upload and attach the new version.
- Confirm the new file reached
completed.
client.vector_stores.files.delete(
vector_store_id=vector_store.id,
file_id=old_file_id,
)Removing a file from a store detaches it from the index. It does not necessarily delete the underlying uploaded file, which exists separately in your account's file storage. Delete that too with client.files.delete(old_file_id) if you no longer need it.
A common bug is to upload the new version without removing the old one. Both stay searchable, and answers become inconsistent.
Cost, lifetime, and access
Vector stores are billed by storage, usually by the gigabyte per day after a small free allowance. Searches are billed separately, as later chapters show. Stores can also be given an expiration policy so that abandoned stores clean themselves up.
vector_store = client.vector_stores.create(
name="temporary-project-docs",
expires_after={"anchor": "last_active_at", "days": 7},
)Here the store expires seven days after it was last used. Check the current rules for your account.
Treat a store as shared data. Anyone who can send a request with your API key and the store ID can query it. If different users must see different documents, give each audience its own store, and never put confidential files in a store that a wider group can reach. The security chapter returns to this.
Common errors
| Symptom | Likely cause |
|---|---|
| The model answers "I couldn't find that" for content you know exists. | The file is still `in_progress`, or it `failed`. |
| Answers quote an old policy. | The old file was never removed from the store. |
| Search returns nothing for a scanned PDF. | The file has no extractable text. Run OCR first. |
| A `404` error mentions the store. | The store expired or was deleted, or the ID is wrong. |
| Every request is slow and costly. | The code creates and fills a new store on each request. |
Exercise
You upload a new version of a leave policy with upload_and_poll, and status is completed. Users still get answers based on the old numbers. What is the most likely cause, and how do you fix it?
Show answer
The old version is still in the vector store, so both versions are searchable and the model may retrieve the old one. Remove the old file from the store with client.vector_stores.files.delete(...), and delete the underlying file with client.files.delete(...) if it is no longer needed. Then confirm that only the new file remains by listing the store's files.
Exercise
A script uploads a PDF and immediately sends a file search request. The answer says nothing relevant was found. Name two possible reasons and one check for each.
Show answer
First, indexing may not have finished. Check that the file's status is completed, or use upload_and_poll. Second, the file may have failed or may have no extractable text, as with a scanned PDF. Check last_error on the file and whether the PDF has a text layer.