Skip to content

pratim4dasude/Finance_AI_Assistant

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

38 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AI Financial Assistant Microservice

A multi-agent AI system that processes financial queries using safety checks, intent classification, and real-time response streaming.

Python FastAPI OpenAI SQLite License: MIT


About This Project

This is a financial AI microservice that processes user queries through a modular pipeline and streams real-time insights.

It works as a structured system with safety checks, intent classification, and agent-based routing, while maintaining session-aware memory.


What It Can Do

Capability Description
Portfolio Analysis Understand and evaluate your holdings
Market Research Analyze current market conditions
Risk Evaluation Quantify and explain portfolio risk
Recommendations Provide actionable investment insights
Financial Calculations Run computations on portfolio data

Architecture Overview

                ┌──────────────────────┐
                │      User Query      │
                └─────────┬────────────┘
                          │
                          ▼
                ┌──────────────────────┐
                │   FastAPI (/chat)    │
                └─────────┬────────────┘
                          │
                          ▼
                ┌──────────────────────┐
                │    Safety Guard      │  ← Policy validation layer
                └─────────┬────────────┘
                          │
              ┌───────────┴───────────┐
           blocked ❌            allowed ✅
                                      │
                                      ▼
                          ┌──────────────────────┐
                          │   Session Memory     │  ← SQLite-backed context
                          └─────────┬────────────┘
                                    │
                                    ▼
                          ┌──────────────────────┐
                          │  Intent Classifier   │  ← LLM-based routing signal
                          └─────────┬────────────┘
                                    │
                                    ▼
                          ┌──────────────────────┐
                          │    Agent Router      │
                          └──────────┬───────────┘
                                     │
              ┌──────────────────────┼──────────────────────┐
              │                      │                      │
              ▼                      ▼                      ▼
   ┌──────────────────┐   ┌──────────────────┐   ┌──────────────────┐
   │  Portfolio Health│   │  Market Research │   │  Risk Analysis   │
   │      Agent       │   │      Agent       │   │      Agent       │
   └──────────┬───────┘   └────────┬─────────┘   └───────┬──────────┘
              └────────────────────┼─────────────────────┘
                                   │
                                   ▼
                        ┌──────────────────────┐
                        │   LLM / Logic Layer  │
                        └─────────┬────────────┘
                                  │
                                  ▼
                        ┌──────────────────────┐
                        │   SSE Streaming Layer│  ← Real-time delivery
                        └─────────┬────────────┘
                                  │
                                  ▼
                              ┌────────┐
                              │  User  │
                              └────────┘

Execution Flow

Request → Safety Check → Memory Retrieval → Intent Classification
       → Agent Routing → Task Execution → LLM Response → SSE Stream

Key Components

1. Safety Guard

Validates every incoming query against financial safety policies before it enters the pipeline. Blocks harmful, speculative, or out-of-scope requests.

2. Session Memory (SQLite)

Maintains conversation context across requests using a lightweight SQLite store. Enables coherent multi-turn interactions without a heavy vector DB.

3. Intent Classifier

Uses an LLM to classify user intent into one of the supported financial domains — portfolio, market, risk, or general. Routes the query accordingly.

4. Agent Router

Maps classified intents to the correct domain agent. Designed for extensibility — adding a new agent requires minimal changes.

5. Domain Agents

Each agent handles a specific financial concern and composes a structured prompt for the LLM layer, enriched with user context and session history.

Agent Responsibility
portfolio_health.py Portfolio composition, concentration & health checks
market_reaserch.py Market conditions, sector trends & news analysis
risk_analysis.py Risk scoring, volatility & exposure evaluation
finance_calculator.py Financial metrics — returns, ratios, P&L
predictive_analysis.py Forecasting & predictive modelling
recommmedation.py Actionable investment recommendations
general_query.py Catch-all handler for general financial queries
stud_agent.py Research & study-oriented financial queries
support.py Fallback & support responses
llm_agent.py Core LLM interaction and prompt orchestration
base.py Abstract base class shared across all agents

Streaming (SSE)

Responses are streamed step-by-step so users see progress immediately.

event: status
data: {"stage": "safety_check"}

event: status
data: {"stage": "classification", "intent": "risk_analysis"}

event: status
data: {"stage": "agent_execution"}

event: response
data: {"content": "Your portfolio has a high concentration in tech...", "intent": "risk_analysis"}

event: done
data: {}

Getting Started

Prerequisites

  • Python 3.10+
  • An OpenAI API key

1. Clone the Repository

git clone https://github.com/2CentsCapital/valura-ai-ai-engineer-assignment-pratim4dasude.git
cd valura-ai-ai-engineer-assignment-pratim4dasude

2. Install Dependencies

pip install -r requirements.txt

3. Configure Environment Variables

# .env
OPENAI_API_KEY=your_openai_api_key
OPENAI_MODEL=gpt-4o-mini

4. Run the Server

# Option A: Module mode
python -m src.main

# Option B: Uvicorn with hot reload
uvicorn src.main:app --reload

The API will be available at http://localhost:8000.


API Reference

POST /chat

Send a financial query and receive a streamed response.

Request Body

{
  "session_id": "user_123",
  "query": "Analyze my portfolio risk",
  "user_context": {
    "portfolio": [
      {"symbol": "AAPL", "value": 5000},
      {"symbol": "TSLA", "value": 3000}
    ]
  }
}

Response — Server-Sent Events stream

event: status
data: {"stage": "classification"}

event: response
data: {"content": "...", "intent": "risk_analysis", "session_id": "user_123"}

event: done
data: {}

Database Debug Utility

A built-in CLI utility for inspecting and managing the SQLite session memory database directly , no external tools required.

python -m src.db_debug
Operation Description
View all sessions List every stored session and its metadata
Fetch by session ID Retrieve the full conversation context for a specific session_id
Delete a session Remove a single session and its associated memory
Clear entire database Wipe all sessions — useful for a clean test slate

Note: This utility operates directly on valura_memory.db. Back up the file before running destructive operations in a shared environment.


Testing

pytest

Tests cover safety guard logic, intent classification accuracy, agent routing, and SSE stream integrity.


Design Principles

Principle Implementation
Modular Architecture Agents are fully isolated — easy to add, swap, or test
Safety First Every request passes through a policy guard before processing
LLM + Rule Hybrid Combines LLM reasoning with deterministic safety and routing rules
Streaming UX SSE ensures users receive real-time feedback at every pipeline stage
Session-Aware SQLite memory enables context-rich, multi-turn conversations

License

This project is licensed under the MIT License.


About

AI-powered financial assistant microservice with multi-agent routing, safety checks, portfolio insights, and real-time streaming responses.

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages