18. AI Agents in Finance & NPS Analyst in a Box#
A fast, conceptual revision guide for 02-ai-agents-finance-notes. Focused on building trustworthy, auditable AI agents in financial services — covering model selection, financial ratio literacy, working and episodic memory, reasoning and verification loops, sequential JSON pipelines, and a multi-agent NPS analytics capstone with deterministic fact-checking.
Finance Domain Foundations & Model Selection#
Revision Notes#
Reference file: Project - AI Agents in Finance.html (Sections 1.1–1.3, 1.5–1.6)
Concept#
General-purpose agent patterns only become bank-ready when paired with financial domain literacy and strict data-governance discipline. In finance, choosing a model or adaptation strategy is driven by data sensitivity first and reasoning depth second, not by picking the largest frontier model for every job.
Key Mental Models#
- Core finance vocabulary you must recognize:
- Earnings & performance: Revenue (top line), Net income (bottom line after costs, interest, and tax), EPS (
net income ÷ shares), Net profit margin (net income ÷ revenue), Guidance (management's forward forecast), YoY (year-over-year comparison), and Fiscal quarter (company-specific accounting calendar). - Market data: Ticker (e.g.,
AAPL,NVDA), OHLCV (Open, High, Low, Close, Volume), Sentiment (positive, negative, neutral), and Portfolio Manager (PM) (the decision-maker who needs concise, evidence-backed briefs).
- Earnings & performance: Revenue (top line), Net income (bottom line after costs, interest, and tax), EPS (
- Two-axis model selection ("Cashier vs. Auditor"):
- Axis 1 — Data sensitivity: Closed APIs (GPT, Claude, Gemini) offer peak capability, but prompts leave the bank. Self-hosted open-weights models (Llama, Mistral, Gemma, GPT-OSS) keep confidential client data in-house at the cost of GPU and ops overhead.
- Axis 2 — Reasoning depth: Fast non-reasoning models ("cashiers") handle high-volume, simple tasks like intraday summaries or sentiment tagging; reasoning models ("auditors") spend extra hidden steps for multi-quarter analysis or complex trade-offs.
- Classifiers vs. generative finance models:
- Specialized classifiers (
FinBERT,SEC-BERT) take a sentence or filing and output a label plus confidence score at high speed and tiny cost — they cannot write summaries, but often beat giant chat models on high-volume tagging (e.g., 50,000 public headlines per hour). - Generative / instruction-tuned finance models (
FinGPT,InvestLM,FinLlama,FinMA,BloombergGPT) and embedded platform assistants (Claude for Financial Services, FactSet Mercury, LSEG Workspace AI, CoCounsel, AlphaSense) handle Q&A, synthesis, and filings analysis. - Finance benchmarks ("exam papers"):
Financial PhraseBank(headline sentiment),FinQA(numerical reasoning over statements),ECTSum(earnings-call summaries), andFiQA(aspect-based Q&A and sentiment).
- Specialized classifiers (
- Prompting vs. fine-tuning vs. tools/RAG:
- Use zero-shot for simple tasks, few-shot (e.g., 3 labeled headlines) for house style, and Chain-of-Thought (CoT) when arithmetic or multi-step logic is required (e.g., comparing profit margins across two years).
- Fine-tuning is rarely the first move in finance because markets move weekly (retaining goes stale fast), client records cannot be uploaded to external sandboxes, decisions depend on live market signals, and bank data is messy.
- Decision rule:
- Stable house style or narrow high-volume classification → fine-tuning or a small specialized classifier.
- Fresh facts (prices, news, ratios) → live data tools.
- Private bank documents → RAG.
- Multi-step analysis, checks, and decisions → agents with tools and memory.
Trade-Offs & Pitfalls#
- The 100-example few-shot wall: Putting 3 examples in a prompt is cheap and effective; putting 100 examples bloats every request's token cost, slows latency, and crowds the context window — switch to retrieval or fine-tuning instead.
- Profit up ≠ healthier business: If revenue grows faster than net income, the net profit margin shrinks. Always check ratios, not just raw dollar increases.
Code Reference#
from pydantic import BaseModel, Field
# Strict Pydantic schema guarantees downstream dashboards and risk checks receive
# typed floats rather than unparsed prose from an LLM.
class PortfolioMetrics(BaseModel):
total_value: float
cagr_pct: float
sharpe_ratio: float
def compute_cagr(start_val: float, end_val: float, years: float) -> float:
"""Never let an LLM do arithmetic — delegate to a verified Python tool."""
# Guard against division-by-zero or negative bases before exponentiation,
# surfacing a clear validation error instead of a NaN or complex number.
if start_val <= 0 or years <= 0:
raise ValueError("start_val and years must be positive")
# Compound Annual Growth Rate: ((V_end / V_start) ** (1 / n) - 1) * 100
return round(((end_val / start_val) ** (1 / years) - 1) * 100, 2)
# -> for (100_000, 161_051, 5): ((1.61051) ** 0.2 - 1) * 100 -> 10.0
from finance_tools import PortfolioMetrics, compute_cagr
cagr = compute_cagr(start_val=100_000, end_val=161_051, years=5)
metrics = PortfolioMetrics(total_value=161_051.0, cagr_pct=cagr, sharpe_ratio=1.42)
print(metrics.model_dump())
# {'total_value': 161051.0, 'cagr_pct': 10.0, 'sharpe_ratio': 1.42}
Structured Outputs, Knowledge Cutoffs & Live Financial Tools#
Revision Notes#
Reference file: Project - AI Agents in Finance.html (Labs 1A, 1B, 1C, 2A & Section 2.1)
Concept#
A standalone LLM is both frozen in time (knowledge cutoff) and unpredictable in formatting. In finance, stale data is wrong data, and loosely formatted text breaks downstream dashboards. Reliable finance agents pair strict output contracts with live deterministic data tools — while remembering that the LLM's interpretation of real numbers still needs human-grade scrutiny.
Key Mental Models#
- "Valid JSON" is not "usable JSON" (Lab 1A):
- Asking three models (GPT-4.1-mini, Gemini 2.5 Flash, Llama 3.1 8B) for JSON with
revenueandepsproduces valid JSON from all three — yet one returns98700000000(a number) while others return"$98.7B (+6% YoY)"(a string), crashing dashboard code likesummary["revenue"] > 90e9. - Fix: Specify exact key names, data types, and units in the contract (e.g.,
revenue_usd: number,revenue_growth_yoy_pct: number), or enforce a strict schema via structured outputs (output_type/ JSON Schema).
- Asking three models (GPT-4.1-mini, Gemini 2.5 Flash, Llama 3.1 8B) for JSON with
- Stale is wrong — live tools & freshness checks (Labs 1B & 1C):
- Asking a plain LLM for "the latest NVIDIA news or price" yields either training-cutoff history (e.g., June 2024) or a polite refusal.
- Wrapping a Python data fetcher (
yfinance) with@function_toolexposes a "menu card" (function name, docstring, type hints) to the LLM. The LLM autonomously translates"Nvidia"into ticker"NVDA", calls the tool, and reads the live result. - Freshness lie detector: Asking for both the price and the date lets you verify instantly whether the answer came from the live tool or stale training memory.
- The three financial ratio families (Section 2.1 & Lab 2A):
- Profitability (how efficiently it earns): Gross margin, Operating margin, Net profit margin, ROA (
net income ÷ total assets), ROE (net income ÷ shareholders' equity). - Valuation (is the price tag fair?): P/E, P/B, P/CF / P/FCF, EV/EBITDA, EV/Sales.
- Liquidity (can it pay bills due this year?): Current ratio, Quick ratio, Cash ratio, Working capital.
- Profitability (how efficiently it earns): Gross margin, Operating margin, Net profit margin, ROA (
- Defensive tool design (Lab 2A):
- When pulling dozens of ratios from a financial API (
Finance Toolkit/ FMP), filter with safe intersection (ratios.index.intersection(desired_names)) so a missing or renamed metric never crashes the tool with aKeyError. - Anchor the current year in the prompt (e.g., "knowing that we are in 2026") so the agent selects the true most recent fiscal year instead of its training cutoff year.
- When pulling dozens of ratios from a financial API (
Trade-Offs & Pitfalls#
- Tools make numbers trustworthy; interpretation is still the LLM's:
- The denominator trap: Apple's ~171% ROE and ~55× P/B look extreme, not because of an API bug, but because heavy share buybacks shrank shareholders' equity (the denominator).
- Shallow textbook readings: An LLM seeing Apple's current ratio of
0.89(< 1.0) will often warn of "potential liquidity issues," missing that Apple generates massive operating cash flow and holds large long-term investments. Always prompt for peer and historical comparisons.
- Model size still affects analytical depth: Small 8B open models can extract surface facts into JSON, whereas larger models synthesize drivers, margins, and strategic context more deeply.
Code Reference#
from openai import OpenAI
from pydantic import BaseModel
# Requiring source_citations alongside numeric fields makes every extracted figure
# auditable against the original SEC 10-K/10-Q paragraph.
class EarningsSummary(BaseModel):
ticker: str
revenue_usd_m: float
yoy_growth_pct: float
key_risks: list[str]
source_citations: list[str]
client = OpenAI()
# beta.chat.completions.parse() uses constrained Structured Outputs so the response
# is guaranteed to match EarningsSummary; temperature=0 maximizes extraction repeatability.
resp = client.beta.chat.completions.parse(
model="gpt-4o-mini",
temperature=0,
messages=[
{"role": "system", "content": "Extract metrics strictly from the provided 10-K excerpt."},
{"role": "user", "content": filing_excerpt},
],
response_format=EarningsSummary,
)
# .parsed returns a validated EarningsSummary instance directly (no manual json.loads).
summary: EarningsSummary = resp.choices[0].message.parsed
# -> EarningsSummary(ticker='ACME', revenue_usd_m=4250.0, yoy_growth_pct=12.4,
# -> key_risks=['FX headwinds in EMEA markets', ...],
# -> source_citations=["Item 7, MD&A p. 42: 'FY2025 revenue rose 12.4% YoY...'"])
# Given a 10-K excerpt for ACME Corp reporting $4,250M revenue (+12.4% YoY):
print(summary.model_dump_json(indent=2))
{
"ticker": "ACME",
"revenue_usd_m": 4250.0,
"yoy_growth_pct": 12.4,
"key_risks": [
"FX headwinds in EMEA markets",
"Customer concentration among top 3 enterprise clients"
],
"source_citations": [
"Item 7, MD&A p. 42: 'FY2025 revenue rose 12.4% YoY to $4,250 million.'"
]
}
Working Memory, Episodic Memory & Context Upkeep#
Revision Notes#
Reference file: Project - AI Agents in Finance.html (Labs 2B, 2C & Section 2.8)
Concept#
Portfolio advisory is never a one-shot query: an agent must remember what the client said two minutes ago (working memory), recall what happened in similar market regimes months ago (episodic memory), respect house rules (semantic memory), and follow standard operating checklists (procedural memory) — all without bloating the context window or violating client suitability rules.
How Working & Episodic Memory Flow (Labs 2B & 2C)#
SQLiteSession preserves multi-turn portfolio state within Day 1, while end-of-day JSON reflections feed ChromaDB so future sessions recall past market regimes as guidance rather than rigid rules.
Key Mental Models#
- Four memory types in a bank:
- Working memory: Today's desk notepad (
SQLiteSession) holding the current allocation, constraints, and multi-turn chat. Without passing the same session on Turn 2, the agent loses the 70/20/10 starting point and cannot size trades — in finance, forgetting turn 1 causes a wrong trade. - Episodic memory: An end-of-day journal capturing past sessions, especially
portfolio_allocation_trajectory(how allocations moved under each market regime), filed in a persistent vector store (ChromaDB) sorted by meaning rather than date. - Semantic memory: Static rulebooks and facts (e.g., max 35% per sector, min 30% in defensive sectors like Healthcare and Utilities, allowed order types).
- Procedural memory: Bank SOP checklists (fetch ratios → check sentiment → check sector exposure → compare to targets → write risk notes), kept under strict controls so agents do not learn bad habits.
- Working memory: Today's desk notepad (
- Guidance, not strict rules: Past episodes may come from a different market regime (e.g., high-volatility declining market vs. low-volatility bullish market). Injecting retrieved memories as guidance lets the agent carry forward client risk preferences without blindly repeating outdated trades.
- Context & memory upkeep (Section 2.8):
- Selective context: Feed only current allocation, recent volatility, relevant past episodes, and active tool schemas — never ten years of raw trade logs.
- Threshold flushing & overflow handling: Frameworks like
LlamaIndexflush short-term chat past a token threshold into three long-term blocks (static facts, extracted facts, vector history), whileCrewAIeither summarizes or halts on overflow. - Hierarchical summaries & forgetting curves: Compress detailed chats → daily summaries → overall profile, and let unused one-off trivia fade while frequently recalled preferences strengthen on each recall.
Trade-Offs & Pitfalls#
- Compliance rule on client profiles: Never let memory frameworks infer hidden personality traits or moods. Financial suitability rules require client preferences to be explicit, sourced, and correctable (e.g., "max 35% per sector, set by client on 12 Oct").
- Two common implementation traps:
- Curly-brace escaping: When using
.format(conversation=...)on a prompt template containing a JSON schema example, double the literal braces ({{/}}) so Python does not mistake JSON keys for format slots. - Chroma query shape & IDs:
collection.query(...)returns nested lists (['documents'][query_index][rank_index]), so[0][0]means first query, best match. Always generate unique IDs per session (or useupsert) so new memories are not silently skipped.
- Curly-brace escaping: When using
Code Reference#
def route_query(intent: str, query: str, tools: dict) -> dict:
"""Route live prices to market APIs, filings to RAG, math to Python."""
# Explicit intent-based dispatch keeps each data modality on its strongest engine:
# live quotes never come from stale RAG chunks, and math never comes from LLM guessing.
if intent == "market_price":
return tools["market_api"](query)
if intent == "sec_filing":
return tools["filing_rag"](query, top_k=5)
if intent == "portfolio_calc":
return tools["python_calc"](query)
# Fail closed on unsupported intents (e.g., tax advice or unverified speculation)
# to satisfy financial compliance boundaries.
return {"refusal": "Query outside supported financial scope."}
tools = {
"market_api": lambda q: {"ticker": q, "price": 228.45, "source": "live_quote"},
"filing_rag": lambda q, top_k=5: {"matches": top_k, "top_hit": "10-K Item 1A Risk Factors"},
"python_calc": lambda q: {"result": 10.0, "unit": "cagr_pct"},
}
print(route_query("market_price", "AAPL", tools))
# {'ticker': 'AAPL', 'price': 228.45, 'source': 'live_quote'}
print(route_query("crypto_tip", "Which coin will 10x?", tools))
# {'refusal': 'Query outside supported financial scope.'}
Reasoning Patterns, Evaluator–Optimizer Loops & Guardrails#
Revision Notes#
Reference file: Project - AI Agents in Finance.html (Section 2.5 & Lab 2E)
Concept#
High-stakes financial workflows cannot rely on a single unverified LLM pass. Production systems combine structured planning, deterministic computation, visible reasoning traces, multi-path voting for ambiguous calls, evaluator–optimizer verification loops, and multi-layer guardrails.
How the Evaluator–Optimizer News Loop Works (Lab 2E)#
A typed Evaluator–Optimizer loop with a hard retry ceiling verifies freshness and links, surrounded by input, tool, task, and output guardrails that block restricted tickers and ungrounded claims.
Key Mental Models#
- Five planning patterns on a trading desk:
- Plan-then-execute: Write the full plan upfront, then execute in order (e.g., trend detection via 20-day moving average).
- Plan-and-execute: Act, inspect results, and dynamically insert new steps (e.g., spotting a debt jump triggers a cash-flow quality check).
- Hierarchical: Break a high-level goal ("cut portfolio volatility") into sub-plans (rebalance equities, shorten bond duration, hedge currency) and concrete trades.
- Planning + ReAct: Each plan step runs its own Think → Act → Observe loop.
- Planning + reflection: Critique the plan before fetching data (e.g., catching a missing cash-flow check early).
- Workflow engineering (LLM vs. code): Not every step in a plan should use an LLM. Let the LLM plan and explain, and let plain Python compute arithmetic (like rolling moving averages) — cheaper, faster, and guaranteed exact.
- Auditable ReAct & graceful tool errors (Lab 2D, LlamaIndex):
- Streaming
Thought → Action → Observationsteps creates an inspectable audit trail for compliance ("why did the system say that?"). - Returning a structured error dict (e.g.,
{"error": "No data found..."}) instead of raising an exception lets a ReAct agent read the error and retry with a corrected ticker.
- Streaming
- Self-consistency for ambiguous calls: For high-stakes judgments (e.g., an earnings beat with falling margins and a CEO departure), run the same CoT prompt multiple times (e.g., 5 paths) with
temperature=1.0and take the majority vote so one brittle reasoning path cannot dominate. - Typed evaluator forms & retry caps (Lab 2E):
- Enforcing an
output_typedataclass withLiteral["successful", "unsuccessful"]turns the judge into a strict tick-box form so Python control flow never parses ambiguous prose. - Always enforce a
max_iterationcap — an unbounded loop between two LLMs can burn tokens indefinitely. Note the off-by-one nuance: checkingnbr_iterations > max_iterationwithmax_iteration = 4allows 5 total runs (1 initial try + 4 retries).
- Enforcing an
- Four guardrail layers in finance:
- Input guardrails: Reject out-of-scope requests before wasting tokens (e.g., asking a fundamentals agent for a 5-year price chart).
- Output guardrails: Block leaks of another client's name or account details before the user sees the reply.
- Tool guardrails: Validate tickers and block restricted-list stocks before calling an external API.
- Task guardrails: Verify intermediate JSON batons contain valid numbers/fields before passing them to the next agent.
Trade-Offs & Pitfalls#
- Self-consistency cost: 5 reasoning paths cost 5× the tokens — reserve it for decisions that matter, not routine headline tagging.
- Stale date-window baking: Interpolating
today_dateandtwo_days_agointo agent instructions via f-strings at initialization time goes stale if a notebook or server stays running overnight; compute dates dynamically per run in production.
Code Reference#
# Hard-coded blocklist catches high-liability advisory language before an answer
# ever reaches the end user (defense-in-depth alongside system-prompt rules).
FORBIDDEN_PHRASES = ("guaranteed return", "buy now", "risk-free profit")
def check_compliance(draft_answer: str, citations: list[str]) -> tuple[bool, str]:
# Case-insensitive scan prevents trivial casing bypasses ("BUY NOW").
lower = draft_answer.lower()
if any(p in lower for p in FORBIDDEN_PHRASES):
return False, "Blocked: contains prohibited investment guarantee language."
# Grounding gate: every financial claim must trace back to at least one verified filing.
if not citations:
return False, "Blocked: financial claim requires at least one filing citation."
return True, draft_answer
from compliance_guard import check_compliance
print(check_compliance("This fund offers a guaranteed return of 15%.", ["10-K p.12"]))
# (False, 'Blocked: contains prohibited investment guarantee language.')
print(check_compliance("Revenue grew 12.4% YoY in FY2025.", []))
# (False, 'Blocked: financial claim requires at least one filing citation.')
print(check_compliance("Revenue grew 12.4% YoY in FY2025.", ["10-K Item 7 p.42"]))
# (True, 'Revenue grew 12.4% YoY in FY2025.')
Sequential Multi-Agent Pipelines & JSON Contracts#
Revision Notes#
Reference file: Project - AI Agents in Finance.html (Lab 2F)
Concept#
When producing an investment memo (BUY / HOLD / SELL), cramming data fetching, ratio interpretation, and final decision-making into one monolithic prompt makes it hard to audit where an error crept in. Splitting the workflow into a sequential relay race of single-purpose agents connected by strict JSON contracts isolates facts from opinions and makes every step inspectable.
How the Relay Pipeline Works (Lab 2F)#
Key Mental Models#
- Strict separation of concerns:
- Agent 1 (Retrieval) fetches only the needed ratio families (profitability + valuation, omitting liquidity to keep context focused) and is forbidden from interpreting.
- Agent 2 (Analysis) rates profitability (
strong|neutral|weak) and valuation (cheap|fair|expensive), cites short evidence, lists 2–3 risks, and carries rawfundamentalsforward so downstream agents can still verify the numbers. - Agent 3 (Decision) synthesizes a
BUY,HOLD, orSELLstance (e.g., strong business + expensive valuation →HOLD), backed by 3 grounded reasons and a 3-item watchlist.
- Why the watchlist matters most to a PM: Listing concrete tripwires that would flip the stance (e.g., "net profit margin drops below 25%" or "P/E compresses") turns a static opinion into an actionable monitoring rule.
- Fixed vocabularies simplify hand-offs: Constraining ratings and stances to fixed enums (
BUY|HOLD|SELL) keeps each downstream agent's logic clean and testable.
Trade-Offs & Pitfalls#
- Knowledge leakage ("spotting the leak"): Even with strict instructions, an analysis agent may sneak ungrounded claims from general training knowledge into
risks(e.g., "market competition impacting future growth" when no ratio mentions competition). In regulated memos, explicitly require every risk to cite an input metric — or ground it with retrieved industry reports. - Prompt-only JSON is fragile: Describing JSON in instructions can break if a model wraps output in markdown code fences. In production, enforce the contract with
output_type(Pydantic/dataclass) or validate the baton with a task guardrail before the next agent runs.
Code Reference#
from pydantic import BaseModel, Field
# Structured rubric schema forces the LLM to classify each customer verbatim into
# consistent dimensions (sentiment, theme, root cause, fix) for reliable aggregation.
class FeedbackTag(BaseModel):
sentiment: str = Field(description="promoter | passive | detractor")
theme: str = Field(description="e.g. onboarding, fees, support, mobile_ux")
root_cause: str
actionable_fix: str
def compute_nps(scores: list[int]) -> float:
# Standard Net Promoter Score formula: %Promoters (9–10) minus %Detractors (0–6);
# Passives (7–8) remain in the denominator but contribute 0 to the numerator.
promoters = sum(1 for s in scores if s >= 9)
# -> for [10, 9, 8, 5, 9, 3, 10, 7]: 4 (scores: 10, 9, 9, 10)
detractors = sum(1 for s in scores if s <= 6)
# -> 2 (scores: 5, 3; passives 8 and 7 stay in len(scores)=8)
return round(((promoters - detractors) / len(scores)) * 100, 1)
# -> round(((4 - 2) / 8) * 100, 1) = 25.0
from nps_analyst import FeedbackTag, compute_nps
print("NPS:", compute_nps([10, 9, 8, 5, 9, 3, 10, 7]))
# NPS: 25.0
tag = FeedbackTag(
sentiment="detractor",
theme="onboarding",
root_cause="KYC document upload timed out twice on mobile",
actionable_fix="Add resumable uploads and client-side image compression",
)
print(tag.model_dump())
# {'sentiment': 'detractor', 'theme': 'onboarding', 'root_cause': 'KYC document upload timed out twice on mobile', 'actionable_fix': 'Add resumable uploads and client-side image compression'}
Capstone Architecture: NPS Analyst in a Box#
Revision Notes#
Reference file: Project - NPS Analyst in a Box.html
Concept#
The capstone applies the multi-agent finance blueprint to a bank's internal customer experience problem: turning 600 quarterly Net Promoter Score (NPS) survey responses (with 536 free-text comments) into a CEO-ready one-page brief that explains how bad the drop is, why it happened, how much revenue is at risk, and what to fix first vs. who to call back this week — with every number computed and verified by plain Python.
How the 3-Phase Team & Code Auditor Work#
Parallel specialist agents connect survey comments to financial churn exposure, while fact_check.py deterministically recomputes every metric, sign, and ₹ lakh figure before CEO delivery.
Key Mental Models#
- Just-enough NPS math & statistical honesty:
- Three buckets (0–10 scale): Promoters (9–10), Passives (7–8), Detractors (0–6 — note how harsh the scale is: a 6 is a detractor).
- Formula:
NPS = % promoters − % detractors(passives stay in the denominator). NPS ranges from−100to+100and is a score, never a percentage (write+18.5, not18.5%). - Small groups wobble: Attach a 95% margin of error to every segment NPS. Flag any segment with
< 30responses aslow_sampleand forbid agents from crowning it "best" or "worst."
- Connecting CX to finance ("NPS is a money number"):
- Expected loss formula:
revenue at risk = Σ (customer's annual revenue × assumed annual churn probability), using explicit house assumptions inconfig.py(e.g., Promoter3%, Passive10%, Detractor25%). - Loud ≠ expensive: The complaint with the highest headcount (e.g., Savings/Card app OTP failures) may represent far less annual revenue than a handful of unhappy Wealth customers (e.g., unexplained advisory fees). Therefore, the brief must rank fixes two ways — by NPS points recovered and by ₹ lakh saved — and prioritize immediate high-value callbacks separately from product fixes.
- Unit hygiene: Report monetary values in ₹ lakh (
1 lakh = ₹1,00,000) from Python tools so the LLM never miscounts zeros.
- Expected loss formula:
- Hands, Brains, Manager, and Auditor:
- Hands (Tools): Plain pandas/Python functions (
survey_tools.py,theme_tools.py,whatif_tools.py) that are unit-testable without an LLM and never crash on bad input. - Brains (5 Specialists): Decide where to drill down, interpret customer comments, connect themes to money, and explain trade-offs.
- Manager (
OrchestratorAgent): Delegates to specialists via.as_tool()across three phases (parallel analysis → dependent planning → synthesis) without doing the analysis itself. - Auditor (
fact_check.py): Deterministic Python code that re-computes headline numbers and verifies the final brief quotes them accurately with correct signs and units — turning a probabilistic demo into something safe to hand to a CEO.
- Hands (Tools): Plain pandas/Python functions (
- The three hidden stories & skeptical data analysis:
- What caused the NPS drop from
+32(July) to−6.5(September). - Where the revenue at risk actually concentrates (loudest complaint vs. most expensive segment).
- Data-quality traps: Detecting score–comment mismatches (e.g., a customer who enters
0but writes "Excellent service, love it!" — likely reversing the scale). A disciplined analyst flags the anomaly and reports the alternative NPS, without silently altering the official headline score.
- What caused the NPS drop from
Trade-Offs & Pitfalls#
- Hidden assumptions break trust: Churn probabilities (
3% / 10% / 25%) are illustrative assumptions, not observed facts. Echoing them in every tool payload and printing them underDATA CAVEATSmakes them transparent and challengeable. - Why agents instead of a 20-line pandas script?: Pandas computes the score instantly, but agents add value in reading hundreds of unstructured comments, choosing follow-up slices dynamically, linking themes to revenue impact, and synthesizing an executive brief — while keeping all arithmetic strictly inside Python.
- Deterministic verification vs. LLM-only checks: Keyword-based theme rules are fast and reproducible, while stretch upgrades like LLM theme tagging (
Literal[...]+ CSV cache), label-aware fact-checking, or retry guardrails (sending failed briefs back to the writer at most twice) push reliability even further.
How All Building Blocks Connect#
Revision Notes#
This module progresses from single-call finance basics to a full, auditable multi-agent system:
- Governance & Domain Grounding (Section 1): Start by picking the right model for data sensitivity and reasoning depth, and use live tools rather than stale training weights or premature fine-tuning.
- Trustworthy Data & Contracts (Labs 1A–1C, 2A): Enforce typed schemas (
output_type/ explicit units) and wrap financial APIs in defensive@function_toolfunctions — while applying ratio literacy to catch shallow LLM interpretations. - Continuity & Learning (Labs 2B–2C, Section 2.8): Add
SQLiteSessionfor within-chat working memory and persistentChromaDBjournals for cross-session episodic memory, keeping client profiles explicit and compliance-friendly. - Reliability & Auditability (Section 2.5, Labs 2D–2F): Combine workflow engineering (code for math, LLM for reasoning), streamed ReAct traces, self-consistency voting, bounded Evaluator–Optimizer loops, four guardrail layers, and sequential JSON-baton pipelines.
- Production Blueprint (NPS Analyst in a Box): Synthesizes every pattern into a 3-phase orchestrated team (
parallel analysis → dependent planning → synthesis) governed by the golden rule of financial AI: code computes, agents reason, and deterministic code audits the final output.
Quick Self-Check Questions#
Self-Check Questions#
Why should you evaluate data sensitivity before reasoning depth when picking a model at a bank?
If client or transaction data cannot legally leave the bank's infrastructure, hosted closed models are immediately ruled out regardless of capability — you must use self-hosted open-weights models first, then size them for reasoning depth.
Why is "valid JSON" not enough for a financial dashboard?
A model can return valid JSON with formatted strings like "$98.7B (+6% YoY)" instead of numeric values in a fixed unit (98700000000), causing downstream numeric comparisons to crash. Always enforce explicit types and units via structured schemas (output_type / JSON Schema).
Apple's ROE is ~171% and its current ratio is ~0.89. What lesson do these two numbers teach agent builders?
Tools guarantee accurate numbers, not accurate interpretations. A ratio is a fraction: buybacks shrank Apple's equity denominator (inflating ROE), and strong operating cash flow makes a sub-1.0 current ratio deliberate rather than distressed.
What breaks in a multi-turn portfolio rebalancing chat if you forget to pass the same SQLiteSession on Turn 2?
Each run is stateless; without the session re-sending Turn 1, the agent loses the starting allocation (e.g., 70/20/10) and cannot size the required buy/sell trades accurately.
Why are retrieved episodic memories injected into a rebalancing prompt as "guidance, not strict rules"?
Market regimes change (e.g., high-volatility declining yesterday vs. low-volatility bullish today). The agent should preserve client preferences and lessons learned without blindly repeating yesterday's trades.
In an Evaluator–Optimizer loop, why must the evaluator use a strict output_type (like Literal["successful", "unsuccessful"]) and a max_iteration cap?
A typed form gives Python a reliable pass/fail branch instead of parsing vague prose, and a hard retry cap prevents two LLMs from looping and burning tokens indefinitely.
In the NPS Analyst capstone, why does the brief rank fixes in two ways (NPS points vs. ₹ lakh at risk) and run fact_check.py after the writer?
Because the loudest complaint by headcount is often not the most expensive one by revenue (loud ≠ expensive), and running a deterministic Python auditor after the LLM writer guarantees every headline number, sign, and unit in the CEO brief matches the underlying data.