# 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.

Original: https://fdetimes.net/en/guides/rag-chat-citations-feedback-button/

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`.

```ts
// 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:

```ts
// 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.

```json
{
  "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.

## Step 3: only real ids become links

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.

```tsx
// 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.

**Key point:** A fabricated citation must never look like a real one, even if the screen looks worse for it.

## 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.

```tsx
// 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.

**Try this week:**

- Give every chunk in your existing RAG store a stable id such as kb://article-1234, then check that the ids survive re-indexing
- Write a component that renders [id] tags as links and test it on an answer with an invented id, to make sure it shows up only as plain text
- Attach the trace ID to message metadata, make a "wrong answer" button post to a feedback endpoint, then read the first 10 responses

## Sources

- [Search results](https://platform.claude.com/docs/en/build-with-claude/search-results.md)

- [Building an AI chat app with RAG and source citations on Vercel](https://vercel.com/kb/guide/building-ai-chat-app-with-rag-and-citations-on-vercel.md)

- [Chatbot (AI SDK UI)](https://ai-sdk.dev/docs/ai-sdk-ui/chatbot.md)

- [User Feedback](https://langfuse.com/docs/observability/features/user-feedback)
