hostserver3 / main.py
abdullahalioo's picture
Update main.py
2f3bde3 verified
raw
history blame
3 kB
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}