CoolFace
Apppublic

hp2030/Ai-Agent_Sales

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
api.py83 linesDownload Raw Back to src
1# src/api.py
2
3"""
4Phase 5 - FastAPI Application for Sales AI Agent (Fixed Version)
5"""
6
7from fastapi import FastAPI
8from pydantic import BaseModel
9import pandas as pd
10import joblib
11import yaml
12
13from action_recommender import recommend_action
14from email_generator import generate_email
15
16# ---------- Load Config, Model, Encoder & Scaler ----------
17config = yaml.safe_load(open("../config.yaml"))
18
19model = joblib.load("../Models/deal_success_model.pkl")
20encoders = joblib.load("../Models/encoders.pkl")
21scaler = joblib.load("../Models/scaler.pkl")
22
23# ---------- FastAPI App ----------
24app = FastAPI(title="Sales AI Agent", description="Deal Prediction, Recommendation, and Email Generator")
25
26# ---------- Define Lead Input Schema ----------
27class Lead(BaseModel):
28    Industry: str
29    Sales_Stage: str   # ✅ Use underscore for API input
30    Lead_Source: str   # ✅ Use underscore for API input
31    Deal_Amount: float
32    Emails: int
33    Meetings: int
34    Days_Since_Last_Contact: int
35
36# ---------- Preprocess Input ----------
37def preprocess_input(lead: Lead) -> pd.DataFrame:
38    data = pd.DataFrame([lead.dict()])
39
40    # ✅ Rename API-friendly keys to match model-friendly keys
41    data.rename(columns={
42        "Sales_Stage": "Sales Stage",
43        "Lead_Source": "Lead Source",
44        "Deal_Amount": "Deal Amount",
45        "Days_Since_Last_Contact": "Days Since Last Contact"
46    }, inplace=True)
47
48    # Encode
49    for col in ['Industry', 'Sales Stage', 'Lead Source']:
50        data[col] = encoders[col].transform(data[col])
51
52    # Scale
53    data[['Deal Amount', 'Emails', 'Meetings', 'Days Since Last Contact']] = scaler.transform(
54        data[['Deal Amount', 'Emails', 'Meetings', 'Days Since Last Contact']]
55    )
56
57    return data
58
59# ---------- API Route ----------
60@app.post("/predict")
61def predict(lead: Lead):
62    # Preprocess
63    data = preprocess_input(lead)
64
65    # Predict
66    probability = model.predict_proba(data)[0][1]
67
68    # Recommend Action
69    recommendation = recommend_action(probability, lead.Days_Since_Last_Contact)
70
71    # Generate Email
72    email = generate_email({
73        "Industry": lead.Industry,
74        "Sales Stage": lead.Sales_Stage,
75        "Deal Amount": lead.Deal_Amount
76    }, recommendation)
77
78    return {
79        "success_probability": round(float(probability), 3),
80        "recommended_action": recommendation,
81        "generated_email": email
82    }
83