Spaces:
Runtime error
Runtime error
from fastapi import FastAPI | |
from pydantic import BaseModel | |
from fastapi.middleware.cors import CORSMiddleware | |
from fastapi.responses import StreamingResponse | |
from hugchat import hugchat | |
from hugchat.login import Login | |
import asyncio | |
import os | |
from dotenv import load_dotenv | |
# Load environment variables from .env file | |
load_dotenv() | |
# Read credentials from environment variables | |
EMAIL = os.getenv("EMAIL") | |
PASSWD = os.getenv("PASSWD") | |
# Cookie storage | |
cookie_path_dir = "./cookies/" | |
os.makedirs(cookie_path_dir, exist_ok=True) | |
# HugChat login | |
sign = Login(EMAIL, PASSWD) | |
cookies = sign.login(cookie_dir_path=cookie_path_dir, save_cookies=True) | |
# Create chatbot instance | |
chatbot = hugchat.ChatBot(cookies=cookies.get_dict()) | |
# Optional: Use assistant ID | |
ASSISTANT_ID = "66017fca58d60bd7d5c5c26c" # Replace if needed | |
chatbot.new_conversation(assistant=ASSISTANT_ID, switch_to=True) | |
# 🔁 Stream response character-by-character as it generates | |
print("Assistant:", end=" ", flush=True) | |
for token in chatbot.chat("Hello, how can I help you today?", stream=True): | |
print(token, end="", flush=True) | |
# Optionally: web search example | |
# response = chatbot.chat("How many models stored in huggingface?", web_search=True) | |
# print("\n\nWeb Search Result:", response.wait_until_done()) | |