Courses  /  Finance & Trading

Financial Agent Workshop

Build & Deploy Multi-Agent Financial AI Agents — with Harness Engineering, Loop Engineering, Evaluation & Observability.

34 lessons · Modules 0–9 · Labs 1–7 · Capstone · Production on bare Debian

Financial Agent Workshop — Build & Deploy Multi-Agent Financial AI Agents. 2–3 days, or self-paced 20–30 hours. Intermediate to advanced. Sample data is synthetic, for teaching only — never use it for real investment decisions.

Plain words first: a harness is the system around the model (tools, loops, checks, traces, rules). A loop is the repeat cycle: think, act, look at the result, repeat. HITL means a human approves important actions. RAG means fetch the evidence first, then answer from it. Groundedness means every number can be traced back to a source.
Start here

How to use this workshop

What it is

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

Why it matters

A workshop this big is easy to get lost in. The fixed shape and the tick boxes keep you moving one small step at a time.

Code — copy and run

# Nothing to install for this page. Just open index.html in your browser.
print('Welcome to the Financial Agent Workshop')

Try it yourself

Open this page, tick this lesson Done, and look at the sidebar to see the whole map.

Check

Do I need to pay for an API key to follow this course?

No. Every lesson runs offline with sample data and a small practice model. Real keys are optional, and the course says so where they would be used.

What will I have built by the end?

A multi-agent financial research system with a harness, tools, verification, tracing, evaluation, governance, and a production deployment plan.

Start here

Setup — Python, venv, and your first run

What it is

You need Python 3.11 or 3.12, Git, and about 8 GB of memory. Make a virtual environment, install the requirements, copy .env.example to .env, and run the first lab. In mock mode (WORKSHOP_MODE=mock) no API key is needed at all. In live mode you set OPENAI_API_KEY and WORKSHOP_MODE=live.

Why it matters

If the setup is wrong, every lab after it fails for a silly reason. Five minutes here saves hours later. Always run commands from the workshop root folder.

Code — copy and run

cd financial-agent-workshop
python -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
cp .env.example .env
python labs/lab01_harness_basics.py
# You should see a short successful run with a trace.

Try it yourself

Run the setup commands above (or, if you only have this page, run the Python check in the next lesson). Then run ./run_all_labs.sh to run all seven labs in order.

Check

What does WORKSHOP_MODE=mock do?

It tells the LLM client to use a small built-in practice model and sample data, so nothing calls the internet and nothing costs money.

I got ModuleNotFoundError. What is wrong?

Your virtual environment is probably not active. Activate it with source .venv/bin/activate, then run pip install -r requirements.txt again, and always run scripts from the workshop root.

Module 0 — Orientation & Setup

Orientation: what you are building and why it is different

What it is

You will build a production-style multi-agent system that reads SEC filings (10-K / 10-Q), earnings transcripts, and financial tables, uses tools for market data and calculations, and works inside a harness. It is measurable, explainable, and governed. This is not another prompt-engineering course. It is about systems that can be trusted with money questions.

Why it matters

A single clever prompt can answer one question well. It cannot be audited, it cannot be tested, and it will quietly invent a revenue number one day. In finance, an invented number is not a small mistake. It is operational risk.

Code — copy and run

# The whole workshop in one idea: Agent = Model + Harness
# The model reasons. The harness makes the reasoning reliable.
ACME = {'net_sales_2025': 4820, 'net_sales_2024': 4330, 'operating_income_2025': 912}
margin = ACME['operating_income_2025'] / ACME['net_sales_2025'] * 100
print(f"Acme 2025 operating margin: {margin:.1f}%")  # 18.9% — computed, not guessed
print('Rule: numbers come from tools and data, never from memory alone.')

Try it yourself

Write down, in one sentence, what your finished system must do that a chatbot cannot.

Check

What does 'production-style' mean here?

It means the system has tools, verification, traces, evaluation, cost tracking, and human approval gates — not just a chat box.

What data will we use?

Synthetic Acme Corp sample data: a 10-K excerpt, an earnings transcript, and a small QA set. It is for teaching only, never for real investment decisions.

Module 0 — Orientation & Setup

Learning philosophy: five rules that guide everything

What it is

Five rules run through the whole workshop. 1) Harness first: the model is necessary but not sufficient; reliability comes from the surrounding system. 2) Ratchet rule: every failure becomes a permanent structural improvement, like a guardrail or a verification step. 3) Evidence over fluency: cite sources, show calculations, support audit. 4) Measure everything: accuracy, faithfulness, latency, cost, tool success rate, human override rate. 5) Production mindset: security, PII, governance, and human approval are first-class, not afterthoughts.

Why it matters

These rules are the difference between a demo and a system. Whenever you are unsure what to build next, ask which rule applies.

Code — copy and run

# The Ratchet rule, as code: a failure becomes a permanent test.
BLOCKED = ['guaranteed return']
def guardrails(text):
    for phrase in BLOCKED:
        if phrase in text.lower():
            return {'ok': False, 'reason': f"blocked phrase: '{phrase}'"}
    return {'ok': True}
print(guardrails('Give me a guaranteed return tip'))  # blocked, forever, by design
print(guardrails('What was Acme net sales in 2025?'))   # ok

Try it yourself

Pick one rule and write down a failure you have seen (or can imagine) that it would prevent.

Check

What is the Ratchet rule in one sentence?

Every failure becomes a permanent structural fix, so that kind of failure cannot happen again.

Why 'evidence over fluency'?

A smooth, confident answer with a wrong number is worse than a short answer with a citation. In finance, the citation is the product.

Module 0 — Orientation & Setup

Tech stack and prerequisites

What it is

Orchestration: LangGraph first, with pure Python fallbacks so labs run anywhere. Models: OpenAI, Anthropic, or any OpenAI-compatible endpoint; Ollama is optional for local models. Retrieval: a simple vector store (Chroma or FAISS) plus keyword search. Tools: yfinance or a mock, a calculator, a document retriever, structured output. Observability: LangSmith-style tracing or local JSONL files. Language: Python 3.11+. Prerequisites: solid Python, basic LLM and RAG familiarity, and comfort reading financial statements helps but is not required — the course supplies the context.

Why it matters

A pragmatic stack matters because you will actually run it. Every part has a simple fallback, so a missing service never blocks a lesson.

Code — copy and run

# Check your Python version (you need 3.11 or newer).
import sys
print(sys.version)
print('OK' if sys.version_info >= (3, 11) else 'Please install Python 3.11+')
# The workshop requirements include: pydantic, langgraph, chromadb,
# faiss-cpu, yfinance, pandas, httpx, jsonlines, matplotlib.

Try it yourself

Check your Python version with the code above, and list which parts of the stack you have used before.

Check

Do I need a paid API key?

No. All labs run with mock and sample data. Real keys are optional and documented.

What if Chroma or FAISS will not install?

The labs fall back to simple in-memory keyword retrieval. You lose nothing important for learning.

Module 1 — From Prompts to Harnesses

The evolution: Prompt → Context → Harness

What it is

Prompt Engineering controls one call: the wording of the instruction and a few examples. Context Engineering controls one context window: what information enters the model at each step, through RAG, memory, and compression. Harness Engineering controls the full task lifetime: tools, state, control loops, verification, guardrails, observability, and governance. The harness is the agent runtime plus its policies and its eval suite.

Why it matters

Each layer fixes the failures of the one before it. A better prompt cannot stop a bad tool call. A better RAG pipeline cannot catch a wrong calculation. Only the harness can do both.

Code — copy and run

# Three layers, one question. Only the harness checks its own work.
QUESTION = 'What was Acme net sales in 2025?'
# Layer 1 — prompt only: the model answers from memory. No check.
# Layer 2 — context: the model answers with a retrieved passage. Still no check.
# Layer 3 — harness: retrieve, calculate, verify, cite, trace.
EVIDENCE = 'Net sales for 2025 were $4.82 billion (10-K Item 7).'
print('Answer:', EVIDENCE)
print('Citation: 10-K Item 7')
print('Verified: number appears in the evidence, not just in the answer.')

Try it yourself

For the question above, write what each layer would do differently.

Check

What is the difference between Context and Harness Engineering?

Context Engineering decides what goes into one model call. Harness Engineering runs the whole task: tools, loops, checks, traces, and rules.

What is the short formula for an agent?

Agent = Model + Harness. The model reasons. The harness turns reasoning into reliable, auditable action.

Module 1 — From Prompts to Harnesses

What a harness is: the seven-layer view

What it is

A harness is the non-model runtime that wraps an LLM so it can keep state across steps, call tools safely, recover from errors, verify results, enforce constraints, emit traces, and support human approval. The four classic pillars are Perception (what goes in), Reasoning (planning and tool choice), Acting (tool execution), and Learning (verification and ratcheting failures into rules). The seven-layer view is: Execution (the control loop), Tooling, Context and memory, Lifecycle and orchestration, Observability, Verification, and Governance.

Why it matters

When something goes wrong, this map tells you where to look. Is it the loop, a tool, the context, or a missing check? Each layer has its own fix.

Code — copy and run

# A tiny harness, in plain Python. This is the shape of src/harness/base.py.
import json, uuid
class Tracer:
    def __init__(self):
        self.events = []
    def emit(self, kind, **payload):
        self.events.append({'type': kind, **payload})
        print(f"[trace] {kind}: {payload}")
class Harness:
    def __init__(self):
        self.tools = {}
        self.tracer = Tracer()
    def register(self, name, fn):
        self.tools[name] = fn
    def run_tool(self, name, **args):
        self.tracer.emit('tool_call', tool=name, args=args)
        result = self.tools[name](**args)
        self.tracer.emit('tool_result', tool=name, result=result)
        return result
h = Harness()
h.register('calculator', lambda expression: eval(expression, {'__builtins__': {}}, {}))
print('P/E check:', h.run_tool('calculator', expression='100 / 3.41'))

Try it yourself

Add a second tool to the harness above, called get_net_sales, that returns 4820 for year 2025.

Check

Name the seven harness layers.

Execution, Tooling, Context and memory, Lifecycle and orchestration, Observability, Verification, Governance.

What are the four pillars?

Perception (input), Reasoning (planning), Acting (tools), Learning (verification and improvement).

Module 1 — From Prompts to Harnesses

Lab 1 — Harness basics: raw answer vs harnessed answer

What it is

Lab 1 (labs/lab01_harness_basics.py) makes the difference visible. First you ask a simulated raw model the question, with no tools and no verification. Then you run the same question through a tiny harness that registers tools, forces one tool call (get_financial_metric for net sales 2025), records a trace, and runs a verifier. The harnessed answer comes with a number, a citation, and a trace. The raw answer comes with confidence and nothing else.

Why it matters

Seeing the two side by side is the whole point of the lab. After this, you will never trust an unchecked answer again.

Code — copy and run

# Lab 1 in miniature: raw vs harnessed.
# Raw: a confident guess, no evidence.
print('RAW: Acme net sales were about $5 billion, I think.')
# Harnessed: tool + citation + verification.
METRICS = {('net_sales', '2025'): 4820, ('net_sales', '2024'): 4330}
def get_financial_metric(metric, year):
    return METRICS[(metric, year)]
value = get_financial_metric('net_sales', '2025')
answer = f"Acme Corp net sales in 2025 were ${value} million (source: 10-K)."
assert value == 4820, 'verifier: number does not match the data'
print('HARNESSED:', answer)
print('Verifier: passed — number matches the metric tool.')

Try it yourself

Change the metric to net sales 2024 and run the code. What answer and citation do you get?

Check

What does Lab 1 prove?

That the same question gets a checkable answer with a harness (tool + citation + trace + verifier) and an uncheckable guess without one.

Where do the traces go?

Into artifacts/ as JSONL files, one line per event, so you can read exactly what happened.

Module 2 — Single-Agent Financial Analyst

Tools: the analyst's hands

What it is

An agent's tools are the only way it touches the world. This workshop uses four: search_documents (keyword retrieval over the 10-K and the earnings transcript, returning a source and a snippet), get_financial_metric (structured numbers from the financials), fetch_market_data (prices, CSV-backed and auditable in mock mode), and calculator (safe arithmetic with an allow-list of characters, never eval on raw input). Each tool returns a ToolResult with success, output, and error fields, so failures are data, not crashes.

Why it matters

Tools are where numbers become trustworthy. A model doing arithmetic in its head will get it wrong. A calculator will not, and its work can be checked.

Code — copy and run

# The workshop tools, simplified. Note the calculator allow-list.
def calculator(expression):
    allowed = set('0123456789.+-*/()% eE')
    if not expression or any(c not in allowed for c in expression.replace(' ', '')):
        return {'success': False, 'error': 'disallowed characters'}
    try:
        return {'success': True, 'output': eval(expression, {'__builtins__': {}}, {})}
    except Exception as e:
        return {'success': False, 'error': str(e)}
print(calculator('912 / 4820 * 100'))   # operating margin, 18.9%
print(calculator("__import__('os')"))   # refused: letters are not allowed
print(calculator('4820 - 4330'))        # sales growth in $ millions

Try it yourself

Use the calculator to work out Acme's 2025 net income margin (net income 684 on sales 4820).

Check

Why must the calculator use an allow-list?

So a model can never smuggle in code. Only digits and arithmetic symbols are allowed through.

What does a ToolResult carry?

Success or failure, the output value, and an error message if it failed.

Module 2 — Single-Agent Financial Analyst

Retrieval: finding the right evidence

What it is

Retrieval is how the agent finds evidence before it speaks. In the workshop it starts simple: keyword search over the 10-K excerpt and the earnings transcript, scored by how often the question words appear, returning the most relevant sentences with their source. In production you would use embeddings and hybrid search (Chroma or FAISS), but the contract is the same: a question goes in, short cited passages come out, and the answer must stay inside them.

Why it matters

Good retrieval is what makes groundedness possible. If the agent cannot find the passage, it must say so, not invent one.

Code — copy and run

# Keyword retrieval, like src/tools/financial_tools.py search_documents.
import re
DOCS = [
    ('10-K', 'Net sales for 2025 were $4.82 billion, an increase of 11.4% from $4.33 billion in 2024.'),
    ('Earnings Call', 'Full-year free cash flow was $710 million.'),
]
def search_documents(query, top_k=3):
    terms = [t.lower() for t in re.findall(r'\w+', query) if len(t) > 2]
    scored = []
    for source, text in DOCS:
        score = sum(text.lower().count(t) for t in terms)
        if score > 0:
            scored.append({'source': source, 'score': score, 'snippet': text})
    scored.sort(key=lambda d: d['score'], reverse=True)
    return scored[:top_k]
print(search_documents('What was Acme free cash flow in 2025?'))

Try it yourself

Ask the retriever about 2025 net sales. Which document wins, and why?

Check

What is RAG in one sentence?

Retrieval-Augmented Generation: fetch the relevant passages first, then let the model answer using only those passages.

What should the agent do if retrieval finds nothing?

Say it found nothing and stop, or ask for a better question. Never invent a passage.

Module 2 — Single-Agent Financial Analyst

The ReAct loop: reason, act, observe, repeat

What it is

ReAct is the basic loop of a single agent. The model thinks (Reason), picks a tool (Act), reads the tool result (Observe), and repeats until it has enough evidence to answer. In the workshop the loop is bounded: a maximum number of steps, and a stop rule when the agent returns a final answer. The loop lives in the harness, not in the model, so it can be traced, limited, and tested.

Why it matters

A loop without a bound is a runaway bill. A loop without observation is just guessing in steps. ReAct gives you both structure and an escape hatch.

Code — copy and run

# A ReAct loop in miniature. The 'model' is a small rule-based stand-in.
# In the real labs, LLMClient.chat() plays this role (mock or live).
DATA = {'net_sales': 4820, 'operating_income': 912}
def fake_model(step, observations):
    if step == 0:
        return {'thought': 'I need the sales and income figures.', 'action': 'tool', 'tool': 'get_metric', 'args': {'metric': 'net_sales'}}
    if step == 1:
        return {'thought': 'Now I need operating income.', 'action': 'tool', 'tool': 'get_metric', 'args': {'metric': 'operating_income'}}
    return {'thought': 'I have both numbers.', 'action': 'final', 'answer': 'margin = 912 / 4820'}
observations = {}
for step in range(3):  # bounded loop: at most 3 steps
    out = fake_model(step, observations)
    print(f"Step {step}: {out['thought']}")
    if out['action'] == 'final':
        print('Final:', out['answer'], '=', round(912 / 4820 * 100, 1), '%')
        break
    observations[out['args']['metric']] = DATA[out['args']['metric']]
    print('  Observed:', observations)

Try it yourself

Add a third tool step to the loop that fetches free cash flow (710) before the final answer.

Check

What do the letters in ReAct stand for?

Reason, Act, Observe — repeated until the agent has enough evidence.

Why must the loop be bounded?

So a confused agent cannot loop forever and spend unlimited time and money.

Module 2 — Single-Agent Financial Analyst

Lab 2 — The single-agent analyst, end to end

What it is

Lab 2 (labs/lab02_single_agent_analyst.py) puts tools, retrieval, and the ReAct loop together into one analyst agent. It answers a financial question by searching documents, fetching metrics, calculating with the calculator tool, and returning a structured answer with citations. The lab also shows the common failure modes of financial RAG: a retrieved passage that does not actually answer the question, a number copied without checking, and a fluent answer with no citation.

Why it matters

This lab is the smallest complete agent in the workshop. Every later module adds a layer to this shape, never replaces it.

Code — copy and run

# Lab 2 in miniature: one analyst, tools, citations, and a check.
def search(q):
    return 'Net sales for 2025 were $4.82 billion (10-K Item 7).'
def calc(expr):
    return eval(expr, {'__builtins__': {}}, {})
question = 'What was Acme 2025 net sales growth?'
evidence = search(question)
growth = calc('(4820 - 4330) / 4330 * 100')
answer = f"Net sales grew {growth:.1f}% in 2025."
print('Question:', question)
print('Evidence:', evidence)
print('Answer:', answer)
print('Citations: 10-K Item 7')
assert abs(growth - 11.4) < 0.1, 'growth does not match the filing'
print('Verifier: growth matches the filing (11.4%).')

Try it yourself

Change the question to operating margin and rebuild the answer the same way: evidence, calculation, citation, check.

Check

What are the three failure modes Lab 2 shows?

Retrieved passages that do not answer the question, numbers copied without checking, and fluent answers with no citation.

What must every answer carry?

Evidence, a calculation done by a tool, and a citation the reader can check.

Module 3 — Multi-Agent Orchestration

Supervisor and specialist workers

What it is

One agent doing everything gets confused. Module 3 splits the work: a Supervisor classifies the question and routes it to specialist workers. The Fundamentals Worker handles metrics, ratios, and tables. The Narrative Worker handles MD&A and the earnings transcript. The Risk and Guidance Worker handles risk factors and management guidance. Each worker has its own tools, its own instructions, and its own output contract. The Supervisor then synthesizes their results into one answer.

Why it matters

Splitting the work is how real research desks work, and it makes each agent's job small enough to check. A worker that only reads tables cannot invent guidance.

Code — copy and run

# Supervisor + workers, in miniature.
def fundamentals_worker(q):
    return {'net_sales_2025': 4820, 'operating_income_2025': 912, 'source': '10-K Item 8'}
def narrative_worker(q):
    return {'summary': 'Growth driven by Automation Systems (+14%) and pricing (+2%).', 'source': '10-K Item 7'}
def risk_worker(q):
    return {'risks': ['semiconductor supply concentration', 'top 10 customers ~28% of revenue'], 'guidance': '2026 sales growth 6-9%, margin 19.0-19.5%', 'source': '10-K Risks + Outlook'}
def supervisor(question):
    parts = [fundamentals_worker(question), narrative_worker(question), risk_worker(question)]
    return {'question': question, 'parts': parts}
result = supervisor('What was Acme 2025 net sales and 2026 guidance?')
for p in result['parts']:
    print(p)

Try it yourself

Add a fourth worker, the Cash Worker, that returns free cash flow ($710M) and cash/debt ($1.12B / $1.45B).

Check

What are the three workers, and what does each own?

Fundamentals owns metrics and tables, Narrative owns MD&A and the transcript, Risk/Guidance owns risk factors and management guidance.

What does the Supervisor do?

It classifies the question, picks the right workers, and combines their results into one answer.

Module 3 — Multi-Agent Orchestration

Multi-agent patterns: when to split, and how

What it is

The slides outline four patterns. Supervisor–Worker: a router plus specialists, best for multi-domain financial tasks. Debate: two agents argue, then a judge decides, best when a claim is uncertain. Map-Reduce (fan-out): parallel sub-agents on different sources, then one synthesis, best for earnings plus filings plus market data at once. And the simple single agent, best when the question is small. Split when the task has clearly separate kinds of evidence, when one agent's context gets crowded, or when different parts need different tools.

Why it matters

Choosing the pattern is a design decision, not a fashion choice. Each pattern has a cost in latency and tokens, and a benefit in accuracy.

Code — copy and run

# Map-Reduce in miniature: fan out to three sources, then synthesize.
def fan_out(question):
    return [
        ('filings', 'Net sales $4.82B in 2025 (+11.4%).'),
        ('earnings', 'Free cash flow $710M; software attach 27% in Q4.'),
        ('market', 'Backlog $2.1B; Q4 revenue $1.31B.'),
    ]
results = fan_out('Summarize Acme 2025')
for source, finding in results:
    print(f'[{source}] {finding}')
print('SYNTHESIS: Acme grew 11.4% in 2025, generated $710M of free cash flow, and enters 2026 with a $2.1B backlog.')

Try it yourself

Pick a question from the QA set and decide: single agent, supervisor, debate, or map-reduce? Write one sentence of reasoning.

Check

When should you use Map-Reduce?

When you need several sources at once — for example filings, the earnings call, and market data — and can combine them afterwards.

When should you NOT split agents?

When the question is small. Splitting adds latency, cost, and places where things can go wrong.

Module 3 — Multi-Agent Orchestration

Lab 3 — The supervisor, running

What it is

Lab 3 (labs/lab03_multi_agent_supervisor.py) runs the Supervisor with the three workers on a real question, with a shared trace that has correlation IDs across the hops, so you can follow one question through every agent. You will see the Supervisor classify the intent, the workers call their tools, and the final answer assembled with citations from each worker.

Why it matters

The trace is the point. Without correlation IDs, a multi-agent run is a black box. With them, you can debug it like any other system.

Code — copy and run

# Lab 3 in miniature: one run id, shared across all workers.
import uuid
run_id = str(uuid.uuid4())[:8]
trace = []
def log(agent, event):
    trace.append({'run_id': run_id, 'agent': agent, 'event': event})
    print(f"[{run_id}] {agent}: {event}")
log('supervisor', 'classified question as fundamentals+narrative+guidance')
log('fundamentals', 'net_sales 2025 = 4820 (10-K Item 8)')
log('narrative', 'growth driven by Automation Systems +14%')
log('risk', 'guidance 2026: sales 6-9%, margin 19.0-19.5%')
log('supervisor', 'synthesized final answer with 3 citations')
print('Trace events:', len(trace), '| run_id:', run_id)

Try it yourself

Run the code and count the trace events. Which worker contributed the guidance numbers?

Check

What is a correlation ID?

One run id shared by every agent in a run, so all their trace lines can be grouped together.

Why does the Supervisor need a trace too?

Because routing decisions are decisions. If it picks the wrong workers, you need to see that choice in the log.

Module 4 — Loop Engineering & Planning

ReAct, in depth

What it is

ReAct (Reason → Act → Observe, repeat) is the workhorse loop for tool-heavy exploration. Each step the agent writes a short thought, picks one tool, and reads the result before deciding the next step. It is flexible, but it can wander, and it can repeat a failing tool call. That is why the harness bounds it, logs every step, and stops it when the answer is ready or the step budget is spent.

Why it matters

ReAct is the default loop in the workshop. Learn it first, and only reach for a fancier loop when ReAct shows a specific weakness.

Code — copy and run

# ReAct with a step budget and a stop rule.
MAX_STEPS = 5
observations = {'net_sales': 4820}
steps = [
    ('think', 'I have sales. I need operating income to get the margin.'),
    ('act', 'get_metric(operating_income) -> 912'),
    ('observe', 'operating income is 912'),
    ('think', 'I have both numbers. I can calculate now.'),
    ('final', 'margin = 912 / 4820 = 18.9%'),
]
for i, (kind, text) in enumerate(steps):
    if i >= MAX_STEPS:
        print('STOP: step budget spent'); break
    print(f'{kind}: {text}')

Try it yourself

Set MAX_STEPS to 2 in the code above. What is missing from the answer, and why is that failure visible?

Check

What are the three ReAct steps?

Reason, Act, Observe — repeated until the agent answers or the budget is spent.

What is ReAct best for?

Tool-heavy exploration, where the agent does not know in advance which tools it will need.

Module 4 — Loop Engineering & Planning

Plan-and-Execute and Reflexion

What it is

Plan-and-Execute makes a plan first, then executes it step by step. It is best for complex multi-step analysis, because the plan can be reviewed before any tool runs. Reflexion adds self-critique: generate an answer, critique it against the evidence, revise, and repeat. It is best for high-stakes numerical claims, where one wrong number matters. The cost is more steps and more tokens, so you use these loops where the stakes justify them.

Why it matters

The loop is a design choice with a price. Plan-and-Execute costs a planning step. Reflexion costs a critique step. Both pay for themselves on hard questions and waste money on easy ones.

Code — copy and run

# Plan-and-Execute, then Reflexion on the result.
plan = ['retrieve filings', 'extract financials', 'fetch market data', 'calculate ratios', 'verify and deliver']
print('PLAN:', plan)
# Execute (simplified): each step returns evidence.
print('Executed: filings retrieved, financials extracted, ratios calculated.')
# Reflexion: critique the draft, then revise.
draft = 'Operating margin was about 19%.'
critique = 'Draft says about 19% but the exact figure is 18.9% (912/4820). Cite Item 8.'
revised = 'Operating margin was 18.9% (912 / 4820), per 10-K Item 8.'
print('CRITIQUE:', critique)
print('REVISED:', revised)

Try it yourself

Write a 4-step plan for the question 'What was Acme free cash flow and what did it return to shareholders?'

Check

When is Plan-and-Execute better than ReAct?

For complex multi-step analysis, because the plan can be checked before any tool runs.

When is Reflexion worth the extra cost?

For high-stakes numerical claims, where a wrong number is expensive.

Module 4 — Loop Engineering & Planning

Choosing a loop, and the cost of loops

What it is

The slides give a simple rule: match the loop to the risk. ReAct for exploration, Plan-and-Execute for complex analysis, Reflexion for numbers that must be right, Supervisor–Worker for multi-domain work, Map-Reduce for parallel sources. Then check the trade-off: every extra loop step costs latency and tokens. In regulated workflows, the loop you can explain and audit beats the loop that is merely clever.

Why it matters

An engineer who can say why they chose a loop, and what it costs, is doing loop engineering. An engineer who just uses the default is not.

Code — copy and run

# Cost of a loop, in tokens and steps. Numbers are illustrative.
loops = {
    'ReAct': {'steps': 4, 'tokens': 3200},
    'Plan-Execute': {'steps': 6, 'tokens': 4800},
    'Reflexion (2 rounds)': {'steps': 9, 'tokens': 7200},
}
for name, v in loops.items():
    print(f"{name}: {v['steps']} steps, {v['tokens']} tokens")
print('Rule: use the cheapest loop that passes your evaluation gate.')

Try it yourself

For a simple fact question (one number, one citation), which loop would you pick, and why?

Check

What should you measure before choosing a loop?

Latency, tokens and cost per task, and whether it passes your evaluation gate.

Why does auditability matter for loop choice?

In a regulated workflow you must be able to explain and replay what the agent did.

Module 4 — Loop Engineering & Planning

Lab 4 — Loop engineering, hands on

What it is

Lab 4 (labs/lab04_loop_engineering.py) lets you run the same question through ReAct, Plan-and-Execute, and Reflexion, and compare the traces. You will see where each loop spends its steps, where each one fails, and how a bounded loop fails visibly instead of silently. The lab's key experiment is to shrink the step budget and watch which evidence goes missing first.

Why it matters

Comparing loops on the same question is the fastest way to learn when each one is right.

Code — copy and run

# Lab 4 in miniature: shrink the budget, watch the failure.
def run_loop(max_steps):
    steps_needed = ['retrieve filings', 'extract financials', 'calculate margin', 'verify']
    done = steps_needed[:max_steps]
    missing = steps_needed[max_steps:]
    print(f'Budget {max_steps}: done {done}')
    if missing:
        print(f'  MISSING: {missing} — the answer will be incomplete, and the trace shows why.')
    else:
        print('  Complete: margin =', round(912 / 4820 * 100, 1), '%')
run_loop(4)
run_loop(2)

Try it yourself

Run the code with a budget of 1. What is the agent missing, and what would a user see?

Check

What does 'bounded loops fail visibly' mean?

When the budget runs out, the trace shows exactly which steps never happened, instead of a confident answer with a hole in it.

Which loop would you pick for a 10-K analysis with five sub-questions?

Plan-and-Execute or Supervisor–Worker, because the work can be planned and split before execution.

Module 5 — Multimodal & Document Intelligence

Tables: numbers that live in rows and columns

What it is

Financial documents hide their most important numbers in tables: the income statement, the balance sheet, the segment breakdown. Lab 5 teaches structured extraction: find the table, read its rows and columns, and turn each cell into a named fact with a citation to the table. A model that reads a table as plain text will mix up years and columns. A structured extractor will not.

Why it matters

Tables are where 'the model read the document' usually breaks. Treat them as data, not as prose.

Code — copy and run

# A table as structured data, not as text.
# From 10-K Item 8 (in $ millions):
TABLE = [
    {'item': 'Net sales', '2025': 4820, '2024': 4330, '2023': 3980},
    {'item': 'Operating income', '2025': 912, '2024': 761, '2023': 650},
    {'item': 'Net income', '2025': 684, '2024': 562, '2023': 478},
]
for row in TABLE:
    print(row['item'], '| 2025:', row['2025'], '| 2024:', row['2024'])
print('Check: 2025 operating margin =', round(912 / 4820 * 100, 1), '%')
print('Citation: 10-K Item 8, Consolidated Statements of Operations.')

Try it yourself

Add a row for diluted EPS (2025: 3.41, 2024: 2.78) and print the table again.

Check

Why must tables be extracted as structured data?

So years and columns cannot be mixed up, and each number keeps its citation to the exact table.

What is a 'structured extraction'?

Turning a table into named facts (item, year, value, source) instead of a blob of text.

Module 5 — Multimodal & Document Intelligence

Charts, images, and earnings audio

What it is

Not all evidence is text. Charts carry trends, dashboards carry KPIs, and earnings calls carry tone and guidance in spoken words. Lab 5 covers all three, with honest stubs where a full system would need more: chart and image extraction returns the chart's data table and a description, and the earnings-audio step works from the transcript, extracting management guidance, risks, and sentiment by keyword and by who said it. The workshop is explicit about this: the audio step is a stub, not a real speech-to-text pipeline, and the lab says so.

Why it matters

Multimodal means more than one kind of input. The discipline is the same as for text: every extracted fact needs a source and a place in the trace.

Code — copy and run

# Earnings-audio stub: extract guidance and sentiment from the transcript.
TRANSCRIPT = [
    ('CEO', 'We delivered 11.4% revenue growth and expanded operating margin by 130 basis points.'),
    ('CFO', 'Full-year free cash flow was $710 million.'),
    ('CFO', 'Guidance for 2026: revenue growth of 6 to 9 percent. Operating margin 19.0 to 19.5 percent.'),
]
def extract_guidance(lines):
    out = []
    for speaker, text in lines:
        if 'guidance' in text.lower() or 'growth' in text.lower():
            out.append({'speaker': speaker, 'text': text, 'source': 'Q4 2025 Earnings Call'})
    return out
for g in extract_guidance(TRANSCRIPT):
    print(g)
print('Note: this is a transcript stub. A real audio step would transcribe speech first.')

Try it yourself

Add a line from the CEO about software attach (27% in Q4) and extract it the same way.

Check

What does the audio step actually do in this workshop?

It works from the transcript text as a stub, extracting guidance, risks, and sentiment. It is labelled as a stub, not a real speech pipeline.

What must a chart extraction return?

The chart's underlying data and a description, with a source — never just 'the chart looks good'.

Module 5 — Multimodal & Document Intelligence

Lab 5 — Structured extraction, end to end

What it is

Lab 5 (labs/lab05_multimodal_docs.py) runs structured extraction over the sample 10-K and transcript and writes the result to artifacts/lab05_structured.json. You will see tables become facts, the transcript become guidance and sentiment, and every fact carry its source. The lab's output file is the input to the evaluation lab: if extraction is wrong here, evaluation will catch it there.

Why it matters

This is where the workshop stops treating documents as text and starts treating them as evidence.

Code — copy and run

# Lab 5 in miniature: extract, structure, save as JSON.
import json
facts = [
    {'fact': 'net_sales_2025', 'value': 4820, 'unit': '$M', 'source': '10-K Item 8'},
    {'fact': 'operating_margin_2025', 'value': 18.9, 'unit': '%', 'source': 'calculated 912/4820'},
    {'fact': 'free_cash_flow_2025', 'value': 710, 'unit': '$M', 'source': 'Q4 2025 Earnings Call (CFO)'},
    {'fact': 'guidance_2026_margin', 'value': '19.0-19.5%', 'unit': '%', 'source': 'Earnings Call guidance'},
]
print(json.dumps(facts, indent=2))
print('Saved shape: artifacts/lab05_structured.json — one fact per line, each with a source.')

Try it yourself

Add a fact for year-end cash ($1.12B) and total debt ($1.45B) with their source (10-K Liquidity).

Check

What does Lab 5 write to disk?

artifacts/lab05_structured.json — the extracted facts, each with a value and a source.

Why does extraction quality matter for evaluation?

Because the evaluation lab checks answers against these facts. Bad extraction means bad scores, and that is the system working.

Module 6 — Evaluation Harness

Evaluation beyond accuracy

What it is

Accuracy alone is not enough. A financial agent must be measured on faithfulness (does the answer stay inside the retrieved evidence?), citation quality (are the sources real and correctly attributed?), tool success rate, numerical correctness (exact match or a tolerance on figures), latency and cost per task, human override and escalation rate, and consistency across repeated runs. Lab 6 builds a lightweight evaluation harness that scores all of these against the gold QA set in data/qa_pairs.json.

Why it matters

If you cannot measure it, you cannot improve it, and you certainly cannot deploy it. Evaluation is the deployment gate.

Code — copy and run

# The gold QA set, and what 'correct' means for each question.
GOLD = [
    {'id': 'q1', 'question': "Acme net sales 2025?", 'answer': '$4.82 billion, +11.4%', 'source': '10-K Item 7'},
    {'id': 'q2', 'question': '2026 operating margin guidance?', 'answer': '19.0-19.5%', 'source': 'Earnings Call guidance'},
    {'id': 'q6', 'question': 'Calculate 2025 operating margin.', 'answer': '18.9% (912 / 4820)', 'source': 'calculated'},
]
for q in GOLD:
    print(q['id'], '|', q['question'], '->', q['answer'])
print('An answer scores only if the number matches AND the citation is real.')

Try it yourself

Write one more gold question from the sample data (for example, free cash flow) with its answer and source.

Check

Name four metrics beyond accuracy.

Faithfulness, citation quality, numerical correctness, and tool success rate — plus latency, cost, override rate, and consistency.

What is a gold QA set?

A small set of questions with known-correct answers and sources, used to score the agent the same way every time.

Module 6 — Evaluation Harness

LLM-as-judge and rubric scoring

What it is

One way to score answers at scale is to use a second model as a judge, with a written rubric: does the answer cite its sources, does every number appear in the evidence, is the calculation shown? The rubric is the contract. The judge is only as good as the rubric, so the rubric must be specific, and the judge's scores must themselves be spot-checked against humans. The workshop also keeps deterministic checks alongside the judge: exact number match, citation presence, and calculation recomputation never need a model at all.

Why it matters

A judge without a rubric is just a second opinion. A rubric without deterministic checks is just a hope.

Code — copy and run

# Rubric scoring, without needing a second model.
def score_answer(answer, evidence_numbers, citations):
    score = {}
    score['has_citation'] = len(citations) > 0
    score['numbers_in_evidence'] = all(str(n) in evidence_numbers for n in [4820, 11.4])
    score['shows_calculation'] = '/' in answer or 'calc' in answer.lower()
    score['total'] = sum(score.values())
    return score
print(score_answer('Net sales $4.82B (+11.4%), 4820/4330 calc, see 10-K Item 7',
                    '4820 11.4 4330', ['10-K Item 7']))
print(score_answer('Net sales were about $5B.', '', []))

Try it yourself

Score this answer with the rubric above: 'Operating margin 18.9% (912/4820), 10-K Item 8.' What does it score?

Check

What is LLM-as-judge?

Using a second model, guided by a written rubric, to score answers at scale.

What should never be left to the judge alone?

Exact numbers and citations. Those can be checked deterministically, and they should be.

Module 6 — Evaluation Harness

Lab 6 — Run the evaluation suite

What it is

Lab 6 (labs/lab06_evaluation_harness.py) runs the full evaluation suite and writes artifacts/lab06_eval_report.json. It runs the agent over the gold QA set, scores each answer on faithfulness, citation, numerical correctness, and cost, and prints a summary. The report is your regression gate: if a change makes the score drop, the change does not ship. The lab also suggests a stretch goal: add an adversarial case, for example a wrong EPS, and check that the verifier catches it.

Why it matters

A score that never moves is not a measurement. Run the suite, change something, run it again, and watch it move.

Code — copy and run

# Lab 6 in miniature: score three answers, print a report.
CASES = [
    {'id': 'q1', 'expected': '4.82', 'got': '4.82', 'cited': True},
    {'id': 'q2', 'expected': '19.0', 'got': '19.0', 'cited': True},
    {'id': 'q6', 'expected': '18.9', 'got': '18.9', 'cited': True},
]
passed = sum(1 for c in CASES if c['expected'] == c['got'] and c['cited'])
print(f"EVALUATION SUMMARY: {passed}/{len(CASES)} checks passed ({passed/len(CASES)*100:.0f}%)")
print('Report shape: artifacts/lab06_eval_report.json — one entry per case, with scores.')
print('Gate rule: if the score drops, the change does not ship.')

Try it yourself

Change one 'got' value to a wrong number and re-run. What does the summary say now?

Check

What is a regression gate?

A rule that blocks a change if the evaluation score drops below a threshold.

Why include an adversarial case?

To prove the verifier catches wrong numbers, not just that it passes right ones.

Module 7 — Observability, Cost & Governance

Tracing and observability

What it is

Every production agent needs structured traces: the input, the plan, every tool call and result, the final answer, and metadata, all linked by a run id across multi-agent hops. It needs cost and token accounting, an error taxonomy (model, tool, policy, verification failure), and logs that can be exported for audit. In this workshop you build a local JSONL tracer (src/harness/base.py Tracer, artifacts/traces.jsonl) that can later be swapped for LangSmith, Phoenix, or custom APM. A trace is not a log file you read when things break. It is the system's memory.

Why it matters

If you cannot replay what the agent did, you cannot debug it, audit it, or defend it. Traces are the replay button.

Code — copy and run

# A JSONL tracer, like src/harness/base.py Tracer.
import json, uuid
from datetime import datetime, timezone
run_id = str(uuid.uuid4())[:8]
events = []
def emit(kind, **payload):
    events.append({'run_id': run_id, 'type': kind, 'time': datetime.now(timezone.utc).isoformat(), **payload})
emit('run_start', query='Acme 2025 net sales?')
emit('tool_call', tool='get_financial_metric', metric='net_sales', year=2025)
emit('tool_result', tool='get_financial_metric', value=4820)
emit('run_end', status='completed', answer='Net sales $4.82B (10-K Item 7)')
for e in events:
    print(json.dumps(e))
print('One line per event, one run id for the whole run.')

Try it yourself

Add an event for a verification step (verifier passed, margin recomputed) to the trace above.

Check

What is a trace?

A structured, ordered record of everything the agent did in one run: inputs, plans, tool calls, results, and the final answer.

What is a correlation ID?

One run id shared across every agent hop, so a multi-agent run can be followed as a single story.

Module 7 — Observability, Cost & Governance

Cost, latency, and reliability

What it is

Measure three things on every run: cost (tokens times price, plus infrastructure), latency (per component, so you can find the bottleneck), and reliability (verify-fail rate, tool error rate, escalation rate). The workshop's observability module rolls these up per component from the traces. Cost is a product decision, not just an engineering metric: a premium multi-agent answer costs more than a cheap factual lookup, and the system should know which one the client is paying for.

Why it matters

An agent that is accurate but unaffordable is a failed product. Cost tracking is how you find out before the bill does.

Code — copy and run

# Cost and latency, per component. Prices are illustrative.
PRICE_PER_1K_TOKENS = 0.01  # dollars, example only
components = [
    {'name': 'llm.research', 'calls': 3, 'tokens': 160, 'latency_ms': 12},
    {'name': 'tool.sec_filing_search', 'calls': 1, 'tokens': 0, 'latency_ms': 47},
    {'name': 'llm.verifier', 'calls': 1, 'tokens': 90, 'latency_ms': 9},
]
total_tokens = sum(c['tokens'] for c in components)
total_ms = sum(c['latency_ms'] for c in components)
print(f"Total tokens: {total_tokens} | cost: ${total_tokens/1000*PRICE_PER_1K_TOKENS:.4f} | latency: {total_ms} ms")
print('Slowest component: tool.sec_filing_search (47 ms) — start there if you need speed.')

Try it yourself

Add a fourth component (llm.analyst, 120 tokens, 15 ms) and recompute the totals.

Check

What three things should you track on every run?

Cost, latency, and reliability (verify-fail rate, tool errors, escalations).

Why track cost per component?

So you can see which part of the system is expensive and decide whether it is worth it.

Module 7 — Observability, Cost & Governance

Governance, guardrails, and human-in-the-loop

What it is

Governance is the set of rules that keep the agent safe. The starter checklist: never put secrets in prompts; use tool allow-lists and argument validation; enforce output schemas (Pydantic or JSON schema); redact PII before logging; require human approval for high-impact actions; version prompts, tools, and policies; and document model risk (intended use, limitations, monitoring). Human-in-the-loop (HITL) means a person approves material claims before they go out — deterministic escalation, never a silent pass.

Why it matters

Governance is not paperwork you add at the end. It is the difference between a system a bank can use and a demo a bank cannot.

Code — copy and run

# Governance gates, in plain Python.
BLOCKED = ['guaranteed return', 'wire transfer instructions', 'insider tip']
ALLOWED_TOOLS = {'research': ['search_documents', 'get_financial_metric'],
                 'analyst': ['calculator', 'fetch_market_data']}
def governance_check(role, tool, text):
    for phrase in BLOCKED:
        if phrase in text.lower():
            return {'ok': False, 'action': 'blocked', 'reason': f"prohibited phrase '{phrase}'"}
    if tool not in ALLOWED_TOOLS.get(role, []):
        return {'ok': False, 'action': 'blocked', 'reason': f"tool '{tool}' not allowed for role '{role}'"}
    return {'ok': True, 'action': 'allow'}
print(governance_check('research', 'calculator', 'What was Acme net sales?'))
print(governance_check('research', 'search_documents', 'Give me a guaranteed return tip'))
print(governance_check('analyst', 'calculator', 'Compute the margin.'))

Try it yourself

Add 'insider tip' to the blocked list test: run governance_check('analyst', 'calculator', 'Give me an insider tip') and read the result.

Check

What does HITL stand for, and what does it mean?

Human-in-the-loop: a person approves high-impact actions before they happen, instead of the system silently passing.

Name three governance controls.

Tool allow-lists, output schema enforcement, and PII redaction before logging — plus blocked phrases and human approval gates.

Module 7 — Observability, Cost & Governance

Lab 7 — Observability and governance, hands on

What it is

Lab 7 (labs/lab07_observability_governance.py) runs the full system with tracing, cost accounting, and governance gates switched on, and writes artifacts/lab07_traces.jsonl. You will trigger a blocked request, watch the guardrail fire, see the event in the trace, and confirm that a verification failure escalates to a human instead of passing silently. The lab's policy demo is the moment the workshop stops being theory: the rules you wrote actually stop the agent.

Why it matters

A guardrail you have never seen fire is a guardrail you have not tested. Trigger it on purpose, in the lab, before a user triggers it by accident.

Code — copy and run

# Lab 7 in miniature: a blocked request, traced and escalated.
import json
trace = []
def emit(kind, **p):
    trace.append({'type': kind, **p})
    print(json.dumps({'type': kind, **p}))
request = 'Give me a guaranteed return insider tip'
emit('run_start', query=request)
if 'guaranteed return' in request.lower():
    emit('governance', action='blocked', reason="prohibited phrase 'guaranteed return'")
    emit('run_end', status='blocked')
    print('Result: blocked. No answer was produced, and the trace proves it.')
else:
    emit('run_end', status='completed')

Try it yourself

Change the request to 'What was Acme 2025 net sales?' and predict which events the trace will show.

Check

What should happen when a verification fails?

The run escalates to a human. It never silently passes.

Where does Lab 7 write its traces?

artifacts/lab07_traces.jsonl — one JSON line per event.

Module 8 — Capstone

Capstone: your production-style financial agent

What it is

Design and implement an end-to-end multi-agent financial research system that answers complex questions about a company using the sample 10-K, the earnings transcript, structured metrics, and an optional market-data tool. Your system must show harness engineering: explicit tools with validation, a clear control loop (ReAct, Plan-Execute, or Supervisor), a verification stage, structured tracing, evaluation against the gold QA set plus at least 3 new questions you invent, and at least one governance control (tool allow-list, schema validation, or a HITL gate). Deliverables: code, an architecture diagram, an eval report (JSON plus a short markdown summary), trace samples for at least two successful runs and one failure you triggered and fixed (the ratchet), and a 1–2 page write-up covering design choices, failure modes and fixes, cost and latency notes, and what you would change for a real regulated deployment. Rubric: Correctness and groundedness 25%, Harness quality 25%, Observability and eval 15%, Governance 10%, Code clarity 10%, Write-up 15%. Stretch goals: a chart or table vision step, multi-company comparison, streaming progress, a Model Card, or a CI job that fails if the average eval score drops below a threshold.

Why it matters

The capstone is your portfolio piece. Treat it like one: a system a hiring manager or a client can run, read, and trust.

Code — copy and run

# Capstone skeleton: supervisor -> workers -> verifier -> governance -> answer.
# (Full version: capstone/starter/agent.py in the repo.)
GOLD = {'net_sales_2025': 4820, 'margin_2025': 18.9, 'fcf_2025': 710}
def fundamentals(q):
    return {'net_sales': GOLD['net_sales_2025'], 'source': '10-K Item 8'}
def narrative(q):
    return {'summary': 'Growth driven by Automation Systems (+14%).', 'source': '10-K Item 7'}
def risk(q):
    return {'guidance': '2026 sales 6-9%, margin 19.0-19.5%', 'source': 'Earnings Call'}
def verifier(answer, evidence):
    ok = '4820' in str(evidence) and '10-K' in str(evidence)
    return {'verdict': 'pass' if ok else 'escalate_to_human', 'issues': [] if ok else ['missing citation']}
parts = [fundamentals('q'), narrative('q'), risk('q')]
answer = 'Acme net sales 2025: $4.82B (+11.4%); 2026 guidance: sales 6-9%, margin 19.0-19.5%.'
print(verifier(answer, parts))
print('Answer:', answer)
print('Citations: 10-K Item 7, Item 8, Earnings Call guidance.')

Try it yourself

Write your capstone plan in five lines: question, workers, loop, verifier, governance control.

Check

What are the six capstone deliverables?

Code, architecture diagram, eval report, trace samples (2 successes + 1 fixed failure), and a 1–2 page write-up.

How much is correctness worth in the rubric?

25% — the same as harness quality. Both matter equally.

Module 9 — Production (bare Debian)

The production API: FastAPI, auth, tiers, and cost gates

What it is

Production turns the workshop agent into a billable service on a bare Debian server — no Docker, no Kubernetes. A FastAPI app serves a research endpoint with API-key auth, request tiers (cheap factual metrics vs premium multi-agent synthesis), a cost gate that refuses or queues requests over budget, a cache so identical queries within a TTL return cached evidence, and a HITL queue for material claims. State lives in SQLite (or PostgreSQL), every request is written to a JSONL ledger with tokens, latency, tool calls, and estimated cost, and the whole thing runs under systemd behind nginx.

Why it matters

The workshop agent answers questions. The production system answers questions, charges for them, and proves what it did. That is the whole difference.

Code — copy and run

# The production API shape (production/api/app.py), simplified to run anywhere.
# Real version: FastAPI + uvicorn. This is the same logic, plain Python.
COST_PER_1K = 0.01
DAILY_CAP_USD = 50.0
spent_today = 12.40
def cost_gate(estimated_tokens, tier):
    est_cost = estimated_tokens / 1000 * COST_PER_1K
    if spent_today + est_cost > DAILY_CAP_USD:
        return {'allowed': False, 'reason': 'daily cost cap reached'}
    return {'allowed': True, 'estimated_cost_usd': round(est_cost, 4), 'tier': tier}
print(cost_gate(2500, 'premium'))
print(cost_gate(5000000, 'premium'))  # over budget: refused, not run
print('Tiers: factual metrics are cheap, full multi-agent synthesis is premium.')

Try it yourself

Work out the estimated cost of a 4,000-token premium request at $0.01 per 1K tokens.

Check

What does the cost gate do?

It refuses or queues a request when its estimated cost would break the budget or the daily cap.

Why have tiers?

So a cheap factual lookup does not pay the price of a full multi-agent synthesis.

Module 9 — Production (bare Debian)

Deploying on bare Debian: systemd, nginx, and runbooks

What it is

On a clean Debian 12+ machine: copy the workshop to /opt, run production/scripts/install_debian.sh (it creates the user, the venv, the systemd unit, and the directories), put secrets in /etc/financial-agent/env, enable and start the service with systemctl enable --now financial-agent-api, then optionally run setup_nginx.sh for TLS and a reverse proxy with rate limiting. Health check: curl http://127.0.0.1:8080/health, then POST a research question to /v1/research with your X-API-Key header. The systemd unit has restart, resource limits, and security hardening directives. Runbooks cover deploy, incident, key rotation, and capacity.

Why it matters

Bare metal plus systemd means predictable cost and no cluster tax. The trade-off is that you own the operations: backups, hardening, and runbooks are yours.

Code — copy and run

[Unit]
Description=Financial Agent API
After=network.target

[Service]
User=financial-agent
WorkingDirectory=/opt/financial-agent-workshop
ExecStart=/opt/financial-agent-workshop/.venv/bin/uvicorn production.api.app:app --host 127.0.0.1 --port 8080
Restart=always
NoNewPrivileges=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target

Try it yourself

Read the unit file above line by line and say what each section does: Unit, Service, Install.

Check

What does install_debian.sh create?

The service user, the virtual environment, the systemd unit, and the data directories.

Why is the API bound to 127.0.0.1?

So it is only reachable through nginx, which adds TLS, rate limiting, and auth at the edge.

Module 9 — Production (bare Debian)

nginx, security hardening, and the money side

What it is

nginx sits in front of the API: TLS termination, rate limiting, and optional basic auth or mTLS. Security hardening (production/security/HARDENING.md) covers secrets only in environment files, PII redaction before logging, and the append-only audit trail. The money side is explicit: the API is billable per research job or seat, one senior analyst plus agents gives roughly 3–5x throughput on filings and calls, compliance automation cuts manual evidence gathering, and the audit trail lets you sell regulated-grade answers at a premium tier. The illustrative ROI target is payback in under 90 days if the system displaces half to one full-time junior researcher. Daily backup and cost-report scripts (production/scripts/backup.sh, cost_report.py) keep the ledger honest.

Why it matters

A production system that cannot show its costs and its audit trail cannot charge for its answers. The ledger is part of the product.

Code — copy and run

# Local smoke test (no root needed) — from the workshop README:
./production/scripts/run_local_api.sh
# In another terminal:
curl -s http://127.0.0.1:8080/health
curl -s -H "X-API-Key: dev-local-key" -H "Content-Type: application/json" \
  -d '{"query":"What was Acme 2025 net sales and 2026 guidance?","tier":"premium"}' \
  http://127.0.0.1:8080/v1/research

Try it yourself

Run the health check above (or read it aloud) and say what a healthy answer looks like.

Check

What does nginx add in front of the API?

TLS, rate limiting, and optional auth — the API itself never faces the internet directly.

What is the illustrative ROI target?

Payback in under 90 days if the system displaces 0.5–1 full-time junior researcher.

Module 9 — Production (bare Debian)

What to do next

What it is

You now have the full path: a harnessed single agent, a supervisor with workers, engineered loops, multimodal extraction, evaluation, observability, governance, a capstone, and a production deployment. Next, deepen the two places the workshop only touches: read the Harness Engineering workshop in this repo for the full harness and loop theory with its own financial system, then the Agent Workflows as Graphs workshop for retrieval over knowledge graphs. Then take your capstone to a real deployment: run it on your Debian box, watch the traces and the cost report for a week, and let the Ratchet rule do its work — every failure becomes a permanent fix.

Why it matters

The workshop ends. The system does not. The next step is to run it, measure it, and fix what breaks.

Code — copy and run

# Your next-week checklist, as code you can tick off.
checklist = [
    'Run all 7 labs and the capstone starter',
    'Run the eval suite and record the score',
    'Trigger one blocked request and read the trace',
    'Run the local API smoke test',
    'Write the 1-2 page capstone write-up',
]
for i, item in enumerate(checklist, 1):
    print(f'{i}. [ ] {item}')

Try it yourself

Pick the first item on the checklist and do it today.

Check

What are the two workshops to read next?

Harness Engineering, then Agent Workflows as Graphs.

What is the Ratchet rule, one more time?

Every failure becomes a permanent structural fix.

Try the financial agent here

Type a question about Acme Corp. The demo shows the Supervisor, the three workers, the Verifier, and the Governance gate — with citations. Try a blocked request too, for example “Give me a guaranteed return tip”.


Press “Run the agent” to see the Supervisor, workers, Verifier, and Governance steps.