Future with Shivank · Hands-on track · Section 5
Deep Search Build an analyst-grade research agent that plans, digs, double-checks and writes the memo
In Section 4 the workflow was fixed in advance: the same five agents, the same three phases, for every stock. A deep search agent goes one step further: it writes its own research plan for whatever question you ask, runs the plan in parallel, checks its numbers with plain Python, and if something is missing it re-plans and tries again — before writing a structured investment memo.
ReAct loops (Section 2), RAG (AWS module, Section 1), multi-agent orchestration and agents-as-tools (Section 4), Pydantic output schemas and PydanticAI (Section 3), MCP (Section 3), async/await basics (Section 1 setup).
Section 5 · Part 1 — The idea
From "answer a question" to "do the research"
5.1What is deep search?
Deep search (also called deep research) is an agent that plans a research strategy, gathers information from many sources in several rounds, checks what it found, and writes a structured report. It is not a faster search engine; it is an automated junior analyst.
Basic RAG is asking a librarian: "find me the page that mentions NVIDIA's revenue." One trip to one shelf, one answer.
Deep search is hiring a research analyst: they write a to-do list, send juniors to five different sources at once, check that the numbers agree, notice "we're missing AMD's figures", go back for them, and only then write the memo.
| Basic RAG | Deep search agent | |
|---|---|---|
| Planning | None | Writes its own research plan with sub-tasks |
| Sources | One pre-built vector store | Live APIs, SEC filings, news, databases |
| Maths | Can't compute over what it finds | Calculates growth, margins, P/E through tools |
| Checking | None | Validates, cross-checks, finds gaps |
| Output | A short answer | A multi-section research memo |
| Time | 1–5 seconds | 30 seconds to a few minutes |
RAG is perfect for "What was NVIDIA's revenue in 2024?" It breaks on "Compare NVIDIA, AMD and Intel on growth, competition and risk, and write a memo" — three companies, several data types, calculations, cross-checks, a structured write-up.
- Many sources are normal: filings, earnings calls, prices, ratios, news, macro data — no single database has them all.
- Accuracy is non-negotiable: a wrong number can mean a wrong trade or a regulatory problem, so built-in checking matters.
- Speed is an edge: read a fresh quarterly filing and flag surprises in minutes, not hours.
- Scale is the bottleneck: an analyst can research 2–3 companies deeply in a day; an agent can cover an entire index and let the analyst focus on decisions.
You've probably used the consumer versions: Gemini Deep Research (Dec 2024), OpenAI Deep Research (Feb 2025) and Perplexity's deep research mode all made this pattern mainstream. The underlying method — plan, search, check, write — is simply how good analysts and investigative journalists have always worked.
5.2Anatomy of a deep search agent
Every deep search agent, whatever the framework, runs the same four-phase loop:
- Plan — split the question into sub-tasks with explicit dependencies. Good tasks are measurable ("fetch AMD revenue") not vague ("understand AMD").
- Execute — run each sub-task with the right tool; independent tasks run at the same time; findings are written to a scratchpad.
- Validate — check consistency (do two sources agree?), completeness (all three companies?), reasonableness (is 500% growth real or a parsing mistake?) and gaps.
- Synthesize or re-plan — if checks pass, write the report; if not, go back to step 1 knowing exactly what's missing.
| Component | Its job | Office analogy |
|---|---|---|
| Planner | Turns the question into sub-tasks + dependencies | Team lead writing the to-do list on a whiteboard |
| Tool executor (researcher) | Calls APIs, filings search, web search | Junior analysts sent out to fetch data — several at once |
| Validator | Checks completeness, ranges, contradictions | The auditor with a printed checklist |
| Synthesizer | Writes the final structured report | The senior analyst who writes the memo |
| Orchestrator | Runs the loop, decides when to retry | The project manager |
| Scratchpad / context manager | Logs every step; keeps the token budget under control | The case file — and the habit of summarising it |
Three ways to arrange those parts
Our project is a hybrid of ② and ③: separate planner / researcher / validator / synthesizer roles, a dependency graph with parallel waves, and a validator written in plain Python.
The story that proves the point: three attempts at the same agent
The open-source AI Alliance team documented building a finance deep-research agent three times. It's the most useful story in this whole section:
Use code to check numbers; use the LLM to reason and write. An LLM asked "does this look right?" can be talked into a plausible wrong number. if operating_margin > gross_margin: can't. (Same lesson as Section 4's peer verdict.)
5.3Financial data: the real challenge
Building a deep search agent is as much data engineering as AI. Fintool's founder has called financial data "adversarial" — it actively resists being read by machines — and estimates data clean-up is about 80% of the engineering work. Once the data is clean, the LLM reasoning is the easy part.
| Kind of data | Examples | How hard? |
|---|---|---|
| Structured | Prices, revenue, EPS, ratios via APIs | Easy — clean JSON. Watch rate limits, freshness, cost. |
| Semi-structured | SEC filings, earnings-call transcripts, news | Hard — messy HTML, speaker labels, duplicates. Each source needs its own parser. |
| Unstructured | Analyst PDFs, web pages, ESG reports | Hardest — PDF tables break, paywalls, scraping. |
| Macro | Interest rates, inflation, jobs data | Easy to fetch, hard to connect to one company. |
Trap 1 · A real-looking 10-K table
What a human reads
| Revenue (in millions) | 2024 | 2023 | 2022 |
|---|---|---|---|
| Products | $89,394 | $78,932 | $68,412 |
| Services(1) | 24,631 | 22,314 | 19,876 |
| Total revenue | $114,025 | $101,246 | $88,288 |
What a naive parser trips on
Other classics: negatives written as (1,234), the same document mixing $1,234.5M, 1.2B and 1,234,500 thousand, units that change mid-table without warning, merged cells. Now imagine dozens of such tables per filing.
Trap 2 · "Q1 2024" means different months for different companies
Companies pick their own financial year. Compare "Q1 2024" across them naively and you compare different months — a silent error: the output looks perfectly plausible and is wrong.
Drag to any month — see what each company calls it
NVIDIA's year ends in late January, so its "FY2024" revenue of $60.9B mostly happened in calendar 2023. AMD and Intel use calendar years. A careful agent says which periods it is comparing — and production systems convert everything to calendar quarters before the LLM ever sees it.
Five rules production teams follow
- Use APIs when they exist — don't scrape what you can query.
- Score your confidence in extracted values; send low-confidence ones for checking.
- Normalise units and periods early, in code. Don't leave it to the LLM — it will slip.
- Cache aggressively — a filed quarter never changes.
- Hand the LLM clean data, not raw text:
"NVIDIA Corp 10-K FY2024... Revenue... see Note 3... $60,922M... includes revenue from... (in millions except per share data)..."
{"ticker": "NVDA", "metric": "revenue", "period": "FY2024", "value": 60922, "unit": "millions_usd", "source": "10-K", "filing_date": "2024-02-21"}
How tools get wired in — three patterns you'll meet: direct tools (one Python function per source — what our lab uses, simplest to read), a meta-tool (one financial_search(query) that routes internally to the right source — keeps the agent's tool list short), and MCP servers (standard plug-in tools any framework can discover — best for sharing across teams).
Section 5 · Part 2 — Build it, step by step
The project: a research desk, written in Python
5.4The project & its map
Our agent gets one real research question from the portfolio manager:
Why can't one LLM call — or the basic RAG you built on AWS — answer this well? Because the question quietly hides five different jobs:
Three decisions before writing any code
Picture the desk on Monday morning. The desk head (planner) writes a to-do list on the whiteboard, with arrows meaning "do this after that". Runners (researcher + tools) grab every card that can start — all at once — and pin what they find to a shared board. A compliance checker (validator) walks the board with a calculator and a checklist. A memo writer (synthesizer) turns the board into the memo. The desk manager (orchestrator) decides: "good enough, write it" or "something's missing — plan again".
| Job | Desk role | File | Uses an LLM? |
|---|---|---|---|
| Turn the question into tasks | Desk head | planner.py | ✅ yes — structured output |
| Fetch numbers, filings, news | Runners | tools/*.py | ❌ no — plain API calls |
| Run the tasks in the right order | Runner coordinator | researcher.py | Only for "thinking" tasks 6 & 7 |
| Check the findings | Compliance | validator.py | ❌ never |
| Write the memo | Memo writer | synthesizer.py | ✅ yes — structured output |
| Run the loop, decide to retry | Desk manager | deep_search_agent.py | ❌ no — a for loop |
Half of this "AI agent" is ordinary Python. That's on purpose: code is cheap, fast and gives the same answer every time. Use the LLM only where you need judgement or language.
The map: one full run
Click through the run and watch the variables change
Gold on the map = what's happening at this step. The boxes in the panel are the real variable names from the code you're about to read — a gold box changed at this step.
Why "all at once" matters
A chef with five ovens doesn't stand in front of oven 1 until the cake is done before putting the bread in oven 2. She fills all five, then waits for the slowest dish. Tool calls are the same: most of their time is spent waiting for a server on the internet. While one call waits, Python can start the others. That's what async / await and asyncio.gather give us.
Wave 1 has one metrics task per company (≈2 s each), plus the filings task (≈4 s) and the news task (≈5 s). Add companies and watch both timelines. Timings are illustrative.
APIs limit how many calls you may make per second. With 50 companies, "all at once" can earn you 429 Too Many Requests. The usual fix is a small "only N at a time" gate called asyncio.Semaphore — like letting only five customers into the bank branch at once.
5.5The data models — the forms everyone fills in
Banks run on forms. A loan application has fixed boxes — name, amount, tenure — and the clerk won't accept "amount: banana". Pydantic models are the agent's forms. Every part hands the next part a filled-in form, and Python refuses a form with a missing or wrong box. That's what stops one confused component from quietly poisoning the next.
# common.py — the "forms" that every part of the agent fills in
from enum import Enum
from pydantic import BaseModel, Field
class TaskStatus(str, Enum): # the 4 stickers a task can wear
PENDING = "pending" # not started yet
RUNNING = "running" # a tool is working on it
COMPLETED = "completed" # finished, result saved
FAILED = "failed" # the tool raised an error
class SubTask(BaseModel):
"""A single research sub-task within a plan."""
id: int # 1, 2, 3 …
description: str # the job, in plain English
data_sources: list[str] = Field(
description="Tools: 'financial_api', 'sec_filing', 'web_search'"
)
dependencies: list[int] = Field(default_factory=list) # ids to wait for
status: TaskStatus = TaskStatus.PENDING # only OUR code changes this
class ResearchPlan(BaseModel): # what the planner returns
question: str
sub_tasks: list[SubTask]
class CompanyMetrics(BaseModel): # one company, clean numbers
ticker: str
revenue: float | None = None # $ millions
revenue_growth: float | None = None # % vs the year before
eps: float | None = None # earnings per share, $
gross_margin: float | None = None # %
operating_margin: float | None = None # %
pe_ratio: float | None = None # price ÷ EPS
market_cap: float | None = None # $
class ValidationResult(BaseModel): # the checker's report card
is_valid: bool
errors: list[str] = Field(default_factory=list) # impossible numbers
warnings: list[str] = Field(default_factory=list) # odd but possible
gaps: list[str] = Field(default_factory=list) # missing pieces
class ResearchReport(BaseModel): # the final memo
title: str
executive_summary: str
key_metrics_table: str
competitive_analysis: str
risk_factors: list[str]
conclusion: str
sources: list[str]
confidence_score: float = Field(description="Between 0 and 1")TaskStatus(str, Enum)— the four stickers. An Enum is a fixed menu of allowed values, so a typo likeTaskStatus.COMPLETDcrashes immediately instead of silently never matching. Mixing instrmakes each sticker also a normal string, so it prints and saves to JSON as"completed".Field(description=...)ondata_sourcesisn't just a comment for humans: it's sent to the LLM as part of the form's instructions. That's how the planner learns the only three tool names it may use.default_factory=listmeans "if nobody fills this in, start with a fresh empty list". An emptydependencieslist means "this task can start straight away".statusdefaults toPENDING. The LLM simply writes"pending"; from then on only our code moves the sticker forward.float | None = Nonereads "a number, or honestly unknown". A missing value staysNone— never0. An unknown margin and a 0% margin are very different facts, and the validator treats them differently.ValidationResulthas three buckets — errors, warnings, gaps — that you'll meet in 5.9.ResearchReportis the memo template: every memo has the same sections, so the PM always knows where to look.
What a filled-in plan looks like
This is the kind of ResearchPlan the planner returns for our question (shown as JSON; wording varies run to run):
{
"question": "Analyze NVIDIA's financial performance ... research memo.",
"sub_tasks": [
{"id": 1, "description": "Fetch NVIDIA (NVDA) revenue, growth, margins and P/E",
"data_sources": ["financial_api"], "dependencies": [], "status": "pending"},
{"id": 2, "description": "Fetch AMD revenue, growth, margins and P/E",
"data_sources": ["financial_api"], "dependencies": [], "status": "pending"},
{"id": 3, "description": "Fetch Intel (INTC) revenue, growth, margins and P/E",
"data_sources": ["financial_api"], "dependencies": [], "status": "pending"},
{"id": 4, "description": "Extract key risk factors from the latest 10-Ks of NVIDIA, AMD and Intel",
"data_sources": ["sec_filing"], "dependencies": [], "status": "pending"},
{"id": 5, "description": "Find recent AI-chip market news on NVIDIA, AMD and Intel",
"data_sources": ["web_search"], "dependencies": [], "status": "pending"},
{"id": 6, "description": "Compare revenue growth, profitability and valuation",
"data_sources": [], "dependencies": [1, 2, 3], "status": "pending"},
{"id": 7, "description": "Draft the investment memo from metrics, risks and news",
"data_sources": [], "dependencies": [4, 5, 6], "status": "pending"}
]
}dependencies
"dependencies": [1, 2, 3] on task 6 means "task 6 may start only after tasks 1, 2 and 3 are COMPLETED". An empty list [] means "no waiting — start now". Compare this JSON with the map above: it's the same graph, written as text.
5.6Step 1 · The planner — from one question to a to-do list
A good desk head doesn't start researching. She writes the cards: one card per job, which source to use, and arrows for what must wait. A good plan is boring and repeatable — ask the same question twice, get the same cards. That's why the planner runs at temperature 0.
# planner.py — turns ONE question into a to-do list (a ResearchPlan)
from openai import AsyncOpenAI
from common import ResearchPlan
PLANNER_PROMPT = """You are a financial research planner. Given a research
question, decompose it into concrete sub-tasks that can be executed by tools.
Available data sources:
- financial_api: Structured financial metrics (revenue, EPS, margins, P/E, market cap)
- sec_filing: SEC filing content (risk factors, business descriptions, MD&A)
- web_search: Recent news, competitive intelligence, analyst commentary
Rules:
1. Each sub-task must have a clear, measurable outcome.
2. Specify which data_sources each sub-task should use.
3. Mark dependencies — which tasks must complete before others can start.
4. Tasks with no dependencies can run in parallel.
5. Always include a final synthesis task that depends on all data-gathering tasks.
6. For multi-company comparisons, create parallel tasks for each company.
Respond with a JSON object matching the ResearchPlan schema."""
async def create_research_plan(question: str) -> ResearchPlan:
"""Generate a structured research plan from a question."""
client = AsyncOpenAI() # ① reads OPENAI_API_KEY
response = await client.chat.completions.parse( # ② ask, and force the shape
model="gpt-4o",
messages=[
{"role": "system", "content": PLANNER_PROMPT},
{"role": "user", "content": question},
],
response_format=ResearchPlan, # ③ "fill in THIS form"
temperature=0, # ④ same question → same plan
)
return response.choices[0].message.parsed # ⑤ a ResearchPlan objectHow the prompt's six rules show up in the plan
| Rule in the prompt | What you see in the plan |
|---|---|
| 1 · Clear, measurable outcome | "Fetch AMD revenue, growth, margins and P/E" — not "look into AMD" |
| 2 · Name the data sources | "data_sources": ["financial_api"] on tasks 1–3 |
| 3 · Mark dependencies | "dependencies": [1, 2, 3] on task 6 |
| 4 · No dependencies → parallel | Tasks 1–5 all have [], so they form wave 1 |
| 5 · A final synthesis task | Task 7 waits for 4, 5 and 6 |
| 6 · One task per company | Three separate tasks 1, 2, 3 — not one "fetch all three" task, so they can run side by side and fail independently |
The code, line by line
AsyncOpenAI()creates the async version of the OpenAI client. It finds your key in theOPENAI_API_KEYenvironment variable — never paste keys into code.await client.chat.completions.parse(...)—awaitmeans "start this, and while we wait for OpenAI's reply, Python may get on with other jobs". We use.parse(not.create) because it's the structured-output version.response_format=ResearchPlan— the magic line. The SDK turns our class into a JSON schema, the model is constrained to reply in exactly that shape, and the SDK turns the reply back into a realResearchPlanobject.temperature=0— the creativity dial at minimum. Same question → (almost) the same plan, which makes runs easy to compare and debug.response.choices[0].message.parsed— unwrapping the parcel:responseis the whole reply envelope →choices[0]the first (and only) answer →message→parsed, our ready-made object.
What .parse does for you behind the scenes. You write the first and get the last; the middle three steps are automatic.
| Variable | Type | What it holds |
|---|---|---|
question | str | "Analyze NVIDIA's financial performance…" |
client | AsyncOpenAI | A connection to OpenAI, with your key |
response | completion envelope | id, token usage, choices list… |
response.choices[0].message.parsed | ResearchPlan | The question + 7 SubTask objects — returned to the caller as plan |
- If the model refuses (rare),
parsedisNoneand the reason sits inmessage.refusal. Check for it before using the plan. - Save every plan to a log file. When a memo looks odd next week, the plan is the first thing compliance will ask to see.
5.7Step 2 · The tools — couriers who also translate
Each data source is a different office with its own address, its own password and its own paperwork. A tool function is a courier who knows one office: it goes there, shows the password, collects the parcel — and then translates the paperwork into our bank's standard form before handing it back. The rest of the agent never sees the office's messy format.
| Tool | Goes to | Needs | Brings back | Typical failures |
|---|---|---|---|---|
get_financial_metrics(ticker) | Financial Datasets API | API key | A clean CompanyMetrics form | wrong key (401), unknown ticker (404), too many calls (429) |
get_risk_factors(ticker) | SEC EDGAR (free, official) | your email | "Item 1A · Risk Factors" text from the latest 10-K | blocked without an email header; very long text |
search_financial_news(query) | Tavily web search | API key | 5 recent articles from trusted sites | stale or off-topic results |
Tool 1 · get_financial_metrics — the most important one
# tools/financial_data.py — fetch ONE company's numbers and clean them up
import os
import httpx
from common import CompanyMetrics
BASE_URL = "https://api.financialdatasets.ai"
def _pct(part, whole):
"""part ÷ whole as a percent (1 decimal), or None if we can't work it out."""
if part is None or not whole:
return None
return round(part / whole * 100, 1)
async def get_financial_metrics(ticker: str) -> CompanyMetrics:
headers = {"X-API-KEY": os.environ["FINANCIAL_DATASETS_API_KEY"]} # ① password
async with httpx.AsyncClient(base_url=BASE_URL, headers=headers,
timeout=30) as client: # ② open line
income_resp = await client.get( # ③ 2 years
"/financials/income-statements",
params={"ticker": ticker, "period": "annual", "limit": 2},
)
price_resp = await client.get("/prices/snapshot", # ④ price
params={"ticker": ticker})
income_resp.raise_for_status() # ⑤ 401 / 404 / 429 / 500 → error
price_resp.raise_for_status()
statements = income_resp.json()["income_statements"] # ⑥ newest year first
latest = statements[0]
prior = statements[1] if len(statements) > 1 else None
snapshot = price_resp.json()["snapshot"]
price = snapshot.get("price") or snapshot.get("close")
revenue = latest.get("revenue") # in plain dollars
eps = latest.get("earnings_per_share")
growth = None
if revenue and prior and prior.get("revenue"): # ⑦ growth needs 2 years
growth = round((revenue / prior["revenue"] - 1) * 100, 1)
return CompanyMetrics( # ⑧ the clean form
ticker=ticker,
revenue=round(revenue / 1_000_000, 1) if revenue else None, # → $ millions
revenue_growth=growth,
eps=eps,
gross_margin=_pct(latest.get("gross_profit"), revenue),
operating_margin=_pct(latest.get("operating_income"), revenue),
pe_ratio=round(price / eps, 1) if price and eps and eps > 0 else None,
market_cap=snapshot.get("market_cap"),
)- The password.
headersis a small dictionary sent with every request. The key comes from the environment, never from the code. async with httpx.AsyncClient(...) as client:opens a connection — think of it as a phone call. Thewithblock hangs up automatically when it ends, even if something goes wrong inside.base_urlsaves typing the address twice;timeout=30means "give up after 30 seconds instead of waiting forever".- Two years of income statements (
limit=2). Why two? Growth needs this year and last year. - Today's price from the price snapshot — needed for P/E.
raise_for_status()turns an HTTP failure (401, 404, 429, 500…) into a Python error. That sounds bad, but it's exactly what we want: the error travels up torun_task, which marks the task FAILED (5.8), which the validator turns into a gap (5.9), which triggers a re-plan. Silent failures are the dangerous ones.- Unpack the parcel.
.json()turns the reply into a Python dictionary.statements[0]is the newest year,statements[1]the year before.snapshot.get("price") or snapshot.get("close")means "useprice; if it's missing, useclose". - Growth is only calculated if both years have revenue — otherwise it stays
None. - Translate into our form. Dollars → millions, ratios → percentages, P/E only if earnings are positive.
Before: what the API sends (trimmed)
After: what the rest of the agent sees
Illustrative values for NVIDIA's fiscal year 2024 (which ended in January 2024 — remember the fiscal calendar in 5.3).
| Number | Formula in the code | Worked example (NVIDIA) |
|---|---|---|
| Revenue growth | (revenue / prior - 1) * 100 | (60,922 ÷ 26,974 − 1) × 100 = 125.9% |
| Gross margin | gross_profit / revenue * 100 | 44,301 ÷ 60,922 × 100 = 72.7% |
| Operating margin | operating_income / revenue * 100 | 32,972 ÷ 60,922 × 100 = 54.1% |
| P/E | price / eps | 817.2 ÷ 11.93 = 68.5× |
💰 Finance corner: the four numbers in plain words optional · glance over
Imagine a sweet shop. Revenue is everything customers paid. Gross margin is what's left after paying for the sugar and milk, as a % of revenue. Operating margin is what's left after also paying rent, salaries and electricity — so it is always smaller than gross margin. Revenue growth compares this year's sales with last year's. P/E asks: "how many years of today's profit would I pay to buy one share?" A P/E of 68 means investors pay 68 years' worth of current profits — they expect profits to grow a lot.
- P/E only when EPS > 0. A loss-making company has negative earnings, and "price ÷ negative number" is meaningless. We store
Noneinstead. - Field names change. APIs rename fields (
pricevsclose). Before trusting any tool, print one raw response and read it. - The two calls run one after the other. They could also run together with
asyncio.gather— a nice small exercise once you've finished 5.8.
What happens when a call fails — the error's journey
One failed courier never crashes the desk. It turns into a note that travels up until someone with the authority to act — the desk manager — decides what to do. You'll make AMD fail on purpose in the simulation in 5.8.
Tool 2 · search_financial_news
# tools/web_search.py — recent news, from trusted publishers only
import os
from tavily import AsyncTavilyClient
TRUSTED = ["reuters.com", "bloomberg.com", "wsj.com",
"cnbc.com", "seekingalpha.com", "ft.com"]
async def search_financial_news(query: str) -> str:
client = AsyncTavilyClient(api_key=os.environ["TAVILY_API_KEY"])
response = await client.search(
query,
topic="news", # news search, not the whole web
include_domains=TRUSTED, # only these publishers
max_results=5,
)
# a list of hits → one readable block of text for the LLM
return "\n\n".join(
f"{hit['title']} ({hit['url']})\n{hit['content']}"
for hit in response["results"]
)include_domains=TRUSTED is the important line: it keeps the agent away from random blogs and forums. The last statement is a generator expression inside "\n\n".join(...) — read it as "for every hit, write title (link) and summary, and glue them together with blank lines". The LLM gets one tidy block of text with sources it can cite.
Tool 3 · get_risk_factors (in words)
SEC EDGAR is the US regulator's free filing system. The tool finds the company's latest annual report (the 10-K) and pulls out section Item 1A · Risk Factors — where companies must list what could hurt them (supply chains, export rules, key customers…). Two rules: EDGAR wants a contact email in the request's User-Agent header (that's why .env has SEC_EDGAR_EMAIL), and it allows roughly 10 requests per second. Filings run to 100+ pages, so the tool trims the text before returning it — fewer tokens, lower cost.
5.8Step 3 · The researcher — run the plan in waves
In a restaurant kitchen, orders hang on a rail. Every round, the head chef looks at the rail and asks one question: "which tickets can I cook right now?" — the ones whose ingredients are ready. She fires all of them at once, waits for that round to finish, then looks at the rail again. When no ticket is left, service is over. If some tickets are stuck waiting for an ingredient that will never arrive, she stops instead of staring at the rail forever.
# researcher.py — run the whole plan, wave by wave
import asyncio
from common import ResearchPlan, TaskStatus
async def execute_plan(plan: ResearchPlan) -> dict[int, str]:
results: dict[int, str] = {} # ① the shared notebook
tasks_by_id = {t.id: t for t in plan.sub_tasks} # ② id → task lookup
while any(t.status == TaskStatus.PENDING for t in plan.sub_tasks): # ③
ready = [ # ④ who can start now?
t for t in plan.sub_tasks
if t.status == TaskStatus.PENDING
and all(tasks_by_id[d].status == TaskStatus.COMPLETED
for d in t.dependencies)
]
if not ready: # ⑤ stuck → stop the loop
break
completed = await asyncio.gather( # ⑥ run the wave together
*[run_task(t, results) for t in ready]
)
for task_id, result in completed: # ⑦ write it all down
results[task_id] = result
return resultsresults— the shared notebook. A dictionary: key = task id, value = what that task found (as text). It starts empty; by the end it looks like{1: '{"ticker": "NVDA", …}', 2: …, 7: "Draft memo…"}.tasks_by_id— a phone book. This is a dict comprehension; read it as "for every tasktin the plan, file it undert.id". Nowtasks_by_id[3]instantly gives task 3, so we can ask "is task 3 done?" in one step.while any(...)—any()asks "is at least one of these true?". Keep going while at least one task still wears the PENDING sticker.ready— who can start now? Read it aloud: "every tasktthat is PENDING and whose every dependencydis COMPLETED".if not ready: break— the safety exit. Tasks are still pending, but none can start: they're waiting for a task that failed. Without this line the loop would spin forever.asyncio.gather(*[...])— fire the whole wave. The list[run_task(t, results) for t in ready]builds one "job" per ready task (nothing runs yet) —run_taskis the one-task worker you'll read just below. The*unpacks the list into separate arguments:gather(job1, job2, job3, …).gatherruns them together and waits for the slowest. It returns their answers in the same order as the jobs, not in finishing order.for task_id, result in completed— each answer is a pair like(2, '{"ticker": "AMD", …}'). Python splits the pair into two variables (tuple unpacking), and we write it into the notebook.
all([]) is True
Tasks 1–5 have no dependencies, so all(... for d in []) checks an empty list. Python says "all of zero things are done" → True. That's why tasks with no dependencies are ready in the very first round — no special case needed.
Round by round, for our plan
| Round | ready | After gather | Keys in results |
|---|---|---|---|
| 1 | [1, 2, 3, 4, 5] | tasks 1–5 COMPLETED | 1 2 3 4 5 |
| 2 | [6] — its deps 1, 2, 3 are done | task 6 COMPLETED | 1 … 6 |
| 3 | [7] — deps 4, 5, 6 are done | task 7 COMPLETED | 1 … 7 |
| 4 | while any(... PENDING ...) is now False → loop ends → return results | ||
What one runner does: run_task
# researcher.py — run ONE task with the right tool (same file as execute_plan)
from openai import AsyncOpenAI
from common import SubTask, TaskStatus
from tools.financial_data import get_financial_metrics
from tools.sec_filings import get_risk_factors
from tools.web_search import search_financial_news
NAMES = {"NVDA": "NVIDIA", "AMD": "AMD", "INTC": "INTEL"}
def extract_tickers(text: str) -> list[str]:
"""'Fetch Intel metrics' → ['INTC']"""
up = text.upper()
return [tk for tk, name in NAMES.items() if tk in up or name in up]
async def analyze_with_llm(instruction: str, context: str) -> str:
"""For 'thinking' tasks (6 and 7): reason over earlier results."""
response = await AsyncOpenAI().chat.completions.create(
model="gpt-4o",
temperature=0,
messages=[
{"role": "system", "content": "You are a financial analyst. "
"Use ONLY the data given. Quote numbers exactly."},
{"role": "user", "content": f"{instruction}\n\nDATA:\n{context}"},
],
)
return response.choices[0].message.content
async def run_task(task: SubTask, results: dict[int, str]) -> tuple[int, str]:
task.status = TaskStatus.RUNNING
try:
if task.dependencies: # ① a thinking task
context = "\n\n".join(f"[Task {d}] {results[d]}"
for d in task.dependencies)
output = await analyze_with_llm(task.description, context)
elif "financial_api" in task.data_sources: # ② numbers
ticker = extract_tickers(task.description)[0]
metrics = await get_financial_metrics(ticker)
output = metrics.model_dump_json()
elif "sec_filing" in task.data_sources: # ③ filings
tickers = extract_tickers(task.description)
output = "\n\n".join([await get_risk_factors(t) for t in tickers])
else: # ④ news
output = await search_financial_news(task.description)
task.status = TaskStatus.COMPLETED
except Exception as e: # ⑤ never crash
task.status = TaskStatus.FAILED
output = f"ERROR: {e}"
return task.id, output- Has dependencies → a "thinking" task (tasks 6 and 7). It collects the earlier results it depends on, labels each one
[Task 1] …, and asks the LLM to reason over them. No tool call — just analysis. financial_api→ numbers.extract_tickersfinds the ticker in the description, the tool fetches aCompanyMetrics, and.model_dump_json()turns the form into JSON text — because the notebook stores text.sec_filing→ filings for every company named in the description.- Anything else → news search, using the task description as the search query.
try / except— never crash. Any error sets the sticker to FAILED and returns"ERROR: …"as the result. Why so careful? If one job insidegatherraises an error,gatherraises it immediately and you lose the whole round's results. Catching the error inside each job means one broken courier never ruins the round.
run_task changes task.status, and somehow execute_plan sees the change. How? plan.sub_tasks[1], tasks_by_id[2] and the task inside run_task are the same object — three bookmarks pointing at one page. Python variables are name tags, not photocopies. Change the page through one bookmark, and every bookmark shows it.
extract_tickersis a simple name lookup: "Advanced Micro Devices" would be missed. Sturdier: add atickerfield toSubTaskand let the planner fill it in.- Task 4 calls the SEC once per company, one after another. Those calls could be gathered too.
Run the plan round by round — then break something
Each click does exactly one thing the code does. Gold rows = this round's ready list. Try the healthy run first, then make the AMD data API fail and watch the whole safety chain work: FAILED → stuck tasks → break → validator gaps → re-plan.
5.9Step 4 · The validator — a checklist, not an opinion
Before any memo leaves Future with Shivank Bank, a compliance officer walks the research board with a checklist and a calculator. She never says "looks fine to me". She asks yes/no questions: Is every card done? Is every company covered? Is this margin even possible? Same questions, same answers, every single time. That's our validator — and it contains no LLM at all.
# validator.py — plain Python checks. No LLM anywhere in this file.
from common import CompanyMetrics, TaskStatus, ValidationResult
def validate_research(plan, results, required_tickers) -> ValidationResult:
errors, warnings, gaps = [], [], [] # ① three empty buckets
# Check 1: did every task finish?
for t in plan.sub_tasks:
if t.status != TaskStatus.COMPLETED:
gaps.append(f"Task {t.id} {t.status.value}: {t.description}")
# Check 2: does every company appear somewhere in the findings?
for ticker in required_tickers:
if not any(ticker.upper() in r.upper() for r in results.values()):
gaps.append(f"Missing data for {ticker}")
# Check 3: are the numbers possible? are they plausible?
for text in results.values():
try:
m = CompanyMetrics.model_validate_json(text) # ② is it a metrics form?
except ValueError:
continue # news, filings… skip
if m.gross_margin is not None and not -50 <= m.gross_margin <= 100:
errors.append(f"{m.ticker}: gross margin {m.gross_margin}% is impossible")
if (m.gross_margin is not None and m.operating_margin is not None
and m.operating_margin > m.gross_margin):
errors.append(f"{m.ticker}: operating margin is above gross margin")
if m.pe_ratio is not None and not 0 < m.pe_ratio <= 150:
warnings.append(f"{m.ticker}: P/E of {m.pe_ratio} is extreme"
" - check earnings")
if m.revenue_growth is not None and abs(m.revenue_growth) > 300:
warnings.append(f"{m.ticker}: revenue growth {m.revenue_growth}% - unit error?")
return ValidationResult( # ③ the verdict
is_valid=not errors and not gaps,
errors=errors, warnings=warnings, gaps=gaps,
)Three buckets, three consequences
The code, line by line
- Three empty lists — one per bucket. Each check drops messages into them.
- Check 1:
!= COMPLETED, not== FAILED. When AMD's task fails, tasks 6 and 7 never run — they stay PENDING forever. A check for "failed" would miss them. "Anything not completed is a gap" catches both.t.status.valueturns the sticker into its text,"failed"or"pending". - Check 2: is every ticker mentioned somewhere? For each ticker, look through all results (uppercased so case doesn't matter).
any(...)stops at the first hit. - Check 3, the trick:
CompanyMetrics.model_validate_json(text)means "try to read this text as a metrics form". News and filing text isn't that JSON, so it raises an error (a kind ofValueError) andcontinueskips to the next result. The form itself tells us which results are metrics! - The verdict:
is_valid = not errors and not gaps. Notice: warnings never block. They're information for the reader, not a reason to redo the work.
| Rule | Why it's there | Bucket | Example it catches |
|---|---|---|---|
| Gross margin outside −50%…100% | Above 100% would mean costs were negative. Usually a decimal slipped. | error | NVDA 727.0 instead of 72.7 |
| Operating margin > gross margin | Operating profit = gross profit minus more costs. It can't be bigger. | error | Intel: gross 41.5%, operating 48.0% |
| P/E ≤ 0 or above 150 | Possible when earnings collapse — but the reader must know. | warning | AMD 195.3 after a weak year |
| Revenue growth beyond ±300% | Possible, but far more often a units bug (thousands vs millions). | warning | 1259% instead of 125.9% |
| Negative operating margin | Not flagged on purpose. Loss-making companies are real. | — | A chipmaker in a bad year |
We tested this. When AMD's metrics fetch failed, check 2 still passed for AMD: the news result says "AMD MI300 ramps", and even the error message contains the URL …?ticker=AMD. A simple text search can be fooled. Check 1 caught the problem instead. That's why good validators layer several simple checks — each one covers another's blind spot.
Remember the three-attempt story from 5.2: the LLM checker approved invented numbers and rejected correct ones. The Python checker runs in about a millisecond, costs nothing, and gives the same answer every time. Use code for facts; use the LLM for words.
Change the numbers — the same rules as the Python code run instantly
Start with a preset, then edit any box. Leave a box empty for "unknown" (None). Untick "Fetched?" to make that company's task fail.
| CompanyCo. | Fetched?OK? | Growth % | Gross margin %Gross % | Operating margin %Oper. % | P/E |
|---|
5.10Step 5 · The synthesizer and the orchestrator
The memo writer receives a folder: every finding, labelled by task, plus the compliance officer's sticky notes ("AMD's P/E is extreme — mention it"). She must fill in the bank's memo template, quote numbers exactly, and say how confident she is. A thin folder or lots of sticky notes → lower confidence.
# synthesizer.py — findings + the checker's notes → the final memo
from openai import AsyncOpenAI
from common import ResearchReport, ValidationResult
SYNTH_PROMPT = """You are a senior equity research analyst.
Write an investment research memo using ONLY the findings provided.
- Quote numbers exactly as given. Never invent a number.
- If data is missing, say so plainly.
- Mention every validation warning where it is relevant.
- confidence_score (0 to 1) must reflect how complete and clean the data is."""
async def synthesize_report(question: str, results: dict[int, str],
validation: ValidationResult) -> ResearchReport:
findings = "\n\n".join(f"[Task {tid}]\n{text}" # ① the research folder
for tid, text in sorted(results.items()))
notes = "\n".join( # ② the checker's notes
[f"WARNING: {w}" for w in validation.warnings]
+ [f"GAP: {g}" for g in validation.gaps]
+ [f"ERROR: {e}" for e in validation.errors]
) or "No issues found."
response = await AsyncOpenAI().chat.completions.parse( # ③ fill the memo form
model="gpt-4o",
temperature=0,
messages=[
{"role": "system", "content": SYNTH_PROMPT},
{"role": "user", "content": f"QUESTION:\n{question}\n\n"
f"FINDINGS:\n{findings}\n\nVALIDATION NOTES:\n{notes}"},
],
response_format=ResearchReport,
)
return response.choices[0].message.parsed- The folder.
sorted(results.items())lists the notebook in task order 1 → 7. Each finding gets a[Task n]label, so the memo can point back to where a number came from. - The sticky notes. Three list comprehensions build lines like
WARNING: AMD: P/E of 195.3 is extreme…, and+glues the lists together. If there are no notes at all, the joined text is empty — and an empty string counts as "false" in Python, soorswaps in"No issues found.". - Fill the memo form. The same
.parse(..., response_format=...)trick as the planner, this time withResearchReport. The LLM can't hand back a memo with a missing section.
Passing the warnings into the prompt is what makes the memo honest: it says "AMD's P/E of 195 reflects depressed earnings after a weak year" instead of quietly presenting 195 as normal. In our sample run the memo came back with 85% confidence because of that one warning. Many teams go one step further and compute the confidence score in code (e.g. start at 100% and subtract for each warning and gap) — the same "code for facts" lesson again.
The orchestrator — the desk manager
# deep_search_agent.py — the manager that runs the whole loop
import asyncio
from pathlib import Path
from common import ResearchReport
from planner import create_research_plan
from researcher import execute_plan
from validator import validate_research
from synthesizer import synthesize_report
MAX_REPLAN_ATTEMPTS = 2
async def deep_search(question: str, tickers: list[str]) -> ResearchReport:
for attempt in range(MAX_REPLAN_ATTEMPTS + 1): # attempt = 0, 1, 2
plan = await create_research_plan(question) # Phase 1: plan
results = await execute_plan(plan) # Phase 2: execute
validation = validate_research(plan, results, tickers) # Phase 3: check
if validation.is_valid:
break # all good → leave
elif attempt < MAX_REPLAN_ATTEMPTS: # tries left → re-plan
problems = validation.gaps + validation.errors
question += "\nAddress these gaps:\n" + "\n".join(problems)
return await synthesize_report(question, results, validation) # Phase 4
if __name__ == "__main__":
QUESTION = (
"Analyze NVIDIA's financial performance and competitive position in "
"the AI chip market. Compare with AMD and Intel on revenue growth, "
"profitability, and key risk factors. Produce a structured "
"investment research memo."
)
report = asyncio.run(deep_search(QUESTION, ["NVDA", "AMD", "INTC"]))
Path("output").mkdir(exist_ok=True)
Path("output/report.json").write_text(report.model_dump_json(indent=2))
print(report.title)
print(report.executive_summary)
print(f"Confidence: {report.confidence_score:.0%}")range(MAX_REPLAN_ATTEMPTS + 1)isrange(3), soattempttakes the values 0, 1, 2: one first try plus two re-plans.- Each attempt runs three phases in order: plan → execute → validate. Each phase's output is the next phase's input — exactly the relay race from 5.5.
if validation.is_valid: break— happy path.breakjumps straight out of the loop to the synthesizer.elif attempt < MAX_REPLAN_ATTEMPTS— not valid, but tries are left. We add the problems to the question. Why the question? The planner has no memory between calls — the question text is its memory. It's like sending the desk head a sticky note: "Last time: AMD numbers missing, tasks 6 and 7 stuck."- Why
gaps + errors? If we sent only the gaps, a run with errors but no gaps would hand the planner an empty "Address these gaps:" list — and it would make the same plan again. - The synthesizer runs after the loop, always. A small Python fact makes this work: variables created inside a
forloop still exist after it ends. Soresultsandvalidationhold the last attempt's values. Even when all three attempts fail, the PM still gets a memo — one that lists the gaps and carries a lower confidence score. - The
__main__block runs only when you start the file directly.asyncio.run(...)starts the async world, andmodel_dump_json(indent=2)saves the memo as readable JSON inoutput/.
Each new attempt starts from scratch: it re-plans and re-fetches everything, even the tasks that worked. A cheaper upgrade keeps the successful results and re-runs only what failed. Fine for learning; worth fixing before you run this on 500 companies a day.
The three possible endings
| Situation | Attempts | What the PM receives |
|---|---|---|
| Everything works | 1 | Memo at ~85% confidence; the AMD P/E warning is mentioned |
| AMD's API hiccups once | 2 — the second plan "knows" about the gap | The same full memo, about 30 seconds later |
| AMD's API is down all day | 3 (the maximum) | A memo that openly lists the missing AMD data, with a clearly lower confidence score |
We ran all three scenarios with mock data APIs and a mock LLM to check the loop behaves exactly like this.
Variable cheat-sheet — the whole run on one card
| Variable | Type | Made by | Used by | Example |
|---|---|---|---|---|
question | str | you (grows on each re-plan) | planner, synthesizer | "Analyze NVIDIA's…" |
tickers | list[str] | you | validator | ["NVDA", "AMD", "INTC"] |
attempt | int | the for loop | the elif | 0, 1 or 2 |
plan | ResearchPlan | planner | researcher, validator | 7 sub-tasks |
ready | list[SubTask] | researcher, each round | gather | tasks 1–5, then 6, then 7 |
results | dict[int, str] | researcher | validator, synthesizer | {1: '{"ticker":"NVDA",…}', …} |
validation | ValidationResult | validator | orchestrator, synthesizer | valid · 1 warning |
report | ResearchReport | synthesizer | you, output/report.json | the memo, 85% confidence |
What comes out — a sample memo (shortened)
Sample output from one run — wording and figures change with live data. The highlighted line exists only because the validator's warning was passed into the synthesizer's prompt.
Section 5 · Part 3 — Make it yours
Hands-on lab, production lessons and the wider world
5.11Lab · the same agent, rebuilt with PydanticAI
You've built every part with the raw OpenAI client, so nothing is magic any more. Now we swap in PydanticAI (you met it in Section 3) for the two LLM calls. You get automatic retries when the LLM's answer doesn't fit the form, and you can switch between OpenAI and Anthropic by changing one string. The tools, the researcher loop and the validator don't change at all.
1 · Set up
pip install pydantic-ai httpx pydantic python-dotenv tavily-python
# optional: cost tracking across the whole pipeline
pip install "pydantic-deep[middleware]"OPENAI_API_KEY=sk-...
FINANCIAL_DATASETS_API_KEY=...
TAVILY_API_KEY=tvly-...
SEC_EDGAR_EMAIL=your-email@example.com2 · The project folder
cd src
python deep_search_agent.py3 · What changes: only the LLM calls
# common.py — lab version: add these lines at the top
from dotenv import load_dotenv
load_dotenv() # copies the .env values into os.environ
PLANNING_MODEL = "openai:gpt-4o" # "provider:model" in one string
SYNTHESIS_MODEL = "openai:gpt-4o"
# Prefer Claude? Set ANTHROPIC_API_KEY and use "anthropic:<model name>",
# e.g. "anthropic:claude-sonnet-5-5" — check your provider's current names.# planner.py — lab version, with PydanticAI
from pydantic_ai import Agent
from common import PLANNING_MODEL, ResearchPlan
PLANNER_SYSTEM_PROMPT = """You are a financial research planner. ...
(exactly the same text as PLANNER_PROMPT above)"""
planner_agent = Agent(
model=PLANNING_MODEL,
system_prompt=PLANNER_SYSTEM_PROMPT,
output_type=ResearchPlan, # the form the answer must fit
retries=2, # wrong shape? sent back, up to 2 times
model_settings={"temperature": 0},
)
async def create_research_plan(question: str) -> ResearchPlan:
result = await planner_agent.run(question)
return result.output # already a ResearchPlan object| Step-by-step version (5.6) | Lab version | |
|---|---|---|
| Who makes the call | AsyncOpenAI().chat.completions.parse(...) | planner_agent.run(question) |
| How you say the shape | response_format=ResearchPlan | output_type=ResearchPlan |
| Getting the object out | response.choices[0].message.parsed | result.output |
| Answer doesn't fit the form | you handle it | sent back to the LLM with the error, up to retries=2 times |
| Switch to Claude | rewrite with another SDK | change one string in common.py |
retries=2 feels like
A clerk hands back a loan form with a red circle: "tenure must be a number — please fix". PydanticAI does exactly that: if the LLM's JSON fails the Pydantic check, it sends the error message back and asks for a corrected answer — up to two times — before giving up.
# synthesizer.py — lab version: only the LLM call changes
from pydantic_ai import Agent
from common import SYNTHESIS_MODEL, ResearchReport, ValidationResult
synth_agent = Agent(
model=SYNTHESIS_MODEL,
system_prompt=SYNTH_PROMPT, # same prompt as before
output_type=ResearchReport,
retries=2,
model_settings={"temperature": 0},
)
async def synthesize_report(question: str, results: dict[int, str],
validation: ValidationResult) -> ResearchReport:
findings = ... # same two lines as before
notes = ...
result = await synth_agent.run(
f"QUESTION:\n{question}\n\nFINDINGS:\n{findings}"
f"\n\nVALIDATION NOTES:\n{notes}"
)
return result.outputPydanticAI ships a fake model, TestModel, that returns dummy-but-valid data in the right shape. Use it to check your imports and plumbing without calling a real LLM. (Your .env still needs an OPENAI_API_KEY line so the agent can be created — but no request is sent and no tokens are used.)
# try_planner.py — test the wiring for free: no real LLM call
import asyncio
from pydantic_ai.models.test import TestModel
from planner import planner_agent, create_research_plan
async def main():
with planner_agent.override(model=TestModel()): # a fake, free "LLM"
plan = await create_research_plan("Compare NVIDIA with AMD")
print(plan) # dummy text, but a perfectly valid ResearchPlan
asyncio.run(main())4 · What a run does — the eight steps
- Takes the research question (default: the NVIDIA vs AMD vs Intel question).
- Plans:
planner_agentreturns aResearchPlan. - Executes the sub-tasks in waves — in parallel where the graph allows.
- Validates the findings with plain Python checks.
- Re-plans if gaps or errors are found — up to two more tries.
- Synthesizes a structured memo:
synth_agentreturns aResearchReport. - Prints a cost summary (only if the optional
pydantic-deep[middleware]is installed). - Saves the memo to
output/— about 30 seconds after you pressed Enter.
- Dynamic peers: given only "Analyze NVIDIA", let the planner add AMD, Intel, Broadcom and Qualcomm itself.
- History: compare today's margins with the 3-year and 5-year averages.
- Human-in-the-loop gate: pause after planning so an analyst approves the plan before any data is fetched.
- Browser tool: use Playwright to read investor-relations pages that block API access.
- JSON for other systems: feed the
ResearchReportinto a risk dashboard. - MCP: wrap the three tools as MCP servers (Section 3) so other teams can reuse them.
- Sub-agents: replace the hand-written loop with
create_deep_agentfrompydantic-deep. - A Claude skill: write a
SKILL.mdthat runspython deep_search_agent.pywith the analyst's question, so analysts can just type "research NVIDIA vs AMD".
5.12From demo to production
"The model is not your product. The experience around the model is your product."
— Nicolas Bustamante, founder of the financial research platform Fintool
The LLM is one component. Whether analysts actually trust and use the tool depends on everything around it. Six lessons from teams running deep search in production:
Context: the agent's desk gets messy
A multi-company study can pile up 50,000–100,000+ tokens of filings, transcripts and news. Four ways teams keep the desk clear:
What does one research run cost?
| Step | Tokens | Cost (GPT-4o-class rates) |
|---|---|---|
| Planning | ~2,000 | ~$0.01 |
| Tool execution (5 calls) | ~15,000 | ~$0.08 |
| Validation | ~3,000 | ~$0.02 |
| Synthesis | ~8,000 | ~$0.04 |
| Total per research run | ~28,000 | ~$0.15 |
Estimates assuming efficient prompts and model routing; prices change, so check your provider's current price list. Our validator itself uses no LLM — the validation line covers lighter LLM checks of report quality. Unoptimised setups often cost 3–5× more.
- Model tiering — cheap models for simple steps.
- Caching — a company's filed numbers for a quarter never change, so cache them forever.
- Shorter prompts — the planner prompt should be tight, not chatty.
- Share common context — explain the industry once, not once per company.
- Token budgets — cap each sub-task; summarise a 10,000-token filing to 500 tokens.
How do you know the memo is right?
| Dimension | Question it asks | How to test it |
|---|---|---|
| Factual accuracy | Are the numbers correct? | Compare with known values from a database or benchmark |
| Completeness | Is every company, metric and section there? | A checklist — in code |
| Structure | Is it organised and coherent? | A separate LLM as judge |
| Citations | Can every claim be traced to a source? | Check links and attributions |
| Consistency | Does section 2 contradict section 4? | Cross-check numbers quoted in different places |
FinDeepResearch, a benchmark of 64 companies across 8 markets and 4 languages (15,808 grading items), found that even the best agents struggle to be well-structured and accurate at the same time. Beautifully formatted reports tended to contain invented numbers; careful ones tended to be messy. Never judge a memo by its formatting.
Write a golden set of 20–30 research questions whose answers a human analyst has checked. Run the agent on them after every prompt or model change. Check the numbers automatically first; use an LLM judge only for the writing quality. If scores drop, don't ship.
5.13Who else builds this
Three open-source projects faced the same problems you just solved — and chose differently:
financial_search tool routes internally to the right source, so the agent's tool list stays short. Logs every step to a JSONL "scratchpad" for audit, keeps only the 5 latest tool results when context fills up, and works with many LLM providers. Price: more tokens.| Persona (style inspired by) | Looks for |
|---|---|
| Damodaran · valuation | DCF, intrinsic value, growth vs value |
| Graham · value | Margin of safety, book value, conservative numbers |
| Ackman · activist | Fixable operations, hidden value, catalysts |
| Wood · innovation | Disruptive technology, market size, revenue growth |
| Burry · contrarian | Crowded trades, hidden risks, short ideas |
| Munger · quality | Moats, management quality, capital allocation |
Commercial platforms, in one line each
- Fintool — reported 98% accuracy on a 100-question set from FinanceBench (a standard finance Q&A test), against 45% for a leading general-purpose assistant, in the company's own benchmark. Its secret is the boring part: data normalisation, fiscal-period alignment and ~2,000 tests.
- AlphaSense — deep research agents over 500 million+ business documents and transcripts, for 7,000+ enterprise customers. Lesson: agents shine brightest on curated, private document collections.
- Google Finance Deep Search — deep search for everyday investors' questions, powered by Gemini. Deep search is becoming a mainstream expectation.
- Claude for Financial Services — Claude connected directly to data providers such as FactSet, Morningstar, PitchBook, S&P Global and Daloopa, with links back to sources. Reported results: AIG made underwriting reviews 5× faster while raising data accuracy from 75% to over 90%; Norway's sovereign wealth fund (NBIM) estimated ~20% productivity gains, about 213,000 hours saved.
Figures are as reported by the companies themselves.
Wrap-up
What to remember
- Deep search = plan → execute → validate → (re-plan) → synthesize. RAG answers a question; deep search does the research.
- The plan is a dependency graph. No dependencies → run together with
asyncio.gather; dependencies → wait your turn. - Pydantic models are the forms passed between parts. Unknown is
None, never 0. - Tools translate. Messy API data becomes clean, labelled numbers in millions and percentages before any LLM sees it.
- Failures become notes, not crashes: FAILED → gap → re-plan, at most twice, and the memo admits what's missing.
- Code checks facts, the LLM writes words. Errors block, warnings travel into the memo, gaps trigger a re-plan.
- 80% of the work is data: units, fiscal calendars, footnotes. The model is not the product.
Everything on this page is for learning. Nothing here is investment advice or a recommendation to buy or sell any security.