An intelligent agentic AI financial advisor built with LangGraph, FastAPI, and Streamlit. GAgent autonomously selects and uses tools to analyze stocks, detect fraud, and perform complex financial calculations through natural language conversations.
- Docker and Docker Compose installed
- Google Gemini API key (Using $300 free starter credits)
-
Clone the repository
git clone https://github.com/ssgrummons/financial-agent-demo cd gagent-financial-advisor -
Configure environment variables
Create a
.envfile in the project root:GOOGLE_API_KEY=your_gemini_api_key_here TEMPERATURE=0.8 HOST=localhost PORT=8001 RELOAD=true LOG_LEVEL=DEBUG STREAMLIT_PORT=8501 API_BASE_URL=http://backend:8000 CORS_ORIGINS=http://localhost:8501,http://localhost:3000
-
Launch the application To pull images from DockerHub:
docker-compose up
Or to rebuild images:
docker-compose up --build
-
Access the application
Navigate to: http://localhost:8501
That's it! The application will automatically pull pre-built images from Docker Hub and start both frontend and backend services.
βββββββββββββββββββ HTTP/WebSocket ββββββββββββββββββββ
β Streamlit β -------------------- β FastAPI β
β Frontend β β Backend β
β (Port 8501) β β (Port 8000) β
βββββββββββββββββββ ββββββββββββββββββββ
β
β
ββββββββββββββββββββ
β LangGraph β
β Agent Core β
ββββββββββββββββββββ
β
ββββββββββββββββΌβββββββββββββββ
β β β
ββββββββββββ ββββββββββββββββ ββββββββββββ
β Stock β β Fraud β β Python β
β Data β β Detection β β REPL β
β Tool β β Tool β β Tool β
ββββββββββββ ββββββββββββββββ ββββββββββββ
- User Interface: Streamlit frontend provides conversational chat interface
- API Gateway: FastAPI backend handles requests and orchestrates agent execution
- Agent Core: LangGraph manages conversation state and tool orchestration
- Tool Selection: AI agent autonomously decides which tools to use based on user queries
- Tool Execution: Agent executes selected tools and synthesizes responses
- Streaming Response: Results stream back to user through WebSocket connection
-
Frontend Container:
samuelgrummons/gagent-frontend:latest- Streamlit application
- Multi-architecture support (ARM64/AMD64)
- Health checks and graceful startup
-
Backend Container:
samuelgrummons/gagent-backend:latest- FastAPI application with LangGraph integration
- Multi-architecture support (ARM64/AMD64)
- Health checks and dependency management
GAgent uses LangGraph as its core agentic framework, providing:
- Autonomous Tool Selection: Agent analyzes user queries and automatically selects appropriate tools
- Conversation Memory: Maintains context across conversation turns using LangGraph's built-in memory system
- Streaming Execution: Real-time response streaming from agent to frontend
- Error Handling: Graceful fallbacks and error recovery
The agent has access to four primary tools:
@tool
def get_stock_data(symbol: str, period: str = "1mo", info_type: str = "all") -> str:- Purpose: Fetch real-time and historical stock data
- Integration: Uses
yfinancelibrary for free Yahoo Finance API access - Capabilities: Price data, company info, historical trends
@tool
def compare_stocks(symbols: str, period: str = "3mo") -> str:- Purpose: Multi-stock analysis and comparison
- Capabilities: Performance comparison, relative analysis
- Purpose: Execute Python code for complex financial calculations
- Integration: LangChain's experimental Python REPL
- Capabilities: Custom calculations, data analysis, plotting
- Use Cases: Sharpe ratios, portfolio optimization, statistical analysis
@tool
def detect_fraud_statistical(transaction_description: str, user_id: str = "default") -> str:- Purpose: Anomaly detection for suspicious transactions
- Method: Statistical analysis against user spending baselines
- Features: Z-score analysis, pattern recognition, risk scoring
GAgent implements a ReAct-style reasoning pattern:
- Observation: Analyzes user input and conversation context
- Thought: Determines what information or calculations are needed
- Action: Selects and executes appropriate tools
- Reflection: Synthesizes tool outputs into coherent response
- Response: Delivers natural language answer to user
Example agent reasoning flow:
User: "Compare Apple and Microsoft stock performance and calculate their Sharpe ratios"
Agent Reasoning:
1. Needs stock data for AAPL and MSFT β use get_stock_data tool
2. Needs comparison analysis β use compare_stocks tool
3. Needs Sharpe ratio calculation β use Python REPL tool
4. Synthesize results into comprehensive response
- Primary Model: Google Gemini 2.5 Pro
- Temperature: 0.8 for balanced creativity and accuracy
- Provider Support: Extensible model factory supports multiple LLM providers
- Configuration: Models and providers configurable via
config.yaml
- Session State: LangGraph's built-in conversation memory
- Context Retention: Maintains conversation history and user preferences
- Scalability: In-memory for demo; production would use persistent storage
- Graph Testing: PyTest coverage for LangGraph workflows
- API Testing: FastAPI endpoint contract testing
- Session Testing: Session management and state persistence testing
GAgent implements several key safeguards to address financial AI ethics and regulatory requirements:
- Disclaimer Protocol: All financial responses begin with "This is educational information and not personalized financial advice"
- Professional Referrals: Users are directed to consult licensed financial professionals for important decisions
- Performance Disclaimers: Clear messaging that "past performance doesn't guarantee future results"
- Conservative Guidance: System emphasizes diversification, risk management, and long-term thinking over speculative recommendations
- No Autonomous Actions: Fraud detection provides risk assessments only - no automatic blocking or account actions
- Explainable Decisions: Statistical analysis provides clear reasoning (z-scores, risk factors, thresholds)
- Bias Acknowledgment: Current synthetic baseline data may introduce bias against:
- Night shift workers (midnight transactions flagged)
- International users (foreign transaction patterns)
- Atypical spending patterns
- Production Mitigation: Real systems would require bias testing, diverse training data, and human oversight
- Model-Level Safety: Leverages Google Gemini's built-in safety and content filtering
- Input Validation: Relies on LLM provider's adversarial input protection
- Upgrade Path: Architecture supports adding dedicated input safety nodes for production deployment
- No Personal Data Storage: Demo uses synthetic user baselines only
- Environment Variable Security: API keys and secrets properly externalized
- Container Isolation: Docker architecture provides service-level isolation
- Production Requirements: Would need encryption, audit logging, and compliance monitoring
- Tool Usage Disclosure: Agent explains which tools it's using and why
- Decision Reasoning: Financial calculations show methodology and assumptions
- Limitation Acknowledgment: Clear about what the system can and cannot do
- Educational Focus: Explains financial concepts rather than just providing answers
- Context Provision: Tool results include background information and caveats
- Professional Guidance: Consistently directs users to qualified advisors for major decisions
- Conservative Defaults: Avoids speculative or high-risk recommendations
- Uncertainty Communication: Acknowledges when information is incomplete or assumptions are made
- Graduated Responses: Risk assessments provide nuanced levels rather than binary decisions
For enterprise deployment, additional safeguards would include:
Regulatory Compliance:
- SEC/FINRA registration considerations for investment advice
- SOX compliance for financial data handling
- PCI DSS compliance for payment-related fraud detection
- GDPR/CCPA compliance for personal financial data
Technical Safeguards:
- Comprehensive bias testing and fairness metrics
- Human-in-the-loop workflows for high-risk decisions
- Audit logging and decision traceability
- Input sanitization and adversarial prompt detection
- Rate limiting to prevent market manipulation
Governance Framework:
- Model governance and validation processes
- Regular bias and fairness audits
- Incident response procedures
- Compliance monitoring and reporting
When calculating financial metrics like the Sharpe ratio, GAgent may request clarification on assumptions:
Example Exchange:
User: "Calculate the Sharpe ratio for Google using 1-year historical data"
Agent: "To calculate the Sharpe ratio for Google (GOOGL), I'll need a risk-free rate..."
Recommended Response: "Use 4.5% as the risk-free rate (current 10-year Treasury rate)"
Why This Happens: Your agent demonstrates proper financial domain knowledge by recognizing that Sharpe ratios require a risk-free rate benchmark. This is actually a positive indicator of the system's financial sophistication.
Future Enhancement: Could automatically fetch current Treasury rates via additional API integration.
"What's Apple's current stock price?"
"Compare Tesla and Ford stock performance over the last 6 months"
"Calculate the Sharpe ratio for Google using 1-year historical data"
"Detect if this transaction is suspicious: Transfer of $5,000 to an unknown account at midnight"
"Analyze this transaction: Wire transfer of $15,000 to offshore account at 3 AM"
"Is this suspicious: Payment of $45 to Starbucks at 10 AM"
"Review Apple's stock trend and calculate its volatility"
"Compare the risk-adjusted returns of Apple, Google, and Microsoft"
"Analyze my portfolio's diversification if I hold 60% Apple, 30% Google, 10% bonds"
- Current State: No authentication implemented for demo simplicity
- Production Consideration: Would require comprehensive auth system
- Related Work: See Enterprise AI Agents with Least Privilege for production security patterns
- Current State: Uses synthetic user baselines for statistical analysis
- Production Consideration: Would require access to real transactional data with proper authorization
- Trade-off: Demonstrates methodology without sensitive data requirements
- Stock Data: Chose
yfinancefor free Yahoo Finance access - Limitation: Subject to rate limits and data delays
- Alternative: Production systems would use premium APIs (Bloomberg, Alpha Vantage Pro)
- Choice: Google Gemini 2.5 Pro using initial credits
- Trade-off: High cost model for impressive results
- Flexibility: Model factory supports easy switching to other providers
- Current State: LangGraph in-memory session management
- Production Need: Database-backed session storage for scalability
- Trade-off: Simplicity for demo vs. production persistence requirements
- Current: Docker Compose for local deployment
- Production: Would require Kubernetes, load balancing, and service mesh
- Benefit: Easy local setup and testing
- Current: PythonREPLTool for complex calculation
- Production: Modal or AWS Lambda with container images
- Trade-off: PythonREPLTool was easy to implement and free but experimental
Run the test suite:
# Backend tests
cd backend
pytest tests/
# Test coverage includes:
# - LangGraph workflow execution
# - API endpoint contracts
# - Session management
# - Tool integration- Implement tool to
FinanceToolsclass insrc/components/tools.py - Add to
FinanceTools.load_tools()method - Update tests in
tests/
Edit src/config/config.yaml to add new model providers or adjust parameters.
All configuration through .env file - no hardcoded secrets.
For production deployment, consider:
- Authentication: Implement OAuth2/JWT authentication
- Database: Persistent session and user data storage
- Monitoring: Application performance monitoring and logging
- Rate Limiting: API rate limiting and quota management
- Security: Input validation, SQL injection prevention
- Scalability: Horizontal scaling with Kubernetes
- Data Privacy: Compliance with financial data regulations
Built with β€οΈ using LangGraph, FastAPI, and Streamlit
Looking up stocks and running analysis using PythonREPLTool:

