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 AI Agent with LangGraph | Planner Agent Implementation | Deep Research Agent | Part 4

GitHub RepositoryWatch on YouTube

β€œBuild a LangGraph Planner Agent using Google Gemini 2.5 Flash. Create an async LLM connector, generate research sub-queries, parse JSON responses, and implement error handling.”

Project SeriesPart 4 of 13

Deep Research Agent

Series Progress31%
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
Building the Agentic AI Brain with LangGraph | Autonomous Deep Research Agent | Part 3
Available
P4
Building AI Agent with LangGraph | Planner Agent Implementation | Deep Research Agent | Part 4
Current Part
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 3Part 5

In the previous part of our Autonomous Deep Research Agent project, we designed the foundation of our multi-agent architecture using LangGraph and Google Gemini.

We introduced four specialized agents:

  1. Planner Agent

  2. Researcher Agent

  3. Critic Agent

  4. Writer Agent

We also created the shared AgentState, which will allow these agents to exchange information throughout the research workflow.

But defining an architecture is only the beginning. Now we need to make these agents actually perform their respective tasks.

In this part, we'll configure Google Gemini 2.5 Flash, create a reusable LLM connector, and implement our first LangGraph node: the Planner Agent.

The Planner Agent will take a user's research question and transform it into 4–6 focused sub-queries that can be used by the Researcher Agent.

Let's start building.


1. Initializing Google Gemini AI

Before implementing our agents, we need to establish a connection with our LLM provider.

For this project, we're using Google Gemini 2.5 Flash.

Rather than initializing the Gemini model separately inside every agent, we'll create a centralized LLM connector.

This gives us a reusable function that our agents can call whenever they need an LLM response.

Getting a Gemini API Key

To get started, visit Google AI Studio.

From there:

  1. Open Google AI Studio.

  2. Navigate to the API keys section.

  3. Create or select a Google Cloud project.

  4. Generate an API key.

  5. Copy the key and store it securely.

Google AI Studio provides API access with usage limits and pricing that depend on the applicable model and account terms. Check the current limits before using it in a production application.

Adding Environment Variables

We'll store two configuration values in our .env file:

GEMINI_API_KEY=your_gemini_api_key
GEMINI_MODEL=gemini-3.8-flash

This keeps our API credentials and model configuration outside the application code.

Important: Never commit your .env file or expose your API key in a public GitHub repository.


2. Creating a Reusable LLM Connector

Inside our agents directory, we'll create a new file:

agents/
    llm.py

This file will act as the central LLM connector for our multi-agent system.

The idea is simple: instead of allowing every agent to manage its own Gemini configuration, we'll initialize the model once and expose a reusable asynchronous function.

Loading the Gemini Configuration

First, we'll load our environment variables and configure the Google Generative AI client.

The connector performs three main operations:

  • Loads the Gemini API key.

  • Retrieves the configured Gemini model name.

  • Initializes the Gemini generative model.

This allows us to change the model through environment configuration rather than modifying every agent.

Building the Async LLM Function

Next, we'll define a reusable asynchronous function that accepts three important parameters:

Parameter

Purpose

system_prompt

Defines the role and instructions for the LLM

user_query

Contains the task or question provided to the model

max_tokens

Controls the maximum generated output length

The function combines the system prompt and user query into a prompt and sends it to Gemini using asynchronous content generation.

We also configure the generation parameters.

Understanding Temperature for Research Applications

One particularly important parameter is temperature.

Temperature controls how much variation and creativity we allow in the model's responses.

For creative writing, a higher temperature may be useful because we want more varied outputs.

However, our application is a research system.

We want the model to focus on the information provided to it rather than unnecessarily generating creative or speculative responses.

For this reason, we're using a lower temperature of 0.3.

This encourages more consistent responses, although temperature alone cannot guarantee factual accuracy. We'll still need research evidence, citations, and evaluation mechanisms to improve reliability.

We also configure the maximum output tokens and handle cases where the model does not return usable text.

With this implementation, we now have a reusable LLM function that our specialized agents can call.


3. Designing the Complete Multi-Agent Architecture

Now that our LLM connector is ready, let's look at how the complete research pipeline will work.

Our MVP architecture contains four specialized agents and a collection of tools.

Each agent has a distinct responsibility.

3.1 Planner Agent

The Planner Agent receives the original research question and breaks it down into approximately four to six focused sub-queries.

For example, consider this question:

"How do ReAct agents work, and how are they used in modern AI applications?"

The Planner Agent can divide it into smaller research directions, such as:

  • Understanding the ReAct framework.

  • The Thought, Action, and Observation cycle.

  • How ReAct agents interact with external tools.

  • Practical applications of ReAct agents.

  • Limitations and challenges of ReAct-based systems.

These sub-queries will be passed to the Researcher Agent through the shared state.

3.2 Researcher Agent

The Researcher Agent receives the generated sub-queries and collects relevant information.

For our MVP, we're planning three main capabilities:

  • Web search

  • arXiv research-paper search

  • Citation building

The Researcher Agent will use these tools to gather information and organize the evidence collected during the research process.

3.3 Critic Agent

Collecting information from multiple sources can introduce conflicting claims.

The Critic Agent will help identify these inconsistencies.

It will use a cross-reference tool to compare information and identify claims that may require further evaluation.

3.4 Writer Agent

The Writer Agent takes the information gathered by the previous agents and generates the final research report.

It will use the LLM connector to organize the research into structured sections, summaries, and citations.


4. Understanding the Tools Used by Our Agents

Alongside the four agents, we'll build dedicated tools.

The tools are responsible for performing specific operations, while the agents decide how to use their capabilities as part of the research workflow.

Our MVP includes the following tools:

Tool

Responsibility

Used by

LLM Connector

Generates LLM responses

Planner and Writer

Web Search

Searches for relevant online information

Researcher

arXiv Search

Finds relevant academic papers

Researcher

Cross-Reference

Compares claims across sources

Critic

Citation Builder

Structures source citations

Researcher

For web search, we're planning to use the Tavily API.

The arXiv search tool will help retrieve relevant academic research papers.

The cross-reference tool will support the Critic Agent, while the citation builder will help the Researcher Agent preserve source information.

This separation makes our architecture easier to extend.

In the future, we can introduce additional agents, tools, and validation stages without redesigning the entire application.


5. Implementing Our First LangGraph Node: Planner Agent

Now comes the main implementation of this episode.

We'll start with the Planner Agent because it is the first component in our research pipeline.

Inside the agents directory, we'll create a dedicated file for our agent nodes.

The Planner node will be an asynchronous function that accepts the shared AgentState and returns the updated state.

Conceptually, its responsibility is:

  1. Read the user's original research query.

  2. Update the execution status.

  3. Add an audit log entry.

  4. Send the query to Gemini using our LLM connector.

  5. Receive the generated sub-queries.

  6. Parse and validate the response.

  7. Store the sub-queries in the shared state.

  8. Return the updated state.

This allows the next agent to access the Planner's output without requiring a separate communication mechanism.

Updating the Execution Status

When the Planner Agent starts executing, we update the report status in our shared state.

In this implementation, we use the existing researching status because our current status enum does not yet include a separate planning value.

We also maintain audit logs.

This helps us understand which agent has executed and what task it was performing.

For example, we record a message indicating that sub-queries are being generated from the original research question.

These logs will become useful when we introduce more complex workflows and execution monitoring.


6. Writing the Planner System Prompt

Next, we define the system prompt that tells Gemini what the Planner Agent is expected to do.

The instructions are straightforward:

  • Act as a research planner.

  • Understand the main query provided by the user.

  • Generate four to six focused sub-queries.

  • Keep each sub-query concise and relevant.

  • Return the output in JSON array format.

Why do we request JSON?

Because we don't want to receive an unstructured paragraph that our application must interpret manually.

We want a predictable output that can be parsed and passed to the next agent.

For example, a valid response should follow this structure:

[
  "Understand the fundamentals of the topic",
  "Explore its architecture and working principles",
  "Identify practical applications",
  "Analyze limitations and challenges",
  "Investigate recent developments"
]

These are illustrative sub-queries. The actual output will depend on the user's research question.


7. Calling Gemini and Generating Sub-Queries

Once the system prompt is ready, we call our reusable LLM function.

We pass:

  • The Planner system prompt.

  • The original user query from AgentState.

  • A maximum output token limit of 500 for this Planner call.

Gemini processes the request and returns its response.

However, we should not immediately assume that the response will always be valid JSON.

LLMs can sometimes return additional formatting, malformed content, or an unexpected response.

Therefore, we need to parse and validate the output before passing it to another agent.

Parsing the JSON Response

We'll use Python's json module to parse the response.

First, we clean the returned text and then attempt to decode it as JSON.

The resulting value should be a Python list containing the generated sub-queries.

We also apply a limit so that even if the model returns more than six sub-queries, we only accept the first six.

This ensures that the Planner Agent follows the constraints of our MVP architecture.


8. Adding Error Handling and Fallback Queries

This is an important part of building a reliable agentic system.

What happens if Gemini returns an invalid response?

What if the response is empty?

What if the JSON cannot be parsed?

We don't want the entire research workflow to fail simply because the Planner Agent produced an unexpected response.

For this reason, we'll add a try-except block.

The implementation handles failures by:

  1. Recording the error in the shared state.

  2. Adding an appropriate audit log message.

  3. Checking whether the generated response has the expected list structure.

  4. Using fallback queries when an exception occurs.

Our fallback strategy generates four basic research directions using the original query:

  • The original query combined with a research-oriented direction.

  • The original query combined with a study-oriented direction.

  • The original query combined with an analysis-oriented direction.

  • Another related research direction.

This ensures that the Researcher Agent can still receive useful starting queries when the LLM response fails.

We also validate that the parsed response is actually a list.

If the response does not follow the expected structure, we record an error rather than silently treating an invalid response as a successful result.

This is an important engineering principle: never assume that an LLM will always return the exact output format you requested.


9. Understanding the Complete Planner Agent Flow

Let's summarize what happens when our Planner Agent executes.

User Research Query
        |
        v
   Planner Node
        |
        v
  Update Agent Status
        |
        v
    Add Audit Log
        |
        v
   Build System Prompt
        |
        v
   Call Gemini LLM
        |
        v
  Receive LLM Response
        |
        v
   Parse JSON Response
        |
        v
    Validate Output
        |
        v
  Store Sub-Queries
        |
        v
   Update Agent State
        |
        v
  Return Updated State

If response parsing or execution fails, our error-handling logic records the problem and provides fallback queries where applicable.

The updated state can then be passed to the next stage of the research workflow.

With this, we've implemented the first actual agent in our Autonomous Deep Research Agent.


10. What's Next?

In this part, we've completed two important building blocks:

  • A reusable Gemini-powered LLM connector.

  • Our first LangGraph agent: the Planner Agent.

We've also designed how the remaining agents and tools will interact.

However, our research pipeline is not complete yet.

The next step is implementing the Researcher Agent.

It will consume the sub-queries generated by the Planner and use external tools to collect relevant information.

We'll begin building the search and research capabilities that will turn our agent from a query planner into an actual research system.


Watch the Complete Implementation

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

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

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

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

Follow the previous parts to understand the complete implementation:

  • Part 1 – Introduction and Project Architecture

  • Part 2 – Backend Development with FastAPI and MongoDB

  • Part 3 – LangGraph, Gemini and Shared Agent State


Final Thoughts

An LLM connection alone doesn't make an application an autonomous agent.

We need to give the model a defined responsibility, connect it to the application's state, control its output, and handle unexpected responses.

That's exactly what we're doing with the Planner Agent.

By separating the planning process from research, evaluation, and report generation, we're building a modular foundation for our Autonomous Deep Research Agent.

In the next part, we'll continue implementing the research pipeline and bring our Researcher Agent to life.

Let's build it one agent at a time.

AgenticAI
Python
AIEngineering
LangGraph
GenerativeAI
DeepResearchAgent
Series Navigation

Up Next: Part 5

Continue following "Deep Research Agent" with Building AI Agent Tools | Rate Limiting & Source Credibility | Deep Research Agent | Part 5.

Part 3Read Part 5

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…