Spaces:
Runtime error
Runtime error
File size: 6,361 Bytes
79d1f81 7ab6ea8 79d1f81 | 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 205 206 207 208 209 | import os
import uuid
import json
import logging
from typing import List, Dict, Any
from dataclasses import dataclass
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from sentence_transformers import SentenceTransformer
import faiss
import numpy as np
from groq import Groq
# Logging setup
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Environment variables
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
if not GROQ_API_KEY:
raise ValueError("GROQ_API_KEY environment variable is required")
# Load JTBD data
with open("expanded_jtbd.json", "r") as f:
JTBD_DATA: List[Dict[str, Any]] = json.load(f)["jobs_to_be_done"]
@dataclass
class JTBDItem:
name: str
description: str
business_function: str
intent_type: str
trigger_sources: List[str]
index: int # Original index in list for reference
# Global variables for vector store
model = None
index = None
jtbd_items: List[JTBDItem] = []
def build_vector_store():
global model, index, jtbd_items
# Initialize embedding model
model = SentenceTransformer('all-MiniLM-L6-v2')
# Prepare JTBD items and descriptions for embedding
descriptions = []
jtbd_items = []
for idx, job in enumerate(JTBD_DATA):
item = JTBDItem(
name=job["name"],
description=job["description"],
business_function=job["business_function"],
intent_type=job["intent_type"],
trigger_sources=job["trigger_sources"],
index=idx
)
jtbd_items.append(item)
descriptions.append(job["description"])
# Embed descriptions
embeddings = model.encode(descriptions)
embeddings = np.array(embeddings).astype('float32')
# Build FAISS index
dimension = embeddings.shape[1]
index = faiss.IndexFlatL2(dimension)
index.add(embeddings)
logger.info(f"Vector store built with {len(jtbd_items)} JTBD items")
# Build vector store on startup
build_vector_store()
# Initialize Groq client
client = Groq(api_key=GROQ_API_KEY)
# Pydantic models
class ContextInput(BaseModel):
context: str
class JTBDOutput(BaseModel):
request_id: str
job_name: str
department: str
source: str
intent_type: str
confidence: float # Optional, based on LLM response
# FastAPI app
app = FastAPI(title="JTBD Identifier AI Agent", version="1.0.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
async def startup_event():
logger.info("Application started")
@app.post("/identify_jtbd", response_model=JTBDOutput)
async def identify_jtbd(input_data: ContextInput):
try:
# Generate unique request ID
request_id = str(uuid.uuid4())
# Embed the input context
context_embedding = model.encode([input_data.context])
context_embedding = np.array(context_embedding).astype('float32')
# Retrieve top-k similar JTBDs (k=5 for efficiency)
k = 5
distances, indices = index.search(context_embedding, k)
# Get top-k JTBD items
top_items = [jtbd_items[i] for i in indices[0]]
# Prepare prompt for Groq
top_descriptions = "\n\n".join([
f"Job {i+1}: {item.name}\nDescription: {item.description}\nDepartment: {item.business_function}\nIntent: {item.intent_type}"
for i, item in enumerate(top_items)
])
prompt = f"""
You are an expert at identifying Jobs To Be Done (JTBD) from email contexts.
Given the following context from an email:
"{input_data.context}"
And these top candidate JTBDs:
{top_descriptions}
Identify the SINGLE BEST matching JTBD. Respond in JSON format only:
{{
"job_name": "exact name of the job",
"department": "exact business_function",
"intent_type": "exact intent_type",
"confidence": <float between 0.0 and 1.0, your estimated match confidence>
}}
If no good match, use the first one with confidence 0.0.
"""
# Call Groq LLM
chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": prompt}],
model="llama3-8b-8192", # Or "mixtral-8x7b-32768" for better reasoning
temperature=0.1,
max_tokens=200,
)
response = chat_completion.choices[0].message.content.strip()
# Parse JSON response
try:
parsed = json.loads(response)
job_name = parsed["job_name"]
department = parsed["department"]
intent_type = parsed["intent_type"]
confidence = float(parsed["confidence"])
except (json.JSONDecodeError, KeyError, ValueError) as e:
logger.warning(f"Failed to parse Groq response: {response}, error: {e}")
# Fallback to top match
top_match = top_items[0]
job_name = top_match.name
department = top_match.business_function
intent_type = top_match.intent_type
confidence = 0.5 # Default fallback
# Fixed source as 'email'
source = "email"
logger.info(f"JTBD identified for request {request_id}: {job_name} in {department}")
return JTBDOutput(
request_id=request_id,
job_name=job_name,
department=department,
source=source,
intent_type=intent_type,
confidence=confidence
)
except Exception as e:
logger.error(f"Error in identify_jtbd: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
# Add this AT THE END of your app.py file
from fastapi.responses import FileResponse
@app.get("/")
async def read_index():
# This serves the HTML file when someone visits the root URL
return FileResponse('index.html')
@app.get("/health")
async def health_check():
return {"status": "healthy"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) |