Skip to content
,

OpenAI File Search API Tutorial in Python: Vector Stores, Citations and Costs

10–15 minutes
Woman in a home office with bookshelves holding a tablet with a VECTOR STORES card, hook 1 GB free file search

OpenAI File Search lets a model answer questions from your own PDFs, docs and code. You upload files into a vector store, and the hosted file_search tool in the Responses API finds the right chunks and cites them.

This tutorial walks you through it in Python, from your first vector store to filters, citations, the search-only endpoint and real costs. Every parameter name comes from the official docs and the openai 3.63.0 Python SDK (released 3 Dec 2026).

TLDR

  • Flow: create a vector store, upload files with upload_and_poll, then pass {"type": "file_search", "vector_store_ids": [...]} to client.responses.create.
  • Citations: the answer comes back with file_citation annotations that hold the file_id, filename and character index.
  • Search only: client.vector_stores.search() returns ranked chunks with no model call, for your own RAG pipeline.
  • Price: $2.50 per 1,000 tool calls plus $0.10 per GB per day of storage, with the first 1 GB free.
  • Limits: 512 MB and 5,000,000 tokens per file, 16 attributes per file, up to 50 results per search.

File Search is a hosted retrieval tool. OpenAI parses your files, splits them into chunks, embeds them and stores them in a vector store. You never run your own vector database or embedding job.

When the model decides it needs your files, it calls the tool by itself. Under the hood, OpenAI’s docs describe these steps:

  • Query rewriting: the user question is rewritten into better search queries.
  • Parallel search: complex questions are split into several searches that run at once.
  • Hybrid search: both keyword and semantic (embedding) search run over your chunks.
  • Reranking: results are reranked so only the most relevant chunks reach the model.
OpenAI File search docs page saying file search is a tool in the Responses API that uses semantic and keyword search over vector stores
Official OpenAI File search guide (checked 3 Dec 2026).

When it is the right tool

  • Good fit: help-desk bots over manuals, internal policy Q&A, searching contracts, docs or code.
  • Bad fit: number crunching over CSV or JSONL tables (use Code Interpreter), and questions about charts or images inside PDFs, which are not parsed.
  • Summaries of a whole book: retrieval returns the best chunks, not the full file, so long summaries are weak.

Note: The Assistants API shut down on 26 August 2026. Vector stores live on and now plug into the Responses API. If you are new to that API, start with our OpenAI Responses API tutorial.

Prerequisites

  • Python 3.10 or newer: the openai 3.63.0 package requires it.
  • An OpenAI API key: see how to get an OpenAI API key if you do not have one.
  • Billing turned on: tool calls and storage over 1 GB are paid.
  • Some files: PDF, DOCX, PPTX, TXT, MD, HTML, JSON or source code. Text files must be UTF-8, UTF-16 or ASCII.

Setup in 5 Steps

  1. Create a project folder. Run mkdir file-search-demo and cd file-search-demo.
  2. Make a virtual environment. Run python -m venv .venv, then activate it.
  3. Install the SDK. Run pip install openai. Check it with pip show openai (we checked 3.63.0).
  4. Set your key. Run export OPENAI_API_KEY="sk-..." on macOS or Linux, or setx OPENAI_API_KEY "sk-..." on Windows. Never paste the key into code.
  5. Add a docs folder. Put a few files in ./docs, for example a returns policy PDF and a FAQ in Markdown.

Create a Vector Store and Upload Files

A vector store is a searchable index of your files. The helper upload_and_poll uploads the file, attaches it, and waits until indexing finishes.

from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY

# 1. Create a vector store that deletes itself after 30 idle days
store = client.vector_stores.create(
    name="support-kb",
    expires_after={"anchor": "last_active_at", "days": 30},
)
print("Vector store:", store.id)

# 2. Upload one file and wait until it is indexed
with open("docs/returns-policy.pdf", "rb") as f:
    vs_file = client.vector_stores.files.upload_and_poll(
        vector_store_id=store.id,
        file=f,
        attributes={"category": "policy", "year": 2026},
    )

print(vs_file.status)        # completed / failed / cancelled
print(vs_file.last_error)    # None when all went well

The file status ends as completed, failed or cancelled. If it failed, last_error.code is one of server_error, unsupported_file or invalid_file.

Tip: Always set expires_after on test stores. The only anchor is last_active_at and days can be 1 to 365, so forgotten demos stop costing you storage.

Upload first, attach later

You can also upload with the Files API using purpose="assistants" and attach the file id afterwards. This is handy when one file goes into several stores.

uploaded = client.files.create(file=open("docs/faq.md", "rb"), purpose="assistants")

client.vector_stores.files.create_and_poll(
    vector_store_id=store.id,
    file_id=uploaded.id,
)

File Batches, Chunking and Attributes

For many files, use a file batch. It is the endpoint OpenAI recommends for multi-file ingestion, and one batch can hold up to 2,000 files.

from pathlib import Path
from openai import OpenAI

client = OpenAI()
STORE_ID = "vs_..."  # your vector store id

paths = list(Path("docs").glob("*.md")) + list(Path("docs").glob("*.pdf"))
streams = [open(p, "rb") for p in paths]

batch = client.vector_stores.file_batches.upload_and_poll(
    vector_store_id=STORE_ID,
    files=streams,
    max_concurrency=5,
    chunking_strategy={
        "type": "static",
        "static": {"max_chunk_size_tokens": 1200, "chunk_overlap_tokens": 200},
    },
)

for s in streams:
    s.close()

print(batch.status, batch.file_counts)

Check batch.file_counts: it shows how many files are completed, failed, in_progress and cancelled.

Chunking options

If you set nothing, OpenAI uses the auto strategy. That means chunks of 800 tokens with a 400-token overlap.

Setting Default Allowed range
max_chunk_size_tokens 800 100 to 4,096
chunk_overlap_tokens 400 Not more than half of the chunk size
Strategy type auto auto or static
  • Smaller chunks: sharper matches for FAQs and short policy clauses.
  • Bigger chunks: more context per hit for long technical docs, but more input tokens per answer.

Per-file attributes in a batch

Attributes are key-value tags you filter on later. Each file gets up to 16 pairs, keys up to 64 characters, and values that are strings (up to 512 characters), numbers or booleans.

To give each file different attributes, use file_batches.create_and_poll with the files list. When you use files, the global attributes and chunking_strategy are ignored.

batch = client.vector_stores.file_batches.create_and_poll(
    vector_store_id=STORE_ID,
    files=[
        {"file_id": "file-aaa", "attributes": {"category": "policy", "region": "eu"}},
        {"file_id": "file-bbb", "attributes": {"category": "faq", "region": "us"}},
    ],
)

Note: Filters on file names only work if you set your own filename attribute. They do not match the uploaded name automatically.

Use the file_search Tool in the Responses API

Now ask a question. Pass the tool with your store id, and the model decides when to search.

from openai import OpenAI

client = OpenAI()
STORE_ID = "vs_..."

response = client.responses.create(
    model="gpt-6.2-sol",
    input="How many days do customers 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)

Here is what each tool option does:

  • vector_store_ids: required list of stores to search.
  • max_num_results: 1 to 50. Fewer results means fewer input tokens and lower latency, but can hurt answer quality.
  • filters: an attribute filter, covered below.
  • ranking_options: ranker (auto or default-2024-11-15), score_threshold from 0 to 1, and hybrid_search weights (embedding_weight, text_weight).

Tip: Set tool_choice="required" if every question must be answered from your files. Pair it with an instruction like “Answer only from the files, and say so if the answer is not there.”

Read Citations and Search Results

The response has two key output items. First comes a file_search_call, then a message whose text carries file_citation annotations.

for item in response.output:
    if item.type == "file_search_call":
        print("Queries used:", item.queries)
        for r in item.results or []:
            print(f"{r.score:.2f}  {r.filename}  {r.text[:80]}")

    if item.type == "message":
        for part in item.content:
            if part.type == "output_text":
                print(part.text)
                for ann in part.annotations:
                    if ann.type == "file_citation":
                        print(f"  [cited] {ann.filename} ({ann.file_id}) at char {ann.index}")
  • index: the character position in the answer where the citation belongs. Use it to insert footnote markers.
  • file_id and filename: which file backed the claim.
  • results: is empty unless you add include=["file_search_call.results"]. Each result has file_id, filename, score, text and attributes.

Note: The raw JSON in the docs shows the field as search_results. The Python SDK object exposes it as results.

Filter by Attributes

Filters narrow the search to files whose attributes match. This is how you keep one store for many customers, regions or years.

Operator Meaning Example value
eq / ne Equals / not equal "policy"
gt / gte Greater than / or equal 2025
lt / lte Less than / or equal 2027
in / nin In list / not in list ["faq", "policy"]
and / or Compound filter with a filters array Nest any of the above
tools = [{
    "type": "file_search",
    "vector_store_ids": [STORE_ID],
    "filters": {
        "type": "and",
        "filters": [
            {"type": "in", "key": "category", "value": ["policy", "faq"]},
            {"type": "gte", "key": "year", "value": 2026},
        ],
    },
}]

response = client.responses.create(
    model="gpt-6.2-sol",
    input="What is the 2026 refund window for EU customers?",
    tools=tools,
)
print(response.output_text)

Warning: Filters are a convenience, not a security wall. For hard tenant isolation, give each customer their own vector store and only pass that store’s id.

Retrieval-Only Search Endpoint

Sometimes you want the chunks but not an answer. Maybe you use another model, or you show raw results in a search box. client.vector_stores.search() does exactly that.

from openai import OpenAI

client = OpenAI()

page = client.vector_stores.search(
    vector_store_id="vs_...",
    query="refund window for damaged items",
    max_num_results=5,
    rewrite_query=True,
    filters={"type": "eq", "key": "category", "value": "policy"},
    ranking_options={"ranker": "auto", "score_threshold": 0.4},
)

for hit in page.data:
    text = " ".join(c.text for c in hit.content)
    print(f"{hit.score:.2f}  {hit.filename}  {text[:100]}")
  • Default results: 10, and you can raise max_num_results to 50.
  • rewrite_query: lets OpenAI rewrite the query. The rewritten text appears in search_query.
  • ranker: set it to none to skip reranking and cut latency.

The same search with curl

curl https://api.openai.com/v1/vector_stores/vs_abc123/search \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"query": "refund window for damaged items", "max_num_results": 5}'

Want to compare with Google’s take on hosted RAG? Our Gemini File Search API guide covers the same idea on the Gemini side.

Pricing and a Worked Cost Example

File Search has three cost parts: tool calls, storage and the normal model tokens. Prices below are from the official pricing page, checked on 3 December 2026.

OpenAI pricing table showing file search storage at 0.10 dollars per GB per day with 1 GB free and tool calls at 2.50 dollars per 1k calls
Official OpenAI API pricing page, built-in tools section (checked 3 Dec 2026).
Item Price Notes
File search tool call $2.50 per 1,000 calls Applies to the Responses API only
Vector store storage $0.10 per GB per day First 1 GB free, across all stores
GPT-6.2 Sol tokens $2 input / $0.10 cached / $10 output per 1M Standard tier
GPT-6.2 Astra tokens $8 input / $0.40 cached / $40 output per 1M Standard tier
Direct search endpoint No per-call fee listed You still pay storage

Storage is billed on the size of the parsed chunks plus their embeddings, not the raw file size. The pricing page also says a GB here means a binary gigabyte (2^30 bytes).

Worked example: a support bot

Say a store uses 3 GB and your bot answers 20,000 questions a month on GPT-6.2 Sol. Each answer pulls about 8,000 input tokens (question plus retrieved chunks) and writes 400 output tokens.

  • Storage: (3 GB minus 1 free GB) x $0.10 x 30 days = $6.00
  • Tool calls: 20,000 / 1,000 x $2.50 = $50.00
  • Input tokens: 160M x $2 per 1M = $320.00
  • Output tokens: 8M x $10 per 1M = $80.00
  • Total: about $456 per month
Quick answer: Tokens, not storage, drive most of the bill. Cutting max_num_results or chunk size often saves more than deleting files. For the full model price list, see our OpenAI API pricing guide.

Limits

Limit Value
Max file size 512 MB
Max tokens per file 5,000,000
Files per vector store 100,000,000 for stores created from November 2025 (10,000 for older stores)
Files per batch 2,000
file_ids when creating a store 500
Attributes per file 16 (keys 64 chars, string values 512 chars)
Results per search 1 to 50 (search endpoint default 10)
Writes to one store (files + file_batches) 300 requests per minute
Attaching files to stores 2,000 files per minute per organization
File search tool rate limit 500 RPM on Build, 1,000 RPM on Launch and Grow
Project file storage 2.5 TB
Store expiry 1 to 365 days after last activity

OpenAI’s docs also list known gaps: images and charts inside documents are not parsed, and CSV or JSONL files are not supported for retrieval.

Troubleshooting: Common Errors and Fixes

Problem or error Likely cause Fix
File status failed with unsupported_file Extension not on the supported list, such as .csv or .xlsx Convert to PDF, TXT, MD or JSON, or use Code Interpreter for tables
invalid_file Corrupt file, scanned PDF with no text layer, or wrong text encoding Re-export the file, run OCR first, save text as UTF-8
server_error on a file Temporary processing failure Delete the vector store file and attach it again
400 error on chunking_strategy Overlap is more than half the chunk size, or size outside 100 to 4,096 Keep chunk_overlap_tokens at or below half of max_chunk_size_tokens
404 not found for a vs_ id Wrong id, deleted store, or a key from another project List stores with client.vector_stores.list() using the same project key
Store status expired The expires_after window passed with no activity Create a new store and re-attach the file ids
429 rate limit while uploading Over 300 writes per minute to one store Use one file batch instead of many single uploads, and back off
Answer has no citations The model chose not to call the tool Set tool_choice="required" and tell the model to answer from files
Empty results You did not request them Add include=["file_search_call.results"]
New file not found right after upload Indexing still running; listing can lag Use the _and_poll helpers and wait for completed

For general API errors such as 401 and 500, our OpenAI API errors guide has the full list of fixes.

Frequently Asked Questions

Do I still need the Assistants API for file search?

No. The Assistants API shut down on 26 August 2026. Vector stores now work with the file_search tool in the Responses API.

Which embedding model does File Search use?

OpenAI’s docs say it uses text-embedding-3-large at 256 dimensions. You cannot pick a different model, so use the Embeddings API if you need full control.

Is the vector_stores.search endpoint free?

The pricing page only lists the $2.50 per 1,000 call fee for the Responses API tool. You still pay storage above the free 1 GB.

Can I search more than one vector store at once?

Yes. vector_store_ids is a list, so you can pass several store ids in one file_search tool.

Does File Search read tables, charts and images in PDFs?

It reads the text in PDFs, but OpenAI lists images, charts and graphs inside documents as not parsed. Add a text description if that content matters.

How do I delete files and stop storage charges?

Call client.vector_stores.files.delete() to remove a file from a store, or client.vector_stores.delete() to drop the whole store. Removal is eventually consistent, so it can take a short time to vanish from search.

How is File Search different from Gemini File Search?

Both are hosted RAG with citations. Pricing and limits differ, so compare our Gemini File Search guide before you choose.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a home office with bookshelves holding a tablet with a VECTOR STORES card, hook 1 GB free file search