Spaces:
Runtime error
Runtime error
File size: 3,604 Bytes
c8f03da d7f32ed c8f03da 49158eb c8f03da e68e9cf c8f03da d5471e9 c8f03da e68e9cf c8f03da 29331bd c8f03da d5471e9 0288607 c8f03da d5471e9 c8f03da 808ec17 c8f03da 1cb9532 c8f03da d5471e9 c8f03da d5471e9 c8f03da d5471e9 c8f03da d5471e9 c8f03da 03991d8 c8f03da cc3751a c8f03da 808ec17 |
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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from hugchat import hugchat
from hugchat.login import Login
from dotenv import load_dotenv
from contextlib import asynccontextmanager
import logging
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Load environment variables
load_dotenv()
# Initialize FastAPI app
app = FastAPI()
# HuggingFace credentials from environment variables
EMAIL = "[email protected]"
PASSWORD = "Allahisgreatest17"
ASSISTANT_ID = "682e0c1f5f0c3d952a27498e"
# Cookie directory path
COOKIE_PATH_DIR = "./cookies/"
# Global chatbot instance
chatbot = None
# Pydantic model for request body
class PromptRequest(BaseModel):
prompt: str
# Ensure cookie directory exists
def ensure_cookie_directory():
if not os.path.exists(COOKIE_PATH_DIR):
try:
os.makedirs(COOKIE_PATH_DIR)
logger.info("Created cookie directory: %s", COOKIE_PATH_DIR)
except Exception as e:
logger.error("Failed to create cookie directory: %s", str(e))
raise
# Lifespan handler for startup and shutdown
@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")
# Ensure cookie directory exists
ensure_cookie_directory()
# Log in to HuggingFace
sign = Login(EMAIL, PASSWORD)
try:
cookies = sign.login(cookie_path_dir=COOKIE_PATH_DIR, save_cookies=True)
logger.info("Successfully logged in to HuggingFace with cookie_path_dir")
except TypeError as e:
logger.warning("cookie_path_dir not supported, trying default cookie storage: %s", str(e))
cookies = sign.login(save_cookies=True) # Fallback to default cookie storage
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)}")
|