Build a Research Deep Agent You Can Trust, Check and Afford
Every earlier part of this series showed one piece of a deep agent: the todo list, the filesystem, subagents, approvals, tracing. Real tasks need them all at once, and that is where things break. A research agent that searches, drafts, checks its own work and writes a report has many steps where it can go wrong. It can invent a fact. It can forget a source. It can overwrite a good report with a bad one. It can loop until your bill or your quota runs out.
The problem for this capstone: build a research agent whose answer you can trust, whose steps you can see, and whose final write you control, and measure what it costs.
We build it from parts you already know:
| Piece | Job | Covered in |
|---|---|---|
TodoListMiddleware | the lead keeps a visible 4-step plan | Part 4 |
researcher subagent | searches the docs, writes sourced notes | Part 6 |
critic subagent | checks the draft against the notes | Part 6 |
| virtual files | /notes/research.md, /draft.md, /final_report.md | Part 5 |
interrupt_on + checkpointer | a human approves the final write | Part 8 |
TraceLogger + pytest | per-step numbers and evals | Part 12 |
The full runnable folder is code/part13/ with a README and a requirements.txt.

Step 1: a search tool that always gives the same answer
A research agent needs something to search. A live web search API needs a key, and its results change daily, so a test that passes today fails next week. We use a local corpus instead: six short Markdown summaries of the public docs pages this series cites, each starting with its source: URL. The tools rank paragraphs with a small TF-IDF score.
pythonfrom langchain_core.tools import tool @tool def search_docs(query: str, k: int = 3) -> str: """Search the saved documentation. Returns the k best paragraphs with doc ids.""" k = max(1, min(int(k), 5)) ranked = sorted(CHUNKS, key=lambda c: _score(query, c[3]), reverse=True) hits = [c for c in ranked if _score(query, c[3]) > 0][:k] if not hits: return f"No results for {query!r}. Try fewer, more specific words." return "\n\n".join(f"[{d}#{i}] {para}" for d, i, para, _ in hits) @tool def read_doc(doc_id: str) -> str: """Read one saved document in full by its id (the part before # in search results).""" doc_id = doc_id.split("#")[0].strip() if doc_id not in DOCS: return f"Unknown doc_id {doc_id!r}. Known ids: {', '.join(sorted(DOCS))}" d = DOCS[doc_id] return f"title: {d['title']}\nsource: {d['source']}\n\n{d['body']}"
Two small choices here prevent common failures. k is clamped to 1-5, so a model that asks for 100 results cannot flood its own context. And a bad doc_id returns the list of valid ids instead of raising, so the model can fix its own mistake. A test query:
text[going-to-production#2] Every production invocation should carry a thread_id in config.configurable, which the checkpointer uses to persist and resume history, ... --- Unknown doc_id 'nope'. Known ids: agent-server, deepagents-overview, going-to-production, rubric-middleware, tracing, workers-ai-pricing
To research your own topic, drop .md files into corpus/. To use the live web, replace these two functions with a search tool; the rest of the agent does not change.
Step 2: the lead, the researcher and the critic
Each agent gets a short, specific prompt. The lead's prompt is an ordered recipe, because a numbered list is easier for a model to follow and easier for us to test:
pythonMAIN_PROMPT = """You are a research lead. You answer one question with a short, sourced report. Work in this order: 1. Call write_todos with 4 steps: research, draft, critique, final report. 2. Call the task tool with subagent_type "researcher". Ask it to save notes to /notes/research.md. 3. Read /notes/research.md and write a draft to /draft.md. Every claim needs a source URL from the notes. 4. Call the task tool with subagent_type "critic" and ask it to review /draft.md against /notes/research.md. 5. Fix every problem the critic lists, then write the result to /final_report.md. 6. Mark all todos completed and reply with two sentences. Keep the todo list current. Never invent facts that are not in the notes.""" SUBAGENTS = [ { "name": "researcher", "description": "Searches the saved docs and writes sourced notes to /notes/research.md.", "system_prompt": RESEARCHER_PROMPT, # "...Run at most 4 searches..." "tools": [search_docs, read_doc], }, { "name": "critic", "description": "Reviews /draft.md against /notes/research.md and lists unsupported claims.", "system_prompt": CRITIC_PROMPT, # "...Reply with a numbered list, or APPROVED." "tools": [], }, ]
The critic gets no custom tools. It still gets the built-in file tools, so it can read_file both files. It cannot search, so it judges only what the researcher actually found. That is the point of a critic: a second pair of eyes that checks the draft against the evidence, not against its own memory.
The researcher's tool output (search results, full documents) stays inside the researcher's context. The lead sees only the researcher's short final reply and the notes file. We measure what that saves below.
Step 3: approve only the final write
We want the agent to write notes and drafts freely, but to stop before /final_report.md. interrupt_on accepts an InterruptOnConfig with a when predicate (in langchain 1.5.2 it receives the tool call request and returns True to pause):
pythonfrom langchain.agents.middleware import TodoListMiddleware from langchain.chat_models import init_chat_model from langgraph.checkpoint.memory import InMemorySaver from deepagents import create_deep_agent def _is_final_report(request) -> bool: return request.tool_call["args"].get("file_path", "").lstrip("/") == "final_report.md" APPROVAL = {"allowed_decisions": ["approve", "edit", "reject"], "when": _is_final_report, "description": "Review the final report before it is written."} agent = create_deep_agent( model=init_chat_model("anthropic:claude-sonnet-4-6"), system_prompt=MAIN_PROMPT, middleware=[TodoListMiddleware()], subagents=SUBAGENTS, interrupt_on={"write_file": APPROVAL, "edit_file": APPROVAL}, checkpointer=InMemorySaver(), name="research_lead", )
We gate edit_file too. Otherwise the agent could write a stub with write_file elsewhere and then edit its way around the gate. lstrip("/") matters as well: in Part 12 we found that deepagents stores a relative final_report.md as /final_report.md, so the check must match both spellings.
The run loop invokes the agent, and while the result holds an __interrupt__, shows the pending write and resumes with a decision:
pythonfrom langgraph.types import Command cfg = {"configurable": {"thread_id": str(uuid.uuid4())}, "callbacks": [log], "recursion_limit": 80} result = agent.invoke({"messages": [{"role": "user", "content": QUESTION}]}, config=cfg) while result.get("__interrupt__"): action = result["__interrupt__"][0].value["action_requests"][0] print(action["args"].get("content", "")[:600]) decision = {"type": "approve"} if input("approve? ") == "y" else \ {"type": "reject", "message": input("why? ")} result = agent.invoke(Command(resume={"decisions": [decision]}), config=cfg)
The recursion_limit is there on purpose. create_deep_agent in 0.7.42 sets a default of 9,999 graph steps (see graph.py). That is a lot of room for a loop on a paid model. A whole run of this agent needs far fewer, so 80 turns a runaway loop into a fast error.
sequenceDiagram participant H as Human participant L as research_lead participant R as researcher participant C as critic participant F as Files L->>L: write_todos L->>R: task: research R->>R: search_docs x3, read_doc R->>F: write /notes/research.md R-->>L: one short reply L->>F: read notes, write /draft.md L->>C: task: review C->>F: read draft + notes C-->>L: numbered problems L-->>H: interrupt: /final_report.md H->>L: approve L->>F: write /final_report.md
Step 4: run it end to end
On the real model. We ran the agent once on Llama 4 Scout on Cloudflare Workers AI. The very first model call came back after 4.9 s with Error code: 429. Workers AI has a free allocation of 10,000 Neurons per day, shared with everything else on the account, and it was used up. Our rule for this series is to stop all real calls on a 429, so the end-to-end numbers below come from the scripted run, scaled by real measurements from Part 12. We say exactly which number is which.
On the scripted fake models. Three scripted models (lead, researcher, critic) return fixed tool calls. Everything else is real: the tools search the real corpus, the subagents run in their own graphs, files and todos land in state, and the approval interrupt fires. The trace, cut to the main steps:
text[ 1] model research_lead 0.5 ms in=- out=- chars=17363 calls=['write_todos'] [ 3] model research_lead 0.4 ms in=- out=- chars=17921 calls=['task'] [ 4] model researcher 0.5 ms in=- out=- chars=9534 calls=['search_docs'] ... [14] model researcher 0.3 ms in=- out=- chars=13555 calls=[] [16] model research_lead 0.5 ms in=- out=- chars=18207 calls=['write_todos'] ... [25] model critic 0.3 ms in=- out=- chars=8854 calls=['read_file', 'read_file'] [28] model critic 0.3 ms in=- out=- chars=10383 calls=[] ... [32] model research_lead 0.4 ms in=- out=- chars=21785 calls=['write_file'] === APPROVAL NEEDED: write_file /final_report.md === # Running a deep agent in production Planning: add TodoListMiddleware, because planning is opt-in since v0.7. (https://docs.langchain.com/oss/python/deepagents/overview) ... decision: approve [36] model research_lead 0.4 ms in=- out=- chars=23235 calls=[] final answer: The report is in /final_report.md. The critic found one unsourced claim and one gap, both fixed. summary: {"model_calls": 19, "tool_calls": 17, ... "approval_pauses": 1, "files": ["/draft.md", "/final_report.md", "/notes/research.md"]} todo: completed | Research the question todo: completed | Write /draft.md todo: completed | Get a critique todo: completed | Write /final_report.md
The chars column is new. The fake model measures each request it receives: the system prompt, all messages and the tool schemas. A fake model reports no tokens, but the size of what the agent sends is real, because the prompts, tools and messages are real.
Step 5: per-step tokens and the cost
To turn characters into tokens, we need one real data point. In Part 12, Llama 4 Scout reported 4,074 input tokens for the first request of a small deep agent. The same request through the measuring fake was 16,808 characters. That gives 4.13 characters per token for these prompts on this model. It is a ratio from one request, so treat everything below as an estimate.
The lead's context per model call, estimated from the measured characters:
research_lead input tokens per call (estimated from measured chars)Data from the sources listed below.
Look at calls 2 and 3. The researcher ran 3 searches and read one full document between them, and the lead's context grew by only about 69 tokens. That is context isolation working: the search results stayed in the researcher's context, and only its one-line reply came back.
Across the whole run, by agent:
Estimated input tokens per run, by agentData from the sources listed below.
The lead is 72% of the input, not because its context is huge but because it makes 11 calls and resends about 4,000 tokens of system prompt and tool schemas every time. The cheapest saving is fewer lead turns: for example, letting it update the todo list in the same turn as other tool calls.
Cost. The Cloudflare Workers AI pricing page (updated 2026-11-18) lists @cf/meta/llama-4-scout-17b-16e-instruct at $0.270 per million input tokens and $0.850 per million output tokens, or 24,545 and 77,273 Neurons per million. Our estimate_cost.py applies those prices:
textmodel calls: 19 input chars 310451 -> ~75,170 input tokens output chars 5379 -> ~1,302 output tokens input tokens by agent: {'research_lead': 53770, 'researcher': 16742, 'critic': 4658} cost per run: ~$0.0214 | ~1,946 neurons (free tier 10,000/day) runs per free day: ~5.1 | 1,000 runs: ~$21.40
So one run is about 2 cents, and the free daily allocation covers about 5 runs. That also explains our 429: the series had already spent the day's Neurons on earlier parts. Output tokens are under 2% of the total. For agents, input is the bill.
Latency. The fake run took 2.0 s, which only measures the harness. In Part 12, Llama 4 Scout averaged 4.4 s per model call (13,158 ms over 3 calls). At that rate, 19 calls is roughly 83 s of model time per run. That is an estimate, not a measurement.
One run: measured harness vs estimated real model time (s)Data from the sources listed below.
Step 6: evals for the whole graph
The same pytest pattern from Part 12 covers the capstone. Six tests, all on the scripted models:
pythondef test_all_three_files_written(approved): assert approved[1]["files"] == ["/draft.md", "/final_report.md", "/notes/research.md"] def test_paused_exactly_once_for_the_final_write(approved): assert approved[1]["approval_pauses"] == 1 def test_every_report_line_has_a_source(approved): lines = [l for l in approved[0]["files"]["/final_report.md"]["content"].splitlines() if l and not l.startswith("#")] assert all("https://" in l for l in lines) def test_reject_keeps_final_report_off_disk(): ... out = agent.invoke(Command(resume={"decisions": [ {"type": "reject", "message": "Not yet."}]}), config=cfg) assert "/final_report.md" not in out["files"]
texttests/test_research_agent.py::test_all_three_files_written PASSED tests/test_research_agent.py::test_paused_exactly_once_for_the_final_write PASSED tests/test_research_agent.py::test_todos_all_completed PASSED tests/test_research_agent.py::test_both_subagents_used PASSED tests/test_research_agent.py::test_every_report_line_has_a_source PASSED tests/test_research_agent.py::test_reject_keeps_final_report_off_disk tool message after reject: error | User rejected the tool call for `write_file` with reason: Not yet. PASSED ============================== 6 passed in 46.46s ==============================
The reject test is the important one. A rejection does not stop the run. The agent gets a ToolMessage with status="error" and your reason, so it can revise and try again, and the file stays off disk until you approve.
flowchart TD Q[Question] --> P[write_todos: 4 steps] P --> R[researcher: search, notes] R --> D[lead: /draft.md] D --> C[critic: review] C -->|problems| X[lead fixes draft] C -->|APPROVED| X X --> G{human approves?} G -->|approve| W["final_report.md written"] G -->|reject + reason| X
Failure modes we actually saw

We only list what showed up in our own logs, and where each one came from.
- Skipped plan (Llama 4 Scout, Part 12 run). The prompt said "First call write_todos". The model called
word_countfirst andwrite_todosthird. Fix: test the order on recorded traces; number the steps in the prompt; for a strict order, enforce it in middleware rather than hoping. - Duplicate tool calls (Llama 4 Scout, Part 12 run).
word_countran twice for one question. Harmless here, costly with a paid search API. Fix: assert call counts in evals; cap searches in the subagent prompt ("at most 4 searches"), as our researcher does. - A judge that passed missing work (Llama 4 Scout as
RubricMiddlewaregrader, Part 12). It marked "saved to /report.md" as passed when no file existed, after 8 calls and 81 s. Fix: check facts like "file exists" and "every line has a URL" in code, astest_every_report_line_has_a_sourcedoes; use a model judge only for quality. - Quota exhaustion (Llama 4 Scout, this part). HTTP 429 on the first call of the capstone. At about 1,946 Neurons per run, five runs use a whole free day. Fix: budget runs from measured tokens, run evals on fakes, and stop on a 429 instead of retrying.
- Growing context (measured, fake run). The lead's request grew from 17,363 to 23,235 characters over 11 calls, about 34%. Every tool result and todo update stays in its history. Fix: keep heavy work in subagents (the researcher's searches cost the lead about 69 tokens); write long content to files, not replies; see Part 11 for summarization.
- Bad tool arguments (caught by tests). A
write_filewith nocontent, or a path with.., comes back as a readable error instead of a crash. A relative path is silently made absolute, which is why our approval check strips the leading/.
We did not see an endless loop in any run. The capstone still sets recursion_limit=80, because the default of 9,999 steps is far more than this task needs.
How this code was tested
Versions: deepagents 0.7.42, langchain 1.5.2, langchain-core 1.8.5, langgraph 1.2.24, langgraph-checkpoint 4.3.2, pytest 9.2.0, Python 3.12.3. The article shows init_chat_model("anthropic:claude-sonnet-4-6"). One end-to-end run used Llama 4 Scout (@cf/meta/llama-4-scout-17b-16e-instruct) on Cloudflare Workers AI through the same create_deep_agent code, and it stopped at the first call with HTTP 429. The complete run and the 6 tests used scripted fake models with the real tools, corpus, subagents, files, todos and approval interrupt. Token counts are estimated from measured request characters with a ratio taken from one real Llama 4 Scout call in Part 12. Failure modes 1 to 3 come from the Part 12 Llama 4 Scout runs.
Nuances from running it live
We deployed this exact team as a public demo: deepagents-examples.vercel.app, code at github.com/NafiGit/deepagents-examples. Real model, live web, on free plans. It took 8 live runs to get one full report, and run 9 was the first that was also right. Here is every run, from the saved event logs.
Live runs: seconds until the run endedData from the sources listed below.
Input tokens per runData from the sources listed below.
Model calls per run (cap 28)Data from the sources listed below.
Run 1 died on its first call and run 3 died on a 429, so neither has final stats.
| Run | What went wrong | What we changed |
|---|---|---|
| 1 | Groq 400: the lead called write_todos, which deepagents 0.7 no longer adds by default | add TodoListMiddleware explicitly |
| 2 | keyless search, slow calls, out of time at 176 s | slimmer tool schemas, researcher and critic on a second model, 429 retries (2a0c742) |
| 3 | Tavily rejected the key (401), then a 429 on the 20b model's 8,000 tokens per minute | a working Tavily key |
| 4 | researcher never wrote notes, empty report at 219 s | tighter budgets and a "sources found" fallback (03ba9b7) |
| 5 | tools removed mid-run, model called one anyway, Groq 400 | keep tools listed but switched off (fe1a700) |
| 6 | model ignored "write notes now", re-read one page 5 times | code writes the notes, repeat-read cap (efb7f9b) |
| 7 | critic empty, lead said "I will" and stopped | empty-critic note, lead nudge (089eef9) |
| 8 | finished, but 0 pages read and an absence claim slipped through | read before searching more, code opens pages, critic checks absence and dates (18fd083) |
| 9 | right answer (0.7.43) and a real critic catch, but Sources had titles without links | attach source URLs from the notes (7144119) |
| 10 | lead read "last month" as October, never opened the releases page, last model call ran past 265 s | open: see Part 12 |
The 300 s wall
A Vercel function on this plan stops at 300 s, so every limit works back from that wall:
gantt title One run's time budget (seconds) dateFormat X axisFormat %s section Before fix (2a0c742) research allowed :0, 185 lead writes up :185, 265 section After fix (03ba9b7) research allowed :0, 130 lead drafts, critic, final :130, 265 section Vercel limit margin before the 300 s stop :265, 300
python# demo/real_agent.py "run_seconds": float(os.environ.get("RUN_SECONDS", "265")), # Vercel Hobby max is 300 s "wrap_up_seconds": float(os.environ.get("WRAP_UP_SECONDS", "130")), # leaves the lead ~2 min "max_searches": int(os.environ.get("MAX_SEARCHES", "3")), "max_fetches": int(os.environ.get("MAX_FETCHES", "3")),
On top of that: at most 28 model calls per run, 5 runs an hour per visitor IP and 60 an hour overall. Those counters live in memory, so on serverless they are best effort per instance.
Free plans move under you
- The model was retired. Groq shut down
llama-3.3-70b-versatilefor free and Developer accounts on August 16, 2026. The demo runs onopenai/gpt-oss-120b, withopenai/gpt-oss-20bfor the researcher and critic, because the free plan meters tokens per minute per model. - Slow without an error. In run 4 the researcher's calls went from a few seconds to 24 to 42 s apart from call 8 on, with no 429 in the log. That looks like throttling, but we could not confirm it.
Run 4: seconds between researcher calls (approx.)Data from the sources listed below.
Gaps are read from 5-second keep-alive pings, so they are approximate.
Approval in a demo
The approval step from Step 3 is real: run 8 paused on /final_report.md and the page showed the card. But a public demo has no one to click it, so the code approves it and moves on:
pythonout = agent.invoke(Command(resume={"decisions": [{"type": "approve"}]}), config=cfg)
In your own app, that line is where a human goes. The demo also has no shell tools, and fetch_page refuses localhost, private and link-local addresses.
Try this
bashcd code/part13 pip install -r requirements.txt python -m research_agent.run --fake --yes # full run, no key needed pytest tests -v -s # 6 evals python estimate_cost.py # cost from the fake run's sizes export ANTHROPIC_API_KEY=... python -m research_agent.run --model anthropic:claude-sonnet-4-6
Then change the question in research_agent/run.py, add your own .md files to corpus/, and reject the first report with a reason to see the lead revise it.
Sources
- Deep Agents overview: https://docs.langchain.com/oss/python/deepagents/overview
- Going to production: https://docs.langchain.com/oss/python/deepagents/going-to-production
- LangSmith Agent Server: https://docs.langchain.com/langsmith/agent-server
- Trace Deep Agents: https://docs.langchain.com/langsmith/trace-deep-agents
- Cloudflare Workers AI pricing: https://developers.cloudflare.com/workers-ai/platform/pricing/
- deepagents source (graph.py, middleware/subagents.py, middleware/rubric.py at v0.7.42): https://github.com/langchain-ai/deepagents
