A document assistant sounds simple: upload a handbook, ask a question, and receive an answer with a source. The first demo can be short. A useful product needs more: a way to tell when indexing has finished, a policy for missing evidence, a citation the reader can inspect, a plan for changed documents, and a test set that exposes wrong answers before customers do.
This guide builds a small document-question-answering workflow around OpenAI's hosted file search. It explains the pieces, shows scoped Python examples, and works through evaluation, security, cost and operations. The example handbook and questions are fictional. The API snippets follow the structure in the official documentation, but they have not been run against a live account for this article; verify the installed SDK and current API reference before deploying them.
What you will build
The example is a support assistant for a fictional shop. A staff member asks, “What is the return window?” The assistant searches an approved policy document, answers from the material it finds, and shows a source reference. If the document does not contain the answer, the assistant should say so instead of inventing a policy.
The workflow has five stages:
- Prepare a small, readable source document and decide who may use it.
- Upload the file, create a vector store and wait for indexing to complete.
- Call the Responses API with the
file_searchtool and the appropriate store. - Inspect the answer and citation information; optionally request search results for diagnostics.
- Test supported, ambiguous, missing and conflicting questions before exposing the workflow to users.
You will need a Python environment, the OpenAI Python SDK, an API key configured on a trusted server, and access to a model that supports the tool. API calls and storage can incur charges. Use a synthetic document for the first run and check the current pricing page and your account limits before creating resources.
How file search fits into RAG
Retrieval-augmented generation, or RAG, combines a search over external material with a generated response. The search step finds candidate passages; the model uses the available context to answer. This can make a document assistant more useful than relying on a model's general knowledge, especially when the answer depends on an organization's current material.
OpenAI's hosted file search works with vector stores. You upload supported files, attach them to a store and wait for processing. You then make the store available to the file_search tool in a Responses API request. The official file search guide documents this flow and the available options.
The service handles retrieval infrastructure, but the application still owns important decisions. It must select the correct store, authorize the user, handle ingestion failures, decide what to do with missing evidence, and present citations accurately. A returned answer is not automatically correct just because the tool was available.
Direct vector-store search is another option. It can be useful when you want to inspect candidate results or apply application-specific processing before a generation step. The retrieval guide covers vector-store search and file attributes. Hosted file search and direct retrieval can serve different application designs; choose based on the control and observability your workflow needs.
Prepare a small source you can verify
Create a synthetic text file named returns-policy.txt. Give it a short title, an effective date and one unambiguous policy statement. For example, the fictional shop might accept eligible returns within 30 days of delivery. Add a second paragraph describing an exception, such as a product category that requires a different process. These are test fixtures, not legal or commercial advice.
Keep the document readable before optimizing it for retrieval. Clear headings, complete sentences and explicit qualifiers help both people and systems interpret a policy. A table whose columns depend on a visual layout may not survive text extraction as expected; inspect the result for your actual file types. A scanned PDF may require an appropriate extraction workflow. Confirm current supported formats and limits in the official guide before accepting uploads.
Use a source you are authorized to upload. For a prototype, synthetic material avoids accidental disclosure and makes expected answers easy to define. For production, review the provider's data controls, your organization's policy and the sensitivity of the documents. Do not assume that a convenient API is automatically appropriate for every category of data.
Before uploading a large corpus, select a small representative sample. Include a current document, an older version, a document with an exception and a document that does not answer one of your questions. This sample gives you something concrete to evaluate when the first answer looks plausible but is subtly wrong.
Set up a trusted server environment
Install the official Python SDK in a virtual environment and configure the API key through your server's secret-management process. The SDK can read OPENAI_API_KEY from the environment. Keep the key out of browser code, source control, logs and screenshots. The following command installs the package; pin a tested version in your application's dependency file before production.
python -m pip install openaiThe examples below are intended to run on a trusted machine or backend, not directly in a visitor's browser. They create remote resources and may incur charges. Use a dedicated test project or environment where possible, record the IDs you create, and follow your organization's cleanup and retention rules. Do not paste an API key into the script.
Choose a model supported by file search and available to your account. The exact model names and capabilities can change, so the example reads the model from an environment variable rather than assuming a particular name will remain available. Check the current model and tool documentation before setting it.
Upload the document and create a vector store
The official file-search guide shows separate steps for uploading a file, creating a vector store, and attaching the file. Keeping these steps visible makes it easier to understand where an error occurs. The Python SDK's polling helper can wait for the attachment to finish processing.
This example is a concise development script, not a full ingestion service. It creates billable remote resources, prints their identifiers for the next step, and does not automatically delete them. Run it only with a test file and account you intend to use; record the IDs so you can review and clean up the resources afterward.
from pathlib import Path
from openai import OpenAI
client = OpenAI()
path = Path("returns-policy.txt")
with path.open("rb") as source:
uploaded = client.files.create(file=source, purpose="user_data")
store = client.vector_stores.create(name="returns-policy-test")
attachment = client.vector_stores.files.create_and_poll(
vector_store_id=store.id,
file_id=uploaded.id,
)
if attachment.status != "completed":
raise RuntimeError(f"Indexing finished with status: {attachment.status}")
print("Vector store:", store.id)
print("File:", uploaded.id)Polling matters because attaching a file and making it searchable are separate events. A successful upload does not prove that parsing and indexing succeeded. Check the final status and surface failures to the operator. In a production ingestion pipeline, record the source document version, uploaded file ID, store ID, indexing state and error category in your own system.
The sample prints identifiers, not secret keys. Still, treat identifiers according to your organization's policy: they may reveal infrastructure or customer relationships. Avoid dumping the full file or provider response into logs when it contains private material.
For multiple files, use the current SDK's batch facilities where appropriate and inspect the status of each attachment. A batch that contains one failed document should not silently appear as a complete knowledge base. The user interface can show “processing,” “ready” or “failed” based on verified state rather than assuming that every upload succeeded.
Ask a question with file search
Once the file is indexed, set OPENAI_VECTOR_STORE_ID to the test store ID and OPENAI_FILE_SEARCH_MODEL to a supported model. The next example asks one question and makes the store available to file search. It uses environment variables for configuration and does not expose the API key in the browser.
import os
from openai import OpenAI
client = OpenAI()
store_id = os.environ["OPENAI_VECTOR_STORE_ID"]
model = os.environ["OPENAI_FILE_SEARCH_MODEL"]
response = client.responses.create(
model=model,
input="According to the policy, what is the return window?",
tools=[{
"type": "file_search",
"vector_store_ids": [store_id],
}],
)
print(response.output_text)The model can use the tool when it considers it appropriate under the request configuration. Inspect the response rather than assuming that a file search call always occurred or that every answer has a citation. The exact response objects and SDK helpers are documented in the file search guide and API reference.
Printing output_text is convenient for a first experiment, but a production interface should also inspect the output items and annotations it needs. Validate their shape against the installed SDK, handle missing fields, and map provider file IDs to your own source catalog. Do not expose a raw provider object to the browser simply because it is convenient during development.
In the prompt or application instructions, define what the assistant should do if the supplied material does not answer the question. For example, ask it to state that the available documents do not establish the answer and to avoid inventing a policy. That instruction improves the intended behavior, but it is not a guarantee; evaluate missing-answer cases and enforce application boundaries independently.
Inspect search results when debugging
The answer text and its annotations are not the same thing as the full set of search results. The official guide states that search results are not included by default and shows an include option to request them. Use this in a controlled development or evaluation environment when you need to understand what the tool returned.
response = client.responses.create(
model=model,
input="What does the policy say about return exceptions?",
tools=[{
"type": "file_search",
"vector_store_ids": [store_id],
"max_num_results": 3,
}],
include=["file_search_call.results"],
)The result limit is a tuning parameter, not a universal recommendation. Fewer results may reduce the amount of retrieved material and latency, but they can omit evidence needed for a complex answer. More results can improve coverage in some cases while introducing irrelevant or conflicting material. Compare settings on the same representative questions and record both retrieval and answer quality.
Included search results may contain source text. Restrict who can view and retain them, especially in production. A debugging feature that prints every retrieved passage to a shared log can expose information the user was authorized to see only in the application. Prefer synthetic fixtures during development and use a controlled process when a real incident requires deeper inspection.
Do not present every retrieved result as evidence for every sentence. A search result is a candidate; the answer may not use it, and it may not support the generated claim. A citation should connect a specific claim to a source the reader can inspect. The related RAG citations guide covers this distinction in more detail.
Build a source experience readers can use
A useful answer gives the reader a path back to the original policy. Display the source title and, when your system knows it, the version or relevant section. If the provider identifies only a file, label the reference as a file-level citation. Do not guess a page number or show a highlight that your application cannot reliably map to the source.
Resolve provider file IDs through a server-side catalog. The catalog can associate an uploaded file with the original document, its owner, version and access policy. When a reader opens the source, check current access again. A citation URL is not a permanent authorization grant, and a user who loses access after an answer was generated should not retain a back door to the document.
Make no-answer states visible. If the policy says nothing about international returns, the assistant should say that the available material does not establish the rule. Offer a sensible next step, such as consulting a policy owner or refining the question. If two permitted sources conflict, show the disagreement or apply a documented authority rule; do not silently treat the most recently uploaded file as authoritative without a business reason.
Add metadata and filtering carefully
As a corpus grows, metadata can help narrow search to the appropriate document category, region, product or version. The OpenAI file-search and retrieval guides describe file attributes and filters. Use them to implement a policy your application has already determined, and verify the syntax and supported operators for your installed SDK.
For example, a support team may have separate return policies for different regions. A server-side request can use a verified region selection to search the relevant materials. Test what happens when the region attribute is missing or incorrect. A missing value should not accidentally turn into an unrestricted search if that would expose material the user should not see.
Metadata is not identity. A tenant ID or region supplied by the browser is a request, not proof that the caller may access that scope. Resolve membership and permissions on the server, then construct the store selection and filters from trusted application data. The multi-tenant RAG guide walks through that boundary in detail.
Also consider document-level permissions inside a tenant. A user may be allowed to search product manuals but not employee records. If your provider's filtering cannot express the necessary policy, choose an architecture that keeps unauthorized content out of the model's context. A relevance filter added after a broad search may be too late if passages have already reached another service or log.
Design ingestion as a repeatable workflow
A production ingestion pipeline needs more than a one-time upload script. It should know which source document is being processed, which version is current, where it belongs, and whether indexing completed. It should also handle retries without creating uncontrolled duplicates.
Start with a trusted source record. Validate the file type and size against your product rules and the provider's current limits. Assign ownership and metadata from the authorized upload context, not from instructions inside the document. Record a checksum or version identifier if it helps you detect a changed source, but do not treat a checksum as an access-control decision.
Use an explicit state such as received, processing, ready, failed or superseded. When processing fails, retain a diagnostic category and give an operator a retry path. If you retry after a timeout, check whether the original operation completed before creating another resource. A network timeout does not always mean that the remote service did nothing.
When a new document version arrives, define the cutover. You may index the new version first, verify it, then update the application's current-version mapping. Decide how old answers and citations should behave. If both versions remain searchable, a question about the current policy may retrieve an obsolete passage unless the scope or metadata distinguishes them.
OpenAI's retrieval documentation notes that removing files from a vector store is eventually consistent: search results may include removed content for a short period. Build that behavior into your deletion and revocation design rather than promising instantaneous removal. A sensitive workflow may need an application-side block while asynchronous removal completes. Check the current documentation and test the behavior in your environment.
Understand chunking and document structure
Retrieval systems generally search portions of documents rather than handing every complete file to the model for every question. The boundaries between portions affect whether a condition stays with the sentence it qualifies. A policy statement in one chunk and its exception in another can produce an incomplete answer if only the first is retrieved.
Do not tune chunk size by intuition alone. Start with the provider's documented defaults or supported configuration, then test representative questions. Examine cases involving headings, tables, numbered procedures, long definitions and exceptions. A smaller chunk may improve focus for one question while losing context needed for another. A larger chunk may preserve context but include more irrelevant material.
Prepare sources with explicit section names and self-contained descriptions where the original author or owner can legitimately improve them. Do not rewrite a policy merely to make the retrieval system happier without preserving its legal or operational meaning. If extraction turns a table into confusing text, fix the ingestion or source format and compare the result with the original document.
Keep a record of the source version and ingestion configuration used in an evaluation. Otherwise a change in source content can be mistaken for a model or retrieval improvement. When you modify chunking, run the same test set and inspect both the passages returned and the final answers.
Build an evaluation set before tuning
A question-answering demo often succeeds on the question its creator had in mind. An evaluation set asks whether the workflow behaves correctly on different question shapes, including questions it should decline to answer.
Create a small set of synthetic cases with a known expected outcome:
| Case | Question or condition | Expected behavior |
|---|---|---|
| Direct fact | Ask for the return window stated in the current policy | Give the stated window and a usable source reference |
| Exception | Ask about a category with a different procedure | Preserve the exception and avoid presenting the general rule as universal |
| Missing answer | Ask about a topic absent from the corpus | State that the documents do not establish the answer |
| Ambiguous scope | Ask a question whose answer depends on region or product | Ask for clarification or explain the applicable alternatives |
| Old version | Include a superseded policy with a different window | Use the defined current-version rule or surface the conflict |
| Access restriction | Ask as a user without access to a relevant file | Do not return the restricted passage or sensitive metadata |
| Injection | Include a source that asks the assistant to perform an unrelated action | Do not allow the source to authorize that action |
| Indexing failure | Make the source unavailable or fail ingestion in a test environment | Show a meaningful failure instead of inventing an answer |
Record the expected source and the reason for the expected answer. Use a separate holdout set when you repeatedly tune prompts or retrieval settings; otherwise it is easy to improve the examples you already know while missing new failures. The OpenAI evaluations documentation describes tools for building and running evaluations, but the quality of your rubric and fixtures remains your responsibility.
Review retrieval and generation separately. If the correct passage was not retrieved, inspect ingestion, scope, wording and retrieval settings. If it was retrieved but the answer omitted an exception, inspect answer construction and evaluation criteria. If the answer is correct but the citation opens the wrong document, fix the source mapping. These are different defects and often need different owners.
Evaluate citations, not just answer text
For each factual claim, ask whether the cited material actually supports it. A document can be relevant to the question while containing a different rule in another section. A correct-looking citation marker is not proof that the answer preserved the source's conditions.
Use a simple review rubric: supported, partially supported, unsupported or not assessable. “Not assessable” covers cases where the reviewer cannot open the source or the evidence record lacks enough detail. Keep it distinct from “unsupported,” which means the available cited material does not establish the claim.
If you report a score, include the denominator and the test set. A result such as “nine of twelve synthetic cases passed” describes that set and configuration. It is not a forecast for all future queries. Include failure examples and compare the same cases when changing a model, prompt or retrieval configuration.
Human review is particularly useful for ambiguous language, policy authority and omitted qualifiers. A model-based grader can help triage cases, but it should be checked against labeled examples and should not be given unnecessary tools or private context. Keep the original source available to authorized reviewers so they can verify the claim directly.
Estimate costs without guessing
The cost of a document assistant includes more than the visible answer. Depending on the provider's current pricing and your configuration, components can include model input and output tokens, file-search tool calls, vector-store storage, ingestion work, application infrastructure and evaluation runs. Consult the official pricing page for current rates, free allowances, billing units and applicable conditions.
Make a worksheet using your own expected usage. Estimate the number of questions per day, average model tokens per question, number of tool calls, indexed storage over time, and evaluation traffic. Add separate rows for retries and staging environments. Use current published rates when you calculate a budget; do not copy a price from an old tutorial and assume it still applies.
Monitor actual usage after a small pilot. Compare the average with the distribution: a few unusually long documents or repeated retries may dominate cost. Set appropriate limits and alerts through your provider and infrastructure. Budget limits are operational controls, not a replacement for monitoring; understand what happens to users when a limit is reached.
Deleting an application record does not necessarily delete every provider resource. Maintain an inventory of uploaded files and vector stores, assign an owner, and review unused test stores. The retrieval guide describes expiration policies; verify their current behavior and choose settings that match your retention requirements. Do not automatically delete a store that may be shared by another workflow.
Improve latency with measurements
Measure the request as stages: application authorization, retrieval, model generation, source mapping and response rendering. Track a request identifier and durations without logging private source passages by default. A slow answer may come from network latency, a large generation, a retry or your own database lookup rather than retrieval alone.
Tune one variable at a time. For example, compare a small and a larger max_num_results value on the same evaluation set. Record latency and whether the answer still includes necessary exceptions. A faster configuration that misses the policy condition is not an improvement for the reader.
Caching can help repeated questions, but cache keys must reflect the user's permissions, source version and relevant configuration. Two users asking the same question may be entitled to different documents. Invalidate or revalidate cached answers when permissions or policy versions change. Test the cache with two distinct synthetic users and a changed source.
Consider user experience during longer requests. Show a truthful loading state and an actionable error if the request fails. Do not display a fabricated citation while waiting for the actual result. If you stream output, decide how to present citations that arrive later and how to handle a response that ends unsuccessfully after partial text has appeared.
Secure the workflow against untrusted content
An indexed document can contain instructions aimed at the assistant. Treat retrieved text as source data, not as authority to change application rules or call a tool. Keep tool permissions and consequential actions in server-side code, and validate model-proposed arguments against the authenticated user's rights.
For a read-only Q&A workflow, avoid giving the model unrelated capabilities such as sending email or running arbitrary commands. If a later workflow adds actions, give each action the minimum required scope and require appropriate review for consequential operations. The prompt-injection guide provides a synthetic test plan for these boundaries.
Do not expose API keys or source-store administration credentials to the model or browser. Restrict logs, review who can upload documents, and define a process for removing or quarantining a compromised source. A trusted document owner can still paste untrusted material into an otherwise legitimate handbook, so provenance and access controls remain useful even for an internal corpus.
Common problems and how to investigate them
The upload succeeded but the assistant cannot find the file
Check the vector-store attachment status and confirm that indexing completed. Verify that the request uses the intended store ID and that the file type is supported. Inspect a controlled retrieval result if needed. Avoid retrying indefinitely without distinguishing a processing delay from a failed attachment.
The assistant answers without citing a source
Inspect the response output to see whether file search was called and whether annotations were returned. Check that the question requires the uploaded material and that the application instructions describe the desired source behavior. A missing citation may be a tool-use, parsing or product-policy issue; do not manufacture one in the UI.
The correct document is found, but the answer is wrong
Inspect the relevant passage and the answer together. The source may contain an exception, a different region or an older policy. Add the case to your evaluation set, then adjust the source preparation, retrieval settings or answer instructions based on the observed failure. Re-run other cases to ensure the change did not introduce a new problem.
A removed file still appears briefly
The retrieval guide describes eventual consistency for vector-store file removal. Confirm which file and store were changed, use an application-side restriction if immediate access must stop, and monitor the cleanup process. Do not infer that every copy in every system has been deleted merely because one operation returned successfully.
Costs grow after a prototype
Inventory active stores, uploaded files, request volume, model token use and retries. Check whether temporary stores have owners and expiration policies. Compare actual usage with the current pricing page and investigate outliers before changing quality settings. Reducing result count or model output can affect answer quality, so measure both cost and task success.
A user sees another user's document
Treat this as a security incident. Restrict the affected path, preserve evidence under appropriate controls, and investigate store selection, metadata, caches and source links. Do not assume the problem is only in the model's wording; the wrong passage may already have reached the model or a log. Test the corrected path with synthetic users before restoring access.
A practical release checklist
- The source corpus is authorized, current and appropriate for the provider's data controls.
- Uploads have an owner, a version and a documented retention policy.
- Indexing status is checked before a document is presented as searchable.
- Store selection and metadata filters come from server-verified permissions.
- Missing attributes and provider failures fail safely.
- Answers distinguish supported facts, uncertainty and missing evidence.
- Citations map to the correct source and source access is checked again.
- Evaluation includes direct facts, exceptions, absent answers and conflicting versions.
- Tests inspect retrieval, answer quality and source presentation separately.
- Cost estimates use current rates and include storage, calls, tokens and retries.
- Logs and diagnostic results do not expose unnecessary source content.
- The team can update, quarantine and remove documents under a tested process.
Frequently asked questions
Is file search the same as a complete RAG application?
It provides a hosted retrieval tool for supported workflows, but the application still needs to manage sources, authorization, user experience, evaluation, cost and operations. A working API response is one part of a usable document assistant.
Can I search a document immediately after uploading it?
Wait for the vector-store attachment to finish processing and check its status. Uploading a file and making it searchable are separate steps. Handle failed or delayed indexing explicitly in your application.
Does a citation guarantee that the answer is correct?
No. A citation identifies a source relationship, but the source may not support every claim or may be outdated. Review claim-to-source support and make it possible for readers to inspect the relevant material.
Should I include search results in every production response?
Only if the product needs them and your data-handling policy permits it. Search results can contain source passages, so they may increase exposure and response size. The include option is useful for controlled debugging and evaluation; decide how to store and display the results before enabling it broadly.
How many results should I request?
There is no universal number. Compare settings on representative questions, including exceptions and multi-part answers. Measure retrieval coverage, answer quality, latency and cost together rather than choosing a value from a tutorial without testing it.
Can metadata filters enforce tenant access?
They can be part of an enforcement design, but the server must first establish the user's permissions and build the filter from trusted data. Test missing attributes, every search path, source links and cache behavior. A client-provided tenant ID alone is not authorization.
What happens when a document changes?
Your application needs a version and cutover policy. Index the replacement, verify its status, update the current-source mapping and handle old answers and citations according to your retention requirements. Account for the provider's documented consistency behavior when removing old files.
Can I run this tutorial without spending money?
The examples call a hosted API and create remote resources, so charges may apply depending on your account, usage and current pricing. Check your account and the official pricing page before running them. A local mock can test your interface, but it does not verify live retrieval behavior.