techprotrade's picture
Add loan-advisor-agent
366ff00 verified
Raw
History Blame Contribute Delete
7.46 kB
# ruff: noqa
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from typing import Optional
from google.adk.agents import Agent
from google.adk.apps import App
from google.adk.models import Gemini
from google.genai import types
import os
import google.auth
_, project_id = google.auth.default()
os.environ["GOOGLE_CLOUD_PROJECT"] = project_id
os.environ["GOOGLE_CLOUD_LOCATION"] = "global"
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True"
def get_loan_products(
use_case: Optional[str] = None,
amount_range: Optional[str] = None,
) -> str:
"""Retrieve available loan products and their terms.
Args:
use_case: The intended use (e.g., 'startup', 'expansion', 'working_capital').
amount_range: The loan amount range as 'min-max' in euros.
Returns:
A JSON string containing available loan products with terms.
"""
loans_db = [
{
"id": "startup_basic",
"name": "Startup Growth Loan",
"min_amount": 10000,
"max_amount": 250000,
"interest_rate": 6.5,
"term_years": [3, 5, 7],
"use_case": ["startup"],
"description": "For new businesses and startups",
},
{
"id": "business_expansion",
"name": "Business Expansion Credit",
"min_amount": 50000,
"max_amount": 1000000,
"interest_rate": 5.2,
"term_years": [5, 7, 10],
"use_case": ["expansion", "growth"],
"description": "For established businesses expanding operations",
},
{
"id": "working_capital",
"name": "Working Capital Loan",
"min_amount": 25000,
"max_amount": 500000,
"interest_rate": 7.1,
"term_years": [2, 3, 5],
"use_case": ["working_capital", "cash_flow"],
"description": "Short-term financing for operational needs",
},
{
"id": "equipment_finance",
"name": "Equipment Financing",
"min_amount": 20000,
"max_amount": 750000,
"interest_rate": 4.8,
"term_years": [5, 7, 10, 12],
"use_case": ["equipment", "infrastructure"],
"description": "Asset-backed financing for equipment purchases",
},
]
filtered = loans_db
if use_case:
filtered = [
loan
for loan in filtered
if any(use in loan["use_case"] for use in use_case.lower().split(","))
]
return json.dumps(filtered, indent=2)
def calculate_loan_payment(
principal: float, annual_interest_rate: float, years: int
) -> str:
"""Calculate monthly payment and total cost for a loan.
Args:
principal: Loan amount in euros.
annual_interest_rate: Annual interest rate as a percentage (e.g., 5.5).
years: Loan term in years.
Returns:
A JSON string with monthly payment, total interest, and total cost.
"""
monthly_rate = annual_interest_rate / 100 / 12
num_payments = years * 12
if monthly_rate == 0:
monthly_payment = principal / num_payments
else:
monthly_payment = principal * (
monthly_rate * (1 + monthly_rate) ** num_payments
) / ((1 + monthly_rate) ** num_payments - 1)
total_paid = monthly_payment * num_payments
total_interest = total_paid - principal
return json.dumps(
{
"principal": principal,
"annual_interest_rate": annual_interest_rate,
"term_years": years,
"monthly_payment": round(monthly_payment, 2),
"total_interest": round(total_interest, 2),
"total_cost": round(total_paid, 2),
}
)
def compare_loan_scenarios(scenarios_json: str) -> str:
"""Compare multiple loan scenarios side-by-side.
Args:
scenarios_json: JSON string with array of {loan_id, amount, years} objects.
Returns:
A comparison table as JSON with all scenarios and their calculations.
"""
try:
scenarios = json.loads(scenarios_json)
except json.JSONDecodeError:
return json.dumps({"error": "Invalid JSON format for scenarios"})
loans_db = {
"startup_basic": {"name": "Startup Growth Loan", "rate": 6.5},
"business_expansion": {"name": "Business Expansion Credit", "rate": 5.2},
"working_capital": {"name": "Working Capital Loan", "rate": 7.1},
"equipment_finance": {"name": "Equipment Financing", "rate": 4.8},
}
comparison = []
for i, scenario in enumerate(scenarios):
loan_id = scenario.get("loan_id")
amount = scenario.get("amount", 0)
years = scenario.get("years", 5)
if loan_id not in loans_db:
comparison.append(
{
"scenario": i + 1,
"error": f"Unknown loan_id: {loan_id}",
}
)
continue
loan_info = loans_db[loan_id]
monthly_rate = loan_info["rate"] / 100 / 12
num_payments = years * 12
if monthly_rate == 0:
monthly_payment = amount / num_payments
else:
monthly_payment = amount * (
monthly_rate * (1 + monthly_rate) ** num_payments
) / ((1 + monthly_rate) ** num_payments - 1)
total_paid = monthly_payment * num_payments
total_interest = total_paid - amount
comparison.append(
{
"scenario": i + 1,
"loan_name": loan_info["name"],
"amount": amount,
"years": years,
"rate": loan_info["rate"],
"monthly_payment": round(monthly_payment, 2),
"total_interest": round(total_interest, 2),
"total_cost": round(total_paid, 2),
}
)
return json.dumps(comparison, indent=2)
root_agent = Agent(
name="root_agent",
model=Gemini(
model="gemini-flash-latest",
retry_options=types.HttpRetryOptions(attempts=3),
),
instruction="""You are an expert loan advisor helping customers find the right loan for their financial needs.
You have access to loan products, calculation tools, and comparison features.
When a user asks about loans:
1. First understand their needs (use case, amount, timeline)
2. Retrieve relevant loan products using get_loan_products
3. If they want calculations, use calculate_loan_payment or compare_loan_scenarios
4. Provide clear, actionable recommendations with pros/cons
5. Always explain terms, rates, and monthly costs clearly
Be proactive in asking clarifying questions about their business needs and financial situation.""",
tools=[get_loan_products, calculate_loan_payment, compare_loan_scenarios],
)
app = App(
root_agent=root_agent,
name="app",
)