Courses  /  AI Agents

Agent Workflows as Graphs

One-day, hands-on workshop. Turn agent workflows into measurable graphs so you can test structure, calculate reliability, catch failures before execution, and validate whether they are ready to run.

Plain language, step by step. No API key needed — the measurement and governance layers are deterministic and need no LLM calls.

Start here

How to use this workshop

What it is

Read in order, one lesson at a time. Tick the Done box when you finish a lesson. Your progress is saved in your browser. Every lesson has the same shape: What it is, Why it matters, code you can copy and run, a small task to try yourself, and two check questions with the answers hidden until you open them.

Why it matters

A workshop only works if you do it, not just read it. The tick boxes and the small tasks keep you moving, one small step at a time, from a plan on paper to a certified workflow.

# No code to run in this lesson.
# Just read the plan below, then start with Setup.
print('Ready. Start with Setup.')

Try it yourself

Tick the Done box on this lesson and watch the progress bar move.

Check

What is the goal of this workshop?

To turn agent workflows into measurable graphs, so you can test structure, calculate reliability, catch failures before execution, and certify whether a workflow is ready to run.

Do you need a paid API key for this workshop?

No. The measurement and governance layers are deterministic. No LLM calls are needed for them.

Start here

Setup — what you need

What it is

You need Python 3.10 or newer, and two small libraries: networkx (for graph maths) and numpy (for numbers). The workshop code itself only needs the standard Python library for the practice versions in this page, so you can run every example here with plain python3 and no install at all. The real workshop code in the repo uses networkx.

Why it matters

If setup is hard, you never start. Keep it to three commands, then run the labs and learn by doing.

# Check your Python version (you need 3.10 or newer)
import sys
print(sys.version)
print("OK" if sys.version_info >= (3, 10) else "Please upgrade Python")

# Real workshop setup (run in your terminal, not here):
#   python -m venv .venv && source .venv/bin/activate
#   pip install -r requirements.txt   # networkx>=3.0, numpy>=1.24
#   python run_all_labs.py            # runs all five labs
#   python labs/lab1_compile_dag.py   # or run one lab at a time

Try it yourself

Run the code above. Then, in your terminal, try pip install networkx numpy (optional — the examples on this page run without them).

Check

What Python version do you need?

Python 3.10 or newer.

What two libraries does the real workshop use?

networkx and numpy.

Section 1 — Why Graph Engineering?

Linear scripts vs a graph model

What it is

Most agent prototypes are written as a straight line: user → planner → tool 1 → tool 2 → writer → answer. That works for a demo. A graph model instead draws the whole workflow as a picture: boxes (nodes) for each agent, tool, gate, or ending point, and arrows (edges) for the links between them. The picture is the plan, and the computer can read it and check it.

Why it matters

A straight line hides the structure. You cannot see what depends on what, so you cannot answer simple questions like 'what breaks if this step fails?' A graph makes the structure visible and checkable before anything runs.

# A linear script: the structure is hidden inside the code.
steps = ["planner", "tool_1", "tool_2", "writer"]
print(" -> ".join(steps))

# The same workflow as a graph: nodes + edges, written down as data.
nodes = ["planner", "researcher", "fact_checker", "analyst", "writer"]
edges = [("planner", "researcher"), ("researcher", "fact_checker"),
         ("fact_checker", "analyst"), ("analyst", "writer")]
print("Nodes:", nodes)
print("Edges:", edges)
print("Now the computer can check the structure before running anything.")

Try it yourself

Draw your own agent workflow as nodes and edges on paper: 4 boxes, 3 arrows. Then write it as two Python lists like above.

Check

What is a node in an agent graph?

One step in the workflow: an agent, a tool, a gate, or a terminal (ending) point.

What is an edge?

An arrow between two nodes. It says one step depends on the other, or hands its work to it.

Section 1 — Why Graph Engineering?

The 6 questions a graph can answer

What it is

Once the workflow is a graph, you can answer six questions that a linear script cannot answer: (1) What fails if node X fails? (2) What is the end-to-end reliability? (3) Are we within the exception budget? (4) Does the plan meet the token, depth, and capability limits? (5) Did behaviour drift from last week? (6) Can we certify the workflow before it runs?

Why it matters

These are the questions a team lead, a customer, or a regulator will ask before a system goes live. If you cannot answer them, you are guessing. A graph lets you compute the answers.

# The six questions, as checks you can run on a graph.
QUESTIONS = [
    "1. What fails if node X fails?        -> downstream closure",
    "2. End-to-end reliability?             -> product of path reliabilities",
    "3. Within the exception budget?        -> allowed failure - observed failure",
    "4. Token / depth / capability limits?  -> deterministic gate",
    "5. Did behaviour drift?                -> trace fingerprint + downstream impact",
    "6. Can we certify it before it runs?   -> scorecard",
]
for q in QUESTIONS:
    print(q)

Try it yourself

Pick one of the six questions and write, in one sentence, why it matters for a system that handles money or health information.

Check

Which question is about cost?

Question 4: does the plan meet the token, depth, and capability limits? Tokens are what you pay for.

Which question is about change over time?

Question 5: did behaviour drift from last week? You compare a new trace with the baseline trace.

Section 1 — Why Graph Engineering?

What you get in this workshop

What it is

This is a one-day, hands-on workshop. You get: the tutorial (this page follows it), a core library (AgentGraph, DAG compiler, reliability engine, governance gate, GraphRAG, tracing and certification), five labs, sample data (healthy, broken, low-reliability, and over-budget plans, plus a GraphRAG knowledge base), and a one-command runner, run_all_labs.py, that runs all five labs and prints a final scorecard.

Why it matters

Knowing the map before you start means you never wonder what comes next. Each lab builds on the one before it, and the last one puts the whole pipeline together.

# The workshop map, as data.
labs = [
    ("Lab 1", "Compile an agent plan into a DAG"),
    ("Lab 2", "Measure and repair reliability"),
    ("Lab 3", "Build a governance gate"),
    ("Lab 4", "GraphRAG retrieval with provenance"),
    ("Lab 5", "Execute, trace, and certify"),
]
for name, title in labs:
    print(name + ": " + title)
print("Every lab ends with a PASS / FAIL verdict.")

Try it yourself

Run the code above, then say out loud what Lab 3 will teach you, in your own words.

Check

How many labs are there, and how does each one end?

Five labs. Each one ends with a PASS / FAIL verdict.

Section 1 — Why Graph Engineering?

Who this workshop is for, and what you will learn

What it is

This workshop is for senior AI and ML engineers, engineers moving agent workflows from prototypes into production, solution and platform architects, and tech leads responsible for reliability, cost, and governance. By the end you will be able to: model workflows as graphs; measure reliability before execution; improve reliability efficiently; govern plans before they run; choose between vector RAG and GraphRAG; build retrieval with provenance; trace execution and detect drift; and certify the complete workflow.

Why it matters

A workshop is only useful if it matches your job. If you are responsible for a system that must not fail silently, must stay within a budget, and must be explainable, this is your workshop.

# The eight outcomes, as a checklist you will tick off.
outcomes = [
    "Model agent workflows as graphs",
    "Measure reliability before execution",
    "Improve reliability efficiently",
    "Govern agent plans before they run",
    "Choose between vector RAG and GraphRAG",
    "Build retrieval with provenance",
    "Trace execution and detect drift",
    "Certify the complete workflow",
]
for i, o in enumerate(outcomes, 1):
    print(f"[ ] {i}. {o}")

Try it yourself

Which of the eight outcomes matters most for your own work? Write it down and keep it in mind as you go through the labs.

Check

What does 'certify the complete workflow' mean?

Bringing all the checks together into one scorecard that says CERTIFIED or NOT CERTIFIED before the workflow is allowed to run.

Do you need to be an expert in graphs already?

No. The workshop teaches DAGs, reliability, and gates from the start, in plain steps.

Section 2 — Core Concepts

2.1 Agent Graph — nodes and edges

What it is

An Agent Graph is a directed graph. Each node (box) carries: an id, a name, a type (agent, tool, gate, or terminal), a reliability between 0 and 1, a token cost, a list of capabilities, and whether it is registered. Each edge (arrow) carries an optional condition (a rule for when to follow it) and a weight. Terminal nodes are the ones whose successful completion defines workflow success.

Why it matters

If the graph is the plan, then the node details are the facts the checks need. Reliability, cost, and capabilities are not decoration — they are the numbers the reliability engine and the governance gate read.

# An agent graph, written as plain Python data.
# Real code: from src.graph import AgentGraph (uses networkx DiGraph).
# Practice version below: plain dicts, so it runs with no install.
nodes = [
    {"id": "planner", "type": "agent", "reliability": 0.99,
     "token_cost": 800, "capabilities": ["planning"], "registered": True},
    {"id": "researcher", "type": "agent", "reliability": 0.98,
     "token_cost": 1500, "capabilities": ["search"], "registered": True},
    {"id": "writer", "type": "terminal", "reliability": 0.99,
     "token_cost": 900, "capabilities": ["writing"], "registered": True},
]
edges = [("planner", "researcher"), ("researcher", "writer")]
for n in nodes:
    print(n["id"], "|", n["type"], "| reliability", n["reliability"],
          "| tokens", n["token_cost"])
print("Terminals:", [n["id"] for n in nodes if n["type"] == "terminal"])

Try it yourself

Add a fourth node to the graph above: a fact_checker (type gate, reliability 0.99, token cost 1200, capability 'verification', registered True), and an edge from researcher to fact_checker.

Check

What does 'registered' mean for a node?

The agent or tool is listed in the capability registry — the workshop's official list of allowed agents and tools.

What is a terminal node?

A node whose successful completion defines workflow success — the ending point of the workflow.

Section 2 — Core Concepts

2.2 DAG Compilation — from plan to graph

What it is

DAG stands for Directed Acyclic Graph: directed means the arrows have a direction, acyclic means there are no loops (you can never come back to a node you already visited). Compilation turns a declarative plan — a dict, JSON, or YAML file that says what the workflow should be — into an AgentGraph. The compiler: (1) creates every declared agent, (2) wires the dependencies, (3) runs structural checks for cycles, orphans, dangling references, and unregistered agents, and (4) computes topological execution levels (which nodes can run first, second, third, and so on).

Why it matters

A plan written as data can be checked, versioned, and reviewed like any other file. A plan hidden inside code cannot. Compilation is the step that turns words into something checkable.

# Compile a plan dict into a graph, step by step (practice version).
# Real code: from src.dag_compiler import compile_plan_to_dag
plan = {
    "name": "research_workflow",
    "nodes": ["planner", "researcher", "fact_checker", "analyst", "writer"],
    "edges": [("planner", "researcher"), ("researcher", "fact_checker"),
              ("fact_checker", "analyst"), ("analyst", "writer")],
    "terminals": ["writer"],
}

def compile_plan(plan):
    graph = {n: [] for n in plan["nodes"]}          # 1. create nodes
    for a, b in plan["edges"]:                      # 2. wire dependencies
        graph[a].append(b)
    errors = []                                     # 3. structural checks
    for a, b in plan["edges"]:
        if b not in graph:
            errors.append("DANGLING_REFERENCE: " + b)
    # 4. execution levels: nodes with no incoming edges first
    incoming = {n: 0 for n in plan["nodes"]}
    for a, b in plan["edges"]:
        incoming[b] += 1
    level, levels = 0, {}
    remaining = set(plan["nodes"])
    while remaining:
        ready = sorted(n for n in remaining if incoming[n] == 0)
        if not ready:
            errors.append("CYCLE_DETECTED")
            break
        levels[level] = ready
        for n in ready:
            remaining.remove(n)
            for m in graph[n]:
                incoming[m] -= 1
        level += 1
    return graph, levels, errors

graph, levels, errors = compile_plan(plan)
print("Valid:", not errors, "| Errors:", errors)
print("Execution levels:", levels)

Try it yourself

Change one edge in the plan above to ('writer', 'planner') and run it again. What error do you get, and why?

Check

What does DAG stand for?

Directed Acyclic Graph — directed arrows, and no loops (acyclic).

What are topological execution levels?

The order nodes can run in: level 0 runs first, then level 1, and so on. A node only runs after everything it depends on.

Section 2 — Core Concepts

2.3 Reliability — the product rule and the exception budget

What it is

If each node fails independently, the reliability of a whole path is the product of the reliabilities of its nodes: multiply them together. For a graph with several paths, take the minimum path reliability as the safe, conservative estimate. Worked example: five nodes with reliabilities 0.99, 0.98, 0.99, 0.97, 0.99. Multiply: 0.99 × 0.98 = 0.970, × 0.99 = 0.961, × 0.97 = 0.932, × 0.99 = 0.922. So the workflow succeeds about 92 times out of 100. The exception budget is the allowed failure rate minus the observed failure rate. If the target is 0.90 reliability, the allowed failure rate is 10%. Observed failure is 100% − 92.2% = 7.8%. Budget remaining: 10% − 7.8% = 2.2%. Still inside budget, but not by much.

Why it matters

Long chains drop fast. Each extra step multiplies by a number below 1, so the total keeps shrinking. That is why a five-step workflow at 0.99 per step is only about 95% reliable, and why measuring matters more than guessing.

# Reliability: multiply the nodes on a path.
# Real code: from src.reliability import ReliabilityEngine
nodes = [("planner", 0.99), ("researcher", 0.98), ("fact_checker", 0.99),
         ("analyst", 0.97), ("writer", 0.99)]
reliability = 1.0
for name, r in nodes:
    reliability *= r
    print(f"after {name}: {reliability:.4f}")
target = 0.90
allowed_failure = 1 - target
observed_failure = 1 - reliability
print(f"Terminal reliability: {reliability:.3f}")
print(f"Exception budget remaining: {allowed_failure - observed_failure:.3f} "
      f"(allowed {allowed_failure:.2f} - observed {observed_failure:.3f})")
print("Meets target 0.90:", reliability >= target)

Try it yourself

Change the analyst reliability to 0.85 and run again. What is the new terminal reliability, and is the exception budget still positive?

Check

Why multiply, not add, the reliabilities?

Because every step must succeed for the path to succeed. If each step succeeds 99 times out of 100, five steps in a row succeed about 95 times out of 100, not 99.

What is the exception budget?

Allowed failure rate minus observed failure rate. Positive means you are inside budget; negative means you have spent it.

Section 2 — Core Concepts

2.4 Governance Gate — a pure function that says PASS or REJECT

What it is

A governance gate is a pure function: plan in, verdict out — PASS or REJECT, plus a scorecard. Pure means the same plan always gives the same verdict, with no hidden state and no LLM call. It checks: is it a DAG, are all agents registered, is depth within the limit, are tokens within budget, is reliability at or above the SLA (service level agreement), are the required capabilities present, and is there at least one terminal node.

Why it matters

A gate that depends on an LLM's mood is not a gate. A pure function is testable, repeatable, and safe to run in CI (the automatic checks that run on every change). If a plan fails, it never runs — no cost, no risk.

# A governance gate as a pure function (practice version).
# Real code: from src.governance import GovernanceGate
def governance_gate(plan, min_reliability=0.90, max_tokens=8000,
                    max_depth=10, required_capabilities=("planning",)):
    checks = {}
    checks["is_dag"] = not plan.get("has_cycle", False)
    checks["all_registered"] = all(n["registered"] for n in plan["nodes"])
    checks["depth_ok"] = plan["depth"] <= max_depth
    checks["tokens_ok"] = sum(n["token_cost"] for n in plan["nodes"]) <= max_tokens
    checks["reliability_ok"] = plan["reliability"] >= min_reliability
    caps = {c for n in plan["nodes"] for c in n["capabilities"]}
    checks["capabilities_ok"] = all(c in caps for c in required_capabilities)
    checks["has_terminal"] = any(n["type"] == "terminal" for n in plan["nodes"])
    verdict = "PASS" if all(checks.values()) else "REJECT"
    return verdict, checks

plan = {"has_cycle": False, "depth": 5, "reliability": 0.922,
        "nodes": [
            {"registered": True, "token_cost": 800, "capabilities": ["planning"], "type": "agent"},
            {"registered": True, "token_cost": 1500, "capabilities": ["search"], "type": "agent"},
            {"registered": True, "token_cost": 900, "capabilities": ["writing"], "type": "terminal"},
        ]}
verdict, checks = governance_gate(plan)
for k, v in checks.items():
    print(("PASS " if v else "FAIL ") + k)
print("Verdict:", verdict)

Try it yourself

Set the plan reliability to 0.85 and run again. Which check fails, and what is the verdict?

Check

What does 'pure function' mean here?

Same input, same output, every time. No hidden state, no randomness, no LLM call inside the gate.

What is an SLA?

A Service Level Agreement — the reliability level you promised, for example 0.90. The gate checks the plan meets it.

Section 2 — Core Concepts

2.5 GraphRAG — vector search vs graph traversal

What it is

Vector similarity finds documents that are relevant to a question. Graph traversal finds connected facts, and returns the explicit path that links them to the question — the provenance. Hybrid retrieval uses vector hits as starting points (seeds), then expands across the graph for up to a few hops. Example provenance path: project_x --depends_on--> project_y --owned_by--> platform_team.

Why it matters

A similarity score cannot explain itself. A path can. For a regulator, an auditor, or a debugging engineer, the path is the answer: it shows how a fact was found, step by step.

# GraphRAG: vector hits as seeds, then graph hops (practice version).
# Real code: from src.graphrag import GraphRAG, GraphEntity, GraphRelation
relations = [
    ("project_x", "depends_on", "project_y"),
    ("project_y", "owned_by", "platform_team"),
    ("platform_team", "led_by", "alice"),
]
def graph_search(seed, max_hops=2):
    paths, frontier = [[seed]], [seed]
    for hop in range(max_hops):
        nxt = []
        for node in frontier:
            for a, rel, b in relations:
                if a == node:
                    paths.append([seed] + [r[2] for r in relations
                                            if r[0] == seed][:0] + [b])
                    nxt.append(b)
        frontier = nxt
    return paths

# Simpler, explicit walk: follow depends_on, then owned_by.
def walk(start, max_hops=2):
    path, current = [start], start
    for _ in range(max_hops):
        nxt = [b for a, rel, b in relations if a == current]
        if not nxt:
            break
        current = nxt[0]
        path.append(current)
    return path

print("Vector search would return: documents similar to the question.")
print("Graph search path:", " -- ".join(walk("project_x", max_hops=2)))
print("Provenance: project_x --depends_on--> project_y --owned_by--> platform_team")

Try it yourself

Add a relation ("alice", "works_on", "project_x") to the list above, then walk from "alice" for 2 hops. What path do you get?

Check

What is provenance?

The explicit path showing how a retrieved fact connects back to the query — who depends on whom, who owns what.

When is vector search enough, and when do you need graph traversal?

Vector search is enough for 'find similar documents'. Graph traversal is needed for multi-hop questions like 'who leads the team that owns the project this depends on?'

Section 2 — Core Concepts

2.6 Trace & Drift — compare a new run with the baseline

What it is

Every execution produces a node-level trace: for each node, its status (ok or failed), latency, tokens used, and an output hash (a short fingerprint of what it produced). Comparing a new trace with the baseline trace reveals which nodes drifted — changed behaviour — and the downstream subgraph they affect. If the fact checker starts failing, everything after it is suspect, even if those nodes report ok.

Why it matters

Without a baseline, every run looks new. With a baseline, a change is visible the moment it happens, and you can see how far its damage spreads.

# Trace and drift: compare two runs node by node (practice version).
# Real code: from src.tracing import ExecutionTracer, DriftDetector
baseline = {"planner": "ok", "researcher": "ok", "fact_checker": "ok",
            "analyst": "ok", "writer": "ok"}
drifted = {"planner": "ok", "researcher": "ok", "fact_checker": "FAILED",
           "analyst": "ok", "writer": "ok"}
order = ["planner", "researcher", "fact_checker", "analyst", "writer"]
drifted_nodes = [n for n in order if baseline[n] != drifted[n]]
print("Drifted nodes:", drifted_nodes)
# Downstream impact: everything after the first drifted node.
first = order.index(drifted_nodes[0])
print("Downstream impact:", order[first + 1:])
print("Severity: HIGH" if drifted_nodes else "none")

Try it yourself

Change the drifted trace so the researcher fails instead. Which nodes are now in the downstream impact?

Check

What is an output hash?

A short fingerprint of what a node produced. If the hash changes, the output changed, even if the status still says ok.

What is downstream impact?

All the nodes after a drifted node. They may have received bad input, so their results cannot be trusted either.

Section 2 — Core Concepts

2.7 Certification — one scorecard, one verdict

What it is

Certification brings everything together into one scorecard that ANDs seven dimensions: structural, reliability, token budget, governance, provenance, execution trace, and drift. AND means every dimension must pass. If any one fails, the verdict is NOT CERTIFIED. Only CERTIFIED workflows are promoted to the serving layer — the place where real users meet the system.

Why it matters

One weak link, one verdict. That is the whole point: certification is not an average. A workflow that is fast but unreliable, or reliable but ungoverned, does not ship.

# Certification scorecard: every dimension must pass (practice version).
# Real code: from src.tracing import certify_workflow
scorecard = {
    "Structural": True, "Reliability": True, "Token budget": True,
    "Governance": True, "Provenance": True, "Execution trace": True,
    "Drift": True,
}
for dim, ok in scorecard.items():
    print(("PASS " if ok else "FAIL ") + dim)
verdict = "CERTIFIED" if all(scorecard.values()) else "NOT CERTIFIED"
print("Verdict:", verdict)

# Now break one dimension:
scorecard["Drift"] = False
print("With drift failing ->", "CERTIFIED" if all(scorecard.values()) else "NOT CERTIFIED")

Try it yourself

Set two dimensions to False in the scorecard above and run it. What is the verdict, and why is it not a partial pass?

Check

What does AND mean in a scorecard?

Every dimension must pass. One failure means the whole workflow is NOT CERTIFIED.

What is the serving layer?

The live system real users talk to. Only CERTIFIED workflows are promoted to it.

Lab 1 — Compile an Agent Plan into a DAG

Lab 1a — Compile the healthy plan

What it is

Turn a declarative plan into a graph with compile_plan_to_dag(plan_dict). The healthy plan in the workshop has 5 nodes and 4 edges, and compiles to a valid DAG with execution levels 0 to 4. The lab command is: python labs/lab1_compile_dag.py

Why it matters

This is the first gate. If the plan does not compile cleanly, nothing else matters — you fix the structure before you spend a single token.

# Lab 1: compile the healthy plan (practice version, stdlib only).
# Real code: from src.dag_compiler import compile_plan_to_dag
plan = {
    "name": "healthy_workflow",
    "nodes": ["planner", "researcher", "fact_checker", "analyst", "writer"],
    "edges": [("planner", "researcher"), ("researcher", "fact_checker"),
              ("fact_checker", "analyst"), ("analyst", "writer")],
}
def compile_plan(plan):
    incoming = {n: 0 for n in plan["nodes"]}
    for a, b in plan["edges"]:
        incoming[b] += 1
    levels, remaining, level = {}, set(plan["nodes"]), 0
    while remaining:
        ready = sorted(n for n in remaining if incoming[n] == 0)
        if not ready:
            return False, levels, ["CYCLE_DETECTED"]
        levels[level] = ready
        for n in ready:
            remaining.remove(n)
            for a, b in plan["edges"]:
                if a == n:
                    incoming[b] -= 1
        level += 1
    return True, levels, []

valid, levels, errors = compile_plan(plan)
print("Valid DAG:", valid)
print("Nodes: 5, Edges: 4")
print("Execution levels:", levels)
print("Errors:", errors)

Try it yourself

Run the code above, then write down the execution level of the analyst node.

Check

How many nodes and edges does the healthy plan have?

5 nodes and 4 edges.

What are the execution levels of the healthy plan?

Levels 0 to 4: planner, researcher, fact_checker, analyst, writer, one per level.

Lab 1 — Compile an Agent Plan into a DAG

Lab 1b — Catch the broken plans

What it is

Three kinds of broken plan, three error names: CYCLE_DETECTED (an arrow loops back), UNREGISTERED_AGENT (a node is not in the registry), and DANGLING_REFERENCE (an edge points to a node that does not exist). The compiler must report all of them, clearly, before anything runs.

Why it matters

Catching these early is the whole value of Lab 1. A cycle would loop forever. An unregistered agent might be a typo that calls the wrong tool. A dangling reference would crash at run time.

# Lab 1: three broken plans, three error names (practice version).
def check_plan(nodes, edges, registered):
    errors = []
    for a, b in edges:
        if b not in nodes:
            errors.append("DANGLING_REFERENCE: " + b)
    for n in nodes:
        if n not in registered:
            errors.append("UNREGISTERED_AGENT: " + n)
    # Cycle check: can we order the nodes? (same level algorithm as Lab 1a)
    incoming = {n: 0 for n in nodes}
    for a, b in edges:
        if b in incoming:
            incoming[b] += 1
    remaining = set(nodes)
    while remaining:
        ready = [n for n in remaining if incoming[n] == 0]
        if not ready:
            errors.append("CYCLE_DETECTED")
            break
        for n in ready:
            remaining.remove(n)
            for a, b in edges:
                if a == n and b in incoming:
                    incoming[b] -= 1
    return errors

registered = {"planner", "researcher", "fact_checker", "analyst", "writer"}
print("Cycle plan:", check_plan(
    ["planner", "researcher"], [("planner", "researcher"), ("researcher", "planner")], registered))
print("Unregistered plan:", check_plan(
    ["planner", "mystery_agent"], [("planner", "mystery_agent")], registered))
print("Dangling plan:", check_plan(
    ["planner"], [("planner", "ghost_node")], registered))

Try it yourself

Write a fourth broken plan of your own: a plan with an orphan node (a node with no edges at all). Does the checker flag it? Should it?

Check

What does CYCLE_DETECTED mean?

An arrow loops back to a node already visited, so the workflow could never finish.

What does DANGLING_REFERENCE mean?

An edge points to a node that does not exist in the plan.

Lab 2 — Measure and Repair Reliability

Lab 2a — Measure reliability and the exception budget

What it is

Use ReliabilityEngine(target_reliability=0.95) and engine.measure(graph). It reports the terminal reliability and the exception budget. The lab command is: python labs/lab2_reliability.py. Worked numbers with our five nodes (0.99, 0.98, 0.99, 0.97, 0.99): terminal reliability 0.922. Against a target of 0.95, the allowed failure rate is 5%, the observed failure rate is 7.8%, so the exception budget is 5% − 7.8% = −2.8%. Negative: over budget. Against a target of 0.90, the budget is 10% − 7.8% = +2.2%. Inside budget.

Why it matters

A target is a promise. Measuring against it tells you whether the promise holds. A negative budget is not a small warning — it means the workflow fails more often than you are allowed to fail.

# Lab 2: measure reliability and the exception budget (practice version).
# Real code: from src.reliability import ReliabilityEngine
class ReliabilityEngine:
    def __init__(self, target_reliability=0.95):
        self.target = target_reliability

    def measure(self, reliabilities):
        terminal = 1.0
        for r in reliabilities:
            terminal *= r
        allowed = 1 - self.target
        observed = 1 - terminal
        return terminal, allowed - observed

engine = ReliabilityEngine(target_reliability=0.95)
rel = [0.99, 0.98, 0.99, 0.97, 0.99]
terminal, budget = engine.measure(rel)
print(f"Terminal reliability: {terminal:.3f} (target 0.95)")
print(f"Exception budget: {budget:+.3f}  (negative = over budget)")
engine90 = ReliabilityEngine(target_reliability=0.90)
terminal90, budget90 = engine90.measure(rel)
print(f"Against target 0.90: budget {budget90:+.3f}")

Try it yourself

Change the target to 0.99 and run again. What is the exception budget now?

Check

What does ReliabilityEngine.measure return?

The terminal reliability and the exception budget for the graph.

What does a negative exception budget mean?

The workflow fails more often than the target allows — you are over budget.

Lab 2 — Measure and Repair Reliability

Lab 2b — Compare repairs: prune, gate, redundancy

What it is

engine.compare_repairs(graph) tests four strategies: baseline (do nothing), prune_weakest (remove the weakest node), add_gate (add a verification gate, reliability about 0.999, cheap tokens), and add_redundancy (run the weakest node twice, so it only fails if both copies fail). Insights from the lab: long chains drop fast; a verification gate often gives the best reliability gain per extra token; redundancy helps the weakest node but doubles its cost; pruning can help or hurt depending on the topology.

Why it matters

Never fix reliability by guessing. Compare the repairs with numbers: how much reliability do you gain, and how many tokens does it cost? The cheapest gain usually wins.

# Lab 2: compare repairs (practice version).
# Real code: repairs = engine.compare_repairs(graph)
base = [0.99, 0.98, 0.99, 0.97, 0.99]

def product(rs):
    out = 1.0
    for r in rs:
        out *= r
    return out

baseline = product(base)
gate = baseline * 0.999                       # add a verification gate
weakest = min(base)
redundant = product(base) / weakest * (1 - (1 - weakest) ** 2)
pruned = product([r for r in base if r != weakest])
print(f"baseline:       {baseline:.3f}")
print(f"add_gate:       {gate:.3f}  (+{gate - baseline:.3f}, cheap tokens)")
print(f"add_redundancy: {redundant:.3f}  (+{redundant - baseline:.3f}, doubles weakest cost)")
print(f"prune_weakest:  {pruned:.3f}  (+{pruned - baseline:.3f}, but you lose that step)")
print("Best gain per token: usually the verification gate.")

Try it yourself

Change the weakest node reliability to 0.70 and run again. Which repair wins now, and why?

Check

Why is a verification gate often the best repair?

It has reliability near 0.999 and costs few tokens, so you gain a lot for very little extra cost.

Why can pruning hurt?

Removing a node also removes the work it did. If that step mattered, the workflow is now incomplete, even if the numbers look better.

Lab 2 — Measure and Repair Reliability

Lab 2c — What the numbers teach you

What it is

Three lessons from Lab 2. First, long chains drop fast: ten steps at 0.99 each is only about 0.90 reliable. Second, verification is cheap insurance: a gate that double-checks the work costs little and catches many failures. Third, redundancy is expensive: doubling a node doubles its cost, so use it only on the weakest link, and only after a gate.

Why it matters

These three lessons are the intuition you will reuse in every later lab. Reliability is a budget, and every repair is a purchase. Buy the cheapest reliability first.

# Lab 2: how fast does a long chain drop? (practice version).
r = 0.99
reliability = 1.0
for step in range(1, 11):
    reliability *= r
    print(f"after {step:2d} steps at 0.99: {reliability:.3f}")
print("Ten steps at 0.99 each is only about 0.90 reliable.")

Try it yourself

Run the code above, then work out in your head: what is 5 steps at 0.95 each? (Answer: about 0.77.)

Check

Ten steps at 0.99 each give what reliability?

About 0.90.

When should you use redundancy?

Only on the weakest link, and only after a verification gate — because it doubles that node's cost.

Lab 3 — Build a Governance Gate

Lab 3a — Build the gate

What it is

Build a GovernanceGate with min_reliability=0.90, max_token_budget=8000, max_depth=10, require_registered=True, and required_capabilities=["planning"]. Then call gate.evaluate_plan(plan, name="candidate") and print result.scorecard(). The lab command is: python labs/lab3_governance.py

Why it matters

The gate is the lock on the door. It runs before execution, it is deterministic, and it costs nothing to run. A plan that fails the gate never spends a token.

# Lab 3: build the governance gate (practice version).
# Real code: from src.governance import GovernanceGate
class GovernanceGate:
    def __init__(self, min_reliability=0.90, max_token_budget=8000,
                 max_depth=10, require_registered=True,
                 required_capabilities=("planning",)):
        self.min_reliability = min_reliability
        self.max_token_budget = max_token_budget
        self.max_depth = max_depth
        self.require_registered = require_registered
        self.required_capabilities = required_capabilities

    def evaluate(self, plan):
        checks = {
            "is_dag": not plan["has_cycle"],
            "all_registered": all(n["registered"] for n in plan["nodes"]),
            "depth_ok": plan["depth"] <= self.max_depth,
            "tokens_ok": sum(n["token_cost"] for n in plan["nodes"]) <= self.max_token_budget,
            "reliability_ok": plan["reliability"] >= self.min_reliability,
            "capabilities_ok": "planning" in {c for n in plan["nodes"] for c in n["capabilities"]},
            "has_terminal": any(n["type"] == "terminal" for n in plan["nodes"]),
        }
        return ("PASS" if all(checks.values()) else "REJECT"), checks

gate = GovernanceGate()
plan = {"has_cycle": False, "depth": 5, "reliability": 0.922,
        "nodes": [
            {"registered": True, "token_cost": 800, "capabilities": ["planning"], "type": "agent"},
            {"registered": True, "token_cost": 1500, "capabilities": ["search"], "type": "agent"},
            {"registered": True, "token_cost": 900, "capabilities": ["writing"], "type": "terminal"},
        ]}
verdict, checks = gate.evaluate(plan)
for k, v in checks.items():
    print(("PASS " if v else "FAIL ") + k)
print("Verdict:", verdict)

Try it yourself

Run the code above. Then change max_token_budget to 2000 in the gate and run again. What changes?

Check

What are the five gate settings in this lab?

Minimum reliability 0.90, maximum tokens 8000, maximum depth 10, all agents registered, and the planning capability required.

When does the gate run?

Before execution — a failing plan never runs and never spends tokens.

Lab 3 — Build a Governance Gate

Lab 3b — PASS and REJECT in practice

What it is

Healthy plan: PASS. Broken plan, low-reliability plan, or over-budget plan: REJECT. The scorecard tells you exactly which check failed, so the fix is obvious: fix the structure, raise the reliability, or cut the tokens. Never override a REJECT by hand without writing down why — that defeats the gate.

Why it matters

A gate that everyone overrides is decoration. The scorecard is the point: it turns 'I feel uneasy' into 'check 4 failed, tokens are 9,500 against a budget of 8,000'.

# Lab 3: three plans, three verdicts (practice version).
# (Uses the GovernanceGate class from Lab 3a — copy it here to run alone.)
class GovernanceGate:
    def __init__(self, min_reliability=0.90, max_token_budget=8000, max_depth=10):
        self.min_reliability = min_reliability
        self.max_token_budget = max_token_budget
        self.max_depth = max_depth
    def evaluate(self, plan):
        checks = {
            "is_dag": not plan["has_cycle"],
            "tokens_ok": sum(n["token_cost"] for n in plan["nodes"]) <= self.max_token_budget,
            "reliability_ok": plan["reliability"] >= self.min_reliability,
            "depth_ok": plan["depth"] <= self.max_depth,
        }
        return ("PASS" if all(checks.values()) else "REJECT"), checks

gate = GovernanceGate()
def node(cost):
    return {"token_cost": cost}
plans = {
    "healthy":    {"has_cycle": False, "depth": 5, "reliability": 0.922,
                   "nodes": [node(800), node(1500), node(900)]},
    "low_rel":    {"has_cycle": False, "depth": 5, "reliability": 0.85,
                   "nodes": [node(800), node(1500), node(900)]},
    "over_budget": {"has_cycle": False, "depth": 5, "reliability": 0.93,
                   "nodes": [node(4000), node(3000), node(2500)]},
}
for name, plan in plans.items():
    verdict, checks = gate.evaluate(plan)
    failed = [k for k, v in checks.items() if not v]
    print(f"{name:12s} -> {verdict}   failed: {failed or 'none'}")

Try it yourself

Add a fourth plan to the code above: a plan with a cycle (has_cycle True). What is its verdict?

Check

What does a healthy plan get?

PASS.

What should you do when a plan is REJECTED?

Fix the failing check — structure, reliability, or tokens — and run the gate again. Do not override it by hand without writing down why.

Lab 4 — GraphRAG Retrieval with Provenance

Lab 4a — Vector search vs graph search

What it is

Vector search finds documents that are similar to the question. Graph search starts from seed entities and follows relations across the graph, up to max_hops hops. The lab API is: rag = GraphRAG(); rag.vector_search("Who leads the ML team?"); rag.graph_search("Project X depends on…", seed_entities=["project_x"], max_hops=2); rag.hybrid_search("Alice collaboration"). The lab command is: python labs/lab4_graphrag.py

Why it matters

Similarity answers 'what looks like this?' Traversal answers 'how is this connected to that?' For multi-hop questions — questions that need two or three jumps — only traversal works.

# Lab 4: vector hits as seeds, graph hops after them (practice version).
# Real code: from src.graphrag import GraphRAG, GraphEntity, GraphRelation, Document
documents = {
    "doc1": "Project X depends on Project Y for its data pipeline.",
    "doc2": "The platform team owns Project Y.",
    "doc3": "Alice leads the platform team.",
}
relations = [
    ("project_x", "depends_on", "project_y"),
    ("project_y", "owned_by", "platform_team"),
    ("platform_team", "led_by", "alice"),
]

def vector_search(query):
    # Practice version: simple word overlap instead of real embeddings.
    words = set(query.lower().split())
    scored = []
    for doc_id, text in documents.items():
        score = len(words & set(text.lower().replace(".", "").split()))
        scored.append((score, doc_id))
    return sorted(scored, reverse=True)

def graph_search(seed_entities, max_hops=2):
    found, frontier = [], list(seed_entities)
    for _ in range(max_hops):
        nxt = []
        for node in frontier:
            for a, rel, b in relations:
                if a == node:
                    found.append((a, rel, b))
                    nxt.append(b)
        frontier = nxt
    return found

print("Vector search for 'Who leads the ML team?':", vector_search("Who leads the ML team?"))
print("Graph search from project_x:", graph_search(["project_x"], max_hops=2))

Try it yourself

Run the code above. Which document does vector search rank first for 'Who leads the ML team?', and why is that not the full answer?

Check

What does vector search return?

Documents similar to the question, ranked by similarity.

What does graph search return?

Connected facts, by following relations from seed entities, hop by hop.

Lab 4 — GraphRAG Retrieval with Provenance

Lab 4b — Provenance: show your working

What it is

Provenance is the explicit path from the question to the fact: project_x --depends_on--> project_y --owned_by--> platform_team. Regulators, auditors, and debugging engineers need to know how a fact was retrieved. A floating similarity score cannot tell them. A path can.

Why it matters

In finance, health, or law, 'the AI said so' is not evidence. The path is the evidence. Keep it, store it, and show it with the answer.

# Lab 4: build and print a provenance path (practice version).
relations = [
    ("project_x", "depends_on", "project_y"),
    ("project_y", "owned_by", "platform_team"),
    ("platform_team", "led_by", "alice"),
]

def provenance_path(start, max_hops=2):
    path = [start]
    steps = []
    current = start
    for _ in range(max_hops):
        nxt = [(rel, b) for a, rel, b in relations if a == current]
        if not nxt:
            break
        rel, current = nxt[0]
        steps.append(rel)
        path.append(current)
    pretty = path[0]
    for rel, node in zip(steps, path[1:]):
        pretty += f" --{rel}--> {node}"
    return pretty

print(provenance_path("project_x", max_hops=2))
print(provenance_path("project_x", max_hops=3))

Try it yourself

Run the code above. What is the 3-hop provenance path starting at project_x?

Check

What is a provenance path?

The explicit chain of relations from the question to the fact, for example project_x depends on project_y, which is owned by the platform team.

Who needs provenance?

Regulators, auditors, and debugging engineers — anyone who must check how a fact was found.

Lab 4 — GraphRAG Retrieval with Provenance

Lab 4c — Hybrid search: seeds plus hops

What it is

Hybrid search combines both: vector search finds the best starting documents, those documents' entities become seeds, and graph search expands from the seeds for up to 2 hops. You get relevance and connections in one answer, with a provenance path for every fact.

Why it matters

Either method alone is half an answer. Vector search finds the right neighbourhood; graph search walks the streets. Together they answer multi-hop questions with proof.

# Lab 4: hybrid search — vector seeds, then graph hops (practice version).
documents = {
    "doc1": "Project X depends on Project Y for its data pipeline.",
    "doc2": "The platform team owns Project Y.",
    "doc3": "Alice leads the platform team.",
}
doc_entities = {"doc1": ["project_x"], "doc2": ["project_y"], "doc3": ["alice"]}
relations = [
    ("project_x", "depends_on", "project_y"),
    ("project_y", "owned_by", "platform_team"),
    ("platform_team", "led_by", "alice"),
]

def hybrid_search(query, max_hops=2):
    words = set(query.lower().split())
    best = max(documents, key=lambda d: len(words & set(documents[d].lower().split())))
    seeds = doc_entities[best]
    found = []
    frontier = list(seeds)
    for _ in range(max_hops):
        nxt = []
        for node in frontier:
            for a, rel, b in relations:
                if a == node:
                    found.append((a, rel, b))
                    nxt.append(b)
        frontier = nxt
    return best, seeds, found

doc, seeds, paths = hybrid_search("Alice collaboration")
print("Best vector hit:", doc, "| seeds:", seeds)
print("Graph expansion:", paths)

Try it yourself

Run the code above with the query 'Project Y owner'. Which document is the best vector hit, and what does the graph expansion find?

Check

What is hybrid search?

Vector search to find starting documents, then graph search from their entities for up to a few hops.

Why use hybrid instead of vector alone?

Vector alone finds similar documents but cannot follow connections. Hybrid follows the connections and keeps the provenance path.

Lab 5 — Execute, Trace, and Certify

Lab 5a — Execute and trace the run

What it is

Run the graph with ExecutionTracer(seed=42). The seed makes the run deterministic: same plan, same seed, same trace. Every node records status, latency, tokens, and an output hash. The lab command is: python labs/lab5_trace_certify.py

Why it matters

A trace is the flight recorder. Without it, a failure is a mystery. With it, you can point at the exact node, the exact time, and the exact output that went wrong.

# Lab 5: trace a run, node by node (practice version).
# Real code: from src.tracing import ExecutionTracer
import hashlib

def run_trace(nodes, seed=42, force_failures=None):
    force_failures = force_failures or {}
    trace = []
    for name, latency_ms, tokens in nodes:
        status = "FAILED" if force_failures.get(name) else "ok"
        out_hash = hashlib.sha256(f"{name}:{seed}:{status}".encode()).hexdigest()[:8]
        trace.append({"node": name, "status": status, "latency_ms": latency_ms,
                      "tokens": tokens, "output_hash": out_hash})
    return trace

nodes = [("planner", 12, 800), ("researcher", 45, 1500), ("fact_checker", 30, 1200),
         ("analyst", 50, 1800), ("writer", 25, 900)]
trace = run_trace(nodes, seed=42)
for row in trace:
    print(row)
print("Overall:", "ok" if all(r["status"] == "ok" for r in trace) else "FAILED")

Try it yourself

Run the code above with force_failures={"analyst": True}. What is the overall status, and which node's output hash changes?

Check

Why does the tracer take a seed?

So the run is deterministic: the same plan and seed always give the same trace, which makes drift detection possible.

What does each trace row record?

Status, latency, tokens, and an output hash for one node.

Lab 5 — Execute, Trace, and Certify

Lab 5b — Detect drift against the baseline

What it is

Run the baseline first, then run again with a forced failure: tracer.run(graph, run_id="drifted_001", force_failures={"fact_checker": True}). DriftDetector().detect(baseline, drifted, graph=graph) reports the drifted nodes, the severity, and the downstream impact — every node after the failed one.

Why it matters

Drift is not 'something changed'. Drift is 'this node changed, and here is everything it touched'. The downstream impact is what makes a small failure a big one.

# Lab 5: detect drift between two runs (practice version).
# Real code: from src.tracing import DriftDetector
baseline = {"planner": "ok", "researcher": "ok", "fact_checker": "ok",
            "analyst": "ok", "writer": "ok"}
drifted = {"planner": "ok", "researcher": "ok", "fact_checker": "FAILED",
           "analyst": "ok", "writer": "ok"}
order = ["planner", "researcher", "fact_checker", "analyst", "writer"]
drifted_nodes = [n for n in order if baseline[n] != drifted[n]]
first = order.index(drifted_nodes[0]) if drifted_nodes else None
downstream = order[first + 1:] if first is not None else []
print("Drifted nodes:", drifted_nodes)
print("Downstream impact:", downstream)
print("Severity:", "HIGH" if len(downstream) >= 2 else "LOW")

Try it yourself

Run the code above, then change the forced failure to the planner. How does the downstream impact change?

Check

What is a baseline trace?

The trace of a known-good run, kept so later runs can be compared with it.

Why does downstream impact matter?

Nodes after a failed node may have received bad input, so their results cannot be trusted either.

Lab 5 — Execute, Trace, and Certify

Lab 5c — Certify the workflow

What it is

certify_workflow(graph, governance_gate, baseline, drifted, provenance_ok=True) builds the seven-dimension scorecard: Structural, Reliability, Token budget, Governance, Provenance, Execution trace, Drift. All seven must pass for CERTIFIED. The drifted run in this lab is NOT CERTIFIED — and that is the correct answer. A certification that passes a drifted run is worthless.

Why it matters

Certification is the promotion gate. It is the last thing that runs before a workflow meets real users, and it must be able to say no.

# Lab 5: build the certification scorecard (practice version).
# Real code: from src.tracing import certify_workflow
def certify(structural, reliability_ok, tokens_ok, governance_ok,
            provenance_ok, trace_ok, drift_ok):
    scorecard = {
        "Structural": structural, "Reliability": reliability_ok,
        "Token budget": tokens_ok, "Governance": governance_ok,
        "Provenance": provenance_ok, "Execution trace": trace_ok,
        "Drift": drift_ok,
    }
    for dim, ok in scorecard.items():
        print(("PASS " if ok else "FAIL ") + dim)
    return "CERTIFIED" if all(scorecard.values()) else "NOT CERTIFIED"

print("Baseline run:")
print("Verdict:", certify(True, True, True, True, True, True, True))
print()
print("Drifted run (fact_checker failed):")
print("Verdict:", certify(True, True, True, True, True, True, False))

Try it yourself

Run the code above. Which single dimension flips the drifted run from CERTIFIED to NOT CERTIFIED?

Check

How many dimensions does the scorecard have?

Seven: Structural, Reliability, Token budget, Governance, Provenance, Execution trace, Drift.

What happens to a workflow that is NOT CERTIFIED?

It is not promoted to the serving layer. It does not meet real users.

Putting It All Together

The production pipeline, steps 1 to 8

What it is

The full pipeline, in order: (1) Author the plan as YAML or a Python dict. (2) compile_plan_to_dag() — structural issues. (3) ReliabilityEngine.measure() — exception budget. (4) GovernanceGate.evaluate_*() — PASS or REJECT. (5) If PASS, ExecutionTracer.run(). (6) DriftDetector against the baseline. (7) certify_workflow() — CERTIFIED or NOT CERTIFIED. (8) Only CERTIFIED workflows are promoted to the serving layer. All of this is deterministic for the same plan and seed. No LLM calls are needed for the measurement and governance layers. The repo demo is demo_end_to_end.py: plan → DAG → reliability → governance → GraphRAG → trace → drift → certification.

Why it matters

This is the whole workshop on one page. If you can run these eight steps, you can run the workshop. If you can explain them, you understand it.

# The production pipeline, end to end (practice version).
# Real code: see demo_end_to_end.py in the repo.
def pipeline(plan_nodes, plan_edges, reliabilities, tokens, seed=42):
    print("1. Author plan: dict with nodes and edges")
    print("2. Compile: valid DAG" if len(plan_edges) == len(plan_nodes) - 1 else "2. Compile: FAILED")
    rel = 1.0
    for r in reliabilities:
        rel *= r
    print(f"3. Reliability: terminal {rel:.3f}, budget {0.10 - (1 - rel):+.3f} (target 0.90)")
    gov = rel >= 0.90 and tokens <= 8000
    print("4. Governance:", "PASS" if gov else "REJECT")
    if not gov:
        print("   Stop here. No execution, no tokens spent.")
        return "NOT CERTIFIED"
    print("5. Trace: baseline run, all nodes ok")
    print("6. Drift: no drift from baseline")
    print("7. Certify: all seven dimensions PASS")
    print("8. Promote to serving layer")
    return "CERTIFIED"

print("Verdict:", pipeline(
    ["planner", "researcher", "fact_checker", "analyst", "writer"],
    [("planner", "researcher"), ("researcher", "fact_checker"),
     ("fact_checker", "analyst"), ("analyst", "writer")],
    [0.99, 0.98, 0.99, 0.97, 0.99], tokens=6200))

Try it yourself

Run the code above with tokens=9500. At which step does the pipeline stop, and what is the verdict?

Check

How many steps are in the production pipeline?

Eight: author, compile, reliability, governance, trace, drift, certify, promote.

Which steps need an LLM call?

None of the measurement and governance steps. They are deterministic.

Production Checklist

Production checklist — 8 items

What it is

Before a workflow goes live, check all eight: (1) Every agent and tool is registered in a capability registry. (2) Plans are stored as versioned artifacts, not only in code. (3) The governance gate runs in CI on every plan change. (4) Reliability target and exception budget are explicit SLOs. (5) Token and latency budgets are enforced before execution. (6) Baseline traces are stored and compared on every release. (7) GraphRAG provenance is retained for audit. (8) The certification scorecard is the promotion gate to production.

Why it matters

A checklist is only useful if you actually check it. Print this one, pin it up, and run through it before every release.

# The production checklist, as code you can run in CI.
CHECKLIST = [
    "Every agent/tool is registered in a capability registry",
    "Plans are stored as versioned artifacts (not only in code)",
    "Governance gate runs in CI on every plan change",
    "Reliability target and exception budget are explicit SLOs",
    "Token and latency budgets are enforced before execution",
    "Baseline traces are stored and compared on every release",
    "GraphRAG provenance is retained for audit",
    "Certification scorecard is the promotion gate to production",
]
for i, item in enumerate(CHECKLIST, 1):
    print(f"[ ] {i}. {item}")
print("All eight checked? Only then promote to production.")

Try it yourself

Pick the checklist item your own team is weakest on, and write one sentence about how you would fix it.

Check

What is an SLO?

A Service Level Objective — the target you promised, for example reliability 0.90 or a token budget of 8000.

What does 'runs in CI' mean for the governance gate?

The gate runs automatically on every plan change, before the change is accepted.

Further Reading

Further reading

What it is

Five sources to go deeper: NetworkX documentation (DAG algorithms, topological sort); the Google SRE book, chapters on error budgets and SLOs; GraphRAG research (Microsoft and others) on knowledge-graph augmented retrieval; OpenTelemetry semantic conventions for GenAI and agent traces; and the NIST AI Risk Management Framework (measurement and validation).

Why it matters

A one-day workshop opens the door. These five sources are the rooms behind it. Read the SRE error-budget chapters first — they are the shortest path from this workshop to production thinking.

# Further reading, as a list to work through.
reading = [
    "NetworkX documentation — DAG algorithms, topological sort",
    "Google SRE book — error budgets and SLOs",
    "GraphRAG research — knowledge-graph augmented retrieval",
    "OpenTelemetry — semantic conventions for GenAI / agent traces",
    "NIST AI Risk Management Framework — measurement & validation",
]
for i, item in enumerate(reading, 1):
    print(f"{i}. {item}")

Try it yourself

Pick one item from the list above and find it online. Write down one idea from it that this workshop did not cover.

Check

Which reading covers error budgets?

The Google SRE book.

Which framework covers measurement and validation of AI risk?

The NIST AI Risk Management Framework.

Capstone — extra practice

Capstone: certify a complete workflow end to end

What it is

Extra practice, not a curriculum lesson. Build a complete workflow of your own: pick a real task (for example, 'research a company and write a short report'), author the plan, compile it, measure reliability, run the governance gate, add a GraphRAG step with provenance, trace a baseline run, force one failure, detect the drift, and certify. Only promote it if the scorecard says CERTIFIED. The code below is the full pipeline in one runnable script — the same shape as demo_end_to_end.py in the repo.

Why it matters

This is the moment the workshop becomes yours. A workflow you built, measured, gated, traced, and certified is a portfolio piece, not a tutorial exercise.

# Capstone: certify a complete workflow end to end (practice version).
# Same shape as demo_end_to_end.py in the repo.
def certify_workflow(scorecard):
    for dim, ok in scorecard.items():
        print(("PASS " if ok else "FAIL ") + dim)
    return "CERTIFIED" if all(scorecard.values()) else "NOT CERTIFIED"

# 1-2. Author + compile
nodes = ["planner", "researcher", "fact_checker", "analyst", "writer"]
edges = [("planner", "researcher"), ("researcher", "fact_checker"),
         ("fact_checker", "analyst"), ("analyst", "writer")]
print("Compiled: valid DAG,", len(nodes), "nodes,", len(edges), "edges")
# 3. Reliability
rel = 1.0
for r in [0.99, 0.98, 0.99, 0.97, 0.99]:
    rel *= r
print(f"Terminal reliability: {rel:.3f}")
# 4. Governance
tokens = 6200
gov = rel >= 0.90 and tokens <= 8000
print("Governance:", "PASS" if gov else "REJECT")
# 5-6. Trace + drift (baseline clean, no drift)
print("Trace: baseline ok. Drift: none.")
# 7. Certify
scorecard = {"Structural": True, "Reliability": rel >= 0.90,
             "Token budget": tokens <= 8000, "Governance": gov,
             "Provenance": True, "Execution trace": True, "Drift": True}
print("Verdict:", certify_workflow(scorecard))

Try it yourself

Change the analyst reliability in the capstone code to 0.80 and run it. Is the workflow still CERTIFIED? What would you change to fix it?

Check

What makes a capstone different from a lab?

A lab teaches one skill. The capstone joins all of them — compile, measure, govern, retrieve, trace, certify — into one workflow you designed yourself.

When is a workflow ready to promote?

Only when the scorecard says CERTIFIED.

Finish

Final checklist

What it is

You are done when you can tick all of these: I can draw an agent workflow as a graph. I can compile a plan into a DAG and explain the execution levels. I can calculate terminal reliability and the exception budget. I can compare repairs and pick the cheapest gain. I can build a governance gate and explain a PASS and a REJECT. I can run vector, graph, and hybrid search and show a provenance path. I can trace a run, detect drift, and explain downstream impact. I can build a certification scorecard and say why a workflow is or is not CERTIFIED.

Why it matters

If you cannot tick one, go back to that lab. The workshop is short on purpose — one day — so going back costs minutes, not weeks.

# Final checklist — tick each one honestly.
items = [
    "Draw an agent workflow as a graph",
    "Compile a plan into a DAG and explain execution levels",
    "Calculate terminal reliability and the exception budget",
    "Compare repairs and pick the cheapest gain",
    "Build a governance gate; explain PASS and REJECT",
    "Run vector, graph, and hybrid search; show provenance",
    "Trace a run, detect drift, explain downstream impact",
    "Build a certification scorecard",
]
for i, item in enumerate(items, 1):
    print(f"[ ] {i}. {item}")

Try it yourself

Tick every item you can honestly tick. For the ones you cannot, write the lesson number next to them and go back.

Check

How long is this workshop meant to take?

One day, hands-on.

What should you do if you cannot tick an item?

Go back to that lab — going back costs minutes, not weeks.

Finish

What to do next

What it is

Next steps: first, apply the pipeline to one of your own agent workflows — compile it, measure it, gate it, certify it. Then go deeper with the Harness Engineering workshop in this repo (guardrails, loop engineering, evaluation, observability), and the Financial agent workshop (the same ideas applied to a production financial system, with a FastAPI service on Debian). Keep your baseline traces: they are what makes drift visible next month.

Why it matters

A workshop ends. The pipeline does not. The next workflow you certify is the real test.

# What to do next, in order.
steps = [
    "1. Certify one of your own agent workflows with this pipeline",
    "2. Harness Engineering workshop — guardrails, loops, evaluation",
    "3. Financial agent workshop — the same ideas in production",
]
for s in steps:
    print(s)

Try it yourself

Write down the name of one real workflow of yours that you will certify first.

Check

What is the first next step?

Apply the pipeline to one of your own agent workflows.

Which two workshops in this repo go deeper?

Harness Engineering, and the Financial agent workshop.

Try it here

Try graph engineering here

Pick a plan. The demo runs the same pipeline you just learned: compile, reliability, governance, trace, certification. No server, no API key — it runs in your browser.

Pick a plan and press "Run the pipeline".