Claude Certified Developer · प्रोफेसनल
Module 1: Answers grounded in your own data
Study notes written by Sanjay Shah. Not official Anthropic material. Facts marked "check before relying on it" may have changed.
On this page
Study notes, not official course material. Our take on official course 1 (reliable production integration grounded in your own knowledge). Facts checked 2026-11-25.
The video opens with a support bot for tenant alpine quoting tenant birch's private refund policy, and sounding completely sure about it. This module is about why that happens and the four promises a production integration has to keep: the right data, cited, honest when there is no answer, and still working when the API has a bad minute.
What you'll be able to do
Trace the tenant id from a verified token all the way to the SQL that fetches context, and explain why a prompt line can't stand in for that.
Enforce tenant isolation in the database with Postgres row-level security (RLS), and prove it with a test.
Pass retrieved chunks to Claude as separate documents with citations on, and check in code that every answer is backed by a retrieved source.
Pick a relevance threshold and make "I don't know" plus escalation the behaviour below it.
Tell retryable from non-retryable API errors, set a total time budget, and make every side-effecting tool idempotent so retries can't refund twice.
Get machine-readable output that matches a schema, and fail safely when it doesn't.
Keep the index fresh, so an edited doc stops answering with its old text.
1. What "grounded" means in production
A grounded answer is one where every factual claim comes from a source you chose to give the model, for this caller, at this moment. That gives you three separate things to get right:
Selection. Did retrieval return the right chunks, from the right tenant only?
Use. Did the model base the answer on those chunks and say which ones?
Abstention. When the chunks don't contain the answer, does the system say so instead of filling the gap?
Most "the AI made it up" incidents are a failure of 1 or 3, not of the model's reading. If the wrong tenant's document is in the context, the model will use it; that's its job. If nothing relevant is in the context and the prompt demands an answer, the model will produce a plausible one. Fix the system around the model first.
There is a fourth promise that has nothing to do with retrieval: reliability. The API will sometimes be slow, rate-limited or overloaded. A grounded answer that arrives twice, or triggers a tool twice, is still a production incident.
2. The request path, with the tenant id followed end to end
The rule: the tenant comes from the verified token, never from the request body, the prompt or the model. If the handler reads body.tenant, any caller can type "birch". If the model chooses which tenant to search (say, a tenant argument on search_docs), a prompt injection can choose for it. The tool should not even have a tenant argument; the server fills it in from the session.
Why "only use alpine's docs" in the prompt doesn't work
Suppose retrieval has no tenant filter and birch's refund doc ranks highest for "can I get a refund after 30 days?". The prompt says "Only use documents belonging to alpine." Three things go wrong:
The model may not be able to tell which document belongs to whom. Chunk text rarely says "this is birch's".
Even if each chunk is labelled, the label is just more text in the context. Nothing forces the model to obey it, and an attacker who can write text into a ticket can write a competing instruction.
The leak has already happened: birch's private text left the database and went to a third-party API call made for an alpine user. Whether or not the model repeats it, your access-control boundary is broken.
A prompt instruction is a request. A database policy is a guarantee. Put the boundary where the data is.
3. Tenant isolation in the database
There are three common ways to separate tenants in one product. They trade isolation strength against operational cost:
| Approach | Isolation | Cost to run | Typical fit |
|---|---|---|---|
| Separate database per tenant | Strongest; a bug in one query can't reach another tenant | Highest: migrations, connections and backups per tenant | Few large tenants, strict contracts |
Shared tables + a mandatory WHERE tenant_id = $1 | Only as strong as every query; one forgotten filter leaks | Lowest | Small teams, early stage, with code review and tests |
| Shared tables + row-level security | The database applies the filter to every query, including ones you forgot | Low; one policy per table | Most multi-tenant SaaS |
The course app uses RLS. The policy:
ALTER TABLE doc_chunks ENABLE ROW LEVEL SECURITY;
ALTER TABLE doc_chunks FORCE ROW LEVEL SECURITY; -- applies to the table owner too
CREATE POLICY tenant_isolation ON doc_chunks
USING (tenant_id = current_setting('app.tenant_id', true));Three details matter here, and each is a classic mistake:
current_setting('app.tenant_id', true): the second argumenttruemeans "return NULL if the setting is missing" instead of raising an error. With NULL,tenant_id = NULLis never true, so a request that forgot to set the tenant sees no rows. That's fail-closed, which is what you want.FORCE ROW LEVEL SECURITY: without it, the role that owns the table bypasses the policy. If your app connects as the owner (very common in dev setups), RLS silently does nothing.Superusers and roles with
BYPASSRLSalways bypass RLS. The app must connect as an ordinary role.
Retrieval sets the tenant inside a transaction, so the setting can't leak to the next request that reuses the pooled connection:
import pg from "pg";
const pool = new pg.Pool(); // connects as app_user: not the owner, no BYPASSRLS
export type Chunk = { doc_id: string; doc_version: number; chunk_text: string; similarity: number };
export async function retrieve(
tenantId: string, // from the verified token, never from the request body
queryEmbedding: number[], // from your embedding provider
k = 5,
): Promise<Chunk[]> {
const db = await pool.connect();
try {
await db.query("BEGIN");
// is_local = true: the setting ends with this transaction
await db.query("SELECT set_config('app.tenant_id', $1, true)", [tenantId]);
const { rows } = await db.query(
`SELECT doc_id, doc_version, chunk_text,
1 - (embedding <=> $1::vector) AS similarity
FROM doc_chunks
ORDER BY embedding <=> $1::vector
LIMIT $2`,
[JSON.stringify(queryEmbedding), k],
);
await db.query("COMMIT");
return rows;
} catch (err) {
await db.query("ROLLBACK");
throw err;
} finally {
db.release();
}
}<=> is pgvector's cosine distance operator, so 1 - distance is the cosine similarity. Anthropic doesn't offer an embeddings endpoint; you use a separate embedding provider and store its vectors.
The test that proves it is short and belongs in CI forever:
test("alpine cannot read birch's chunks", async () => {
const birchVector = await embed("birch refund policy after 30 days");
const rows = await retrieve("alpine", birchVector, 50);
expect(rows.every((r) => r.doc_id.startsWith("alpine/"))).toBe(true);
});Write it so it would fail on the old code. A test that passes before and after the fix proves nothing.
4. Passing context: separate documents, citations on
How you place retrieved text in the request changes how well you can check the answer.
Weak: paste all chunks into one big string in the system prompt. The model can't point to a source, you can't check it, and the model can't tell where one doc ends and the next begins.
Better: send each chunk as its own document content block with citations enabled. The API then returns the answer split into text blocks, and the cited ones carry pointers back to the documents you sent.
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const SYSTEM = `You answer support questions for one customer using only the documents provided.
If the documents don't contain the answer, say you don't know and that a person will follow up.
Never guess policy, prices or dates.`;
export async function answer(question: string, chunks: Chunk[]) {
return client.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
system: SYSTEM,
messages: [{
role: "user",
content: [
...chunks.map((c) => ({
type: "document" as const,
source: { type: "text" as const, media_type: "text/plain" as const, data: c.chunk_text },
title: `${c.doc_id}@v${c.doc_version}`,
citations: { enabled: true },
})),
{ type: "text" as const, text: question },
],
}],
});
}Notes on this call:
Documents before the question. Long context first and the question last is the usual layout, and it also suits caching later (Module 8).
max_tokensis not tiny. On Claude Opus 5.5 thinking is always on and counts toward output, so a small cap can cut the answer off. Checkstop_reason(below) rather than guessing a tight cap.Citations are all or nothing: enable them on every document block in the request, or on none.
Checking citations in code
With the native citations feature, each citation has a document_index that points at one of the documents you sent, plus the cited_text. The model can't cite a document you didn't send, but your code still has to check two things: that the answer cites anything at all, and that the indexes map to chunks you actually retrieved for this request.
type Check = { ok: true; docs: string[] } | { ok: false; reason: string };
export function checkCitations(msg: Anthropic.Message, chunks: Chunk[]): Check {
const docs = new Set<string>();
for (const block of msg.content) {
if (block.type !== "text" || !block.citations) continue;
for (const c of block.citations) {
if (c.type !== "char_location") return { ok: false, reason: `unexpected citation type ${c.type}` };
const chunk = chunks[c.document_index];
if (!chunk) return { ok: false, reason: "citation points outside the retrieved set" };
docs.add(`${chunk.doc_id}@v${chunk.doc_version}`);
}
}
return docs.size > 0 ? { ok: true, docs: [...docs] } : { ok: false, reason: "no citations" };
}If you instead ask the model to write source ids in its text or JSON (for example because you also need structured output, see section 7), the risk changes: now the model can type an id that doesn't exist, or one from training data. Then the check becomes "every id it wrote is in the set I retrieved", and it's mandatory.
5. Teaching the system to say "I don't know"
The invented-policy failure from the video: a question has no answer in alpine's docs, retrieval returns the five "least bad" chunks, and the model stitches a believable policy together from them.
Retrieval always returns something. LIMIT 5 returns five rows even if all five are unrelated. So the system needs its own idea of "good enough":
const MIN_SIMILARITY = 0.78; // calibrate on your own data; depends on the embedding model
export async function handle(tenantId: string, question: string) {
const chunks = (await retrieve(tenantId, await embed(question))).filter(
(c) => c.similarity >= MIN_SIMILARITY,
);
if (chunks.length === 0) return escalate(tenantId, question, "no relevant source");
const msg = await answer(question, chunks);
if (msg.stop_reason !== "end_turn") return escalate(tenantId, question, `stop_reason ${msg.stop_reason}`);
const check = checkCitations(msg, chunks);
if (!check.ok) return escalate(tenantId, question, check.reason);
return { msg, sources: check.docs };
}That's three gates, cheapest first: the threshold before any model call, then the stop reason, then the citation check.
Calibrating the threshold. There is no universal number. Similarity scores depend on the embedding model and on your documents. Take 50–100 real questions, label which retrieved chunks actually answer them, and look at the score distributions of "answers it" and "doesn't". Pick the threshold where the cost of a wrong answer and the cost of an unneeded escalation balance for your business. A refunds bot should lean towards escalating; an internal FAQ bot can be more lenient.
The prompt still matters. The system prompt gives explicit permission to say "I don't know". Without it, models tend to try to be helpful. The code gates catch what the prompt misses; the prompt cuts down how often the gates fire.
Failure case: the threshold is right, but the answer still mixes in a guess
Two chunks pass the threshold. One covers refunds within 30 days. The question is about 45 days. The model answers, cites the 30-day chunk, and adds "after 30 days, refunds are usually not possible", which no document says. The citation check passes because there is a citation.
The fix is not a bigger regex. It belongs to evaluation (Module 4): a grader that checks each claim against the cited text, run on a sample, plus a rule in the prompt ("If the documents cover only part of the question, answer that part and say the rest needs a person"). Code checks catch structural failures; judgement failures need an eval.
6. Surviving a bad minute: errors, retries and time budgets
Which errors to retry
| Status | Type | Retry? | What it usually means |
|---|---|---|---|
| 400 | invalid_request_error | No | Your request is wrong. Retrying sends the same wrong request. |
| 401 / 403 | authentication_error / permission_error | No | Credential or access problem. |
| 404 | not_found_error | No | Wrong endpoint or a model your organisation can't use. |
| 413 | request_too_large | No | Shrink the request. |
| 429 | rate_limit_error | Yes, after retry-after | Too many requests. Exception: a monthly spend-cap 429 has no retry-after and keeps failing until access resumes. |
| 500 | api_error | Yes, with backoff | Service problem. |
| 529 | overloaded_error | Yes, with backoff | The API is temporarily overloaded. |
The official SDKs already retry connection errors, 408, 409, 429 and 5xx with exponential backoff, two times by default (maxRetries). Use that instead of writing your own loop, and configure it:
const client = new Anthropic({
maxRetries: 3, // per call
timeout: 30_000, // per attempt, in milliseconds in the TypeScript SDK
});
// A total budget for this user request, across all attempts:
const msg = await client.messages.create(params, { signal: AbortSignal.timeout(75_000) });Why a total budget: the per-attempt timeout times the number of attempts can add up to minutes. A user waiting on a support widget won't wait that long. Decide what the slowest acceptable answer is, cap the whole call at that, and fall back to "a person will reply" when it runs out.
If you write your own retry (for a raw HTTP client, say), use exponential backoff with jitter so that a thousand clients that failed at the same moment don't all retry at the same moment. Honour retry-after when it's present.
The double refund
The failure in the video: the agent decides to call issue_refund, your code runs it, the refund succeeds, and then the next model call (the one that would read the tool result) times out. The naive wrapper retries the whole turn from the start. The model sees the original ticket again, decides again to refund, and your code refunds again.
The lesson: retrying a model call is safe; retrying a side effect is not. The model call has no effects outside the response. Your tools do. So idempotency lives in the tools:
CREATE TABLE idempotency_keys (
key text PRIMARY KEY,
status text NOT NULL CHECK (status IN ('pending', 'done')),
result jsonb,
created_at timestamptz NOT NULL DEFAULT now()
);export async function issueRefund(a: { tenantId: string; ticketId: string; orderId: string; amountCents: number }) {
// Key on the business intent, not on anything the model generates.
const key = `refund:${a.tenantId}:${a.ticketId}:${a.orderId}`;
const claimed = await pool.query(
`INSERT INTO idempotency_keys (key, status) VALUES ($1, 'pending')
ON CONFLICT (key) DO NOTHING RETURNING key`,
[key],
);
if (claimed.rowCount === 0) {
const { rows } = await pool.query("SELECT status, result FROM idempotency_keys WHERE key = $1", [key]);
return rows[0].status === "done" ? rows[0].result : { status: "in_progress" };
}
const result = await payments.refund({ ...a, idempotencyKey: key }); // the provider dedupes too
await pool.query("UPDATE idempotency_keys SET status = 'done', result = $2 WHERE key = $1", [key, result]);
return result;
}Why the key is built from ticketId and orderId and not from the tool_use id: when the turn is retried, the model produces a new tool-use block with a new id. A key based on that id is different every time, so it dedupes nothing. Key on what the action means: "refund this order for this ticket".
Failure case inside the fix: the process crashes after payments.refund succeeds but before the UPDATE. The row stays pending forever, and retries return in_progress. Two defences: pass the same key to the payment provider (most payment APIs accept an idempotency key), so a later retry returns the original refund instead of making a new one, and run a small reconcile job that settles old pending rows by asking the provider.
Refusals and other stop reasons
A response can be HTTP 200 and still not be an answer. Always read stop_reason before reading content:
end_turn: normal finish.max_tokens: cut off. Don't show a half-answer; retry with more room or escalate.tool_use: the model wants a tool; run it and continue the loop.refusal: the model's safety classifiers declined;stop_detailshas a category. Treat it as "no answer", escalate, and log it. A sudden rise in refusals is a monitoring signal (Module 3).
For the newest models the API also offers server-side fallbacks: on a refusal, the same request is re-run on a fallback model within the same call. It's a beta feature, enabled with a beta header and a fallbacks parameter on the beta messages endpoint. It's worth knowing it exists; check the current docs before you depend on it.
7. Output you can parse: structured outputs and safe failure
Some calls aren't answers for people; they're decisions for code: triage category, "does this need a human?", extracted order ids. Here you want output that matches a schema every time.
The current API supports structured outputs: you give a JSON schema in output_config.format and the response is constrained to it. In TypeScript the helper takes a Zod schema and parses the response for you:
import { z } from "zod";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
const Triage = z.object({
category: z.enum(["billing", "technical", "account", "other"]),
order_ids: z.array(z.string()),
needs_human: z.boolean(),
});
export async function triage(ticketText: string) {
const r = await client.messages.parse({
model: "claude-opus-5-5",
max_tokens: 16000,
messages: [{ role: "user", content: `Classify this support ticket:\n\n${ticketText}` }],
output_config: { format: zodOutputFormat(Triage) },
});
if (r.stop_reason !== "end_turn" || !r.parsed_output) {
return { category: "other", order_ids: [], needs_human: true } as const; // safe default
}
return r.parsed_output;
}For tool calls there's the matching guarantee: set strict: true on the tool definition (with additionalProperties: false and a required list in the schema), and the tool input will validate against the schema.
Two things structured outputs don't fix:
Truth. The schema guarantees shape, not facts.
order_idswill be an array of strings; whether they're this customer's orders is your code's job. Always check ids against the database for this tenant.Cut-offs and refusals. A response stopped by
max_tokensor a refusal won't have a valid parsed output. That's why the code above checksstop_reasonand falls back to the safe default, which is "a person looks at it".
The video plan's checklist says "one repair attempt, then a safe failure". With structured outputs, invalid JSON is rare, so the repair attempt is mostly for the old path (asking for JSON in plain text, which you may still have on some platform). Keep the safe failure either way.
A known clash: native citations and output_config.format can't be used in the same request (the API returns a 400). That's why the course app uses two calls: triage() with structured output, then answer() with citations. If you really need one call, ask for cited ids inside the schema and check them yourself, as in section 4.
8. Freshness: when the doc changes but the old chunk still answers
Birch edits its refund policy from 30 to 14 days. The help-centre page updates. The bot keeps saying 30 days for a week because nobody re-indexed.
The fix has three parts:
Every chunk carries
doc_id,doc_versionand a content hash. You can't fix what you can't see.Re-index on change, not on a schedule. The help centre emits an event when a doc is published. The indexer deletes the old version's chunks and inserts the new ones in one transaction, so there's never a moment with both versions (two answers) or neither (no answer).
Show the version in the citation (
birch/refunds@v7). Support staff can then see at a glance that an answer came from an old version.
A nightly job that compares source hashes with indexed hashes catches missed events.
9. Putting it together: the 20-question smoke set
Before and after the fixes, run a small fixed set of questions with known expected behaviour (not exact wording):
| Category | Example | Expected behaviour |
|---|---|---|
| Cross-tenant | alpine user asks about a policy only birch has | "I don't know" + escalate; no birch text in context |
| No answer | a question no alpine doc covers | "I don't know" + escalate |
| Normal | "How do I reset my password?" | answer, at least one citation, cited doc is alpine's |
| Fault | fault proxy returns 529 then succeeds | one answer, no duplicate tool calls |
| Timeout after tool | proxy drops the response after issue_refund ran | exactly one refund row |
Twenty questions is enough to catch regressions in the four promises. Module 4 turns this into a real eval with graders and a release gate.
Trade-offs
RLS vs a WHERE clause. RLS covers queries you forgot; it costs a policy per table and some care with roles and pooled connections. A WHERE clause is simpler and easier to read, and one missed filter is a leak.
Strict vs lenient threshold. Strict means more escalations (cost: people's time), lenient means more invented answers (cost: trust, and sometimes money). Decide per use case.
Native citations vs ids in JSON. Native citations can't point outside what you sent and give character ranges, but they can't be combined with structured outputs. Ids in JSON combine with a schema, but you must check every id.
SDK retries vs your own. The SDK's are correct and tested; your own let you add per-error policy (e.g. switch platform on repeated 529). Start with the SDK's.
Idempotency in your tool vs at the provider. Do both. Yours stops the duplicate call; the provider's catches the crash window yours can't.
Common mistakes
Taking the tenant from the request body, a header the client sets, or a tool argument the model fills.
Enabling RLS but connecting as the table owner (no
FORCE) or as a superuser, so the policy never applies.Using
current_setting('app.tenant_id')without the secondtrueargument, then "fixing" the resulting errors by setting a default tenant (fail-open).Setting the tenant with a session-level
SETon a pooled connection, so the next request inherits it.One giant string of context, so nothing can be cited or checked.
Treating "the answer has a citation" as "the answer is correct".
Retrying whole agent turns after a tool already ran, or keying idempotency on the tool-use id.
Retrying 400s, or retrying a spend-cap 429 forever.
Reading
content[0].textwithout checkingstop_reason.Re-indexing on a timer only, or re-indexing in two steps so both versions answer for a while.
Remember
The tenant comes from the verified token. The database enforces it. The prompt never does.
Send each source as its own document with citations on, and check in code that the answer cites what you retrieved.
Retrieval always returns something. A threshold, plus "I don't know and a person will follow up", is a feature.
Retry model calls; never blindly retry side effects. Key idempotency on business intent.
Read
stop_reasonbefore content. Structured outputs guarantee shape, not truth.Chunks carry doc id and version; re-index on change, in one transaction.
Check before relying on it
Server-side refusal fallbacks are a beta feature on the newest models (beta header
server-side-fallback-2026-07-01on 2026-11-25); the parameter shape and model support may change.Citations +
output_config.formatreturning a 400 was the documented behaviour on 2026-11-25. Check whether it still holds.SDK retry defaults (2 retries; 408/409/429/5xx and connection errors) and whether the built-in backoff adds jitter can differ by SDK and version.
AbortSignalas a whole-call budget: I confirmed the TypeScript SDK accepts asignalrequest option; check that it also cancels the sleep between retries in your SDK version.Thinking always on for
claude-opus-5-5(its default effort ismedium, and{type: "disabled"}returns a 400): model-specific, and true on 2026-11-25.