Spaces:
Runtime error
Runtime error
File size: 3,002 Bytes
c8f03da d7f32ed c8f03da 49158eb c8f03da e68e9cf c8f03da e68e9cf c8f03da 29331bd c8f03da 2f3bde3 c8f03da d5471e9 c8f03da 808ec17 c8f03da d5471e9 2f3bde3 d5471e9 c8f03da d5471e9 c8f03da d5471e9 c8f03da d5471e9 c8f03da 03991d8 c8f03da cc3751a c8f03da 808ec17 2f3bde3 |
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 |
import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from hugchat import hugchat
from hugchat.login import Login
import logging
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize FastAPI app
app = FastAPI()
# HuggingFace credentials from environment variables
EMAIL = "[email protected]"
PASSWORD = "Allahisgreatest17"
ASSISTANT_ID = "682e0c1f5f0c3d952a27498e"
# Global chatbot instance
chatbot = None
# Pydantic model for request body
class PromptRequest(BaseModel):
prompt: str
# Lifespan handler for startup and shutdown
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
global chatbot
try:
# Validate credentials
if not EMAIL or not PASSWORD or not ASSISTANT_ID:
logger.error("Missing environment variables: EMAIL=%s, PASSWORD=%s, ASSISTANT_ID=%s",
EMAIL, "****" if PASSWORD else None, ASSISTANT_ID)
raise ValueError("HuggingFace credentials or assistant ID not provided in environment variables")
# Log in to HuggingFace
sign = Login(EMAIL, PASSWORD)
try:
# Try login without cookie_path_dir to avoid file system issues
cookies = sign.login(save_cookies=False)
logger.info("Successfully logged in to HuggingFace without saving cookies")
except Exception as e:
logger.error("Login failed: %s", str(e))
raise
# Initialize chatbot
chatbot = hugchat.ChatBot(cookies=cookies.get_dict())
chatbot.new_conversation(assistant=ASSISTANT_ID, switch_to=True)
logger.info("Chatbot initialized with assistant ID: %s", ASSISTANT_ID)
except Exception as e:
logger.error("Failed to initialize chatbot: %s", str(e))
raise HTTPException(status_code=500, detail=f"Failed to initialize chatbot: {str(e)}")
yield # Application runs here
# Shutdown: Clean up (optional)
logger.info("Shutting down application")
# Attach lifespan handler to FastAPI app
app.lifespan = lifespan
# Endpoint to handle chat requests
@app.post("/ask")
async def ask(prompt_request: PromptRequest):
try:
if not chatbot:
logger.error("Chatbot not initialized")
raise HTTPException(status_code=500, detail="Chatbot not initialized")
# Send prompt to chatbot
response = chatbot.chat(prompt_request.prompt, stream=False)
logger.info("Received response for prompt: %s", prompt_request.prompt)
# Return structured response
return {"status": "success", "response": response}
except Exception as e:
logger.error("Error processing request: %s", str(e))
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
# Health check endpoint
@app.get("/health")
async def health():
return {"status": "healthy", "chatbot_initialized": chatbot is not None}
|