Spaces:
Sleeping
Sleeping
File size: 1,795 Bytes
150833d 5c98132 528eda9 ab390c2 d74ca8b 528eda9 ab390c2 5c98132 114406d 528eda9 ab390c2 114406d 150833d 5c98132 150833d 5c98132 ab390c2 5c98132 114406d 5c98132 d74ca8b 114406d 5c98132 9c576b0 114406d 9c576b0 596e686 114406d 150833d 596e686 d74ca8b 150833d 114406d |
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 |
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) |