Faithfulness checking
Score whether an LLM response is grounded in the memories you recalled, and gate downstream actions on the score — a client-side pattern built on recall.
There is no faithfulness endpoint on Brain's data plane. Recall returns the grounded memories; the faithfulness check is your own LLM call over those memory texts. (Some SDKs ship a checkFaithfulness() convenience helper that wraps exactly this pattern — see your SDK reference.)
- A Brain client with an API key (see Identity by key).
- An LLM that produces the responses you want to verify (any provider — Anthropic, OpenAI, Google, local).
- Familiarity with Building context.
A guarded RAG loop that recalls supporting memories, asks an LLM, scores the answer's faithfulness against those memories, and either commits to the answer or regenerates with stricter instructions.
Step-by-step
Recall the memories that answer the query, assemble them into a context block client-side, and hold on to that block so you can pass it back into the check.
import { BrainHttpClient } from "@brain-db/sdk";
const brain = new BrainHttpClient({ apiKey: process.env.BRAIN_API_KEY! });
const res = await brain.recall({ query: userQuery, maxResults: 8 });
const context = res.memories.map((m) => `- ${m.text}`).join("\n");
const answer = await llm.complete({
system: `Answer using ONLY the context. If unsupported, say so.\n\n${context}`,
user: userQuery,
});import os
from brain_db_sdk import BrainHttpClient
brain = BrainHttpClient(os.environ["BRAIN_API_KEY"])
res = brain.recall(query=user_query, max_results=8)
context = "\n".join(f"- {m.text}" for m in res.memories)
answer = llm.complete(
system=f"Answer using ONLY the context. If unsupported, say so.\n\n{context}",
user=user_query,
)curl -X POST "$BRAIN_BASE_URL/v1/recall" \
-H "Authorization: Bearer $BRAIN_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "query": "'"$Q"'", "max_results": 8 }'
# → { "answer_kind": "many", "memories": [ { "text": "...", ... } ] }If answer_kind is none, there is nothing to ground an answer in — short-circuit and return "I don't have that information" rather than letting the LLM guess.
Ask a small model to check each claim in the answer against the recalled memory texts. This is an ordinary LLM call — keep it separate so you can apply it selectively.
const judgePrompt = [
"You are a faithfulness judge. Given CONTEXT and an ANSWER, list any claim",
"in the ANSWER not supported by the CONTEXT, and return strict JSON:",
'{ "score": 0..1, "verdict": "faithful|partial|unfaithful", "unsupported_claims": string[] }',
"",
`CONTEXT:\n${context}`,
`ANSWER:\n${answer}`,
].join("\n");
const report = JSON.parse(await llm.complete({ user: judgePrompt, jsonMode: true }));
// report.score, report.verdict, report.unsupported_claimsimport json
judge_prompt = f"""You are a faithfulness judge. Given CONTEXT and an ANSWER, list any claim
in the ANSWER not supported by the CONTEXT, and return strict JSON:
{{ "score": 0..1, "verdict": "faithful|partial|unfaithful", "unsupported_claims": [] }}
CONTEXT:
{context}
ANSWER:
{answer}"""
report = json.loads(llm.complete(user=judge_prompt, json_mode=True))
# report["score"], report["verdict"], report["unsupported_claims"]A reasonable bucketing: faithful at score ≥ 0.85, partial at 0.6–0.85, unfaithful below 0.6.
Three policies depending on what's at stake:
- High-stakes (sending a payment, posting publicly) → require
verdict === "faithful". - Medium-stakes (drafting an email for human review) → accept
partial, surfaceunsupported_claimsto the reviewer. - Low-stakes (chitchat reply) → skip the check; the cost isn't worth it.
if (report.verdict === "unfaithful") {
return regenerateWithStricterPrompt(userQuery, context);
}
if (report.verdict === "partial") {
return { text: answer, flagged: report.unsupported_claims };
}
return { text: answer, flagged: [] };When a check fails, regenerate with an explicit instruction to stay within the context. Often a single retry resolves it.
async function regenerateWithStricterPrompt(query: string, context: string) {
return llm.complete({
system: [
"Answer ONLY using facts from the context.",
'If the context does not contain the answer, say "I don\'t have that information."',
"Do not infer, do not extrapolate.",
"",
context,
].join("\n"),
user: query,
temperature: 0.0,
});
}If the regeneration also fails, abort and surface the unsupported claims — the model genuinely can't answer with what's in memory.
Cost and latency considerations
The check is a single LLM call — typically a few hundred milliseconds with a small model. You're trading that latency for safety; for high-stakes actions it's almost always worth it. To keep cost manageable on a high-traffic agent:
- Skip the check on repeat / cached queries.
- Only run it when recall returned a thin evidence base (
answer_kindsingle, or very few memories) — that's where hallucination risk is highest. - Run it asynchronously when the action is reversible: emit the answer immediately, check in the background, and roll back / flag if it fails.
Log each check's verdict and the recalled memory_ids next to your application's user-action id. When you discover a wrong answer in the wild, the memory ids tell you which memories the model saw, and the verdict tells you whether the guard caught it.
Was this page helpful?
Graph queries
When to reach past recall into the typed graph — resolve an entity, read its relations, traverse from an anchor, and export the whole graph.
Identity walkthrough
How an API key carries identity — it binds a (namespace, space) scope at creation, the server derives everything from it, and the connected client reports it back.