Skip to main content
← Back to Blog
2026-02-21 · 9 min readAI AgentsPythonUpdated Oct 30, 2026

Building a Deep Research Agent: An End-to-End Walkthrough

A code-first walkthrough of a citation-backed research agent in Python. It splits a vague topic into search queries, searches the web with Tavily, keeps each source URL next to its text, writes a structured brief with OpenAI Structured Outputs and checks that every cited URL came from the search results. Tested with stub clients, no real API keys needed.

Avnish Yadav
AI Automation Engineer & Salesforce Developer
19 views
Building a Deep Research Agent: An End-to-End Walkthrough

This walkthrough is for developers who want an LLM to research a topic without making up facts. You will build a small research agent in Python. It turns a vague topic into search queries, pulls real sources from the web, and writes a brief in which every claim points to a URL. It also catches any source the model invented.

Key takeaways

  • A model's training data is not a research source. Give the agent a search tool and make it cite the URL behind every claim.
  • Keep each URL next to its text in the context, and ask for the result as typed JSON, so your code can check the citations.
  • Check the output in code: any cited URL that was not in the search results is a warning sign.

The problem with LLMs as researchers

Ask a chat model to "research the current state of solid-state batteries" and you get a decent overview. Ask it for a citation-backed brief on last month's breakthroughs and it struggles. Its knowledge stops at its training cutoff, so it can mix up dates, speak in generalities, or name papers that don't exist.

The fix is to stop treating the model as a knowledge base. Treat it as a reasoning engine that works on text you hand it.

A deep research agent is an LLM program that plans its own searches, reads what comes back, and writes a cited answer from those sources instead of from memory. To build a reliable one, you give the model a tool that fetches fresh data from the web. Then you make it cite its sources, and you check those citations in code.

The architecture: the research loop

A single prompt that searches once and answers is not enough for deep research. This agent works in five steps:

  1. Query analyzer: breaks the user's vague request into specific search queries.
  2. The hunter (search): runs each query and collects the results.
  3. The filter: drops duplicate pages so they don't waste context tokens.
  4. The synthesizer: writes the brief from the collected text only, with a citation for each claim.
  5. The architect: returns the brief as JSON with a fixed shape (summary, insights, action list, sources), which your code checks.

If you are new to agents, building an AI agent from scratch covers the basic loop first.

Step 1: The stack

You don't need a large framework for this. You need three things:

  • Orchestration: plain Python 3.10 or newer, with the openai and tavily-python packages.
  • Search tool: the Tavily search API. Its search endpoint returns, for each result, the URL, a title, a relevance score and the content most relevant to your query. That saves you from writing a scraper.
  • Model: a strong reasoning model, since the synthesis step does the hard work. On the date above, OpenAI's models page calls gpt-6-astra its flagship model for complex reasoning. Anthropic's equivalent is claude-sonnet-5-5 or claude-opus-5-5. Model ids change often, so check the provider's models page before you pick one.

Install the packages in a virtual environment:

python -m venv .venv
source .venv/bin/activate
pip install -U openai tavily-python pydantic

You need an OpenAI API key in OPENAI_API_KEY and a Tavily key in TAVILY_API_KEY. Tavily's Python reference passes the key to TavilyClient as its first argument, so the code reads it from the environment itself. Never paste keys into the code.

Create research_agent.py and start with the clients:

import json
import os

from openai import OpenAI
from pydantic import BaseModel, Field
from tavily import TavilyClient

client = OpenAI()  # reads OPENAI_API_KEY from the environment
tavily = TavilyClient(os.environ["TAVILY_API_KEY"])
MODEL = os.getenv("RESEARCH_MODEL", "gpt-6-astra")

Checked against openai@3.41.0, tavily-python@0.8.5 and pydantic@2.14.2 with Python 3.14, 2026-10-30.

Reading the model id from the RESEARCH_MODEL variable lets you switch models without touching the code.

Step 2: Break down the query

Users ask lazy questions, such as "Tell me about AI agents." Search that word for word and you get generic pages. So the first step asks the model to expand the topic into three focused queries.

Instead of asking for "a JSON list" and hoping, the code asks for a typed object. OpenAI's Structured Outputs guide shows this pattern: pass a Pydantic model as text_format to client.responses.parse(), then read the result from output_parsed.

class SearchPlan(BaseModel):
    queries: list[str] = Field(description="Three distinct search engine queries")

def generate_search_queries(topic: str) -> list[str]:
    response = client.responses.parse(
        model=MODEL,
        input=[
            {
                "role": "system",
                "content": (
                    "You are a research planner. Break the topic into 3 distinct "
                    "search engine queries: 1. a general overview, 2. technical "
                    "implementation details, 3. recent news or competitor analysis."
                ),
            },
            {"role": "user", "content": topic},
        ],
        text_format=SearchPlan,
    )
    return response.output_parsed.queries

For "AI agents", a run might return queries like "AI agent architecture patterns", "LangGraph vs AutoGen comparison" and "autonomous agent news this year". Your queries will differ on every run. Now the agent has a plan.

Step 3: The search and context layer

This is where many research agents go wrong. They paste whole web pages into the context window, and the useful facts drown in navigation menus and ads.

Tavily returns the text that matches your query, so the context stays small. The key rule here is citation discipline: store the URL right next to its text, so the model always knows where a fact came from.

def search_and_pack(queries: list[str]) -> str:
    seen = set()
    context_buffer = []
    for query in queries:
        response = tavily.search(query=query, search_depth="advanced", max_results=3)
        for result in response["results"]:
            if result["url"] in seen:
                continue  # the same page often answers two queries
            seen.add(result["url"])
            context_buffer.append(
                f"Source: {result['url']}\nContent: {result['content']}\n---"
            )
    return "\n".join(context_buffer)

What the two search settings do, according to Tavily's search docs:

Setting What you get Trade-off Use it when
search_depth="basic" Several relevant snippets per URL, about 500 characters each 1 credit per call, faster Quick lookups and drafts
search_depth="advanced" The most relevant snippets per URL, about 800 characters each 2 credits per call, slower Research where relevance matters most
include_raw_content=True The page's full cleaned text, in a raw_content field Much more text to pay for in tokens You need a whole article, not snippets

Tavily calls those sizes "a target, not a hard limit", and chunks_per_source caps how many snippets you get per page. An earlier version of this post said advanced returns the full page text. It doesn't: it returns better snippets. Use include_raw_content when you need the whole page.

Add re-ranking for production

Before the synthesis step, score each result against the original topic and keep only the best ones. A small embedding model is cheap enough for this. The goal is to spend expensive model tokens only on text that is likely to matter.

Step 4: Synthesis and hallucination avoidance

Now you have a block of text in which every chunk carries its source. The synthesis prompt has to keep the model inside that text. Give it a "citations required" rule: every claim ends with the URL it came from.

SYSTEM_PROMPT = """You are a technical analyst. Write a research brief based ONLY on the provided context.

RULES:
1. Citation discipline: follow every claim with its source URL from the context, in square brackets.
2. No guessing: if the context does not answer something, write "Data unavailable."
3. Sources: list only URLs that appear after "Source:" in the context.
4. Tone: concise, technical, builder-centric."""

The "Data unavailable" rule matters. Without a way to say "I don't know", the model fills the gap with something that sounds right.

Step 5: Structured output (the action list)

A wall of text is hard to act on. Ask for the brief as a typed object instead. You can then render it in a UI, store it in a database, or send it to Notion.

The same responses.parse() call from Step 2 does the work, this time with a richer schema:

class ResearchBrief(BaseModel):
    summary: str = Field(description="Executive summary of findings, with citations")
    key_insights: list[str] = Field(description="Technical details, each with a citation")
    action_items: list[str] = Field(description="Suggested next steps for a developer")
    sources: list[str] = Field(description="Unique URLs used, copied from the context")

def write_brief(topic: str, context: str) -> ResearchBrief:
    response = client.responses.parse(
        model=MODEL,
        input=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": f"Topic: {topic}\n\nContext:\n{context}"},
        ],
        text_format=ResearchBrief,
    )
    return response.output_parsed

def unknown_sources(brief: ResearchBrief, context: str) -> list[str]:
    """URLs the model cited that never appeared in the search results."""
    return [url for url in brief.sources if f"Source: {url}\n" not in context]

The unknown_sources check is the part prompts can't give you. A prompt asks the model to cite only real sources. This function checks that it did. Any URL it returns is one the model made up or changed.

Run the pipeline

Add the run code at the bottom of the file. It sits under if __name__ == "__main__":, so importing the module (as the test below does) makes no API calls.

if __name__ == "__main__":
    topic = "Vector databases"
    context = search_and_pack(generate_search_queries(topic))
    brief = write_brief(topic, context)
    print(json.dumps(brief.model_dump(), indent=2))

    bad = unknown_sources(brief, context)
    if bad:
        print("Warning: cited URLs not found in the search results:", bad)

Run it with python research_agent.py. You don't just get a chat reply; you get an object. For "Vector databases", an action list might look like this (your run will differ):

  • Compare a managed vector database with a self-hosted one for cost at your expected scale.
  • Measure how the HNSW index settings change query latency on your own data.
  • Prototype a hybrid search that mixes keyword and vector results.

That moves you from learning about a topic to building with it. To see how retrieval over your own documents works, read the RAG basics guide.

Test the wiring without real API keys

You can check the whole pipeline before you spend a credit. Save this as test_research_agent.py next to research_agent.py. It swaps the two network calls for stubs that return fixed answers.

from types import SimpleNamespace

import research_agent as ra

replies = [
    ra.SearchPlan(queries=["q1", "q2", "q3"]),
    ra.ResearchBrief(
        summary="Short summary [https://one.test/1]",
        key_insights=["Insight [https://one.test/1]"],
        action_items=["Prototype hybrid search"],
        sources=["https://one.test/1", "https://made-up.test/x"],
    ),
]
ra.client.responses.parse = lambda **kw: SimpleNamespace(output_parsed=replies.pop(0))
ra.tavily.search = lambda **kw: {"results": [
    {"url": "https://one.test/1", "content": "text one"},
    {"url": "https://one.test/2", "content": "text two"},
]}

queries = ra.generate_search_queries("Vector databases")
context = ra.search_and_pack(queries)
assert context.count("Source: ") == 2  # duplicates across the 3 queries dropped
brief = ra.write_brief("Vector databases", context)
assert ra.unknown_sources(brief, context) == ["https://made-up.test/x"]
print("research agent wiring works")

Both clients are created when the module is imported, so both keys must be set, but placeholders work: OPENAI_API_KEY=placeholder TAVILY_API_KEY=placeholder python test_research_agent.py. This test ran against the full file above and printed research agent wiring works.

Next steps: multi-hop research

This is a first version of a research agent. It works well for direct questions. The next step is multi-hop research: when the agent reads a source that mentions a term it doesn't understand, it runs a new search for that term, then returns to the original brief.

That needs a loop with state: which queries ran, what was found, and how many hops are left. Graph frameworks such as LangGraph are built for this, and graph engineering for AI agents shows the pattern. But start with the version here. Get the citation discipline right first, or a complex agent will only produce complex mistakes.

Frequently asked questions

What is the difference between a research agent and a chatbot?

A chatbot answers from what the model learned in training. A research agent plans searches, fetches current sources, and writes its answer from those sources, with a citation for each claim. That makes its output newer and easier to check.

Does Tavily return the full text of each page?

Not by default. According to Tavily's search docs, the content field holds the snippets most relevant to your query. Set include_raw_content=True if you need the page's full cleaned text, and expect to pay for many more tokens.

How do I stop the agent from inventing sources?

Use three layers. Keep each URL next to its text in the context, tell the model to cite only those URLs, and check the result in code. The unknown_sources function in this post flags any cited URL that the search never returned.

Can I use Claude instead of OpenAI?

Yes. The search and context steps don't depend on the model. Swap the two responses.parse() calls for your provider's structured output feature, keep the same Pydantic models, and pick a current id such as claude-sonnet-5-5 from Anthropic's models page.

Which model should I use for the synthesis step?

Use a strong reasoning model, because the synthesis step decides what the sources say. Query planning is a simpler task, so a smaller, cheaper model often works there. Model ids change often, so check the provider's models page.

Sources

Verified against the sources below on October 30, 2026. Products and docs change often: check the linked sources if something looks different.

  1. Tavily Docs: Search endpoint
  2. Tavily Docs: Python SDK reference
  3. OpenAI API: Structured Outputs
  4. OpenAI API: Models
  5. Claude Docs: Models overview
  6. openai on PyPI
  7. tavily-python on PyPI
Written by

Avnish Yadav

AI Automation Engineer & Salesforce Developer

Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.

About meLinkedIn

Share
Discussion

Comments

Loading comments...

Add a comment

Comments are reviewed before they appear.