from fastapi import FastAPI, Query, HTTPException app = FastAPI() @app.get("/search") def search(query: str, n: int = Query(5, ge=1)): """ Endpoint for querying the search engine. Args: query (str): The search query. n (int): Number of results to return (default: 5). Returns: dict: Query results. """ if not query.strip(): raise HTTPException(status_code=400, detail="Query cannot be empty.") search_engine = app.state.search_engine if not search_engine: raise HTTPException(status_code=500, detail="Search engine not initialized.") try: results = search_engine.most_similar(query, n) except Exception as e: raise HTTPException( status_code=500, detail=f"An unexpected error occurred: {str(e)}" ) return {"query": query, "results": results}