Backend service for managing inbound leads, running AI-assisted lead scoring, and controlling handoff to sales through explicit business rules.
This project demonstrates:
- asynchronous API development with FastAPI
- PostgreSQL integration with Tortoise ORM
- separation of API, business logic, and AI/scoring logic
- controlled AI usage in a product workflow
The service models a simplified lead-processing workflow.
A lead moves through a cold pipeline, can be analyzed by an AI-assisted scoring module, and may be transferred to sales only if specific business conditions are met.
The goal of the project is to show how AI can be integrated into a backend system as a decision-support component, not as a fully autonomous mechanism.
- create and retrieve leads
- manage lead stages with transition validation
- run AI-assisted lead scoring
- generate a recommendation for the next step
- validate handoff to sales
- automatically create a
Salerecord on successful transfer
- Python 3.12
- FastAPI
- PostgreSQL
- Tortoise ORM
- Docker / Docker Compose
A cold lead moves through the following stages:
new → contacted → qualified → transferred
↘ lost
- stage skipping is not allowed
- a lead can be moved to
lostfrom any non-final stage - final stages (
transferred,lost) are immutable
A lead can be moved to transferred only if:
ai_score >= 0.6business_domainis defined
If the conditions are met:
- the lead stage becomes
transferred - a
Salerecord is created
Otherwise, the API returns an error.
The AI/scoring module analyzes a lead using:
sourcestageactivity_countbusiness_domain
It returns:
score— estimated probability of a successful dealrecommendation— recommended next actionreason— short explanation of the result
Example response:
{
"score": 0.78,
"recommendation": "transfer_to_sales",
"reason": "lead has high activity and clear business domain"
}In this project, AI is used as an assistive module:
- it evaluates the lead
- suggests the next step
- supports the manager's decision-making
Final control remains with the system's business rules and user actions. This keeps the workflow deterministic and prevents AI from autonomously making critical product decisions.
Main endpoints:
POST /leads/— create a leadGET /leads/{id}— get a lead by IDPATCH /leads/{id}/stage— update the lead stagePOST /leads/{id}/analyze— run AI analysis for a lead
After startup, the API documentation is available at:
http://localhost:8000/docs
app/
api/
leads.py
services/
ai_service.py
lead_service.py
models.py
schemas.py
main.py
app/api/leads.py— HTTP API and request handlingapp/services/lead_service.py— lead and sales business logicapp/services/ai_service.py— AI/scoring moduleapp/models.py— ORM modelsapp/schemas.py— Pydantic schemasapp/main.py— application entry point and initialization
Requirements:
- Docker
- Docker Compose
git clone https://github.com/machinatororis/lead-qualification-api.git
cd lead-qualification-api
docker compose up --buildAfter startup:
- API:
http://localhost:8000 - Healthcheck:
http://localhost:8000/health - Swagger UI:
http://localhost:8000/docs
Services:
db— PostgreSQLapp— FastAPI application
git clone https://github.com/machinatororis/lead-qualification-api.git
cd lead-qualification-apiFor example, with Docker:
docker run --name lead-db \
-e POSTGRES_DB=lead_ai_crm \
-e POSTGRES_USER=postgres \
-e POSTGRES_PASSWORD=postgres \
-p 5432:5432 \
-d postgres:16Create a .env file based on .env.example:
cp .env.example .envExample:
DB_URL=postgres://postgres:postgres@localhost:5432/lead_ai_crmpython -m venv venvWindows:
venv\Scripts\activateLinux / macOS:
source venv/bin/activateThen install dependencies and start the server:
pip install -r requirements.txt
uvicorn app.main:app --reloadAfter startup:
- Healthcheck:
http://localhost:8000/health - Swagger UI:
http://localhost:8000/docs
Fields:
source— lead source (scanner,partner,manual)stage— current lead stagebusiness_domain— business domainactivity_count— number of interactionsai_score— estimated deal probabilityai_recommendation— AI recommendationai_reason— explanation of the AI result
Created automatically when a lead is successfully transferred to sales.
- A manager creates a new lead
- The lead moves through the early stages of the cold pipeline
- The user runs AI analysis
- The system stores
score,recommendation, andreason - On transfer attempt, the service validates the business conditions
- If the conditions are met, a
Salerecord is created
In a production-ready version, I would extend the project with:
- database migrations
- automated tests for the service layer and business rules
- centralized configuration management
- structured logging and metrics
- more granular error handling
- background jobs or queues for AI analysis
- authentication and role-based access control
- external AI/ML integration instead of rule-based scoring
This project focuses on backend design for a lead qualification workflow where AI is integrated into a clear business process and constrained by explicit system rules.
The main engineering goals were:
- separating API, business logic, and AI logic
- modeling domain constraints
- validating stage transitions
- using AI in a controlled, product-oriented way
The project includes:
- unit tests for lead stage transition rules and sales handoff validation
- async tests for database-backed service operations
- tests for AI scoring behavior
Run tests with:
pytest