Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

RAG Test - Product Recommendation API

A FastAPI-based product recommendation service that uses SerpAPI for Amazon product search and OpenAI for intelligent recommendations based on user's recent purchases.

Features

  • 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

Architecture

┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   FastAPI App   │    │  Recommendation  │    │   External      │
│                 │    │    Services      │    │   Services      │
│  - Router       │───▶│                  │───▶│                 │
│  - Schemas      │    │  - Sanitization  │    │  - SerpAPI      │
│  - Main App     │    │  - Amazon Search │    │  - OpenAI       │
│                 │    │  - Formatting    │    │                 │
│                 │    │  - AI Query      │    │                 │
└─────────────────┘    └──────────────────┘    └─────────────────┘

Project Structure

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

API Endpoints

GET /v1/recommendations

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"
  }
}

Prerequisites

  • Docker and Docker Compose
  • SerpAPI account and API key
  • OpenAI account and API key

Environment Variables

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

Installation and Setup

  1. Clone the repository:

    git clone <repository-url>
    cd rag_test
  2. 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
  3. Start the application:

    make start

Usage

Using Make Commands

Start the service:

make start

Stop the service:

make stop

Run tests:

make test

Get recommendations:

curl "http://localhost:8000/v1/recommendations?recent_bought_product=iPhone%2014"

API Documentation

Once the service is running, visit:

Testing

Run All Tests

make test

Run Specific Test Suites

# Service layer tests
make test-services

# API/Route tests
make test-router

# Tests with coverage report
make test-coverage

Test Coverage

The 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

Development

Local Development Setup

  1. Install dependencies:

    pip install -r requirements.txt
  2. Run the application locally:

    uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
  3. Run tests locally:

    pytest app/tests/ -v

Adding New Features

  1. Services: Add business logic in app/services/recommendation_services.py
  2. Routes: Add API endpoints in app/routers/recommendation_router.py
  3. Schemas: Define data models in app/schemas/recommendation_schemas.py
  4. Tests: Add tests in app/tests/

Code Structure

  • 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 RecommendationException for pipeline errors

Docker Commands

# 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

How It Works

Recommendation Pipeline

  1. Input Sanitization: Clean and normalize the user's product input
  2. Amazon Search: Search for complementary accessories using SerpAPI
  3. Result Formatting: Structure search results for AI consumption
  4. AI Analysis: Use OpenAI to generate intelligent recommendations
  5. Response Formatting: Return structured JSON with recommendations

Processing Flow

User Input → Sanitize → Amazon Search → Format Results → OpenAI Query → Structured Response

Troubleshooting

Common Issues

  1. API Key Errors:

    • Ensure SERPAPI_API_KEY and OPENAI_API_KEY are set in .env
    • Verify API keys are valid and have sufficient credits
  2. Container Issues:

    • Check if the container is running: docker compose ps
    • View logs: docker compose logs rag_test
  3. Test Failures:

    • Ensure the container is running before executing tests
    • Check that all dependencies are installed: pip install -r requirements.txt

Environment Variables

Required environment variables:

  • SERPAPI_API_KEY: Your SerpAPI key for Amazon product search
  • OPENAI_API_KEY: Your OpenAI API key for AI recommendations
  • OPENAI_MODEL: OpenAI model to use (recommended: gpt-4o)

Logs

View application logs:

docker compose logs rag_test -f

Performance

  • 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)

Technology Stack

  • 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

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass: make test
  5. Submit a pull request

License

This project is licensed under the MIT License.

About

This project implements SerpAPI and OpenAI to create a cross-sell agent based on recent purchase of a client

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages