Skip to content

SynapCores / Recipe

RAG with Citations (grounded answers that cite sources)

Make an AI agent cite its sources — retrieve passages, generate an answer, and attach the source documents it used, all in one SQL database. Auditable RAG that works with Claude Code, OpenClaw, LangChain, or a voice agent.

All recipes· agents· 13 minutesintermediateen
Install free
Instance: localhost:8080

Install free with one command, then open RAG with Citations (grounded answers that cite sources) in your instance. It's staged for a preview — nothing runs until you click Run. New to SynapCores? The quickstart covers install to first query.

Share

Objective

An answer you can't trace is an answer you can't trust. For support bots, research agents, and anything regulated, the agent must say where an answer came from. Here you'll extend RAG so every answer ships with citations: retrieve the top passages, generate the answer from them, and return the exact sources used, each with the citation handle the answer refers to. All in one database, no citation framework. The same pipeline works from any framework or a voice agent — see Use it from your agent at the end.

Want the whole app, not just the queries? The tutorial Build a local RAG app with citations in one database turns this pattern into a working support bot in 28 lines of Python, and compares it with the same app built on Postgres, pgvector and Ollama.

Step 1: Create the cited knowledge base

Each chunk carries a stable doc_ref (the citation handle) alongside its text and embedding.

CREATE TABLE IF NOT EXISTS recipe_rag_cited (
  chunk_id   INTEGER PRIMARY KEY,
  doc_ref    TEXT,                                   -- citation handle, e.g. 'SecurityPolicy §4.2'
  content    TEXT,
  embedding  VECTOR(384)
);

Step 2: Load documents with citation handles

Policy passages with the references a compliance-minded agent must cite. ON CONFLICT DO NOTHING makes the load safe to run again.

INSERT INTO recipe_rag_cited (chunk_id, doc_ref, content) VALUES
 (1,'SecurityPolicy §2.1','All customer data is encrypted at rest using AES-256.'),
 (2,'SecurityPolicy §4.2','Access to production databases requires multi-factor authentication and is logged.'),
 (3,'Privacy §3.0','Personal data is retained for 24 months after account closure, then permanently deleted.'),
 (4,'SLA §1.4','The service guarantees 99.9% monthly uptime, with credits for any breach.'),
 (5,'Privacy §5.1','Customers may request a full export or deletion of their data within 30 days.'),
 (6,'SecurityPolicy §6.0','Third-party vendors are reviewed annually and must sign a data-processing agreement.')
ON CONFLICT (chunk_id) DO NOTHING;

Step 3: Embed the knowledge base

The embedding model runs in-database — your citation-aware retrieval index in one line.

UPDATE recipe_rag_cited SET embedding = EMBED(content);

Step 4: Retrieve the top passages with their citation handles

Retrieval returns both the text and the doc_ref, so the citation travels with the evidence. We project the similarity as relevance and order by that alias.

SELECT chunk_id, doc_ref, content,
       COSINE_SIMILARITY(embedding, EMBED('How is customer data protected and who can access it?')) AS relevance
FROM recipe_rag_cited
ORDER BY relevance DESC
LIMIT 3;

Step 5: Materialize the top sources, then generate a cited answer

First empty the two working tables, so every question starts from a clean slate. Then freeze the top-3 retrieved passages — with their citation handles — into a small table. Concatenate them into one context string, each passage prefixed with its citation handle, and feed that to GENERATE(), telling it to cite each source name inline. To ask another question, put it in Step 4 and in both Step-5 queries that name it (the INSERT INTO recipe_rag_cited_top and the GENERATE prompt), then run Steps 4–6 again.

CREATE TABLE IF NOT EXISTS recipe_rag_cited_top (
  chunk_id  INTEGER PRIMARY KEY,
  doc_ref   TEXT,
  content   TEXT,
  relevance DOUBLE
);
CREATE TABLE IF NOT EXISTS recipe_rag_cited_ctx (id INTEGER PRIMARY KEY, sources TEXT);
DELETE FROM recipe_rag_cited_top;
DELETE FROM recipe_rag_cited_ctx;
INSERT INTO recipe_rag_cited_top (chunk_id, doc_ref, content, relevance)
SELECT chunk_id, doc_ref, content,
       COSINE_SIMILARITY(embedding, EMBED('How is customer data protected and who can access it?')) AS relevance
FROM recipe_rag_cited
ORDER BY relevance DESC
LIMIT 3;
INSERT INTO recipe_rag_cited_ctx (id, sources)
SELECT 1, GROUP_CONCAT('(' || doc_ref || ') ' || content, ' ') FROM recipe_rag_cited_top;
SELECT GENERATE(
  'Answer the question using ONLY these sources, and cite the source name in parentheses inline, e.g. (SecurityPolicy §4.2). Sources: ' ||
  sources ||
  ' Question: How is customer data protected and who can access it? Answer with inline citations:') AS cited_answer
FROM recipe_rag_cited_ctx;

Step 6: Return the citation list alongside the answer

Produce the source list your UI shows under the answer — a complete, auditable trail, ordered by relevance.

SELECT doc_ref AS citation, content, relevance
FROM recipe_rag_cited_top
ORDER BY relevance DESC;

Cleanup (Optional)

DROP TABLE IF EXISTS recipe_rag_cited;
DROP TABLE IF EXISTS recipe_rag_cited_top;
DROP TABLE IF EXISTS recipe_rag_cited_ctx;

Expected Outcomes

  • Step 4 retrieves the encryption and access-control passages, each carrying its doc_ref.
  • Step 5 produces an answer that cites its sources inline by handle, e.g. (SecurityPolicy §2.1), pointing at the right SecurityPolicy sections.
  • Step 6 returns the matching citation list (handle + text), ordered by relevance — the audit trail your UI renders under the answer.

You now have RAG that doesn't just answer — it shows its work, with citations traceable back to your source documents.

Use it from your agent (framework-agnostic — this is the whole point)

Cited RAG is just a doc table + a retrieve that keeps each source's handle + generate, so any agent uses it with no framework lock-in:

  • REST / SDK — POST /v1/query/execute (any language), or @synapcores/sdk client.executeQuery(...). Your agent runs the Step-5 queries for the cited answer and the Step-6 query for the source list, then renders both.
  • MCP (native, on by default) — point any MCP client (Claude Code, Cursor, a custom loop, a voice runtime) at ws://<your-instance>/mcp?token=<jwt> (JWT from one POST /v1/auth/login → access_token). The agent runs the Step-5 CREATE TABLE, DELETE and INSERT statements through the execute tool, then the GENERATE query and the Step-6 query through the query tool, and gets the cited answer and its source list — auditable RAG as tool calls.
  • Any framework — OpenClaw, LangChain / LlamaIndex citation chains, a custom loop, or a voice agent (which reads the answer and offers "I can send you the sources") all use the same cited store. The database is the brain; the framework is swappable.

Key Concepts Learned

  • Carry a doc_ref on every chunk so the citation travels with the evidence through retrieval.
  • Freezing the top passages in recipe_rag_cited_top keeps the answer (Step 5) and the citation list (Step 6) on the same sources.
  • Returning the answer and its source list together makes RAG auditable, not just fluent.
  • Because it's plain data ops (SQL / REST / MCP), cited RAG works for any agent — the agent-agnostic backend pattern this cluster builds on.

Tags

ai-agentragcitationsretrieval-augmented-generationvectorembeddingsmcp