Bot_test / app.py
Futuresony's picture
Update app.py
d74ca8b verified
import os
from fastapi import FastAPI, Request, HTTPException
import uvicorn
from gradio_client import Client
import uuid
# Keys
VALID_API_KEY = os.getenv("APP_API_KEY") # for your FastAPI security
SPACE_API_KEY = os.getenv("SPACE_API_KEY") # for your hosted HF Space
# Connect to hosted space
client = Client("Futuresony/Mr.Events")
#Futuresony/Mr.Events
#Futuresony/ABSA_Test_Space
app = FastAPI()
@app.post("/chat")
async def chat(request: Request):
data = await request.json()
# API key check from headers or JSON
api_key = request.headers.get("X-API-Key") or data.get("api_key")
if api_key != VALID_API_KEY:
raise HTTPException(status_code=403, detail="Invalid API Key")
user_message = data.get("message")
# Check for user_id in the request data, generate one if not present
user_id = data.get("user_id")
if not user_id:
user_id = str(uuid.uuid4()) # Generate a unique ID if none is provided
print(f"Generated user_id: {user_id} for this request.")
if not user_message:
raise HTTPException(status_code=400, detail="Message is required")
# Call your hosted Space, passing the message and additional inputs (api_key, user_id)
# The ChatInterface handles chat_history internally when type="messages"
result = client.predict(
user_message, # Primary query
api_key, # First additional input (API Key)
user_id, # Second additional input (User ID - assuming this will be added to Gradio)
api_name="/chat" # Ensure this matches the endpoint in the Gradio app
)
return {"response": result, "user_id": user_id} # Return the user_id so the client can potentially reuse it
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)