sndev
Project CategoriesDeveloper LearnDeveloper Insights
LoginGet Started
sndevv1.0.0
AboutProject FeedInsightsYouTubePrivacy PolicyTerms of Service

Β© 2026 sndev β€’ v1.0.0

Home
Categories
Dev Learn
Insights
Sign In
Agentic AI
Nov 15, 2026
s
sndev

Building the Agentic AI Brain with LangGraph | Autonomous Deep Research Agent | Part 3

GitHub RepositoryWatch on YouTube

β€œLearn how to build a multi-agent AI architecture using LangGraph and Gemini 2.5 Flash. Create shared agent state, define four specialized agents, and structure research data with Pydantic.”

Project SeriesPart 3 of 13

Deep Research Agent

Series Progress23%
Series Episodes (13)
Build an Autonomous Deep Research Agent | End-to-End Agentic AI Project | Part 1
Available
Setup & Installation for Autonomous Deep Research Agent | End-to-End Agentic AI Project | Part 2
Available
P3
Building the Agentic AI Brain with LangGraph | Autonomous Deep Research Agent | Part 3
Current Part
Building AI Agent with LangGraph | Planner Agent Implementation | Deep Research Agent | Part 4
Available
Building AI Agent Tools | Rate Limiting & Source Credibility | Deep Research Agent | Part 5
Available
Building a Web Search Tool for AI Agents with Tavily API | Deep Research Agent Part 6
Available
Building arXiv Search, Cross-Referencing, and Citation Tools | Deep Research Agent Part 7
Available
Building the Researcher Agent with Web Search, arXiv & Source Ranking | Deep Research Agent Part 8
Available
Building the Critic Agent: Detecting Conflicting Research | Deep Research System Part 9
Available
Building the Writer Agent – Generating Structured AI Research Reports | Part 10
Available
Building a Multi-Agent Workflow with LangGraph | Deep Research Agent – Part 11
Available
Building a Real-Time WebSocket Streaming Engine with FastAPI | Deep Research Agent – Part 12
Available
Building and Deploying a Full-Stack AI Deep Research Agent | Part 13 – Final Chapter
Available
Part 2Part 4

In the previous part of our Autonomous Deep Research Agent project, we established the backend foundation using Python, FastAPI, Pydantic, and MongoDB Atlas.

We created our API structure, defined the initial data models, and connected our application to MongoDB.

Now it's time to start building the intelligence behind our application.

In this part, we'll introduce LangGraph and Google Gemini Flash and begin designing the multi-agent architecture that will eventually power our autonomous research system.

Rather than relying on a single AI model to perform every task, we'll divide the research process into four specialized agents:

  1. Planner Agent

  2. Researcher Agent

  3. Critic Agent

  4. Writer Agent

Each agent will have a specific responsibility, and they'll exchange information through a shared state managed by LangGraph.

We'll also create the foundational data structures required to store research sources, citations, conflicts, and report sections.


1. Managing Database Connections with FastAPI Lifespan

Before starting the agentic architecture, we need to complete an important part of our backend: managing the MongoDB connection throughout the application's lifecycle.

Previously, we created our database connection functions inside db.py:

  • init_db() – Initializes the database connection.

  • close_db() – Closes the database connection.

  • get_db() – Provides access to the database.

However, we still need to tell FastAPI when these functions should execute.

For this, we'll use FastAPI Lifespan.

The idea is straightforward:

  • When the FastAPI application starts, initialize the database connection.

  • Keep the connection available while the application is running.

  • When the application shuts down, close the database connection.

We implement this using an asynchronous context manager.

from contextlib import asynccontextmanager

from fastapi import FastAPI

from db import init_db, close_db

@asynccontextmanager
async def lifespan(app: FastAPI):
    await init_db()

    yield

    await close_db()

The @asynccontextmanager decorator allows us to manage resources across the lifetime of our application.

The yield statement separates the startup and shutdown phases.

Everything before yield executes during application startup, while everything after it executes when the application shuts down.

Next, we pass this lifespan function to our FastAPI application:

app = FastAPI(lifespan=lifespan)

We also load our environment variables when the application starts:

from dotenv import load_dotenv

load_dotenv()

This allows our application to access configuration values stored in the .env file.

After implementing this, we run the server and verify that the database connection is established successfully. When we stop the server, the connection is closed.

With this, our FastAPI application can manage its MongoDB connection automatically.


2. Introducing LangGraph: The Brain of Our Deep Research Agent

Now that our backend and database connection are ready, we can begin building the agentic system.

For this project, we're using LangGraph.

You might already be familiar with LangChain. LangChain is commonly used to build LLM-powered chains and applications where components execute in a sequence.

LangGraph gives us a different level of control.

It allows us to build workflows that can include:

  • Multiple specialized agents

  • Shared state between agents

  • Conditional execution

  • Cyclical workflows

  • Repeated execution and feedback loops

This is particularly useful for our Deep Research Agent.

Research isn't always a simple linear process. Sometimes the system needs to identify missing information, revisit a research question, collect additional evidence, or evaluate conflicting sources.

A graph-based workflow gives us the flexibility to design these interactions.

Installing the Required Dependencies

We'll install the packages needed for our LangGraph-based architecture and Google Gemini integration.

The main dependencies include:

  • langchain

  • langgraph

  • langchain-google-genai

We also pin package versions in our requirements file to maintain a consistent development environment.

The versions used in this recording include:

Package

Version

LangChain

0.3.0

LangGraph

0.2.28

Google Generative AI integration

0.7.2


3. Why We're Using Google Gemini 2.5 Flash

For the LLM layer, we're choosing Google Gemini 2.5 Flash.

There are two important considerations behind this decision.

First, our application is designed to process research material, including multiple sources and research papers.

Second, research-heavy tasks can require a large amount of context. The model needs to work with substantial amounts of information collected during the research process.

For this reason, we want a model with a large context window that can support our research workflow.

Gemini 2.5 Flash is our selected model for this project.

We'll use it as the foundation for powering our specialized agents.


4. Understanding LangGraph Shared State

Before writing the agents, we need to understand one of the most important concepts in LangGraph: State.

Let's understand it through an assembly-line analogy.

Imagine a factory where a product moves through multiple workers.

Each worker performs a specific task and adds something to the product before passing it to the next worker.

By the time the product reaches the final worker, it contains the contributions of everyone who worked on it.

Our multi-agent system follows a similar idea.

Instead of factory workers, we have AI agents.

Instead of a physical product, we have a shared state.

The state carries information between agents. Each agent reads the information it needs and contributes its own output.

In our application, this state will eventually contain:

  • The original user query

  • The maximum number of sources

  • Research sub-queries

  • Collected research sources

  • Citations

  • Conflicting claims

  • The final report summary

  • Structured report sections

  • Error and audit information

In our implementation, we'll define this state using Python's TypedDict.

This gives us a structured way to describe the information flowing through our LangGraph workflow.


5. Designing Our Four Specialized AI Agents

Our Deep Research Agent will use four specialized agents.

Each agent will contribute a different part of the final research report.

5.1 Planner Agent

The Planner Agent is responsible for understanding the user's research query and breaking it into smaller, actionable sub-queries.

For example, imagine a user asks:

"How is generative AI changing software engineering?"

Instead of asking a researcher agent to search for this broad topic directly, the Planner Agent can divide it into smaller research directions:

  • Current applications of generative AI in software development

  • AI-assisted code generation and debugging

  • Impact on software engineering productivity

  • Challenges and limitations of AI-generated code

  • Future developments in AI-powered software engineering

These sub-queries provide a structured direction for the research process.

We'll store them in the shared state so that the Researcher Agent can use them later.

5.2 Researcher Agent

The Researcher Agent is responsible for collecting information from different sources.

It will eventually gather research material from sources such as:

  • Web search results

  • PDF documents

  • Research papers available through arXiv

However, storing only a URL or a text string isn't sufficient.

We need to preserve additional information about each source, including its title, source type, extracted snippet, confidence score, timestamp, and metadata.

This is why we'll create a dedicated SourceDoc data model.

5.3 Critic Agent

Collecting information isn't enough. We also need a mechanism to evaluate the collected research.

This is where the Critic Agent comes in.

Its responsibility will be to identify conflicting information and potential inconsistencies in the research material.

For example, two sources might provide different claims about the same subject.

The Critic Agent will eventually help identify these conflicts so they can be evaluated before the final report is generated.

We'll create a structured ConflictFlag model to store these findings.

5.4 Writer Agent

Finally, the Writer Agent will organize the information gathered by the previous agents into a structured research report.

It will work with:

  • The research summary

  • Report headings

  • Main content

  • Supporting citations

The objective is to produce a readable, well-organized research report instead of simply returning a collection of search results.


6. Creating the Shared AgentState

Now that we understand the responsibilities of our agents, we can start defining the shared state.

Inside our project, we'll create a separate agents folder.

Our first file will be:

agents/
    state.py

We'll use TypedDict to define the structure of our state.

from typing import TypedDict, List, Any, Optional

class AgentState(TypedDict):
    # User input
    query: str
    max_sources: int

    # Planner contribution
    sub_queries: List[str]

    # Researcher contribution
    sources: List[Any]
    citations: List[dict]

    # Critic contribution
    conflicts: List[Any]

    # Writer contribution
    summary: str
    sections: List[Any]

    # Additional information
    error: Optional[str]
    report_id: Optional[str]
    log: List[str]

This is the central structure that will carry information throughout our multi-agent workflow.

Notice that the user initially provides only two values:

  • query

  • max_sources

The remaining fields will be populated as the agents perform their respective tasks.

The Planner Agent contributes the sub-queries.

The Researcher Agent contributes sources and citations.

The Critic Agent contributes conflict information.

The Writer Agent contributes the summary and report sections.

We also maintain additional fields for error handling, report identification, and logging.

This gives us a common structure for managing the information exchanged between our agents.


7. Creating the SourceDoc Pydantic Model

One important part of our research system is managing the sources collected by the Researcher Agent.

A research source contains more than just a URL.

We may need to store:

  • URL

  • Title

  • Source type

  • Extracted snippet

  • Confidence score

  • Timestamp

  • Additional metadata

To represent this information consistently, we'll create a SourceDoc model using Pydantic.

class SourceDoc(BaseModel):
    url: str
    title: str
    source_type: str
    snippet: str
    confidence_score: float
    timestamp: datetime
    metadata: dict

The confidence score is represented as a floating-point value, allowing us to store a score between 0 and 1.

The timestamp helps us keep track of when the source was collected.

The metadata field allows us to preserve additional information that may vary depending on the source.

This structured representation makes it easier to work with research sources throughout our application.

Defining Supported Source Types

Our research system is designed to work with different kinds of information sources.

For the initial architecture, we'll define three source categories:

  1. Web: Information collected from web search.

  2. PDF: Information extracted from PDF documents.

  3. arXiv: Research papers available through the arXiv research repository.

By defining these categories, we can distinguish between different types of sources instead of treating every source as an ordinary string.


8. Managing Research Citations

Citations are extremely important in a research application.

A report should not simply present information without indicating where that information came from.

For this reason, our shared state includes a dedicated citations field.

We'll use this field to store citation information collected during the research process.

The Researcher Agent will eventually contribute these citations, and the Writer Agent will use them while generating the final report.

This establishes the foundation for producing research reports that connect their claims to supporting sources.


9. Designing the Critic Agent's ConflictFlag Model

Next, we need to define how the Critic Agent will represent conflicting information.

For this, we'll create a ConflictFlag model.

class ConflictFlag(BaseModel):
    claim: str
    source_a: str
    source_b: str
    description: str

Let's understand these fields:

  • claim: The claim or statement where a conflict has been identified.

  • source_a: The first source associated with the claim.

  • source_b: The second source providing conflicting information.

  • description: A description of the identified conflict.

This structure will allow us to represent disagreements between sources in a consistent format.

The Critic Agent can eventually use this information to help evaluate the reliability and consistency of our research.


10. Defining the Writer Agent's Report Structure

The final responsibility belongs to the Writer Agent.

It needs a structured way to organize the information collected by the other agents.

We'll create a ReportSection model containing:

  • Heading

  • Content

  • Citations

Each report section will have its own heading, main content, and associated citations.

The Writer Agent will use these sections to organize the final report into a readable structure.

Alongside the report sections, our shared state will also contain:

  • summary: A summary of the research report.

  • error: Information about any errors encountered.

  • report_id: An identifier for the generated report.

  • log: A list of log entries.

These fields provide the foundation for managing the report and tracking information throughout the workflow.


11. What's Next?

At this point, we've established the foundational architecture for our multi-agent research system.

We've completed the FastAPI database lifecycle integration, introduced LangGraph, selected Gemini 2.5 Flash, and designed the shared state that will connect our four specialized agents.

We've also defined structured models for research sources, source types, conflict information, and report sections.

However, we haven't yet completed the actual execution of the agents.

The next step is to initialize the Gemini integration and begin building the LLM functionality that will power these agents.

From there, we'll gradually connect the agents into a working LangGraph workflow.

Our ultimate goal is to build a system that can independently plan research, gather evidence, evaluate information, and generate a comprehensive report.


Watch the Complete Implementation

This article accompanies Part 3 of our End-to-End Autonomous Deep Research Agent series.

Watch the video: [Insert Part 3 YouTube Video Link]

GitHub Repository:
https://github.com/snsupratim/research-agent

Complete Project Documentation:
https://www.sndev.co/project/988de038-1e9a-4411-aac5-828477b52df8

If you're following the series, you can also revisit the previous parts:

  • Part 1 – Introduction & Project Architecture

  • Part 2 – Building the Backend with FastAPI & MongoDB


Final Thoughts

Building an autonomous research system requires more than connecting an LLM to a search tool.

We need to think about how tasks are divided, how agents exchange information, how research sources are represented, and how the final output is structured.

That's why we're taking a multi-agent approach with LangGraph.

By separating planning, research, evaluation, and report generation into specialized responsibilities, we're laying the foundation for a more structured and extensible research system.

In the upcoming parts, we'll turn this architecture into an actual working agentic workflow.

Let's build it step by step.

AgenticAI
Python
FastAPI
AIEngineering
LangGraph
GenerativeAI
Gemini
DeepResearchAgent
Series Navigation

Up Next: Part 4

Continue following "Deep Research Agent" with Building AI Agent with LangGraph | Planner Agent Implementation | Deep Research Agent | Part 4.

Part 2Read Part 4

Community Discussion
0

Ask questions, discuss architecture, and share insights with other developers.

Sort:

Sign in to join the discussion and share your thoughts with other developers.

Sign In to Comment
Loading discussions…