Part 12 - Build a MugMori AI Service API with FastAPI
Understand how FastAPI can provide MugMori with an AI service API using Pydantic, scikit-learn, PostgreSQL, and OpenAI.
Build a MugMori AI Service API with FastAPI
MugMori can use a dedicated AI service to provide product recommendations and customer support without placing AI-provider credentials in the mobile app or browser.
The service receives a structured request, gathers approved MugMori data, calls the appropriate AI or machine-learning component, validates the result, and returns consistent JSON.
FastAPI is the AI service boundary. It coordinates the workflow, but each technology has a separate responsibility.
The service architecture
MugMori mobile app, website, or Django
↓ HTTPS / JSON
FastAPI AI service
↓
Pydantic request and response models
↓
AI application services
├── PostgreSQL data
├── scikit-learn models
└── OpenAI API
The first version can live in the same repository while keeping a clear API boundary. It can later become its own Docker or Fly.io service if the traffic, deployment cycle, or security requirements justify that change.
What each technology does
| Technology | MugMori responsibility | What it should not do |
|---|---|---|
| FastAPI | Routes requests, authenticates callers, coordinates services, and returns JSON | Store API keys in frontend code |
| Pydantic | Validates request and response shapes | Decide whether a recommendation is commercially correct |
| scikit-learn | Produces structured recommendations or predictions | Generate natural-language customer conversations |
| PostgreSQL | Stores products, bookings, policies, feedback, and approved training data | Automatically expose every database column to AI |
| OpenAI API | Produces chatbot responses using approved context | Directly query the database without application controls |
| Frontend or Django | Calls the AI service and displays the result | Call OpenAI with a secret key from the browser |
This separation makes the system easier to test and replace. For example, a recommendation model can be retrained without changing the chatbot endpoint.
Example API surface
| Method | Endpoint | Purpose |
|---|---|---|
| GET | /ai/health |
Confirm that the service is available |
| POST | /ai/recommendations |
Recommend MugMori products |
| POST | /ai/chat |
Answer a customer question using approved context |
| POST | /ai/predict |
Run a future prediction or classification model |
Example recommendation request:
{
"customer_id": "customer-123",
"occasion": "office gift",
"budget_sgd": 35,
"preferred_style": "minimal"
}
Example response:
{
"recommendations": [
{
"product_id": "mug-001",
"reason": "Fits the budget and minimal style",
"score": 0.87
}
],
"model_version": "recommendations-v1"
}
Pydantic validates the API contract
Pydantic models define what the AI service accepts and returns.
| Validation | Example |
|---|---|
| Required field | occasion must be provided |
| Type | budget_sgd must be a number |
| Range | Budget cannot be negative |
| Allowed value | Recommendation style must be supported |
| Response shape | Every recommendation has an ID, reason, and score |
The validation workflow is:
Request arrives
↓
Pydantic validates fields and types
↓ invalid ↓ valid
Return 422 JSON Call AI service logic
↓
Validate response model
↓
Return consistent JSON
Response validation matters because an AI or model result should not be allowed to silently return missing fields, invalid scores, or unexpected data to the frontend.
PostgreSQL is the controlled data source
PostgreSQL can store both MugMori business records and carefully selected AI data.
| Data area | Example records | AI use |
|---|---|---|
| Products | Mug name, design, price, stock | Filter and recommend products |
| Bookings | Pickup slot, status, merchant | Answer collection questions |
| Policies | Refund, delivery, redemption rules | Give policy-grounded chatbot answers |
| Feedback | Rating, product ID, written feedback | Evaluate recommendation quality |
| Training data | Approved features and labels | Train or evaluate scikit-learn models |
The AI service should query a controlled service or repository layer rather than expose unrestricted SQL. Sensitive fields, payment data, secret credentials, and private customer notes should not be included in prompts or training datasets without a documented reason.
Product recommendations with scikit-learn
scikit-learn is suitable for structured recommendation experiments, such as matching customer preferences with product features.
Customer requests recommendations
↓
FastAPI validates the request
↓
Service loads approved product features
↓
scikit-learn calculates recommendation scores
↓
Business rules remove unavailable products
↓
Pydantic validates the response
↓
Frontend receives product IDs and explanations
| Model input | Example |
|---|---|
| Product features | Colour, design, size, price, availability |
| Customer preference | Minimal, colourful, office gift |
| Business rules | In stock, within budget, available for pickup |
| Model output | Product ID and recommendation score |
The model should recommend product IDs and scores. The application should retrieve the current price, stock, and policy information from PostgreSQL instead of trusting stale values stored inside a model file.
Chatbot responses with OpenAI
OpenAI is useful for natural-language interaction, such as helping a customer understand pickup rules or comparing two mug designs.
Customer asks a question
↓
FastAPI validates the message
↓
Service retrieves approved MugMori context
↓
FastAPI sends limited context to OpenAI
↓
OpenAI drafts a natural-language answer
↓
Application checks safety and response format
↓
FastAPI returns the answer to the frontend
The chatbot should use approved policy context for questions about refunds, delivery, payments, and QR redemption. It should not invent a policy when the relevant information is unavailable.
| Chatbot question | Safe context |
|---|---|
| “Can I collect my mug tomorrow?” | Current booking and pickup rules |
| “Can I get a refund?” | Published refund policy and order status |
| “Which mug fits my budget?” | Current products, prices, stock, and recommendation results |
| “What happens when I scan my QR code?” | Published redemption workflow |
Training data and operational data
These data categories should not be mixed casually:
| Category | Purpose | Example |
|---|---|---|
| Operational data | Runs the live business | Product stock and booking status |
| Feature data | Describes model inputs | Style, colour, price range |
| Label data | Defines what the model learns | Customer selected or rated product |
| Evaluation data | Measures model quality | Held-back recommendation examples |
| Prompt context | Supports one chatbot answer | Current refund policy |
Adding every customer conversation to training data is not automatically correct. Data needs review, privacy rules, retention limits, and a clear purpose before it becomes training material.
Why FastAPI should control both AI providers
The frontend should call FastAPI rather than call scikit-learn or OpenAI directly.
| Concern | FastAPI control |
|---|---|
| API keys | Stored in server environment secrets |
| Input validation | Pydantic models and application rules |
| Data access | Approved PostgreSQL queries or repositories |
| Cost control | Rate limits, request limits, and model selection |
| Privacy | Remove or restrict unnecessary personal data |
| Auditability | Record model version, request ID, and outcome |
| Fallbacks | Return a safe response when a provider is unavailable |
This also gives the frontend a stable contract if the business changes models later.
Failure handling
| Failure | Response |
|---|---|
| Invalid request | Return a Pydantic validation error |
| Product is out of stock | Exclude it and return available alternatives |
| Model is unavailable | Return a temporary service error or deterministic fallback |
| OpenAI request times out | Return a safe support message and log the timeout |
| Policy context is missing | Do not invent an answer; direct the customer to support |
| Database is unavailable | Return service-unavailable status without exposing internals |
| Recommendation confidence is low | Explain that no strong match was found |
AI output should not bypass normal business rules. A recommendation cannot make an unavailable product purchasable, and a chatbot cannot approve a refund without the application’s normal authorization workflow.
A practical implementation roadmap
| Phase | Deliverable |
|---|---|
| 1 | FastAPI health endpoint and Pydantic request models |
| 2 | Read-only product recommendation endpoint with placeholder logic |
| 3 | PostgreSQL repository for products and published policies |
| 4 | scikit-learn experiment with versioned training and evaluation data |
| 5 | OpenAI chatbot using restricted MugMori policy context |
| 6 | Authentication, rate limits, logging, and cost monitoring |
| 7 | Frontend integration and user-feedback evaluation |
Start with deterministic rules and placeholder responses before introducing a trained model or an external language model. This makes the API contract and business rules testable first.
Final architecture
MugMori frontend or Django
↓ HTTPS / JSON
FastAPI AI service
├── Pydantic request and response validation
├── Product recommendation service
│ └── scikit-learn model
├── Chat service
│ └── OpenAI API
└── Repository layer
└── PostgreSQL
FastAPI is the API layer for the AI service. Pydantic protects the contract, scikit-learn handles structured recommendation logic, PostgreSQL stores controlled business and training data, and OpenAI provides conversational responses. Keeping those responsibilities separate gives MugMori a useful starting architecture that can evolve without exposing secrets or allowing AI output to override business rules.