A FastAPI-based product recommendation service that uses SerpAPI for Amazon product search and OpenAI for intelligent recommendations based on user's recent purchases.
- Smart Product Recommendations: Get personalized product suggestions based on recent purchases
- Amazon Product Search: Real-time product search using SerpAPI Amazon integration
- OpenAI Integration: AI-powered recommendation analysis with structured JSON responses
- RESTful API: Clean, well-documented API endpoints with comprehensive error handling
- Comprehensive Testing: Full test coverage with mocked external services
- Docker Support: Containerized deployment with Docker Compose
- Clean Codebase: Well-organized project structure with optimized Docker setup
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ FastAPI App │ │ Recommendation │ │ External │
│ │ │ Services │ │ Services │
│ - Router │───▶│ │───▶│ │
│ - Schemas │ │ - Sanitization │ │ - SerpAPI │
│ - Main App │ │ - Amazon Search │ │ - OpenAI │
│ │ │ - Formatting │ │ │
│ │ │ - AI Query │ │ │
└─────────────────┘ └──────────────────┘ └─────────────────┘
rag_test/
├── app/
│ ├── main.py # FastAPI application entry point
│ ├── routers/
│ │ └── recommendation_router.py # API endpoints
│ ├── services/
│ │ └── recommendation_services.py # Business logic
│ ├── schemas/
│ │ └── recommendation_schemas.py # Pydantic models
│ ├── tests/
│ │ ├── test_recommendation_services.py
│ │ └── test_recommendation_router.py
│ └── Dockerfile
├── docker-compose.yml
├── Makefile
├── requirements.in
├── requirements.txt
└── README.md
Get product recommendations based on a recent purchase.
Parameters:
recent_bought_product(query, required): The product the user recently purchased
Success Response:
{
"message": "Great choice with your iPhone 14!",
"recommendations": [
{
"description": "Perfect companion for your iPhone 14",
"price": "$249.99",
"rating": "4.8"
},
{
"description": "Essential protection for your device",
"price": "$39.99",
"rating": "4.6"
}
],
"status": "success",
"recent_bought_product": "iPhone 14"
}Error Response:
{
"detail": {
"error": "SerpAPI search failed: API key invalid",
"status": "error",
"details": "Recommendation pipeline failed"
}
}- Docker and Docker Compose
- SerpAPI account and API key
- OpenAI account and API key
Create a .env file in the project root:
SERPAPI_API_KEY=your_serpapi_key_here
OPENAI_API_KEY=your_openai_key_here
OPENAI_MODEL=gpt-4o-
Clone the repository:
git clone <repository-url> cd rag_test
-
Set up environment variables:
# Create .env file with your API keys echo "SERPAPI_API_KEY=your_key" > .env echo "OPENAI_API_KEY=your_key" >> .env echo "OPENAI_MODEL=gpt-4o" >> .env
-
Start the application:
make start
Start the service:
make startStop the service:
make stopRun tests:
make testGet recommendations:
curl "http://localhost:8000/v1/recommendations?recent_bought_product=iPhone%2014"Once the service is running, visit:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- Health Check: http://localhost:8000/
make test# Service layer tests
make test-services
# API/Route tests
make test-router
# Tests with coverage report
make test-coverageThe test suite includes:
- 35 passing tests with comprehensive coverage
- Unit tests for all service functions (sanitization, search, formatting, AI query)
- Integration tests for API endpoints
- Mocked external services (SerpAPI, OpenAI)
- Error handling scenarios (API failures, validation errors)
- Schema validation tests for request/response models
-
Install dependencies:
pip install -r requirements.txt
-
Run the application locally:
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
-
Run tests locally:
pytest app/tests/ -v
- Services: Add business logic in
app/services/recommendation_services.py - Routes: Add API endpoints in
app/routers/recommendation_router.py - Schemas: Define data models in
app/schemas/recommendation_schemas.py - Tests: Add tests in
app/tests/
- Services Layer: Contains sanitization, Amazon search, formatting, and OpenAI query logic
- Router Layer: Handles HTTP requests, validation, and response formatting
- Schema Layer: Defines request/response models with Pydantic validation
- Exception Handling: Custom
RecommendationExceptionfor pipeline errors
# Start the service
make start
# Stop the service
make stop
# View logs
docker compose logs rag_test -f
# Rebuild and restart
docker compose up rag_test --build --force-recreate- Input Sanitization: Clean and normalize the user's product input
- Amazon Search: Search for complementary accessories using SerpAPI
- Result Formatting: Structure search results for AI consumption
- AI Analysis: Use OpenAI to generate intelligent recommendations
- Response Formatting: Return structured JSON with recommendations
User Input → Sanitize → Amazon Search → Format Results → OpenAI Query → Structured Response
-
API Key Errors:
- Ensure
SERPAPI_API_KEYandOPENAI_API_KEYare set in.env - Verify API keys are valid and have sufficient credits
- Ensure
-
Container Issues:
- Check if the container is running:
docker compose ps - View logs:
docker compose logs rag_test
- Check if the container is running:
-
Test Failures:
- Ensure the container is running before executing tests
- Check that all dependencies are installed:
pip install -r requirements.txt
Required environment variables:
SERPAPI_API_KEY: Your SerpAPI key for Amazon product searchOPENAI_API_KEY: Your OpenAI API key for AI recommendationsOPENAI_MODEL: OpenAI model to use (recommended:gpt-4o)
View application logs:
docker compose logs rag_test -f- Response Time: Average response time under 3 seconds
- Concurrent Requests: Supports multiple simultaneous requests
- Caching: No caching implemented (real-time results)
- Rate Limiting: Depends on API provider limits (SerpAPI, OpenAI)
- FastAPI: Modern, fast web framework for building APIs
- Pydantic: Data validation and settings management
- SerpAPI: Amazon product search integration
- OpenAI: AI-powered recommendation engine
- Docker: Containerized deployment
- Python 3.11: Modern Python runtime with performance improvements
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass:
make test - Submit a pull request
This project is licensed under the MIT License.