- unwind ai
- Posts
- Build a Multi-Agent Personal Finance Coach
Build a Multi-Agent Personal Finance Coach
Fully functional multi-agent app with step-by-step instructions (100% opensource)
Financial management is a deeply personal and context-sensitive domain where one-size-fits-all AI solutions typically fall short. Building truly helpful AI financial advisors requires understanding the interplay between budgeting, saving, and debt management as interconnected rather than isolated concerns.
A multi-agent system provides the perfect architecture for this approach, allowing us to craft specialized agents that collaborate rather than operate in silos, mirroring how human financial advisors actually work.
In this tutorial, we'll build a Multi-Agent Personal Financial Coach application using Google’s newly released Agent Development Kit (ADK) and the Gemini model. Our application will feature specialized agents for budget analysis, savings strategies, and debt reduction working together to provide comprehensive financial advice. The system will offer actionable recommendations with interactive visualizations.
Google's (ADK) is an open-source, code-first Python toolkit designed for building AI agents with fine-grained control. You can define agent behavior, orchestration, and tool use directly in code, making it perfect for our multi-agent systems.
What We’re Building
This Streamlit application implements a comprehensive financial advisory system using Google's Agent Development Kit (ADK) with multiple specialized AI agents.
Features:
👬 Multi-Agent Financial Analysis System
Budget Analysis Agent: Analyzes spending patterns and recommends optimizations
Savings Strategy Agent: Creates personalized savings plans and emergency fund strategies
Debt Reduction Agent: Develops optimized debt payoff strategies using avalanche and snowball methods
🫰 Expense Analysis:
Supports both CSV upload and manual expense entry
Visual breakdown of spending by category
Automated expense categorization and pattern detection
💰 Savings Recommendations:
Emergency fund sizing and building strategies
Custom savings allocations across different goals
💸 Debt Management:
Multiple debt handling with interest rate optimization
Comparison between avalanche and snowball methods
Visual debt payoff timeline and interest savings analysis
Actionable debt reduction recommendations
📊 Interactive Visualizations:
Pie charts for expense breakdown
Bar charts for income vs. expenses
Debt comparison graphs
How The App Works
The application follows a multi-agent coordination pattern typical of complex AI systems:
Data Collection: Users enter financial information (income, expenses, debts) through the Streamlit interface, either manually or via CSV upload.
Agent Chain Execution: The app uses
SequentialAgent
, a workflow agent that executes its sub-agents in the order they are specified in the list:Budget Analysis Agent evaluates spending patterns and identifies areas for reduction
Savings Strategy Agent develops savings plans based on budget analysis
Debt Reduction Agent creates optimized debt payoff strategies using both analytical methods
State Management: Each agent stores its results in the shared session state, allowing subsequent agents to build upon prior analysis. This state-passing mechanism enables a coherent analysis pipeline without duplicating work.
Visualization: The application processes agent outputs into interactive visualizations using Plotly, making complex financial insights accessible and actionable.
Prerequisites
Before we begin, make sure you have the following:
Python installed on your machine (version 3.10 or higher is recommended)
Your Gemini API key (get one from Google AI Studio)
A code editor of your choice (we recommend VS Code or PyCharm for their excellent Python support)
Basic familiarity with Python programming
Code Walkthrough
Setting Up the Environment
First, let's get our development environment ready:
Clone the GitHub repository:
git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git
Go to the ai_financial_coach_agent folder:
cd ai_agent_tutorials/ai_financial_coach_agent
Install the required dependencies:
pip install -r requirements.txt
API Key: Get your Gemini API key from the Google AI Studio.
Creating the Streamlit App
Let’s create our app. Create a new file ai_financial_coach_agent.py
and add the following code:
Import necessary libraries:
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from typing import Dict, List, Optional, Any
import os
import asyncio
from datetime import datetime
from dotenv import load_dotenv
import json
import logging
from pydantic import BaseModel, Field
from google.adk.agents import LlmAgent, SequentialAgent
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner
from google.genai import types
Define Output Schemas with Pydantic: This ensures our agents produce structured, validated outputs.
class BudgetAnalysis(BaseModel):
total_expenses: float = Field(..., description="Total monthly expenses")
monthly_income: Optional[float] = Field(None, description="Monthly income")
spending_categories: List[SpendingCategory] = Field(..., description="Breakdown of spending by category")
recommendations: List[SpendingRecommendation] = Field(..., description="Spending recommendations")
class SavingsStrategy(BaseModel):
emergency_fund: EmergencyFund = Field(..., description="Emergency fund recommendation")
recommendations: List[SavingsRecommendation] = Field(..., description="Savings allocation recommendations")
automation_techniques: Optional[List[AutomationTechnique]] = Field(None, description="Automation techniques to help save")
class DebtReduction(BaseModel):
total_debt: float = Field(..., description="Total debt amount")
debts: List[Debt] = Field(..., description="List of all debts")
payoff_plans: PayoffPlans = Field(..., description="Debt payoff strategies")
recommendations: Optional[List[DebtRecommendation]] = Field(None, description="Recommendations for debt reduction")
Set Up the Finance Advisor System: Initialize the session service and create specialized agents.
class FinanceAdvisorSystem:
def __init__(self):
self.session_service = InMemorySessionService()
self.budget_analysis_agent = LlmAgent(
name="BudgetAnalysisAgent",
model="gemini-2.0-flash-exp",
description="Analyzes financial data to categorize spending patterns and recommend budget improvements",
instruction="""You are a Budget Analysis Agent specialized in reviewing financial transactions and expenses.
You are the first agent in a sequence of three financial advisor agents...""",
output_schema=BudgetAnalysis,
output_key="budget_analysis"
)
self.savings_strategy_agent = LlmAgent(
name="SavingsStrategyAgent",
model="gemini-2.0-flash-exp",
description="Recommends optimal savings strategies based on income, expenses, and financial goals",
instruction="""You are a Savings Strategy Agent specialized in creating personalized savings plans.
You are the second agent in the sequence...""",
output_schema=SavingsStrategy,
output_key="savings_strategy"
)
self.debt_reduction_agent = LlmAgent(
name="DebtReductionAgent",
model="gemini-2.0-flash-exp",
description="Creates optimized debt payoff plans to minimize interest paid and time to debt freedom",
instruction="""You are a Debt Reduction Agent specialized in creating debt payoff strategies.
You are the final agent in the sequence...""",
output_schema=DebtReduction,
output_key="debt_reduction"
)
self.coordinator_agent = SequentialAgent(
name="FinanceCoordinatorAgent",
description="Coordinates specialized finance agents to provide comprehensive financial advice",
sub_agents=[
self.budget_analysis_agent,
self.savings_strategy_agent,
self.debt_reduction_agent
]
)
self.runner = Runner(
agent=self.coordinator_agent,
app_name=APP_NAME,
session_service=self.session_service
)
Finance Analysis Method: Process financial data through the agent pipeline.
async def analyze_finances(self, financial_data: Dict[str, Any]) -> Dict[str, Any]:
session_id = f"finance_session_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
try:
initial_state = {
"monthly_income": financial_data.get("monthly_income", 0),
"dependants": financial_data.get("dependants", 0),
"transactions": financial_data.get("transactions", []),
"manual_expenses": financial_data.get("manual_expenses", {}),
"debts": financial_data.get("debts", [])
}
session = self.session_service.create_session(
app_name=APP_NAME,
user_id=USER_ID,
session_id=session_id,
state=initial_state
)
# Preprocess transaction data if available
if session.state.get("transactions"):
self._preprocess_transactions(session)
# Process manual expenses if available
if session.state.get("manual_expenses"):
self._preprocess_manual_expenses(session)
# Create default results as fallback
default_results = self._create_default_results(financial_data)
# Create user message
user_content = types.Content(
role='user',
parts=[types.Part(text=json.dumps(financial_data))]
)
# Run the agent pipeline
async for event in self.runner.run_async(
user_id=USER_ID,
session_id=session_id,
new_message=user_content
):
if event.is_final_response() and event.author == self.coordinator_agent.name:
break
# Get updated session state with agent results
updated_session = self.session_service.get_session(
app_name=APP_NAME,
user_id=USER_ID,
session_id=session_id
)
# Extract and return results
results = {}
for key in ["budget_analysis", "savings_strategy", "debt_reduction"]:
value = updated_session.state.get(key)
results[key] = parse_json_safely(value, default_results[key]) if value else default_results[key]
return results
finally:
# Clean up session
self.session_service.delete_session(
app_name=APP_NAME,
user_id=USER_ID,
session_id=session_id
)
CSV Transaction Processing: Parse and validate CSV upload data.
def parse_csv_transactions(file_content) -> List[Dict[str, Any]]:
"""Parse CSV file content into a list of transactions"""
try:
# Read CSV content
df = pd.read_csv(StringIO(file_content.decode('utf-8')))
# Validate required columns
required_columns = ['Date', 'Category', 'Amount']
missing_columns = [col for col in required_columns if col not in df.columns]
if missing_columns:
raise ValueError(f"Missing required columns: {', '.join(missing_columns)}")
# Convert date strings to datetime and then to string format YYYY-MM-DD
df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d')
# Convert amount strings to float, handling currency symbols and commas
df['Amount'] = df['Amount'].replace('[\$,]', '', regex=True).astype(float)
# Group by category and calculate totals
category_totals = df.groupby('Category')['Amount'].sum().reset_index()
# Convert to list of dictionaries
transactions = df.to_dict('records')
return {
'transactions': transactions,
'category_totals': category_totals.to_dict('records')
}
except Exception as e:
raise ValueError(f"Error parsing CSV file: {str(e)}")
Visualization Functions: Create interactive charts for budget breakdown, savings, and debt comparison.
def display_budget_analysis(analysis: Dict[str, Any]):
if "spending_categories" in analysis:
st.subheader("Spending by Category")
fig = px.pie(
values=[cat["amount"] for cat in analysis["spending_categories"]],
names=[cat["category"] for cat in analysis["spending_categories"]],
title="Your Spending Breakdown"
)
st.plotly_chart(fig)
if "total_expenses" in analysis:
st.subheader("Income vs. Expenses")
income = analysis.get("monthly_income", 0)
expenses = analysis["total_expenses"]
surplus_deficit = income - expenses
fig = go.Figure()
fig.add_trace(go.Bar(x=["Income", "Expenses"],
y=[income, expenses],
marker_color=["green", "red"]))
fig.update_layout(title="Monthly Income vs. Expenses")
st.plotly_chart(fig)
Streamlit UI Setup: Create the main UI with tabs for different data entry options.
def main():
st.set_page_config(
page_title="AI Financial Coach with Google ADK",
layout="wide",
initial_sidebar_state="expanded"
)
# Sidebar with API key info and CSV template
with st.sidebar:
st.title("🔑 Setup & Templates")
st.info("📝 Please ensure you have your Gemini API key in the .env file:\n```\nGOOGLE_API_KEY=your_api_key_here\n```")
st.caption("This application uses Google's ADK (Agent Development Kit) and Gemini AI to provide personalized financial advice.")
# Add CSV template download
st.subheader("📊 CSV Template")
st.markdown("""
Download the template CSV file with the required format:
- Date (YYYY-MM-DD)
- Category
- Amount (numeric)
""")
# Create sample CSV content
sample_csv = """Date,Category,Amount
2024-01-01,Housing,1200.00
2024-01-02,Food,150.50
2024-01-03,Transportation,45.00"""
st.download_button(
label="📥 Download CSV Template",
data=sample_csv,
file_name="expense_template.csv",
mime="text/csv"
)
Running the App
With our code in place, it's time to launch the app.
In your terminal, navigate to the project folder, and run the following command
streamlit run ai_financial_coach_agent.py
Streamlit will provide a local URL (typically http://localhost:8501). Open this in your web browser, put in your API key, enter your details, and watch the agents give you real actionable recommendations.
Working Application Demo
Conclusion
You've successfully built a comprehensive Multi-Agent Financial Coach using Google's Agent Development Kit and Gemini AI. This application demonstrates how specialized agents can work together to solve complex problems, sharing information through a structured workflow.
For further enhancements, consider:
Extending Historical Analysis: Add time-series projections to show how savings will grow or debts will decrease over time based on recommendations.
Financial Goal Planning: Add a fourth specialized agent focused specifically on goal setting and milestone planning for major life purchases or events.
Custom Agent Instructions: Allow users to provide specific contexts or preferences that would customize each agent's approach (risk tolerance, value prioritization, geographic considerations).
Persistent Storage: Implement a database backend to allow users to save their financial data and track progress over time.
Keep experimenting with different agent configurations and features to build more sophisticated AI applications.
We share hands-on tutorials like this 2-3 times a week, to help you stay ahead in the world of AI. If you're serious about leveling up your AI skills and staying ahead of the curve, subscribe now and be the first to access our latest tutorials.
Reply