From the blog

RAG Citations in Elixir: Show Sources for Every AI Answer in Phoenix

By Liam Killingback ·

RAG Citations in Elixir: Show Sources for Every AI Answer in Phoenix

A RAG answer without sources asks the reader for blind trust. The model says the refund window is 30 days, and the user has two options: believe it, or open the PDF and look for themselves, at which point your AI feature has saved them nothing. A small [2] next to the claim, linked to page 14 of the policy document, changes that. The user can check in one click, and you can check too, in code, before the answer is ever shown.

This post builds RAG citations in Elixir from end to end: retrieval that keeps provenance, a prompt that numbers its sources, structured output that carries a supporting quote for every citation, a verifier that rejects citations the model made up, and a Phoenix LiveView that renders the markers as clickable sources. It assumes you already have retrieval working. If you do not, start with RAG in Elixir with pgvector and Postgres and come back.

What a citation has to prove

It helps to be precise about what you are promising. A citation in a RAG answer makes three claims:

  1. The source exists. The marker points at a chunk that was really retrieved for this question, not a number the model invented.
  2. The source says it. The cited chunk contains text that supports the sentence.
  3. The reader can get there. The marker resolves to something a human can open: a document title, a page, a heading.

Models are good at the format and unreliable on the first two. Ask for citations and you will get tidy [1] and [3] markers on almost every sentence, some pointing at chunks that say nothing of the sort, and now and then a [7] when you supplied five sources. So the design rule for this whole post is: the model proposes citations, your code decides which ones survive.

Step 1: Keep provenance through retrieval

You cannot cite what you did not keep. Many first RAG pipelines store only content and embedding, then discover at citation time that nobody knows which page a chunk came from. Store the location when you ingest:

defmodule MyApp.Repo.Migrations.AddProvenanceToChunks do
  use Ecto.Migration

  def change do
    alter table(:document_chunks) do
      add :position, :integer
      add :page, :integer
      add :heading, :text
    end
  end
end

position is the chunk’s order within the document, page is the PDF page it starts on (nil for formats without pages), and heading is the nearest section title. If your splitter does not track these yet, text chunking for RAG in Elixir shows a chunker that carries the heading along.

Retrieval then returns a small struct per hit, with everything the UI will need:

defmodule MyApp.RAG.Source do
  @enforce_keys [:n, :chunk_id, :document_id, :title, :content]
  defstruct [:n, :chunk_id, :document_id, :title, :page, :heading, :content]
end

defmodule MyApp.RAG.Retrieval do
  import Ecto.Query
  import Pgvector.Ecto.Query

  alias MyApp.Knowledge.{Document, DocumentChunk}
  alias MyApp.RAG.Source
  alias MyApp.Repo

  def sources(question, opts \\ []) do
    k = Keyword.get(opts, :k, 5)
    {:ok, vector} = MyApp.Embeddings.embed(question)

    from(c in DocumentChunk,
      join: d in Document,
      on: d.id == c.document_id,
      order_by: cosine_distance(c.embedding, ^vector),
      limit: ^k,
      select: %{chunk: c, title: d.title}
    )
    |> Repo.all()
    |> Enum.with_index(1)
    |> Enum.map(fn {%{chunk: c, title: title}, n} ->
      %Source{
        n: n,
        chunk_id: c.id,
        document_id: c.document_id,
        title: title,
        page: c.page,
        heading: c.heading,
        content: c.content
      }
    end)
  end
end

The important field is n. Sources are numbered once, here, and that number is the only identifier the model ever sees. Do not put database ids in the prompt: models transcribe long ids badly, and a short integer the model gets wrong is easy to detect.

Step 2: Number the sources in the prompt

Format each source as a clearly delimited block with its number:

defmodule MyApp.RAG.Prompt do
  alias MyApp.RAG.Source

  @system """
  You answer questions using only the numbered sources provided.

  Rules:
  - After every sentence that states a fact, add the supporting source
    number in square brackets, like [2]. Use [1][3] for two sources.
  - Only cite source numbers that appear below.
  - For each citation, copy a short exact quote (under 25 words) from that
    source that supports the sentence.
  - If the sources do not contain the answer, say so and cite nothing.
  """

  def system, do: @system

  def user(question, sources) do
    blocks =
      Enum.map_join(sources, "\n\n", fn %Source{} = s ->
        "[#{s.n}] #{s.title}#{location(s)}\n#{s.content}"
      end)

    "Sources:\n\n#{blocks}\n\nQuestion: #{question}"
  end

  defp location(%Source{page: nil}), do: ""
  defp location(%Source{page: page}), do: " (page #{page})"
end

Two details matter more than they look. First, the “say so and cite nothing” rule gives the model a way out. Without it, a model with weak sources will still produce a confident answer and attach whichever numbers are nearest. Second, the exact quote is what makes verification possible in the next step. A bare [2] can only be checked for existence. A quote can be checked against the text.

Step 3: Ask for structured output

You want the answer text (with inline markers) and the list of quotes as separate fields. OpenAI’s structured outputs guarantee the shape, so there is no fragile parsing of a prose answer:

defmodule MyApp.RAG.Answer do
  alias MyApp.RAG.Prompt

  @schema %{
    type: "object",
    additionalProperties: false,
    required: ["answer", "citations"],
    properties: %{
      answer: %{type: "string"},
      citations: %{
        type: "array",
        items: %{
          type: "object",
          additionalProperties: false,
          required: ["source", "quote"],
          properties: %{
            source: %{type: "integer"},
            quote: %{type: "string"}
          }
        }
      }
    }
  }

  def generate(question, sources) do
    body = %{
      model: "gpt-4o-mini",
      temperature: 0,
      messages: [
        %{role: "system", content: Prompt.system()},
        %{role: "user", content: Prompt.user(question, sources)}
      ],
      response_format: %{
        type: "json_schema",
        json_schema: %{name: "cited_answer", strict: true, schema: @schema}
      }
    }

    case Req.post("https://api.openai.com/v1/chat/completions",
           json: body,
           auth: {:bearer, System.fetch_env!("OPENAI_API_KEY")},
           receive_timeout: 60_000
         ) do
      {:ok, %{status: 200, body: %{"choices" => [%{"message" => %{"content" => json}} | _]}}} ->
        Jason.decode(json)

      {:ok, %{status: status, body: body}} ->
        {:error, {:openai, status, body}}

      {:error, reason} ->
        {:error, reason}
    end
  end
end

The result is a map like %{"answer" => "Refunds are available for 30 days [2].", "citations" => [%{"source" => 2, "quote" => "within 30 days of purchase"}]}. The shape is guaranteed. The truth of it is not, which is the next step.

If you would rather validate with Ecto changesets and retry on failure, the same schema works through Instructor in Elixir.

Step 4: Verify every citation in code

This is the step most tutorials skip, and it is the one that makes citations worth showing. For each citation, check that the source number was really supplied and that the quote appears in that source:

defmodule MyApp.RAG.Citations do
  alias MyApp.RAG.Source

  @marker ~r/\[(\d+)\]/

  @doc """
  Returns the answer with unverified markers removed, plus the verified
  sources in the order they are first cited.
  """
  def verify(%{"answer" => answer, "citations" => citations}, sources) do
    by_n = Map.new(sources, &{&1.n, &1})

    verified =
      citations
      |> Enum.filter(fn %{"source" => n, "quote" => quote} ->
        case by_n do
          %{^n => %Source{content: content}} -> supported?(content, quote)
          _ -> false
        end
      end)
      |> MapSet.new(& &1["source"])

    cleaned =
      Regex.replace(@marker, answer, fn marker, n ->
        if String.to_integer(n) in verified, do: marker, else: ""
      end)

    cited =
      @marker
      |> Regex.scan(cleaned, capture: :all_but_first)
      |> List.flatten()
      |> Enum.map(&String.to_integer/1)
      |> Enum.uniq()
      |> Enum.map(&Map.fetch!(by_n, &1))

    %{answer: String.trim(cleaned), sources: cited, grounded?: cited != []}
  end

  defp supported?(content, quote) do
    q = normalize(quote)
    String.length(q) >= 12 and String.contains?(normalize(content), q)
  end

  defp normalize(text) do
    text
    |> String.downcase()
    |> String.replace(~r/[^\p{L}\p{N}]+/u, " ")
    |> String.trim()
  end
end

A few choices in there are deliberate:

  • Normalise before comparing. PDF text is full of odd whitespace, curly quotes and hyphenated line breaks. Lowercasing and collapsing everything that is not a letter or digit makes “exact quote” tolerant of formatting without making it tolerant of invention.
  • A minimum quote length. A quote of “the” appears in every chunk. Twelve normalised characters is a low bar that still rules out trivial matches.
  • Markers without a verified quote are removed. The sentence stays, the [4] goes. The user sees an uncited sentence, which is the honest state of affairs.
  • grounded? is false when nothing survived. That flag drives the UI: an ungrounded answer gets a warning, or is replaced with “I could not find this in your documents”.

What verification does not prove

Be honest about the limit. A verified quote proves the source contains those words. It does not prove the sentence follows from them. A model can quote “refunds within 30 days” and write “refunds are not available”. This check catches invented and misattributed sources, which are the common failures. For high-stakes domains, add an entailment check on top (a second, cheap model call asking whether the quote supports the sentence) and sample real answers into an eval set, as described in Elixir LLM evals with ExUnit.

Step 5: Render clickable sources in LiveView

The answer text contains markers like [2]. Split it into segments so the template can render text as text and markers as links, with no raw HTML and no injection risk:

defmodule MyApp.RAG.Render do
  @marker ~r/\[(\d+)\]/

  def segments(answer) do
    @marker
    |> Regex.split(answer, include_captures: true)
    |> Enum.reject(&(&1 == ""))
    |> Enum.map(fn part ->
      case Regex.run(@marker, part) do
        [^part, n] -> {:cite, String.to_integer(n)}
        _ -> {:text, part}
      end
    end)
  end
end

The LiveView runs the pipeline off the socket process with start_async/3 (available since LiveView 0.20) and renders the result:

defmodule MyAppWeb.AskLive do
  use MyAppWeb, :live_view

  alias MyApp.RAG.{Answer, Citations, Render, Retrieval}

  def mount(_params, _session, socket) do
    {:ok, assign(socket, result: nil, loading: false)}
  end

  def handle_event("ask", %{"question" => question}, socket) do
    socket =
      socket
      |> assign(loading: true, result: nil)
      |> start_async(:answer, fn ->
        sources = Retrieval.sources(question)

        with {:ok, raw} <- Answer.generate(question, sources) do
          {:ok, Citations.verify(raw, sources)}
        end
      end)

    {:noreply, socket}
  end

  def handle_async(:answer, {:ok, {:ok, result}}, socket) do
    {:noreply, assign(socket, loading: false, result: result)}
  end

  def handle_async(:answer, _failure, socket) do
    {:noreply, socket |> assign(loading: false) |> put_flash(:error, "Could not answer that.")}
  end
end
<form phx-submit="ask">
  <input type="text" name="question" placeholder="Ask your documents" />
  <button disabled={@loading}>Ask</button>
</form>

<article :if={@result}>
  <p :if={not @result.grounded?} class="warning">
    No supporting source was found for this answer. Treat it with care.
  </p>

  <p>
    <%= for segment <- Render.segments(@result.answer) do %>
      <%= case segment do %>
        <% {:text, text} -> %><%= text %>
        <% {:cite, n} -> %><sup><a href={"#source-#{n}"}>[<%= n %>]</a></sup>
      <% end %>
    <% end %>
  </p>

  <ol class="sources">
    <li :for={s <- @result.sources} id={"source-#{s.n}"} value={s.n}>
      <.link navigate={~p"/documents/#{s.document_id}?page=#{s.page || 1}"}>
        <%= s.title %><%= if s.page, do: ", page #{s.page}" %>
      </.link>
      <span :if={s.heading}>(<%= s.heading %>)</span>
    </li>
  </ol>
</article>

The value={s.n} on each list item keeps the visible number equal to the marker, even when the model cited sources 2 and 4 and skipped the rest. If you want a tidy 1, 2, 3 instead, renumber in Citations.verify/2 by mapping each verified n to its index in first-cited order and rewriting the markers at the same time.

This is the pattern pdfai ships: upload a PDF, ask a question, and jump from the answer to the page it came from. If you want the upload, extraction, embedding and chat screens already wired together, it will save you the week this pipeline takes to get right.

Step 6: Citations with streaming

Streaming and verified citations pull in opposite directions. Tokens arrive before you can check anything, so you have two reasonable options.

Stream the text, verify at the end. Use a plain (non-JSON) streamed completion with inline markers only, render markers as inert superscripts while tokens arrive, and when the stream completes, check each marker’s number against the supplied sources and turn the valid ones into links. You lose quote verification, so you only prove that the source exists, not that it says it. This suits low-stakes chat.

Do not stream grounded answers. Show retrieval progress instead (“Searching 3 documents”, then “Reading 5 passages”), then render the verified answer in one piece. With a small, fast model the wait is a second or two, and every marker the user sees has been checked. This suits anything where a wrong source is worse than a short wait: legal, medical, finance, internal policy.

A middle path is to stream first and run the structured, quote-verified call in the background, then swap in the verified sources when it lands. It doubles the model cost per question, so reserve it for answers that are worth it.

Step 7: Store what was cited

Persist the citations with the answer. It costs one table and pays for itself the first time a customer asks “where did the assistant get that?” three weeks later:

create table(:answer_citations) do
  add :answer_id, references(:answers, on_delete: :delete_all), null: false
  add :chunk_id, references(:document_chunks, on_delete: :nilify_all)
  add :n, :integer, null: false
  add :quote, :text, null: false
  add :verified, :boolean, null: false
  timestamps(updated_at: false)
end

Store rejected citations too, with verified: false. The rejection rate is the most useful quality metric this pipeline produces. If it climbs after a prompt change or a model upgrade, you know before your users do. A chunk that is retrieved often and never cited is a retrieval problem. A chunk that is cited often is content worth keeping fresh.

Testing the verifier

The verifier is pure, so it tests without any API calls:

defmodule MyApp.RAG.CitationsTest do
  use ExUnit.Case, async: true

  alias MyApp.RAG.{Citations, Source}

  @sources [
    %Source{n: 1, chunk_id: 10, document_id: 1, title: "Pricing", content: "Plans start at $29 per month."},
    %Source{n: 2, chunk_id: 11, document_id: 2, title: "Refund policy",
            content: "Refunds are available within 30 days\nof purchase."}
  ]

  test "keeps a citation whose quote is in the source" do
    raw = %{
      "answer" => "You can get a refund for 30 days [2].",
      "citations" => [%{"source" => 2, "quote" => "within 30 days of purchase"}]
    }

    assert %{grounded?: true, sources: [%Source{n: 2}]} = Citations.verify(raw, @sources)
  end

  test "drops a citation to a source that was never supplied" do
    raw = %{
      "answer" => "Refunds take 5 days [7].",
      "citations" => [%{"source" => 7, "quote" => "refunds take five days to process"}]
    }

    assert %{answer: "Refunds take 5 days .", grounded?: false, sources: []} =
             Citations.verify(raw, @sources)
  end

  test "drops a citation whose quote is not in the source" do
    raw = %{
      "answer" => "Refunds are available for 90 days [2].",
      "citations" => [%{"source" => 2, "quote" => "within 90 days of purchase"}]
    }

    assert %{grounded?: false} = Citations.verify(raw, @sources)
  end
end

The second test shows a cosmetic wart: removing a marker can leave a space before the full stop. Tidy it with one more String.replace(cleaned, ~r/\s+([.,;:])/, "\\1") in verify/2, and add the assertion.

Common mistakes

  • Citing documents instead of passages. “Source: handbook.pdf” on a 200-page file is not a citation. Cite the chunk and link to the page.
  • Too many sources in the prompt. With 20 chunks, models cite loosely. Retrieve wide, then narrow to the best five with a reranker before you number them.
  • Chunks that are too small to quote. A 100-character chunk rarely contains a full supporting sentence. Citation quality is one more reason to chunk on section boundaries.
  • Trusting the marker count. Five markers do not mean five supported claims. Report the verified count, not the raw one.
  • Leaking sources across tenants. A citation is a link to a document. Scope retrieval by organisation in the query itself, never after the fact.

Summary

RAG citations in Elixir come down to one principle: the model proposes and your code verifies. Keep page and heading through ingestion so there is something to point at. Number the sources in the prompt and ask for an exact quote with every citation. Use structured output so the shape is guaranteed, then check each citation against the chunks you really retrieved and strip the ones that fail. Render markers as links in LiveView from segments, not raw HTML, and store both the accepted and the rejected citations so you can measure the pipeline over time.

If you would rather start from a working document Q&A app than assemble this from parts, pdfai has the upload, extraction, pgvector search and chat interface in place, and the Builder Pass includes it along with every other PhxTemplates starter for a single lifetime price.