This guide was prepared with AI assistance using the linked documentation. Code examples are illustrative; verify them against your environment and current API documentation before use.
An assistant answers a deadline question: “Applications close on 15 May.” It adds a link to a policy document. The link opens the right file, but the date appears in a section about a different application type. The answer looks well sourced and is still wrong.
That distinction shapes the entire citation design. A search result is a candidate source. A file annotation connects a response to a document. Neither, by itself, proves that a particular sentence follows from a particular passage. A useful citation system helps readers inspect that connection and tells them when the evidence is missing, conflicting, stale or unavailable.
This guide is for product engineers building retrieval-augmented generation (RAG) experiences. It follows a fictional application-deadline example through retrieval, answer construction, display, and evaluation. The dates, documents and review outcomes in the walkthrough are synthetic. The code shows application-level structures and tests; adapt it to your actual provider response and do not treat it as a complete production integration.
What a good citation lets a reader do
A citation earns its place when it answers three questions: Which source supports this claim? Where in that source should I look? Can I inspect it now? A file title alone answers only part of the first question. A link to a page or highlighted passage helps with the second, provided the passage is actually the evidence for the claim. Access checks and clear unavailable states address the third.
Start with a small contract for your product:
- Answers distinguish source-supported statements from synthesis and uncertainty.
- Every citation points to a source the reader can access, or clearly says why the source is unavailable.
- The source title, version and relevant location are shown when your system knows them.
- Missing evidence leads to an explicit limitation or a request for clarification, not an invented source.
- Conflicting evidence is visible rather than silently compressed into one definitive answer.
The contract should match the underlying data. If your retrieval service returns only file-level references, do not display “verified on page 4” unless your application has independently obtained and checked that page location. A citation interface must not imply more precision than the system possesses.
Retrieval, annotation and evidence are different things
RAG typically starts with a query, searches a collection of documents, and passes some retrieved material to a model to help it answer. A retrieval result might be highly relevant and still not support the generated wording. It might concern the wrong date, a different region, an outdated version, or an exception that changes the rule.
The following concepts are useful to keep separate:
| Item | What it tells you | What it does not establish |
|---|---|---|
| Retrieved result | A search system returned a source or passage for this query | The answer used it correctly or the user can still open it |
| File annotation | A provider associated part of its output with a file | The cited file proves every statement in the surrounding paragraph |
| Claim-to-evidence link | Your application associated a claim with a source or span | The association is necessarily correct without review or testing |
| Source preview | The reader can inspect available source material | The displayed excerpt contains all context needed to interpret it |
| Reviewer judgment | A person or evaluation process assessed a particular case | Every future answer from the system will be correct |
OpenAI's file search guide documents file citations and an option to include search results in the response. Read the guide and the reference for your SDK version before mapping provider fields into your own schema. Search results and output annotations serve different purposes; your adapter should not assume they are interchangeable or always present.
The retrieval guide describes direct vector-store search. Direct retrieval can be useful when you need to inspect search results before generation. Hosted search can reduce the amount of integration code you write. In either design, make your evidence contract explicit and validate the actual response shapes you receive.
Walk through a deadline question
Suppose a reader asks: “When do applications close?” Your collection contains a fictional program handbook with two deadlines: a standard application closes on 15 May, and a scholarship application closes on 1 April. The year and time zone appear elsewhere in the handbook. An old version lists a different date.
A useful assistant should first notice that the question is ambiguous. It can ask which application the reader means, or it can give both dates with their conditions and source references if the evidence is sufficient. If the current document does not state a year or time zone, the answer should not invent them. A reasonable response might say: “The handbook lists 15 May for standard applications and 1 April for scholarship applications. It does not specify a year in the retrieved passage.”
The reader then needs to inspect the handbook. If your system knows the correct section or page, the citation can open there. If it only knows the file, use an honest label such as “Open the program handbook” and show a source preview only when that preview is available. Keep the document version visible when it matters, because the old handbook may otherwise appear to contradict the answer.
This example is deliberately simple, but it exposes several design decisions: how to identify the current source, how to preserve qualifiers, how to link multiple claims to different passages, and how to behave when the source does not answer the full question. Write expected behavior for these cases before choosing a citation component.
Design an evidence record your application can understand
Normalize provider output into an internal record before rendering it. That record should distinguish the source itself from the claim that refers to it. Your provider might identify a file but not a stable paragraph. Your source catalog may know the version but not the page. Optional fields represent that uncertainty without forcing the UI to fabricate a location.
The following TypeScript is an application type sketch. It is not an OpenAI SDK response schema, and the illustrative IDs are local to the application. Use your own validation, authorization and storage layers.
type SourceRef = {
id: string;
title: string;
version?: string;
locationLabel?: string;
sourceUrl?: string;
};
type Claim = {
text: string;
sourceIds: string[];
};
type AnswerRecord = {
claims: Claim[];
sources: SourceRef[];
status: "supported" | "partial" | "insufficient" | "conflicting";
};The status values are product choices. They are not a substitute for an evaluation rubric and do not turn model self-assessment into a guarantee. A system could mark an answer as “supported” only after a specific process runs; another product may avoid that label entirely. The important part is to define what a status means and avoid presenting an unverified model judgment as a fact.
Keep source identity stable across rendering and storage. A filename is convenient for display but can change or collide. A document identifier plus a version can point to a more specific record, though your source catalog must enforce its meaning. If you display an excerpt, record how the excerpt was obtained and avoid silently switching it to text from a later document version.
When the provider gives offsets, check what those offsets refer to: characters, bytes, tokens, output text or source text. Unicode, normalization and text transformations can make apparently simple offsets misalign. Treat an offset as usable only after validating its bounds and confirming the exact string it indexes. If validation fails, fall back to a less precise source link or a visible unavailable state.
Extract citations without confusing them with search results
Your adapter has two jobs: preserve what the provider actually returned and reject unsupported assumptions. Parse the response using the installed SDK's types or schema. Check which output items are messages, tool calls or other content before reading them. A response may contain no file annotations, and a successful API call does not imply a successful search.
The file-search guide shows that annotations can identify files, while included search results expose additional retrieval information when requested. The precise fields and availability can change. Avoid hard-coding a sample response from a blog post as a universal parser. Pin and review your dependencies, maintain test fixtures from the response shape you use, and inspect release notes when upgrading.
Here is a provider-independent mapping sketch. ProviderAnnotation is a placeholder that your adapter must replace with the actual validated shape. The function does not infer a page number or claim that a source supports a statement; it preserves only fields the application has already validated.
type ProviderAnnotation = { fileId: string; filename?: string };
function mapAnnotation(item: ProviderAnnotation): SourceRef {
return {
id: item.fileId,
title: item.filename || "Source document",
};
}One implementation pitfall is assuming the list of retrieved files is the list of sources used in the answer. Search may return a passage that the model ignores, or the final response may contain a claim unsupported by any returned passage. Conversely, a file annotation may not give enough detail to construct a precise excerpt. Show only the evidence your pipeline can defend.
Another pitfall is relying on display text as an identifier. Two files named policy.pdf are not necessarily the same document. Use your application's stable ID and re-resolve a source through a trusted catalog. When a provider reference cannot be mapped safely, show that the citation is unavailable and retain a diagnostic record for the team.
Connect claims to evidence at the right granularity
An answer often contains several claims. “The deadline is 15 May, the fee is waived, and decisions arrive in June” may require three separate passages. A single citation at the end of the paragraph can imply that all three facts come from one source even when only the deadline is supported.
Break the answer into independently reviewable claims when the task demands it. Attach references close to the supported statement. Where multiple sources jointly support a conclusion, let readers open each source and explain the relationship: one may state the rule and another may define an exception. Do not attach an unrelated source merely to make every sentence look cited.
Granularity is a product tradeoff. Citation markers after every few words can make an answer difficult to read. A citation after a short sentence may be enough if that sentence has one coherent claim. A complex paragraph with several conditions benefits from smaller units or a source panel that explicitly lists which statements each source supports.
Separate direct quotation from paraphrase. If you show quotation marks, the displayed text should match the source under your stated normalization rules and preserve enough context to avoid changing its meaning. If your pipeline has rewritten or summarized the passage, label it as a summary. Do not manufacture quotation marks around model-generated text.
For calculations, show the inputs and the operation. If a source states a fee of 100 units and another says a 20 percent discount applies, the answer can show the arithmetic and cite both inputs. The computed value is your application's synthesis; the underlying documents may not contain that exact number. Test rounding rules and conditions separately.
Build a useful source panel
A source panel can make an answer easier to inspect without forcing the reader to open a long document immediately. A practical panel might show the document title, version or date where known, a short excerpt, and an action to open the full source. If the system cannot locate an excerpt, say “Open document” instead of showing a generic paragraph as if it were the cited passage.
Give links descriptive names. “Program handbook, standard applications section” tells a screen-reader user more than “Source 1.” Make citation controls reachable by keyboard, preserve visible focus, and ensure the relationship between a claim and its source is understandable without relying solely on color. The W3C Web Accessibility Initiative publishes guidance for accessible web content; test the actual component with assistive technology and keyboard navigation.
Make opening behavior predictable. If a citation opens a panel, label the button as an action. If it navigates to a document, use a link. If the source opens in a new context, tell the reader where appropriate. When the panel closes, return focus to the triggering control. A citation should help readers follow evidence, not trap them in a visually appealing but inaccessible overlay.
Be careful with highlights. If you cannot reliably map a search chunk to a PDF page, don't draw a highlight over an unrelated region. An approximate location may be useful, but label it as approximate and provide a way to open the full document. A broken highlight is worse than a clear file-level link because it creates false confidence in the passage.
Make source access a fresh authorization decision
A citation can outlive the permission that allowed the answer to be generated. A user may change roles, leave a workspace, or lose access to a document. When someone opens the citation, the source endpoint should check current access again. Possession of a citation URL is not proof of authorization.
Avoid revealing private information in an unavailable state. Depending on your product's policy, a generic “This source is unavailable” may be safer than showing a restricted filename. If the reader previously had access and your policy permits a more detailed explanation, tell them how to request access without exposing the document to someone else.
This article focuses on evidence and the reader experience. For a deeper treatment of tenant scope and retrieval controls, see multi-tenant RAG authorization. The key connection here is practical: a citation must remain useful without becoming a back door around the source's normal access rules.
Handle no answer, partial answer and conflict
Not every question has an answer in the permitted collection. If search returns nothing useful, say that the available sources do not establish the answer. Offer a next step: ask the user to clarify the application type, broaden the authorized collection if appropriate, or contact the document owner. Avoid a confident answer assembled from the model's general knowledge when the product promises answers grounded in a particular collection.
Partial evidence deserves a partial answer. If the handbook supplies dates but omits the year, show the dates and identify the missing year. If a policy describes who qualifies but not the amount, do not infer a number from an older policy. Readers can then decide whether the answer is sufficient for their task.
Conflicting documents require an explicit rule. A newer file is not automatically authoritative merely because its upload timestamp is later; it may be a draft or an unrelated revision. Use source metadata and business rules when available, or present the conflict and route the question for human review. Show the relevant titles and dates if the reader is allowed to see them.
A retrieval score is not a calibrated probability that a claim is true. Scores can help select or rank candidate results, but a threshold that works for one corpus or query pattern may fail for another. Evaluate any threshold on representative cases, including cases where the correct behavior is to abstain. Report the uncertainty honestly rather than translating a raw score into “95% confidence.”
Keep versions and freshness visible
Documents change. A citation generated in March might point to a policy that was replaced in April. Decide whether an old answer should keep pointing to the exact version it used, point to the current document with a warning, or be regenerated. The choice depends on whether the product is a historical record, a current-policy assistant, or both.
Store enough provenance to explain the answer later: a source identifier, the version or checksum when available, the time the answer was produced, and the retrieval or corpus configuration needed by your evaluation process. Do not imply that a source was reviewed on a date merely because it was indexed then. “Indexed on” and “effective from” describe different events.
Consider a fictional travel policy updated on 1 June. An answer produced in May can remain a valid historical record if the interface clearly shows which version supported it. A new question in July should not silently reuse the May answer from a cache if the current policy has changed. Cache invalidation and document versioning are therefore part of evidence quality, even though neither makes a claim correct on its own.
When a source is deleted or replaced, define what happens to citations and stored excerpts. Some products must retain an audit record; others must delete cached text promptly. Apply your actual retention and access requirements, and do not promise permanent links or complete deletion unless the storage and backup processes support those promises.
A compact evaluation dataset
Build an evaluation set from representative question types, using synthetic or appropriately approved material. Each case should include the question, the permitted source set, the expected answer or expected limitation, and the evidence a reviewer should inspect. Keep versioned fixtures so a change to a prompt, chunking strategy or model can be compared against the same baseline.
Start with cases that expose different failure modes:
| Case | Fixture | Expected behavior |
|---|---|---|
| One supported fact | Current handbook states one deadline | Answer gives the deadline and links the supporting source |
| Ambiguous request | Handbook lists standard and scholarship dates | Ask which type or show both with their conditions |
| Missing year | Passage supplies a day and month only | Do not invent a year; identify the gap |
| Conflicting versions | Old and current policies disagree | Apply a documented authority rule or expose the conflict |
| Unsupported claim | The source mentions a date but no fee | Do not assert a fee as sourced |
| Restricted source | A relevant file exists but the reader lacks access | Do not reveal its content or restricted metadata |
| Deleted source | An old citation refers to a removed file | Show the defined unavailable or historical state |
| Wrong passage | Correct file, different section | Flag the claim as unsupported by the displayed evidence |
The table is a starting point, not a claim about your application's performance. Add cases from actual support questions only when their use and retention are authorized. Separate development examples from a holdout set so you can check whether changes generalize beyond the cases used during tuning.
OpenAI's evaluation documentation discusses building and running evaluations. Your chosen evaluation service is only one piece of the process. The team still needs a clear rubric, access to appropriate evidence, and a method for reviewing disagreements.
Judge retrieval and answer quality separately
When a test fails, identify which stage failed. Did search omit the source? Did it return the right file but the wrong passage? Did the model ignore a relevant passage, add an unsupported detail, or attach the wrong reference? Did the source endpoint deny access correctly but the UI mislabel the failure? A single pass/fail score hides these distinctions.
Use separate review questions:
- Retrieval: Was the necessary, permitted material available in the result set?
- Attribution: Does each cited source correspond to the claim it is attached to?
- Support: Does the cited material actually establish that claim, including its qualifiers?
- Completeness: Does the answer omit a condition that changes the reader's decision?
- Access: Can the authorized reader inspect the source, and are denied readers protected?
- Presentation: Does the interface accurately describe the precision and freshness of the reference?
For a small evaluation set, human review can be more informative than a sophisticated metric without clear labels. Two reviewers can independently assess difficult examples and discuss disagreements. Record the reason for each decision: “wrong application type” is actionable; “bad answer” is not. Use a model-based grader as an aid only after checking how it behaves on your own edge cases, and keep the original source material available to authorized reviewers.
If you report rates, state the denominator and the dataset. “Eight of ten synthetic deadline cases had correctly attributed citations” is a description of that test set, not a prediction for all production traffic. A small sample can expose serious bugs, but it cannot establish a reliable overall error rate by itself.
An example review rubric
Use a simple, repeatable rubric before inventing a composite score. For each claim, reviewers can choose one of four labels:
- Supported: the cited material establishes the claim and preserves its important conditions.
- Partially supported: the source supports part of the claim, but a qualifier or second fact is missing.
- Unsupported: the cited material does not establish the claim, even if it is thematically related.
- Not assessable: the reviewer cannot access enough source material or the evidence record is incomplete.
The distinction between unsupported and not assessable matters. A broken source link does not prove the claim is false; it means the reviewer cannot verify it through the supplied evidence. Conversely, a working link to the wrong section should not receive a passing label merely because the file is relevant.
Review source versions as well as text. A claim may accurately quote an outdated policy and still be unsuitable as the answer to a question about the current policy. Record whether the document was authoritative for the task and time described. If authority cannot be established, mark that uncertainty rather than relying on a filename or upload date.
Local assertions for evidence records
Unit tests can catch malformed records before the UI renders them. The following is an illustrative local test for the application types above. It checks referential integrity only; it does not prove that a source supports the claim or that a user is authorized to open it.
function hasResolvableReferences(answer: AnswerRecord): boolean {
const known = new Set(answer.sources.map((source) => source.id));
return answer.claims.every((claim) =>
claim.sourceIds.every((id) => known.has(id)),
);
}
const example: AnswerRecord = {
status: "partial",
claims: [{ text: "The handbook lists a May deadline.", sourceIds: ["doc-1"] }],
sources: [{ id: "doc-1", title: "Program handbook" }],
};
console.assert(hasResolvableReferences(example));Add tests for duplicate identifiers, empty source titles, unknown references, malformed locations and unsupported URLs. If a claim has no source IDs, your rendering logic should make that visible or omit the claim according to your product contract. A function that returns true for an empty list is mathematically consistent, but it might be the wrong policy for your application.
Integration tests need to exercise more: a source link that works for an authorized user, a denied user, a replaced document, and a response where the provider returns no citation. Browser tests should confirm that a keyboard user can open and close the evidence panel and that the visible source matches the record. Use synthetic documents so test output does not leak customer data.
Measure changes without hiding tradeoffs
Suppose a chunking change retrieves the relevant document in more test cases but also leads the model to combine unrelated passages. Reporting only retrieval improvement would hide a decline in answer attribution. Compare retrieval, citation support, abstention, latency and access failures separately for the same set of questions.
Record the configuration with each evaluation: corpus version, retrieval settings, model identifier, prompt version, evaluation date, and reviewer or grading method. Avoid logging private source text unless your policy allows it. If a provider response changes after an SDK upgrade, rerun parser fixtures and source-link tests before treating an apparent quality change as a model improvement.
Use a small release gate appropriate to the risk. A low-stakes internal search assistant might accept a staged rollout with human feedback. An assistant used for consequential decisions needs stronger review, escalation paths, and domain-specific controls. In either case, design the interface so users can inspect evidence and report a suspected mismatch.
Common citation mistakes
Citing a relevant file that does not support the sentence
The handbook contains a deadline, but not for the application type named in the answer. Check the claim and passage together. Include a “same file, wrong section” case in your evaluation set, because a file-level relevance check will miss it.
Showing every retrieved file as a source
Search results can contain useful candidates that the answer never used. Label a list as “retrieved documents” if that is what it is. A “sources for this claim” label requires a defensible association between the claim and those documents.
Inventing precision
The provider supplies a file reference, so the UI guesses a page number or highlights the first matching date. Preserve the file-level reference and clearly state that a precise location is unavailable. Add finer locations only when your ingestion and mapping process can produce them reliably.
Treating a similarity score as factual confidence
A high search score may mean the text is similar to the query. It does not establish that the document is current, applicable or authoritative. Keep relevance separate from evidence support and measure both on realistic cases.
Linking to an inaccessible source without explanation
Readers click a citation and encounter a confusing error. Recheck access, show a clear unavailable state, and provide the appropriate next step. Do not reveal a restricted title merely to make the error more descriptive.
Hiding a conflict to produce a tidy answer
Two sources disagree, so the model picks the more fluent statement. Apply an explicit authority rule or show the conflict. A clean paragraph is not worth a false sense of certainty.
Dropping conditions from a quotation
A passage says a deadline applies only to one region, but the answer presents it as universal. Test whether the claim preserves scope, dates, exceptions and units. Quote enough context to avoid changing the meaning.
A practical rollout sequence
Begin with one workflow and a small collection whose ownership and update process are understood. Define the evidence contract and the source access policy. Create synthetic examples covering a clear answer, an ambiguous question, a missing fact and a conflict. Implement the simplest source display that accurately reflects the information you have.
Next, build an adapter around the real provider response and store sanitized evaluation fixtures. Test parser failures and source availability. Have reviewers inspect claim-to-source relationships before adding a visual “supported” badge. If the team cannot explain what a badge means or how it is checked, remove it until the criterion is defined.
Then test the full reader journey. Ask a question, inspect the answer, open each source, navigate back, and repeat after a source is changed or access is removed. Include mobile layout, keyboard navigation and a screen reader in your checks. A correct backend record can still produce a misleading or unusable interface if labels, ordering or focus behavior are wrong.
After release, establish a feedback route. A reader should be able to flag “this source does not support the answer” without copying confidential material into a public issue. Route the report to an authorized reviewer, track the underlying cause and add a regression case when appropriate. A feedback button alone is not a process; someone must own review and follow-up.
Checklist for a citation review
- The answer distinguishes claims, synthesis, uncertainty and direct quotations.
- Each displayed citation maps to a source actually returned or otherwise verified by the application.
- The interface does not invent page numbers, offsets, quotations or confidence values.
- Source titles, versions and locations are shown only when known and permitted.
- The reader can access the source through a current authorization check.
- Missing, partial and conflicting evidence have clear product states.
- The source preview retains enough context to avoid misleading the reader.
- Evaluation cases separate retrieval, attribution, support and presentation failures.
- Tests cover missing annotations, malformed references and changed source permissions.
- Keyboard and assistive-technology users can reach and understand the citation controls.
- Source versioning, cache behavior and retention follow a documented policy.
- A reviewer can report and investigate a mismatch without unnecessary data exposure.
Frequently asked questions
Does a citation mean the answer is true?
No. A citation gives the reader a route to evidence; the cited material may be outdated, inapplicable or unrelated to a particular claim. Inspect the source and its context, and evaluate whether it actually supports the statement.
Should every sentence have a citation?
Not necessarily. A greeting or a transition may not need one, while a sentence containing several factual claims may need more than one. The useful unit is the claim the reader might want to verify. Design a citation density that preserves both traceability and readability.
What if the provider returns a filename but no page number?
Show a file-level link and label it accordingly. You can add a location later if your ingestion pipeline can map a citation to a stable page or section. Do not infer a precise location from a filename or from an unvalidated text match.
What if the source is unavailable after the answer was generated?
Recheck access and follow your documented retention policy. Explain that the source is unavailable without exposing restricted information. If the answer is historical, indicate whether it reflects an earlier source version; if the task requires current information, consider asking the user to rerun the question after the source is restored or updated.
Can a model evaluate its own citations?
A model can assist evaluation, but its judgment should be checked against a labeled sample and the source material. It can miss qualifiers or confidently approve a weak connection. Use deterministic checks for IDs and access, and involve human review for cases where factual support or authority is difficult to judge.
How should I handle two sources that disagree?
Use a documented business rule if one source is demonstrably authoritative for the question. Otherwise show the conflict and its context, or route the question to a person who can resolve it. Avoid silently choosing whichever statement sounds more plausible.
Are retrieved excerpts always safe to display?
No. The user must be authorized to see the underlying source and the excerpt must comply with your retention and display policies. The excerpt can also omit a condition that changes its meaning, so review how chunks are selected and presented.
