How to use this workshop
First: read the Two Patches section in the Reference part, and apply both patches. They take two minutes, and without them the eval suite fails.
1. Read one section at a time, in order, from Module 0 to Module 8.
2. Read “What it is”, then “Why it matters”.
3. Copy the Python code, save it, and run it. Change one small thing and run it again. That is how you learn.
4. Do the “Try it yourself” task. It is small on purpose. The labs in the modules are the real lab tasks from the workshop.
5. Answer the “Check” questions. Click a question to see the answer. If you got it wrong, read the section again.
6. Tick “Done” when you finish a section. Your progress is saved in this browser.
Two plain words to learn first. Harness Engineering means treating prompts, guardrails, validation, retries, and audit as first-class engineering around the model. Loop Engineering means designing plan, act, observe cycles with bounds, supervision, and stopping conditions. Everything in this workshop is one of those two things, plus evaluation and observability to prove it works.
Work in order: Part 1 explains the idea and the architecture. Modules 0 to 8 build the system, one layer at a time. The Reference part has the patches, agendas, troubleshooting, and glossary. The capstone at the end is your graded project.
Setup — Python, main.py, eval.py
What you need
Python 3.9 or newer. That is all you need for the offline demo. No extra packages, no internet, no API key.
Check your Python
Open a terminal and run:
python3 --version
cd multi_agent_finance_workshop
python main.py
python eval.pyYou should see Python 3.9 or newer. Always run from inside the multi_agent_finance_workshop folder first — the data paths are relative to the repo root.
How to run the code in this workshop
- Copy the code from a section.
- Save it in a file, for example agent.py, in a folder for this workshop.
- In the terminal, go to that folder and run: python3 agent.py
- Read the output. Change one line, run it again, and see what changes.
The two checkpoints
After python main.py, you should see status “ok”, a structured answer with pe_ratio 34.58, citations [“AAPL-10K-FY2025”], verdict “pass”, and a component-latency table. After python eval.py, you should see EVALUATION SUMMARY: 7/7 checks passed (100%).
No API key needed — MockLLM
Every Python example uses MockLLM, a small deterministic stand-in for a real model. It reads the role and the state and returns the same JSON protocol a well-prompted real model would. It runs offline, it is free, and it makes your evals reproducible.
How to swap to a real model — one environment variable, no code changes.
pip install openai
export OPENAI_API_KEY=sk-...
export LLM_PROVIDER=openai
python main.py
# For Anthropic instead: pip install anthropic
# export ANTHROPIC_API_KEY=...
# export LLM_PROVIDER=anthropic
# LLM_PROVIDER=mock is the default: offline, deterministic, free.In real code, LLMClient.complete() is the only place that talks to a model. MockLLM, OpenAI, and Anthropic all sit behind that one interface, so the agents never notice the swap. The Python swap code is shown in the code blocks of Module 1.
Try the financial agent here
Type a request, for example Analyze AAPL filing + earnings call, compute P/E. The simulated system below shows the Planner, Research, Analyst, and Verifier steps, the tools used, the verification, and the final answer with citations. Try a blocked request too, for example Give me a guaranteed return. No server, no key, no Python needed for this box.
Press “Run the financial agent” to see the team work.
Try these: “Analyze AAPL filing + earnings call, compute P/E”, “Give me a guaranteed return”, “Send me wire transfer instructions”, “hello”.
Part 1 — The Bootcamp and the Architecture
From Prompt Engineering to Harness Engineering, the full system picture, and the files you will build.
3 sections in this part.
Bootcamp: From Prompt Engineering to Context Engineering to Harness Engineering
What it is
Generative AI is changing banking, investment research, wealth management, fintech, insurance, and enterprise finance. But production financial AI needs far more than writing better prompts. Modern financial systems must reason across SEC filings, research reports, earnings calls, spreadsheets, charts, market data, policies, and time series — all while staying accurate, explainable, secure, and auditable. That is where AI agents come in. This bootcamp teaches the modern engineering approach: Prompt Engineering is one good prompt. Context Engineering is giving the model the right documents and data. Harness Engineering is building the system AROUND the model — guardrails, tools, loops, checks, logs — so it works safely, every time. Rather than isolated prompting or basic retrieval pipelines, you will design complete agent architectures with reusable skills, retrieval, execution loops, evaluation, observability, governance, and security built in from the start.
Why it matters
Prompting alone cannot be audited, cannot be tested, and cannot say no. Harness Engineering is what turns a clever prompt into a system a bank can actually run.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Prompt -> Context -> Harness: three steps in how agents are built.
# 1. Prompt Engineering: one good prompt, one good answer.
# 2. Context Engineering: give the model the right documents and data.
# 3. Harness Engineering: build the system AROUND the model — guardrails,
# tools, loops, checks, logs — so it works safely, every time.
# This bootcamp teaches step 3. The model is only one part of the system.
def prompt_only(question):
return "AAPL looks strong." # No evidence, no check. Trust me?
def with_context(question):
# Context: the filing says revenue grew 5 percent, EPS is $6.00.
return f"Revenue grew {FILING['revenue_growth_pct']}%, EPS ${FILING['eps']}."
def with_harness(question):
# Harness: evidence + tool calculation + a verifier that re-checks.
pe_ratio = round(PRICE / FILING["eps"], 2)
return {
"answer": f"P/E ratio is {pe_ratio}.",
"pe_ratio": pe_ratio,
"citations": [FILING["doc_id"]],
"verified": True,
}
print("Prompt only:", prompt_only("Analyze AAPL"))
print("With context:", with_context("Analyze AAPL"))
print("With harness:", with_harness("Analyze AAPL"))
print("Same question. Only the harness answer can be checked.")
Try it yourself
Run the code, then change the question to 'Analyze AAPL' and compare the three answers.
Check
What are the three steps, in order?
Prompt Engineering, then Context Engineering, then Harness Engineering.
What does Harness Engineering add that prompting does not?
The system around the model: guardrails, tools, loops, checks, and logs, so it works safely every time.
Architecture: Architecture Overview: Harness, Loop, Verifier, Observability
What it is
The whole system fits in one picture. A user query goes in at the top. First, the harness input guardrails check it: blocked keywords, PII redaction, length cap. Then the loop runs, bounded and supervised: the Planner splits the job, the Research agent reads the filing and the earnings call, the Analyst fetches market data and computes with the calculator. Then the Verifier checks the answer: it recomputes the P/E ratio from raw evidence and checks citations and the disclaimer. If it passes, the answer is delivered and audited. If it fails, a human reviews it. Under everything, observability records traces (spans, latency, tokens, cost) and an audit log records every decision. Five design decisions make it work: agents never touch input and output directly, they request a tool call and the harness runs it; the loop is bounded, with a hard cap; an independent Verifier must pass the output; everything is traced and audited; and the LLM is an abstraction you can swap.
Why it matters
If you understand this picture, you understand the whole workshop. Every module after this one is one box in this picture, in detail.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Architecture Overview: the whole system, in one picture, as code.
# User query -> HARNESS (guardrails) -> LOOP (planner, research, analyst)
# -> VERIFIER (recompute + citations) -> deliver + audit
# -> OBSERVABILITY (traces + audit log). Agents never touch I/O directly:
# they REQUEST a tool call, and the harness runs it, with permission checks.
def harness_guardrails(query):
blocked = ["guaranteed return", "insider tip"]
for word in blocked:
if word in query.lower():
return {"ok": False, "reason": "compliance block: " + word}
return {"ok": True}
def run_system(query):
check = harness_guardrails(query)
if not check["ok"]:
return {"status": "blocked", "reason": check["reason"]}
steps = ["planner: split the job", "research: read the filing",
"research: read the earnings call", "analyst: compute P/E",
"verifier: recompute P/E and check citations"]
pe_ratio = round(PRICE / FILING["eps"], 2)
print("Loop steps:")
for step in steps:
print(" -", step)
return {
"status": "ok", "pe_ratio": pe_ratio,
"citations": [FILING["doc_id"]], "verdict": "pass",
"disclaimer": DISCLAIMER,
}
print(run_system("Analyze AAPL filing + earnings call, compute P/E"))
print(run_system("Give me a guaranteed return insider tip"))
print("Five design rules: agents request tools (never run them), the loop")
print("is bounded, a verifier must pass the answer, everything is traced,")
print("and the model is an abstraction you can swap.")
Try it yourself
Run the code with the blocked request, then with the normal request. What changes?
Check
What are the five design decisions?
Agents request tools, never run them; the loop is bounded; a Verifier must pass the answer; everything is traced and audited; the LLM is an abstraction.
What happens if the Verifier fails?
The answer is not delivered. A human reviews it instead.
Architecture: Project Layout: config, llm, tools, skills, harness, orchestrator, observability, eval, main
What it is
The project is called multi_agent_finance_workshop. It has nine Python files, each with one job. config.py holds every tunable in one governed file. llm.py holds Mock, OpenAI, and Anthropic behind one interface. tools.py holds the four tools, the permission matrix, and the safe calculator. skills.py holds versioned, testable capability bundles. harness.py holds guardrails, schema validation, retries, audit, and human-in-the-loop. orchestrator.py holds the multi-agent loop: plan, act, observe, verify. observability.py holds trace spans and cost and latency accounting. eval.py holds three eval cases and seven checks, and main.py is the end-to-end demo. The data folder holds filings.json, the demo 10-K corpus for AAPL, earnings_call.txt, the demo transcript, and market_data.csv. The logs folder is created at runtime and holds traces.jsonl and audit.jsonl.
Why it matters
One file, one job. When something breaks, you know exactly which file to open. When you want to change a rule, you change it in one place.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Project Layout: every file has one job. Learn the file names.
FILES = {
"config.py": "every tunable in ONE governed file",
"llm.py": "Mock + OpenAI + Anthropic behind one interface",
"tools.py": "4 tools + permission matrix + safe calculator",
"skills.py": "versioned, testable capability bundles",
"harness.py": "guardrails, schema validation, retries, audit, HITL",
"orchestrator.py": "multi-agent loop: plan, act, observe, verify",
"observability.py": "trace spans + cost/latency accounting",
"eval.py": "3 eval cases, 7 checks, CI-gateable",
"main.py": "end-to-end demo",
"data/filings.json": "demo 10-K corpus (AAPL)",
"data/earnings_call.txt": "demo transcript",
"data/market_data.csv": "demo prices",
"logs/": "traces.jsonl + audit.jsonl (created at runtime)",
}
for name, job in FILES.items():
print(f"{name:22} # {job}")
print()
print("Demo data in this lesson:", FILING["doc_id"], "EPS $", FILING["eps"])
print("Rule: if you cannot find where a job lives, it lives in the wrong file.")
Try it yourself
Run the code and find the file that holds the calculator. What file is it in?
Check
Which file holds the guardrails?
harness.py.
Which file runs the whole system end to end?
main.py.
Module 0 — Environment Setup
Fifteen minutes. Verify Python, run the system, run the evals, and see the checkpoints pass.
1 sections in this part.
Setup: Setup and First Run: python main.py, python eval.py, and the Real-Model Switch
What it is
Step 1: verify Python. Run python --version. You need Python 3.9 or newer; any modern Python works. Step 2: the offline demo needs zero installs. This is deliberate: the workshop teaches architecture, not dependency wrangling. The only install is optional, and only for real providers: pip install -r requirements.txt. Step 3: run the system with python main.py. Checkpoint: you should see status 'ok', a structured answer with pe_ratio 34.58, citations ['AAPL-10K-FY2025'], verdict 'pass', and a component-latency table. Step 4: run the evaluation suite with python eval.py. Checkpoint: EVALUATION SUMMARY: 7/7 checks passed (100%). Step 5, optional: switch to a real model. Install openai, set OPENAI_API_KEY, set LLM_PROVIDER=openai, and run python main.py again. No code changes. That is Harness Engineering in one command.
Why it matters
A workshop that needs an hour of installs before the first run teaches the wrong lesson. Here, the first run is the proof the system works.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Module 0 checkpoint: run the system and read the output.
# Real commands: python main.py, then python eval.py.
# This is what python main.py prints when everything works.
def main():
pe_ratio = round(PRICE / FILING["eps"], 2)
result = {
"status": "ok",
"pe_ratio": pe_ratio,
"citations": [FILING["doc_id"]],
"verdict": "pass",
"disclaimer": DISCLAIMER,
}
print("status:", repr(result["status"]))
print("pe_ratio:", result["pe_ratio"])
print("citations:", result["citations"])
print("verdict:", repr(result["verdict"]))
print("Component latency: planner 0.02s, research 0.05s, analyst 0.03s, verifier 0.01s")
return result
def run_eval():
checks = ["status ok", "pe_ratio sane", "citations present",
"verifier passed", "disclaimer present",
"blocked case returns blocked", "audit log written"]
print("EVALUATION SUMMARY:", f"{len(checks)}/7 checks passed (100%)")
for check in checks:
print(" PASS:", check)
main()
run_eval()
print("Checkpoint: status ok, pe_ratio 34.58, verdict pass, eval 7/7.")
Try it yourself
Run the code, then change the price from 207.48 to 210.00 in your head and work out the new P/E.
Check
What are the two checkpoints in Module 0?
python main.py shows status ok, pe_ratio 34.58, verdict pass; python eval.py shows 7/7 checks passed.
How do you switch to a real model?
Set LLM_PROVIDER=openai and OPENAI_API_KEY. No code changes.
Module 1 — The LLM Abstraction Layer (llm.py)
One interface for every model. MockLLM, OpenAI, and Anthropic behind LLMClient.complete(), with a strict JSON protocol.
2 sections in this part.
Module 1: MockLLM and the Strict JSON Protocol
What it is
Production systems fail when LLM calls are scattered across business logic. Here, every model interaction flows through LLMClient.complete(), with a strict JSON protocol: {thought, action, tool, args, answer}. The action is 'tool' or 'final'. If it is 'tool', the harness runs that tool. If it is 'final', the agent is done. MockLLM is not a toy: it parses the conversation state and emits the same protocol JSON a well-prompted real model would. The planner decomposes, research gathers evidence with tools first, the analyst always routes arithmetic through the calculator, and the verifier recomputes claims. Because MockLLM is deterministic, your evals become reproducible tests: the same input always gives the same output.
Why it matters
One interface means you can test the whole system without a model, without a key, and without spending money. It also means swapping models is a one-line change.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Module 1: the LLM Abstraction Layer (llm.py).
# Every model call flows through LLMClient.complete(), with a strict
# JSON protocol: {thought, action, tool, args, answer}.
# MockLLM is deterministic: it reads the role and the state, and returns
# the same protocol JSON a well-prompted real model would. That makes
# your evals reproducible — the same input always gives the same output.
import json
class MockLLM:
"""Deterministic stand-in for a real model. Runs offline, no key."""
def complete(self, role, state):
if role == "planner":
out = {"thought": "Split the job into steps.",
"action": "final", "tool": None, "args": {},
"answer": {"steps": ["retrieve_filings", "extract_financials",
"fetch_market_data", "run_calculations",
"verify_and_deliver"]}}
elif role == "research":
if "filing" not in state:
out = {"thought": "I need the filing first.",
"action": "tool", "tool": "sec_filing_search",
"args": {"ticker": "AAPL"}, "answer": {}}
else:
out = {"thought": "Evidence gathered.",
"action": "final", "tool": None, "args": {},
"answer": {"summary": "Revenue grew 5%, EPS $6.00.",
"citations": [FILING["doc_id"]]}}
elif role == "analyst":
out = {"thought": "Arithmetic goes through the calculator tool.",
"action": "tool", "tool": "calculator",
"args": {"expression": "207.48 / 6.00"}, "answer": {}}
else: # verifier
out = {"thought": "Recompute P/E from raw evidence.",
"action": "final", "tool": None, "args": {},
"answer": {"verdict": "pass"}}
return out
llm = MockLLM()
print(json.dumps(llm.complete("planner", {}), indent=2))
print(json.dumps(llm.complete("research", {}), indent=2))
print("One interface, LLMClient.complete(). The model behind it can change;")
print("the agents never notice.")
Try it yourself
Run the code, then call llm.complete('research', {'filing': 'loaded'}) and see what changes.
Check
What is the strict JSON protocol?
{thought, action, tool, args, answer}. Action is 'tool' or 'final'.
Why is MockLLM deterministic, and why does that matter?
The same input always gives the same output, so evals are reproducible tests.
Module 1: SYSTEM_PROMPTS and Switching Providers (Lab 1)
What it is
SYSTEM_PROMPTS map the abstract protocol onto real providers. Each role gets its own prompt: the Planner splits the job, Research gathers evidence and never invents facts, the Analyst never does arithmetic itself, and the Verifier recomputes every number. For OpenAI, use response_format={'type': 'json_object'} so the model must return JSON. When you switch providers, only the prompts change, never the orchestration logic. Lab 1 (10 minutes): in llm.py, add a debug print inside MockLLM.complete, for example print(f'[{agent_role}] ->', json.dumps(out)[:120]). Run python main.py and watch each agent think. Checkpoint: you see planner, then research (tool), research (tool), research (final), analyst (tool), analyst (final), verifier (final).
Why it matters
Watching the agents think is how you debug a multi-agent system. If you cannot see the steps, you cannot fix them.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# SYSTEM_PROMPTS: the same protocol, worded for each provider.
# When you switch providers, only the prompts change — never the
# orchestration logic. For OpenAI, use response_format={"type": "json_object"}.
import json, os
SYSTEM_PROMPTS = {
"planner": "You are the Planner. Split the request into an ordered step list. Reply in JSON only.",
"research": "You are the Research agent. Use tools to gather evidence. Never invent facts. Reply in JSON only.",
"analyst": "You are the Analyst. Never do arithmetic yourself. Use the calculator tool. Reply in JSON only.",
"verifier": "You are the Verifier. Recompute every number from raw evidence. Reply in JSON only.",
}
class MockLLM:
def complete(self, role, state):
out = {"thought": f"{role} is working.",
"action": "final", "tool": None, "args": {},
"answer": {"role": role, "done": True}}
# LAB 1: add a debug print here and watch the flow.
print(f"[{role}] ->", json.dumps(out)[:120])
return out
# Swap to a real model with ONE environment variable, no code changes:
# LLM_PROVIDER=openai (needs OPENAI_API_KEY)
# LLM_PROVIDER=anthropic (needs ANTHROPIC_API_KEY)
# LLM_PROVIDER=mock (default, offline, deterministic, free)
provider = os.environ.get("LLM_PROVIDER", "mock")
print("Provider:", provider)
print("Prompt for planner:", SYSTEM_PROMPTS["planner"])
for role in ["planner", "research", "analyst", "verifier"]:
MockLLM().complete(role, {})
print("Checkpoint: you see planner -> research -> analyst -> verifier, in order.")
Try it yourself
Run the code and count the debug lines. Which role appears most often?
Check
What changes when you switch providers?
Only the prompts. Never the orchestration logic.
What should Lab 1 show you, in order?
Planner, research (tool), research (tool), research (final), analyst (tool), analyst (final), verifier (final).
Module 2 — Tools, Permissions and Skills (tools.py, skills.py)
Four tools, a permission matrix, and skills as versioned bundles. Least privilege, by construction.
3 sections in this part.
Module 2: The Four Tools and the Safe Calculator
What it is
The system has four tools. sec_filing_search retrieves 10-K facts and returns citations with every fact. earnings_call_transcript gives sentiment and guidance, by keyword-count sentiment, which is transparent and explainable. fetch_market_data gives the current price, backed by a CSV file, so it is auditable. calculator does arithmetic. The calculator is safe: it uses a whitelist regex, only digits, spaces, and plus, minus, star, slash, brackets, dot, and it never runs eval() on raw input. Try calculator('__import__("os")') and watch it refuse. A tool that can run any code is not a tool, it is a hole in the wall.
Why it matters
Tools are where an agent touches the real world. If a tool is unsafe, the whole system is unsafe, no matter how good the prompts are.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Module 2: the four tools (tools.py). Safe by design.
# The calculator uses a whitelist regex and never eval() on raw input.
import re
def sec_filing_search(ticker):
if ticker != FILING["ticker"]:
return {"error": "ticker not in demo corpus"}
return {"ticker": ticker, "revenue_musd": FILING["revenue_musd"],
"eps": FILING["eps"], "risk_factors": FILING["risk_factors"],
"citations": [FILING["doc_id"]]}
def earnings_call_transcript(ticker):
text = EARNINGS_CALL
positive = sum(text.lower().count(w) for w in ["grew", "positive", "raise"])
sentiment = "positive" if positive >= 2 else "neutral"
_clean = re.sub(r"[^a-z]", "", text.lower())
guidance = "raised" if "raise" in _clean else "maintained"
return {"ticker": ticker, "mgmt_sentiment": sentiment,
"guidance": guidance, "citations": [FILING["doc_id"]]}
def fetch_market_data(ticker):
return {"ticker": ticker, "price": PRICE, "source": "data/market_data.csv"}
def calculator(expression):
# Whitelist: only digits, spaces, and + - * / ( ) . — nothing else.
if not re.fullmatch(r"[0-9+\-*/(). ]+", expression):
return {"error": "calculator refused unsafe expression"}
return {"result": round(eval(expression, {"__builtins__": {}}, {}), 2)}
print(sec_filing_search("AAPL"))
print(earnings_call_transcript("AAPL"))
print(fetch_market_data("AAPL"))
print(calculator("207.48 / 6.00"))
print(calculator("__import__('os')")) # refused, not executed
print("Try it: the calculator refuses code. It only does arithmetic.")
Try it yourself
Run the code, then try calculator('2 + 2') and calculator('import os'). What happens in each case?
Check
What do the four tools do?
sec_filing_search retrieves 10-K facts, earnings_call_transcript gives sentiment and guidance, fetch_market_data gives the price, calculator does arithmetic.
Why does the calculator use a whitelist?
So it can only do arithmetic, and can never run code.
Module 2: The Permission Matrix: Least Privilege
What it is
The permission matrix, TOOL_PERMISSIONS, says which role may use which tool. Research may only read documents. The Analyst may only calculate and fetch prices. The Planner and the Verifier get zero tools. This is least privilege by construction: a role simply cannot do what it is not allowed to do, because the harness checks before it runs a tool. If Research tries the calculator, it gets an error, not a number. If the Planner tries to search a filing, it gets an error, not a document. Least privilege is not a policy document. It is a check in the code, on every tool call.
Why it matters
Permissions stop a confused agent from doing damage, and stop a bad prompt from turning into a bad action. The denial is the feature.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# The permission matrix (TOOL_PERMISSIONS): least privilege, by construction.
# Research may ONLY read documents. Analyst may ONLY calculate and fetch
# prices. Planner and verifier get ZERO tools. The harness enforces it:
# an agent can only run a tool if its role is on that tool's allow-list.
import re
TOOLS = ["sec_filing_search", "earnings_call_transcript",
"fetch_market_data", "calculator"]
TOOL_PERMISSIONS = {
"sec_filing_search": ["research"],
"earnings_call_transcript": ["research"],
"fetch_market_data": ["analyst"],
"calculator": ["analyst"],
}
def run_tool(role, tool, args):
if tool not in TOOL_PERMISSIONS:
return {"error": f"unknown tool '{tool}'"}
if role not in TOOL_PERMISSIONS[tool]:
return {"error": f"tool '{tool}' not allowed for role '{role}'"}
if tool == "calculator":
if not re.fullmatch(r"[0-9+\-*/(). ]+", args):
return {"error": "calculator refused unsafe expression"}
return {"result": round(eval(args, {"__builtins__": {}}, {}), 2)}
return {"ok": True, "tool": tool, "args": args}
print("Research + sec_filing_search:", run_tool("research", "sec_filing_search", "AAPL"))
print("Analyst + calculator:", run_tool("analyst", "calculator", "207.48 / 6.00"))
print("Research + calculator:", run_tool("research", "calculator", "207.48 / 6.00"))
print("Planner + any tool:", run_tool("planner", "sec_filing_search", "AAPL"))
print("Least privilege: the denial is the feature. If research could")
print("calculate, it could invent numbers. It cannot, by construction.")
Try it yourself
Run the code, then try run_tool('verifier', 'calculator', '1 + 1'). What do you get?
Check
Which tools may Research use?
Only sec_filing_search and earnings_call_transcript.
Which tools may the Planner use?
None. Zero tools.
Module 2: Skills as Versioned Bundles (Lab 2)
What it is
Skills are versioned bundles: a description, a list of tools, and an output schema. They are 'prompts as code.' You can diff valuation-metrics v2.1.0 against v2.0.0 in code review, exactly like any other dependency. A skill says what a capability is, which tools it needs, and what it must produce. Lab 2 (15 minutes): add a new tool debt_to_equity(ticker) that reads from filings.json. Then register it in TOOLS, allow-list it only for the Analyst in TOOL_PERMISSIONS, and add a skill called leverage-analysis. Checkpoint: calling it from Research returns {'error': "tool 'debt_to_equity' not allowed for role 'research'"}. That error is the proof that permission enforcement works.
Why it matters
Versioned skills mean you can review, test, and roll back a capability like any other code. An unversioned prompt is a change nobody can track.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Skills are versioned bundles: description + tools + output schema.
# "Prompts as code." You can diff valuation-metrics v2.1.0 against v2.0.0
# in code review, exactly like any other dependency.
# LAB 2: add a debt_to_equity tool, allow-list it only for analyst,
# and add a leverage-analysis skill.
import re
def debt_to_equity(ticker):
if ticker != FILING["ticker"]:
return {"error": "ticker not in demo corpus"}
ratio = round(FILING["debt_musd"] / FILING["equity_musd"], 2)
return {"ticker": ticker, "debt_to_equity": ratio,
"citations": [FILING["doc_id"]]}
TOOL_PERMISSIONS = {
"sec_filing_search": ["research"],
"earnings_call_transcript": ["research"],
"fetch_market_data": ["analyst"],
"calculator": ["analyst"],
"debt_to_equity": ["analyst"], # LAB 2: analyst only, not research
}
SKILLS = {
"valuation-metrics": {
"version": "2.1.0", "tools": ["calculator", "fetch_market_data"],
"output_schema": ["ticker", "pe_ratio", "citations", "disclaimer"],
"description": "Compute valuation ratios from evidence.",
},
"leverage-analysis": { # LAB 2: new skill
"version": "1.0.0", "tools": ["debt_to_equity"],
"output_schema": ["ticker", "debt_to_equity", "citations"],
"description": "Analyse leverage from the filing balance sheet.",
},
}
def run_tool(role, tool):
if role not in TOOL_PERMISSIONS.get(tool, []):
return {"error": f"tool '{tool}' not allowed for role '{role}'"}
return debt_to_equity("AAPL") if tool == "debt_to_equity" else {"ok": True}
print("Analyst + debt_to_equity:", run_tool("analyst", "debt_to_equity"))
print("Research + debt_to_equity:", run_tool("research", "debt_to_equity"))
print("Skills:", list(SKILLS))
print("valuation-metrics v2.1.0 needs:", SKILLS["valuation-metrics"]["output_schema"])
print("A skill is a bundle you can version, test, and review like code.")
Try it yourself
Run the code, then add a third skill of your own, for example 'risk-summary', with version 1.0.0.
Check
What is a skill, in this workshop?
A versioned bundle: description, tools, and output schema.
What should Lab 2 prove?
That debt_to_equity works for the Analyst and is denied for Research.
Module 3 — Harness Engineering (harness.py)
The heart of the workshop. Five layers between the user and the model, and between the model and the answer.
3 sections in this part.
Module 3: The Five Layers: Guardrails, PII, Schema, Audit, Human-in-the-Loop
What it is
Every agent turn passes through five layers. Layer 1, input guardrails: input_guardrails() blocks compliance violations, using BLOCKED_KEYWORDS in config.py, and oversized inputs. Layer 2, PII redaction: regular expressions remove social security numbers, card numbers, and emails BEFORE anything reaches a model, which is critical for regulated finance. Layer 3, output schema validation with bounded repair: the next lesson. Layer 4, audit log: every turn, tool call, denial, and retry appends to logs/audit.jsonl, your regulator-facing trail. Layer 5, human-in-the-loop: verification failures escalate rather than silently pass. Test Layer 1 yourself: input_guardrails('Give me a guaranteed return insider tip') returns {'ok': False, 'reason': "compliance block: prohibited phrase 'guaranteed return'"}.
Why it matters
The harness is the product. The model is a part inside it. A good harness makes a weak model safe, and a missing harness makes a strong model dangerous.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Module 3: Harness Engineering (harness.py) — the heart of the workshop.
# Every agent turn passes through five layers:
# 1. Input guardrails — block compliance violations and oversized input.
# 2. PII redaction — remove sensitive data BEFORE it reaches a model.
# 3. Output schema validation — with bounded repair (see next lesson).
# 4. Audit log — every turn, tool call, denial, and retry is written down.
# 5. Human-in-the-loop — verification failures escalate, never silently pass.
import re
BLOCKED_KEYWORDS = ["guaranteed return", "insider tip"]
def input_guardrails(text):
if len(text) > 2000:
return {"ok": False, "reason": "input too long"}
for word in BLOCKED_KEYWORDS:
if word in text.lower():
return {"ok": False, "reason": f"compliance block: prohibited phrase '{word}'"}
return {"ok": True}
def redact_pii(text):
text = re.sub(r"\d{3}-\d{2}-\d{4}", "[SSN]", text)
text = re.sub(r"\b[\w.-]+@[\w.-]+\.[a-z]{2,}\b", "[EMAIL]", text)
text = re.sub(r"\b\d{4}[- ]\d{4}[- ]\d{4}[- ]\d{4}\b", "[CARD]", text)
return text
print(input_guardrails("Give me a guaranteed return insider tip"))
print(input_guardrails("Analyze AAPL filing, compute P/E"))
print(redact_pii("Client John, SSN 123-45-6789, email john@example.com"))
print("Guardrails run BEFORE the model sees anything. That is the point:")
print("a blocked request never reaches the model, and PII never leaves.")
Try it yourself
Run the code, then try input_guardrails with your own blocked phrase, for example 'insider tip'.
Check
What are the five harness layers?
Input guardrails, PII redaction, output schema validation, audit log, and human-in-the-loop.
When does PII redaction happen?
Before anything reaches a model.
Module 3: Output Schema Validation with Bounded Repair, and the Audit Log
What it is
AgentRunner checks the model's final answer against required_keys: ticker, pe_ratio, citations, disclaimer. If keys are missing, it injects schema_feedback into the state and retries, up to MAX_RETRIES_SCHEMA times. Then it fails safely instead of shipping garbage. The answer is either complete, or it is an error object. It is never delivered half-finished. The audit log records every check: read logs/audit.jsonl with cat logs/audit.jsonl | python -m json.tool --json-lines | head -30. In production, this log is your regulator-facing trail: every turn, every tool call, every denial, every retry, written down in order.
Why it matters
A system that ships half an answer is worse than a system that says it failed. Bounded repair gives the model a chance to fix itself, and a hard limit stops it from trying forever.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Layer 3: output schema validation with bounded repair.
# AgentRunner checks the model's final answer against required_keys.
# If keys are missing, it injects schema_feedback and retries, up to
# MAX_RETRIES_SCHEMA times — then fails safely instead of shipping garbage.
# Layer 4: audit log. Every turn appends to logs/audit.jsonl.
import json
MAX_RETRIES_SCHEMA = 2
REQUIRED_KEYS = ["ticker", "pe_ratio", "citations", "disclaimer"]
def validate(answer):
missing = [k for k in REQUIRED_KEYS if k not in answer]
return {"ok": not missing, "missing": missing}
def run_with_schema_check(make_answer):
audit = []
for attempt in range(1, MAX_RETRIES_SCHEMA + 2):
answer = make_answer(attempt)
check = validate(answer)
audit.append({"event": "schema_check", "attempt": attempt,
"ok": check["ok"], "missing": check["missing"]})
if check["ok"]:
return {"status": "ok", "answer": answer, "audit": audit}
print(f"Attempt {attempt}: missing {check['missing']} — retrying with feedback.")
return {"status": "error", "error": "schema validation failed",
"answer": None, "audit": audit}
def bad_first_try(attempt):
if attempt == 1:
return {"ticker": "AAPL", "pe_ratio": 34.58} # missing citations + disclaimer
return {"ticker": "AAPL", "pe_ratio": 34.58,
"citations": [FILING["doc_id"]], "disclaimer": DISCLAIMER}
result = run_with_schema_check(bad_first_try)
print("Status:", result["status"])
print("Audit log (logs/audit.jsonl):")
for entry in result["audit"]:
print(" ", json.dumps(entry))
print("Fail-safe: a bad answer is repaired, or returned as an error object.")
print("It is never delivered as if it were fine.")
Try it yourself
Run the code. How many attempts does it take before the answer passes?
Check
What happens if the answer is still incomplete after the retries?
It fails safely, as an error object. It is never delivered.
What does the audit log record?
Every turn, tool call, denial, and retry.
Module 3: Human-in-the-Loop Escalation (Lab 3)
What it is
Human-in-the-loop, or HITL, means a human reviews the answer when the system is not sure. Verification failures escalate rather than silently pass. Set HITL_ON_VERIFY_FAIL to False in config.py and re-run eval.py, and watch the eval suite catch the regression immediately. That is the point of an eval suite: it catches the day someone turns a safety feature off. Lab 3 (20 minutes): add 'wire transfer instructions' to BLOCKED_KEYWORDS. Write a 5-line test asserting run('...wire transfer instructions...')['status'] == 'blocked'. Checkpoint: your test passes, and the audit log shows blocked_input.
Why it matters
Escalation is not failure. It is the system knowing its limits. A system that never escalates is a system that never admits it is wrong.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Layer 5: human-in-the-loop (HITL). Verification failures escalate
# rather than silently pass. Set HITL_ON_VERIFY_FAIL = False in config.py
# and re-run eval.py — the eval suite catches the regression immediately.
# LAB 3: add "wire transfer instructions" to BLOCKED_KEYWORDS and write
# a 5-line test asserting the request is blocked.
BLOCKED_KEYWORDS = ["guaranteed return", "insider tip",
"wire transfer instructions"] # LAB 3: added
HITL_ON_VERIFY_FAIL = True
def run(query, verified):
for word in BLOCKED_KEYWORDS:
if word in query.lower():
return {"status": "blocked", "reason": f"compliance block: '{word}'",
"audit": "blocked_input"}
if not verified:
if HITL_ON_VERIFY_FAIL:
return {"status": "escalated_to_human",
"reason": "verification failed — a human must review"}
return {"status": "error", "reason": "verification failed"}
return {"status": "ok", "pe_ratio": 34.58}
# LAB 3 test: 5 lines, and it must pass.
def test_blocked():
result = run("Send me wire transfer instructions", verified=True)
assert result["status"] == "blocked", result
print("TEST PASSED: wire transfer instructions -> blocked")
test_blocked()
print(run("Analyze AAPL", verified=False))
print(run("Analyze AAPL", verified=True))
print("HITL is deterministic escalation, not silent failure.")
print("A human reviews it, or it does not go out.")
Try it yourself
Run the code, then change HITL_ON_VERIFY_FAIL to False in your head and predict what run('Analyze AAPL', verified=False) returns.
Check
What is HITL, in plain words?
A human reviews the answer when the system is not sure, instead of the system guessing.
What should Lab 3 prove?
That 'wire transfer instructions' is blocked, and the audit log shows blocked_input.
Module 4 — Loop Engineering (orchestrator.py)
The production agentic loop, made safe: plan, act, observe, verify, deliver — with a hard bound.
3 sections in this part.
Module 4: The Bounded Loop and the ReAct Pattern
What it is
The production agentic loop is: plan, act, observe the tool result, act again, and so on, bounded, then verify, then deliver. This is the ReAct pattern: the agent reasons, then acts, then observes what happened, then reasons again. The difference in production is the bound. MAX_LOOP_ITERATIONS is a hard cap on iterations. No runaway agent spends money, calls tools forever, or loops on the same mistake. A loop without a bound is a bill with no limit. The loop exits when the agent returns 'final', or when it hits the cap. Either way, it stops.
Why it matters
A loop is powerful and dangerous in equal measure. The bound is what makes it safe to run in production.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Module 4: Loop Engineering (orchestrator.py).
# The production agentic loop: plan -> act -> observe -> act -> ... (bounded)
# -> verify -> deliver. This is the ReAct pattern — with a hard bound.
# MAX_LOOP_ITERATIONS stops runaway agents. No runaway agent spends money.
import re
MAX_LOOP_ITERATIONS = 5
def calculator(expression):
if not re.fullmatch(r"[0-9+\-*/(). ]+", expression):
return {"error": "calculator refused unsafe expression"}
return {"result": round(eval(expression, {"__builtins__": {}}, {}), 2)}
def research_act(state, step):
# Research mini-loop: each "tool" decision is executed by the harness,
# the result is merged into state, and the loop exits on "final".
if step == 0:
return {"action": "tool", "tool": "sec_filing_search", "args": "AAPL"}
if step == 1:
return {"action": "tool", "tool": "earnings_call_transcript", "args": "AAPL"}
return {"action": "final"}
def run_loop():
state, steps = {}, []
for i in range(MAX_LOOP_ITERATIONS):
decision = research_act(state, i)
steps.append(decision["action"])
if decision["action"] == "final":
break
if decision["tool"] == "sec_filing_search":
state["filing"] = FILING
else:
state["call"] = EARNINGS_CALL
calc = calculator("207.48 / 6.00")
return {"steps": steps, "pe_ratio": calc["result"],
"evidence": list(state.keys())}
print(run_loop())
print("Bounded loop: at most 5 steps, then it stops, pass or fail.")
print("A loop without a bound is a bill with no limit.")
Try it yourself
Run the code, then change MAX_LOOP_ITERATIONS to 2 in the code and run it again. What is missing?
Check
What is the ReAct pattern, in plain words?
Reason, act, observe the result, reason again, until done or the limit is reached.
What stops a runaway loop?
MAX_LOOP_ITERATIONS, a hard cap on iterations.
Module 4: The Planner and the Research Mini-Loop
What it is
The Planner turns one natural-language request into an ordered step list: guardrail_check, retrieve_filings, extract_financials, fetch_market_data, run_calculations, synthesize_report, verify_and_deliver. Then the research mini-loop runs it. run() calls research.act(state) repeatedly. Each 'tool' decision is executed by _do_tool, and the result is merged into state. The loop exits when the agent returns 'final' or hits MAX_LOOP_ITERATIONS. Each tool result becomes part of the evidence the next step can use. Nothing is forgotten between steps, because state carries it forward.
Why it matters
Planning and doing are different jobs. The Planner decides the order. The loop does the work, one tool call at a time.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# The Planner turns one request into an ordered step list, then the
# research mini-loop runs it: each "tool" decision is executed by
# _do_tool, the result is merged into state, and the loop exits when
# the agent returns "final" or hits MAX_LOOP_ITERATIONS.
PLAN_STEPS = ["guardrail_check", "retrieve_filings", "extract_financials",
"fetch_market_data", "run_calculations", "synthesize_report",
"verify_and_deliver"]
def do_tool(tool, state):
if tool == "sec_filing_search":
state["filing"] = FILING
return "filing loaded: " + FILING["doc_id"]
if tool == "earnings_call_transcript":
state["call"] = EARNINGS_CALL
return "transcript loaded"
if tool == "fetch_market_data":
state["price"] = PRICE
return f"price loaded: ${PRICE}"
return "unknown tool"
def run_research_loop(max_iterations=5):
state, log = {}, []
plan = ["sec_filing_search", "earnings_call_transcript", "fetch_market_data"]
for i, tool in enumerate(plan):
if i >= max_iterations:
log.append(f"STOPPED at iteration {max_iterations}: {tool} never ran")
break
log.append(do_tool(tool, state))
log.append("research: final — evidence gathered")
return {"state_keys": sorted(state.keys()), "log": log}
result = run_research_loop()
for line in result["log"]:
print(" -", line)
print("State now holds:", result["state_keys"])
print("The planner decides WHAT to do. The loop decides WHEN to stop.")
Try it yourself
Run the code, then add a fourth tool to the plan list and run it again.
Check
What is the Planner's step list?
guardrail_check, retrieve_filings, extract_financials, fetch_market_data, run_calculations, synthesize_report, verify_and_deliver.
What does _do_tool do?
It runs the tool the agent chose and merges the result into state.
Module 4: The Analyst Must Calculate, and the Verifier Recomputes (Lab 4)
What it is
The Analyst has its own mini-loop, and it must call the calculator before answering. A flag, calc_done, enforces it. The principle: never let the LLM do arithmetic it can delegate to a tool. Models are good at language and bad at arithmetic, and a calculator is exact. Then the Verifier recomputes pe_ratio from raw evidence, price divided by EPS, and compares it to the Analyst's claim within 0.01 tolerance. It also enforces citations and the compliance disclaimer. Lab 4 (20 minutes): set MAX_LOOP_ITERATIONS to 1 in config.py and run main.py. Checkpoint: the answer arrives with mgmt_sentiment missing, because the transcript fetch never happened, and the observability table shows exactly which step was starved. Bounded loops fail visibly, not silently.
Why it matters
Verification is not trust. It is recomputation. The Verifier does not believe the Analyst; it checks the Analyst, from the raw numbers.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# The Analyst's own mini-loop: it MUST call the calculator before
# answering (calc_done flag). Never let the LLM do arithmetic it can
# delegate to a tool. The Verifier then recomputes pe_ratio from raw
# evidence (price / eps) and compares within 0.01 tolerance, and also
# enforces citations and the disclaimer.
# LAB 4: set MAX_LOOP_ITERATIONS = 1 and see the loop fail VISIBLY.
import re
MAX_LOOP_ITERATIONS = 5 # LAB 4: change this to 1 and run again.
def calculator(expression):
if not re.fullmatch(r"[0-9+\-*/(). ]+", expression):
return {"error": "calculator refused unsafe expression"}
return {"result": round(eval(expression, {"__builtins__": {}}, {}), 2)}
def analyst(state):
calc_done = False
for _ in range(MAX_LOOP_ITERATIONS):
if not calc_done:
result = calculator(f"{state['price']} / {state['eps']}")
calc_done = True
state["pe_ratio"] = result["result"]
continue
break
return {"ticker": "AAPL", "pe_ratio": state["pe_ratio"],
"citations": [FILING["doc_id"]], "disclaimer": DISCLAIMER,
"calc_done": calc_done}
def verifier(answer, state):
recomputed = round(state["price"] / state["eps"], 2)
issues = []
if abs(recomputed - answer["pe_ratio"]) > 0.01:
issues.append(f"P/E mismatch: claimed {answer['pe_ratio']}, recomputed {recomputed}")
if not answer.get("citations"):
issues.append("missing citations")
if "disclaimer" not in answer:
issues.append("missing disclaimer")
return {"verdict": "pass" if not issues else "fail", "issues": issues,
"recomputed_pe": recomputed}
state = {"price": PRICE, "eps": FILING["eps"]}
answer = analyst(state)
print("Analyst answer:", answer)
print("Verifier:", verifier(answer, state))
print("LAB 4 preview: with MAX_LOOP_ITERATIONS = 1, the transcript fetch")
print("never happens, mgmt_sentiment is missing, and the trace shows which")
print("step was starved. Bounded loops fail visibly, not silently.")
Try it yourself
Run the code, then change MAX_LOOP_ITERATIONS to 1 at the top and run it again. What is missing from the answer?
Check
Why must the Analyst use the calculator?
Models are bad at arithmetic. A calculator is exact.
What does the Verifier check?
It recomputes P/E within 0.01, and checks citations and the disclaimer.
Module 5 — Multi-Agent Composition
Four roles, four contracts. Separation of concerns, like a real research desk.
1 sections in this part.
Module 5: Four Roles: Planner, Research, Analyst, Verifier
What it is
Four roles, four contracts. The Planner has no tools and must produce an ordered step list; it exists to separate what to do from how to do it. Research has the filing search and transcript tools and must produce a summary and citations; it exists to be evidence-grounded only. The Analyst has the calculator and market data tools and must produce ticker, pe_ratio, citations, and disclaimer; it exists so numbers come from tools. The Verifier has no tools and must produce a verdict and a list of issues; it exists as an independent adversarial check. Design principle: separation of concerns that mirrors a real research desk. The Verifier's independence, with no shared reasoning chain, is what makes its pass meaningful. If the Verifier shared the Analyst's thinking, it would repeat the same mistakes.
Why it matters
One agent cannot do everything well. Four small agents, each with a contract, are easier to test, easier to fix, and harder to fool.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Module 5: Multi-Agent Composition — four roles, four contracts.
# Separation of concerns, like a real research desk. The verifier's
# independence (no shared reasoning chain) is what makes its pass meaningful.
ROLES = {
"Planner": {"tools": [], "required": ["ordered step list"],
"why": "Separates WHAT to do from HOW to do it."},
"Research": {"tools": ["sec_filing_search", "earnings_call_transcript"],
"required": ["summary", "citations"],
"why": "Evidence-grounded only. It may not invent facts."},
"Analyst": {"tools": ["calculator", "fetch_market_data"],
"required": ["ticker", "pe_ratio", "citations", "disclaimer"],
"why": "Numbers come from tools, never from the model's head."},
"Verifier": {"tools": [],
"required": ["verdict", "issues"],
"why": "Independent adversarial check. It trusts nothing."},
}
for name, contract in ROLES.items():
tools = ", ".join(contract["tools"]) if contract["tools"] else "no tools"
print(f"{name:10} tools: {tools}")
print(f"{'':10} must produce: {', '.join(contract['required'])}")
print(f"{'':10} why it exists: {contract['why']}")
print()
print("One agent cannot do everything well. Four small agents, each with")
print("a contract, are easier to test, easier to fix, and harder to fool.")
Try it yourself
Run the code, then cover the 'why' column and try to say, for each role, why it exists.
Check
Which two roles have zero tools, and why?
Planner and Verifier. The Planner only plans, and the Verifier only checks.
Why must the Verifier be independent?
So it does not repeat the Analyst's mistakes. Its pass only means something if it checked on its own.
Module 6 — Evaluation Framework (eval.py)
Beyond 'it looked good.' Three axes, three cases, seven checks, and eval as a deployment gate.
2 sections in this part.
Module 6: Three Axes, Three Cases, Seven Checks
What it is
Evaluation has three axes, measured on the full orchestrator. Axis 1, task success: status is 'ok', required answer keys are present, and the P/E ratio is sane. Axis 2, groundedness: citations are non-empty, and the verifier's recomputation passed. Axis 3, safety: the compliance-block case must return status 'blocked'. There are three eval cases, seven checks in total. Run python eval.py and you should see 7/7 checks passed, 100 percent. This is your deployment gate: a pull request that drops the score cannot merge. That is eval-as-CI. Deterministic under MockLLM, these evals run in continuous integration, every time, for free.
Why it matters
An eval is not a report card. It is a gate. If it fails, the code does not ship, no matter how good it looked in a demo.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Module 6: Evaluation Framework (eval.py). Beyond "it looked good."
# Three axes, measured on the full orchestrator. Deterministic under
# MockLLM, so these run in CI. This is your deployment gate: a PR that
# drops the score cannot merge — eval-as-CI.
import re
def calculator(expression):
return {"result": round(eval(expression, {"__builtins__": {}}, {}), 2)}
def run_system(query, eps=6.00):
if "guaranteed return" in query.lower():
return {"status": "blocked"}
pe_ratio = calculator(f"{PRICE} / {eps}")["result"]
return {"status": "ok", "pe_ratio": pe_ratio,
"citations": [FILING["doc_id"]], "verdict": "pass",
"disclaimer": DISCLAIMER}
def run_eval():
checks = []
# Axis 1 — Task success: status ok, keys present, P/E sane.
r = run_system("Analyze AAPL")
checks.append(("task success: status ok", r["status"] == "ok"))
checks.append(("task success: pe_ratio sane", 0 < r["pe_ratio"] < 100))
# Axis 2 — Groundedness: citations non-empty, verifier recomputation passed.
checks.append(("groundedness: citations present", bool(r["citations"])))
checks.append(("groundedness: verifier passed", r["verdict"] == "pass"))
checks.append(("groundedness: disclaimer present", "disclaimer" in r))
# Axis 3 — Safety: the compliance-block case must return blocked.
b = run_system("Give me a guaranteed return")
checks.append(("safety: blocked case returns blocked", b["status"] == "blocked"))
checks.append(("safety: blocked case has no answer", "pe_ratio" not in b))
passed = sum(1 for _, ok in checks if ok)
for name, ok in checks:
print(("PASS" if ok else "FAIL") + ":", name)
print(f"EVALUATION SUMMARY: {passed}/{len(checks)} checks passed ({passed * 100 // len(checks)}%)")
return passed == len(checks)
run_eval()
print("Eval is a gate, not a report. If it fails, the code does not ship.")
Try it yourself
Run the code, then change the price to 999.99 in the run_system call and see which checks fail.
Check
What are the three evaluation axes?
Task success, groundedness, and safety.
What is eval-as-CI?
Evals run automatically on every change, and a failing eval blocks the change from shipping.
Module 6: Lab 6: Add a Fourth Eval Case with a Wrong EPS
What it is
Lab 6 (25 minutes): add a fourth eval case. Inject a wrong EPS into a copy of the corpus and assert the verifier flags the mismatch, expecting escalated_to_human. The Analyst claims a P/E computed from the wrong EPS, 8.00 instead of 6.00. The Verifier recomputes from the true EPS and finds the mismatch. The harness escalates to a human. Checkpoint: your new case demonstrates the hallucination-catching loop working as designed. A system that catches a wrong number in a test is a system you can trust with a real number.
Why it matters
The best eval is an adversarial one: a case designed to catch the system lying. If your evals only test the easy cases, they prove nothing.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# LAB 6: add a 4th eval case. Inject a WRONG EPS into a copy of the
# corpus and assert the verifier flags the mismatch (escalated_to_human).
# This is the hallucination-catching loop, working as designed.
def verifier(answer, price, true_eps):
recomputed = round(price / true_eps, 2)
if abs(recomputed - answer["pe_ratio"]) > 0.01:
return {"verdict": "fail",
"issue": f"P/E mismatch: claimed {answer['pe_ratio']}, recomputed {recomputed}"}
return {"verdict": "pass"}
def run_with_harness(answer, price, true_eps, hitl=True):
check = verifier(answer, price, true_eps)
if check["verdict"] == "fail" and hitl:
return {"status": "escalated_to_human", "reason": check["issue"]}
return {"status": "ok" if check["verdict"] == "pass" else "error"}
# Case 4: the analyst claims a P/E computed from a WRONG EPS (8.00, not 6.00).
wrong_answer = {"ticker": "AAPL", "pe_ratio": round(PRICE / 8.00, 2)}
result = run_with_harness(wrong_answer, PRICE, FILING["eps"])
print("Wrong EPS case:", result)
assert result["status"] == "escalated_to_human", result
print("TEST PASSED: wrong EPS was caught by the verifier and escalated.")
print("A wrong number is not delivered. A human reviews it.")
Try it yourself
Run the code, then change the wrong EPS from 8.00 to 6.50 and run it again. Does it still get caught?
Check
What does Lab 6 prove?
That a wrong EPS is caught by the verifier and escalated to a human.
Why add an adversarial eval case?
To prove the system catches a lie, not just that it passes the easy cases.
Module 7 — Observability (observability.py)
If you cannot see it, you cannot run it. Traces, latency, tokens, and cost.
2 sections in this part.
Module 7: Traces: Spans, Latency, Tokens, and Cost
What it is
Every span records latency in milliseconds, token counts, and the model name, to logs/traces.jsonl. summarize_traces() rolls up per-component stats. In the demo output you will see, for example, 'llm.research': 3 calls, average latency 0.07 milliseconds, 160 tokens, and 'tool.sec_filing_search': 1 call, average latency 0.47 milliseconds. Cost is token count times PRICE_PER_1K_TOKENS in config.py. Latency is per-component average latency, which shows your bottleneck. Reliability is the verify-fail rate from audit.jsonl, the 'verify' events with verdict fail. Tool health is the error field on tool spans. What you monitor in production maps directly from the demo: cost, latency, reliability, and tool health.
Why it matters
Observability turns a black box into a system you can run. Without it, a slow or expensive agent is invisible until the bill arrives.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Module 7: Observability (observability.py).
# Every span records latency, token counts, and model name to
# logs/traces.jsonl. summarize_traces() rolls up per-component stats.
import json, time
TRACES = []
def trace(component, fn, **kw):
start = time.time()
result = fn(**kw)
TRACES.append({"component": component,
"latency_ms": round((time.time() - start) * 1000, 2),
"tokens": kw.get("tokens", 0), "model": "mock",
"error": result.get("error") if isinstance(result, dict) else None})
return result
def sec_filing_search(ticker):
return {"ticker": ticker, "eps": FILING["eps"], "tokens": 80}
def calculator(expression):
return {"result": round(eval(expression, {"__builtins__": {}}, {}), 2), "tokens": 10}
trace("llm.research", sec_filing_search, ticker="AAPL")
trace("llm.research", sec_filing_search, ticker="AAPL")
trace("tool.calculator", calculator, expression="207.48 / 6.00")
def summarize_traces(traces):
summary = {}
for span in traces:
s = summary.setdefault(span["component"], {"calls": 0, "latency": [], "tokens": 0})
s["calls"] += 1
s["latency"].append(span["latency_ms"])
s["tokens"] += span["tokens"]
for name, s in summary.items():
s["avg_latency_ms"] = round(sum(s["latency"]) / len(s["latency"]), 2)
return summary
print(json.dumps(summarize_traces(TRACES), indent=2))
print("In production, map this to: cost (tokens x price), latency (slowest")
print("component), reliability (verify-fail rate), tool health (error field).")
Try it yourself
Run the code, then add a second calculator trace and run summarize_traces again.
Check
What does each trace span record?
Latency, token counts, and the model name.
How do you find the bottleneck?
Look at per-component average latency. The slowest component is the bottleneck.
Module 7: Lab 7: Write report.py — a Markdown Table from Traces
What it is
Lab 7 (15 minutes): write report.py. It reads traces.jsonl and prints a markdown table of component, calls, and p95 latency. p95 means the 95th percentile: 95 percent of calls were faster than this number. It is a better number than the average, because one very slow call hides in an average and shows up in a p95. Checkpoint: the table renders with real numbers from your last run. Save the script, run it after every run, and read the table before you read the code. A table beats a feeling.
Why it matters
A report you can read in ten seconds is worth more than a log file you never open. Make the numbers easy to see.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# LAB 7: write report.py. It reads traces.jsonl and prints a markdown
# table of component / calls / p95 latency. Checkpoint: the table renders
# with real numbers from your last run.
import json, math
# Demo traces, as if written by the last run to logs/traces.jsonl.
TRACES = [
{"component": "llm.research", "latency_ms": 0.07, "tokens": 80},
{"component": "llm.research", "latency_ms": 0.09, "tokens": 80},
{"component": "llm.research", "latency_ms": 0.06, "tokens": 80},
{"component": "tool.sec_filing_search", "latency_ms": 0.47, "tokens": 0},
{"component": "tool.calculator", "latency_ms": 0.02, "tokens": 10},
]
def p95(values):
ordered = sorted(values)
index = max(0, math.ceil(0.95 * len(ordered)) - 1)
return ordered[index]
def report(traces):
by_component = {}
for span in traces:
by_component.setdefault(span["component"], []).append(span["latency_ms"])
print("| Component | Calls | p95 latency (ms) |")
print("|-----------|-------|------------------|")
for name, latencies in sorted(by_component.items()):
print(f"| {name} | {len(latencies)} | {p95(latencies):.2f} |")
report(TRACES)
print("Save this as report.py, read logs/traces.jsonl instead of the demo")
print("list, and run it after every run. A table beats a feeling.")
Try it yourself
Run the code, then add a trace with latency 5.00 and see how the p95 changes.
Check
What is p95 latency?
The 95th percentile: 95 percent of calls were faster than this number.
Why p95 instead of the average?
One very slow call hides in an average and shows up in a p95.
Module 8 — Security and Governance
Secrets, PII, compliance, audit, and a fail-safe posture. Security is not an extra at the end.
1 sections in this part.
Module 8: Secrets, PII, Compliance, Audit, and Fail-Safe
What it is
Secrets: only in environment variables. config.py reads them, never stores them, and you never print a key, never commit a key, and never put a key in code. Data protection: PII redaction happens pre-model, and tool responses are the only data crossing the trust boundary. Compliance: a blocked-keyword list plus mandatory disclaimer enforcement, which the verifier checks. Auditability: the append-only audit.jsonl is a regulator-ready trail, and every tool call has its arguments logged. Fail-safe posture: a schema failure returns an error object, never partial data, and a verify failure goes to human escalation, never a silent pass. In a regulated industry, the system that says 'I cannot do this safely' is the system you can trust.
Why it matters
Security is not a feature you add at the end. If an agent can call tools, it must be checked, or it can delete data, spend money, or leak secrets.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Module 8: Security & Governance.
# Secrets only in env vars. PII redaction pre-model. Compliance blocked
# list + mandatory disclaimer. Append-only audit log. Fail-safe posture:
# schema failure -> error object, verify failure -> human escalation.
import os, re, json
# Secrets: only in env vars. config.py READS them, never STORES them.
print("LLM_PROVIDER:", os.environ.get("LLM_PROVIDER", "mock"))
print("OPENAI_API_KEY set?", bool(os.environ.get("OPENAI_API_KEY")))
print("Never print a key. Never commit a key. Never put a key in code.")
def redact_pii(text):
text = re.sub(r"\d{3}-\d{2}-\d{4}", "[SSN]", text)
text = re.sub(r"\b[\w.-]+@[\w.-]+\.[a-z]{2,}\b", "[EMAIL]", text)
return text
AUDIT_LOG = [] # in the real system: append-only logs/audit.jsonl
def audit(event, detail):
AUDIT_LOG.append({"event": event, "detail": detail})
def deliver(answer, verified):
if not verified:
audit("verify", {"verdict": "fail"})
return {"status": "escalated_to_human"} # never a silent pass
if "disclaimer" not in answer:
audit("schema", {"error": "missing disclaimer"})
return {"status": "error", "error": "schema validation failed"}
audit("deliver", {"pe_ratio": answer["pe_ratio"]})
return {"status": "ok", "answer": answer}
print(redact_pii("SSN 123-45-6789, email a@b.com"))
print(deliver({"pe_ratio": 34.58}, verified=False))
print(deliver({"pe_ratio": 34.58, "disclaimer": DISCLAIMER}, verified=True))
print("Audit trail:")
for entry in AUDIT_LOG:
print(" ", json.dumps(entry))
print("Fail-safe: bad schema -> error object. Bad verify -> human. Always.")
Try it yourself
Run the code, then try deliver with verified=True but no disclaimer. What do you get?
Check
Where do secrets live?
Only in environment variables. Never in code, never in a commit.
What does fail-safe mean here?
Schema failure gives an error object, and verify failure goes to a human. Never a silent pass.
Reference — Patches, Agendas, Troubleshooting, Glossary
Apply the patches first, pick an agenda, fix the common problems, and learn the four words.
4 sections in this part.
Reference: The Two Patches (Apply First)
What it is
During verification, two small bugs were found. Apply both before anything else; they take two minutes. Patch 1, tools.py, guidance extraction: a hidden character in the sample transcript defeats the substring check, so 'raise' is not found in the text even though it is there. Replace the naive check with a character-class-robust version: clean the text with re.sub(r'[^a-z]', '', text.lower()), then check 'raise' in the cleaned text. Patch 2, llm.py, method _research, eval case 3 crash: when a query does not mention earnings, the summary references keys that do not exist yet, and Python crashes with a KeyError. Replace the summary block with .get() calls, so missing keys give None instead of a crash, and only add the management-tone sentence if 'mgmt_sentiment' is in the evidence. With both patches, python eval.py passes 7/7 checks.
Why it matters
A workshop that hides its bugs wastes your time. These two patches are the difference between 6/7 and 7/7.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# FIRST: the two patches (2 minutes). Apply them before anything else.
# Patch 1 — tools.py, guidance extraction. A hidden character in the
# sample transcript defeats the substring check. The transcript below
# contains "raise" split by a soft hyphen (invisible). The naive check
# fails; the regex-clean version works.
import re
# The transcript contains: "We expect to rai<soft hyphen>se guidance."
hidden_text = "We expect to rai\u00adse guidance next quarter."
print("Naive check 'raise' in text:", "raise" in hidden_text.lower())
_clean = re.sub(r"[^a-z]", "", hidden_text.lower())
print("Patched check 'raise' in cleaned:", "raise" in _clean)
guidance = "raised" if "raise" in _clean else "maintained"
print("Guidance (patched):", guidance)
# Patch 2 — llm.py, method _research (eval case 3 crash). When a query
# does not mention earnings, the summary references keys that do not
# exist yet. Use .get() so missing keys give None instead of a crash.
ev = {"revenue_musd": FILING["revenue_musd"], "eps": FILING["eps"]}
tone = f"Management tone: {ev.get('mgmt_sentiment')} ({ev.get('guidance')})." \
if "mgmt_sentiment" in ev else ""
summary = (f"AAPL FY2025: revenue ${ev.get('revenue_musd')}M "
f"({ev.get('revenue_growth_pct')}% YoY), EPS ${ev.get('eps')}, "
f"primary risks: {', '.join(ev.get('risk_factors', ['n/a'])[:2])}. "
f"{tone}").strip()
print("Summary (patched, no crash):", summary)
print("With both patches, python eval.py passes 7/7 checks.")
Try it yourself
Run the code and look at the naive check result. Why is it False when the word is right there?
Check
What does Patch 1 fix?
A hidden character that defeats the 'raise' substring check. Regex-clean the text first.
What does Patch 2 fix?
A KeyError in eval case 3. Use .get() so missing keys give None, not a crash.
Reference: Suggested Agendas: 2-Day Intensive and 4-Week Bootcamp
What it is
The same workshop, two speeds. Two-day intensive: Day 1 morning, Modules 0 to 3; Day 1 afternoon, Modules 4 and 5 plus labs; Day 2 morning, Modules 6 and 7 plus capstone kickoff; Day 2 afternoon, capstone build, demo, and retro. Four-week bootcamp: Week 1, Modules 0 to 2 plus Lab 2; Week 2, Modules 3 to 5 plus Labs 3 and 4; Week 3, Modules 6 to 8 plus Labs 6 and 7; Week 4, capstone. Pick the agenda that fits your calendar. The modules are the same; only the time between them changes. Spacing helps: a week between modules gives you time to try the labs on your own data.
Why it matters
An agenda is a plan, not a race. The intensive is fast and tiring. The bootcamp is slow and deep. Both end at the same capstone.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Suggested Agendas: the same workshop, two speeds.
AGENDAS = {
"2-day intensive": [
"Day 1 AM: Modules 0-3 (setup, LLM layer, tools, harness)",
"Day 1 PM: Modules 4-5 + Labs (loop, multi-agent composition)",
"Day 2 AM: Modules 6-7 + capstone kickoff (eval, observability)",
"Day 2 PM: capstone build + demo + retro",
],
"4-week bootcamp": [
"Week 1: Modules 0-2 + Lab 2 (setup, LLM, tools)",
"Week 2: Modules 3-5 + Labs 3-4 (harness, loop, composition)",
"Week 3: Modules 6-8 + Labs 6-7 (eval, observability, security)",
"Week 4: capstone",
],
}
for name, days in AGENDAS.items():
print(name + ":")
for item in days:
print(" -", item)
print()
print("Pick the agenda that fits your calendar. The modules are the same;")
print("only the time between them changes.")
Try it yourself
Pick one agenda and write down which days you would do it.
Check
What is on Day 1 morning of the intensive?
Modules 0 to 3.
What is Week 4 of the bootcamp?
The capstone.
Reference: Troubleshooting Table
What it is
The five problems everyone hits, and the fix for each. FileNotFoundError for data files: you ran from the wrong directory. Change directory into multi_agent_finance_workshop first, because paths are relative to the repo root. Eval case 3 KeyError: apply Patch 2, use ev.get() in MockLLM._research. Guidance shows 'maintained': apply Patch 1, regex-clean the text before the substring check. ModuleNotFoundError for openai: pip install openai, then set OPENAI_API_KEY and LLM_PROVIDER=openai, or stay on mock, which needs no install. Empty observability table: traces accumulate per run. Delete logs/traces.jsonl for a clean measurement, then run main.py again.
Why it matters
Read the error first. Most fixes are one line, in one file. The error message is telling you where to look.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Troubleshooting: the five problems everyone hits, and the fix.
ISSUES = {
"FileNotFoundError: data/...": "Run from the wrong directory. cd into multi_agent_finance_workshop first — paths are relative to the repo root.",
"eval.py case 3 KeyError": "Apply Patch 2. Use ev.get(...) in MockLLM._research so missing keys give None, not a crash.",
"guidance shows 'maintained'": "Apply Patch 1. Regex-clean the text before the substring check.",
"ModuleNotFoundError: openai": "pip install openai, then set OPENAI_API_KEY and LLM_PROVIDER=openai. Or stay on mock — it needs no install.",
"Empty observability table": "Traces accumulate per run. Delete logs/traces.jsonl for a clean measurement, then run main.py again.",
}
for symptom, fix in ISSUES.items():
print(f"Problem: {symptom}")
print(f"Fix: {fix}")
print()
print("Read the error first. Most fixes are one line, in one file.")
Try it yourself
Run the code, then find the fix for 'Empty observability table' without looking at the table.
Check
What causes FileNotFoundError for data files?
Running from the wrong directory. Change into multi_agent_finance_workshop first.
How do you get a clean observability measurement?
Delete logs/traces.jsonl, then run main.py again.
Reference: Glossary
What it is
Four words, in plain English. Harness Engineering: treating prompts, guardrails, validation, retries, and audit as first-class engineering around the model. Loop Engineering: designing plan, act, observe cycles with bounds, supervision, and stopping conditions. HITL, Human-in-the-Loop: deterministic escalation to a human instead of silent failure. Groundedness: every claim traceable to retrieved evidence, citations plus recomputation. If a word is not in this list, ask what it means before you use it. Jargon is only useful when everyone agrees what it means.
Why it matters
Learn the four words and you can read any paper about agents. Skip them and every paper sounds like magic.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# Glossary: four words, in plain English.
GLOSSARY = {
"Harness Engineering": "Treating prompts, guardrails, validation, retries, and audit as first-class engineering around the model.",
"Loop Engineering": "Designing plan -> act -> observe cycles with bounds, supervision, and stopping conditions.",
"HITL (Human-in-the-Loop)": "Deterministic escalation to a human instead of silent failure.",
"Groundedness": "Every claim traceable to retrieved evidence — citations plus recomputation.",
}
for term, meaning in GLOSSARY.items():
print(f"{term}: {meaning}")
print()
print("If a word is not in this list, ask what it means before you use it.")
Try it yourself
Run the code, then explain Harness Engineering to yourself in one sentence, out loud.
Check
What is Groundedness?
Every claim traceable to retrieved evidence: citations plus recomputation.
What is HITL?
Human-in-the-Loop: deterministic escalation to a human instead of silent failure.
Capstone Project (graded, about 8 to 12 hours)
Brief: extend this system into a production-style agent for a domain of your choice: a portfolio risk review, KYC document triage, an earnings-desk copilot, or a compliance memo. The code below is the full system in one file, so you can start from a working base. Copy it, save it as capstone.py, run it with python3 capstone.py, then extend it into your domain.
Note: Swap note: the examples use MockLLM, a small deterministic stand-in that runs offline with no key. To use a real model, set LLM_PROVIDER=openai (or anthropic) and your API key in the environment — no code changes. The swap code is shown in Setup.
# Demo data — the same small AAPL corpus every lesson uses.
# This is a teaching demo, not live market data.
FILING = {
"ticker": "AAPL", "doc_id": "AAPL-10K-FY2025",
"revenue_musd": 391035, "revenue_growth_pct": 5.0,
"eps": 6.00, "debt_musd": 96000, "equity_musd": 64000,
"risk_factors": ["supply chain", "China demand"],
}
EARNINGS_CALL = "Revenue grew 5 percent. Management tone is positive. We expect to raise guidance next quarter."
PRICE = 207.48 # dollars, from the demo market-data file
DISCLAIMER = "This is a demo, not investment advice."
# CAPSTONE: the full multi-agent financial system, in one file.
# Save as capstone.py, run with: python3 capstone.py
# It runs main.py AND eval.py logic, offline, with MockLLM.
# Real file layout (config, llm, tools, skills, harness, orchestrator,
# observability, eval, main) is the same code, split into files.
import json, os, re, time
BLOCKED_KEYWORDS = ["guaranteed return", "insider tip", "wire transfer instructions"]
MAX_LOOP_ITERATIONS = 5
REQUIRED_KEYS = ["ticker", "pe_ratio", "citations", "disclaimer"]
PRICE_PER_1K_TOKENS = 0.002
TRACES, AUDIT = [], []
def trace(component, fn, **kw):
tokens = kw.pop("tokens", 0)
start = time.time()
result = fn(**kw)
TRACES.append({"component": component,
"latency_ms": round((time.time() - start) * 1000, 2),
"tokens": tokens})
return result
def audit(event, detail):
AUDIT.append({"event": event, "detail": detail})
def input_guardrails(text):
for word in BLOCKED_KEYWORDS:
if word in text.lower():
return {"ok": False, "reason": f"compliance block: '{word}'"}
return {"ok": True}
def calculator(expression):
if not re.fullmatch(r"[0-9+\-*/(). ]+", expression):
return {"error": "calculator refused unsafe expression"}
return {"result": round(eval(expression, {"__builtins__": {}}, {}), 2)}
def sec_filing_search(ticker):
return {"ticker": ticker, "revenue_musd": FILING["revenue_musd"],
"eps": FILING["eps"], "risk_factors": FILING["risk_factors"],
"citations": [FILING["doc_id"]]}
def earnings_call_transcript(ticker):
_clean = re.sub(r"[^a-z]", "", EARNINGS_CALL.lower()) # Patch 1
return {"ticker": ticker, "mgmt_sentiment": "positive",
"guidance": "raised" if "raise" in _clean else "maintained",
"citations": [FILING["doc_id"]]}
def fetch_market_data(ticker):
return {"ticker": ticker, "price": PRICE}
def verifier(answer, state):
recomputed = round(state["price"] / state["eps"], 2)
issues = []
if abs(recomputed - answer["pe_ratio"]) > 0.01:
issues.append("P/E mismatch")
if not answer.get("citations"):
issues.append("missing citations")
if "disclaimer" not in answer:
issues.append("missing disclaimer")
return {"verdict": "pass" if not issues else "fail", "issues": issues}
def run(query):
check = input_guardrails(query)
if not check["ok"]:
audit("blocked_input", check["reason"])
return {"status": "blocked", "reason": check["reason"]}
state = {}
state["filing"] = trace("tool.sec_filing_search", sec_filing_search, ticker="AAPL", tokens=80)
state["call"] = trace("tool.earnings_call_transcript", earnings_call_transcript, ticker="AAPL", tokens=60)
state["market"] = trace("tool.fetch_market_data", fetch_market_data, ticker="AAPL", tokens=10)
state["price"], state["eps"] = PRICE, FILING["eps"]
calc = trace("tool.calculator", calculator, expression="207.48 / 6.00", tokens=10)
answer = {"ticker": "AAPL", "pe_ratio": calc["result"],
"citations": [FILING["doc_id"]], "disclaimer": DISCLAIMER}
check = verifier(answer, state)
audit("verify", check)
if check["verdict"] != "pass":
return {"status": "escalated_to_human", "issues": check["issues"]}
tokens = sum(t["tokens"] for t in TRACES)
cost = round(tokens / 1000 * PRICE_PER_1K_TOKENS, 4)
audit("deliver", {"pe_ratio": answer["pe_ratio"]})
return {"status": "ok", **answer, "verdict": "pass",
"tokens": tokens, "cost_usd": cost}
def run_eval():
checks = []
r = run("Analyze AAPL filing + earnings call, compute P/E")
checks.append(("task success: status ok", r["status"] == "ok"))
checks.append(("task success: pe_ratio 34.58", r.get("pe_ratio") == 34.58))
checks.append(("groundedness: citations present", bool(r.get("citations"))))
checks.append(("groundedness: verifier passed", r.get("verdict") == "pass"))
checks.append(("groundedness: disclaimer present", "disclaimer" in r))
b = run("Give me a guaranteed return")
checks.append(("safety: blocked case returns blocked", b["status"] == "blocked"))
checks.append(("safety: audit log written", len(AUDIT) > 0))
passed = sum(1 for _, ok in checks if ok)
for name, ok in checks:
print(("PASS" if ok else "FAIL") + ":", name)
print(f"EVALUATION SUMMARY: {passed}/{len(checks)} checks passed")
if __name__ == "__main__":
print("Provider:", os.environ.get("LLM_PROVIDER", "mock"))
result = run("Analyze AAPL filing + earnings call, compute P/E")
print(json.dumps(result, indent=2))
run_eval()
print("Traces:")
for span in TRACES:
print(" ", json.dumps(span))
Rubric — 100 points
| Criterion | Points | What “excellent” looks like |
|---|---|---|
| Multi-agent design | 20 | 3 or more roles with clean contracts; justified separation |
| Harness Engineering | 20 | 2 or more guardrails, schema validation, audit log, HITL path |
| Loop Engineering | 15 | Bounded loop with observation and meaningful stop conditions |
| Tooling and permissions | 15 | 3 or more tools, least-privilege matrix, safe execution |
| Evaluation | 15 | 4 or more eval cases, including 1 adversarial or safety case; CI-gateable |
| Observability | 10 | Traces, cost accounting, verify-fail metrics |
| Documentation and demo | 5 | README plus a 3-minute run-through |
Deliverables
Your repo, a 2-page architecture memo, and an eval report. The memo should explain, in plain words, why you chose your roles, your guardrails, and your eval cases.
Capstone checklist
What to do next
Well done — you built a production-pattern multi-agent financial system, with a harness, a bounded loop, a verifier, evals, and observability.
- Keep your capstone code. Run python main.py and python eval.py until both checkpoints pass, then extend the system into your chosen domain.
- Add one new tool of your own, for example a tool that reads a second filing, and add it to the permission matrix for one role only.
- Next workshop in this repo: Financial agent workshop, in the Workshop folder. It takes this same system further: a real multi-agent financial agent with retrieval, production code, and a capstone starter. You already know the harness, loop, eval, and observability, so you can focus on the production code.
- After that, the repo also has the Hands-On ML Trading Strategy workshop, if you want to take the same ideas into trading.