https://github.com/sathviknayak123/wealthpilot
A Multi-agent system for personal finance intelligence. Built with real A2A protocol for agent communication, MCP for tool access, and LangGraph agents for autonomous reasoning.
https://github.com/sathviknayak123/wealthpilot
a2a-protocol agentic-ai fastapi langchain langfuse langgraph mcp multi-agent-systems postgres-database redis-cache
Last synced: 6 days ago
JSON representation
A Multi-agent system for personal finance intelligence. Built with real A2A protocol for agent communication, MCP for tool access, and LangGraph agents for autonomous reasoning.
- Host: GitHub
- URL: https://github.com/sathviknayak123/wealthpilot
- Owner: SathvikNayak123
- Created: 2026-03-25T15:13:47.000Z (2 months ago)
- Default Branch: main
- Last Pushed: 2026-04-29T18:45:25.000Z (about 1 month ago)
- Last Synced: 2026-04-29T20:29:38.626Z (about 1 month ago)
- Topics: a2a-protocol, agentic-ai, fastapi, langchain, langfuse, langgraph, mcp, multi-agent-systems, postgres-database, redis-cache
- Language: Python
- Homepage:
- Size: 924 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# FinAgent — Multi-Agent Finance Intelligence for Indian Retail Investors
A multi-agent system for personal finance intelligence, targeted at Indian retail investors. Built on the A2A protocol (agent-to-agent communication), MCP (Model Context Protocol) for tool access, and LangChain ReAct agents for autonomous reasoning.
## FlowChart

## What It Does
- **Answers complex multi-agent queries in parallel** — "Show my portfolio value, tax liability, AND latest stock news" → delegates to Portfolio, Tax, and News agents simultaneously
- **Handles live financial data** — real-time NSE/BSE stock prices, forex rates (USD/INR), Alpha Vantage fundamentals
- **Calculates India-specific taxes** — STCG/LTCG, tax-loss harvesting, FY2024-25 rules
- **Requires human approval for payments** — HITL (human-in-the-loop) pauses transaction agent and waits for explicit user consent before processing
- **Combines reasoning + data + tools** — each agent runs its own ReAct loop with MCP tools
- **Routes queries to the right cost tier** — greedy rule-based → Gemini 2.5 Flash → Gemini 2.5 Flash (preview) based on complexity
- **Persistent multi-turn memory** — user profiles, conversation archives, portfolio snapshots, RAG-ready embeddings
- **Observability at scale** — Langfuse traces every LLM call; circuit breakers prevent cascading failures
- **Exports reports** — generates Google Sheets, charts (26+ types), and data visualizations
## Core Features
### Agent-to-Agent Communication (A2A Protocol)
- Agents discover each other via **AgentCards** — self-describing service endpoints
- **JSON-RPC 2.0 + SSE** for streaming results
- Full task lifecycle: `submitted` → `working` → `completed` / `input_required` / `error`
- HITL integration: agents can pause and request user input before proceeding
### Reasoning & Planning
- **ReAct agents** — structured Thought→Action→Observation loops via LangChain
- **Pre-flight execution planning** — `create_plan` tool generates an inspectable DAG before the agent runs
- **Parallel execution** — independent sub-tasks run simultaneously
- **Reflection step** — orchestrator evaluates completeness before responding
### Tool Access (MCP Servers)
- **NSE/BSE real-time data** — community `nse-bse-mcp` server (Streamable HTTP)
- **Alpha Vantage global market data** — stock quotes, forex, company fundamentals
- **Tavily web search** — financial news, sentiment analysis
- **Razorpay payments** — payment links, bill payments, refunds (requires HITL approval)
- **Google Sheets export** — portfolio reports, data visualization
- **AntV charts** — 26+ chart types (pie, line, bar, treemap, radar, scatter, sankey, etc.)
### Safety & Reliability
- **Input guardrails** — regex heuristics + LLM classifier to catch prompt injection, off-topic queries, PII
- **Output guardrails** — cross-check financial numbers against regex patterns
- **Circuit breakers** — per-agent failure tracking; opens after 3 failures in 120s, stays open 30s
- **Partial responses** — returns results from available agents when some are down
- **Context budget allocator** — prevents LLM context overflow on long sessions
- **Rate limiting + token authentication** — HITL resume endpoints are protected
### Observability & Evaluation
- **Langfuse integration** — traces every LLM call with token counts, latency, cost
- **Structured logging** — `structlog` JSON output for all events
- **Trajectory logging** — captures full decision chain (model tier, agents, tools, tokens) for offline analysis and benchmarking
- **Per-agent tracing** — `trace_agent_call` context manager with span lifecycle management
### Persistent Memory & RAG
- **User profiles** — persistent across sessions
- **Conversation archives** — periodically saved for context recovery
- **Portfolio snapshots** — historical holdings for trend analysis
- **Vector embeddings** — enables similarity search for RAG (Retrieval-Augmented Generation)
- **Redis session memory** — short-term conversation summaries
- **PostgreSQL long-term storage** — user data, conversation history, benchmark results
### Caching
- **Prompt-level caching** — Redis-backed cache for static content (system prompts, instrument schemas, tax rules)
- **Node-level result caching** — LangGraph in-memory cache for identical sub-queries (5-min TTL)
- **Provider-native caching** — cache_control hints for Anthropic and OpenRouter (Gemini) prompt caching
## Agents
| Agent | Capabilities | MCP Server(s) |
|-------|--------------|---------------|
| **Orchestrator** | Execution planning, multi-agent delegation, result synthesis | — |
| **Portfolio** | Live stock prices, P&L calculation, sector exposure, holdings analysis | NSE/BSE (Streamable HTTP `:3100`) |
| **Tax** | STCG/LTCG calculation, tax-loss harvesting, India FY2024-25 rules | — (custom tools) |
| **News** | Financial news search, sentiment analysis, market alerts | Tavily (Stdio via npx) |
| **Transaction** | Payment links, bill payments, refunds, UPI/bank transfers | Razorpay (Stdio via npx + mcp-remote) |
| **Market Data** | Global stock quotes, forex (USD/INR), company fundamentals, earnings | Alpha Vantage (Stdio via uvx) |
| **Export** | Spreadsheet export, portfolio reports, batch data downloads | Google Sheets (Stdio via uvx) |
| **Chart** | 26+ chart types: pie, line, bar, treemap, radar, scatter, area, sankey, network, dual-axes | AntV Chart (Stdio via npx) |
| **Debate** | Bull vs Bear adversarial debate; Judge synthesizes recommendation | — (pure LLM) |
| **Simulation** | Monte Carlo GBM: 1000 paths, P10/P50/P90 percentiles, 95% VaR, prob-of-loss | Alpha Vantage (Stdio via uvx) + NumPy |
### MCP Server Details
| Server | Package | Transport | Auth | Host |
|--------|---------|-----------|------|------|
| NSE/BSE | `nse-bse-mcp` | Streamable HTTP | None (public data) | `localhost:3100` |
| AntV Chart | `@antv/mcp-server-chart` | Stdio (npx) | None | Spawned on startup |
| Tavily | `tavily-mcp` | Stdio (npx) | `TAVILY_API_KEY` | Spawned on startup |
| Razorpay | `mcp-remote` + mcp.razorpay.com | Stdio (npx) | Base64(KEY_ID:KEY_SECRET) | Spawned on startup |
| Alpha Vantage | `av-mcp` | Stdio (uvx) | `ALPHA_VANTAGE_API_KEY` | Spawned on startup |
| Google Sheets | `mcp-google-sheets` | Stdio (uvx) | Service account JSON | Spawned on startup |
All stdio MCP servers are spawned automatically by the agent on startup via `langchain-mcp-adapters`.
## Design Decisions
| Concern | Decision | Why |
|---------|----------|-----|
| **Agent communication** | A2A protocol (JSON-RPC 2.0 + SSE) with AgentCard discovery | Decouples agents from orchestrator; each agent is a standalone microservice; easy to add/remove agents without API changes |
| **Tool access** | `langchain-mcp-adapters` → `MultiServerMCPClient` | Standardized tool interface; leverage pre-built MCP servers from community and vendors; no custom API wrappers |
| **Reasoning** | LangChain ReAct with structured responses | Thought→Action→Observation loops are transparent and debuggable; structured output format enables downstream validation |
| **Planning** | Pre-flight DAG execution planner before ReAct | One LLM call to produce an inspectable plan; reveals agent dependencies upfront; prevents redundant sub-task delegation |
| **Orchestration** | Sequential agent chains (dependency-aware) + parallel waves | Respects data dependencies while maximizing parallelism for independent tasks |
| **Cost routing** | 3-tier complexity-based router | Tier 1 (no LLM) for greetings; Tier 2 (fast LLM) for simple queries; Tier 3 (capable LLM) for multi-agent; rule-based first to avoid LLM cost |
| **Safety** | 2-layer input guardrails + 1-layer output | Regex heuristics are fast and catch obvious attacks; LLM classifier handles nuanced cases; output cross-check prevents hallucinated numbers |
| **HITL** | A2A `input_required` task state | Transaction agent pauses; API gateway polls for user approval; circuit breaker prevents duplicate payment attempts |
| **Context management** | Priority-based budget allocator with conversation summarizer | Prevents context overflow on long sessions; prioritizes recent and high-value context over old turns |
| **Caching** | Multi-level: node-level (LangGraph) + prompt-level (Redis) + provider-native (Anthropic/Gemini) | Node caching catches identical sub-queries; Redis caching amortizes serialization; provider caching reduces input tokens for repeated queries |
| **Circuit breakers** | Per-agent failure tracking with exponential backoff | Prevents cascading failures when a downstream agent is slow/down; fallback to partial responses improves user experience |
| **Observability** | Langfuse LLM traces + trajectory logging | Langfuse captures every LLM call with tokens/cost/latency; trajectories enable offline analysis, benchmark scoring, and root-cause debugging |
| **Persistent memory** | PostgreSQL (long-term) + Redis (session-level) | Redis for fast session state; PostgreSQL for durable user profiles and conversation archives; pgvector for RAG embeddings |
| **Model selection** | Gemini 2.5 Flash (Tier 2/3) | Low cost, low latency, reasoning capabilities; preview version for complex queries |
## Quick Start
### 1. Environment Setup
```bash
cp .env.example .env
# Fill in your API keys in .env
```
Required keys:
- `OPENROUTER_API_KEY` — LLM provider
Optional keys (enable additional agents):
- `TAVILY_API_KEY` — News search
- `RAZORPAY_KEY_ID` + `RAZORPAY_KEY_SECRET` — Payment processing
- `ALPHA_VANTAGE_API_KEY` — Global market data
- `GOOGLE_SHEETS_SERVICE_ACCOUNT_PATH` + `GOOGLE_SHEETS_DRIVE_FOLDER_ID` — Spreadsheet export
### 2. Start Infrastructure (Docker)
```bash
# Core infrastructure (Postgres + Redis)
docker compose up -d
# Core + Langfuse observability dashboard (:3001)
docker compose --profile observability up -d
```
### 3. Start the NSE-BSE MCP Server
```bash
# Install once
npm install -g nse-bse-mcp
# Run on port 3100 (keep this terminal open)
PORT=3100 npx nse-bse-mcp
```
### 4. Start Agents (each in its own terminal)
```bash
pip install -e ".[dev]"
python -m agents.portfolio # NSE/BSE MCP
python -m agents.tax # custom tax tools
python -m agents.news # Tavily MCP
python -m agents.orchestrator_server # A2A orchestration
```
### 5. Start the API Gateway and Frontend
```bash
# Backend
uvicorn api.main:app --reload --port 8000
# Frontend
cd frontend && npm install && npm run dev
```
### 6. Verify
```bash
# Check any agent's A2A card
curl http://localhost:10001/.well-known/agent.json | jq .
# Check gateway health
curl http://localhost:8000/health | jq .
```
## API Endpoints
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/chat` | POST | SSE streaming chat (forwards to orchestrator via A2A) |
| `/ws/chat/{session_id}` | WebSocket | Real-time bidirectional chat |
| `/resume/{session_id}` | POST | Resume after HITL approval |
| `/health` | GET | Health check (pings orchestrator + Redis) |
### Example: Chat Request
```bash
curl -N -X POST http://localhost:8000/chat \
-H "Content-Type: application/json" \
-d '{
"message": "What is my portfolio value and tax liability?",
"user_id": "user-1",
"holdings": [
{"symbol": "RELIANCE", "quantity": 10, "avg_buy_price": 2400.0},
{"symbol": "TCS", "quantity": 5, "avg_buy_price": 3500.0}
]
}'
```
### Request Flow
1. API gateway receives the request and forwards it to the Orchestrator via A2A `message/stream`
2. Orchestrator calls `create_plan` — produces a DAG of required agents and their dependencies
3. Orchestrator's ReAct loop delegates to specialist agents in dependency order (parallel where possible)
4. Each specialist agent runs its own ReAct loop with MCP tools to complete its sub-task
5. Orchestrator calls `reflect` — evaluates whether all sub-tasks were completed satisfactorily
6. Final response streams back to the client via SSE
## License
Private — All rights reserved.