abdullahalioo commited on
Commit
49158eb
·
verified ·
1 Parent(s): 664b22f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +61 -21
main.py CHANGED
@@ -1,30 +1,70 @@
 
1
  from hugchat import hugchat
2
  from hugchat.login import Login
3
  import os
4
 
5
- # Credentials
6
- EMAIL = os.getenv("EMAIL")
7
- PASSWD = os.getenv("PASSWD")
8
 
9
- # Path to store cookies
10
- cookie_path_dir = "./cookies/" # Make sure this directory exists
11
 
12
- # Log in and get cookies
13
- sign = Login(EMAIL, PASSWD)
14
- cookies = sign.login(cookie_dir_path=cookie_path_dir, save_cookies=True)
15
-
16
- # Create ChatBot with cookies
17
- chatbot = hugchat.ChatBot(cookies=cookies.get_dict())
18
-
19
- # 🔁 Create a new conversation with a custom assistant ID
20
- ASSISTANT_ID = "66017fca58d60bd7d5c5c26c" # Replace with your actual assistant ID
21
- chatbot.new_conversation(assistant=ASSISTANT_ID, switch_to=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
- # 🔁 Stream response character-by-character as it generates
24
- print("Assistant:", end=" ", flush=True)
25
- for token in chatbot.chat("Hello, how can I help you today?", stream=True):
 
 
 
 
 
 
26
 
 
27
 
28
- # Optionally: web search example
29
- # response = chatbot.chat("How many models stored in huggingface?", web_search=True)
30
- # print("\n\nWeb Search Result:", response.wait_until_done())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Query
2
  from hugchat import hugchat
3
  from hugchat.login import Login
4
  import os
5
 
6
+ app = FastAPI()
 
 
7
 
8
+ # Global variable to store the chatbot instance
9
+ chatbot = None
10
 
11
+ def setup_chatbot(email, password, cookie_path, assistant_id):
12
+ """
13
+ Sets up the Hugging Face chatbot with login and conversation.
14
+
15
+ Args:
16
+ email (str): User email for login
17
+ password (str): User password for login
18
+ cookie_path (str): Directory to store cookies
19
+ assistant_id (str): ID of the assistant to use
20
+
21
+ Returns:
22
+ hugchat.ChatBot: Configured chatbot instance
23
+ """
24
+ try:
25
+ # Create cookie directory if it doesn't exist
26
+ os.makedirs(cookie_path, exist_ok=True)
27
+
28
+ sign = Login(email, password)
29
+ cookies = sign.login(cookie_dir_path=cookie_path, save_cookies=True)
30
+ chatbot = hugchat.ChatBot(cookies=cookies.get_dict())
31
+ chatbot.new_conversation(assistant=assistant_id, switch_to=True)
32
+ return chatbot
33
+ except Exception as e:
34
+ raise Exception(f"Failed to set up chatbot: {e}")
35
 
36
+ # Initialize chatbot at startup
37
+ @app.on_event("startup")
38
+ async def startup_event():
39
+ global chatbot
40
+ # Credentials and configuration
41
+ EMAIL = os.getenv("EMAIL")
42
+ PASSWD = os.getenv("PASSWD")
43
+ COOKIE_PATH_DIR = "./cookies/"
44
+ ASSISTANT_ID = "682e0c1f5f0c3d952a27498e" # Replace with your actual assistant ID
45
 
46
+ chatbot = setup_chatbot(EMAIL, PASSWD, COOKIE_PATH_DIR, ASSISTANT_ID)
47
 
48
+ @app.post("/generate")
49
+ async def generate_response(
50
+ prompt: str = Query(..., description="The prompt for the AI")
51
+ ):
52
+ """
53
+ Generates a response from the AI based on the provided prompt.
54
+
55
+ Args:
56
+ prompt (str): The user's input prompt for the AI.
57
+
58
+ Returns:
59
+ dict: A dictionary containing the AI's response or an error message.
60
+ """
61
+ global chatbot
62
+ if chatbot is None:
63
+ return {"error": "Chatbot not initialized. Please try again later."}
64
+
65
+ try:
66
+ # Generate response (non-streaming for simplicity in API context)
67
+ response = chatbot.chat(prompt, stream=False)
68
+ return {"response": response}
69
+ except Exception as e:
70
+ return {"error": f"Failed to generate response: {str(e)}"}