Decomposing Financial Queries with TODO Planning Agents

Implement a task-planning agentic RAG system that decomposes complex financial comparison queries into checklists using TodoListMiddleware and SummarizationMiddleware.

Jun 19, 20265 min readFollow

Topics You Will Master

Decomposing multi-part queries into sequential tasks with TodoListMiddleware
Managing long-running agent threads using SummarizationMiddleware thresholds
Interacting with structured todo states (in_progress, pending, completed)
Tracing parallel and linear reasoning paths using Gemini 3 and LangChain

Complex user queries like "Compare Apple's Q1 2024 earnings with its current stock performance" require multiple sequential actions. An agent must search historical databases, call live APIs, compile data tables, and write comparisons. Without structured guidance, agents can lose track of the plan. By integrating task-planning (TODO lists) and summarization middleware, developers can create reliable multi-step agents.

This guide covers building a deep financial research agent equipped with planning and memory consolidation middlewares.

95% OFF

Agentic RAG with LangChain and LangGraph - Ollama

Step-by-step guide to RAG with LangChain, LangGraph, and Ollama | DeepSeek R1, QWEN, LLAMA, FAISS.

Enroll Now — 95% OFF →

Planning Agent Architecture

To prevent memory bloat and execution drift, we configure two distinct middlewares:

  1. Summarization Middleware: Monitors thread history. When the message history exceeds 25 messages, it compresses the oldest 15 messages into a running summary, keeping only the 10 most recent messages as raw context.
  2. TodoList Middleware: Intercepts the query to generate a checklist. The agent runs the write_todos tool to declare subtasks, updating each task's status as it works.
PLAINTEXT
                  +--------------------------------+
                  |       User Complex Query       |
                  +--------------------------------+
                                  |
                                  v
                  +--------------------------------+
                  |  TodoListMiddleware Intercept  |
                  +--------------------------------+
                                  |
                                  v
                  +--------------------------------+
                  |  Generate & Write Task List    |
                  |  - Todo 1: Search Q1 Revenue   |
                  |  - Todo 2: Get Stock Price     |
                  |  - Todo 3: Synthesize Metrics  |
                  +--------------------------------+
                                  |
                                  v
                  +--------------------------------+
                  | Sequential Executor with Memory| <---> Summarization DB
                  +--------------------------------+

Implementing the Planning Agent

Initialize the agent with middleware lists in scripts/planning_agent.py:

PYTHON
import sqlite3
from dotenv import load_dotenv
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.agents import create_agent
from langgraph.checkpoint.sqlite import SqliteSaver

# Middleware modules
from langchain.agents.middleware import TodoListMiddleware, SummarizationMiddleware

from scripts.rag_tools import hybrid_search, live_finance_researcher
from scripts.prompts import MULTIMODEL_AGENT_PROMPT

load_dotenv()

# Select reasoning engine
model = ChatGoogleGenerativeAI(model='gemini-3-pro-preview')

def get_planning_agent():
    # Database connection for task state persistence
    conn = sqlite3.connect('data/todo_financial_research_agent.db', check_same_thread=False)
    checkpointer = SqliteSaver(conn=conn)

    agent = create_agent(
        model=model,
        tools=[hybrid_search, live_finance_researcher],
        system_prompt=MULTIMODEL_AGENT_PROMPT,
        checkpointer=checkpointer,
        middleware=[
            # Keeps context window small during long reasoning loops
            SummarizationMiddleware(
                model=model,
                trigger=[('messages', 25)],
                keep=('messages', 10)
            ),
            # Decomposes queries into structured task states
            TodoListMiddleware()
        ]
    )
    return agent

agent = get_planning_agent()

Tracing Execution Flows

We pass the agent a multi-part query to trace how it plans, executes, and updates its progress.

PYTHON
from scripts.agent_utils import stream_agent_response

query = "Compare Microsoft's Q2 2024 revenue from SEC filings with its current stock performance."
stream_agent_response(agent, query, thread_id="comparison_session")

Stage 1: Planning and Decomposing Tasks

First, the TodoListMiddleware intercepts the query. The agent calls write_todos to establish a plan:

PLAINTEXT
  [Tool Triggered]: write_todos
   Arguments: {
     'todos': [
       {'status': 'in_progress', 'content': "Search for Microsoft's Q2 2024 revenue in SEC filings"}, 
       {'status': 'pending', 'content': "Get Microsoft's current stock performance from Yahoo Finance"}, 
       {'status': 'pending', 'content': "Compare the revenue data with current stock performance and write a summary with citations"}
     ]
   }

  [Tool Completed]

Stage 2: Historical Research (Task 1)

Next, the agent tackles the first task in its checklist by querying the historical database:

PLAINTEXT
  [Tool Triggered]: hybrid_search
   Arguments: {'query': 'Microsoft Q2 2024 revenue SEC filings'}

  [Tool Completed] (returned 12450 chars)

Stage 3: Live Market Research (Task 2)

After parsing the historical metrics, the agent updates the status of the first task to completed and queries Yahoo Finance for current stock data:

PLAINTEXT
  [Tool Triggered]: write_todos
   Arguments: {
     'todos': [
       {'status': 'completed', 'content': "Search for Microsoft's Q2 2024 revenue in SEC filings"}, 
       {'status': 'in_progress', 'content': "Get Microsoft's current stock performance from Yahoo Finance"}, 
       {'status': 'pending', 'content': "Compare the revenue data with current stock performance and write a summary with citations"}
     ]
   }

  [Tool Completed]

  [Tool Triggered]: live_finance_researcher
   Arguments: {'query': 'Microsoft current stock price and performance'}

  [Tool Completed] (returned 540 chars)

Stage 4: Synthesizing the Final Analysis (Task 3)

Finally, the agent compiles the retrieved data, updates the task statuses, and outputs its final answer:

PLAINTEXT
  [Tool Triggered]: write_todos
   Arguments: {
     'todos': [
       {'status': 'completed', 'content': "Search for Microsoft's Q2 2024 revenue in SEC filings"}, 
       {'status': 'completed', 'content': "Get Microsoft's current stock performance from Yahoo Finance"}, 
       {'status': 'completed', 'content': "Compare the revenue data with current stock performance and write a summary with citations"}
     ]
   }

  [Tool Completed]

### Microsoft Performance Analysis

| Metric Category | Historical Q2 2024 (Ended Dec 31, 2023) | Current Market Performance |
| :--- | :--- | :--- |
| **Revenue** | $62.02 Billion (up 18% YoY) | N/A |
| **Stock Price** | N/A | $491.02 |
| **Market Cap** | N/A | $3.65 Trillion |

**Synthesis:** 
Microsoft's strong financial performance in Q2 2024, driven by a 33% increase in operating income, supports its premium valuation in the public market today.

Sources:
- Source: MSFT-Q2-2024-10Q.pdf, page 14
- Source: Yahoo Finance (live data)

Found this useful? Keep building with me.

New tutorials every week on YouTube — or go deeper with a full structured course.

Find this tutorial useful?

Subscribe to our YouTube channels for more practical production walk-throughs.

Discussion & Comments