β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.β
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:
Planner Agent
Researcher Agent
Critic Agent
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.
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.
To get started, visit Google AI Studio.
From there:
Open Google AI Studio.
Navigate to the API keys section.
Create or select a Google Cloud project.
Generate an API key.
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.
We'll store two configuration values in our .env file:
GEMINI_API_KEY=your_gemini_api_key
GEMINI_MODEL=gemini-3.8-flashThis 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.
Inside our agents directory, we'll create a new file:
agents/
llm.pyThis 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.
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.
Next, we'll define a reusable asynchronous function that accepts three important parameters:
Parameter | Purpose |
|---|---|
| Defines the role and instructions for the LLM |
| Contains the task or question provided to the model |
| 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.
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.
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.
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.
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.
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.
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.
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.
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:
Read the user's original research query.
Update the execution status.
Add an audit log entry.
Send the query to Gemini using our LLM connector.
Receive the generated sub-queries.
Parse and validate the response.
Store the sub-queries in the shared state.
Return the updated state.
This allows the next agent to access the Planner's output without requiring a separate communication mechanism.
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.
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.
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.
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.
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:
Recording the error in the shared state.
Adding an appropriate audit log message.
Checking whether the generated response has the expected list structure.
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.
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 StateIf 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.
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.
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
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.
Continue following "Deep Research Agent" with Building AI Agent Tools | Rate Limiting & Source Credibility | Deep Research Agent | Part 5.
Ask questions, discuss architecture, and share insights with other developers.
Sign in to join the discussion and share your thoughts with other developers.
Sign In to Comment