abdullahalioo commited on
Commit
c8f03da
·
verified ·
1 Parent(s): e68e9cf

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +80 -18
main.py CHANGED
@@ -1,31 +1,93 @@
 
 
 
1
  from hugchat import hugchat
2
  from hugchat.login import Login
3
- import fastapi
4
- from fastapi import FastAPI, Query
 
 
 
 
 
 
 
 
 
 
5
  app = FastAPI()
6
- # Your HuggingFace credentials
 
 
7
  EMAIL = "[email protected]"
8
  PASSWORD = "Allahisgreatest17"
9
- @app.post("/ask")
10
- def main(prompt: str = Query(..., description="The prompt for the AI")):
11
- # Login and save cookies (optional cookie path omitted for simplicity)
12
- sign = Login(EMAIL, PASSWORD)
13
- cookies = sign.login(save_cookies=True)
 
 
14
 
15
- # Initialize chatbot with cookies
16
- chatbot = hugchat.ChatBot(cookies=cookies.get_dict())
 
17
 
18
- # Start a new conversation with your assistant ID
19
- ASSISTANT_ID = "682e0c1f5f0c3d952a27498e" # Replace with your assistant ID
20
- chatbot.new_conversation(assistant=ASSISTANT_ID, switch_to=True)
 
 
21
 
22
- # Send message and get the full response (no streaming)
23
- response = chatbot.chat(f"{prompt}", stream=False)
 
 
 
 
 
 
 
24
 
25
- # Print full response
26
- print("Assistant:", response)
27
- return response
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
 
 
 
30
 
 
 
 
 
 
31
 
 
1
+ import os
2
+ from fastapi import FastAPI, HTTPException
3
+ from pydantic import BaseModel
4
  from hugchat import hugchat
5
  from hugchat.login import Login
6
+ from dotenv import load_dotenv
7
+ from contextlib import asynccontextmanager
8
+ import logging
9
+
10
+ # Set up logging
11
+ logging.basicConfig(level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # Load environment variables
15
+ load_dotenv()
16
+
17
+ # Initialize FastAPI app
18
  app = FastAPI()
19
+
20
+ # HuggingFace credentials from environment variables
21
+ # HuggingFace credentials from environment variables
22
  EMAIL = "[email protected]"
23
  PASSWORD = "Allahisgreatest17"
24
+ ASSISTANT_ID = "682e0c1f5f0c3d952a27498e"
25
+
26
+ # Cookie directory path
27
+ COOKIE_PATH_DIR = "./cookies/"
28
+
29
+ # Global chatbot instance
30
+ chatbot = None
31
 
32
+ # Pydantic model for request body
33
+ class PromptRequest(BaseModel):
34
+ prompt: str
35
 
36
+ # Ensure cookie directory exists
37
+ def ensure_cookie_directory():
38
+ if not os.path.exists(COOKIE_PATH_DIR):
39
+ os.makedirs(COOKIE_PATH_DIR)
40
+ logger.info("Created cookie directory: %s", COOKIE_PATH_DIR)
41
 
42
+ # Lifespan handler for startup and shutdown
43
+ @asynccontextmanager
44
+ async def lifespan(app: FastAPI):
45
+ # Startup: Initialize chatbot
46
+ global chatbot
47
+ try:
48
+ # Validate credentials
49
+ if not EMAIL or not PASSWORD or not ASSISTANT_ID:
50
+ raise ValueError("HuggingFace credentials or assistant ID not provided in environment variables")
51
 
52
+ # Ensure cookie directory exists
53
+ ensure_cookie_directory()
 
54
 
55
+ # Log in to HuggingFace
56
+ sign = Login(EMAIL, PASSWORD)
57
+ cookies = sign.login(cookie_path_dir=COOKIE_PATH_DIR, save_cookies=True)
58
+ logger.info("Successfully logged in to HuggingFace")
59
+
60
+ # Initialize chatbot
61
+ chatbot = hugchat.ChatBot(cookies=cookies.get_dict())
62
+ # Start a new conversation
63
+ chatbot.new_conversation(assistant=ASSISTANT_ID, switch_to=True)
64
+ logger.info("Chatbot initialized with assistant ID: %s", ASSISTANT_ID)
65
+ except Exception as e:
66
+ logger.error("Failed to initialize chatbot: %s", str(e))
67
+ raise HTTPException(status_code=500, detail="Failed to initialize chatbot")
68
+
69
+ yield # Application runs here
70
+
71
+ # Shutdown: Clean up (optional)
72
+ logger.info("Shutting down application")
73
+
74
+ # Attach lifespan handler to FastAPI app
75
+ app.lifespan = lifespan
76
+
77
+ # Endpoint to handle chat requests
78
+ @app.post("/ask")
79
+ async def ask(prompt_request: PromptRequest):
80
+ try:
81
+ if not chatbot:
82
+ raise HTTPException(status_code=500, detail="Chatbot not initialized")
83
 
84
+ # Send prompt to chatbot
85
+ response = chatbot.chat(prompt_request.prompt, stream=False)
86
+ logger.info("Received response for prompt: %s", prompt_request.prompt)
87
 
88
+ # Return structured response
89
+ return {"status": "success", "response": response}
90
+ except Exception as e:
91
+ logger.error("Error processing request: %s", str(e))
92
+ raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
93