Future with Shivank · AI Agents in Finance · Sections 7–9

Future with Shivank · Hands-on track · Sections 7–9

Teams of Agents Design multi-agent systems, run an AI investment committee, and process an insurance claim a regulator would sign off

One agent is like one talented analyst. Real finance work is done by teams: people with different roles, rules about who decides, and a paper trail. These three sections teach you how to design such a team of agents — and, just as important, when not to — and then you build two of them in code.

🏦 One week at Future with Shivank Bank, three teams. The research desk needs health checks on five portfolio companies before lunch (Section 7). The trading floor wants an AI investment committee whose BUY calls can be challenged and tested on past data (Section 8). And at 2:47 AM, a customer of the bank's insurance arm rear-ends a delivery truck on the I-95 — her claim has to be handled fast, fairly and with a full audit trail (Section 9).
7architecture styles, each with a finance example
11complete lab files on this page — 5 run free (no API key)
12simulations to click through
15interview questions with model answers
Section 7 labFinancial health analyzer4 agents in a pipeline, one shared whiteboard, handoffs with reasons — then 5 companies in parallel.
Section 8 labsAI investment committee4 analysts in parallel → portfolio manager → risk officer, a walk-forward backtest, and a bull-vs-bear debate.
Section 9 labsInsurance claims team7 agents with least-privilege access, a compliance veto, a fraud debate and invariant tests.
🧠 Analogy💰 Finance corner⚠️ Watch out💡 Tip🎯 Interview angle🧪 Simulation (click it!)

Section 7 · Part 1 — Is a team worth it?

Designing a team of agents

7.1One agent or a team? The answer with numbers

You already know the intuition: specialists working together can beat one generalist. In an interview, intuition isn't enough — the follow-up is always "how do you know a team is worth the extra cost?" This part gives you the evidence, a simple test, and a rule you can state in one sentence.

🧠 Analogy — a solo adviser vs a deal team

A solo financial adviser is fast and never miscommunicates with herself. A bank's M&A deal team — lawyers, analysts, credit, compliance — is slower to coordinate, but it can handle a $2 billion acquisition no single person could. Hiring the whole deal team to approve a $20,000 car loan would be absurd. Multi-agent systems are the deal team: worth it for big, splittable work, wasteful for small, tightly connected work.

The four walls a single agent runs into

🧱 Context overflowTen annual reports, price history and news don't fit in one context window — and quality drops long before the hard limit.Finance: a 20-stock portfolio review.
🧱 Conflicting objectivesOne prompt asked to find returns and to police risk will quietly favour one of them.Finance: a trader marking their own homework.
🧱 LatencyEight tool calls of four seconds each, one after another, is half a minute before the first word.Finance: a pre-market brief due at 8:00.
🧱 Specialization depthA prompt stuffed with tax, credit, FX and compliance rules becomes a generalist that is shallow in all of them.Finance: every desk's rulebook in one prompt.

What the evidence says — both sides

FindingWhat happenedWhat it really tells you
+90.2%Anthropic's multi-agent research system (a lead agent plus parallel sub-agents) beat a single agent on its internal research evaluation.Mostly explained by more total tokens spent in parallel, and strongest on breadth-first questions that split into independent directions.
+8% / +35%Microsoft's AutoGen research: multi-agent designs raised F1 for spotting unsafe code (GPT-4 / GPT-3.5).Weaker models gain more from a second pair of eyes.
↓ qualityLangChain benchmarks: a single agent's tool-use accuracy falls steeply as unrelated "distractor" domains are added to its context.Splitting domains removes interference — the specialization wall in numbers.
14 ways to failThe MAST study catalogued 14 recurring multi-agent failure modes across 7 frameworks and 1,600+ traces; gains on popular benchmarks were often minimal.Teams fail in new ways: bad specs, agents misaligned with each other, nobody verifying the result.
~15×Token use: a single agent spends roughly 4× the tokens of a chat; a multi-agent system roughly 15×.Every extra agent must buy its way in.
Coupled → 1Cognition (makers of the Devin coding agent): for tightly coupled work, use one agent with well-engineered context.Parallel sub-agents that can't see each other's decisions make conflicting ones.

The coupling test

So when does splitting help? Look at how the pieces of work depend on each other. Organisation theory has a neat three-way split for this, and it maps straight onto agent design:

① Pooled ② Sequential ③ Reciprocal AAPL MSFT NVDA merge table pieces never talk to each other fetch score report each step needs the one before pricing risk model every change bounces back and forth ✓ parallel agents shine ✓ a pipeline fits ✗ keep it in ONE agent
A quick proxy borrowed from parallel computing: if your agents would spend more tokens talking to each other (passing and reconciling intermediate results) than doing new work, merge them back into one agent.
🎯 Interview angle — "When would you add agent number N+1?"

Only when all three are true:

  1. It owns a separable piece of work (pooled or sequential, never reciprocal).
  2. It carries a domain prompt that would otherwise dilute the existing agents.
  3. Its extra token cost buys a measured gain in quality or speed.

Then add the counter-point that shows maturity: "For tightly coupled work like one codebase, I'd start with a single strong agent with good tools and context — teams win on breadth-first work like research across many companies."

7.2Seven architecture styles — the org chart of your agents

Two words that people mix up in interviews: a design pattern is how one agent thinks (ReAct, reflexion — Section 6). An architectural style is how many agents are wired together: who talks to whom, and who has the final say. Patterns are an employee's skills; styles are the org chart. A real system uses both — for example, ReAct agents inside an orchestrator–worker team.

🧪 Simulation · the style gallery

Click a style to see its shape and its finance job

If your problem looks like…Reach forBecause
Fixed stages, same order every time, auditors watchingSequential pipelinePredictable, easy to test and replay
"Who should handle this?" decided by one coordinatorOrchestrator–workerClean delegation; workers can run in parallel
Sub-tasks that themselves need splittingHierarchicalEach sub-team absorbs its own detail
Value comes from disagreementPeer-to-peer debateDiverse views stress-test each other
Many independent pieces, or a cross-checkParallelizationWall-clock time = the slowest piece
Quality must climb over draftsEvaluator–optimizerDraft → review → revise, with a round cap
Overlapping specialists; best fit varies by queryContract-net marketplaceAgents bid; routing adapts by itself

Peer-to-peer: how does a leaderless group decide?

Without a boss, you must pick a consensus mechanism up front — it decides how disagreement is "priced":

Majority votesimple
BUY 3, HOLD 2 → BUY. Ignores how sure each analyst is.
Weighted votetrusts track record
Weights by confidence, relevance or past accuracy.
Debate + synthesisshows reasoning
Arguments with evidence; a synthesizer weighs them (Section 8 builds this).
Convergenceagreed view
Rounds until positions are close — or a round cap hits.
⚠️ "Debate" that isn't

Many popular "AI hedge fund" demos run named analyst agents independently and let a portfolio manager combine their signals. That is parallelization with an aggregator, not a true debate: nobody answers anybody. Real peer-to-peer adds rounds where the bear must answer the bull's strongest point. Knowing this distinction is a great interview detail.

Contract-net: let the agents bid

Instead of a hard-coded router, a mediator broadcasts the question, every specialist replies with a bid (how confident it is that this is its job), and the top bidders get the work — the way a trading desk routes an inquiry to whoever knows the topic best.

🧪 Simulation · run a bidding round

Pick a client question, then move the threshold

Minimum bid to be considered0.50
Agents to hire (top K)2
💡 The honest trade-off

Every bid is an extra LLM call: broadcasting to N specialists adds N calls per question. LLM self-confidence is poorly calibrated (try the checkbox above). And you need a fallback for when nobody bids. If the specialists don't really overlap, a plain router is cheaper and better.

Real systems are hybrids

Production systems usually combine two or three styles. Three combinations come up again and again:

Hierarchical + parallelbank risk reportA CRO agent owns the verdict; market, credit, operational and regulatory risk run in parallel underneath. A data-snapshot agent first freezes prices so every risk agent uses the same numbers.
Sequential + dynamic routingresearch requestsA cheap classifier first: "What's Apple's market cap?" goes to one agent in seconds; "compare our tech holdings' risk-adjusted returns to the Nasdaq" wakes the full pipeline.
Single agent + escalationcustomer serviceOne generalist handles the routine ~80%. Only a fraud pattern or a thorny compliance question summons a team — you pay team costs only where they're deserved. Section 9 does exactly this.

And grow into them. A sensible path is five phases, each added only when measurements justify it:

Phase 1Single agentone agent + finance tools proves value
Phase 2Routingsend each query type to the right place
Phase 3Specialistsone agent per domain, own tools and prompts
Phase 4Coordinationhandoffs, shared state, a supervisor
Phase 5Quality loopevaluator agents review the output
🧪 Simulation · architecture drill (interview practice)

Which style would you pick?

Pick an answer.

Section 7 · Part 2 — Making agents work together

Talking, handing off, disagreeing — and surviving failures

7.3Coordination: how agents share, hand off and settle fights

Two ways to share information

🧠 Analogy — emails vs a whiteboard

Message passing is a team that only talks by email: every message is a clean, logged record, but if you need something from last week you must forward it again. Shared state is a whiteboard in the deal room: everyone reads and writes the same board — quick and simple, but you need rules about who may write where, or people rub out each other's numbers.

Message passingShared state
HowAgent A sends a structured message to agent BAgents read and write one common object
GoodEvery message is a loggable event — an audit trail for free; no race conditionsNothing to route; any agent can read the latest data
Watch outOverhead; old context must be re-sent explicitlyAgents depend on the data's shape; concurrent writes can clash; "who changed this?"
In our labsHandoffs between agents (7.5, 9.3)LlamaIndex ctx.store (7.5, 9.3) · LangGraph State (8.2)

Most finance systems use both: messages carry control ("your turn, because…"), shared state carries data (ratios, scores, the claim record). Long-term memory layers such as Mem0, Letta and Zep are the same whiteboard idea, kept outside any one context window.

Handoffs — and why the reason matters

A handoff is the moment one agent passes control to another. Each framework spells it differently, and the difference is a favourite interview question:

FrameworkHow you write itWho decides the next agent?
LlamaIndexcan_handoff_to=["ProfitabilityAgent"]The LLM, but only among the names you listed — routes are visible in code
LangGraphadd_edge / add_conditional_edgesThe graph: fixed edges, or a Python function reading the state
OpenAI Agents SDKhandoffs=[specialist]The LLM — and the specialist then takes over the conversation and answers the user
OpenAI Agents SDKspecialist.as_tool(...)The manager calls the specialist like a tool and keeps control, so it can combine several answers
🎯 Interview angle — "handoff or agent-as-tool?"

Ask who should own the conversation after the call. If the specialist should answer the user directly (a billing question goes to billing), use a handoff. If a manager must aggregate several specialists (price + company info + income statement → one analysis), use agents as tools.

💰 Finance corner — the reason is part of the audit trail

"Handing off to Compliance because this trade exceeds the portfolio's risk limits" is not chit-chat — if a regulator later asks why a trade was blocked, that sentence is the answer. Always log the reason with every handoff. (LlamaIndex's built-in handoff tool even has a required reason argument; our lab prints it.)

When agents disagree

In a team, disagreement is often a sign the system works — a risk agent that never argues with the trader isn't doing its job. What matters is having a rule for settling it. There are four, and you'll mix them:

🧪 Simulation · settle a sizing fight

Trader wants 10,000 shares. Risk says 3,000 is the most it can live with.

Portfolio NAV $50M · share price $400 · firm policy: no single stock above 5% of NAV. Pick a resolution strategy:

StrategyFinance useSpeedComplexity
Hierarchical — a fixed chain of authorityCompliance veto, risk limitsInstantLow
Policy-based — neutral rules everyone obeysPosition caps, exposure limitsInstantLow
Negotiation — agents propose compromisesTrade sizing under risk constraintsMediumMedium
Scoring (game-theoretic) — proposals ranked by a formulaCompeting portfolio strategiesSlowHigh

Rule of thumb: hierarchy and policy handle the non-negotiables (regulation, hard limits) and are written in code. Negotiation and scoring handle discretionary calls where reasonable agents can disagree.

Who speaks next: static vs dynamic control

Static control fixes the order at design time (A → B → C): predictable and auditable, but blind to surprises. Dynamic control lets an LLM or a router pick the next agent at runtime — like an investment committee where the macro analyst speaks first on the day rates jump. Most production systems use a static backbone (compliance always runs, in order) with dynamic choices at a few decision points.

💡 Mechanical problems deserve mechanical answers

Agents competing for API rate limits or compute? That's a token bucket or priority queue problem — give compliance checks the top priority and allocate in code. Using LLM "negotiation" here is over-engineering. Save negotiation for real judgment calls, such as splitting a remaining $10M risk budget between three trading ideas with different Sharpe ratios and holding periods.

7.4Production hardening: tracing, failures, context, cost, tests

1 · Trace everything, with one ID

A team of agents is much harder to debug than one agent: you need to know who did what, what they passed on, and where it went wrong. Log, for every agent step: timestamp, agent name, input, output, tool calls with arguments and results, token count, and — for handoffs — the reason. Then add two production habits:

  • A correlation ID created when the request arrives and carried through every handoff, tool call and retry. That one ID turns scattered per-agent logs into the single chain a regulator asks for.
  • OpenTelemetry-compatible tracing (for example Langfuse or Arize Phoenix), so your observability survives a framework change.
{"cid":"req-7f3a","t":"09:14:02","agent":"FundamentalAgent","tool":"get_fundamentals","args":{"ticker":"AAPL"},"tokens":812} {"cid":"req-7f3a","t":"09:14:05","agent":"FundamentalAgent","handoff_to":"ProfitabilityAgent","reason":"ratios saved"} {"cid":"req-7f3a","t":"09:14:09","agent":"ProfitabilityAgent","output":"ROA 26.13% → 10/10","tokens":1290}

2 · Failures: the answer depends on who failed and what already happened

Four recovery tools — retry with backoff (max ~3), fallback agent (e.g. a smaller model that can at least extract the numbers), graceful degradation (continue and flag the gap), and a circuit breaker (stop calling a broken agent, alert ops). The skill is choosing the right one:

🧪 Simulation · failure drill

Pick an incident and walk the decision path

⚠️ The two rules people forget
  • Retries are only safe for read-only tools. If an agent times out after sending an order, a blind retry can buy twice. Label every tool read-only or side-effecting, give side-effecting tools an idempotency key, and checkpoint the pipeline so a replay skips finished steps.
  • Compliance and risk never "degrade gracefully". If the risk check fails, the trade is blocked. Analysts may fail soft; gates fail closed.

3 · Keep each context small

Four ways to fight context overflow: context editing (prune stale tool results), memory files (write intermediate results to disk, read back when needed), small tool responses (filter to the last 2–3 years at the tool, not in the prompt), and the strongest one, sub-agent isolation.

💰 Finance corner — summarize first, then synthesize

A 20-holding portfolio review can produce 50,000+ tokens of raw data. If each company's specialist first writes a 500–1,000-token summary, the supervisor reasons over 10,000–20,000 tokens instead. The CRO doesn't need the full credit model — just the credit score and the key findings.

4 · Control cost — in this order

  1. Prompt caching. Multi-agent cost is mostly duplicated input: every agent re-reads system prompts, tool schemas and history. Keep that prefix byte-identical so the provider's cache discounts it. Biggest lever; design it in from day one.
  2. Model tiering. Data-fetching agents on a small model, synthesis on a big one — typically 40–60% cheaper with little quality loss. Section 8's committee does this.
  3. Agent pruning. "What's Apple's price?" shouldn't wake four analysts. Route simple questions to one agent.
  4. Tool-result caching. Fetch a company's data once and share it through state.
  5. Token budgets. Cap each agent so a stuck loop can't run up the bill.

5 · Test the team, not the wording

Test at four levels: unit (one agent, mocked inputs), integration (does the state one agent writes reach the next?), end-to-end, and adversarial (conflicting data, a company with one quarter of history). LLM wording changes run to run, so freeze tool responses as fixtures, pin the model version, and assert on invariants — "every metric has a score", "a payout never exceeds the limit" — instead of exact text. Section 9's lab ships a real invariant test file.

Over-agentificationanti-patternCurrency conversion, a percentage, data formatting: if it's a deterministic function, make it a tool, not an agent.
Premature parallelizationanti-patternRunning dependent tasks in parallel creates races and inconsistent results. Prove independence first.
Forgetting the simple optionanti-patternOne agent with five well-designed tools often beats a poorly coordinated team — cheaper and more reliable.

Section 7 · Part 3 — Hands-on lab

Lab: a multi-agent financial health analyzer

7.5Four agents, one whiteboard, handoffs with reasons

📅 Monday, 8:30 am — research desk. "Give me a financial health check on Apple: how profitable, how liquid, overall score, and why." We build it as a sequential pipeline: one agent collects the numbers, two specialists score them, a supervisor writes the report. Then we run five companies in parallel.
user: "health analysis of AAPL" FundamentalAgentget_fundamentals ProfitabilityAgentget_profitability_ratios LiquidityAgentget_liquidity_ratios SupervisorAgentno tools · last agent handoff+ reason handoff+ reason handoff+ reason ctx.store["state"] — the shared whiteboard ticker · sector · ratios profitability {band…} liquidity {band…} rubric_warning numbers and bands are written by TOOLS (code); scores and words come from the agents' LLMs writesreads ratios, writesreads ratios, writes reads the agents' scoresfrom the shared chat
Messages carry control (the handoffs); the whiteboard carries data. The supervisor has can_handoff_to=[], so the run ends with its report.

Setup

Terminal · set up once
pip install llama-index-core llama-index-llms-openai yfinance python-dotenv
echo "OPENAI_API_KEY=sk-..." > .env       # your key, never committed
python health_analyzer.py AAPL

The full file is in the Complete code appendix at the end of this page — create health_analyzer.py, paste it in, and run.

💰 Finance corner: the eight ratios and their health bands optional · glance over
RatioWhat it asksHealthyCaution
Return on assets (ROA)Profit per $ of everything the company owns> 5%2–5% moderate · < 2% weak
Return on equity (ROE)Profit per $ of shareholders' money> 15%8–15% moderate · < 8% weak
Net profit marginCents of profit per $ of sales> 10%5–10% · < 5% weak
Gross marginSales minus direct costs, as %> 40%20–40% · < 20% weak
Current ratioShort-term assets ÷ short-term debts1.5–3.0< 1.0 warning · > 3.0 maybe idle cash
Quick ratioSame, without inventory> 1.0< 1.0
Debt-to-equityBorrowed $ per $ of equity0.3–1.5> 2.0 high leverage
Interest coverageOperating profit ÷ interest bill> 3.01.5–3.0 · < 1.5 distress

The catch: these are rules for ordinary companies. A bank borrows for a living, so its "current ratio" and "debt-to-equity" mean nothing useful — banks are judged on capital (CET1: top-quality capital vs risk-weighted assets) and liquidity (LCR: can liquid assets cover 30 days of stressed outflows?). We keep JPMorgan (JPM) in the demo portfolio on purpose so you can see a confident score on the wrong rubric — and why real systems route by sector.

Step 1 — imports and the one model constant

Python · health_analyzer.py · setup
import asyncio
import sys

import yfinance as yf
from dotenv import load_dotenv
from llama_index.core.agent.workflow import (
    AgentStream,
    AgentWorkflow,
    FunctionAgent,
    ToolCall,
)
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI

load_dotenv()                      # reads OPENAI_API_KEY from .env
MODEL = "gpt-4o"                   # any tool-calling OpenAI model works — change one line
llm = OpenAI(model=MODEL)

load_dotenv() copies the keys from your .env file into environment variables, where the OpenAI client finds them. Every agent will share this one llm object.

Step 2 — the thresholds live in code

Python · health_analyzer.py · band functions
# Each rule: (metric label, how to read the number, function that returns a band)
# Bands are decided by CODE, so every run gives the same band for the same number.
def band_profitability(name: str, pct: float) -> str:
    """ROA / ROE / margins, given in percent (26.1 means 26.1%)."""
    limits = {                      # (strong above, weak below)
        "roa": (5, 2),
        "roe": (15, 8),
        "net_margin": (10, 5),
        "gross_margin": (40, 20),
    }
    strong, weak = limits[name]
    if pct > strong:
        return "strong"
    if pct < weak:
        return "weak"
    return "moderate"


def band_liquidity(name: str, x: float) -> str:
    """Current ratio, quick ratio, debt-to-equity and interest coverage (plain ratios)."""
    if name == "current_ratio":
        if x < 1.0:
            return "warning (below 1.0)"
        if x < 1.5:
            return "moderate"
        if x <= 3.0:
            return "healthy"
        return "healthy, but maybe idle cash (above 3.0)"
    if name == "quick_ratio":
        return "healthy" if x > 1.0 else "caution (below 1.0)"
    if name == "debt_to_equity":
        if x > 2.0:
            return "high leverage (above 2.0)"
        if x > 1.5:
            return "moderate"
        if x >= 0.3:
            return "healthy"
        return "conservative (below 0.3)"
    if name == "interest_coverage":
        if x > 3.0:
            return "healthy"
        if x >= 1.5:
            return "moderate"
        return "distress risk (below 1.5)"
    raise ValueError(name)
  1. limits[name] looks up the pair for one metric, e.g. "roa": (5, 2), and unpacks it: strong, weak = 5, 2.
  2. For ROA 26.13: 26.13 > 5 → "strong". For a current ratio of 0.87: 0.87 < 1.0 → "warning (below 1.0)".
  3. Why not let the LLM compare? Because 0.87 < 1.0 must give the same answer every run, and an auditor must be able to re-run it. Code decides the band; the LLM turns the band into a 1–10 score and a sentence.

Step 3 — fetch the raw numbers (plain Python)

Python · health_analyzer.py · fetch_ratios
def fetch_ratios(ticker: str) -> dict:
    """Plain Python, no LLM: pull the raw numbers from Yahoo Finance."""
    t = yf.Ticker(ticker)
    info = t.info or {}

    def pct(key):                   # 0.2613 → 26.13 (percent)
        v = info.get(key)
        return round(v * 100, 2) if v is not None else None

    d_e = info.get("debtToEquity")  # Yahoo gives 151.9 meaning 1.519×
    ratios = {
        "roa": pct("returnOnAssets"),
        "roe": pct("returnOnEquity"),
        "net_margin": pct("profitMargins"),
        "gross_margin": pct("grossMargins"),
        "current_ratio": info.get("currentRatio"),
        "quick_ratio": info.get("quickRatio"),
        "debt_to_equity": round(d_e / 100, 2) if d_e is not None else None,
        "interest_coverage": None,
    }
    try:                            # EBIT ÷ interest expense, latest fiscal year
        inc = t.income_stmt
        ebit = inc.loc["EBIT"].iloc[0]
        interest = abs(inc.loc["Interest Expense"].iloc[0])
        if interest:
            ratios["interest_coverage"] = round(float(ebit / interest), 2)
    except Exception:
        pass                        # some companies don't report it → stays None
    return {"sector": info.get("sector", "Unknown"), "ratios": ratios}
  1. pct() is a tiny helper inside the function: Yahoo gives 0.2613, we store 26.13 (percent), rounded to 2 decimals.
  2. A real-world quirk: Yahoo reports debt-to-equity already ×100 (151.9 means 1.519×), so we divide by 100. Data plumbing like this is where many "the AI got it wrong" bugs really come from.
  3. Interest coverage = EBIT ÷ interest expense from the income statement. Some companies don't report interest separately, so it's wrapped in try/except and stays None — the agents are told to say "missing", never to invent it.

Step 4 — the tools: read the whiteboard, write my slot, save

Python · health_analyzer.py · the three tools
async def get_fundamentals(ctx: Context, ticker: str) -> str:
    """Collect the raw financial ratios for a ticker and save them in shared state."""
    data = await asyncio.to_thread(fetch_ratios, ticker)   # don't block the event loop

    state = await ctx.store.get("state")                    # 1. read the whiteboard
    state["ticker"] = ticker.upper()                        # 2. write my slots
    state["sector"] = data["sector"]
    state["ratios"] = data["ratios"]
    if data["sector"] == "Financial Services":              # banks need CET1 / LCR instead
        state["rubric_warning"] = (
            "Bank or financial firm: current ratio and debt-to-equity do not fit. "
            "Treat the liquidity scores as low-confidence."
        )
    await ctx.store.set("state", state)                     # 3. save it back
    return f"Ratios saved for {ticker.upper()} (sector: {data['sector']})."


async def get_profitability_ratios(ctx: Context) -> str:
    """Read ROA, ROE and margins from shared state and band them against the thresholds."""
    state = await ctx.store.get("state")
    rows = {}
    for name in ("roa", "roe", "net_margin", "gross_margin"):
        v = state["ratios"].get(name)
        rows[name] = {"value_pct": v,
                      "band": band_profitability(name, v) if v is not None else "missing"}
    state["profitability"] = rows
    await ctx.store.set("state", state)
    return str(rows)


async def get_liquidity_ratios(ctx: Context) -> str:
    """Read the liquidity and leverage ratios from shared state and band them."""
    state = await ctx.store.get("state")
    rows = {}
    for name in ("current_ratio", "quick_ratio", "debt_to_equity", "interest_coverage"):
        v = state["ratios"].get(name)
        rows[name] = {"value": v,
                      "band": band_liquidity(name, v) if v is not None else "missing"}
    state["liquidity"] = rows
    await ctx.store.set("state", state)
    warning = state.get("rubric_warning")
    return str(rows) + (f"\nWARNING: {warning}" if warning else "")
  1. ctx: Context as the first parameter tells LlamaIndex to inject the workflow context. The LLM never sees ctx; it only sees the other parameters (here, ticker). The docstring becomes the tool description the LLM reads.
  2. The three-line rhythm in every tool: state = await ctx.store.get("state") → change only my keys → await ctx.store.set("state", state). Forget the set and your change is lost.
  3. await asyncio.to_thread(fetch_ratios, ticker) runs the slow, blocking Yahoo call in a worker thread. Without it, one company's download would freeze the event loop — and the parallel version below would quietly run one-by-one.
  4. The bank guard: if the sector is "Financial Services", the tool writes a rubric_warning. The liquidity tool repeats it, and the supervisor is told to put it at the top of the report.
  5. What the tool returns (a short string) is what the LLM sees as the tool result. The full data stays on the whiteboard.

Step 5 — the four agents

Python · health_analyzer.py · four FunctionAgents
SCORING_RULES = (
    "Score EVERY metric from 1 to 10 and justify each score in one sentence using "
    "the actual number. Use the band from the tool as your anchor: "
    "strong/healthy = 8-10, moderate = 5-7, weak/warning/distress = 1-4. "
    "If a value is missing, say so and do not invent it."
)

fundamental_agent = FunctionAgent(
    name="FundamentalAgent",
    description="Collects the raw financial ratios for the ticker.",
    system_prompt=(
        "You are the fundamental data analyst. Call get_fundamentals EXACTLY ONCE "
        "for the ticker in the user's request, then hand off to ProfitabilityAgent."
    ),
    llm=llm,
    tools=[get_fundamentals],
    can_handoff_to=["ProfitabilityAgent"],
)

profitability_agent = FunctionAgent(
    name="ProfitabilityAgent",
    description="Scores profitability: ROA, ROE, net margin, gross margin.",
    system_prompt=(
        "You are the profitability analyst. Call get_profitability_ratios EXACTLY ONCE. "
        + SCORING_RULES + " Then hand off to LiquidityAgent."
    ),
    llm=llm,
    tools=[get_profitability_ratios],
    can_handoff_to=["LiquidityAgent"],
)

liquidity_agent = FunctionAgent(
    name="LiquidityAgent",
    description="Scores liquidity and leverage: current, quick, D/E, interest coverage.",
    system_prompt=(
        "You are the liquidity and solvency analyst. Call get_liquidity_ratios EXACTLY ONCE. "
        + SCORING_RULES + " If the tool returns a WARNING, repeat it. "
        "Then hand off to SupervisorAgent."
    ),
    llm=llm,
    tools=[get_liquidity_ratios],
    can_handoff_to=["SupervisorAgent"],
)

supervisor_agent = FunctionAgent(
    name="SupervisorAgent",
    description="Writes the final financial health report.",
    system_prompt=(
        "You are the head of research. Using the analysts' scores above, write the final "
        "report: (1) profitability summary, (2) liquidity summary, (3) overall health "
        "score 1-10 that is consistent with the individual scores, (4) the two biggest "
        "strengths and the two biggest concerns. If there is a rubric WARNING, put it at "
        "the top. You are the last agent: write the answer yourself, do not hand off."
    ),
    llm=llm,
    tools=[],
    can_handoff_to=[],               # [] = nobody. Leaving it out would allow ANY agent!
)
  1. name is how other agents refer to it in a handoff; description is what they read when deciding.
  2. "Call … EXACTLY ONCE" keeps the run predictable: a transient tool error shouldn't turn into a retry loop that burns the iteration budget.
  3. SCORING_RULES anchors the LLM's 1–10 score to the code's band (strong = 8–10, moderate = 5–7, weak = 1–4), so two runs can't give ROA 26% a 4/10.
  4. can_handoff_to=["ProfitabilityAgent"] limits each agent to the next one in line: the pipeline's order is enforced, and visible in code.
  5. can_handoff_to=[] on the supervisor means "nobody". Leaving the argument out would mean "anyone" — the supervisor could bounce work back up the chain.

Step 6 — wire the workflow

Python · health_analyzer.py · build_workflow
def build_workflow() -> AgentWorkflow:
    return AgentWorkflow(
        agents=[fundamental_agent, profitability_agent, liquidity_agent, supervisor_agent],
        root_agent=fundamental_agent.name,          # who receives the user's message
        initial_state={                             # the shared whiteboard, empty at start
            "ticker": "",
            "sector": "",
            "ratios": {},
            "profitability": {},
            "liquidity": {},
            "rubric_warning": None,
        },
    )

root_agent receives the user's message first. initial_state is the empty whiteboard. One detail worth knowing: AgentWorkflow pastes "Current state: {…}" in front of your first message, so the agents can see the whiteboard. Handy here — and a privacy leak in Section 9, where we'll switch it off.

Step 7 — run it and watch the handoffs

Python · health_analyzer.py · run_analysis and main
async def run_analysis(ticker: str, verbose: bool = True) -> dict:
    """Run the 4-agent pipeline once. Returns the report, the final state and the handoffs."""
    handler = build_workflow().run(
        user_msg=f"Provide the financial health analysis of {ticker}.",
        max_iterations=60,                          # default 20 is too tight for 4 agents
    )
    handoffs, last_agent = [], None
    async for event in handler.stream_events():
        if isinstance(event, ToolCall) and event.tool_name == "handoff":
            hop = (last_agent, event.tool_kwargs.get("to_agent"), event.tool_kwargs.get("reason"))
            handoffs.append(hop)                    # audit trail: who, to whom, WHY
            if verbose:
                print(f"\n   🔀 handoff {hop[0]} → {hop[1]}  (reason: {hop[2]})")
        elif isinstance(event, AgentStream):
            if event.current_agent_name != last_agent:
                last_agent = event.current_agent_name
                if verbose:
                    print(f"\n{'=' * 60}\n🤖 Active agent: {last_agent}\n{'=' * 60}")
            if verbose and event.delta:
                print(event.delta, end="", flush=True)

    result = await handler                          # the last agent's answer
    state = await handler.ctx.store.get("state")    # the whiteboard after the run
    return {"ticker": ticker.upper(), "report": str(result), "state": state, "handoffs": handoffs}


if __name__ == "__main__":
    ticker = sys.argv[1] if len(sys.argv) > 1 else "AAPL"
    out = asyncio.run(run_analysis(ticker))
    print("\n\n--- Deterministic bands saved in shared state ---")
    for section in ("profitability", "liquidity"):
        for metric, row in out["state"][section].items():
            print(f"{section:13} {metric:18} {row}")
  1. max_iterations=60. The default is 20. Four agents need about 12 steps between them (tool call, handoff, answer each) and a single retry can use up the rest, so we give it room.
  2. handler.stream_events() yields events while the agents work. AgentStream carries text as it's generated (event.delta) and the active agent's name; ToolCall fires for every tool call.
  3. Handoffs are tool calls to a built-in tool called handoff, with arguments to_agent and reason. We catch them and keep (from, to, reason) in handoffs — the audit trail from 7.3.
  4. result = await handler waits for the end and gives the last agent's answer; handler.ctx.store.get("state") gives the final whiteboard.
🧪 Simulation · follow one run through the whiteboard

Eight steps from question to report

The big diagram above lights up as you click. Watch which keys of state change.

What a run prints (shortened sample)

🤖 Active agent: FundamentalAgent 🔀 handoff FundamentalAgent → ProfitabilityAgent (reason: Ratios for AAPL are saved; profitability scoring is next.) 🤖 Active agent: ProfitabilityAgent ROA 26.13% → 10/10: far above the 5% healthy line. ROE 151.91% → 10/10: well above 15% (boosted by buybacks shrinking equity). Net margin 24.3% → 9/10 · Gross margin 46.9% → 9/10 🔀 handoff ProfitabilityAgent → LiquidityAgent (reason: Profitability scored; liquidity is next.) 🤖 Active agent: LiquidityAgent Current ratio 0.87 → 3/10: below the 1.0 warning line · Quick ratio 0.83 → 4/10 Debt-to-equity 1.52 → 6/10 (just above the healthy range) · Interest coverage: not reported 🔀 handoff LiquidityAgent → SupervisorAgent (reason: Both analyses complete.) 🤖 Active agent: SupervisorAgent Overall health 7/10 — exceptional profitability, thin short-term liquidity…

A sample run; the wording changes each time, the bands don't.

🎯 Interview angle — three "why" questions about this lab
  • Why is the supervisor can_handoff_to=[] and not just left out? Left out means "may hand off to anyone"; an empty list means "nobody" — it must answer.
  • Why do tools compute the bands instead of the LLM? Reproducibility and audit: a comparison like 0.87 < 1.0 must never vary. LLMs do judgment and wording.
  • What breaks on JPM, and how would you fix it? The rubric, not the code: industrial ratios don't fit banks. Route by sector to a bank-specific agent (CET1, LCR) — a sequential pipeline with a routing step.

Extension A — five companies at once

Each company's analysis is pooled work (7.1): nobody needs anybody else's answer. So we wrap the whole pipeline in the parallelization style.

Python · portfolio_parallel.py · analyze_portfolio
import asyncio
import sys
import time

from health_analyzer import run_analysis

TICKERS = ["AAPL", "MSFT", "GOOGL", "NVDA", "JPM"]   # JPM kept on purpose: a bank!


async def analyze_company(ticker: str) -> dict:
    """Run the full 4-agent pipeline for one company and time it."""
    start = time.perf_counter()
    result = await run_analysis(ticker, verbose=False)
    result["seconds"] = time.perf_counter() - start
    return result


async def analyze_portfolio(tickers: list[str]) -> list:
    # gather() starts every pipeline at once and waits for all of them.
    # return_exceptions=True: one company failing becomes ONE bad row,
    # instead of crashing the whole portfolio run.
    return await asyncio.gather(
        *[analyze_company(t) for t in tickers],
        return_exceptions=True,
    )
  1. [analyze_company(t) for t in tickers] creates five coroutines — five not-yet-started pipeline runs.
  2. asyncio.gather(*…) starts them all and waits for every one. Results come back in the same order as tickers, whichever finishes first.
  3. return_exceptions=True. If NVDA's run hits a rate limit, its slot holds the exception object instead of crashing the other four. The table prints that row as FAILED — graceful degradation from 7.4.
Ticker ROA Current Profitability band Liquidity band secs AAPL 26.13% 0.87 strong warning (below 1.0) 21.4 MSFT … … … 19.8 NVDA FAILED → RateLimitError: … JPM 1.3% n/a weak ← a GOOD ROA for a bank! missing ⚠ bank: wrong rubric Wall-clock: 23.0s vs sum of the runs one-by-one: 84.6s

Illustrative output: wall-clock time ≈ the slowest company, not the sum. Note JPM: 1.3% ROA is healthy for a bank, yet the industrial rubric calls it "weak".

Extension B — add an evaluator (try it yourself)

Turn the pipeline into a sequential + evaluator–optimizer hybrid: add an EvaluatorAgent that checks the supervisor's report for completeness (every metric scored?), consistency (does the overall score fit the individual scores?) and justification (is each score backed by a number?). Wiring: set the supervisor's can_handoff_to=["EvaluatorAgent"], the evaluator's can_handoff_to=["SupervisorAgent"], and allow one revision round. Better still, compute the consistency check in a tool (average of the metric scores vs the overall score) — an evaluator grounded in code beats one that only has opinions.


Section 8 · Part 1 — An investment committee made of agents

The AI investment committee

8.1Designing the committee

📅 Tuesday, 7:45 am — trading floor. At a real fund, a stock idea goes to an investment committee: four analysts each present one angle, the portfolio manager (PM) makes the call and sizes it, and the chief risk officer can veto. We copy that org chart, seat for seat, with agents.
💰 Finance corner: why four lenses — and why it's hard to beat the market optional · glance over

Efficient markets, in one breath. The efficient market hypothesis says prices already reflect information: past prices (weak form), all public news (semi-strong), even private information (strong form). If that were perfectly true nobody would be paid to research — so some inefficiency must survive to reward the work (the Grossman–Stiglitz paradox). But edges get competed away once they're known: the classic "post-earnings drift" has weakened a lot since it was published. Expect a small edge, if any.

LensLooks atClassic tools
FundamentalsIs the business good, and is the price fair?P/E, ROE, margins, debt; factor models (CAPM, Fama–French); the Piotroski F-score
TechnicalsWhat is the price itself doing?Trend (price vs 50- and 200-day averages), momentum (RSI), volatility
SentimentWhat tone is the news taking?Finance-specific word lists (in finance, "liability" isn't a negative word)
MacroWhat's the weather for all stocks?VIX (the "fear gauge"), the 10-year Treasury yield, the S&P 500's last month

Why combine them? Signals like value and momentum tend to move against each other, so blending lenses smooths mistakes. But beware the opposite trap: researchers have published hundreds of "factors" and most don't survive careful testing — more lenses is not automatically better.

🧪 Simulation · indicator lab (what the technical analyst is handed)

Shape a price path and watch the numbers the code computes

Trend (annual drift)+20%
Volatility (annual)35%
Last month's move0%

The committee's org chart

START Fundamentals · Sonnet9 ratios from yfinance Technicals · SonnetSMA 50/200 · RSI · volatility Sentiment · Haikufiltered news headlines Macro · SonnetVIX · 10y yield · S&P 1-month Portfolio managerOpus · thesis + sizing Risk officerrules, then Opus END fan-in: the PM waits for ALL four fan-out
A deterministic fan-out / fan-in with a hierarchical synthesis. The graph itself is the orchestrator: every decision runs the same four seats, so no LLM call is spent on "who should I ask?".
SeatModel tierGets (computed in code)Must end with
Fundamentals analystSonnetP/E, P/B, ROE, margins, debt, growthBULLISH / NEUTRAL / BEARISH
Technical analystSonnetLast close, SMA 50/200, RSI-14, 30-day volatilityBULLISH / NEUTRAL / BEARISH
Sentiment analystHaiku — cheap, it's close to classificationUp to 8 headlines with date + publisherPOSITIVE / MIXED / NEGATIVE
Macro strategistSonnetVIX, 10-year yield, S&P 1-month return (no ticker!)risk-on / risk-off / neutral
Portfolio managerOpus — the hardest reasoningAll four reportsACTION=…; CONFIDENCE=…; SIZE_PCT=…
Risk officerRules first, then OpusThe thesis, the volatility, the macro reportVERDICT=APPROVED|REJECTED
🎯 Interview angle — "why not let the PM call the analysts as tools?"

Because every decision needs all four views. A fixed fan-out runs them in parallel, costs no routing call, and produces the same audit trail every time. Tool-calling (or a router) earns its keep when the set of specialists you need varies from question to question.

8.2Lab: the committee in LangGraph

Terminal
cd section8_trading_committee
python superstep_demo.py               # FREE — no key: how the graph runs
python investment_committee.py TSLA    # needs ANTHROPIC_API_KEY · 6 LLM calls

Step 1 — models and limits

Python · investment_committee.py · setup
from __future__ import annotations

import re
import sys
from typing import TypedDict

import yfinance as yf
from dotenv import load_dotenv
from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage, SystemMessage
from langgraph.graph import END, START, StateGraph

load_dotenv()

# One model per cost tier. Change the names here and nowhere else.
# We never pass temperature: newer Claude models no longer accept it.
OPUS_MODEL, SONNET_MODEL, HAIKU_MODEL = "claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5"
opus = ChatAnthropic(model=OPUS_MODEL, max_tokens=2048)      # PM + risk: hardest reasoning
sonnet = ChatAnthropic(model=SONNET_MODEL, max_tokens=1500)  # three analysts
haiku = ChatAnthropic(model=HAIKU_MODEL, max_tokens=800)     # sentiment: cheap, high volume

SINGLE_NAME_CAP_PCT = 3.0     # firm-wide limit per stock — known to the risk officer ONLY
VOL_CEILING = 0.60            # 60% annualised volatility → automatic veto
MIN_CONFIDENCE = 50
  1. Three clients, created once and reused by every node — one per cost tier. max_tokens matches the word limits in the prompts, a cheap guard against run-away answers.
  2. No temperature. Newer Claude models no longer accept it, so we steer behaviour with prompts and strict output formats instead — they work on every model.
  3. The risk limits are constants (3% cap, 60% volatility ceiling, confidence 50). They're used by the risk officer only — the PM is deliberately not told the 3% cap. If it knew, its sizes would cluster just under 3% and the risk review would become a formality. Keeping them separate makes disagreements visible in the audit trail.

Step 2 — the shared state

Python · investment_committee.py · CommitteeState
class CommitteeState(TypedDict):
    ticker: str
    indicators: dict            # written by technicals; re-used by the risk officer
    fundamentals_report: str    # ┐
    technicals_report: str      # │ four analysts write four DIFFERENT keys,
    sentiment_report: str       # │ in parallel → no clash, no reducer needed
    macro_report: str           # ┘
    pm_thesis: str
    risk_verdict: str
    final_decision: str

A TypedDict is just a dictionary with named, typed keys — the whiteboard every node reads. Each node returns a partial dict with only the keys it owns, and LangGraph merges it in. Because the four parallel analysts write four different keys, nothing can clash. We added one key, indicators: the technical analyst saves its numbers so the risk officer later judges the very same snapshot instead of re-downloading prices that may have moved.

Step 3 — the numbers, computed in plain Python

Python · investment_committee.py · data fetchers
def fetch_fundamentals(ticker: str) -> dict:
    info = yf.Ticker(ticker).info or {}
    keys = ["trailingPE", "forwardPE", "priceToBook", "returnOnEquity", "profitMargins",
            "debtToEquity", "currentRatio", "revenueGrowth", "earningsGrowth"]
    return {k: info.get(k) for k in keys}


def compute_indicators(ticker: str, period: str = "1y") -> dict:
    close = yf.Ticker(ticker).history(period=period)["Close"]
    sma_50 = close.rolling(50).mean().iloc[-1] if len(close) >= 50 else None
    sma_200 = close.rolling(200).mean().iloc[-1] if len(close) >= 200 else None
    delta = close.diff()                               # day-to-day change
    gain = delta.clip(lower=0).rolling(14).mean()      # average up-move, 14 days
    loss = (-delta.clip(upper=0)).rolling(14).mean()   # average down-move, 14 days
    rsi = (100 - 100 / (1 + gain / loss)).iloc[-1]
    vol_30d = close.pct_change().rolling(30).std().iloc[-1] * (252 ** 0.5)
    return {
        "last_close": round(float(close.iloc[-1]), 2),
        "sma_50": round(float(sma_50), 2) if sma_50 is not None else None,
        "sma_200": round(float(sma_200), 2) if sma_200 is not None else None,
        "rsi_14": round(float(rsi), 1),
        "vol_30d_annualized": round(float(vol_30d), 4),
    }


def fetch_macro_snapshot() -> dict:
    vix = yf.Ticker("^VIX").history(period="5d")["Close"].iloc[-1]
    tnx = yf.Ticker("^TNX").history(period="5d")["Close"].iloc[-1]
    spx = yf.Ticker("^GSPC").history(period="1mo")["Close"]
    return {
        "vix": round(float(vix), 2),
        "us_10y_yield_pct": round(float(tnx), 2),
        "spx_1m_return_pct": round(float((spx.iloc[-1] / spx.iloc[0] - 1) * 100), 2),
    }
  1. SMA (simple moving average): close.rolling(50).mean().iloc[-1] = the average of the last 50 closes. The if len(close) >= 50 guard avoids a meaningless average for a newly listed stock.
  2. RSI-14 in four lines: delta is each day's change; clip(lower=0) keeps only up-moves, -delta.clip(upper=0) only down-moves (as positive numbers); each is averaged over 14 days. RSI = 100 − 100 / (1 + avg gain ÷ avg loss). Above 70 is conventionally "overbought", below 30 "oversold". (Charting sites often use a smoothed average, so their RSI can differ slightly.)
  3. Volatility: the standard deviation of the last 30 daily returns × √252 (trading days in a year) = annualised volatility. 0.42 means about ±42% a year.
  4. Why in code and not as an LLM tool? Each analyst needs exactly one data source, so letting an LLM decide "which tool?" would add a call and add risk. We call the function ourselves and hand the result to the model. Cheaper, reproducible, auditable.
🔍 The news filter (optional detail) optional
Python · investment_committee.py · fetch_news
GENERIC = {"inc", "inc.", "corp", "corp.", "corporation", "company", "co", "holdings",
           "group", "the", "plc", "ltd", "class", "platforms"}


def _is_about_company(title: str, ticker: str, short_name: str) -> bool:
    """Keep a headline only if it names the ticker or a meaningful word of the company name."""
    words = re.findall(r"[A-Za-z0-9&.]+", title)
    if ticker.upper() in (w.upper().strip(".") for w in words):
        return True
    name_words = [w.lower().strip(",.") for w in short_name.split()]
    key_words = [w for w in name_words if len(w) >= 4 and w not in GENERIC]
    return any(k in title.lower() for k in key_words)


def fetch_news(ticker: str, n: int = 8) -> list[str]:
    """Up to n headlines PRIMARILY about the ticker: '[date, publisher] title — first sentence'."""
    try:
        stock = yf.Ticker(ticker)
        short_name = (stock.info or {}).get("shortName", "")
        items = stock.news or []
    except Exception:
        items, short_name = [], ""
    lines = []
    for it in items:
        content = it.get("content", it)
        title = content.get("title") or it.get("title")
        if not title or not _is_about_company(title, ticker, short_name):
            continue                                   # market-wide noise → skip
        publisher = (content.get("provider") or {}).get("displayName", "")
        pub_date = (content.get("pubDate") or "").split("T", 1)[0]
        summary = (content.get("summary") or content.get("description") or "").strip()
        m = re.search(r"([^.!?]*[.!?])", summary)
        first = m.group(1).strip() if m else summary[:200]
        meta = ", ".join(p for p in (pub_date, publisher) if p)
        line = (f"[{meta}] " if meta else "") + title + (f" — {first}" if first else "")
        lines.append(line)
        if len(lines) >= n:
            break
    return lines

Per-ticker news feeds include market-wide stories ("Stocks rally as yields fall") that would dilute the sentiment signal. _is_about_company keeps a headline only if it names the ticker or a meaningful word of the company name ("Tesla" from "Tesla, Inc."; never "Inc."). Each line also carries the date (recent news counts more) and the publisher (Reuters ≠ a blog; eight bullish stories from one outlet smell like a PR push).

Step 4 — the four analysts share one shape

Python · investment_committee.py · analyst nodes
def fundamentals_analyst(state: CommitteeState) -> dict:
    data = fetch_fundamentals(state["ticker"])                       # 1. numbers, in code
    sys_msg = SystemMessage(content=(                                # 2. role + output shape
        "You are a senior equity fundamentals analyst. Given the ratios, write a SHORT "
        "report (max 150 words) covering: (1) valuation stance, (2) profitability, "
        "(3) balance-sheet strength, (4) growth. Conclude with a tilt: "
        "BULLISH / NEUTRAL / BEARISH on fundamentals."))
    msg = HumanMessage(content=f"Ticker: {state['ticker']}\nRatios: {data}")
    out = sonnet.invoke([sys_msg, msg])                              # 3. the right tier
    return {"fundamentals_report": out.content}                      # 4. ONLY my own key


def technicals_analyst(state: CommitteeState) -> dict:
    ind = compute_indicators(state["ticker"])
    sys_msg = SystemMessage(content=(
        "You are a technical analyst. Given price-derived indicators, write a SHORT report "
        "(max 120 words) on trend (price vs SMA50/SMA200), momentum (RSI) and volatility. "
        "Conclude with: BULLISH / NEUTRAL / BEARISH on technicals."))
    msg = HumanMessage(content=f"Ticker: {state['ticker']}\nIndicators: {ind}")
    out = sonnet.invoke([sys_msg, msg])
    return {"technicals_report": out.content, "indicators": ind}     # keep the snapshot


def sentiment_analyst(state: CommitteeState) -> dict:
    headlines = fetch_news(state["ticker"])
    body = "\n- ".join(headlines) if headlines else "(no headlines available)"
    sys_msg = SystemMessage(content=(
        "You are a news sentiment analyst. Each line is one article, already filtered to "
        "be primarily about the ticker, formatted '[date, publisher] title — first sentence'. "
        "Use the metadata, not just the title:\n"
        "- Weight RECENT articles more heavily (sentiment decays).\n"
        "- Treat tier-1 financial press (Reuters, Bloomberg, WSJ, FT) as harder evidence "
        "than opinion outlets or blogs.\n"
        "- If coverage is concentrated in one publisher, flag a possible PR push.\n"
        "Produce a SHORT report (max 120 words) and score sentiment as: "
        "POSITIVE / MIXED / NEGATIVE."))
    msg = HumanMessage(content=f"Ticker: {state['ticker']}\nHeadlines:\n- {body}")
    out = haiku.invoke([sys_msg, msg])
    return {"sentiment_report": out.content}


def macro_analyst(state: CommitteeState) -> dict:
    macro = fetch_macro_snapshot()                    # no ticker: the market regime
    sys_msg = SystemMessage(content=(
        "You are a macro strategist. Given a short macro snapshot, write a SHORT report "
        "(max 120 words) on the regime (risk-on / risk-off / neutral) and what it implies "
        "for a single-name long-only equity position."))
    msg = HumanMessage(content=f"Macro snapshot: {macro}")
    out = sonnet.invoke([sys_msg, msg])
    return {"macro_report": out.content}
  1. Fetch in code → prompt that fixes the role and the ending → call the right tier → return only my key.
  2. The fixed ending (BULLISH / NEUTRAL / BEARISH) makes the PM's job easier: four reports, one shared vocabulary.
  3. The macro node never sees the ticker — it describes the weather for every stock.

How LangGraph runs it: supersteps (free demo, no key)

Python · superstep_demo.py
import operator
import time
from typing import Annotated, TypedDict

from langgraph.errors import InvalidUpdateError
from langgraph.graph import END, START, StateGraph


def slow_node(name: str, key: str, seconds: float):
    """Build a node that 'thinks' for a while, then writes one key."""
    def node(state):
        time.sleep(seconds)                       # stands in for an LLM call
        return {key: f"{name} done"}
    return node


# --- 1 + 2: four analysts in parallel, each writing its OWN key -------------------
class Committee(TypedDict):
    fundamentals: str
    technicals: str
    sentiment: str
    macro: str
    pm: str


def pm_node(state: Committee):
    ready = [k for k in ("fundamentals", "technicals", "sentiment", "macro") if state[k]]
    return {"pm": f"PM saw {len(ready)}/4 reports"}


g = StateGraph(Committee)
for name in ("fundamentals", "technicals", "sentiment", "macro"):
    g.add_node(name, slow_node(name, name, 1.0))
    g.add_edge(START, name)                       # fan-out
    g.add_edge(name, "pm")                        # fan-in (implicit join)
g.add_node("pm", pm_node)
g.add_edge("pm", END)
committee = g.compile()

t0 = time.perf_counter()
empty = {"fundamentals": "", "technicals": "", "sentiment": "", "macro": "", "pm": ""}
for step, update in enumerate(committee.stream(empty, stream_mode="updates"), 1):
    print(f"t={time.perf_counter() - t0:4.1f}s  update {step}: {update}")
print("→ four 1-second analysts finished in about 1 second, then the PM ran once.\n")

# --- 3: two parallel nodes writing the SAME key ------------------------------------
class NoReducer(TypedDict):
    notes: str                                    # plain key: one writer per superstep


bad = StateGraph(NoReducer)
bad.add_node("bull", lambda s: {"notes": "bull says BUY"})
bad.add_node("bear", lambda s: {"notes": "bear says SELL"})
bad.add_edge(START, "bull")
bad.add_edge(START, "bear")
bad.add_edge("bull", END)
bad.add_edge("bear", END)
try:
    bad.compile().invoke({"notes": ""})
except InvalidUpdateError as e:
    print("Without a reducer →", type(e).__name__, ":", str(e).splitlines()[0])


class WithReducer(TypedDict):
    notes: Annotated[list[str], operator.add]     # reducer: concatenate the lists


good = StateGraph(WithReducer)
good.add_node("bull", lambda s: {"notes": ["bull says BUY"]})
good.add_node("bear", lambda s: {"notes": ["bear says SELL"]})
good.add_edge(START, "bull")
good.add_edge(START, "bear")
good.add_edge("bull", END)
good.add_edge("bear", END)
print("With operator.add  →", good.compile().invoke({"notes": []})["notes"])
t= 1.0s update 1: {'fundamentals': {'fundamentals': 'fundamentals done'}} t= 1.0s update 2: {'macro': {'macro': 'macro done'}} t= 1.0s update 3: {'sentiment': {'sentiment': 'sentiment done'}} t= 1.0s update 4: {'technicals': {'technicals': 'technicals done'}} t= 1.0s update 5: {'pm': {'pm': 'PM saw 4/4 reports'}} Without a reducer → InvalidUpdateError : At key 'notes': Can receive only one value per step. … With operator.add → ['bear says SELL', 'bull says BUY']
  1. Superstep: LangGraph runs every node whose inputs are ready at the same time, then merges their updates into the state, then looks for the next ready nodes. Four 1-second "analysts" finish in about 1 second, not 4.
  2. Implicit join: a node with several incoming edges waits for all of them. The PM ran once, after the fourth report — you never wrote a "wait" yourself.
  3. Reducers: two parallel nodes writing the same key crash with InvalidUpdateError, because LangGraph can't guess which value wins. Annotated[list, operator.add] tells it how to combine them. Our committee avoids the need by giving each analyst its own key.

Step 5 — the portfolio manager's contract

Python · investment_committee.py · parse_pm_line and portfolio_manager
PM_LINE_RE = re.compile(
    r"ACTION\s*=\s*(BUY|HOLD|SELL)\s*;\s*CONFIDENCE\s*=\s*(\d+)\s*;\s*SIZE_PCT\s*=\s*([\d.]+)",
    re.IGNORECASE)


def parse_pm_line(thesis: str) -> tuple[str, int, float] | None:
    """Read 'ACTION=BUY; CONFIDENCE=68; SIZE_PCT=2.0' → ('BUY', 68, 2.0). None if missing."""
    matches = PM_LINE_RE.findall(thesis)
    if not matches:
        return None
    action, conf, size = matches[-1]                  # the LAST such line wins
    return action.upper(), int(conf), float(size)


def portfolio_manager(state: CommitteeState) -> dict:
    sys_msg = SystemMessage(content=(
        "You are the Portfolio Manager. Synthesise the four analyst reports into a single "
        "thesis (max 250 words). End STRICTLY with one line of the form:\n"
        "ACTION=<BUY|HOLD|SELL>; CONFIDENCE=<0-100>; SIZE_PCT=<0.0-5.0>\n\n"
        "SIZE_PCT is the target position as % of TOTAL PORTFOLIO NAV. Size purely on your "
        "conviction; do not anticipate any downstream review. Scale:\n"
        "  0.0      -> HOLD or SELL (no new long exposure)\n"
        "  0.5-1.0  -> probe / starter position when conviction is mixed\n"
        "  1.0-2.0  -> standard BUY at moderate conviction (CONFIDENCE 50-70)\n"
        "  2.0-3.0  -> strong BUY at high conviction (CONFIDENCE 70+)\n"
        "  3.1-5.0  -> concentrated bet: only if EVERY analyst is bullish AND macro supports it\n"
        "A BUY at SIZE_PCT=0 is incoherent — pick HOLD instead. "
        "A HOLD or SELL must have SIZE_PCT=0."))
    msg = HumanMessage(content=(
        f"Ticker: {state['ticker']}\n\n"
        f"--- Fundamentals ---\n{state['fundamentals_report']}\n\n"
        f"--- Technicals ---\n{state['technicals_report']}\n\n"
        f"--- Sentiment ---\n{state['sentiment_report']}\n\n"
        f"--- Macro ---\n{state['macro_report']}"))
    out = opus.invoke([sys_msg, msg])
    return {"pm_thesis": out.content}
  1. Free text + one strict line. The thesis can be any prose; the last line must be ACTION=BUY; CONFIDENCE=68; SIZE_PCT=2.0. That one line is what code reads — no extra LLM call to "interpret" the PM.
  2. The sizing scale ties size to conviction (probe 0.5–1%, standard 1–2%, strong 2–3%, concentrated 3–5% only when everything lines up) and bans nonsense like "BUY at 0%".
  3. PM_LINE_RE captures three groups: (BUY|HOLD|SELL), (\d+) digits, ([\d.]+) digits and dots. re.IGNORECASE accepts "buy". findall(...)[-1] takes the last match, in case the model quotes an example line earlier in its answer.
  4. Returns None if the line is missing — and the risk officer treats None as a veto, never as a guess.

Step 6 — the risk officer: rules first, then judgment

Python · investment_committee.py · risk_officer
VERDICT_RE = re.compile(r"VERDICT\s*=\s*(APPROVED|REJECTED)", re.IGNORECASE)


def risk_officer(state: CommitteeState) -> dict:
    vol = state["indicators"]["vol_30d_annualized"]      # the SAME snapshot the analyst saw
    parsed = parse_pm_line(state["pm_thesis"])

    # Layer 1 — hard rules in code. Numbers are compared by Python, never by the LLM.
    problems = []
    if vol > VOL_CEILING:
        problems.append(f"realized 30d vol {vol:.1%} exceeds the {VOL_CEILING:.0%} ceiling")
    if parsed is None:
        problems.append("PM thesis has no valid ACTION/CONFIDENCE/SIZE_PCT line")
    else:
        action, conf, size = parsed
        if action == "BUY" and size > SINGLE_NAME_CAP_PCT:
            problems.append(f"SIZE_PCT {size} is above the {SINGLE_NAME_CAP_PCT}% single-name cap")
        if action == "BUY" and conf < MIN_CONFIDENCE:
            problems.append(f"CONFIDENCE {conf} is below {MIN_CONFIDENCE}")
        if (action == "BUY") != (size > 0):
            problems.append(f"incoherent line: {action} with SIZE_PCT={size}")
    if problems:
        return {"risk_verdict": "VETO: " + "; ".join(problems),
                "final_decision": "HOLD (risk veto)"}

    action = parsed[0]
    if action != "BUY":                                  # nothing to approve: no new risk
        return {"risk_verdict": f"No new long exposure ({action}).", "final_decision": action}

    # Layer 2 — the judgment call an LLM is good at: did the thesis ignore the macro picture?
    sys_msg = SystemMessage(content=(
        "You are the Chief Risk Officer. The numeric limits have ALREADY been checked in code. "
        "Your only job: REJECT if the thesis recommends BUY while ignoring or dismissing "
        "material macro headwinds described in the macro report; otherwise APPROVE. "
        "Reply STRICTLY: VERDICT=<APPROVED|REJECTED>; REASON=<one sentence>"))
    msg = HumanMessage(content=(
        f"Macro report:\n{state['macro_report']}\n\nPM thesis:\n{state['pm_thesis']}"))
    out = opus.invoke([sys_msg, msg])
    m = VERDICT_RE.search(out.content)
    verdict = m.group(1).upper() if m else "REJECTED"   # unreadable answer → fail SAFE
    final = action if verdict == "APPROVED" else "HOLD (risk rejected)"
    return {"risk_verdict": out.content, "final_decision": final}
  1. Layer 1 — code. Volatility above 60%, size above the 3% cap, confidence below 50, an incoherent line, or no line at all → "HOLD (risk veto)", with every reason listed. No LLM call is spent on a trade that already breaks a rule.
  2. Nothing to approve: HOLD and SELL add no new risk, so we skip the LLM.
  3. Layer 2 — the LLM gets the one question rules can't answer: did the thesis ignore macro headwinds?
  4. Strict parsing, failing safe. VERDICT_RE looks for VERDICT=APPROVED or VERDICT=REJECTED. An unreadable reply counts as REJECTED.
💡 Three upgrades over a typical first draft

A common first version asks the LLM to check "size > 3.0" and "confidence < 50" and then tests "REJECTED" in reply.upper(). That fails in three ways: LLMs are unreliable at comparing numbers; a reply like "VERDICT=APPROVED; REASON=not rejected, macro is covered" contains the word REJECTED; and a reply with no verdict at all is silently approved. Try all three in the simulation below.

🧪 Simulation · be the risk officer

Set the PM's line and the market, then see which layer decides

Step 7 — wire the graph and run it

Python · investment_committee.py · build_committee and run_committee
def build_committee():
    g = StateGraph(CommitteeState)
    g.add_node("fundamentals", fundamentals_analyst)
    g.add_node("technicals", technicals_analyst)
    g.add_node("sentiment", sentiment_analyst)
    g.add_node("macro", macro_analyst)
    g.add_node("portfolio_manager", portfolio_manager)
    g.add_node("risk_officer", risk_officer)
    for analyst in ("fundamentals", "technicals", "sentiment", "macro"):
        g.add_edge(START, analyst)                 # fan-out: all four start together
        g.add_edge(analyst, "portfolio_manager")   # fan-in: PM waits for all four
    g.add_edge("portfolio_manager", "risk_officer")
    g.add_edge("risk_officer", END)
    return g.compile()


COMMITTEE = build_committee()                      # compile once, reuse for every ticker


def run_committee(ticker: str) -> dict:
    initial: CommitteeState = {
        "ticker": ticker.upper(), "indicators": {},
        "fundamentals_report": "", "technicals_report": "",
        "sentiment_report": "", "macro_report": "",
        "pm_thesis": "", "risk_verdict": "", "final_decision": "",
    }
    return COMMITTEE.invoke(initial)

Two lines inside the loop create the whole shape: add_edge(START, analyst) fans out, add_edge(analyst, "portfolio_manager") fans in. compile() checks the graph and returns a runnable; we compile once and reuse it. In production you'd use .astream() to show progress and a checkpointer (e.g. MemorySaver) so a crashed run can resume.

🧪 Simulation · one committee decision, superstep by superstep

Watch the state fill up

The org-chart diagram above lights up as you click.

================================================================================ FINAL DECISION for TSLA: BUY ================================================================================ --- PM thesis --- [~250 words weighing a NEUTRAL fundamentals view (rich valuation), BULLISH technicals, POSITIVE delivery news and a risk-on macro regime …] ACTION=BUY; CONFIDENCE=68; SIZE_PCT=2.0 --- Risk verdict --- VERDICT=APPROVED; REASON=The thesis names rate risk explicitly and sizes modestly.

Sample output — the decision on a real run depends on that day's data. For learning only, not investment advice.


Section 8 · Part 2 — Is the committee any good?

Backtesting the committee, then making it argue

8.3Backtesting an agent committee

One well-written BUY tells you nothing about whether the committee makes good decisions on average. For that you replay it over many past dates and measure — a backtest. The ideas are old; agents add four new traps.

🧠 Analogy — the exam the student has already seen

Testing an LLM on 2023 market data is like grading a student on an exam whose answer sheet was in their textbook. If the model was trained on text written after your test dates, a great score may just be memory. And if your data functions quietly return today's numbers, you've handed the student tomorrow's newspaper too.

💸 Cost and time6 LLM calls per decision. Five years × 50 stocks × daily ≈ 375,000 calls — roughly $8,000–$15,000. So start small: 3–10 stocks, weekly, a few months.
🔮 Training-data leakageThe model may already "know" what happened. Start the test window after the training cutoff of every model in the committee.
📅 Point-in-time datayf.Ticker(t).info and .news return today's data. A real backtest needs every fetcher to accept an as_of_date. (Prices are fine — they're time-stamped by nature.)
🎲 RandomnessThe same committee can decide differently on a rerun. Run several times and report the spread, not one lucky number.

Plus the classic traps that apply to any strategy: survivorship bias (testing only companies that still exist) and multiple testing (try enough prompt variants and one will look brilliant by luck).

data the committee may see at Fri 3 Fri 1 Fri 2 Fri 3: decide Fri 4: exit Fri 5 hold one week → this return belongs to the trade TODAYlive .info / .news look-ahead leak: future data in a past decision
Walk-forward: step through the dates; at each one, decide using only the past, hold to the next date, record the result. Repeating this produces an honest out-of-sample record — if the data really is point-in-time. (Variations: an expanding window keeps all history; a rolling window keeps only the last N periods and adapts faster to regime changes.)
MetricPlain EnglishRough benchmark
Cumulative returnHow much the portfolio grew overallCompare with buy-and-hold
Sharpe ratioAverage return ÷ its wobble, scaled to a year (× √52 for weekly)> 0.5 over a long period is encouraging
Max drawdownWorst fall from a previous peakSmaller than buy-and-hold's
Hit rateShare of trades that made money> 50% beats a coin flip
TurnoverHow much it trades — a proxy for costsLower is cheaper
Information ratioExcess return over a benchmark ÷ the wobble of that excessLike Sharpe, but vs the index

The harness, piece by piece

Python · backtest.py · Trade
from __future__ import annotations

import argparse
import random
import re
from dataclasses import dataclass

import numpy as np
import pandas as pd
import yfinance as yf

UNIVERSE = ["TSLA", "MSFT", "NVDA"]
START, END = "2026-07-01", "2026-10-01"   # pick a window after your models' training cutoff


@dataclass
class Trade:
    decision_date: pd.Timestamp
    ticker: str
    action: str            # "BUY" or "SELL"
    size_pct: float        # PM-proposed size, % of NAV
    confidence: int
    entry_price: float
    exit_date: pd.Timestamp
    exit_price: float

    @property
    def pnl_pct(self) -> float:                  # the stock's move, signed by direction
        sign = 1 if self.action == "BUY" else -1
        return sign * (self.exit_price / self.entry_price - 1)

    @property
    def weighted_pnl(self) -> float:             # what it did to the WHOLE portfolio
        return (self.size_pct / 100.0) * self.pnl_pct
  1. @dataclass writes the boring __init__ for us: a Trade is just eight named fields.
  2. pnl_pct: bought at 100, sold at 105 → 1 × (105/100 − 1) = 0.05 (+5%). For a SELL the sign flips.
  3. weighted_pnl: a 2% position that gains 5% adds 0.02 × 0.05 = 0.001 — 0.1% to the whole portfolio. That's what lets us add up several positions.
Python · backtest.py · parse_decision
_ACTION_RE = re.compile(r"ACTION\s*=\s*(BUY|HOLD|SELL)", re.I)
_CONF_RE = re.compile(r"CONFIDENCE\s*=\s*(\d+)", re.I)
_SIZE_RE = re.compile(r"SIZE_PCT\s*=\s*([\d.]+)", re.I)


def parse_decision(committee_result: dict) -> tuple[str, int, float]:
    thesis = committee_result["pm_thesis"]
    a, c, s = _ACTION_RE.findall(thesis), _CONF_RE.findall(thesis), _SIZE_RE.findall(thesis)
    action = a[-1].upper() if a else "HOLD"
    confidence = int(c[-1]) if c else 0
    size_pct = float(s[-1]) if s else 0.0
    final = committee_result["final_decision"].lower()
    if "(risk veto)" in final or "(risk rejected)" in final:
        return "HOLD", confidence, 0.0           # the risk officer ALWAYS wins
    return action, confidence, size_pct

Same three fields as the risk officer reads, and one rule above all: if the final decision says (risk veto) or (risk rejected), the trade becomes HOLD with size 0 — the risk officer always wins, in the backtest exactly as in production.

Python · backtest.py · walk_forward
def _price_on_or_before(series: pd.Series, when: pd.Timestamp) -> float | None:
    """Last close on or before a date (Fridays can be holidays)."""
    s = series[series.index <= when]
    return float(s.iloc[-1]) if len(s) else None


def walk_forward(committee_fn, universe, start, end, rebalance_freq="W-FRI"):
    """committee_fn(ticker, as_of) -> committee result dict."""
    rebalance_dates = pd.date_range(start, end, freq=rebalance_freq)
    prices = {}
    for t in universe:
        close = yf.Ticker(t).history(start=start, end=end)["Close"]
        close.index = close.index.tz_localize(None)        # compare dates without time zones
        prices[t] = close

    trades = []
    for i, decision_date in enumerate(rebalance_dates[:-1]):
        exit_date = rebalance_dates[i + 1]                  # hold for exactly one period
        for ticker in universe:
            result = committee_fn(ticker, decision_date)
            action, confidence, size_pct = parse_decision(result)
            if action == "HOLD" or size_pct == 0.0:
                continue                                    # no position, no trade
            entry = _price_on_or_before(prices[ticker], decision_date)
            exit_ = _price_on_or_before(prices[ticker], exit_date)
            if entry is None or exit_ is None:
                continue
            trades.append(Trade(decision_date, ticker, action, size_pct, confidence,
                                entry, exit_date, exit_))
    return trades, rebalance_dates
  1. pd.date_range(start, end, freq="W-FRI") lists every Friday in the window.
  2. Prices are downloaded once per ticker; tz_localize(None) strips Yahoo's time zone so dates compare cleanly.
  3. rebalance_dates[:-1] skips the last Friday: it has no "next Friday" to exit on.
  4. committee_fn(ticker, decision_date) is passed in, not hard-wired — so you can swap the real committee for a free stand-in, or later for a point-in-time version.
  5. _price_on_or_before handles holidays: if a Friday has no close, use the last one before it.
Python · backtest.py · equity_curve and metrics
def equity_curve(trades, rebalance_dates, start_nav=1_000_000.0) -> pd.Series:
    """Portfolio value after each period. Weeks with no trades count as 0% weeks."""
    weekly = pd.Series(0.0, index=rebalance_dates[1:])      # every exit date, default 0%
    for t in trades:
        weekly[t.exit_date] += t.weighted_pnl               # add up all positions that week
    curve = (1 + weekly).cumprod() * start_nav
    return pd.concat([pd.Series([start_nav], index=[rebalance_dates[0]]), curve])


def metrics(curve: pd.Series, trades, periods_per_year: float = 52.0) -> dict:
    rets = curve.pct_change().dropna()
    sharpe = (rets.mean() / rets.std()) * np.sqrt(periods_per_year) if rets.std() > 0 else 0.0
    max_dd = (curve / curve.cummax() - 1).min()             # worst fall from a previous peak
    wins = sum(1 for t in trades if t.pnl_pct > 0)
    return {
        "trades": len(trades),
        "hit_rate": wins / len(trades) if trades else 0.0,
        "cumulative_return": float(curve.iloc[-1] / curve.iloc[0] - 1),
        "sharpe": float(sharpe),
        "max_drawdown": float(max_dd),
    }
  1. Every week gets a row, starting at 0%. A quiet week with no trades is a 0% week, not a missing week. Dropping those weeks (a very common bug) makes the returns look steadier and inflates the Sharpe ratio — try the toggle below.
  2. (1 + weekly).cumprod() × 1,000,000: +1% then −0.5% → 1,000,000 × 1.01 × 0.995 = 1,004,950.
  3. Max drawdown: curve / curve.cummax() − 1 is "how far below the best value so far" at each point; .min() is the worst of those.
Python · backtest.py · live vs free stand-in committee
def live_committee(ticker: str, as_of: pd.Timestamp) -> dict:
    """The real committee. It IGNORES as_of: its fetchers return today's data (look-ahead!)."""
    from investment_committee import run_committee        # imported only when needed
    return run_committee(ticker)


def random_committee(ticker: str, as_of: pd.Timestamp) -> dict:
    """Free stand-in that mimics the committee's output format, to test the harness."""
    rnd = random.Random(f"{ticker}{as_of.date()}")         # same inputs → same 'decision'
    action = rnd.choice(["BUY", "BUY", "HOLD"])
    conf, size = (rnd.randint(50, 80), rnd.choice([1.0, 1.5, 2.0])) if action == "BUY" else (55, 0.0)
    final = "HOLD (risk veto)" if rnd.random() < 0.1 else action
    return {"pm_thesis": f"...\nACTION={action}; CONFIDENCE={conf}; SIZE_PCT={size}",
            "final_decision": final}

Test the harness before you pay for it. python backtest.py --dry-run uses random_committee, which writes answers in exactly the committee's format (seeded per ticker and date, so reruns match). Plumbing bugs show up for free; only then switch to the ~200-call real run.

🧪 Simulation · backtest playground

Twelve Fridays, a random committee, and the metrics

This random committee buys about 30% of the time, so some Fridays have no trades. Click 🎲 a few times: over only 12 weeks the Sharpe ratio swings wildly — a reminder that short backtests prove very little.

How much would a bigger backtest cost?

================================================================ Universe : TSLA, MSFT, NVDA (live committee) Window : 2026-07-01 to 2026-10-01 (weekly, W-FRI) Trades executed : 24 Hit rate : 54.2% Cumulative ret. : 3.8% Sharpe (annl.) : 0.74 Max drawdown : -2.9% ================================================================

A sample run. With live fundamentals and news it is a plumbing test, not evidence — and 24 trades over three months is far too few to be statistically meaningful. Most first agent strategies don't beat buy-and-hold after costs; the point of the harness is to measure and improve.

8.4Adversarial debate: make the committee argue with itself

The committee aggregates evidence well, but it has a structural blind spot: every seat is asked "is this attractive?" and no seat is paid to say no.

Confirmation biasblind spot 1After a strong rally, fundamentals improve, charts look bullish, news turns happy and macro stays calm — four "independent" views lean the same way, and the PM's conviction soars.
Correlated reasoningblind spot 2Agents on the same model share the same blind spots. Asking the same model to "be contrarian" often yields weak objections.
The fix: structured oppositiondebate layerKeep the committee. Add a second graph where a bull and a bear — on different model families — attack the thesis, a devil's advocate attacks both, and a neutral judge decides.
STAGE 2 · debate graph (does not re-fetch any data) Committeestage 1: thesis +decision (BUY) 🐂 BullClaude Opus 🐻 BearOpenAI GPT 😈 Devil's advocate1 weakness per side ⚖️ JudgeSonnet final in parallel · never see each other
Composition, not replacement: stage 2 consumes stage 1's thesis and decision. You could swap the committee for a quant signal, or the debate for a simpler review, without touching the other.
⚠️ Model diversity has a cost

If the bull runs on a stronger model than the bear, the debate tilts toward BUY just because the bull argues better — and no later stage can repair a strong bear case that was never written. Pick adversaries of similar strength, and test the pairing now and then: rerun old debates with the models swapped. If verdicts flip with the seats, you're measuring model strength, not the trade. (Our judge is a Claude model, like the bull; a judge from a third family would remove even that tilt.)

The debate graph in code

Python · adversarial_debate.py · models and DebateState
from __future__ import annotations

import re
import sys
from typing import TypedDict

from dotenv import load_dotenv
from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from langgraph.graph import END, START, StateGraph

from investment_committee import OPUS_MODEL, SONNET_MODEL, run_committee

load_dotenv()
BEAR_MODEL = "gpt-4o"                       # a DIFFERENT model family on purpose

bull_model = ChatAnthropic(model=OPUS_MODEL, max_tokens=1500)
bear_model = ChatOpenAI(model=BEAR_MODEL, max_tokens=1500)
devil_model = ChatAnthropic(model=SONNET_MODEL, max_tokens=1000)
judge_model = ChatAnthropic(model=SONNET_MODEL, max_tokens=1500)


class DebateState(TypedDict):
    ticker: str
    committee_thesis: str       # ← copied in from stage 1
    committee_decision: str     # ← copied in from stage 1
    bull_case: str
    bear_case: str
    devil_critique: str
    judge_verdict: str
    final_decision: str

Importing run_committee makes the two-stage design explicit. The model names come from the committee file, so there's still only one place to change them. committee_thesis and committee_decision are copied into the debate state, so every debater sees exactly what the committee concluded.

Python · adversarial_debate.py · bull and bear
def _case_message(state: DebateState) -> HumanMessage:
    return HumanMessage(content=(
        f"Ticker: {state['ticker']}\n"
        f"Committee thesis:\n{state['committee_thesis']}\n"
        f"Committee decision: {state['committee_decision']}"))


def bull_node(state: DebateState) -> dict:
    sys_msg = SystemMessage(content=(
        "You are a BULL analyst. Construct the strongest possible case to ENTER a long "
        "position. Cite the strongest evidence from the committee thesis: catalysts, "
        "valuation support, technical confirmation, sentiment tailwinds. Be concrete and "
        "do NOT hedge. Max 200 words. End with: BULL_CONVICTION=<0-100>."))
    return {"bull_case": bull_model.invoke([sys_msg, _case_message(state)]).content}


def bear_node(state: DebateState) -> dict:
    sys_msg = SystemMessage(content=(
        "You are a BEAR analyst. Construct the strongest possible case AGAINST entering a "
        "long position. Surface risks the committee may have under-weighted: tail risks, "
        "macro headwinds, valuation stretch, sentiment crowding, technical exhaustion. Be "
        "concrete and do NOT hedge. Max 200 words. End with: BEAR_CONVICTION=<0-100>."))
    return {"bear_case": bear_model.invoke([sys_msg, _case_message(state)]).content}
  1. "Do NOT hedge." Without it, both sides drift toward balanced, mushy answers and the debate loses its point.
  2. BULL_CONVICTION / BEAR_CONVICTION give the judge (and your logs) a number next to the words.
  3. Fixed roles: the bull always argues for, the bear always against — so whatever the committee said, it gets challenged.
Python · adversarial_debate.py · devil's advocate
def devil_advocate(state: DebateState) -> dict:
    sys_msg = SystemMessage(content=(
        "You are a Devil's Advocate. Identify the SINGLE weakest claim in the BULL case and "
        "the SINGLE weakest claim in the BEAR case, and explain in one sentence each why "
        "those claims are weak. Max 150 words."))
    msg = HumanMessage(content=f"BULL case:\n{state['bull_case']}\n\nBEAR case:\n{state['bear_case']}")
    return {"devil_critique": devil_model.invoke([sys_msg, msg]).content}

"The single weakest claim on each side." Free to roam, a critic writes a polite overview of everything; forced to choose one, it must prioritise. Good structure often comes from a well-chosen constraint.

Python · adversarial_debate.py · judge
VERDICT_RE = re.compile(r"VERDICT\s*=\s*(BUY|HOLD|SELL)", re.IGNORECASE)


def _parse_verdict(text: str) -> str:
    m = VERDICT_RE.search(text)
    return m.group(1).upper() if m else "HOLD"   # unreadable → the safe default


def judge_node(state: DebateState) -> dict:
    sys_msg = SystemMessage(content=(
        "You are a NEUTRAL Judge. Weigh the bull case, the bear case and the devil's "
        "critique. Issue a verdict that MAY DIFFER from the committee's prior decision. "
        "Confirm the committee unless one side shows a clear, material flaw. "
        "Reply STRICTLY in the form:\n"
        "VERDICT=<BUY|HOLD|SELL>\nCONFIDENCE=<0-100>\nRATIONALE=<2-3 sentences>"))
    msg = HumanMessage(content=(
        f"Committee prior: {state['committee_decision']}\n\n"
        f"BULL case:\n{state['bull_case']}\n\n"
        f"BEAR case:\n{state['bear_case']}\n\n"
        f"Devil's critique:\n{state['devil_critique']}"))
    out = judge_model.invoke([sys_msg, msg])
    return {"judge_verdict": out.content, "final_decision": _parse_verdict(out.content)}
  1. "May differ from the committee's prior decision" — without this line, judges tend to anchor on the committee and rubber-stamp it.
  2. "Confirm the committee unless one side shows a clear, material flaw" — the opposite guard. A debate layer naturally lowers conviction; if almost every BUY turns into HOLD in your backtest, the judge is too aggressive.
  3. _parse_verdict uses a strict regex; anything unreadable becomes HOLD, the safe default.
Python · adversarial_debate.py · build_debate and run_pipeline
def build_debate():
    g = StateGraph(DebateState)
    g.add_node("bull", bull_node)
    g.add_node("bear", bear_node)
    g.add_node("devil", devil_advocate)
    g.add_node("judge", judge_node)
    g.add_edge(START, "bull")          # bull and bear in parallel…
    g.add_edge(START, "bear")
    g.add_edge("bull", "devil")        # …the devil waits for both
    g.add_edge("bear", "devil")
    g.add_edge("devil", "judge")
    g.add_edge("judge", END)
    return g.compile()


def run_pipeline(ticker: str) -> dict:
    committee_result = run_committee(ticker)                   # stage 1
    initial: DebateState = {
        "ticker": ticker.upper(),
        "committee_thesis": committee_result["pm_thesis"],
        "committee_decision": committee_result["final_decision"],
        "bull_case": "", "bear_case": "", "devil_critique": "",
        "judge_verdict": "", "final_decision": "",
    }
    debate_result = build_debate().invoke(initial)             # stage 2
    return {"committee": committee_result, "debate": debate_result}
🧪 Simulation · debate the TSLA BUY

Committee says BUY. Does it survive the debate?

================================================================================ COMMITTEE said : BUY DEBATE judge : HOLD (bull 72 vs bear 64) ================================================================================ --- Judge verdict --- VERDICT=HOLD CONFIDENCE=55 RATIONALE=The bull's catalyst argument is real but largely priced in, and the bear's rate-headwind point is the binding constraint for the next quarter. Downgrade to HOLD.

A typical result: the debate's most common value is not a reversal but lower conviction — a smaller position, or none. Cost: 4 extra LLM calls and a second provider.

Closing the loop: use the backtest to improve the system

You can't retrain an LLM committee like a quant model, but every recorded trade stores the full context — reports, thesis, risk verdict, outcome — so you can tune its configuration:

Confidence calibrationGroup past trades by CONFIDENCE. If 80-confidence trades win no more often than 55-confidence ones, tighten the PM's rubric or stop sizing on stated conviction.
Role attributionIf bad calls keep tracing back to one seat — say, sentiment turning bullish right before drawdowns — fix that role's prompt, data or model, locally.
Threshold tuningMeasure how vetoed trades would have done. Is the 60% volatility ceiling protecting you, or just blocking winners?
Model selectionRerun the same windows changing one model assignment (PM on Opus vs Sonnet, bull/bear seats swapped). If verdicts move while the evidence is identical, the model — not the analysis — is deciding.
🎯 Interview angle — "how would you evaluate a multi-agent trading system?"

Walk-forward on point-in-time data, starting after every model's training cutoff; several runs to see the spread; Sharpe, drawdown and hit rate against buy-and-hold after costs; then use the trade log for calibration and role attribution — and re-check every change on a window it wasn't tuned on, or you're just overfitting prompts. Finally, show the trader the system's historical hit rate in today's market regime next to each new call: decision support, not autopilot.


Section 9 · Part 1 — A team that a regulator can audit

Insurance claims with a compliance-first team

9.1Why insurance is a different multi-agent problem

🌧️ 2:47 AM, I-95, heavy rain. Sarah Chen, a customer of Future with Shivank Bank's insurance arm, rear-ends a delivery truck that stopped suddenly. Front bumper crushed, a headlight shattered, nobody hurt at the scene (her back starts aching later). The police report isn't filed yet. Standing on the hard shoulder, she opens the app and starts a claim. What happens next must be fast, fair, legal in her state — and explainable line by line if she ever disputes it.
3 sLemonade's record time to approve and pay a simple claim (2016)
30 min → 90 sdocument fraud review time at Inscribe with AI risk agents
100+insurers using Shift Technology's AI fraud detection
~$309Bestimated yearly cost of US insurance fraud (2022)
Trading committee (Section 8)Claims team (this section)
InputsNumbers: prices, ratios, headlinesDocuments: forms, photos, police reports, repair quotes, medical records
ClockMarkets move in secondsLegal deadlines: acknowledge in ~15 days, resolve in ~30–45 (varies by state)
A mistake hurtsThe fund's P&LA customer — and can become a bad-faith lawsuit
The regulator asks"Why this trade?""Which policy clause justified this denial?"
HumansPM signs off on big tradesAdjusters, a Special Investigations Unit (SIU), coverage specialists

Four things make a team the natural design here (not just "because we can"):

1 · Many kinds of dataA photo needs a vision model, a PDF needs extraction, a police report needs cross-checking. Different specialists, different tools.
2 · Security boundariesThe fraud agent needs claims history but never medical records. Separate agents = separate permissions.
3 · Audit by constructionEach agent is one documented step in the reasoning chain — exactly the shape regulators ask for.
4 · Natural pause pointsBetween agents is where a human can step in: high value, fraud flag, unclear coverage.
💰 Finance corner: insurance words you'll meet optional · glance over
  • FNOL (first notice of loss) — the moment the customer reports the incident. Starts the clock.
  • Coverage section / exclusion — the clause that pays for this kind of loss (e.g. Collision) / the clause that says "not this" (e.g. racing).
  • Deductible — the part the customer pays herself. Limit — the most the insurer will pay. Payout = repair − deductible, capped at the limit, never below zero.
  • Adjuster — the person who handles a claim; SIU — the Special Investigations Unit for suspected fraud.
  • Fraud types — hard (staged accidents), soft (inflating a real claim), organised (rings of fake claims). Detection mixes rules, pattern matching, network analysis (shared phones, addresses, body shops) and document-forgery checks.
  • Underwriting — deciding whether to insure someone, and at what price.

9.2Designing the claims pipeline

The style is a sequential pipeline with guardrails (7.2): seven agents in a fixed order, a check at every handoff, and a compliance agent with the last word. Two side doors handle the unusual: a fraud investigation team and human review — the "single agent + escalation" hybrid from 7.2, applied to a pipeline.

🔎 Fraud investigation debatescore > 40 → section 9.4 🙋 Human review gateshigh value · flags · gaps FNOLopen record Doc parserphotos · forms Coveragepolicy clauses Fraud screenred-flag rules Assessmentpayout Decisionmakes the call Complianceveto · last word 🛡 each handoff:a guardrail check 📜 Append-only audit log — every agent writes; names and policy numbers redacteda shared utility, not an agent · kept for the regulatory retention period
The conflict hierarchy is fixed in code: Compliance > Fraud > Adjudication (Decision) > Assessment. Whatever the decision agent says, a failed compliance check blocks payment.

Least privilege: who may see and write what

AgentMay see (raw inputs)May write (claim fields)Moves money?
FNOLthe claim formcreates the recordno
Document parsersubmitted documentsparsed docs, damage description, missing docsno
Coveragethe policycovered?, section, limit, deductible, reasoningno
Fraud screenerpolicy dates, claims history, report datefraud score, red flags, recommendationno
Assessmentthe repair quote linespayout, breakdownproposes
Decision— (claim record only)decision, reasoning, human-review gatesdecides
Compliance— (claim record only)compliance issuescan block

Each handoff hides a small guardrail. A good example is document handling, which always runs in three stages — classify (what is this?) → extract (which fields?) → validate (does the police report's date match the claimed date of loss? does the plate on the photo match the policy?).

9.3Lab: the seven-agent claims pipeline

The lab is in two layers. claims_rules.py holds every rule that moves money or blocks a decision — plain Python you can run and test for free. claims_pipeline.py wraps those rules in seven LlamaIndex agents. That split is the main lesson: agents orchestrate and explain; rules decide. Where production would call an LLM or a vision model (reading policy wording, pricing damage from photos), the code is marked # PRODUCTION:.

Terminal
cd section9_insurance_claims
python claims_rules.py                     # FREE: Sarah's claim through all 7 stages, no LLM
python claims_rules.py --suspicious        # FREE: same claim with 3 red flags
python -m pytest test_claims_rules.py -q   # FREE: 11 invariant tests
python claims_pipeline.py                  # the agent version (OPENAI_API_KEY)

Step 1 — the claim record is the contract

Python · claims_rules.py · ClaimType and ClaimRecord
from __future__ import annotations

import re
import sys
import uuid
from datetime import date, datetime, timezone
from enum import Enum

from pydantic import BaseModel


class ClaimType(str, Enum):
    AUTO = "auto"
    PROPERTY = "property"
    HEALTH = "health"
    LIABILITY = "liability"


class ClaimRecord(BaseModel):
    """The contract every agent reads and writes. Each stage owns its own fields."""
    claim_id: str
    policyholder_name: str
    policy_number: str
    claim_type: ClaimType
    date_of_loss: date
    description: str
    status: str = "received"
    # DocumentParser
    parsed_documents: list[dict] = []
    damage_description: str = ""
    missing_documents: list[str] = []
    # CoverageAgent
    coverage_verified: bool | None = None
    coverage_section: str = ""
    applicable_limit: float = 0.0
    deductible: float = 0.0
    coverage_reasoning: str = ""
    # FraudScreener
    fraud_score: int | None = None
    red_flags: list[str] = []
    fraud_recommendation: str = ""
    # AssessmentAgent
    estimated_payout: float | None = None
    assessment_breakdown: str = ""
    # DecisionAgent
    decision: str = ""
    decision_reasoning: str = ""
    human_review_gates: list[str] = []
    # ComplianceAgent
    compliance_issues: list[str] = []
    stages_completed: list[str] = []

A Pydantic model doubles as documentation: every agent knows exactly which fields exist and which belong to whom (the comments). ClaimType(str, Enum) means the value is both an enum and a plain string — "auto" prints and saves cleanly.

Step 2 — least privilege, enforced in code

Python · claims_rules.py · DATA_ACCESS and OWNED_FIELDS
# Least privilege: which top-level inputs each agent may SEE …
DATA_ACCESS = {
    "FNOLAgent":       ["claim_form"],
    "DocumentParser":  ["submitted_documents"],
    "CoverageAgent":   ["policy"],
    "FraudScreener":   ["policy", "claims_history", "fnol_date"],
    "AssessmentAgent": ["claim_form"],           # the body-shop estimate lines
    "DecisionAgent":   [],                        # works only from the claim record
    "ComplianceAgent": [],
}
# … and which claim fields each agent may WRITE (no agent can overwrite another's work).
OWNED_FIELDS = {
    "DocumentParser":  {"parsed_documents", "damage_description", "missing_documents"},
    "CoverageAgent":   {"coverage_verified", "coverage_section", "applicable_limit",
                        "deductible", "coverage_reasoning"},
    "FraudScreener":   {"fraud_score", "red_flags", "fraud_recommendation"},
    "AssessmentAgent": {"estimated_payout", "assessment_breakdown"},
    "DecisionAgent":   {"decision", "decision_reasoning", "human_review_gates"},
    "ComplianceAgent": {"compliance_issues"},
}


def scoped_view(state: dict, agent: str) -> dict:
    """Give an agent only the inputs it is allowed to see."""
    return {k: state[k] for k in DATA_ACCESS[agent] if k in state}


def write_fields(claim: dict, agent: str, status: str, **fields) -> None:
    """Write an agent's results into the claim — refuse anything it doesn't own."""
    illegal = set(fields) - OWNED_FIELDS[agent]
    if illegal:
        raise PermissionError(f"{agent} may not write {sorted(illegal)}")
    claim.update(fields)
    claim["status"] = status
    claim["stages_completed"] = claim.get("stages_completed", []) + [agent]
  1. scoped_view(state, "FraudScreener") returns a new dict with only policy, claims_history and fnol_date. The fraud tool literally cannot read the photos.
  2. write_fields(claim, agent, status, **fields): **fields collects keyword arguments into a dict. set(fields) - OWNED_FIELDS[agent] is "fields you tried to write that you don't own" — if that's not empty, PermissionError.
  3. It also appends the agent to stages_completed, which compliance later checks. A prompt can ask an agent to stay in its lane; code makes it.

Step 3 — the audit log, with PII redacted

Python · claims_rules.py · redact and log_audit
def redact(text: str, claim: dict) -> str:
    """Replace the policyholder's name and policy number with opaque tokens."""
    for secret, label in ((claim.get("policyholder_name"), "NAME"),
                          (claim.get("policy_number"), "POLICY")):
        if secret:
            text = re.sub(re.escape(secret), f"[{label}:{claim['claim_id']}]", text, flags=re.I)
    return text


def log_audit(state: dict, agent: str, action: str, details: str = "") -> None:
    """Append-only audit trail. Every agent writes here; nobody edits old lines."""
    claim = state.get("claim", {})
    state.setdefault("audit_log", []).append({
        "ts": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "claim_id": claim.get("claim_id", "?"),
        "agent": agent,
        "action": action,
        "details": redact(details, claim) if claim else details,
    })

re.escape(secret) makes the name safe to use inside a regular expression; flags=re.I catches "sarah chen" too. The replacement token [NAME:CLM-2026-…] is opaque — only authorised staff can map the claim ID back to a person. setdefault("audit_log", []) creates the list the first time; after that we only ever append.

Step 4 — the rules that matter

Python · claims_rules.py · screen_for_fraud
FRAUD_THRESHOLD = 40


def screen_for_fraud(policy: dict, claim: dict, claims_history: list, fnol_date: str) -> dict:
    score, flags = 0, []
    if days_between(policy["inception_date"], claim["date_of_loss"]) < 30:
        score += 25
        flags.append("Loss within 30 days of policy start (buy-and-claim pattern)")
    if len(claims_history) >= 3:
        score += 20
        flags.append(f"{len(claims_history)} prior claims in 12 months")
    if days_between(claim["date_of_loss"], fnol_date) > 30:
        score += 15
        flags.append("Reported more than 30 days after the loss")
    return {"fraud_score": score, "red_flags": flags,
            "fraud_recommendation": "investigate" if score > FRAUD_THRESHOLD else "proceed"}
  1. Three red flags, three weights: a loss within 30 days of buying the policy (+25, "buy-and-claim"), three or more prior claims (+20), reporting more than 30 days late (+15). Maximum 60.
  2. Above 40 → "investigate". Not "fraud" — a recommendation to look closer.
  3. Why rules, not an LLM? When a decision is challenged in court, "the score was 45 because these two rules fired" is defensible; "the model felt suspicious" is not.
Python · claims_rules.py · assess_damage
def assess_damage(repair_items: list[dict], deductible: float, limit: float) -> dict:
    # PRODUCTION: a vision/LLM estimate from photos, checked against a body-shop quote.
    gross = sum(i["cost"] for i in repair_items)
    payout = max(0.0, min(gross - deductible, limit))     # never negative, never above limit
    lines = ", ".join(f"{i['item']} ${i['cost']:,}" for i in repair_items)
    return {"estimated_payout": payout,
            "assessment_breakdown": f"{lines} = ${gross:,} gross − ${deductible:,.0f} deductible"
                                    f" → ${payout:,.0f} (limit ${limit:,.0f})"}

max(0.0, min(gross − deductible, limit)) in words: subtract the deductible, cap at the limit, never go below zero. Sarah: $4,300 − $500 = $3,800, well under the $50,000 limit.

Python · claims_rules.py · human_review_gates and make_decision
HIGH_VALUE_THRESHOLD = 100_000


def human_review_gates(claim: dict) -> list[str]:
    gates = []
    if (claim.get("estimated_payout") or 0) > HIGH_VALUE_THRESHOLD:
        gates.append("HIGH_VALUE → senior adjuster")
    if (claim.get("fraud_score") or 0) > FRAUD_THRESHOLD:
        gates.append("FRAUD_FLAG → fraud investigation / SIU")
    if claim.get("coverage_verified") is None:
        gates.append("COVERAGE_AMBIGUOUS → coverage specialist")
    if claim.get("claim_type") in ("health", "liability"):
        gates.append("REGULATORY → bodily-injury adjuster")
    if claim.get("missing_documents"):
        gates.append("INCOMPLETE_DOCS → request " + ", ".join(claim["missing_documents"]))
    return gates


STATUS_AFTER = {"APPROVE": "approved", "DENY": "denied", "ESCALATE": "escalated"}


def make_decision(claim: dict) -> dict:
    # PRODUCTION: an LLM writes the reasoning; the CHOICE still follows these rules.
    gates = human_review_gates(claim)
    if claim["coverage_verified"] is False:
        decision = "DENY"
        reasoning = (f"{claim['coverage_reasoning']} Policy reference: "
                     f"{claim['coverage_section'] or 'policy period'}. The claimant may contact "
                     "the state Department of Insurance.")
    elif gates:
        decision = "ESCALATE"
        reasoning = ("Paused for human review: " + "; ".join(gates) +
                     f". Fraud score {claim['fraud_score']}/100; proposed payout "
                     f"${claim['estimated_payout']:,.0f}.")
    else:
        decision = "APPROVE"
        reasoning = (f"{claim['coverage_reasoning']} Fraud score {claim['fraud_score']}/100 "
                     f"with no red flags. Payout: {claim['assessment_breakdown']}.")
    return {"decision": decision, "decision_reasoning": reasoning, "human_review_gates": gates}
  1. Gates first. Five conditions pause the claim for a person: high value (> $100,000), a fraud flag, unclear coverage, a regulated claim type (bodily injury), missing documents.
  2. Order of the decision: not covered → DENY (with the clause and the right to contact the state's Department of Insurance); any gate → ESCALATE; otherwise APPROVE.
  3. The reasoning string always cites the coverage clause, the fraud score and the payout maths — a complete chain an auditor can follow.
Python · claims_rules.py · validate_compliance
DENIAL_REASONS = ("POLICY_INACTIVE", "EXCLUSION", "NOT_COVERED")
ALL_STAGES = ["DocumentParser", "CoverageAgent", "FraudScreener", "AssessmentAgent", "DecisionAgent"]


def validate_compliance(claim: dict) -> list[str]:
    issues = []
    if claim["decision"] == "DENY" and not claim["decision_reasoning"].startswith(DENIAL_REASONS):
        issues.append("Denial reason not a recognised category")
    if len(claim["decision_reasoning"]) < 50:
        issues.append("Reasoning too short for an audit")
    missing = [s for s in ALL_STAGES if s not in claim.get("stages_completed", [])]
    if missing:
        issues.append(f"Pipeline stage missing: {missing}")
    if claim["decision"] == "APPROVE":
        if (claim.get("fraud_score") or 0) > FRAUD_THRESHOLD:
            issues.append("Approved despite a fraud flag")
        if (claim.get("estimated_payout") or 0) > claim.get("applicable_limit", 0):
            issues.append("Payout above the policy limit")
        if claim.get("human_review_gates"):
            issues.append("Auto-approved although a human-review gate fired")
    return issues

Compliance re-checks the whole claim, not just the decision agent's word: a denial must start with a recognised reason category, the reasoning must be long enough to audit, every stage must have run, and an APPROVE may never coexist with a fraud flag, a payout above the limit, or a human-review gate. Any issue → BLOCKED. This is the hierarchical conflict resolution from 7.3, in code.

Step 5 — tools: load my view, call the rule, write my fields, log

Python · claims_pipeline.py · _load and the first two tools
async def _load(ctx: Context, agent: str):
    """state = the shared whiteboard; view = ONLY the raw inputs this agent may see."""
    state = await ctx.store.get("state")
    inputs = await ctx.store.get("case_inputs")       # kept OUT of "state" on purpose
    return state, R.scoped_view(inputs, agent)


async def process_fnol(ctx: Context) -> str:
    """Create the claim record from the submitted claim form."""
    state, view = await _load(ctx, "FNOLAgent")       # sees the claim form only
    claim = R.fnol_intake(view["claim_form"])          # data never passes through the LLM
    state["claim"] = claim
    R.log_audit(state, "FNOLAgent", "claim created", f"type={claim['claim_type']}")
    await ctx.store.set("state", state)
    return f"FNOL processed. Claim {claim['claim_id']}, type {claim['claim_type']}."


async def parse_documents(ctx: Context) -> str:
    """Parse the submitted documents and list any missing ones."""
    state, view = await _load(ctx, "DocumentParser")
    r = R.parse_documents(view["submitted_documents"])
    R.write_fields(state["claim"], "DocumentParser", "parsing", **r)
    R.log_audit(state, "DocumentParser", "documents parsed", f"{len(r['parsed_documents'])} docs")
    await ctx.store.set("state", state)
    return (f"Parsed {len(r['parsed_documents'])} documents. Damage: {r['damage_description']}. "
            f"Missing: {r['missing_documents'] or 'none'}.")
  1. No arguments except ctx. Unlike a typical tool, process_fnol doesn't let the LLM pass the claim data in. The data goes from storage → rule → storage without passing through the model, so the model can't retype a policy number wrong.
  2. _load returns two things: the shared state (the claim record and audit log) and the agent's scoped view of the raw inputs.
  3. The other five tools follow the same four-line rhythm: load → rule → write_fields → log_audit.

Step 6 — seven agents from one factory

Python · claims_pipeline.py · make_agent and PIPELINE
def make_agent(name: str, job: str, tool, next_agent: str | None) -> FunctionAgent:
    hand = (f"then hand off to {next_agent} with a one-line reason."
            if next_agent else "then give the final answer yourself. Do not hand off.")
    return FunctionAgent(
        name=name,
        description=job,
        system_prompt=(
            f"You are the {name} of an auto-insurance claims team. Your job: {job} "
            f"Call {tool.__name__} EXACTLY ONCE. Report its result in one or two sentences "
            "without changing any number, decision or flag, " + hand),
        llm=llm,
        tools=[tool],
        can_handoff_to=[next_agent] if next_agent else [],
    )


PIPELINE = [   # (agent name, job, tool) in order
    ("FNOLAgent", "open the claim record from the first notice of loss.", process_fnol),
    ("DocumentParser", "turn the submitted documents into structured data.", parse_documents),
    ("CoverageAgent", "check what the policy covers for this loss.", verify_coverage),
    ("FraudScreener", "screen the claim for fraud red flags.", screen_for_fraud),
    ("AssessmentAgent", "estimate the payout within deductible and limit.", assess_damage),
    ("DecisionAgent", "decide APPROVE, DENY or ESCALATE.", make_decision),
    ("ComplianceAgent", "validate the decision before anything is paid.", validate_compliance),
]
AGENTS = [
    make_agent(name, job, tool, PIPELINE[i + 1][0] if i + 1 < len(PIPELINE) else None)
    for i, (name, job, tool) in enumerate(PIPELINE)
]

Seven near-identical agents are a job for a function. PIPELINE lists them in order; the list comprehension gives agent i the handoff target PIPELINE[i + 1], and the last one gets []. The prompt's key phrase: "without changing any number, decision or flag" — the LLM narrates, it doesn't edit.

Step 7 — run it, and keep PII out of the prompt

Python · claims_pipeline.py · run_claim
async def run_claim(case_inputs: dict, verbose: bool = True) -> dict:
    workflow = AgentWorkflow(
        agents=AGENTS, root_agent="FNOLAgent",
        initial_state={"claim": {}, "audit_log": []},  # AgentWorkflow pastes THIS into the
    )                                                   # first prompt — so no PII goes in it
    ctx = Context(workflow)
    await ctx.store.set("case_inputs", case_inputs)     # raw claim data: tools only
    handler = workflow.run(user_msg="A new auto claim was submitted. Process it.",
                           ctx=ctx, max_iterations=60)  # 7 agents × ~3 steps: 20 is too few
    last = None
    async for ev in handler.stream_events():
        if verbose and isinstance(ev, AgentStream) and ev.current_agent_name != last:
            last = ev.current_agent_name
            print(f"\n== {last} " + "=" * (50 - len(last)))
        if verbose and isinstance(ev, AgentStream) and ev.delta:
            print(ev.delta, end="", flush=True)
        if verbose and isinstance(ev, ToolCall) and ev.tool_name == "handoff":
            print(f"\n   🔀 → {ev.tool_kwargs.get('to_agent')}: {ev.tool_kwargs.get('reason')}")
    await handler
    return await ctx.store.get("state")


if __name__ == "__main__":
    inputs = R.sample_state(suspicious="--suspicious" in sys.argv)
    state = asyncio.run(run_claim(inputs))
    c = state["claim"]
    print(f"\n\nRESULT {c['claim_id']}: {c['decision']}  payout ${c['estimated_payout']:,.0f}  "
          f"fraud {c['fraud_score']}/100  gates {c['human_review_gates'] or 'none'}  "
          f"compliance {c['compliance_issues'] or 'OK'}")
    print("\nAudit log (append-only, PII redacted):")
    for row in state["audit_log"]:
        print(f"  {row['ts']}  {row['agent']:16} {row['action']:18} {row['details'][:90]}")
⚠️ A real privacy trap we found while testing

AgentWorkflow copies "Current state: {…}" into the first prompt (7.5). Put Sarah's claim form into initial_state and her name and policy number go straight to the LLM provider — we checked with a test that captures every prompt. The fix: keep the raw inputs under a separate store key ("case_inputs") that only tools read, and keep initial_state free of personal data. The shipped test asserts that "Sarah Chen" never appears in any prompt.

== FNOLAgent ======================================== FNOL processed. Claim CLM-2026-3F8A2C41, type auto. 🔀 → DocumentParser: claim record created == DocumentParser =================================== Parsed 4 documents. Front bumper crushed, grille cracked; left headlight shattered. Missing: none. == CoverageAgent ==================================== Covered under Part D §1 Collision: limit $50,000, deductible $500. == FraudScreener ==================================== Fraud score 0/100. No red flags. Recommendation: proceed. == AssessmentAgent ================================== front bumper $2,600, headlight assembly $1,100, labour $600 = $4,300 gross − $500 deductible → $3,800 == DecisionAgent ==================================== APPROVE: covered under Part D §1 Collision … fraud score 0/100 with no red flags … == ComplianceAgent ================================== Decision validated. Compliant. Audit log (append-only, PII redacted): FNOLAgent claim created type=auto … ComplianceAgent validated compliant

A sample run: the agents' wording varies; the numbers come from the rules and don't. With --suspicious the fraud score is 60 and the decision is ESCALATE.

Step 8 — test invariants, not wording

Python · test_claims_rules.py
import copy

import pytest

import claims_rules as R


def run(**changes):
    """Run the whole pipeline offline on a copy of the sample, with some inputs changed."""
    state = copy.deepcopy(R.sample_state())
    for key, value in changes.items():
        if key == "repair_items":
            state["claim_form"] = {**state["claim_form"], "repair_items": value}
        else:
            state[key] = value
    return R.run_offline(state)["claim"]


def test_happy_path_matches_the_sample_run():
    c = run()
    assert (c["decision"], c["estimated_payout"], c["fraud_score"]) == ("APPROVE", 3800, 0)


@pytest.mark.parametrize("costs", [[100], [4_300], [80_000], [250_000]])
def test_payout_is_never_negative_and_never_above_the_limit(costs):
    c = run(repair_items=[{"item": "x", "cost": k} for k in costs])
    assert 0 <= c["estimated_payout"] <= c["applicable_limit"]


def test_a_fraud_flag_is_never_auto_approved():
    c = run(claims_history=[{}, {}, {}], fnol_date="2026-05-20")      # 20 + 15 = 35 → still fine
    assert c["fraud_score"] == 35 and c["decision"] == "APPROVE"
    c = run(policy={**R.SAMPLE_POLICY, "inception_date": "2026-03-20"},
            claims_history=[{}, {}, {}])                               # 25 + 20 = 45 > 40
    assert c["decision"] == "ESCALATE"


def test_missing_police_report_pauses_the_claim():
    docs = [d for d in R.SAMPLE_DOCUMENTS if d["type"] != "police_report"]
    c = run(submitted_documents=docs)
    assert c["decision"] == "ESCALATE" and "police_report" in c["missing_documents"]


def test_excluded_cause_is_denied_with_a_recognised_reason():
    form = {**R.SAMPLE_CLAIM_FORM, "description": "Collision during an amateur racing event; car hit a wall."}
    c = run(claim_form=form, submitted_documents=[form] + R.SAMPLE_DOCUMENTS[1:])
    assert c["decision"] == "DENY" and c["decision_reasoning"].startswith("EXCLUSION")
    assert c["compliance_issues"] == []


def test_compliance_blocks_short_reasoning_and_skipped_stages():
    c = run()
    c["decision_reasoning"] = "ok"
    c["stages_completed"].remove("FraudScreener")
    issues = R.validate_compliance(c)
    assert "Reasoning too short for an audit" in issues
    assert any("FraudScreener" in i for i in issues)


def test_no_personal_data_in_the_audit_log():
    state = R.run_offline(copy.deepcopy(R.sample_state()))
    text = str(state["audit_log"])
    assert "Sarah Chen" not in text and "FWS-AUTO-58213" not in text


def test_an_agent_cannot_write_another_agents_fields():
    claim = run()
    with pytest.raises(PermissionError):
        R.write_fields(claim, "AssessmentAgent", "assessment", fraud_score=0)

Each test states a rule that must hold for every claim: payouts stay between 0 and the limit, a fraud flag is never auto-approved, a missing police report pauses the claim, exclusions are denied with a proper reason, compliance blocks sloppy reasoning, no personal data reaches the audit log, and no agent can overwrite another's fields. @pytest.mark.parametrize runs the payout test four times with different repair bills. These run in milliseconds, cost nothing, and would catch a bad prompt or rule change before it reaches a customer.

🧪 Simulation · the claims desk

Change the facts of the claim and watch every stage respond

Audit log (what a regulator would read)

Section 9 · Part 2 — Escalation and production

When the rules raise a flag — and running it for real

9.4Fraud investigation as a debate

The screener's rules catch obvious patterns. But a flag is not a verdict — and a system that only looks for fraud will find it everywhere, including in honest claims. Wrongful accusations damage customers, invite regulators, and can lead to bad-faith litigation. So flagged claims go to a small adversarial team, the peer-to-peer debate style from 7.2.

🧠 Analogy — prosecution, defence, and a careful senior investigator

One investigator builds the strongest case for fraud. Another — a consumer advocate — gives an innocent explanation for every red flag. A senior investigator weighs the quality of evidence on both sides. Real Special Investigations Units work by weighing evidence for and against; the multi-agent version makes that discipline structural.

Escalatedfraud score 60 Fraud advocatecase FOR fraud Legitimacy advocaterebuts, sees opening Investigationdecision → referral strong indicators→ refer to SIU likely fraud→ human review inconclusive→ proceed with care likely legitimate→ clear the flag sequential on purpose: the defence answers the prosecution's actual argument
Unlike the bull and bear in 8.4 (parallel, blind to each other), these advocates run in sequence on a shared conversation, so the rebuttal addresses the opening. In production, three evidence-gathering agents would run in parallel first (documents, claim history, network links).
ReferralWhat happens next
strong_fraud_indicatorsRefer to the Special Investigations Unit, with the evidence and the debate transcript
likely_fraudFlag for human review by a senior adjuster
inconclusiveResume with caution: an adjuster double-checks before payment
likely_legitimateClear the flag and resume normal processing

None of these says "fraud". Fraud is a legal conclusion with a high bar of proof; the strongest thing an automated system should produce is a referral.

The code

Python · fraud_investigation.py · FraudArgument and routing
import asyncio
from typing import Literal

from dotenv import load_dotenv
from llama_index.core.agent.workflow import AgentStream, AgentWorkflow, FunctionAgent
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI
from pydantic import BaseModel, Field, ValidationError

import claims_rules as R

load_dotenv()
llm = OpenAI(model="gpt-4o")


class FraudArgument(BaseModel):
    position: Literal["fraud", "legitimate"]
    confidence: float = Field(ge=0.0, le=1.0)
    evidence: list[str]
    reasoning: str
    weaknesses: list[str]          # each side must name the holes in its OWN case


Referral = Literal["strong_fraud_indicators", "likely_fraud", "inconclusive", "likely_legitimate"]
ROUTING = {                        # code, not the LLM, decides where the claim goes next
    "strong_fraud_indicators": "Refer to the Special Investigations Unit (SIU)",
    "likely_fraud": "Flag for human review by a senior adjuster",
    "inconclusive": "Resume with caution: adjuster double-checks before payment",
    "likely_legitimate": "Clear the flag and resume normal processing",
}
  1. Literal["fraud", "legitimate"] allows only those two words; Field(ge=0.0, le=1.0) keeps confidence between 0 and 1. A reply of confidence=72 fails validation.
  2. weaknesses: each side must name the holes in its own case. That makes arguments more honest and tells the decision agent exactly where each side is thin.
  3. ROUTING is a plain dictionary: the LLM picks a label; code decides where the claim goes.
Python · fraud_investigation.py · the three tools
async def get_case_file(ctx: Context) -> str:
    """Return the evidence both advocates must argue from (no personal data)."""
    claim = (await ctx.store.get("case"))["claim"]    # the escalated claim, tools only
    return (f"Claim {claim['claim_id']} ({claim['claim_type']}), loss {claim['date_of_loss']}.\n"
            f"Description: {R.redact(claim['description'], claim)}\n"
            f"Fraud score: {claim['fraud_score']}/100. Red flags: {claim['red_flags']}\n"
            f"Coverage: {claim['coverage_reasoning']}\n"
            f"Documents: {[d['type'] for d in claim['parsed_documents']]}; "
            f"damage: {claim['damage_description']}\nPayout at stake: ${claim['estimated_payout']:,.0f}")


async def submit_argument(ctx: Context, position: str, confidence: float,
                          evidence: list[str], reasoning: str, weaknesses: list[str]) -> str:
    """Save your structured argument. position must be 'fraud' or 'legitimate'; confidence 0-1."""
    try:
        arg = FraudArgument(position=position, confidence=confidence, evidence=evidence,
                            reasoning=reasoning, weaknesses=weaknesses)
    except ValidationError as e:                       # the LLM gets the error and can retry
        return f"REJECTED, fix and resubmit: {e.errors()[0]['msg']}"
    state = await ctx.store.get("state")
    state["arguments"][arg.position] = arg.model_dump()
    await ctx.store.set("state", state)
    return f"{arg.position} argument saved (confidence {arg.confidence:.2f})."


async def produce_fraud_determination(ctx: Context, referral: Referral,
                                      confidence: float, rationale: str) -> str:
    """Record the referral signal after BOTH arguments are in."""
    if referral not in ROUTING:                          # the type hint shapes the schema the
        return f"REJECTED: referral must be one of {list(ROUTING)}"   # LLM sees; it doesn't CHECK
    state = await ctx.store.get("state")
    if set(state["arguments"]) != {"fraud", "legitimate"}:   # guardrail: hear both sides
        return "REFUSED: both the fraud and the legitimacy arguments are required first."
    state["determination"] = {"referral": referral, "confidence": confidence,
                              "rationale": rationale, "next_step": ROUTING[referral]}
    await ctx.store.set("state", state)
    case = await ctx.store.get("case")
    R.log_audit(case, "InvestigationDecision", f"referral {referral}", rationale)
    await ctx.store.set("case", case)
    return f"{referral} → {ROUTING[referral]}"
  1. get_case_file reads the escalated claim from a separate store key and returns it redacted — the debaters argue from evidence, not identity.
  2. submit_argument validates with Pydantic. On a ValidationError it returns "REJECTED, fix and resubmit: …" — the LLM sees the message and retries with a valid value.
  3. A lesson from testing: the referral: Referral type hint shapes the schema the LLM is shown, but LlamaIndex does not enforce it when the call arrives. Our test sent referral="fraud" and it got through to a KeyError. Hence the explicit if referral not in ROUTING check. Type hints describe; code must still check.
  4. "Hear both sides" guardrail: the decision tool refuses to record a referral until both arguments exist.
Python · fraud_investigation.py · three agents
ARGUE = ("First call get_case_file once. Then call submit_argument once with your structured "
         "argument, citing specific evidence and listing the weaknesses of your OWN argument.")

fraud_advocate = FunctionAgent(
    name="FraudAdvocate", description="Argues the case for fraud.",
    system_prompt=("You are an insurance fraud investigator. Build the strongest possible case "
                   "that this claim is fraudulent. " + ARGUE + " Then hand off to LegitimacyAdvocate."),
    llm=llm, tools=[get_case_file, submit_argument], can_handoff_to=["LegitimacyAdvocate"])

legitimacy_advocate = FunctionAgent(
    name="LegitimacyAdvocate", description="Argues the claim is legitimate.",
    system_prompt=("You are a consumer-protection advocate. Build the strongest possible case "
                   "that this claim is legitimate; give an innocent explanation for EVERY red "
                   "flag. " + ARGUE + " Then hand off to InvestigationDecision."),
    llm=llm, tools=[get_case_file, submit_argument], can_handoff_to=["InvestigationDecision"])

investigation_decision = FunctionAgent(
    name="InvestigationDecision", description="Weighs both arguments.",
    system_prompt=("You are the senior fraud investigator. Weigh both arguments above on evidence "
                   "quality, not on confidence alone. Call produce_fraud_determination once with "
                   "a referral: strong_fraud_indicators, likely_fraud, inconclusive or "
                   "likely_legitimate. You never declare fraud: that is a legal conclusion."),
    llm=llm, tools=[produce_fraud_determination], can_handoff_to=[])

Both advocates share the same instructions (ARGUE) and the same two tools; only their side differs. The handoff chain is fixed — fraud advocate → legitimacy advocate → decision — and the decision agent has can_handoff_to=[]. Its prompt ends with the rule that matters most: "You never declare fraud."

Python · fraud_investigation.py · investigate
async def investigate(claim_state: dict) -> dict:
    """claim_state: the pipeline's final state (claim + audit_log) for an ESCALATED claim."""
    workflow = AgentWorkflow(
        agents=[fraud_advocate, legitimacy_advocate, investigation_decision],
        root_agent="FraudAdvocate",
        initial_state={"arguments": {}, "determination": None},
    )
    ctx = Context(workflow)
    await ctx.store.set("case", claim_state)           # claim + audit log: kept out of "state"
    handler = workflow.run(user_msg="Investigate the escalated claim.", ctx=ctx, max_iterations=40)
    last = None
    async for ev in handler.stream_events():
        if isinstance(ev, AgentStream) and ev.current_agent_name != last:
            last = ev.current_agent_name
            print(f"\n== {last} " + "=" * (40 - len(last)))
        if isinstance(ev, AgentStream) and ev.delta:
            print(ev.delta, end="", flush=True)
    await handler
    state, case = await ctx.store.get("state"), await ctx.store.get("case")
    return {**state, "audit_log": case["audit_log"]}


if __name__ == "__main__":
    escalated = R.run_offline(R.sample_state(suspicious=True))   # stage 1: pipeline rules
    print("Pipeline decision:", escalated["claim"]["decision"], "→ starting the investigation")
    result = asyncio.run(investigate(escalated))
    for side, arg in result["arguments"].items():
        print(f"\n{side.upper():10} confidence {arg['confidence']:.2f} · weaknesses: {arg['weaknesses']}")
    d = result["determination"]
    print(f"\nREFERRAL: {d['referral']} → {d['next_step']}\nWhy: {d['rationale']}")

The escalated claim goes under the store key "case", not into initial_state — same privacy rule as 9.3. The __main__ block first runs the free rules on the suspicious claim (stage 1, ESCALATE), then hands the result to the debate (stage 2): the single agent + escalation hybrid from 7.2, built from a pipeline.

Pipeline decision: ESCALATE → starting the investigation FRAUD confidence 0.70 · weaknesses: ['no direct evidence the loss was staged'] LEGITIMATE confidence 0.55 · weaknesses: ['the 38-day reporting delay is unexplained'] REFERRAL: likely_fraud → Flag for human review by a senior adjuster Why: Three independent red flags; the innocent explanations are plausible but undocumented.

A sample run. Referral labels vary with the evidence and the model; the routing for each label never does.

9.5Production in a regulated world

Regulation is a patchwork, not one rulebook

WhereWhat appliesWhat it means for agents
United StatesInsurance is regulated state by state; most claims-handling rules descend from the NAIC's model Unfair Claims Settlement Practices Act, enforced through market-conduct examsA denial must cite the specific policy provision and, in many states, tell the claimant they can contact the state Department of Insurance. Suspected fraud is usually reportable to a state fraud bureau.
European UnionSolvency II (capital and risk), GDPR (data), the AI ActThe AI Act lists risk assessment and pricing of life and health insurance for individuals as high-risk; an auto-claims pipeline isn't automatically high-risk, but transparency and data-protection duties still apply.
Explainability"The AI said no" is not a denial reason. → the decision agent's full reasoning chain, citing clauses.
Non-discriminationNo unfair outcomes by race, gender, religion or disability; historical data can hide bias. → test any predictive model for disparate impact.
TimelinessOften: acknowledge within ~15 days, resolve within 30–45. → track deadlines per claim; escalate before they're missed.
PrivacyMedical records, IDs, finances. → least-privilege access, redaction, retention limits.
💡 Ground agents in the current rulebook

Rules change and differ by state. Rather than trusting a model's memory, index the insurer's own coverage manuals, claims-handling guidelines and retention schedules with RAG (or a knowledge graph), so agents cite today's internal policy.

The audit trail is the product

For every claim, a regulator should be able to read: which documents arrived and when; what was extracted (and how confident the extraction was); which policy section was applied and how; which fraud checks ran and what they found; the itemised payout; the complete decision reasoning; which compliance rules were applied; and whether a human reviewed it and what they decided. Store it append-only — an event stream (Kafka, AWS EventBridge) or a database table with cryptographic integrity checks.

Human-in-the-loop gates belong in configuration

The five gates from the lab — high value, fraud flag, ambiguous coverage, regulated claim types (bodily injury, total loss, sometimes minors), incomplete documents — should be settings, not code edits. A paused claim keeps its place and its state; nothing downstream runs until the gate clears. Tune them with care: too tight and adjusters drown in false alarms, too loose and the errors you most wanted a human to catch slip through. For rare one-offs (an unusual document type, a strange regulatory query) the pipeline can spawn a short-lived ephemeral agent for that claim alone.

💰 Finance corner — data protection in three rules
  • Access per agent: the parser sees documents but not claims history; the fraud agent sees history but not medical records (our DATA_ACCESS).
  • Redact logs: name and policy number become an opaque token tied to the claim ID (our redact).
  • Retain, then purge: keep claim data and agent logs for the regulatory period — often 5–7 years after the claim closes, longer with litigation or minors — then delete automatically.

Underwriting: a pipeline with a parallel step

Deciding whether to insure a new driver needs three independent lookups — credit, driving record, property value. They don't depend on each other (pooled work, 7.1), so they run at the same time inside an otherwise sequential flow.

Python · underwriting_enrichment.py · enrich_application
import asyncio
import time

# Credit-based insurance scores are banned or restricted in some states (for auto
# insurance, e.g. California, Hawaii, Massachusetts) and pulling a consumer report
# triggers FCRA duties. So the check is switched per jurisdiction, in config — not in a prompt.
CREDIT_CHECK_ALLOWED = {"TX": True, "FL": True, "CA": False, "HI": False, "MA": False}
TIMEOUT_S = 2.0                     # one slow provider must not stall the whole application


async def check_credit(applicant_id: str) -> dict:
    await asyncio.sleep(1.0)        # pretend: a credit-bureau API call
    return {"insurance_score": 742}


async def check_driving_record(license_number: str) -> dict:
    await asyncio.sleep(1.2)        # pretend: a motor-vehicle-records API call
    return {"violations_3y": 1, "at_fault_accidents_3y": 0}


async def check_property_value(address: str) -> dict:
    await asyncio.sleep(3.0)        # pretend: a SLOW valuation API (will time out)
    return {"estimated_value": 615_000}


async def _guarded(coro) -> dict:
    """Run one check with a timeout; a failure becomes a note, not a crash."""
    try:
        return await asyncio.wait_for(coro, timeout=TIMEOUT_S)
    except Exception as e:
        return {"status": "unavailable → manual review", "reason": type(e).__name__}


async def enrich_application(application: dict) -> dict:
    """Run the enrichment checks concurrently and return all results."""
    checks = {
        "driving": check_driving_record(application["license_number"]),
        "property": check_property_value(application["address"]),
    }
    if CREDIT_CHECK_ALLOWED.get(application["state"], False):
        checks["credit"] = check_credit(application["applicant_id"])
    results = await asyncio.gather(*[_guarded(c) for c in checks.values()])
    out = dict(zip(checks, results))
    if "credit" not in checks:
        out["credit"] = {"status": f"skipped: not permitted in {application['state']}"}
    return out
  1. CREDIT_CHECK_ALLOWED: credit-based insurance scoring is banned or restricted in some states (for auto, e.g. California, Hawaii and Massachusetts), and pulling a consumer report triggers duties under the Fair Credit Reporting Act. That decision lives in configuration, per jurisdiction — never in a prompt.
  2. asyncio.wait_for(…, timeout=2.0) inside _guarded: one slow provider becomes "unavailable → manual review" instead of stalling the application.
  3. dict(zip(checks, results)) pairs each name with its result — gather keeps the order you gave it.
TX: 2.0s (one after another it would take 4.2s) driving {'violations_3y': 1, 'at_fault_accidents_3y': 0} property {'status': 'unavailable → manual review', 'reason': 'TimeoutError'} credit {'insurance_score': 742} CA: 2.0s (one after another it would take 3.2s) driving {'violations_3y': 1, 'at_fault_accidents_3y': 0} property {'status': 'unavailable → manual review', 'reason': 'TimeoutError'} credit {'status': 'skipped: not permitted in CA'}

Real output of the free script (the checks are canned stand-ins). In production each check would be a tool-equipped agent calling a credit bureau, a motor-vehicle-records service and a valuation API.

🎯 Interview angle — "how do you make an agent pipeline regulator-ready?"

Rules, not prompts, for anything that moves money or blocks a decision; least-privilege data access enforced in code; an append-only, PII-redacted audit log written by every step; a compliance gate with veto power that re-checks the whole record; configurable human-review gates; deadline tracking per jurisdiction; invariant tests in CI; and outputs phrased as referrals, never legal conclusions.


Interview prep

15 questions you can now answer well

Click a question, answer it out loud first, then compare. Good answers are short, give a reason, and name a trade-off.

When would you choose a multi-agent system over a single agent?

When the work is separable (independent or step-by-step, not constant back-and-forth), spans domains that would dilute one prompt, or splits into pieces that can run in parallel. Teams win on breadth-first work like researching many companies; for tightly coupled work like one codebase, a single agent with good context is usually more reliable. And each extra agent must justify its cost — a multi-agent system can use around 15× the tokens of a chat.

What goes wrong in multi-agent systems?

Three families: unclear specifications (agents misread their role or the task), misalignment between agents (they ignore or contradict each other, lose context in handoffs), and weak verification (nobody checks the final answer). Plus cost and latency. Mitigations: narrow roles, structured outputs, logged handoff reasons, a verifier or gate at the end, and tracing with a correlation ID.

Orchestrator–worker vs hierarchical — what's the difference?

Orchestrator–worker is flat: one coordinator, simple workers, all results flow back to the coordinator. Hierarchical adds levels: sub-leaders run their own teams and make local decisions, so the top agent sees summaries, not raw detail. Use hierarchical when sub-tasks need their own decomposition or the real organisation is hierarchical — e.g. a CRO over market, credit and operational risk teams.

Handoff or agent-as-tool?

Decide who owns the conversation afterwards. A handoff passes control: the specialist answers the user. An agent-as-tool keeps the manager in control so it can combine several specialists' results into one answer.

Message passing or shared state — and how do you avoid clashing writes?

Usually both: messages for control, shared state for data. To avoid clashes, give each parallel writer its own key (our committee's four *_report slots) or declare a reducer such as Annotated[list, operator.add]; otherwise LangGraph raises InvalidUpdateError. For more safety, restrict which fields each agent may write, in code.

Two agents disagree on a trade size. How does the system decide?

Non-negotiables first, in code: a fixed hierarchy (compliance > risk > PM > trader) and neutral policies (no position above 5% of NAV). For discretionary questions, negotiation (e.g. a smaller size with a tighter stop-loss) or a scoring function on Sharpe, drawdown and tail risk. Whatever wins, log why.

An agent fails mid-pipeline. What do you do?

It depends on the role and on what already happened. Compliance or risk failed → halt. Failed after a side effect (order sent) → never blindly retry; check by idempotency key and resume from a checkpoint. Transient error on a read-only tool → retry with backoff, max about 3. Repeated failures → circuit breaker. Otherwise a fallback agent, or continue and flag the gap.

How do you keep a multi-agent system's cost under control?

Most cost is duplicated input, so: prompt caching with a stable prefix; model tiering (small models for data fetching, large for synthesis — often 40–60% cheaper); routing simple questions away from the full team; fetching shared data once into state; and a token budget per agent.

How do you test something whose output changes every run?

Test at four levels — unit, integration, end-to-end, adversarial. Freeze tool responses as fixtures, pin model versions, and assert invariants (every metric scored; payout ≤ limit; a fraud flag is never auto-approved; no PII in logs) rather than exact wording. Live-API runs become scheduled smoke tests that alert rather than block.

Why compute indicators in code instead of giving the LLM a tool?

Each analyst needs exactly one data source, so a "which tool?" decision adds a call and a failure point for nothing. Computing in code is cheaper, reproducible and auditable; the LLM only interprets. Tool-calling makes sense when the agent must choose among several sources.

Explain LangGraph supersteps.

LangGraph runs every node whose inputs are ready at the same time, merges their returned updates into the state, then finds the next ready nodes. A node with several incoming edges waits for all of them — an implicit join. That's how four analysts run in parallel and the PM runs once, after all four.

How do you backtest an LLM trading agent honestly?

Walk-forward on point-in-time data (every fetcher takes an as_of_date), starting after every model's training cutoff; include costs and slippage; run several times and report the spread; compare Sharpe, drawdown and hit rate with buy-and-hold; and re-test any change on a window it wasn't tuned on. Start small — agent backtests are expensive.

Why put the bull and the bear on different model families?

Same-model agents share blind spots, so their "disagreement" is weak. Different families disagree more genuinely. The risk: unequal strength tilts the outcome toward the stronger arguer. Test by rerunning debates with the models swapped — if verdicts flip, you're measuring the models, not the trade.

How do you keep personal data out of LLM prompts?

Give each agent a scoped view of only the data it needs; let tools move data from storage to rules without routing it through LLM arguments; redact names and IDs in anything that goes to a model or a log; and check your framework's defaults — AgentWorkflow pastes the whole initial state into the first prompt, so we kept raw inputs under a separate key. Then add a test that captures prompts and asserts the PII never appears.

Why does the fraud team output a "referral" and not a verdict?

Fraud is a legal conclusion with a high bar of proof, and a wrongful accusation can lead to bad-faith litigation and regulatory trouble. The system's strongest output is a referral (SIU, human review, proceed with care, clear) — and code, not the LLM, maps that label to the next step.


Wrap-up

What to remember

SectionBig ideaWhere you saw it in code
7 · Agent teamsSplit only separable work; pick a style; settle conflicts and failures by rolecan_handoff_to, ctx.store, asyncio.gather(return_exceptions=True)
8 · Trading committeeDeterministic fan-out / fan-in; numbers in code, judgment in LLMs; test before you trustadd_edge(START, …), parse_pm_line, two-layer risk_officer, walk_forward
9 · Insurance claimsRules decide, agents explain; least privilege; compliance has the last wordscoped_view, write_fields, validate_compliance, invariant tests
  1. A team of agents is a cost you justify with evidence — separable work, diluted prompts, real parallelism. Coupled work stays with one agent.
  2. Styles are org charts. Pipelines for audited steps, orchestrators for delegation, hierarchies for big domains, debates for disagreement, parallel for speed, evaluator loops for quality, contract-net for overlapping specialists — and production systems mix two or three.
  3. Every handoff carries a reason; every request carries one ID. That's your audit trail.
  4. Failures are handled by role: retry only read-only work, guard side effects with idempotency keys, and let gates fail closed.
  5. Numbers in code, words from LLMs. Thresholds, sizes, payouts and vetoes are deterministic and testable.
  6. A backtest is only as honest as its data. Point-in-time inputs, post-cutoff windows, several runs, costs included.
  7. In regulated work, design for the auditor first: least privilege, redaction, an append-only log, human gates, referrals not verdicts.

QuizCheck yourself


Appendix

Complete code for every lab

Everything you need is on this page — nothing to download. Create the folders below, then create each file with exactly the name shown and paste the code in. The walkthroughs above explain each part; these are the full files, including imports, sample data and the run block at the bottom.

sections7-9_labs/ ├── .env # OPENAI_API_KEY=... ANTHROPIC_API_KEY=... ├── section7_health_analyzer/ │ ├── health_analyzer.py │ └── portfolio_parallel.py ├── section8_trading_committee/ │ ├── investment_committee.py │ ├── superstep_demo.py # free │ ├── backtest.py # --dry-run is free │ └── adversarial_debate.py └── section9_insurance_claims/ ├── claims_rules.py # free ├── test_claims_rules.py # free ├── claims_pipeline.py ├── fraud_investigation.py └── underwriting_enrichment.py # free
Terminal · set up once (Python 3.10+)
python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install llama-index-core llama-index-llms-openai langgraph langchain-anthropic \
            langchain-openai yfinance pandas numpy pydantic python-dotenv pytest
# .env in the top folder (scripts in sub-folders find it automatically):
#   OPENAI_API_KEY=sk-...
#   ANTHROPIC_API_KEY=sk-ant-...
📄 Section 7 · health_analyzer.py section7_health_analyzer/health_analyzer.py

4-agent LlamaIndex pipeline. Needs OPENAI_API_KEY.

section7_health_analyzer/health_analyzer.py
"""
Section 7 lab — Multi-agent financial health analyzer
=====================================================
Style: SEQUENTIAL PIPELINE with SHARED STATE and EXPLICIT HANDOFFS
       (built with LlamaIndex AgentWorkflow)

    FundamentalAgent → ProfitabilityAgent → LiquidityAgent → SupervisorAgent

    • Tools do the deterministic work (fetch numbers, compare with thresholds).
    • Agents (LLMs) do the judgment (score 1–10, explain, write the report).
    • Everyone reads/writes one shared "state" dict that lives in ctx.store.

How to run
----------
1. pip install llama-index-core llama-index-llms-openai yfinance python-dotenv
2. Put your key in a .env file (in this folder or the folder above):
       OPENAI_API_KEY=sk-...
3. python health_analyzer.py            # analyses AAPL
   python health_analyzer.py MSFT       # any ticker
   python health_analyzer.py JPM        # a bank: watch the rubric warning!

Cost: one run ≈ 10–14 LLM calls on MODEL (a few cents).
Data: yfinance (free, no key). For learning only — not investment advice.
"""

import asyncio
import sys

import yfinance as yf
from dotenv import load_dotenv
from llama_index.core.agent.workflow import (
    AgentStream,
    AgentWorkflow,
    FunctionAgent,
    ToolCall,
)
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI

load_dotenv()                      # reads OPENAI_API_KEY from .env
MODEL = "gpt-4o"                   # any tool-calling OpenAI model works — change one line
llm = OpenAI(model=MODEL)

# Each rule: (metric label, how to read the number, function that returns a band)
# Bands are decided by CODE, so every run gives the same band for the same number.
def band_profitability(name: str, pct: float) -> str:
    """ROA / ROE / margins, given in percent (26.1 means 26.1%)."""
    limits = {                      # (strong above, weak below)
        "roa": (5, 2),
        "roe": (15, 8),
        "net_margin": (10, 5),
        "gross_margin": (40, 20),
    }
    strong, weak = limits[name]
    if pct > strong:
        return "strong"
    if pct < weak:
        return "weak"
    return "moderate"


def band_liquidity(name: str, x: float) -> str:
    """Current ratio, quick ratio, debt-to-equity and interest coverage (plain ratios)."""
    if name == "current_ratio":
        if x < 1.0:
            return "warning (below 1.0)"
        if x < 1.5:
            return "moderate"
        if x <= 3.0:
            return "healthy"
        return "healthy, but maybe idle cash (above 3.0)"
    if name == "quick_ratio":
        return "healthy" if x > 1.0 else "caution (below 1.0)"
    if name == "debt_to_equity":
        if x > 2.0:
            return "high leverage (above 2.0)"
        if x > 1.5:
            return "moderate"
        if x >= 0.3:
            return "healthy"
        return "conservative (below 0.3)"
    if name == "interest_coverage":
        if x > 3.0:
            return "healthy"
        if x >= 1.5:
            return "moderate"
        return "distress risk (below 1.5)"
    raise ValueError(name)

def fetch_ratios(ticker: str) -> dict:
    """Plain Python, no LLM: pull the raw numbers from Yahoo Finance."""
    t = yf.Ticker(ticker)
    info = t.info or {}

    def pct(key):                   # 0.2613 → 26.13 (percent)
        v = info.get(key)
        return round(v * 100, 2) if v is not None else None

    d_e = info.get("debtToEquity")  # Yahoo gives 151.9 meaning 1.519×
    ratios = {
        "roa": pct("returnOnAssets"),
        "roe": pct("returnOnEquity"),
        "net_margin": pct("profitMargins"),
        "gross_margin": pct("grossMargins"),
        "current_ratio": info.get("currentRatio"),
        "quick_ratio": info.get("quickRatio"),
        "debt_to_equity": round(d_e / 100, 2) if d_e is not None else None,
        "interest_coverage": None,
    }
    try:                            # EBIT ÷ interest expense, latest fiscal year
        inc = t.income_stmt
        ebit = inc.loc["EBIT"].iloc[0]
        interest = abs(inc.loc["Interest Expense"].iloc[0])
        if interest:
            ratios["interest_coverage"] = round(float(ebit / interest), 2)
    except Exception:
        pass                        # some companies don't report it → stays None
    return {"sector": info.get("sector", "Unknown"), "ratios": ratios}

async def get_fundamentals(ctx: Context, ticker: str) -> str:
    """Collect the raw financial ratios for a ticker and save them in shared state."""
    data = await asyncio.to_thread(fetch_ratios, ticker)   # don't block the event loop

    state = await ctx.store.get("state")                    # 1. read the whiteboard
    state["ticker"] = ticker.upper()                        # 2. write my slots
    state["sector"] = data["sector"]
    state["ratios"] = data["ratios"]
    if data["sector"] == "Financial Services":              # banks need CET1 / LCR instead
        state["rubric_warning"] = (
            "Bank or financial firm: current ratio and debt-to-equity do not fit. "
            "Treat the liquidity scores as low-confidence."
        )
    await ctx.store.set("state", state)                     # 3. save it back
    return f"Ratios saved for {ticker.upper()} (sector: {data['sector']})."


async def get_profitability_ratios(ctx: Context) -> str:
    """Read ROA, ROE and margins from shared state and band them against the thresholds."""
    state = await ctx.store.get("state")
    rows = {}
    for name in ("roa", "roe", "net_margin", "gross_margin"):
        v = state["ratios"].get(name)
        rows[name] = {"value_pct": v,
                      "band": band_profitability(name, v) if v is not None else "missing"}
    state["profitability"] = rows
    await ctx.store.set("state", state)
    return str(rows)


async def get_liquidity_ratios(ctx: Context) -> str:
    """Read the liquidity and leverage ratios from shared state and band them."""
    state = await ctx.store.get("state")
    rows = {}
    for name in ("current_ratio", "quick_ratio", "debt_to_equity", "interest_coverage"):
        v = state["ratios"].get(name)
        rows[name] = {"value": v,
                      "band": band_liquidity(name, v) if v is not None else "missing"}
    state["liquidity"] = rows
    await ctx.store.set("state", state)
    warning = state.get("rubric_warning")
    return str(rows) + (f"\nWARNING: {warning}" if warning else "")

SCORING_RULES = (
    "Score EVERY metric from 1 to 10 and justify each score in one sentence using "
    "the actual number. Use the band from the tool as your anchor: "
    "strong/healthy = 8-10, moderate = 5-7, weak/warning/distress = 1-4. "
    "If a value is missing, say so and do not invent it."
)

fundamental_agent = FunctionAgent(
    name="FundamentalAgent",
    description="Collects the raw financial ratios for the ticker.",
    system_prompt=(
        "You are the fundamental data analyst. Call get_fundamentals EXACTLY ONCE "
        "for the ticker in the user's request, then hand off to ProfitabilityAgent."
    ),
    llm=llm,
    tools=[get_fundamentals],
    can_handoff_to=["ProfitabilityAgent"],
)

profitability_agent = FunctionAgent(
    name="ProfitabilityAgent",
    description="Scores profitability: ROA, ROE, net margin, gross margin.",
    system_prompt=(
        "You are the profitability analyst. Call get_profitability_ratios EXACTLY ONCE. "
        + SCORING_RULES + " Then hand off to LiquidityAgent."
    ),
    llm=llm,
    tools=[get_profitability_ratios],
    can_handoff_to=["LiquidityAgent"],
)

liquidity_agent = FunctionAgent(
    name="LiquidityAgent",
    description="Scores liquidity and leverage: current, quick, D/E, interest coverage.",
    system_prompt=(
        "You are the liquidity and solvency analyst. Call get_liquidity_ratios EXACTLY ONCE. "
        + SCORING_RULES + " If the tool returns a WARNING, repeat it. "
        "Then hand off to SupervisorAgent."
    ),
    llm=llm,
    tools=[get_liquidity_ratios],
    can_handoff_to=["SupervisorAgent"],
)

supervisor_agent = FunctionAgent(
    name="SupervisorAgent",
    description="Writes the final financial health report.",
    system_prompt=(
        "You are the head of research. Using the analysts' scores above, write the final "
        "report: (1) profitability summary, (2) liquidity summary, (3) overall health "
        "score 1-10 that is consistent with the individual scores, (4) the two biggest "
        "strengths and the two biggest concerns. If there is a rubric WARNING, put it at "
        "the top. You are the last agent: write the answer yourself, do not hand off."
    ),
    llm=llm,
    tools=[],
    can_handoff_to=[],               # [] = nobody. Leaving it out would allow ANY agent!
)

def build_workflow() -> AgentWorkflow:
    return AgentWorkflow(
        agents=[fundamental_agent, profitability_agent, liquidity_agent, supervisor_agent],
        root_agent=fundamental_agent.name,          # who receives the user's message
        initial_state={                             # the shared whiteboard, empty at start
            "ticker": "",
            "sector": "",
            "ratios": {},
            "profitability": {},
            "liquidity": {},
            "rubric_warning": None,
        },
    )

async def run_analysis(ticker: str, verbose: bool = True) -> dict:
    """Run the 4-agent pipeline once. Returns the report, the final state and the handoffs."""
    handler = build_workflow().run(
        user_msg=f"Provide the financial health analysis of {ticker}.",
        max_iterations=60,                          # default 20 is too tight for 4 agents
    )
    handoffs, last_agent = [], None
    async for event in handler.stream_events():
        if isinstance(event, ToolCall) and event.tool_name == "handoff":
            hop = (last_agent, event.tool_kwargs.get("to_agent"), event.tool_kwargs.get("reason"))
            handoffs.append(hop)                    # audit trail: who, to whom, WHY
            if verbose:
                print(f"\n   🔀 handoff {hop[0]} → {hop[1]}  (reason: {hop[2]})")
        elif isinstance(event, AgentStream):
            if event.current_agent_name != last_agent:
                last_agent = event.current_agent_name
                if verbose:
                    print(f"\n{'=' * 60}\n🤖 Active agent: {last_agent}\n{'=' * 60}")
            if verbose and event.delta:
                print(event.delta, end="", flush=True)

    result = await handler                          # the last agent's answer
    state = await handler.ctx.store.get("state")    # the whiteboard after the run
    return {"ticker": ticker.upper(), "report": str(result), "state": state, "handoffs": handoffs}


if __name__ == "__main__":
    ticker = sys.argv[1] if len(sys.argv) > 1 else "AAPL"
    out = asyncio.run(run_analysis(ticker))
    print("\n\n--- Deterministic bands saved in shared state ---")
    for section in ("profitability", "liquidity"):
        for metric, row in out["state"][section].items():
            print(f"{section:13} {metric:18} {row}")
📄 Section 7 · portfolio_parallel.py section7_health_analyzer/portfolio_parallel.py

Five companies in parallel; imports health_analyzer.py from the same folder.

section7_health_analyzer/portfolio_parallel.py
"""
Section 7 lab — extension: analyse a whole portfolio IN PARALLEL
================================================================
Style: PARALLELIZATION wrapped around the SEQUENTIAL PIPELINE from health_analyzer.py.
Five independent copies of the 4-agent pipeline run at the same time, one per company.

How to run (same .env as health_analyzer.py):
    python portfolio_parallel.py
    python portfolio_parallel.py AAPL MSFT KO

Cost: about 5 × one single-company run.
"""

import asyncio
import sys
import time

from health_analyzer import run_analysis

TICKERS = ["AAPL", "MSFT", "GOOGL", "NVDA", "JPM"]   # JPM kept on purpose: a bank!


async def analyze_company(ticker: str) -> dict:
    """Run the full 4-agent pipeline for one company and time it."""
    start = time.perf_counter()
    result = await run_analysis(ticker, verbose=False)
    result["seconds"] = time.perf_counter() - start
    return result


async def analyze_portfolio(tickers: list[str]) -> list:
    # gather() starts every pipeline at once and waits for all of them.
    # return_exceptions=True: one company failing becomes ONE bad row,
    # instead of crashing the whole portfolio run.
    return await asyncio.gather(
        *[analyze_company(t) for t in tickers],
        return_exceptions=True,
    )

def print_table(tickers: list[str], results: list, wall: float) -> None:
    print(f"\n{'Ticker':7} {'ROA':>8} {'Current':>8}  {'Profitability band':20} {'Liquidity band':26} {'secs':>5}")
    print("-" * 80)
    total = 0.0
    for ticker, r in zip(tickers, results):
        if isinstance(r, Exception):                       # the degraded row
            print(f"{ticker:7} FAILED → {type(r).__name__}: {r}")
            continue
        total += r["seconds"]
        p, l = r["state"]["profitability"], r["state"]["liquidity"]
        roa, cur = p["roa"]["value_pct"], l["current_ratio"]["value"]
        print(f"{ticker:7} {str(roa) + '%' if roa is not None else 'n/a':>8} "
              f"{cur if cur is not None else 'n/a':>8}  {p['roa']['band']:20} "
              f"{l['current_ratio']['band'][:26]:26} {r['seconds']:5.1f}"
              + ("   ⚠ bank: wrong rubric" if r["state"].get("rubric_warning") else ""))
    print("-" * 80)
    print(f"Wall-clock: {wall:.1f}s   vs   sum of the runs one-by-one: {total:.1f}s")


if __name__ == "__main__":
    tickers = sys.argv[1:] or TICKERS
    t0 = time.perf_counter()
    results = asyncio.run(analyze_portfolio(tickers))
    print_table(tickers, results, time.perf_counter() - t0)
    for ticker, r in zip(tickers, results):
        if not isinstance(r, Exception):
            print(f"\n{'#' * 70}\n{ticker} — final report\n{'#' * 70}\n{r['report']}")
📄 Section 8 · investment_committee.py section8_trading_committee/investment_committee.py

The LangGraph committee. Needs ANTHROPIC_API_KEY.

section8_trading_committee/investment_committee.py
"""
Section 8 lab — An AI investment committee (LangGraph)
======================================================
Style: deterministic FAN-OUT / FAN-IN with a hierarchical synthesis.

          ┌── fundamentals (Sonnet) ──┐
          ├── technicals   (Sonnet) ──┤
  START ──┤                           ├──► portfolio_manager (Opus) ──► risk_officer ──► END
          ├── sentiment    (Haiku)  ──┤                                 (rules + Opus)
          └── macro        (Sonnet) ──┘

    • Numbers are fetched and computed in PLAIN PYTHON (yfinance + pandas).
    • LLMs only read those numbers and write short reports.
    • The graph itself is the orchestrator: no LLM decides who runs next.

How to run
----------
1. pip install langgraph langchain-anthropic yfinance pandas python-dotenv
2. .env (here or one folder up):   ANTHROPIC_API_KEY=sk-ant-...
3. python investment_committee.py            # TSLA
   python investment_committee.py MSFT

Cost: 6 LLM calls per decision. Live data: fine for TODAY's decision only
(see backtest.py for why that matters). Learning only — not investment advice.
"""

from __future__ import annotations

import re
import sys
from typing import TypedDict

import yfinance as yf
from dotenv import load_dotenv
from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage, SystemMessage
from langgraph.graph import END, START, StateGraph

load_dotenv()

# One model per cost tier. Change the names here and nowhere else.
# We never pass temperature: newer Claude models no longer accept it.
OPUS_MODEL, SONNET_MODEL, HAIKU_MODEL = "claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5"
opus = ChatAnthropic(model=OPUS_MODEL, max_tokens=2048)      # PM + risk: hardest reasoning
sonnet = ChatAnthropic(model=SONNET_MODEL, max_tokens=1500)  # three analysts
haiku = ChatAnthropic(model=HAIKU_MODEL, max_tokens=800)     # sentiment: cheap, high volume

SINGLE_NAME_CAP_PCT = 3.0     # firm-wide limit per stock — known to the risk officer ONLY
VOL_CEILING = 0.60            # 60% annualised volatility → automatic veto
MIN_CONFIDENCE = 50

class CommitteeState(TypedDict):
    ticker: str
    indicators: dict            # written by technicals; re-used by the risk officer
    fundamentals_report: str    # ┐
    technicals_report: str      # │ four analysts write four DIFFERENT keys,
    sentiment_report: str       # │ in parallel → no clash, no reducer needed
    macro_report: str           # ┘
    pm_thesis: str
    risk_verdict: str
    final_decision: str

def fetch_fundamentals(ticker: str) -> dict:
    info = yf.Ticker(ticker).info or {}
    keys = ["trailingPE", "forwardPE", "priceToBook", "returnOnEquity", "profitMargins",
            "debtToEquity", "currentRatio", "revenueGrowth", "earningsGrowth"]
    return {k: info.get(k) for k in keys}


def compute_indicators(ticker: str, period: str = "1y") -> dict:
    close = yf.Ticker(ticker).history(period=period)["Close"]
    sma_50 = close.rolling(50).mean().iloc[-1] if len(close) >= 50 else None
    sma_200 = close.rolling(200).mean().iloc[-1] if len(close) >= 200 else None
    delta = close.diff()                               # day-to-day change
    gain = delta.clip(lower=0).rolling(14).mean()      # average up-move, 14 days
    loss = (-delta.clip(upper=0)).rolling(14).mean()   # average down-move, 14 days
    rsi = (100 - 100 / (1 + gain / loss)).iloc[-1]
    vol_30d = close.pct_change().rolling(30).std().iloc[-1] * (252 ** 0.5)
    return {
        "last_close": round(float(close.iloc[-1]), 2),
        "sma_50": round(float(sma_50), 2) if sma_50 is not None else None,
        "sma_200": round(float(sma_200), 2) if sma_200 is not None else None,
        "rsi_14": round(float(rsi), 1),
        "vol_30d_annualized": round(float(vol_30d), 4),
    }


def fetch_macro_snapshot() -> dict:
    vix = yf.Ticker("^VIX").history(period="5d")["Close"].iloc[-1]
    tnx = yf.Ticker("^TNX").history(period="5d")["Close"].iloc[-1]
    spx = yf.Ticker("^GSPC").history(period="1mo")["Close"]
    return {
        "vix": round(float(vix), 2),
        "us_10y_yield_pct": round(float(tnx), 2),
        "spx_1m_return_pct": round(float((spx.iloc[-1] / spx.iloc[0] - 1) * 100), 2),
    }

GENERIC = {"inc", "inc.", "corp", "corp.", "corporation", "company", "co", "holdings",
           "group", "the", "plc", "ltd", "class", "platforms"}


def _is_about_company(title: str, ticker: str, short_name: str) -> bool:
    """Keep a headline only if it names the ticker or a meaningful word of the company name."""
    words = re.findall(r"[A-Za-z0-9&.]+", title)
    if ticker.upper() in (w.upper().strip(".") for w in words):
        return True
    name_words = [w.lower().strip(",.") for w in short_name.split()]
    key_words = [w for w in name_words if len(w) >= 4 and w not in GENERIC]
    return any(k in title.lower() for k in key_words)


def fetch_news(ticker: str, n: int = 8) -> list[str]:
    """Up to n headlines PRIMARILY about the ticker: '[date, publisher] title — first sentence'."""
    try:
        stock = yf.Ticker(ticker)
        short_name = (stock.info or {}).get("shortName", "")
        items = stock.news or []
    except Exception:
        items, short_name = [], ""
    lines = []
    for it in items:
        content = it.get("content", it)
        title = content.get("title") or it.get("title")
        if not title or not _is_about_company(title, ticker, short_name):
            continue                                   # market-wide noise → skip
        publisher = (content.get("provider") or {}).get("displayName", "")
        pub_date = (content.get("pubDate") or "").split("T", 1)[0]
        summary = (content.get("summary") or content.get("description") or "").strip()
        m = re.search(r"([^.!?]*[.!?])", summary)
        first = m.group(1).strip() if m else summary[:200]
        meta = ", ".join(p for p in (pub_date, publisher) if p)
        line = (f"[{meta}] " if meta else "") + title + (f" — {first}" if first else "")
        lines.append(line)
        if len(lines) >= n:
            break
    return lines

def fundamentals_analyst(state: CommitteeState) -> dict:
    data = fetch_fundamentals(state["ticker"])                       # 1. numbers, in code
    sys_msg = SystemMessage(content=(                                # 2. role + output shape
        "You are a senior equity fundamentals analyst. Given the ratios, write a SHORT "
        "report (max 150 words) covering: (1) valuation stance, (2) profitability, "
        "(3) balance-sheet strength, (4) growth. Conclude with a tilt: "
        "BULLISH / NEUTRAL / BEARISH on fundamentals."))
    msg = HumanMessage(content=f"Ticker: {state['ticker']}\nRatios: {data}")
    out = sonnet.invoke([sys_msg, msg])                              # 3. the right tier
    return {"fundamentals_report": out.content}                      # 4. ONLY my own key


def technicals_analyst(state: CommitteeState) -> dict:
    ind = compute_indicators(state["ticker"])
    sys_msg = SystemMessage(content=(
        "You are a technical analyst. Given price-derived indicators, write a SHORT report "
        "(max 120 words) on trend (price vs SMA50/SMA200), momentum (RSI) and volatility. "
        "Conclude with: BULLISH / NEUTRAL / BEARISH on technicals."))
    msg = HumanMessage(content=f"Ticker: {state['ticker']}\nIndicators: {ind}")
    out = sonnet.invoke([sys_msg, msg])
    return {"technicals_report": out.content, "indicators": ind}     # keep the snapshot


def sentiment_analyst(state: CommitteeState) -> dict:
    headlines = fetch_news(state["ticker"])
    body = "\n- ".join(headlines) if headlines else "(no headlines available)"
    sys_msg = SystemMessage(content=(
        "You are a news sentiment analyst. Each line is one article, already filtered to "
        "be primarily about the ticker, formatted '[date, publisher] title — first sentence'. "
        "Use the metadata, not just the title:\n"
        "- Weight RECENT articles more heavily (sentiment decays).\n"
        "- Treat tier-1 financial press (Reuters, Bloomberg, WSJ, FT) as harder evidence "
        "than opinion outlets or blogs.\n"
        "- If coverage is concentrated in one publisher, flag a possible PR push.\n"
        "Produce a SHORT report (max 120 words) and score sentiment as: "
        "POSITIVE / MIXED / NEGATIVE."))
    msg = HumanMessage(content=f"Ticker: {state['ticker']}\nHeadlines:\n- {body}")
    out = haiku.invoke([sys_msg, msg])
    return {"sentiment_report": out.content}


def macro_analyst(state: CommitteeState) -> dict:
    macro = fetch_macro_snapshot()                    # no ticker: the market regime
    sys_msg = SystemMessage(content=(
        "You are a macro strategist. Given a short macro snapshot, write a SHORT report "
        "(max 120 words) on the regime (risk-on / risk-off / neutral) and what it implies "
        "for a single-name long-only equity position."))
    msg = HumanMessage(content=f"Macro snapshot: {macro}")
    out = sonnet.invoke([sys_msg, msg])
    return {"macro_report": out.content}

PM_LINE_RE = re.compile(
    r"ACTION\s*=\s*(BUY|HOLD|SELL)\s*;\s*CONFIDENCE\s*=\s*(\d+)\s*;\s*SIZE_PCT\s*=\s*([\d.]+)",
    re.IGNORECASE)


def parse_pm_line(thesis: str) -> tuple[str, int, float] | None:
    """Read 'ACTION=BUY; CONFIDENCE=68; SIZE_PCT=2.0' → ('BUY', 68, 2.0). None if missing."""
    matches = PM_LINE_RE.findall(thesis)
    if not matches:
        return None
    action, conf, size = matches[-1]                  # the LAST such line wins
    return action.upper(), int(conf), float(size)


def portfolio_manager(state: CommitteeState) -> dict:
    sys_msg = SystemMessage(content=(
        "You are the Portfolio Manager. Synthesise the four analyst reports into a single "
        "thesis (max 250 words). End STRICTLY with one line of the form:\n"
        "ACTION=<BUY|HOLD|SELL>; CONFIDENCE=<0-100>; SIZE_PCT=<0.0-5.0>\n\n"
        "SIZE_PCT is the target position as % of TOTAL PORTFOLIO NAV. Size purely on your "
        "conviction; do not anticipate any downstream review. Scale:\n"
        "  0.0      -> HOLD or SELL (no new long exposure)\n"
        "  0.5-1.0  -> probe / starter position when conviction is mixed\n"
        "  1.0-2.0  -> standard BUY at moderate conviction (CONFIDENCE 50-70)\n"
        "  2.0-3.0  -> strong BUY at high conviction (CONFIDENCE 70+)\n"
        "  3.1-5.0  -> concentrated bet: only if EVERY analyst is bullish AND macro supports it\n"
        "A BUY at SIZE_PCT=0 is incoherent — pick HOLD instead. "
        "A HOLD or SELL must have SIZE_PCT=0."))
    msg = HumanMessage(content=(
        f"Ticker: {state['ticker']}\n\n"
        f"--- Fundamentals ---\n{state['fundamentals_report']}\n\n"
        f"--- Technicals ---\n{state['technicals_report']}\n\n"
        f"--- Sentiment ---\n{state['sentiment_report']}\n\n"
        f"--- Macro ---\n{state['macro_report']}"))
    out = opus.invoke([sys_msg, msg])
    return {"pm_thesis": out.content}

VERDICT_RE = re.compile(r"VERDICT\s*=\s*(APPROVED|REJECTED)", re.IGNORECASE)


def risk_officer(state: CommitteeState) -> dict:
    vol = state["indicators"]["vol_30d_annualized"]      # the SAME snapshot the analyst saw
    parsed = parse_pm_line(state["pm_thesis"])

    # Layer 1 — hard rules in code. Numbers are compared by Python, never by the LLM.
    problems = []
    if vol > VOL_CEILING:
        problems.append(f"realized 30d vol {vol:.1%} exceeds the {VOL_CEILING:.0%} ceiling")
    if parsed is None:
        problems.append("PM thesis has no valid ACTION/CONFIDENCE/SIZE_PCT line")
    else:
        action, conf, size = parsed
        if action == "BUY" and size > SINGLE_NAME_CAP_PCT:
            problems.append(f"SIZE_PCT {size} is above the {SINGLE_NAME_CAP_PCT}% single-name cap")
        if action == "BUY" and conf < MIN_CONFIDENCE:
            problems.append(f"CONFIDENCE {conf} is below {MIN_CONFIDENCE}")
        if (action == "BUY") != (size > 0):
            problems.append(f"incoherent line: {action} with SIZE_PCT={size}")
    if problems:
        return {"risk_verdict": "VETO: " + "; ".join(problems),
                "final_decision": "HOLD (risk veto)"}

    action = parsed[0]
    if action != "BUY":                                  # nothing to approve: no new risk
        return {"risk_verdict": f"No new long exposure ({action}).", "final_decision": action}

    # Layer 2 — the judgment call an LLM is good at: did the thesis ignore the macro picture?
    sys_msg = SystemMessage(content=(
        "You are the Chief Risk Officer. The numeric limits have ALREADY been checked in code. "
        "Your only job: REJECT if the thesis recommends BUY while ignoring or dismissing "
        "material macro headwinds described in the macro report; otherwise APPROVE. "
        "Reply STRICTLY: VERDICT=<APPROVED|REJECTED>; REASON=<one sentence>"))
    msg = HumanMessage(content=(
        f"Macro report:\n{state['macro_report']}\n\nPM thesis:\n{state['pm_thesis']}"))
    out = opus.invoke([sys_msg, msg])
    m = VERDICT_RE.search(out.content)
    verdict = m.group(1).upper() if m else "REJECTED"   # unreadable answer → fail SAFE
    final = action if verdict == "APPROVED" else "HOLD (risk rejected)"
    return {"risk_verdict": out.content, "final_decision": final}

def build_committee():
    g = StateGraph(CommitteeState)
    g.add_node("fundamentals", fundamentals_analyst)
    g.add_node("technicals", technicals_analyst)
    g.add_node("sentiment", sentiment_analyst)
    g.add_node("macro", macro_analyst)
    g.add_node("portfolio_manager", portfolio_manager)
    g.add_node("risk_officer", risk_officer)
    for analyst in ("fundamentals", "technicals", "sentiment", "macro"):
        g.add_edge(START, analyst)                 # fan-out: all four start together
        g.add_edge(analyst, "portfolio_manager")   # fan-in: PM waits for all four
    g.add_edge("portfolio_manager", "risk_officer")
    g.add_edge("risk_officer", END)
    return g.compile()


COMMITTEE = build_committee()                      # compile once, reuse for every ticker


def run_committee(ticker: str) -> dict:
    initial: CommitteeState = {
        "ticker": ticker.upper(), "indicators": {},
        "fundamentals_report": "", "technicals_report": "",
        "sentiment_report": "", "macro_report": "",
        "pm_thesis": "", "risk_verdict": "", "final_decision": "",
    }
    return COMMITTEE.invoke(initial)

if __name__ == "__main__":
    ticker = sys.argv[1] if len(sys.argv) > 1 else "TSLA"
    result = run_committee(ticker)
    print("=" * 80)
    print(f"FINAL DECISION for {ticker.upper()}: {result['final_decision']}")
    print("=" * 80)
    print("--- PM thesis ---\n" + result["pm_thesis"])
    print("\n--- Risk verdict ---\n" + result["risk_verdict"])
📄 Section 8 · superstep_demo.py section8_trading_committee/superstep_demo.py

Free: no key, no LLM.

section8_trading_committee/superstep_demo.py
"""
Section 8 — FREE demo (no API key, no LLM): how LangGraph runs a fan-out / fan-in graph
======================================================================================
Shows three things you will be asked about in interviews:
  1. SUPERSTEPS  – all nodes whose inputs are ready run together, then state is merged.
  2. IMPLICIT JOIN – a node with several incoming edges waits for ALL of them.
  3. REDUCERS    – two parallel nodes writing the SAME key crash… unless you add a reducer.

How to run:   python superstep_demo.py
"""

import operator
import time
from typing import Annotated, TypedDict

from langgraph.errors import InvalidUpdateError
from langgraph.graph import END, START, StateGraph


def slow_node(name: str, key: str, seconds: float):
    """Build a node that 'thinks' for a while, then writes one key."""
    def node(state):
        time.sleep(seconds)                       # stands in for an LLM call
        return {key: f"{name} done"}
    return node


# --- 1 + 2: four analysts in parallel, each writing its OWN key -------------------
class Committee(TypedDict):
    fundamentals: str
    technicals: str
    sentiment: str
    macro: str
    pm: str


def pm_node(state: Committee):
    ready = [k for k in ("fundamentals", "technicals", "sentiment", "macro") if state[k]]
    return {"pm": f"PM saw {len(ready)}/4 reports"}


g = StateGraph(Committee)
for name in ("fundamentals", "technicals", "sentiment", "macro"):
    g.add_node(name, slow_node(name, name, 1.0))
    g.add_edge(START, name)                       # fan-out
    g.add_edge(name, "pm")                        # fan-in (implicit join)
g.add_node("pm", pm_node)
g.add_edge("pm", END)
committee = g.compile()

t0 = time.perf_counter()
empty = {"fundamentals": "", "technicals": "", "sentiment": "", "macro": "", "pm": ""}
for step, update in enumerate(committee.stream(empty, stream_mode="updates"), 1):
    print(f"t={time.perf_counter() - t0:4.1f}s  update {step}: {update}")
print("→ four 1-second analysts finished in about 1 second, then the PM ran once.\n")

# --- 3: two parallel nodes writing the SAME key ------------------------------------
class NoReducer(TypedDict):
    notes: str                                    # plain key: one writer per superstep


bad = StateGraph(NoReducer)
bad.add_node("bull", lambda s: {"notes": "bull says BUY"})
bad.add_node("bear", lambda s: {"notes": "bear says SELL"})
bad.add_edge(START, "bull")
bad.add_edge(START, "bear")
bad.add_edge("bull", END)
bad.add_edge("bear", END)
try:
    bad.compile().invoke({"notes": ""})
except InvalidUpdateError as e:
    print("Without a reducer →", type(e).__name__, ":", str(e).splitlines()[0])


class WithReducer(TypedDict):
    notes: Annotated[list[str], operator.add]     # reducer: concatenate the lists


good = StateGraph(WithReducer)
good.add_node("bull", lambda s: {"notes": ["bull says BUY"]})
good.add_node("bear", lambda s: {"notes": ["bear says SELL"]})
good.add_edge(START, "bull")
good.add_edge(START, "bear")
good.add_edge("bull", END)
good.add_edge("bear", END)
print("With operator.add  →", good.compile().invoke({"notes": []})["notes"])
📄 Section 8 · backtest.py section8_trading_committee/backtest.py

Run with --dry-run first (free).

section8_trading_committee/backtest.py
"""
Section 8 lab — A minimal walk-forward backtest for the committee
================================================================
Every Friday: run the committee on each stock → open the position it asks for →
hold it until next Friday → record the profit or loss → move one week forward.

How to run
----------
    python backtest.py --dry-run     # FREE: a random stand-in committee tests the plumbing
    python backtest.py               # REAL: ~36 committee runs ≈ 200 LLM calls, a few dollars

⚠ Big caveat (read before trusting any number): the real committee fetches TODAY's
fundamentals and news even when it is "deciding" on a past Friday. That is look-ahead bias.
A research-grade backtest needs point-in-time data (every fetcher takes an as_of_date)
and a window that starts AFTER the training cutoff of every model you use.
"""

from __future__ import annotations

import argparse
import random
import re
from dataclasses import dataclass

import numpy as np
import pandas as pd
import yfinance as yf

UNIVERSE = ["TSLA", "MSFT", "NVDA"]
START, END = "2026-07-01", "2026-10-01"   # pick a window after your models' training cutoff


@dataclass
class Trade:
    decision_date: pd.Timestamp
    ticker: str
    action: str            # "BUY" or "SELL"
    size_pct: float        # PM-proposed size, % of NAV
    confidence: int
    entry_price: float
    exit_date: pd.Timestamp
    exit_price: float

    @property
    def pnl_pct(self) -> float:                  # the stock's move, signed by direction
        sign = 1 if self.action == "BUY" else -1
        return sign * (self.exit_price / self.entry_price - 1)

    @property
    def weighted_pnl(self) -> float:             # what it did to the WHOLE portfolio
        return (self.size_pct / 100.0) * self.pnl_pct

_ACTION_RE = re.compile(r"ACTION\s*=\s*(BUY|HOLD|SELL)", re.I)
_CONF_RE = re.compile(r"CONFIDENCE\s*=\s*(\d+)", re.I)
_SIZE_RE = re.compile(r"SIZE_PCT\s*=\s*([\d.]+)", re.I)


def parse_decision(committee_result: dict) -> tuple[str, int, float]:
    thesis = committee_result["pm_thesis"]
    a, c, s = _ACTION_RE.findall(thesis), _CONF_RE.findall(thesis), _SIZE_RE.findall(thesis)
    action = a[-1].upper() if a else "HOLD"
    confidence = int(c[-1]) if c else 0
    size_pct = float(s[-1]) if s else 0.0
    final = committee_result["final_decision"].lower()
    if "(risk veto)" in final or "(risk rejected)" in final:
        return "HOLD", confidence, 0.0           # the risk officer ALWAYS wins
    return action, confidence, size_pct

def _price_on_or_before(series: pd.Series, when: pd.Timestamp) -> float | None:
    """Last close on or before a date (Fridays can be holidays)."""
    s = series[series.index <= when]
    return float(s.iloc[-1]) if len(s) else None


def walk_forward(committee_fn, universe, start, end, rebalance_freq="W-FRI"):
    """committee_fn(ticker, as_of) -> committee result dict."""
    rebalance_dates = pd.date_range(start, end, freq=rebalance_freq)
    prices = {}
    for t in universe:
        close = yf.Ticker(t).history(start=start, end=end)["Close"]
        close.index = close.index.tz_localize(None)        # compare dates without time zones
        prices[t] = close

    trades = []
    for i, decision_date in enumerate(rebalance_dates[:-1]):
        exit_date = rebalance_dates[i + 1]                  # hold for exactly one period
        for ticker in universe:
            result = committee_fn(ticker, decision_date)
            action, confidence, size_pct = parse_decision(result)
            if action == "HOLD" or size_pct == 0.0:
                continue                                    # no position, no trade
            entry = _price_on_or_before(prices[ticker], decision_date)
            exit_ = _price_on_or_before(prices[ticker], exit_date)
            if entry is None or exit_ is None:
                continue
            trades.append(Trade(decision_date, ticker, action, size_pct, confidence,
                                entry, exit_date, exit_))
    return trades, rebalance_dates

def equity_curve(trades, rebalance_dates, start_nav=1_000_000.0) -> pd.Series:
    """Portfolio value after each period. Weeks with no trades count as 0% weeks."""
    weekly = pd.Series(0.0, index=rebalance_dates[1:])      # every exit date, default 0%
    for t in trades:
        weekly[t.exit_date] += t.weighted_pnl               # add up all positions that week
    curve = (1 + weekly).cumprod() * start_nav
    return pd.concat([pd.Series([start_nav], index=[rebalance_dates[0]]), curve])


def metrics(curve: pd.Series, trades, periods_per_year: float = 52.0) -> dict:
    rets = curve.pct_change().dropna()
    sharpe = (rets.mean() / rets.std()) * np.sqrt(periods_per_year) if rets.std() > 0 else 0.0
    max_dd = (curve / curve.cummax() - 1).min()             # worst fall from a previous peak
    wins = sum(1 for t in trades if t.pnl_pct > 0)
    return {
        "trades": len(trades),
        "hit_rate": wins / len(trades) if trades else 0.0,
        "cumulative_return": float(curve.iloc[-1] / curve.iloc[0] - 1),
        "sharpe": float(sharpe),
        "max_drawdown": float(max_dd),
    }

def live_committee(ticker: str, as_of: pd.Timestamp) -> dict:
    """The real committee. It IGNORES as_of: its fetchers return today's data (look-ahead!)."""
    from investment_committee import run_committee        # imported only when needed
    return run_committee(ticker)


def random_committee(ticker: str, as_of: pd.Timestamp) -> dict:
    """Free stand-in that mimics the committee's output format, to test the harness."""
    rnd = random.Random(f"{ticker}{as_of.date()}")         # same inputs → same 'decision'
    action = rnd.choice(["BUY", "BUY", "HOLD"])
    conf, size = (rnd.randint(50, 80), rnd.choice([1.0, 1.5, 2.0])) if action == "BUY" else (55, 0.0)
    final = "HOLD (risk veto)" if rnd.random() < 0.1 else action
    return {"pm_thesis": f"...\nACTION={action}; CONFIDENCE={conf}; SIZE_PCT={size}",
            "final_decision": final}

if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--dry-run", action="store_true", help="use the free random committee")
    args = ap.parse_args()
    fn = random_committee if args.dry_run else live_committee

    trades, dates = walk_forward(fn, UNIVERSE, START, END)
    curve = equity_curve(trades, dates)
    m = metrics(curve, trades)
    print("=" * 64)
    print(f"Universe        : {', '.join(UNIVERSE)}   ({'DRY RUN' if args.dry_run else 'live committee'})")
    print(f"Window          : {START} to {END}  (weekly, W-FRI)")
    print(f"Trades executed : {m['trades']}")
    print(f"Hit rate        : {m['hit_rate']:.1%}")
    print(f"Cumulative ret. : {m['cumulative_return']:.1%}")
    print(f"Sharpe (annl.)  : {m['sharpe']:.2f}")
    print(f"Max drawdown    : {m['max_drawdown']:.1%}")
    print("=" * 64)
📄 Section 8 · adversarial_debate.py section8_trading_committee/adversarial_debate.py

Needs ANTHROPIC_API_KEY and OPENAI_API_KEY.

section8_trading_committee/adversarial_debate.py
"""
Section 8 lab — Stress-test the committee with an adversarial debate (LangGraph)
===============================================================================
Stage 1: the investment committee (investment_committee.py) produces a thesis + decision.
Stage 2: this graph attacks it from both sides, then a judge decides.

          ┌── bull (Claude Opus) ──┐
  START ──┤                        ├──► devil's advocate (Sonnet) ──► judge (Sonnet) ──► END
          └── bear (OpenAI GPT)  ──┘

    • Bull and bear run in PARALLEL and never see each other's argument.
    • Different model families for bull and bear → less "correlated reasoning".
    • The judge may disagree with the committee — and is told so.

How to run
----------
1. pip install langgraph langchain-anthropic langchain-openai yfinance pandas python-dotenv
2. .env:  ANTHROPIC_API_KEY=sk-ant-...   and   OPENAI_API_KEY=sk-...
3. python adversarial_debate.py          # TSLA
   python adversarial_debate.py NVDA

Cost: 6 committee calls + 4 debate calls = 10 LLM calls. Learning only — not advice.
"""

from __future__ import annotations

import re
import sys
from typing import TypedDict

from dotenv import load_dotenv
from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from langgraph.graph import END, START, StateGraph

from investment_committee import OPUS_MODEL, SONNET_MODEL, run_committee

load_dotenv()
BEAR_MODEL = "gpt-4o"                       # a DIFFERENT model family on purpose

bull_model = ChatAnthropic(model=OPUS_MODEL, max_tokens=1500)
bear_model = ChatOpenAI(model=BEAR_MODEL, max_tokens=1500)
devil_model = ChatAnthropic(model=SONNET_MODEL, max_tokens=1000)
judge_model = ChatAnthropic(model=SONNET_MODEL, max_tokens=1500)


class DebateState(TypedDict):
    ticker: str
    committee_thesis: str       # ← copied in from stage 1
    committee_decision: str     # ← copied in from stage 1
    bull_case: str
    bear_case: str
    devil_critique: str
    judge_verdict: str
    final_decision: str

def _case_message(state: DebateState) -> HumanMessage:
    return HumanMessage(content=(
        f"Ticker: {state['ticker']}\n"
        f"Committee thesis:\n{state['committee_thesis']}\n"
        f"Committee decision: {state['committee_decision']}"))


def bull_node(state: DebateState) -> dict:
    sys_msg = SystemMessage(content=(
        "You are a BULL analyst. Construct the strongest possible case to ENTER a long "
        "position. Cite the strongest evidence from the committee thesis: catalysts, "
        "valuation support, technical confirmation, sentiment tailwinds. Be concrete and "
        "do NOT hedge. Max 200 words. End with: BULL_CONVICTION=<0-100>."))
    return {"bull_case": bull_model.invoke([sys_msg, _case_message(state)]).content}


def bear_node(state: DebateState) -> dict:
    sys_msg = SystemMessage(content=(
        "You are a BEAR analyst. Construct the strongest possible case AGAINST entering a "
        "long position. Surface risks the committee may have under-weighted: tail risks, "
        "macro headwinds, valuation stretch, sentiment crowding, technical exhaustion. Be "
        "concrete and do NOT hedge. Max 200 words. End with: BEAR_CONVICTION=<0-100>."))
    return {"bear_case": bear_model.invoke([sys_msg, _case_message(state)]).content}

def devil_advocate(state: DebateState) -> dict:
    sys_msg = SystemMessage(content=(
        "You are a Devil's Advocate. Identify the SINGLE weakest claim in the BULL case and "
        "the SINGLE weakest claim in the BEAR case, and explain in one sentence each why "
        "those claims are weak. Max 150 words."))
    msg = HumanMessage(content=f"BULL case:\n{state['bull_case']}\n\nBEAR case:\n{state['bear_case']}")
    return {"devil_critique": devil_model.invoke([sys_msg, msg]).content}

VERDICT_RE = re.compile(r"VERDICT\s*=\s*(BUY|HOLD|SELL)", re.IGNORECASE)


def _parse_verdict(text: str) -> str:
    m = VERDICT_RE.search(text)
    return m.group(1).upper() if m else "HOLD"   # unreadable → the safe default


def judge_node(state: DebateState) -> dict:
    sys_msg = SystemMessage(content=(
        "You are a NEUTRAL Judge. Weigh the bull case, the bear case and the devil's "
        "critique. Issue a verdict that MAY DIFFER from the committee's prior decision. "
        "Confirm the committee unless one side shows a clear, material flaw. "
        "Reply STRICTLY in the form:\n"
        "VERDICT=<BUY|HOLD|SELL>\nCONFIDENCE=<0-100>\nRATIONALE=<2-3 sentences>"))
    msg = HumanMessage(content=(
        f"Committee prior: {state['committee_decision']}\n\n"
        f"BULL case:\n{state['bull_case']}\n\n"
        f"BEAR case:\n{state['bear_case']}\n\n"
        f"Devil's critique:\n{state['devil_critique']}"))
    out = judge_model.invoke([sys_msg, msg])
    return {"judge_verdict": out.content, "final_decision": _parse_verdict(out.content)}

def build_debate():
    g = StateGraph(DebateState)
    g.add_node("bull", bull_node)
    g.add_node("bear", bear_node)
    g.add_node("devil", devil_advocate)
    g.add_node("judge", judge_node)
    g.add_edge(START, "bull")          # bull and bear in parallel…
    g.add_edge(START, "bear")
    g.add_edge("bull", "devil")        # …the devil waits for both
    g.add_edge("bear", "devil")
    g.add_edge("devil", "judge")
    g.add_edge("judge", END)
    return g.compile()


def run_pipeline(ticker: str) -> dict:
    committee_result = run_committee(ticker)                   # stage 1
    initial: DebateState = {
        "ticker": ticker.upper(),
        "committee_thesis": committee_result["pm_thesis"],
        "committee_decision": committee_result["final_decision"],
        "bull_case": "", "bear_case": "", "devil_critique": "",
        "judge_verdict": "", "final_decision": "",
    }
    debate_result = build_debate().invoke(initial)             # stage 2
    return {"committee": committee_result, "debate": debate_result}

def _conviction(text: str, side: str) -> str:
    m = re.search(rf"{side}_CONVICTION\s*=\s*(\d+)", text, re.I)
    return m.group(1) if m else "?"


if __name__ == "__main__":
    ticker = sys.argv[1] if len(sys.argv) > 1 else "TSLA"
    out = run_pipeline(ticker)
    c, d = out["committee"], out["debate"]
    print("=" * 80)
    print(f"COMMITTEE said : {c['final_decision']}")
    print(f"DEBATE judge   : {d['final_decision']}   "
          f"(bull {_conviction(d['bull_case'], 'BULL')} vs bear {_conviction(d['bear_case'], 'BEAR')})")
    print("=" * 80)
    for title, key in (("Bull case", "bull_case"), ("Bear case", "bear_case"),
                       ("Devil's critique", "devil_critique"), ("Judge verdict", "judge_verdict")):
        print(f"\n--- {title} ---\n{d[key]}")
📄 Section 9 · claims_rules.py section9_insurance_claims/claims_rules.py

Free: every rule, the sample claim, and an offline run.

section9_insurance_claims/claims_rules.py
"""
Section 9 lab — the RULES behind the claims pipeline (pure Python: no LLM, no API key)
=====================================================================================
Everything that moves money or blocks a decision lives here, as plain functions:
  fraud score · payout · decision · human-review gates · compliance checks · audit log.
Rules are auditable, repeatable and unit-testable — exactly what a regulator asks for.
The agents in claims_pipeline.py call these functions through their tools.

How to run (free):
    python claims_rules.py                 # Sarah Chen's claim, no LLM at all
    python claims_rules.py --suspicious    # a claim that trips the fraud rules
    python -m pytest test_claims_rules.py -q
"""

from __future__ import annotations

import re
import sys
import uuid
from datetime import date, datetime, timezone
from enum import Enum

from pydantic import BaseModel


class ClaimType(str, Enum):
    AUTO = "auto"
    PROPERTY = "property"
    HEALTH = "health"
    LIABILITY = "liability"


class ClaimRecord(BaseModel):
    """The contract every agent reads and writes. Each stage owns its own fields."""
    claim_id: str
    policyholder_name: str
    policy_number: str
    claim_type: ClaimType
    date_of_loss: date
    description: str
    status: str = "received"
    # DocumentParser
    parsed_documents: list[dict] = []
    damage_description: str = ""
    missing_documents: list[str] = []
    # CoverageAgent
    coverage_verified: bool | None = None
    coverage_section: str = ""
    applicable_limit: float = 0.0
    deductible: float = 0.0
    coverage_reasoning: str = ""
    # FraudScreener
    fraud_score: int | None = None
    red_flags: list[str] = []
    fraud_recommendation: str = ""
    # AssessmentAgent
    estimated_payout: float | None = None
    assessment_breakdown: str = ""
    # DecisionAgent
    decision: str = ""
    decision_reasoning: str = ""
    human_review_gates: list[str] = []
    # ComplianceAgent
    compliance_issues: list[str] = []
    stages_completed: list[str] = []

# Least privilege: which top-level inputs each agent may SEE …
DATA_ACCESS = {
    "FNOLAgent":       ["claim_form"],
    "DocumentParser":  ["submitted_documents"],
    "CoverageAgent":   ["policy"],
    "FraudScreener":   ["policy", "claims_history", "fnol_date"],
    "AssessmentAgent": ["claim_form"],           # the body-shop estimate lines
    "DecisionAgent":   [],                        # works only from the claim record
    "ComplianceAgent": [],
}
# … and which claim fields each agent may WRITE (no agent can overwrite another's work).
OWNED_FIELDS = {
    "DocumentParser":  {"parsed_documents", "damage_description", "missing_documents"},
    "CoverageAgent":   {"coverage_verified", "coverage_section", "applicable_limit",
                        "deductible", "coverage_reasoning"},
    "FraudScreener":   {"fraud_score", "red_flags", "fraud_recommendation"},
    "AssessmentAgent": {"estimated_payout", "assessment_breakdown"},
    "DecisionAgent":   {"decision", "decision_reasoning", "human_review_gates"},
    "ComplianceAgent": {"compliance_issues"},
}


def scoped_view(state: dict, agent: str) -> dict:
    """Give an agent only the inputs it is allowed to see."""
    return {k: state[k] for k in DATA_ACCESS[agent] if k in state}


def write_fields(claim: dict, agent: str, status: str, **fields) -> None:
    """Write an agent's results into the claim — refuse anything it doesn't own."""
    illegal = set(fields) - OWNED_FIELDS[agent]
    if illegal:
        raise PermissionError(f"{agent} may not write {sorted(illegal)}")
    claim.update(fields)
    claim["status"] = status
    claim["stages_completed"] = claim.get("stages_completed", []) + [agent]

def redact(text: str, claim: dict) -> str:
    """Replace the policyholder's name and policy number with opaque tokens."""
    for secret, label in ((claim.get("policyholder_name"), "NAME"),
                          (claim.get("policy_number"), "POLICY")):
        if secret:
            text = re.sub(re.escape(secret), f"[{label}:{claim['claim_id']}]", text, flags=re.I)
    return text


def log_audit(state: dict, agent: str, action: str, details: str = "") -> None:
    """Append-only audit trail. Every agent writes here; nobody edits old lines."""
    claim = state.get("claim", {})
    state.setdefault("audit_log", []).append({
        "ts": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "claim_id": claim.get("claim_id", "?"),
        "agent": agent,
        "action": action,
        "details": redact(details, claim) if claim else details,
    })

AUTO_WORDS = r"\b(car|vehicle|truck|collision|rear-end|bumper|headlight)\b"
PROPERTY_WORDS = r"\b(roof|house|kitchen|fire|flood|burst pipe)\b"


def classify_claim_type(description: str) -> ClaimType:
    d = description.lower()
    if re.search(AUTO_WORDS, d):                    # whole words only: "car" ≠ "careful"
        return ClaimType.AUTO
    if re.search(PROPERTY_WORDS, d):
        return ClaimType.PROPERTY
    return ClaimType.LIABILITY


def fnol_intake(claim_form: dict) -> dict:
    claim = ClaimRecord(
        claim_id=f"CLM-{claim_form['date_of_loss'][:4]}-{uuid.uuid4().hex[:8].upper()}",
        policyholder_name=claim_form["name"],
        policy_number=claim_form["policy_number"],
        claim_type=classify_claim_type(claim_form["description"]),
        date_of_loss=claim_form["date_of_loss"],
        description=claim_form["description"],
    )
    return claim.model_dump(mode="json")


REQUIRED_DOCS = {"claim_form", "photo", "police_report"}


def parse_documents(documents: list[dict]) -> dict:
    parsed = []
    for doc in documents:
        if doc["type"] == "photo":
            # PRODUCTION: send the image to a vision model here.
            # LAB: the photo arrives as a written description standing in for that output.
            parsed.append({"type": "damage_photo", "description": doc["description"]})
        elif doc["type"] in ("claim_form", "police_report"):
            parsed.append(doc)
    seen = {d["type"] for d in documents}
    damage = "; ".join(d["description"] for d in parsed if d["type"] == "damage_photo")
    return {"parsed_documents": parsed, "damage_description": damage,
            "missing_documents": sorted(REQUIRED_DOCS - seen)}

def days_between(a, b) -> int:
    to_d = lambda x: x if isinstance(x, date) else date.fromisoformat(x)
    return (to_d(b) - to_d(a)).days


def verify_coverage(claim: dict, policy: dict) -> dict:
    # PRODUCTION: an LLM reads the policy wording and cites sections. LAB: keyword rules.
    loss, desc = claim["date_of_loss"], claim["description"].lower()
    started = days_between(policy["inception_date"], loss) >= 0     # loss on/after the start
    not_ended = days_between(loss, policy["expiry_date"]) >= 0      # loss on/before the end
    if not (started and not_ended):
        return {"coverage_verified": False, "coverage_section": "",
                "applicable_limit": 0.0, "deductible": 0.0,
                "coverage_reasoning": "POLICY_INACTIVE: loss date outside the policy period."}
    for ex in policy["exclusions"]:
        if any(k in desc for k in ex["keywords"]):
            return {"coverage_verified": False, "coverage_section": ex["ref"],
                    "applicable_limit": 0.0, "deductible": 0.0,
                    "coverage_reasoning": f"EXCLUSION: {ex['ref']} applies ({ex['label']})."}
    for sec in policy["coverage_sections"]:
        if any(k in desc for k in sec["keywords"]):
            return {"coverage_verified": True, "coverage_section": sec["ref"],
                    "applicable_limit": float(sec["limit"]), "deductible": float(sec["deductible"]),
                    "coverage_reasoning": (f"Covered under {sec['ref']}: limit ${sec['limit']:,}, "
                                           f"deductible ${sec['deductible']:,}.")}
    return {"coverage_verified": None, "coverage_section": "", "applicable_limit": 0.0,
            "deductible": 0.0, "coverage_reasoning": "AMBIGUOUS: no section clearly applies."}

FRAUD_THRESHOLD = 40


def screen_for_fraud(policy: dict, claim: dict, claims_history: list, fnol_date: str) -> dict:
    score, flags = 0, []
    if days_between(policy["inception_date"], claim["date_of_loss"]) < 30:
        score += 25
        flags.append("Loss within 30 days of policy start (buy-and-claim pattern)")
    if len(claims_history) >= 3:
        score += 20
        flags.append(f"{len(claims_history)} prior claims in 12 months")
    if days_between(claim["date_of_loss"], fnol_date) > 30:
        score += 15
        flags.append("Reported more than 30 days after the loss")
    return {"fraud_score": score, "red_flags": flags,
            "fraud_recommendation": "investigate" if score > FRAUD_THRESHOLD else "proceed"}

def assess_damage(repair_items: list[dict], deductible: float, limit: float) -> dict:
    # PRODUCTION: a vision/LLM estimate from photos, checked against a body-shop quote.
    gross = sum(i["cost"] for i in repair_items)
    payout = max(0.0, min(gross - deductible, limit))     # never negative, never above limit
    lines = ", ".join(f"{i['item']} ${i['cost']:,}" for i in repair_items)
    return {"estimated_payout": payout,
            "assessment_breakdown": f"{lines} = ${gross:,} gross − ${deductible:,.0f} deductible"
                                    f" → ${payout:,.0f} (limit ${limit:,.0f})"}

HIGH_VALUE_THRESHOLD = 100_000


def human_review_gates(claim: dict) -> list[str]:
    gates = []
    if (claim.get("estimated_payout") or 0) > HIGH_VALUE_THRESHOLD:
        gates.append("HIGH_VALUE → senior adjuster")
    if (claim.get("fraud_score") or 0) > FRAUD_THRESHOLD:
        gates.append("FRAUD_FLAG → fraud investigation / SIU")
    if claim.get("coverage_verified") is None:
        gates.append("COVERAGE_AMBIGUOUS → coverage specialist")
    if claim.get("claim_type") in ("health", "liability"):
        gates.append("REGULATORY → bodily-injury adjuster")
    if claim.get("missing_documents"):
        gates.append("INCOMPLETE_DOCS → request " + ", ".join(claim["missing_documents"]))
    return gates


STATUS_AFTER = {"APPROVE": "approved", "DENY": "denied", "ESCALATE": "escalated"}


def make_decision(claim: dict) -> dict:
    # PRODUCTION: an LLM writes the reasoning; the CHOICE still follows these rules.
    gates = human_review_gates(claim)
    if claim["coverage_verified"] is False:
        decision = "DENY"
        reasoning = (f"{claim['coverage_reasoning']} Policy reference: "
                     f"{claim['coverage_section'] or 'policy period'}. The claimant may contact "
                     "the state Department of Insurance.")
    elif gates:
        decision = "ESCALATE"
        reasoning = ("Paused for human review: " + "; ".join(gates) +
                     f". Fraud score {claim['fraud_score']}/100; proposed payout "
                     f"${claim['estimated_payout']:,.0f}.")
    else:
        decision = "APPROVE"
        reasoning = (f"{claim['coverage_reasoning']} Fraud score {claim['fraud_score']}/100 "
                     f"with no red flags. Payout: {claim['assessment_breakdown']}.")
    return {"decision": decision, "decision_reasoning": reasoning, "human_review_gates": gates}

DENIAL_REASONS = ("POLICY_INACTIVE", "EXCLUSION", "NOT_COVERED")
ALL_STAGES = ["DocumentParser", "CoverageAgent", "FraudScreener", "AssessmentAgent", "DecisionAgent"]


def validate_compliance(claim: dict) -> list[str]:
    issues = []
    if claim["decision"] == "DENY" and not claim["decision_reasoning"].startswith(DENIAL_REASONS):
        issues.append("Denial reason not a recognised category")
    if len(claim["decision_reasoning"]) < 50:
        issues.append("Reasoning too short for an audit")
    missing = [s for s in ALL_STAGES if s not in claim.get("stages_completed", [])]
    if missing:
        issues.append(f"Pipeline stage missing: {missing}")
    if claim["decision"] == "APPROVE":
        if (claim.get("fraud_score") or 0) > FRAUD_THRESHOLD:
            issues.append("Approved despite a fraud flag")
        if (claim.get("estimated_payout") or 0) > claim.get("applicable_limit", 0):
            issues.append("Payout above the policy limit")
        if claim.get("human_review_gates"):
            issues.append("Auto-approved although a human-review gate fired")
    return issues

SAMPLE_POLICY = {
    "policy_number": "FWS-AUTO-58213", "holder": "Sarah Chen",
    "inception_date": "2025-11-02", "expiry_date": "2026-11-01",
    "coverage_sections": [
        {"ref": "Part D §1 Collision", "keywords": ["collision", "rear-end", "hit a"],
         "limit": 50_000, "deductible": 500},
        {"ref": "Part D §2 Comprehensive", "keywords": ["theft", "stolen", "hail", "flood"],
         "limit": 50_000, "deductible": 250},
    ],
    "exclusions": [{"ref": "Exclusion 4", "label": "racing or intentional damage",
                    "keywords": ["racing", "intentional"]}],
}
SAMPLE_CLAIM_FORM = {
    "type": "claim_form", "name": "Sarah Chen", "policy_number": "FWS-AUTO-58213",
    "date_of_loss": "2026-04-07",
    "description": ("Rear-end collision on I-95 at 2:47 AM in rain: my car hit a stopped "
                    "delivery truck. Front bumper and headlight damaged. No injuries at the "
                    "scene; back pain noted later (separate injury feature)."),
    "repair_items": [{"item": "front bumper", "cost": 2_600},
                     {"item": "headlight assembly", "cost": 1_100},
                     {"item": "labour", "cost": 600}],
}
SAMPLE_DOCUMENTS = [
    SAMPLE_CLAIM_FORM,
    {"type": "photo", "description": "Front bumper crushed, grille cracked"},
    {"type": "photo", "description": "Left headlight assembly shattered"},
    {"type": "police_report", "report_number": "HP-2026-0407-118",
     "summary": "Vehicle 1 struck a stationary delivery truck; wet road; no citations."},
]


def sample_state(suspicious: bool = False) -> dict:
    """The starting whiteboard for one claim. suspicious=True trips all three fraud rules."""
    state = {"claim_form": SAMPLE_CLAIM_FORM, "submitted_documents": SAMPLE_DOCUMENTS,
             "policy": SAMPLE_POLICY, "claims_history": [], "fnol_date": "2026-04-08",
             "audit_log": []}
    if suspicious:
        state["policy"] = {**SAMPLE_POLICY, "inception_date": "2026-03-20"}   # 18 days before
        state["claims_history"] = [{"id": "C1"}, {"id": "C2"}, {"id": "C3"}]
        state["fnol_date"] = "2026-05-15"                                      # 38 days late
    return state

def run_offline(state: dict) -> dict:
    """The same seven stages as the agent pipeline, called directly — handy for tests."""
    claim = fnol_intake(state["claim_form"]); state["claim"] = claim
    log_audit(state, "FNOLAgent", "claim created",
              f"{claim['policyholder_name']} / {claim['policy_number']}, type={claim['claim_type']}")
    r = parse_documents(state["submitted_documents"])
    write_fields(claim, "DocumentParser", "parsing", **r)
    log_audit(state, "DocumentParser", "documents parsed", f"{len(r['parsed_documents'])} docs")
    r = verify_coverage(claim, state["policy"])
    write_fields(claim, "CoverageAgent", "coverage_check", **r)
    log_audit(state, "CoverageAgent", "coverage checked", r["coverage_reasoning"])
    r = screen_for_fraud(state["policy"], claim, state["claims_history"], state["fnol_date"])
    write_fields(claim, "FraudScreener", "fraud_screening", **r)
    log_audit(state, "FraudScreener", "fraud screened", f"score={r['fraud_score']} {r['red_flags']}")
    r = assess_damage(state["claim_form"]["repair_items"], claim["deductible"], claim["applicable_limit"])
    write_fields(claim, "AssessmentAgent", "assessment", **r)
    log_audit(state, "AssessmentAgent", "damage assessed", r["assessment_breakdown"])
    r = make_decision(claim)
    write_fields(claim, "DecisionAgent", STATUS_AFTER[r["decision"]], **r)
    log_audit(state, "DecisionAgent", f"decision {r['decision']}", r["decision_reasoning"])
    issues = validate_compliance(claim)
    write_fields(claim, "ComplianceAgent", "blocked" if issues else "compliance_ok", compliance_issues=issues)
    log_audit(state, "ComplianceAgent", "BLOCKED" if issues else "validated", str(issues or "compliant"))
    return state


if __name__ == "__main__":
    final = run_offline(sample_state(suspicious="--suspicious" in sys.argv))
    c = final["claim"]
    print(f"{c['claim_id']}: {c['decision']}  payout ${c['estimated_payout']:,.0f}  "
          f"fraud {c['fraud_score']}/100  compliance issues: {c['compliance_issues'] or 'none'}")
    print("\nAudit log (PII redacted):")
    for row in final["audit_log"]:
        print(f"  {row['agent']:16} {row['action']:18} {row['details']}")
📄 Section 9 · test_claims_rules.py section9_insurance_claims/test_claims_rules.py

Free: python -m pytest test_claims_rules.py -q

section9_insurance_claims/test_claims_rules.py
"""
Section 9 lab — invariant tests for the claims rules (free: no LLM, no API key)
==============================================================================
An LLM's wording changes every run, so we don't test wording. We test INVARIANTS:
statements that must be true for EVERY claim, whatever the agents say.

How to run:   python -m pytest test_claims_rules.py -q
"""

import copy

import pytest

import claims_rules as R


def run(**changes):
    """Run the whole pipeline offline on a copy of the sample, with some inputs changed."""
    state = copy.deepcopy(R.sample_state())
    for key, value in changes.items():
        if key == "repair_items":
            state["claim_form"] = {**state["claim_form"], "repair_items": value}
        else:
            state[key] = value
    return R.run_offline(state)["claim"]


def test_happy_path_matches_the_sample_run():
    c = run()
    assert (c["decision"], c["estimated_payout"], c["fraud_score"]) == ("APPROVE", 3800, 0)


@pytest.mark.parametrize("costs", [[100], [4_300], [80_000], [250_000]])
def test_payout_is_never_negative_and_never_above_the_limit(costs):
    c = run(repair_items=[{"item": "x", "cost": k} for k in costs])
    assert 0 <= c["estimated_payout"] <= c["applicable_limit"]


def test_a_fraud_flag_is_never_auto_approved():
    c = run(claims_history=[{}, {}, {}], fnol_date="2026-05-20")      # 20 + 15 = 35 → still fine
    assert c["fraud_score"] == 35 and c["decision"] == "APPROVE"
    c = run(policy={**R.SAMPLE_POLICY, "inception_date": "2026-03-20"},
            claims_history=[{}, {}, {}])                               # 25 + 20 = 45 > 40
    assert c["decision"] == "ESCALATE"


def test_missing_police_report_pauses_the_claim():
    docs = [d for d in R.SAMPLE_DOCUMENTS if d["type"] != "police_report"]
    c = run(submitted_documents=docs)
    assert c["decision"] == "ESCALATE" and "police_report" in c["missing_documents"]


def test_excluded_cause_is_denied_with_a_recognised_reason():
    form = {**R.SAMPLE_CLAIM_FORM, "description": "Collision during an amateur racing event; car hit a wall."}
    c = run(claim_form=form, submitted_documents=[form] + R.SAMPLE_DOCUMENTS[1:])
    assert c["decision"] == "DENY" and c["decision_reasoning"].startswith("EXCLUSION")
    assert c["compliance_issues"] == []


def test_compliance_blocks_short_reasoning_and_skipped_stages():
    c = run()
    c["decision_reasoning"] = "ok"
    c["stages_completed"].remove("FraudScreener")
    issues = R.validate_compliance(c)
    assert "Reasoning too short for an audit" in issues
    assert any("FraudScreener" in i for i in issues)


def test_no_personal_data_in_the_audit_log():
    state = R.run_offline(copy.deepcopy(R.sample_state()))
    text = str(state["audit_log"])
    assert "Sarah Chen" not in text and "FWS-AUTO-58213" not in text


def test_an_agent_cannot_write_another_agents_fields():
    claim = run()
    with pytest.raises(PermissionError):
        R.write_fields(claim, "AssessmentAgent", "assessment", fraud_score=0)
📄 Section 9 · claims_pipeline.py section9_insurance_claims/claims_pipeline.py

Seven LlamaIndex agents. Needs OPENAI_API_KEY.

section9_insurance_claims/claims_pipeline.py
"""
Section 9 lab — Auto-claims pipeline with seven agents (LlamaIndex AgentWorkflow)
================================================================================
Style: SEQUENTIAL PIPELINE WITH GUARDRAILS — compliance has the last word.

  FNOL → DocumentParser → Coverage → FraudScreener → Assessment → Decision → Compliance

    • Each agent has ONE tool. The tool reads only what the agent may see (DATA_ACCESS)
      and writes only the fields the agent owns (OWNED_FIELDS) — see claims_rules.py.
    • Money and blocking decisions come from rules, never from free text.
    • Every step appends a PII-redacted line to the audit log.

How to run
----------
1. pip install llama-index-core llama-index-llms-openai pydantic python-dotenv
2. .env:   OPENAI_API_KEY=sk-...
3. python claims_pipeline.py                # Sarah Chen's rear-end collision → APPROVE $3,800
   python claims_pipeline.py --suspicious   # same claim, three fraud red flags → ESCALATE
   (no key? run  python claims_rules.py  — the same stages without LLMs)

Cost: about 14–21 LLM calls per claim (each agent: tool call + short summary + handoff).
"""

import asyncio
import sys

from dotenv import load_dotenv
from llama_index.core.agent.workflow import AgentStream, AgentWorkflow, FunctionAgent, ToolCall
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI

import claims_rules as R

load_dotenv()
MODEL = "gpt-4o"
llm = OpenAI(model=MODEL)

async def _load(ctx: Context, agent: str):
    """state = the shared whiteboard; view = ONLY the raw inputs this agent may see."""
    state = await ctx.store.get("state")
    inputs = await ctx.store.get("case_inputs")       # kept OUT of "state" on purpose
    return state, R.scoped_view(inputs, agent)


async def process_fnol(ctx: Context) -> str:
    """Create the claim record from the submitted claim form."""
    state, view = await _load(ctx, "FNOLAgent")       # sees the claim form only
    claim = R.fnol_intake(view["claim_form"])          # data never passes through the LLM
    state["claim"] = claim
    R.log_audit(state, "FNOLAgent", "claim created", f"type={claim['claim_type']}")
    await ctx.store.set("state", state)
    return f"FNOL processed. Claim {claim['claim_id']}, type {claim['claim_type']}."


async def parse_documents(ctx: Context) -> str:
    """Parse the submitted documents and list any missing ones."""
    state, view = await _load(ctx, "DocumentParser")
    r = R.parse_documents(view["submitted_documents"])
    R.write_fields(state["claim"], "DocumentParser", "parsing", **r)
    R.log_audit(state, "DocumentParser", "documents parsed", f"{len(r['parsed_documents'])} docs")
    await ctx.store.set("state", state)
    return (f"Parsed {len(r['parsed_documents'])} documents. Damage: {r['damage_description']}. "
            f"Missing: {r['missing_documents'] or 'none'}.")


async def verify_coverage(ctx: Context) -> str:
    """Check the claim against the policy sections and exclusions."""
    state, view = await _load(ctx, "CoverageAgent")
    r = R.verify_coverage(state["claim"], view["policy"])
    R.write_fields(state["claim"], "CoverageAgent", "coverage_check", **r)
    R.log_audit(state, "CoverageAgent", "coverage checked", r["coverage_reasoning"])
    await ctx.store.set("state", state)
    return r["coverage_reasoning"]


async def screen_for_fraud(ctx: Context) -> str:
    """Score the claim against the fraud red-flag rules."""
    state, view = await _load(ctx, "FraudScreener")   # policy dates + claims history only
    r = R.screen_for_fraud(view["policy"], state["claim"], view["claims_history"], view["fnol_date"])
    R.write_fields(state["claim"], "FraudScreener", "fraud_screening", **r)
    R.log_audit(state, "FraudScreener", "fraud screened", f"score={r['fraud_score']} flags={r['red_flags']}")
    await ctx.store.set("state", state)
    return (f"Fraud score {r['fraud_score']}/100. Flags: {r['red_flags'] or 'none'}. "
            f"Recommendation: {r['fraud_recommendation']}.")


async def assess_damage(ctx: Context) -> str:
    """Price the repair, apply the deductible and cap at the limit."""
    state, view = await _load(ctx, "AssessmentAgent")
    claim = state["claim"]
    r = R.assess_damage(view["claim_form"]["repair_items"], claim["deductible"], claim["applicable_limit"])
    R.write_fields(claim, "AssessmentAgent", "assessment", **r)
    R.log_audit(state, "AssessmentAgent", "damage assessed", r["assessment_breakdown"])
    await ctx.store.set("state", state)
    return r["assessment_breakdown"]


async def make_decision(ctx: Context) -> str:
    """Decide APPROVE / DENY / ESCALATE from the coverage, fraud and assessment results."""
    state, _ = await _load(ctx, "DecisionAgent")       # no raw inputs: the claim record only
    r = R.make_decision(state["claim"])
    R.write_fields(state["claim"], "DecisionAgent", R.STATUS_AFTER[r["decision"]], **r)
    R.log_audit(state, "DecisionAgent", f"decision {r['decision']}", r["decision_reasoning"])
    await ctx.store.set("state", state)
    return f"{r['decision']}: {r['decision_reasoning']}"


async def validate_compliance(ctx: Context) -> str:
    """Final guardrail: block the decision if any regulatory check fails."""
    state, _ = await _load(ctx, "ComplianceAgent")
    issues = R.validate_compliance(state["claim"])
    status = "blocked" if issues else "compliance_ok"
    R.write_fields(state["claim"], "ComplianceAgent", status, compliance_issues=issues)
    R.log_audit(state, "ComplianceAgent", "BLOCKED" if issues else "validated", str(issues or "compliant"))
    await ctx.store.set("state", state)
    return f"BLOCKED: {issues}" if issues else "Decision validated. Compliant."

def make_agent(name: str, job: str, tool, next_agent: str | None) -> FunctionAgent:
    hand = (f"then hand off to {next_agent} with a one-line reason."
            if next_agent else "then give the final answer yourself. Do not hand off.")
    return FunctionAgent(
        name=name,
        description=job,
        system_prompt=(
            f"You are the {name} of an auto-insurance claims team. Your job: {job} "
            f"Call {tool.__name__} EXACTLY ONCE. Report its result in one or two sentences "
            "without changing any number, decision or flag, " + hand),
        llm=llm,
        tools=[tool],
        can_handoff_to=[next_agent] if next_agent else [],
    )


PIPELINE = [   # (agent name, job, tool) in order
    ("FNOLAgent", "open the claim record from the first notice of loss.", process_fnol),
    ("DocumentParser", "turn the submitted documents into structured data.", parse_documents),
    ("CoverageAgent", "check what the policy covers for this loss.", verify_coverage),
    ("FraudScreener", "screen the claim for fraud red flags.", screen_for_fraud),
    ("AssessmentAgent", "estimate the payout within deductible and limit.", assess_damage),
    ("DecisionAgent", "decide APPROVE, DENY or ESCALATE.", make_decision),
    ("ComplianceAgent", "validate the decision before anything is paid.", validate_compliance),
]
AGENTS = [
    make_agent(name, job, tool, PIPELINE[i + 1][0] if i + 1 < len(PIPELINE) else None)
    for i, (name, job, tool) in enumerate(PIPELINE)
]

async def run_claim(case_inputs: dict, verbose: bool = True) -> dict:
    workflow = AgentWorkflow(
        agents=AGENTS, root_agent="FNOLAgent",
        initial_state={"claim": {}, "audit_log": []},  # AgentWorkflow pastes THIS into the
    )                                                   # first prompt — so no PII goes in it
    ctx = Context(workflow)
    await ctx.store.set("case_inputs", case_inputs)     # raw claim data: tools only
    handler = workflow.run(user_msg="A new auto claim was submitted. Process it.",
                           ctx=ctx, max_iterations=60)  # 7 agents × ~3 steps: 20 is too few
    last = None
    async for ev in handler.stream_events():
        if verbose and isinstance(ev, AgentStream) and ev.current_agent_name != last:
            last = ev.current_agent_name
            print(f"\n== {last} " + "=" * (50 - len(last)))
        if verbose and isinstance(ev, AgentStream) and ev.delta:
            print(ev.delta, end="", flush=True)
        if verbose and isinstance(ev, ToolCall) and ev.tool_name == "handoff":
            print(f"\n   🔀 → {ev.tool_kwargs.get('to_agent')}: {ev.tool_kwargs.get('reason')}")
    await handler
    return await ctx.store.get("state")


if __name__ == "__main__":
    inputs = R.sample_state(suspicious="--suspicious" in sys.argv)
    state = asyncio.run(run_claim(inputs))
    c = state["claim"]
    print(f"\n\nRESULT {c['claim_id']}: {c['decision']}  payout ${c['estimated_payout']:,.0f}  "
          f"fraud {c['fraud_score']}/100  gates {c['human_review_gates'] or 'none'}  "
          f"compliance {c['compliance_issues'] or 'OK'}")
    print("\nAudit log (append-only, PII redacted):")
    for row in state["audit_log"]:
        print(f"  {row['ts']}  {row['agent']:16} {row['action']:18} {row['details'][:90]}")
📄 Section 9 · fraud_investigation.py section9_insurance_claims/fraud_investigation.py

The fraud debate. Needs OPENAI_API_KEY.

section9_insurance_claims/fraud_investigation.py
"""
Section 9 lab — extension: adversarial fraud investigation (LlamaIndex AgentWorkflow)
====================================================================================
Style: PEER-TO-PEER DEBATE, triggered only when the pipeline escalates a fraud flag.

  FraudAdvocate ──► LegitimacyAdvocate ──► InvestigationDecision
  (argues fraud)    (argues legitimate,     (weighs both → a REFERRAL, never a verdict
                     sees the opening)        of fraud: that is a legal conclusion)

How to run
----------
    python fraud_investigation.py            # runs the suspicious claim through it
Needs OPENAI_API_KEY in .env. Cost: about 9–12 LLM calls.
"""

import asyncio
from typing import Literal

from dotenv import load_dotenv
from llama_index.core.agent.workflow import AgentStream, AgentWorkflow, FunctionAgent
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI
from pydantic import BaseModel, Field, ValidationError

import claims_rules as R

load_dotenv()
llm = OpenAI(model="gpt-4o")


class FraudArgument(BaseModel):
    position: Literal["fraud", "legitimate"]
    confidence: float = Field(ge=0.0, le=1.0)
    evidence: list[str]
    reasoning: str
    weaknesses: list[str]          # each side must name the holes in its OWN case


Referral = Literal["strong_fraud_indicators", "likely_fraud", "inconclusive", "likely_legitimate"]
ROUTING = {                        # code, not the LLM, decides where the claim goes next
    "strong_fraud_indicators": "Refer to the Special Investigations Unit (SIU)",
    "likely_fraud": "Flag for human review by a senior adjuster",
    "inconclusive": "Resume with caution: adjuster double-checks before payment",
    "likely_legitimate": "Clear the flag and resume normal processing",
}

async def get_case_file(ctx: Context) -> str:
    """Return the evidence both advocates must argue from (no personal data)."""
    claim = (await ctx.store.get("case"))["claim"]    # the escalated claim, tools only
    return (f"Claim {claim['claim_id']} ({claim['claim_type']}), loss {claim['date_of_loss']}.\n"
            f"Description: {R.redact(claim['description'], claim)}\n"
            f"Fraud score: {claim['fraud_score']}/100. Red flags: {claim['red_flags']}\n"
            f"Coverage: {claim['coverage_reasoning']}\n"
            f"Documents: {[d['type'] for d in claim['parsed_documents']]}; "
            f"damage: {claim['damage_description']}\nPayout at stake: ${claim['estimated_payout']:,.0f}")


async def submit_argument(ctx: Context, position: str, confidence: float,
                          evidence: list[str], reasoning: str, weaknesses: list[str]) -> str:
    """Save your structured argument. position must be 'fraud' or 'legitimate'; confidence 0-1."""
    try:
        arg = FraudArgument(position=position, confidence=confidence, evidence=evidence,
                            reasoning=reasoning, weaknesses=weaknesses)
    except ValidationError as e:                       # the LLM gets the error and can retry
        return f"REJECTED, fix and resubmit: {e.errors()[0]['msg']}"
    state = await ctx.store.get("state")
    state["arguments"][arg.position] = arg.model_dump()
    await ctx.store.set("state", state)
    return f"{arg.position} argument saved (confidence {arg.confidence:.2f})."


async def produce_fraud_determination(ctx: Context, referral: Referral,
                                      confidence: float, rationale: str) -> str:
    """Record the referral signal after BOTH arguments are in."""
    if referral not in ROUTING:                          # the type hint shapes the schema the
        return f"REJECTED: referral must be one of {list(ROUTING)}"   # LLM sees; it doesn't CHECK
    state = await ctx.store.get("state")
    if set(state["arguments"]) != {"fraud", "legitimate"}:   # guardrail: hear both sides
        return "REFUSED: both the fraud and the legitimacy arguments are required first."
    state["determination"] = {"referral": referral, "confidence": confidence,
                              "rationale": rationale, "next_step": ROUTING[referral]}
    await ctx.store.set("state", state)
    case = await ctx.store.get("case")
    R.log_audit(case, "InvestigationDecision", f"referral {referral}", rationale)
    await ctx.store.set("case", case)
    return f"{referral} → {ROUTING[referral]}"

ARGUE = ("First call get_case_file once. Then call submit_argument once with your structured "
         "argument, citing specific evidence and listing the weaknesses of your OWN argument.")

fraud_advocate = FunctionAgent(
    name="FraudAdvocate", description="Argues the case for fraud.",
    system_prompt=("You are an insurance fraud investigator. Build the strongest possible case "
                   "that this claim is fraudulent. " + ARGUE + " Then hand off to LegitimacyAdvocate."),
    llm=llm, tools=[get_case_file, submit_argument], can_handoff_to=["LegitimacyAdvocate"])

legitimacy_advocate = FunctionAgent(
    name="LegitimacyAdvocate", description="Argues the claim is legitimate.",
    system_prompt=("You are a consumer-protection advocate. Build the strongest possible case "
                   "that this claim is legitimate; give an innocent explanation for EVERY red "
                   "flag. " + ARGUE + " Then hand off to InvestigationDecision."),
    llm=llm, tools=[get_case_file, submit_argument], can_handoff_to=["InvestigationDecision"])

investigation_decision = FunctionAgent(
    name="InvestigationDecision", description="Weighs both arguments.",
    system_prompt=("You are the senior fraud investigator. Weigh both arguments above on evidence "
                   "quality, not on confidence alone. Call produce_fraud_determination once with "
                   "a referral: strong_fraud_indicators, likely_fraud, inconclusive or "
                   "likely_legitimate. You never declare fraud: that is a legal conclusion."),
    llm=llm, tools=[produce_fraud_determination], can_handoff_to=[])

async def investigate(claim_state: dict) -> dict:
    """claim_state: the pipeline's final state (claim + audit_log) for an ESCALATED claim."""
    workflow = AgentWorkflow(
        agents=[fraud_advocate, legitimacy_advocate, investigation_decision],
        root_agent="FraudAdvocate",
        initial_state={"arguments": {}, "determination": None},
    )
    ctx = Context(workflow)
    await ctx.store.set("case", claim_state)           # claim + audit log: kept out of "state"
    handler = workflow.run(user_msg="Investigate the escalated claim.", ctx=ctx, max_iterations=40)
    last = None
    async for ev in handler.stream_events():
        if isinstance(ev, AgentStream) and ev.current_agent_name != last:
            last = ev.current_agent_name
            print(f"\n== {last} " + "=" * (40 - len(last)))
        if isinstance(ev, AgentStream) and ev.delta:
            print(ev.delta, end="", flush=True)
    await handler
    state, case = await ctx.store.get("state"), await ctx.store.get("case")
    return {**state, "audit_log": case["audit_log"]}


if __name__ == "__main__":
    escalated = R.run_offline(R.sample_state(suspicious=True))   # stage 1: pipeline rules
    print("Pipeline decision:", escalated["claim"]["decision"], "→ starting the investigation")
    result = asyncio.run(investigate(escalated))
    for side, arg in result["arguments"].items():
        print(f"\n{side.upper():10} confidence {arg['confidence']:.2f} · weaknesses: {arg['weaknesses']}")
    d = result["determination"]
    print(f"\nREFERRAL: {d['referral']} → {d['next_step']}\nWhy: {d['rationale']}")
📄 Section 9 · underwriting_enrichment.py section9_insurance_claims/underwriting_enrichment.py

Free: canned data, real asyncio.

section9_insurance_claims/underwriting_enrichment.py
"""
Section 9 lab — extension: parallel data enrichment for underwriting (free: canned data)
======================================================================================
Style: a SEQUENTIAL underwriting flow whose enrichment stage runs in PARALLEL.
The three checks don't depend on each other, so we start them together.

How to run:   python underwriting_enrichment.py
(The three checks are stand-ins that sleep and return canned data. In production each
would be a tool-equipped agent calling a credit bureau, a driving-record service and a
property-valuation API.)
"""

import asyncio
import time

# Credit-based insurance scores are banned or restricted in some states (for auto
# insurance, e.g. California, Hawaii, Massachusetts) and pulling a consumer report
# triggers FCRA duties. So the check is switched per jurisdiction, in config — not in a prompt.
CREDIT_CHECK_ALLOWED = {"TX": True, "FL": True, "CA": False, "HI": False, "MA": False}
TIMEOUT_S = 2.0                     # one slow provider must not stall the whole application


async def check_credit(applicant_id: str) -> dict:
    await asyncio.sleep(1.0)        # pretend: a credit-bureau API call
    return {"insurance_score": 742}


async def check_driving_record(license_number: str) -> dict:
    await asyncio.sleep(1.2)        # pretend: a motor-vehicle-records API call
    return {"violations_3y": 1, "at_fault_accidents_3y": 0}


async def check_property_value(address: str) -> dict:
    await asyncio.sleep(3.0)        # pretend: a SLOW valuation API (will time out)
    return {"estimated_value": 615_000}


async def _guarded(coro) -> dict:
    """Run one check with a timeout; a failure becomes a note, not a crash."""
    try:
        return await asyncio.wait_for(coro, timeout=TIMEOUT_S)
    except Exception as e:
        return {"status": "unavailable → manual review", "reason": type(e).__name__}


async def enrich_application(application: dict) -> dict:
    """Run the enrichment checks concurrently and return all results."""
    checks = {
        "driving": check_driving_record(application["license_number"]),
        "property": check_property_value(application["address"]),
    }
    if CREDIT_CHECK_ALLOWED.get(application["state"], False):
        checks["credit"] = check_credit(application["applicant_id"])
    results = await asyncio.gather(*[_guarded(c) for c in checks.values()])
    out = dict(zip(checks, results))
    if "credit" not in checks:
        out["credit"] = {"status": f"skipped: not permitted in {application['state']}"}
    return out


if __name__ == "__main__":
    for app in ({"applicant_id": "A-1", "license_number": "TX-55", "address": "1 Elm St, Austin", "state": "TX"},
                {"applicant_id": "A-2", "license_number": "CA-77", "address": "9 Oak Ave, Fresno", "state": "CA"}):
        t0 = time.perf_counter()
        result = asyncio.run(enrich_application(app))
        print(f"{app['state']}: {time.perf_counter() - t0:.1f}s (one after another it would take "
              f"{1.2 + 2.0 + (1.0 if CREDIT_CHECK_ALLOWED[app['state']] else 0):.1f}s)")
        for k, v in result.items():
            print(f"   {k:9} {v}")