Spaces:
Runtime error
Runtime error
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,12 +1,26 @@
|
|
| 1 |
from fastapi import FastAPI, HTTPException
|
| 2 |
from fastapi.responses import StreamingResponse
|
|
|
|
| 3 |
from pydantic import BaseModel
|
| 4 |
from hugchat import hugchat
|
| 5 |
from hugchat.login import Login
|
| 6 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
# Pydantic model for request body
|
| 11 |
class QuestionRequest(BaseModel):
|
| 12 |
question: str
|
|
@@ -28,15 +42,23 @@ def setup_chatbot(email, password, cookie_path, assistant_id):
|
|
| 28 |
hugchat.ChatBot: Configured chatbot instance
|
| 29 |
"""
|
| 30 |
try:
|
|
|
|
| 31 |
# Create cookie directory if it doesn't exist
|
| 32 |
os.makedirs(cookie_path, exist_ok=True)
|
| 33 |
|
|
|
|
| 34 |
sign = Login(email, password)
|
| 35 |
cookies = sign.login(cookie_dir_path=cookie_path, save_cookies=True)
|
|
|
|
|
|
|
| 36 |
chatbot = hugchat.ChatBot(cookies=cookies.get_dict())
|
|
|
|
|
|
|
| 37 |
chatbot.new_conversation(assistant=assistant_id, switch_to=True)
|
|
|
|
| 38 |
return chatbot
|
| 39 |
except Exception as e:
|
|
|
|
| 40 |
raise Exception(f"Failed to set up chatbot: {e}")
|
| 41 |
|
| 42 |
# Initialize chatbot at startup
|
|
@@ -49,7 +71,10 @@ async def startup_event():
|
|
| 49 |
COOKIE_PATH_DIR = "./cookies/"
|
| 50 |
ASSISTANT_ID = "682e0c1f5f0c3d952a27498e" # Replace with your actual assistant ID
|
| 51 |
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
@app.post("/generate")
|
| 55 |
async def generate_response(request: QuestionRequest):
|
|
@@ -64,22 +89,36 @@ async def generate_response(request: QuestionRequest):
|
|
| 64 |
"""
|
| 65 |
global chatbot
|
| 66 |
if chatbot is None:
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
async def generate():
|
| 70 |
try:
|
|
|
|
| 71 |
# Use streaming to match client expectations
|
| 72 |
for token in chatbot.chat(request.question, stream=True):
|
| 73 |
# Handle hugchat response (token may be dict or string)
|
| 74 |
if isinstance(token, dict):
|
| 75 |
-
# Extract token from dictionary (e.g., {"type": "stream", "token": "text"})
|
| 76 |
token_text = token.get("token", "")
|
| 77 |
else:
|
| 78 |
token_text = str(token)
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
except Exception as e:
|
|
|
|
| 83 |
error_message = f"Error: Failed to generate response: {str(e)}"
|
| 84 |
yield error_message.encode('utf-8')
|
| 85 |
|
|
|
|
| 1 |
from fastapi import FastAPI, HTTPException
|
| 2 |
from fastapi.responses import StreamingResponse
|
| 3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
from pydantic import BaseModel
|
| 5 |
from hugchat import hugchat
|
| 6 |
from hugchat.login import Login
|
| 7 |
import os
|
| 8 |
+
import logging
|
| 9 |
+
|
| 10 |
+
# Set up logging
|
| 11 |
+
logging.basicConfig(level=logging.INFO)
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
app = FastAPI()
|
| 15 |
|
| 16 |
+
# Enable CORS for client compatibility
|
| 17 |
+
app.add_middleware(
|
| 18 |
+
CORSMiddleware,
|
| 19 |
+
allow_origins=["*"],
|
| 20 |
+
allow_methods=["*"],
|
| 21 |
+
allow_headers=["*"],
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
# Pydantic model for request body
|
| 25 |
class QuestionRequest(BaseModel):
|
| 26 |
question: str
|
|
|
|
| 42 |
hugchat.ChatBot: Configured chatbot instance
|
| 43 |
"""
|
| 44 |
try:
|
| 45 |
+
logger.info("Setting up chatbot...")
|
| 46 |
# Create cookie directory if it doesn't exist
|
| 47 |
os.makedirs(cookie_path, exist_ok=True)
|
| 48 |
|
| 49 |
+
logger.info("Logging in with Hugging Face credentials...")
|
| 50 |
sign = Login(email, password)
|
| 51 |
cookies = sign.login(cookie_dir_path=cookie_path, save_cookies=True)
|
| 52 |
+
|
| 53 |
+
logger.info("Initializing ChatBot...")
|
| 54 |
chatbot = hugchat.ChatBot(cookies=cookies.get_dict())
|
| 55 |
+
|
| 56 |
+
logger.info(f"Creating new conversation with assistant ID: {assistant_id}")
|
| 57 |
chatbot.new_conversation(assistant=assistant_id, switch_to=True)
|
| 58 |
+
logger.info("Chatbot setup complete.")
|
| 59 |
return chatbot
|
| 60 |
except Exception as e:
|
| 61 |
+
logger.error(f"Failed to set up chatbot: {str(e)}")
|
| 62 |
raise Exception(f"Failed to set up chatbot: {e}")
|
| 63 |
|
| 64 |
# Initialize chatbot at startup
|
|
|
|
| 71 |
COOKIE_PATH_DIR = "./cookies/"
|
| 72 |
ASSISTANT_ID = "682e0c1f5f0c3d952a27498e" # Replace with your actual assistant ID
|
| 73 |
|
| 74 |
+
try:
|
| 75 |
+
chatbot = setup_chatbot(EMAIL, PASSWD, COOKIE_PATH_DIR, ASSISTANT_ID)
|
| 76 |
+
except Exception as e:
|
| 77 |
+
logger.error(f"Startup error: {str(e)}")
|
| 78 |
|
| 79 |
@app.post("/generate")
|
| 80 |
async def generate_response(request: QuestionRequest):
|
|
|
|
| 89 |
"""
|
| 90 |
global chatbot
|
| 91 |
if chatbot is None:
|
| 92 |
+
logger.error("Chatbot not initialized.")
|
| 93 |
+
async def generate_error():
|
| 94 |
+
error_message = "Error: Chatbot not initialized. Please try again later."
|
| 95 |
+
yield error_message.encode('utf-8')
|
| 96 |
+
return StreamingResponse(generate_error(), media_type="text/plain")
|
| 97 |
|
| 98 |
async def generate():
|
| 99 |
try:
|
| 100 |
+
logger.info(f"Processing question: {request.question}")
|
| 101 |
# Use streaming to match client expectations
|
| 102 |
for token in chatbot.chat(request.question, stream=True):
|
| 103 |
# Handle hugchat response (token may be dict or string)
|
| 104 |
if isinstance(token, dict):
|
|
|
|
| 105 |
token_text = token.get("token", "")
|
| 106 |
else:
|
| 107 |
token_text = str(token)
|
| 108 |
|
| 109 |
+
if token_text:
|
| 110 |
+
logger.debug(f"Streaming token: {token_text}")
|
| 111 |
+
yield token_text.encode('utf-8')
|
| 112 |
+
else:
|
| 113 |
+
logger.warning("Empty token received.")
|
| 114 |
+
|
| 115 |
+
# Fallback response if no tokens were yielded
|
| 116 |
+
if not any(True for _ in chatbot.chat(request.question, stream=True)):
|
| 117 |
+
fallback = "Welcome, valued client! How can Abdullah Ali and our premium team bring your vision to life with a custom website ($200–$600) or AI chatbot ($119)?"
|
| 118 |
+
logger.info("Using fallback response.")
|
| 119 |
+
yield fallback.encode('utf-8')
|
| 120 |
except Exception as e:
|
| 121 |
+
logger.error(f"Failed to generate response: {str(e)}")
|
| 122 |
error_message = f"Error: Failed to generate response: {str(e)}"
|
| 123 |
yield error_message.encode('utf-8')
|
| 124 |
|