A citation-first RAG API retrieves authorized chunks, assigns server-owned reference labels, asks a model for structured claims using only those labels, and validates every citation before responding. The model never chooses a tenant, constructs SQL, or turns arbitrary URLs into evidence. Deterministic provider fakes make the request path testable without paid services.
The request handler receives an authenticated principal from middleware, not from JSON. A retrieval repository accepts that policy object and a validated query vector. The generator sees labels such as [S1], not database authority.
Escape or delimit retrieved text as untrusted data. The system instruction says retrieved content may contain instructions and must be used only as evidence. Enforce a token budget and diversify documents. Keep a server map from S1 to authorized chunk ID and source coordinates.
Parse schema-constrained output. Reject unknown labels, duplicate malformed objects, missing citations for factual claims under your policy, or citations no longer accessible. Optionally run entailment checks, but human-reviewed evaluation remains necessary. On validation failure, retry once with a repair instruction only if the deadline allows; otherwise abstain.
Use fake providers and fixtures for: supported answer, no evidence, invented citation, cross-tenant chunk, prompt injection inside source, generator timeout, invalid JSON, deleted source, and context overflow. Assert response status, abstention reason, citation links, and stage metrics.
Generate a provider-neutral citation-first RAG API skeleton in [Python/TypeScript] using my existing repository interface. Include typed request/response models, authenticated policy context, deadlines, bounded context, structured generation, citation validation, abstention, safe metrics, and deterministic fakes. Do not include secrets or framework-owned retrieval magic.
Verification contract: Run the nine adversarial fixtures above; review SQL separately and prove every returned citation was both retrieved and authorized.