Agentic Architectures

Catalogue / Guardrails & Routing

Constitutional Critique

Check a draft against written rules and fix exactly what fails

Shape
loop
Model calls
1 draft + rules × rounds + revisions (e.g. 1 + 8 × 2 + 1 = 18)
Latency
medium
Complexity
medium

Also known as Rule-based critique and revision

1

How do I make sure every output follows our rules, every time?

Write the rules down as a short numbered list, the constitution. Each draft is checked against every rule separately, with a pass or fail and the passage concerned. A reviser then fixes exactly the failed rules, and the draft is checked again.

You may need it if

  • Legal, brand or compliance teams keep sending back AI-written text for the same reasons.
  • Your rules exist in a document, but nobody can show that a given output was checked against them.
  • A general request to "follow our guidelines" works most of the time, and that is not enough.
2

When is a written constitution the wrong tool?

Use it when

  • The rules can be written as short, checkable statements, such as "never promise a delivery date".
  • Every output must be shown to comply, for example for an audit or a regulated market.
  • The same rules apply to many outputs, so writing them once pays off.

Avoid it when

  • The goal is general quality, such as clarity or persuasion, not compliance with fixed rules.
    Use Reflection instead
  • The concern is an action on a system, such as a payment or a deletion, not the content of a text.
    Use Dry Run instead
  • The main risk is wrong facts. A rule check cannot tell whether a figure is true.
    Use Chain of Verification instead
  • The rules are vague values, such as "be on-brand", that two people would judge differently.

What it costs

Model calls
1 draft + rules × rounds + revisions (e.g. 1 + 8 × 2 + 1 = 18)
Latency
medium
Complexity
medium
3

How does a draft move through the rule checks?

A loop with one check per rule. The drafter writes or takes the draft. Checkers each test one rule and quote the passage. A gate counts the failures and the rounds. The reviser fixes only the failed rules, and all rules are checked again.

every rule passesfailures,rounds leftrevised draftfailures,rounds spentDraft or task: An existing draft to check, or a task for which a draft must be written first.Draft or taskDrafter: Writes the first draft when given a task. Passes an existing draft through unchanged.DrafterConstitution: The numbered list of rules, each short and checkable, kept between runs.ConstitutionRule checkers: One per rule. Returns pass or fail and quotes the passage that breaks the rule.Rule checkersAll rules pass?: Counts failed rules and rounds used, and picks one of three exits.All rulespass?Reviser: Fixes exactly the failed rules in the quoted passages and changes nothing else.ReviserCompliant: The draft that passed every rule, with the check record.CompliantRejected: The last draft with the rules it still fails at the round limit.Rejected
  1. Step 1 of 5

    A draft to check

    If the input is a task, the drafter writes a draft with the constitution in view. If it is already a draft, say a sales email from another system, it passes through untouched.

  2. Step 2 of 5

    One checker per rule

    Each checker receives the draft and a single rule. It answers pass or fail, and on a fail it quotes the exact passage. Checking one rule at a time keeps each judgement narrow and honest.

  3. Step 3 of 5

    The gate counts

    A plain rule reads the results. No failures means release. Failures with rounds left mean revision. Failures at the limit mean rejection.

  4. Step 4 of 5

    Fix what failed, nothing more

    The reviser receives the draft, the failed rules and the quoted passages. It rewrites those passages only, then the whole draft goes back to every checker, because a fix can break another rule.

  5. Step 5 of 5

    Two different exits

    A compliant draft leaves with its check record as proof. A draft that still fails at the limit leaves through a separate exit, so it can go to a person instead of a customer.

What each part does
Draft or task
An existing draft to check, or a task for which a draft must be written first.
Drafter
Writes the first draft when given a task. Passes an existing draft through unchanged.
Constitution
The numbered list of rules, each short and checkable, kept between runs.
Rule checkers
One per rule. Returns pass or fail and quotes the passage that breaks the rule.
All rules pass?
Counts failed rules and rounds used, and picks one of three exits.
Reviser
Fixes exactly the failed rules in the quoted passages and changes nothing else.
Compliant
The draft that passed every rule, with the check record.
Rejected
The last draft with the rules it still fails at the round limit.
  • Drafter → Rule checkers: draft
  • Constitution → Rule checkers: one rule each
  • Rule checkers → All rules pass?: pass or fail per rule
  • All rules pass? → Compliant: every rule passes
  • All rules pass? → Reviser: failures, rounds left
  • Reviser → Rule checkers: revised draft
  • All rules pass? → Rejected: failures, rounds spent

Where it connects

Entry
input
DraftAnswerDocumentTask

A text to check, or a task to write one for. The constitution is supplied separately or already stored.

Exit
compliant
AnswerDocument

When: Every rule passes, at any round within the limit.

The compliant text, followed by the check record listing each rule, its result per round and what was changed.

Exit
rejected
Verdict

When: Some rules still fail when the round limit is reached.

The last draft, each rule it still fails with the quoted passage, and the revision history. Must not be sent on as compliant.

Memory kept between runs
constitution
Knowledge

A numbered list of short rules, each with one example of a violation. Changed by its owners, never by the run.

4

What do I ask my assistant to set up?

The agents to launch

Drafter

If you are given a task, write a draft that fulfils it and respects the rules listed. If you are given an existing draft, return it unchanged.

Sees: The input and the full constitution.

Rule checker, one per rule in the constitution, at most twelve

You check one rule only. Read the draft and answer pass or fail. On a fail, quote every passage that breaks the rule and say why in one line. Ignore all other concerns.

Sees: The draft and one rule with its example. Not the other rules, the task's backstory or earlier rounds.

Reviser

Fix the quoted passages so that each failed rule passes. Change nothing else in the draft. Return the full revised draft and a list of what you changed.

Sees: The current draft, the failed rules with their quoted passages, and the full constitution. Not the checkers' passes.

A prompt you can paste

Works with any assistant that can launch sub-agents. It contains the agents, the procedure and the stop rule above.

Framework-agnostic prompt
You are the orchestrator of a multi-agent workflow that follows the "Constitutional Critique" architecture.
Launch every agent listed below as a separate sub-agent with its own context. Give each agent only the context stated for it. Do not do an agent's work yourself. If you cannot launch sub-agents, play each agent in a clearly separated turn and never let it use what is withheld from it.

# Task
[Describe your task here]

# Constitutional Critique
Check a draft against written rules and fix exactly what fails.
Input: the task above. It must provide: A text to check, or a task to write one for. The constitution is supplied separately or already stored. If something essential is missing, ask for it before starting.

Agents to launch:
- Drafter: If you are given a task, write a draft that fulfils it and respects the rules listed. If you are given an existing draft, return it unchanged.
  Context for this agent: The input and the full constitution.
- Rule checker (one per rule in the constitution, at most twelve): You check one rule only. Read the draft and answer pass or fail. On a fail, quote every passage that breaks the rule and say why in one line. Ignore all other concerns.
  Context for this agent: The draft and one rule with its example. Not the other rules, the task's backstory or earlier rounds.
- Reviser: Fix the quoted passages so that each failed rule passes. Change nothing else in the draft. Return the full revised draft and a list of what you changed.
  Context for this agent: The current draft, the failed rules with their quoted passages, and the full constitution. Not the checkers' passes.

Procedure:
1. Load the constitution. Each rule must be one checkable sentence with one example of a violation. Reject vague rules before starting.
2. Launch the drafter. If the input is already a draft, use it as is.
3. Launch one checker per rule as separate agents, in parallel, each on the current draft.
4. If every rule passes, deliver the draft as compliant.
5. If some rules fail and fewer than 2 revisions were made, launch the reviser with the failed rules and quotes, then repeat the checks on all rules.
6. If rules still fail after 2 revisions, deliver the draft as rejected.

Stop rule: Stop as soon as every rule passes, or after 2 revisions with failures left. In that case the draft leaves as rejected, never as compliant.

Exits:
- `compliant`, when: Every rule passes, at any round within the limit. Deliver: The compliant text, followed by the check record listing each rule, its result per round and what was changed.
- `rejected`, when: Some rules still fail when the round limit is reached. Deliver: The last draft, each rule it still fails with the quoted passage, and the revision history. Must not be sent on as compliant.

# Final deliverable
The final draft labelled compliant or rejected, then a table of every rule with its result per round, and the list of changes made by each revision.

The same thing in code

LangGraph, python, package langgraph
import operator
from typing import Annotated, TypedDict

from langchain.chat_models import init_chat_model
from langgraph.graph import END, START, StateGraph
from langgraph.types import Send
from pydantic import BaseModel

model = init_chat_model("anthropic:claude-sonnet-5-5")

# the constitution: short checkable rules, each with one example of a violation
CONSTITUTION: list[tuple[str, str]] = [
    ("Make no promise about delivery dates.", "Your order will arrive Friday."),
    ("Name no competitor.", "Unlike Acme, we..."),
][:12]  # at most twelve checkers
MAX_REVISIONS = 2

class Verdict(BaseModel):
    rule: int = 0
    passed: bool
    quotes: list[str]  # every passage that breaks the rule
    why: str

class Revision(BaseModel):
    draft: str
    changes: list[str]

class State(TypedDict):
    task: str
    draft: str
    revisions: int
    verdicts: Annotated[list[Verdict], operator.add]
    record: Annotated[list[str], operator.add]
    status: str

class CheckInput(TypedDict):
    draft: str
    rule: int

async def drafter(state: State) -> dict:
    rules = "\n".join(f"{i}. {r}" for i, (r, _) in enumerate(CONSTITUTION, 1))
    msg = await model.ainvoke(
        "If you are given a task, write a draft that fulfils it and respects these rules. "
        f"If you are given an existing draft, return it unchanged.\n\nRules:\n{rules}\n\nInput:\n{state['task']}")
    return {"draft": msg.text}

def fan_out(state: State) -> list[Send]:
    return [Send("checker", {"draft": state["draft"], "rule": i}) for i in range(len(CONSTITUTION))]

async def checker(state: CheckInput) -> dict:
    # sees the draft and one rule only, not the other rules or earlier rounds
    rule, example = CONSTITUTION[state["rule"]]
    v = Verdict.model_validate(await model.with_structured_output(Verdict).ainvoke(
        f"You check one rule only: {rule} (violation example: {example}). Answer pass or fail. "
        f"On a fail, quote every passage that breaks it and say why in one line.\n\nDraft:\n{state['draft']}"))
    return {"verdicts": [v.model_copy(update={"rule": state["rule"]})]}

def failures(state: State) -> list[Verdict]:
    return [v for v in state["verdicts"][-len(CONSTITUTION):] if not v.passed]  # this round's verdicts

async def gate(state: State) -> dict:
    failed = [v.rule + 1 for v in failures(state)]
    return {"record": [f"round {state['revisions']}: failed rules {failed or 'none'}"]}

def route(state: State):
    if not failures(state):
        return "compliant"
    if state["revisions"] < MAX_REVISIONS:  # the gate: at most 2 revisions
        return "reviser"
    return "rejected"

async def reviser(state: State) -> dict:
    # sees the failed rules with quotes and the constitution, not the passes
    failed = "\n".join(f"Rule {v.rule + 1}: {CONSTITUTION[v.rule][0]} Quotes: {v.quotes}" for v in failures(state))
    rev = Revision.model_validate(await model.with_structured_output(Revision).ainvoke(
        "Fix the quoted passages so each failed rule passes. Change nothing else. Return the full draft "
        f"and a list of changes.\n\nFailed:\n{failed}\n\nDraft:\n{state['draft']}"))
    return {"draft": rev.draft, "revisions": state["revisions"] + 1, "record": rev.changes}

async def compliant(state: State) -> dict:
    return {"status": "compliant"}

async def rejected(state: State) -> dict:
    return {"status": "rejected"}  # a separate exit: never released as compliant

graph = StateGraph(State)
graph.add_node("drafter", drafter)
graph.add_node("checker", checker, input_schema=CheckInput)
graph.add_node("gate", gate)
graph.add_node("reviser", reviser)
graph.add_node("compliant", compliant)
graph.add_node("rejected", rejected)
graph.add_edge(START, "drafter")
graph.add_conditional_edges("drafter", fan_out, ["checker"])
graph.add_edge("checker", "gate")
graph.add_conditional_edges("gate", route, ["compliant", "reviser", "rejected"])
graph.add_conditional_edges("reviser", fan_out, ["checker"])  # every rule is checked again
graph.add_edge("compliant", END)
graph.add_edge("rejected", END)
app = graph.compile()

async def run(task: str):
    s = await app.ainvoke({"task": task, "draft": "", "revisions": 0, "verdicts": [], "record": [], "status": ""})
    return {"status": s["status"], "draft": s["draft"], "record": s["record"], "verdicts": s["verdicts"]}

Load CONSTITUTION from the file its owners maintain, and send rejected drafts to a person rather than back to the caller.

Claude Agent SDK, python, package claude-agent-sdk
import asyncio
from typing import TypeVar

from claude_agent_sdk import AgentDefinition, ClaudeAgentOptions, ResultMessage, query
from pydantic import BaseModel

CONSTITUTION: list[tuple[str, str]] = [  # short checkable rules, each with one violation example
    ("Make no promise about delivery dates.", "Your order will arrive Friday."),
    ("Name no competitor.", "Unlike Acme, we..."),
][:12]  # at most twelve checkers
MAX_REVISIONS = 2
RULES = "\n".join(f"{i}. {r}" for i, (r, _) in enumerate(CONSTITUTION, 1))

AGENTS = {
    "drafter": AgentDefinition(
        description="Writes a draft for a task, or passes an existing draft through unchanged.",
        prompt=f"If given a task, write a draft that fulfils it and respects these rules:\n{RULES}\n"
               "If given an existing draft, return it unchanged.", tools=[]),
    "checker": AgentDefinition(
        description="Checks a draft against exactly one rule.",
        prompt="You check one rule only. Answer pass or fail. On a fail, quote every passage that breaks "
               "the rule and say why in one line. Ignore all other concerns.", tools=[]),
    "reviser": AgentDefinition(
        description="Fixes only the quoted passages that fail rules.",
        prompt=f"Fix the quoted passages so each failed rule passes. Change nothing else.\nRules:\n{RULES}",
        tools=[]),
}

class Draft(BaseModel):
    draft: str
    changes: list[str] = []

class Verdict(BaseModel):
    passed: bool
    quotes: list[str]
    why: str

M = TypeVar("M", bound=BaseModel)

async def delegate(agent: str, payload: str, schema: type[M]) -> M:
    # each call is a fresh sub-agent run: it sees only the payload it is handed
    options = ClaudeAgentOptions(
        agents={agent: AGENTS[agent]}, allowed_tools=["Agent"], permission_mode="dontAsk",
        output_format={"type": "json_schema", "schema": schema.model_json_schema()})
    prompt = f"Hand exactly this input to the {agent} agent and return its result.\n\n{payload}"
    async for msg in query(prompt=prompt, options=options):
        if isinstance(msg, ResultMessage) and msg.structured_output:
            return schema.model_validate(msg.structured_output)
    raise RuntimeError(f"{agent} returned no result")

async def run(task: str):
    draft = (await delegate("drafter", task, Draft)).draft
    record: list[str] = []
    for revision in range(MAX_REVISIONS + 1):
        verdicts = await asyncio.gather(*(  # one checker per rule, in parallel
            delegate("checker", f"Rule: {rule}\nViolation example: {ex}\n\nDraft:\n{draft}", Verdict)
            for rule, ex in CONSTITUTION))
        failed = [(i, v) for i, v in enumerate(verdicts) if not v.passed]
        record.append(f"round {revision}: failed rules {[i + 1 for i, _ in failed] or 'none'}")
        if not failed:
            return {"status": "compliant", "draft": draft, "record": record}
        if revision == MAX_REVISIONS:  # the gate: 2 revisions spent, leave by the rejected exit
            break
        quotes = "\n".join(f"Rule {i + 1}: {CONSTITUTION[i][0]} Quotes: {v.quotes} ({v.why})" for i, v in failed)
        fixed = await delegate("reviser", f"Failed rules:\n{quotes}\n\nDraft:\n{draft}", Draft)
        draft, record = fixed.draft, record + fixed.changes
    return {"status": "rejected", "draft": draft, "record": record, "still_failing": [i + 1 for i, _ in failed]}

Load CONSTITUTION from the file its owners maintain, and route rejected drafts to a person.

OpenAI Agents SDK, python, package openai-agents
import asyncio

from agents import Agent, Runner
from pydantic import BaseModel

CONSTITUTION: list[tuple[str, str]] = [  # short checkable rules, each with one violation example
    ("Make no promise about delivery dates.", "Your order will arrive Friday."),
    ("Name no competitor.", "Unlike Acme, we..."),
][:12]  # at most twelve checkers
MAX_REVISIONS = 2
RULES = "\n".join(f"{i}. {r}" for i, (r, _) in enumerate(CONSTITUTION, 1))

class Verdict(BaseModel):
    passed: bool
    quotes: list[str]
    why: str

class Revision(BaseModel):
    draft: str
    changes: list[str]

drafter = Agent(
    name="Drafter",
    instructions=f"If given a task, write a draft that fulfils it and respects these rules:\n{RULES}\n"
                 "If given an existing draft, return it unchanged.")
checker = Agent(
    name="Rule checker",
    instructions="You check one rule only. Answer pass or fail. On a fail, quote every passage that breaks "
                 "the rule and say why in one line. Ignore all other concerns.",
    output_type=Verdict)
reviser = Agent(
    name="Reviser",
    instructions=f"Fix the quoted passages so each failed rule passes. Change nothing else. "
                 f"Return the full draft and a list of changes.\nRules:\n{RULES}",
    output_type=Revision)

async def check(rule: str, example: str, draft: str) -> Verdict:
    # the checker sees the draft and one rule, nothing else
    result = await Runner.run(checker, f"Rule: {rule}\nViolation example: {example}\n\nDraft:\n{draft}")
    return result.final_output_as(Verdict)

async def run(task: str):
    draft = str((await Runner.run(drafter, task)).final_output)
    record: list[str] = []
    for revision in range(MAX_REVISIONS + 1):
        verdicts = await asyncio.gather(*(check(r, ex, draft) for r, ex in CONSTITUTION))
        failed = [(i, v) for i, v in enumerate(verdicts) if not v.passed]
        record.append(f"round {revision}: failed rules {[i + 1 for i, _ in failed] or 'none'}")
        if not failed:
            return {"status": "compliant", "draft": draft, "record": record}
        if revision == MAX_REVISIONS:  # the gate: 2 revisions spent, leave by the rejected exit
            break
        quotes = "\n".join(f"Rule {i + 1}: {CONSTITUTION[i][0]} Quotes: {v.quotes} ({v.why})" for i, v in failed)
        fixed = (await Runner.run(reviser, f"Failed rules:\n{quotes}\n\nDraft:\n{draft}")).final_output_as(Revision)
        draft, record = fixed.draft, record + fixed.changes
    return {"status": "rejected", "draft": draft, "record": record, "still_failing": [i + 1 for i, _ in failed]}

Load CONSTITUTION from the file its owners maintain, and route rejected drafts to a person.

Vercel AI SDK, typescript, package ai
import { anthropic } from '@ai-sdk/anthropic';
import { generateText, Output } from 'ai';
import { z } from 'zod';

const model = anthropic('claude-sonnet-5-5');
// short checkable rules, each with one violation example; at most twelve checkers
const CONSTITUTION: [rule: string, example: string][] = [
  ['Make no promise about delivery dates.', 'Your order will arrive Friday.'],
  ['Name no competitor.', 'Unlike Acme, we...'],
].slice(0, 12) as [string, string][];
const MAX_REVISIONS = 2;
const RULES = CONSTITUTION.map(([r], i) => `${i + 1}. ${r}`).join('\n');

const Verdict = z.object({ passed: z.boolean(), quotes: z.array(z.string()), why: z.string() });
const Revision = z.object({ draft: z.string(), changes: z.array(z.string()) });

async function drafter(input: string) {
  const { text } = await generateText({
    model,
    instructions: `If given a task, write a draft that fulfils it and respects these rules:\n${RULES}\n`
      + 'If given an existing draft, return it unchanged.',
    prompt: input,
  });
  return text;
}

// the checker sees the draft and one rule, nothing else
async function checker([rule, example]: [string, string], draft: string) {
  const { output } = await generateText({
    model,
    instructions: 'You check one rule only. Answer pass or fail. On a fail, quote every passage that breaks '
      + 'the rule and say why in one line. Ignore all other concerns.',
    prompt: `Rule: ${rule}\nViolation example: ${example}\n\nDraft:\n${draft}`,
    output: Output.object({ schema: Verdict }),
  });
  return output;
}

async function reviser(failed: string, draft: string) {
  const { output } = await generateText({
    model,
    instructions: 'Fix the quoted passages so each failed rule passes. Change nothing else. '
      + `Return the full draft and a list of changes.\nRules:\n${RULES}`,
    prompt: `Failed rules:\n${failed}\n\nDraft:\n${draft}`,
    output: Output.object({ schema: Revision }),
  });
  return output;
}

export async function run(task: string) {
  let draft = await drafter(task);
  const record: string[] = [];
  let failing: number[] = [];
  for (let revision = 0; revision <= MAX_REVISIONS; revision++) {
    const verdicts = await Promise.all(CONSTITUTION.map((rule) => checker(rule, draft))); // one per rule
    const failed = verdicts.map((v, i) => ({ v, i })).filter(({ v }) => !v.passed);
    failing = failed.map(({ i }) => i + 1);
    record.push(`round ${revision}: failed rules ${failing.join(', ') || 'none'}`);
    if (failed.length === 0) return { status: 'compliant', draft, record };
    if (revision === MAX_REVISIONS) break; // the gate: 2 revisions spent, leave by the rejected exit
    const quotes = failed
      .map(({ v, i }) => `Rule ${i + 1}: ${CONSTITUTION[i][0]} Quotes: ${v.quotes.join(' | ')} (${v.why})`)
      .join('\n');
    const fixed = await reviser(quotes, draft);
    draft = fixed.draft;
    record.push(...fixed.changes);
  }
  return { status: 'rejected', draft, record, stillFailing: failing };
}

Load CONSTITUTION from the file its owners maintain, and route rejected drafts to a person.

Snippets are generated when the site is built and type-checked against the SDK versions listed in the repository. Treat them as a starting skeleton.

What goes wrong

  • Rules such as "be respectful" get inconsistent verdicts. Rewrite each rule so that a quoted passage can prove a failure.
  • Checking all rules in one call lets the checker skim. One rule per checker costs more and misses less.
  • A reviser that rewrites the whole draft breaks rules that passed. Restrict it to the quoted passages and recheck everything.

Chain it

It can take the result of

Source