RAG_IR_API / main_api.py
Erenuo's picture
Upload 10 files
60b4e60 verified
Raw History Blame Contribute Delete
2.13 kB
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn
from typing import List
try:
from recognize import IntentRecognizer
except ImportError:
# Dummy class for startup if recognize.py is missing
class IntentRecognizer:
def __init__(self): self.collection = None
def recognize_intent(self, query_text): return [{"intent": "error", "score": 0.0}]
# --- CHANGE: Update API Data Models ---
class Prediction(BaseModel):
intent: str
score: float
class QueryRequest(BaseModel):
text: str
class IntentResponse(BaseModel):
query_text: str
predictions: List[Prediction] # The response is now a list of predictions
# --- FastAPI Application ---
app = FastAPI(
title="Intent Recognition API",
description="An API that uses a vector database to recognize user intent.",
version="1.1.0", # Version bump
)
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
recognizer = None
@app.on_event("startup")
def load_recognizer():
global recognizer
print("--- Application starting up... ---")
recognizer = IntentRecognizer()
# --- CHANGE: Update API Endpoint ---
@app.post("/recognize-intent/", response_model=IntentResponse)
def recognize_intent_endpoint(request: QueryRequest):
if not recognizer or not recognizer.collection:
raise HTTPException(status_code=503, detail="Intent Recognizer is not available.")
query = request.text
# The recognizer now returns a list of prediction dicts
predictions_list = recognizer.recognize_intent(query)
return IntentResponse(
query_text=query,
predictions=predictions_list
)
@app.get("/", summary="Root endpoint for health check")
def read_root():
return {"status": "Intent Recognition API is running."}
if __name__ == "__main__":
uvicorn.run("main_api:app", host="127.0.0.1", port=8000, reload=True)