File size: 7,339 Bytes
56c0820
 
 
 
 
c5e2fc6
56c0820
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6b14ad
56c0820
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import os
import re
import json
import joblib
import numpy as np
import pickle
from crewai import Agent, Task, Crew, LLM
from crewai.tools import tool
from dataLoader import *

# Load trained model, scaler, and feature columns
model_filename = "modelUberML.pkl"
with open(model_filename, 'rb') as file:
    model_data = pickle.load(file)
    ride_model = model_data['model']
    scaler = model_data['scaler']
    feature_columns = model_data['feature_columns']


# Define Tools for the Agents
@tool("predict_ride")
def predict_ride(rideID: str, return_json: bool = False):
    """Predict the success of an Uber ride using the trained ML model and save result to Firebase."""
    ride_data_dict = pull_ride_data(rideID)
    if not ride_data_dict:
        error = f"Error: No ride data found for document ID '{rideID}'"
        if return_json:
            return {"status": "error", "message": error}
        return error

    # Define feature mapping (same as training)
    FEATURE_MAPPING = {
        "Avg CTAT": "Avg CTAT",
        "Avg VTAT": "Avg VTAT",
        "Booking Value": "Booking Value",
        "Customer Rating": "Customer Rating",
        "Driver Ratings": "Driver Ratings",
        "Ride Distance": "Ride Distance",
        "Booking Status_Cancelled by Driver": "Booking Status_Cancelled by Driver",
        "Booking Status_Incomplete": "Booking Status_Incomplete",
        "Booking Status_No Driver Found": "Booking Status_No Driver Found",
        "Payment Method_Credit Card": "Payment Method_Credit Card",
        "Payment Method_Debit Card": "Payment Method_Debit Card",
        "Payment Method_UPI": "Payment Method_UPI",
        "Payment Method_Uber Wallet": "Payment Method_Uber Wallet",
        "Vehicle Type_Bike": "Vehicle Type_Bike",
        "Vehicle Type_Go Mini": "Vehicle Type_Go Mini",
        "Vehicle Type_Go Sedan": "Vehicle Type_Go Sedan",
        "Vehicle Type_Premier Sedan": "Vehicle Type_Premier Sedan",
        "Vehicle Type_Uber XL": "Vehicle Type_Uber XL",
        "Vehicle Type_eBike": "Vehicle Type_eBike",
        "Pickup Location": "Pickup Location",
        "Drop Location": "Drop Location",
    }

    # Extract features
    input_features = {}
    for firestore_key, model_col in FEATURE_MAPPING.items():
        val = ride_data_dict.get(firestore_key)
        if val is None:
            error = f"Error: Missing required feature '{firestore_key}'"
            if return_json:
                return {"status": "error", "message": error}
            return error
        input_features[model_col] = val

    # Create DataFrame
    df_sample = pd.DataFrame([input_features])

    # One-hot encode categorical features
    categorical_cols = ['Pickup Location', 'Drop Location']
    df_sample = pd.get_dummies(df_sample, columns=categorical_cols)

    # Ensure all training columns are present
    for col in feature_columns:
        if col not in df_sample.columns:
            df_sample[col] = 0
    df_sample = df_sample[feature_columns]

    # Scale
    ride_scaled = scaler.transform(df_sample)

    # Predict
    prediction = ride_model.predict(ride_scaled)[0]
    probability = ride_model.predict_proba(ride_scaled)[0]
    confidence = float(max(probability))

    # Save to Firebase
    success = push_prediction_result(rideID, prediction, confidence)

    # Prepare result
    result_dict = {
        "prediction": int(prediction),
        "confidence": confidence,
        "rideID": rideID,
        "saved_to_firebase": success
    }

    if return_json:
        return result_dict
    else:
        return json.dumps(result_dict, indent=2)

@tool("format_prediction")
def format_prediction(rideID: str, return_json: bool = False):
    """Fetch prediction + ride data and format into readable output"""

    pred_data = pull_prediction_data(rideID)
    ride_data = pull_ride_data(rideID)
    if not pred_data:
        error = f"No prediction found for rideID {rideID}"
        return {"status": "error", "message": f"No prediction found{rideID}"} if return_json else error
    if not ride_data:
        error = f"No ride data found for rideID {rideID}"
        return {"status": "error", "message": error} if return_json else error

    #Build the formatted result
    formatted = {
        "rideID": rideID,
        "prediction": pred_data.get("prediction", "N/A"),
        "confidence": pred_data.get("confidence", "N/A"),

        #Fields
        "bookingValue": ride_data.get("Booking Value"),
        "avgCTAT": ride_data.get("Avg CTAT"),
        "avgVTAT": ride_data.get("Avg VTAT"),
        "statusCompleted": ride_data.get("Booking Status_Completed"),
    }

    return formatted if return_json else json.dumps(formatted, indent=2)


llm = LLM(
    model="huggingface/meta-llama/Llama-3.1-8B-Instruct"
)



# Define Agents
ride_success_predictor = Agent(
    role="Ride Success Calculator Agent",
    goal="Calculate the success or failure of a ride using ML model and LLM interpretation",
    backstory="You combine machine learning predictions with natural language explanations to provide personalized ride success assessments.",
    verbose=True,
    llm=llm,
    tools=[predict_ride]
)

formatting_agent = Agent(
    role="Formatting Agent",
    goal="Retrieve prediction + ride data and format into readable output",
    backstory="You turn raw ML prediction results into clean, readable formatted summaries.",
    verbose=True,
    llm=llm,
    tools=[format_prediction],
)

# Define Tasks
predict_ride_success = Task(
    description=f"Calculate ride success/failure using the ML model based on ride features.",
    expected_output="Binary success/failure, confidence score, and brief explanation.",
    agent=ride_success_predictor,
)

format_prediction_task = Task(
    description=f"Pull prediction and ride data for a given rideID, then format the results into a readable report",
    expected_output="A structured summary of ride performance and prediction results.",
    agent=formatting_agent,
)

# Define Crew
crew = Crew(
    agents=[ride_success_predictor, formatting_agent],
    tasks=[predict_ride_success, format_prediction_task],
    verbose=True
)

def run_crew_for_ride(rideID: str):
    """Run the full crew pipeline for a given rideID and return the final output."""
    # Inject rideID into tasks dynamically
    for task in crew.tasks:
        # Dynamically update task descriptions to include rideID
        if "predict_ride_success" in task.description or "Calculate ride success" in task.description:
            task.description = f"Predict ride success for rideID: {rideID}. Use the predict_ride tool with this rideID."
        if "format_prediction_task" in task.description or "Pull prediction and ride data" in task.description:
            task.description = f"Format the prediction and ride data for rideID: {rideID}. Use the format_prediction tool with this rideID."

    # Run crew
    result = crew.kickoff()
    return result.raw if hasattr(result, 'raw') else str(result)


# Optional: Keep CLI for local testing
if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1:
        ride_id = sys.argv[1]
        print(f"Running crew for rideID: {ride_id}")
        output = run_crew_for_ride(ride_id)
        print("\n=== FINAL OUTPUT ===\n")
        print(output)
    else:
        print("Usage: python crew.py <rideID>")