FDE Times dataFDE jobs open 928▲21 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 85Companies hiring 200Remote-friendly 24%Median US pay $200kTop hirer Databricks 107
中文VI

The newspaper of the Forward Deployed Engineer

Guides

Build a RAG chat where fake citations give themselves away

Clickable sources expose invented references, and a "wrong" button tied to the trace turns every frustrated user into a test case.

ShareLinkedInFacebookX

In brief

  • A citation becomes a link only when its id matches a retrieved source, so a citation the model invents shows up as plain text and is visibly broken.
  • With Anthropic's search_result, citations are off by default, every result in a request must use the same setting, and a prompt demanding JSON only can strip citations out.
  • The "wrong" button must carry the trace ID of that exact answer, so the feedback is stored as a score attached to the trace.
GraphicFrom retrieved chunk to eval case
  1. 1Assign stable idsEach chunk carries an unchanging string, such as kb://article-1234
  2. 2Stream source partsThe route retrieves, writes the sources, then merges the model stream into the same response
  3. 3Model cites [id]Each claim carries an id tag, or citations come from search_result
  4. 4Only matching ids linkAn id the model invents matches no source and renders as plain text
  5. 5"Wrong answer" buttonSends the trace ID in metadata, stored as a score attached to the trace
  6. 6Becomes an eval setLow scores reveal quality problems and what to fix first

Fabricated citations cannot become links, and every wrong answer is recorded along with its trace.

Graphic: FDE Times

Vercel’s guide to building a RAG chat contains a design decision worth copying: if the model invents an [id] tag, the tag matches no source and stays as plain text. A fake citation looks broken instead of passing for a trustworthy link.

That small detail answers the question every client asks during a RAG demo: “How do I know it isn’t making things up?” This guide builds a React interface that can answer it. Every citation is clickable and opens the right source document, and every answer has a “wrong” button wired straight to its trace.

For an FDE, this is first-week work at a client site. Business users do not read logs. They click on citations, and when something is wrong, they click the button. Langfuse states the purpose of this feedback loop plainly: find quality problems, build better evals and decide what to fix first.

What you need

You need a React app using the AI SDK’s useChat, a server route that handles retrieval, and a document store that has already been chunked. To record feedback, add an observability tool that accepts scores per trace, such as Langfuse.

The code below has been simplified for readability. Check exact field names against the documentation for the SDK version you use.

There are two ways to get citations, and it helps to know both before writing any code:

[id] tags in the text (Vercel pattern) Anthropic’s search_result
Who attaches citations The model writes [id] following the system prompt The API returns citations on text blocks
Prompt Must tell the model to cite after every claim No special prompt needed
Guard against invention The UI links only ids that match a source Each citation carries the source and title you supplied
Use when You want to stay independent of the model provider You already run on Claude

Step 1: a stable id for every chunk

The whole mechanism rests on an identifier that never changes. Anthropic’s documentation says the source field accepts any stable string: a URL, or an internal code such as kb://article-1234.

// Simplified: every retrieved chunk carries a stable id
type Chunk = {
  id: string;     // e.g. "kb://article-1234"
  title: string;
  url: string;    // what the UI opens when the user clicks
  text: string;
};

Check: re-index the document store once, then compare the id of the same passage before and after. If ids are generated from chunk sequence numbers, links in old conversations will point to the wrong place after the very first re-index.

Step 2: the route streams sources first, the answer second

In Vercel’s pattern, the chat route itself does three things: it retrieves, writes the source parts, then merges the model’s stream into the same response. The client therefore holds the list of real sources before the first word of the answer appears.

The system prompt tells the model to mark its source right after each claim. It can be written like this:

// Simplified: build the context with ids so the model can cite them
const system = `Answer only from the sources below.
After each claim, cite its source with the [id] tag.
${chunks.map(c => `[${c.id}] ${c.text}`).join("\n")}`;

Check: call the route with a question whose answer is in the store, and confirm that source parts arrive in the stream before the text.

Step 2b: use search_result if you run Claude

With Claude, you pass chunks in as search result blocks. Claude then cites your content the way it cites web search results: each citation carries the source and title you supplied. You only ask the question, with no extra instructions, and citations appear on the text blocks that draw on that content.

{
  "type": "search_result",
  "source": "kb://article-1234",
  "title": "Refund policy 2026",
  "content": [{ "type": "text", "text": "..." }],
  "citations": { "enabled": true }
}

The structure of the content field above is simplified. The "enabled": true line, however, must stay: citations are off by default, and every search result in a single request must use the same setting.

AI SDK UI splits sources into two kinds of part: source-url for web pages and source-document for documents. The component below collects those parts into a lookup table, then splits the text on the [id] tags.

// Simplified: check source part field names against the AI SDK docs
function Answer({ message }) {
  const sources = new Map();
  for (const p of message.parts) {
    if (p.type === "source-url" || p.type === "source-document") {
      sources.set(p.sourceId, p);
    }
  }
  const text = message.parts
    .filter(p => p.type === "text").map(p => p.text).join("");

  return text.split(/(\[[^\]]+\])/).map((seg, i) => {
    const id = seg.match(/^\[([^\]]+)\]$/)?.[1];
    const src = id && sources.get(id);
    return src
      ? <a key={i} href={src.url} target="_blank">[{src.title ?? id}]</a>
      : <span key={i}>{seg}</span>;
  });
}

The line that matters most is the src ? condition. Any tag missing from the lookup table is printed as plain text.

Check: insert the string [kb://does-not-exist] by hand into a mock answer. If it renders as a link, your filter is broken.

Step 4: the “wrong” button must know which answer it is flagging

A feedback button is only useful if it connects back to the run that produced the answer. The AI SDK lets you attach arbitrary metadata to a message. The documentation uses timestamps or model information as examples, but the same slot can carry a trace ID.

// Simplified: the server attaches traceId to the message metadata
const { messages, regenerate } = useChat();

async function markWrong(message, comment) {
  await fetch("/api/feedback", {
    method: "POST",
    body: JSON.stringify({
      traceId: message.metadata?.traceId,
      value: 0,
      comment,
    }),
  });
}

On the server, the /api/feedback endpoint writes the feedback to the observability tool. In Langfuse, thumbs up/down is stored as a score and linked to the trace. To let the user retry straight away, call regenerate, the function useChat provides to ask the model to process the last message again.

Call regenerate only after the feedback has been recorded. Do it the other way round and the wrong answer vanishes from the screen before anyone has saved it.

Check: click “wrong” on an answer, open the observability tool and confirm the score sits on that answer’s trace, not on the trace of the next one.

Three common mistakes

The most frequent mistake happens when the frontend team wants structured answers. Anthropic’s documentation warns that if the prompt asks for JSON only, the response may contain few or no citations. If you need structure, have the model answer in prose with citations, then build the structure from the blocks on the server.

The second mistake is forgetting "enabled": true, or enabling it for some results and disabling it for others in the same request. Both make citations disappear. The third sits in the UI: printing the raw error on screen when the stream breaks. The AI SDK recommends showing a generic message such as “Something went wrong.” and keeping the details in the logs.

What this looks like at a client site

Say you deploy a policy lookup assistant for a customer service team. On day one, staff will try to catch it out. An answer whose link opens the right clause, plus a “wrong” button they know someone actually reads, usually persuades them more than any accuracy figure on a slide.

After two weeks, every score of 0 is a real test case: a real question, a real answer and a full trace. Filter them out and you have a starter eval set and a fix list, ranked by how much users were genuinely annoyed.

On the career side, when reading FDE or applied AI job postings, look for phrases such as “citations”, “grounding”, “user feedback loop” or “evals”. On a CV, describe the whole closed loop instead of just “built a RAG chatbot”. For example: citations render as links only when the id matches a retrieved source, feedback is stored as a score attached to the trace, and that feedback becomes the eval set.

Every model gets things wrong eventually. What clients remember is whether, when it did, they could tell and could report it.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
4 sources
Read next on the roadmap · Stage 3: Applied AIOne error kills a Step Functions run. Agent approvals need guardrailsCapped retries, deadlines on human waits and a default that blocks the action when nobody replies are what enterprise security teams will ask an FDE to prove.