A simplified, production-ready AI agent system for financial market research using OpenAI, Qdrant Cloud, and CrewAI with FastAPI endpoints.
This project demonstrates a practical implementation of an AI agent system with:
- OpenAI LLM Integration: Direct integration with GPT-4 for text generation and embeddings
- Qdrant Cloud Vector Database: Semantic search and RAG (Retrieval-Augmented Generation)
- CrewAI Agents: Multi-agent orchestration for financial research
- FastAPI REST API: Production-ready HTTP endpoints
- Comprehensive Testing Guide: Detailed instructions for testing all AI safety scenarios
- LLM Client (
llm.py): OpenAI integration for text generation and embeddings - Vector Store (
vector_db.py): Qdrant Cloud integration for semantic search - RAG System (
rag.py): Retrieval-Augmented Generation for grounded responses - Agents (
agents.py): CrewAI agents for market analysis, news research, and report writing - FastAPI App (
main.py): REST API with 9 endpoints
| Endpoint | Method | Purpose |
|---|---|---|
/health |
GET | Health check |
/rag/ingest |
POST | Ingest documents into RAG system |
/rag/search |
POST | Semantic search in vector store |
/rag/generate |
POST | Generate response with RAG grounding |
/rag/documents/{doc_id} |
DELETE | Delete document from RAG |
/llm/generate |
POST | Generate text using OpenAI |
/llm/embedding |
POST | Generate embeddings |
/research/workflow |
POST | Run complete research workflow |
/research/market-analysis |
POST | Perform market analysis |
/research/news |
POST | Research news using RAG |
- Python 3.10+
- OpenAI API key (get one here)
- Qdrant Cloud account (create one here)
# Clone/extract project
cd finagent-simple
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -e .
# Create .env file
cp .env.example .env
# Edit .env with your credentials
nano .env # or use your preferred editorEdit .env with your credentials:
# OpenAI Configuration
OPENAI_API_KEY=sk-your-api-key-here
OPENAI_MODEL=gpt-4
# Qdrant Cloud Configuration
QDRANT_URL=https://your-instance.qdrant.io
QDRANT_API_KEY=your-qdrant-api-key
# FastAPI Configuration
API_HOST=0.0.0.0
API_PORT=8000
API_DEBUG=truepython main.pyServer will be available at http://localhost:8000
API Documentation: Visit http://localhost:8000/docs for interactive Swagger UI
curl -X POST "http://localhost:8000/llm/generate" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Analyze the current tech sector",
"system_prompt": "You are a financial analyst",
"temperature": 0.7
}'curl -X POST "http://localhost:8000/llm/embedding" \
-H "Content-Type: application/json" \
-d '{
"text": "Apple stock analysis"
}'curl -X POST "http://localhost:8000/rag/ingest" \
-H "Content-Type: application/json" \
-d '{
"doc_id": "apple_news_1",
"content": "Apple Inc. announced record quarterly earnings with strong iPhone sales",
"metadata": {"source": "news", "date": "2024-01-15"}
}'curl -X POST "http://localhost:8000/rag/search" \
-H "Content-Type: application/json" \
-d '{
"query": "Apple earnings",
"limit": 5
}'curl -X POST "http://localhost:8000/rag/generate" \
-H "Content-Type: application/json" \
-d '{
"query": "What were Apple'\''s latest earnings?"
}'curl -X POST "http://localhost:8000/research/market-analysis" \
-H "Content-Type: application/json" \
-d '{
"symbols": ["AAPL", "MSFT", "GOOGL"]
}'curl -X POST "http://localhost:8000/research/news" \
-H "Content-Type: application/json" \
-d '{
"query": "latest developments in AI stocks"
}'curl -X POST "http://localhost:8000/research/workflow" \
-H "Content-Type: application/json" \
-d '{
"symbols": ["AAPL", "MSFT"],
"query": "AI and machine learning investments"
}'This project includes comprehensive testing guides for all AI safety scenarios. See TESTING_GUIDE.md for detailed instructions on testing:
- Hallucinations: Verify factual accuracy and consistency
- Prompt Injection: Test resistance to adversarial prompts
- Data Drift: Monitor performance degradation over time
- Bias and Toxicity: Ensure fair and safe responses
- Performance: Measure latency and throughput
- Tool Use: Verify agent tool selection and planning
- Security: Test input validation and output sanitization
- RAG System: Verify document retrieval and grounding
# Run Python test suite
python test_api.pyfinagent-simple/
βββ config.py # Configuration management
βββ llm.py # OpenAI integration
βββ vector_db.py # Qdrant Cloud integration
βββ rag.py # RAG system
βββ agents.py # CrewAI agents
βββ main.py # FastAPI application
βββ test_api.py # Automated test suite
βββ pyproject.toml # Dependencies
βββ .env.example # Configuration template
βββ README.md # This file
βββ TESTING_GUIDE.md # Comprehensive testing guide
User Request
β
FastAPI Endpoint
β
βββββββββββββββββββββββββββββββββββββββ
β LLM Client (OpenAI) β
β - Text generation β
β - Embedding generation β
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β Vector Store (Qdrant Cloud) β
β - Document storage β
β - Semantic search β
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β RAG System β
β - Document ingestion β
β - Context retrieval β
β - Grounded generation β
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β Agents (CrewAI) β
β - Market Analyst β
β - News Researcher β
β - Report Writer β
βββββββββββββββββββββββββββββββββββββββ
β
Response to User
LLM Client: Wraps OpenAI API for text generation and embeddings
- Uses GPT-4 for generation
- Uses text-embedding-3-small for embeddings (1536 dimensions)
Vector Store: Manages Qdrant Cloud collections
- Stores documents with embeddings
- Performs semantic search with cosine similarity
- Supports metadata filtering
RAG System: Orchestrates retrieval and generation
- Ingests documents with embeddings
- Retrieves relevant context for queries
- Generates grounded responses
Agents: Multi-agent system for complex tasks
- Market Analyst: Analyzes market conditions
- News Researcher: Researches using RAG
- Report Writer: Synthesizes information into reports
- API Keys: Store in
.envfile, never commit to version control - Input Validation: All inputs are validated by Pydantic
- Output Safety: LLM responses are returned as-is (implement sanitization if needed)
- Rate Limiting: Implement at API gateway level for production
- Authentication: Add authentication layer for production deployment
| Operation | Typical Latency | Notes |
|---|---|---|
| Text Generation | 2-10s | Depends on prompt length and complexity |
| Embedding Generation | 1-3s | For typical financial text |
| Vector Search | <1s | Qdrant Cloud is very fast |
| RAG Generation | 2-10s | Retrieval + generation time |
| Market Analysis | 5-15s | Multiple LLM calls |
| Full Workflow | 10-30s | All agents + synthesis |
Solution:
- Check
.envfile has correct keys - Verify OpenAI API key is active
- Verify Qdrant Cloud credentials
Solution:
- Verify Qdrant Cloud instance is running
- Check QDRANT_URL is correct (should be HTTPS)
- Verify network connectivity
Solution:
- This is normal for LLM calls (2-10 seconds)
- Check OpenAI API rate limits
- Verify network connectivity
Solution:
- Ensure collection is created before ingesting documents
- Check collection name matches in code
- Verify Qdrant Cloud connection
The TESTING_GUIDE.md file provides comprehensive instructions for testing:
- Hallucination Testing: Verify consistency and factual accuracy
- Prompt Injection Testing: Test resistance to adversarial inputs
- Data Drift Testing: Monitor performance over time
- Bias Testing: Ensure fair treatment across different inputs
- Performance Testing: Measure latency and throughput
- Security Testing: Verify input/output validation
- RAG Testing: Verify document retrieval and grounding
Each test includes:
- Detailed explanation of what is being tested
- Curl commands to execute the test
- Expected behavior
- Interpretation of results
# Test 1: Consistency
for i in {1..3}; do
curl -X POST "http://localhost:8000/llm/generate" \
-H "Content-Type: application/json" \
-d '{
"prompt": "What is 2 + 2?",
"temperature": 0.0
}' | jq '.response'
done
# All responses should be identicalTo extend this project:
- Add new agents in
agents.py - Add new endpoints in
main.py - Add corresponding tests in
TESTING_GUIDE.md - Update documentation
This project is provided as-is for educational and testing purposes.
RAG combines retrieval and generation to produce grounded, factual responses:
- User query is converted to embedding
- Semantically similar documents are retrieved
- Retrieved documents provide context
- LLM generates response based on context
This significantly reduces hallucinations.
Multiple specialized agents work together:
- Market Analyst: Analyzes market conditions
- News Researcher: Researches using RAG
- Report Writer: Synthesizes findings
Each agent is specialized for its task, improving overall quality.
Text is converted to high-dimensional vectors:
- Same meaning β similar vectors
- Different meaning β different vectors
- Enables semantic search (finding similar documents)
Search based on meaning, not keywords:
- Query: "Apple earnings"
- Finds documents about Apple's financial results
- Even if exact keywords don't match
For issues or questions:
- Check
TESTING_GUIDE.mdfor testing instructions - Review error messages carefully
- Check API documentation
- Verify configuration in
.env
Ready to test AI agents? Start with the TESTING_GUIDE.md file! π