CoolFace
Apppublic

Misbah17311/financial-intelligence-agent

sourceHugging Faceupdated 6mo agoView on Hugging Face
1likes
App README

Financial Intelligence Agent

A production-grade multi-agent AI system for financial Q&A. Combines structured SQL data (2,100 company records) with hybrid semantic search over 110K+ news articles, protected by a layered guardrail system.

Built with LangGraph, FastAPI, ChromaDB, DuckDB, and a custom HTML/CSS/JS frontend.


Architecture Diagram

mermaid
flowchart TB
    subgraph Frontend["Frontend ยท HTML/CSS/JS"]
        UI[Chat Interface]
    end

    subgraph API["FastAPI Backend"]
        direction TB
        EP["/api/query endpoint"]

        subgraph Guardrails["๐Ÿ›ก๏ธ Input Guardrails"]
            G1[Input Length Check]
            G2[PII Detection]
            G3[SQL Injection Scanner]
            G4[Prompt Injection Detector]
            G5[Topic Relevance Filter]
        end

        subgraph AgentPipeline["๐Ÿค– LangGraph Agent Pipeline"]
            Planner["๐Ÿง  Planner Agent"]
            Retriever["๐Ÿ” Retriever Agent"]
            Analyst["๐Ÿ“Š Analyst Agent"]
            Critic["โœ… Critic Agent"]
        end

        subgraph OutputGuardrails["๐Ÿ›ก๏ธ Output Guardrails"]
            OG1[Response Validation]
        end
    end

    subgraph DataLayer["Data Layer"]
        DuckDB["๐Ÿ—„๏ธ DuckDB ยท 2,100 records ยท SQL"]
        ChromaDB["๐Ÿ”ฎ ChromaDB ยท 110K chunks ยท Vector"]
        BM25["๐Ÿ“ BM25 Index ยท 110K chunks ยท Keyword"]
    end

    subgraph Retrieval["Hybrid Retrieval"]
        VS[Vector Search]
        KS[Keyword Search]
        RRF[Reciprocal Rank Fusion]
        RE[Cross-Encoder Reranker]
    end

    subgraph LLM["LLM Provider ยท Swappable"]
        OpenAI["OpenAI GPT-4o-mini"]
        Anthropic["Claude Sonnet"]
        Groq["Llama 3.3 70B"]
    end

    UI -->|POST /api/query| EP
    EP --> G1 --> G2 --> G3 --> G4 --> G5
    G5 -->|All checks passed| Planner
    G5 -->|Blocked| UI

    Planner -->|Execution plan| Retriever
    Retriever -->|SQL queries| DuckDB
    Retriever -->|Search queries| Retrieval
    ChromaDB --> VS
    BM25 --> KS
    VS --> RRF
    KS --> RRF
    RRF --> RE
    RE -->|Top results| Retriever
    Retriever -->|Retrieved data| Analyst
    Analyst -->|Draft answer| Critic
    Critic -->|APPROVED| OG1
    Critic -->|REVISE| Analyst
    OG1 --> UI

    Planner -.->|LLM calls| LLM
    Analyst -.->|LLM calls| LLM
    Critic -.->|LLM calls| LLM

Guardrails โ€” Safety Mechanisms

The system implements a layered defense with 6 guardrails (5 input + 1 output) that run on every query. Blocked queries never reach the LLM โ€” saving cost and preventing abuse.

#GuardrailLayerWhat It CatchesExample Trigger
1Input LengthInputPrompt stuffing, absurdly long inputsQueries > 2,000 characters
2PII DetectionInputSSNs, credit card numbers, emails, phone numbersMy SSN is 123-45-6789...
3SQL InjectionInputDROP TABLE, UNION SELECT, comment injection, DuckDB escapes'; DROP TABLE companies; --
4Prompt InjectionInputJailbreaks, instruction override, system prompt extractionIgnore all previous instructions...
5Topic RelevanceInputOff-topic queries (recipes, medical, legal, creative writing)Write me a poem about sunflowers
6Response ValidationOutputLeaked system prompts, generic AI refusals in financial contextCatches hijacked LLM behavior

How Guardrails Work

  1. 1.Sequential short-circuit: Input checks run cheapest-first and stop on the first failure โ€” no LLM calls wasted
  2. 2.Visual feedback: The UI displays guardrail status as colored pills (green โœ“ = passed, red โœ— = blocked) on every response
  3. 3.SQL layer protection: DuckDB queries are additionally restricted to SELECT/WITH/EXPLAIN only โ€” no DDL/DML ever reaches the database
  4. 4.Zero-cost blocking: Rejected queries return instantly with the guardrail name and a user-friendly explanation

Quick Start

Prerequisites

  • โ€”Python 3.10+
  • โ€”An OpenAI API key (or Anthropic/Groq โ€” see Swapping LLMs)

1. Clone & Setup Environment

bash
git clone <repo-url>
cd financial-intelligence-agent

python3 -m venv venv
source venv/bin/activate   # Windows: venv\Scripts\activate
pip install -r requirements.txt

2. Configure API Key

bash
cp .env.example .env
# Edit .env and add your OPENAI_API_KEY

3. Run Data Ingestion

bash
python setup.py

Downloads ~110K financial news articles from HuggingFace, generates company fundamentals for 105 companies (7 sectors, 20 quarters), and builds all indexes (DuckDB, ChromaDB, BM25). Takes ~15โ€“20 min on first run.

4. Start the Application

bash
# FastAPI (recommended โ€” full-featured UI with guardrails)
uvicorn src.api:app --host 0.0.0.0 --port 8000

# Or Streamlit (simpler alternative)
streamlit run src/ui/app.py

Open http://localhost:8000 in your browser.


Swapping LLMs

Change the provider in .env โ€” no code changes needed:

env
LLM_PROVIDER=anthropic
ANTHROPIC_API_KEY=sk-ant-...
LLM_MODEL=                     # leave blank for defaults
ProviderDefault ModelNotes
OpenAIgpt-4o-miniBest speed/quality/cost balance
Anthropicclaude-sonnet-4-20250514Higher quality, slower
Groqllama-3.3-70b-versatileFree tier available

Project Structure

โ”œโ”€โ”€ frontend/                     # production web UI
โ”‚   โ”œโ”€โ”€ index.html
โ”‚   โ””โ”€โ”€ static/
โ”‚       โ”œโ”€โ”€ style.css             # dark theme, responsive
โ”‚       โ””โ”€โ”€ app.js                # chat logic, guardrail display
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ api.py                    # FastAPI backend + endpoints
โ”‚   โ”œโ”€โ”€ config.py                 # central config (reads .env)
โ”‚   โ”œโ”€โ”€ llm.py                    # LLM factory (provider swapping)
โ”‚   โ”œโ”€โ”€ guardrails.py             # 6-layer safety system
โ”‚   โ”œโ”€โ”€ logger.py                 # structured logging
โ”‚   โ”œโ”€โ”€ data_platform/
โ”‚   โ”‚   โ”œโ”€โ”€ ingest.py             # data download + processing
โ”‚   โ”‚   โ”œโ”€โ”€ duckdb_store.py       # SQL database for financials
โ”‚   โ”‚   โ”œโ”€โ”€ chroma_store.py       # vector store for embeddings
โ”‚   โ”‚   โ””โ”€โ”€ bm25_store.py         # BM25 keyword index
โ”‚   โ”œโ”€โ”€ retrieval/
โ”‚   โ”‚   โ””โ”€โ”€ hybrid.py             # vector + BM25 โ†’ RRF โ†’ reranking
โ”‚   โ”œโ”€โ”€ tools/
โ”‚   โ”‚   โ””โ”€โ”€ agent_tools.py        # LangChain tools
โ”‚   โ”œโ”€โ”€ agents/
โ”‚   โ”‚   โ””โ”€โ”€ graph.py              # multi-agent LangGraph pipeline
โ”‚   โ””โ”€โ”€ ui/
โ”‚       โ””โ”€โ”€ app.py                # Streamlit alternative UI
โ”œโ”€โ”€ evaluation/
โ”‚   โ”œโ”€โ”€ evaluate.py               # automated eval (LLM-as-judge)
โ”‚   โ”œโ”€โ”€ test_queries.json         # 20 test queries
โ”‚   โ””โ”€โ”€ results/                  # evaluation output
โ”œโ”€โ”€ data/                         # generated by setup.py
โ”œโ”€โ”€ setup.py                      # one-command data pipeline
โ”œโ”€โ”€ requirements.txt
โ”œโ”€โ”€ .env.example
โ”œโ”€โ”€ ARCHITECTURE.md
โ””โ”€โ”€ README.md

Data Sources

DatasetSourceRecordsPurpose
Financial news4 HuggingFace datasets~110,000 articlesSemantic search, sentiment, analyst opinions
Company fundamentalsGenerated (realistic distributions)2,100 rowsRevenue, profit, assets, market cap by quarter

Structured data: 105 companies across 7 sectors (Technology, Healthcare, Finance, Energy, Consumer, Industrial, Communication) over 20 quarters (Q1 2020 โ€“ Q4 2024).

Unstructured data: ashraq/financial-news-articles, oliverwang15/news_with_gpt_instructions, twitter-financial-news-sentiment, nickmuchi/financial-classification.


Evaluation Results

20 curated queries tested across SQL lookups, comparisons, aggregations, trend analysis, sentiment, and multi-hop reasoning:

MetricScore
Response Rate100%
Tool Routing Accuracy100%
Overall Quality (LLM-as-judge)4.74 / 5.0
Relevance5.0 / 5.0
Accuracy4.6 / 5.0
Completeness4.5 / 5.0
Clarity4.85 / 5.0
Median Latency10.7s
bash
python evaluation/evaluate.py

Key Design Decisions

  • โ€”Hybrid retrieval: Dense embeddings + BM25 merged via Reciprocal Rank Fusion, re-scored by a cross-encoder. Catches both semantic and exact-match relevance.
  • โ€”Multi-agent pipeline: Planner โ†’ Retriever โ†’ Analyst โ†’ Critic. The Critic catches hallucinations before answers reach the user.
  • โ€”Guardrails-first: Input validation runs before any LLM call. Blocked queries cost zero tokens.
  • โ€”Local embeddings: all-MiniLM-L6-v2 on CPU โ€” no API key needed for the embedding pipeline.
  • โ€”DuckDB: Embedded SQL, no server required, read-only at runtime for safety.

Demo Video

Link to demo video

The demo covers:

  1. 1.Normal flow: SQL queries, semantic search, complex multi-step analysis
  2. 2.Guardrail activation: SQL injection, prompt injection, PII detection, off-topic blocking โ€” all caught with visual feedback