dwfwfwfwf commited on
Commit
efc8e53
·
verified ·
1 Parent(s): 70a8026

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +411 -0
app.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import uuid
4
+ from typing import List, Dict, Optional, Union, Generator, Any
5
+
6
+ from fastapi import FastAPI, HTTPException, Request, status
7
+ from fastapi.responses import StreamingResponse, JSONResponse
8
+ from pydantic import BaseModel, Field
9
+ import uvicorn
10
+
11
+ from hugchat import hugchat
12
+ from hugchat.login import Login
13
+ # from hugchat.types.message import MessageNode # For type hinting if needed
14
+
15
+ # --- Configuration ---
16
+ HF_EMAIL = "xawet73334@magpit.com"
17
+ HF_PASSWD = "Xawet73334@magpit.com"
18
+ COOKIE_PATH_DIR = "./hugchat_cookies/"
19
+
20
+ if not HF_EMAIL or not HF_PASSWD:
21
+ print("Warning: HUGGINGFACE_EMAIL or HUGGINGFACE_PASSWD environment variables not set.")
22
+ # Allow running without credentials if cookies already exist, for example.
23
+ # The startup logic will handle login/cookie loading.
24
+
25
+ # --- Global HugChatBot instance and model info ---
26
+ chatbot: Optional[hugchat.ChatBot] = None
27
+ available_models_list: List[str] = []
28
+ available_models_map: Dict[str, int] = {} # Maps model name to index
29
+ current_llm_model_on_chatbot: Optional[str] = None
30
+ server_start_time = int(time.time()) # For 'created' timestamps
31
+
32
+ # --- Pydantic Models for OpenAI Compatibility ---
33
+
34
+ # Model for /v1/models
35
+ class ModelCard(BaseModel):
36
+ id: str
37
+ object: str = "model"
38
+ created: int = Field(default_factory=lambda: server_start_time)
39
+ owned_by: str = "huggingface" # Or parse from model ID if possible
40
+ # Add other common fields if desired, often with default/null values
41
+ # permission: Optional[List[Any]] = None
42
+ # root: Optional[str] = None
43
+ # parent: Optional[str] = None
44
+
45
+ class ModelList(BaseModel):
46
+ object: str = "list"
47
+ data: List[ModelCard]
48
+
49
+ # Models for /v1/chat/completions (from previous example)
50
+ class ChatMessage(BaseModel):
51
+ role: str
52
+ content: str
53
+ # name: Optional[str] = None # For function calling, not directly supported by hugchat
54
+
55
+ class ChatCompletionRequest(BaseModel):
56
+ model: str
57
+ messages: List[ChatMessage]
58
+ stream: Optional[bool] = False
59
+ temperature: Optional[float] = Field(None, ge=0.0, le=2.0) # hugchat might not support all
60
+ top_p: Optional[float] = Field(None, ge=0.0, le=1.0) # these params directly
61
+ n: Optional[int] = Field(None, ge=1) # often n=1 for chat
62
+ max_tokens: Optional[int] = Field(None, ge=1)
63
+ # presence_penalty: Optional[float] = None
64
+ # frequency_penalty: Optional[float] = None
65
+ # logit_bias: Optional[Dict[str, float]] = None
66
+ # user: Optional[str] = None # For tracking, not used by hugchat
67
+ # stop: Optional[Union[str, List[str]]] = None # hugchat handles its own stop
68
+
69
+ class DeltaMessage(BaseModel):
70
+ role: Optional[str] = None
71
+ content: Optional[str] = None
72
+
73
+ class ChatCompletionChunkChoice(BaseModel):
74
+ index: int = 0
75
+ delta: DeltaMessage
76
+ finish_reason: Optional[str] = None # "stop", "length", "content_filter", "tool_calls"
77
+
78
+ class ChatCompletionChunk(BaseModel):
79
+ id: str
80
+ object: str = "chat.completion.chunk"
81
+ created: int = Field(default_factory=lambda: int(time.time()))
82
+ model: str
83
+ # system_fingerprint: Optional[str] = None # OpenAI specific
84
+ choices: List[ChatCompletionChunkChoice]
85
+
86
+ class ResponseMessage(BaseModel):
87
+ role: str
88
+ content: str
89
+ # tool_calls: Optional[List[Any]] = None # For function/tool calling
90
+
91
+ class ChatCompletionChoice(BaseModel):
92
+ index: int = 0
93
+ message: ResponseMessage
94
+ finish_reason: str = "stop"
95
+ # logprobs: Optional[Any] = None
96
+
97
+ class UsageInfo(BaseModel): # Mocked, as hugchat doesn't provide token counts
98
+ prompt_tokens: int = 0
99
+ completion_tokens: int = 0
100
+ total_tokens: int = 0
101
+
102
+ class ChatCompletionResponse(BaseModel):
103
+ id: str
104
+ object: str = "chat.completion"
105
+ created: int = Field(default_factory=lambda: int(time.time()))
106
+ model: str
107
+ # system_fingerprint: Optional[str] = None
108
+ choices: List[ChatCompletionChoice]
109
+ usage: Optional[UsageInfo] = Field(default_factory=lambda: UsageInfo())
110
+
111
+
112
+ # --- FastAPI App ---
113
+ app = FastAPI(
114
+ title="HugChat OpenAI-Compatible API",
115
+ description="An OpenAI-compatible API wrapper for HuggingChat.",
116
+ version="0.1.1" # Incremented version
117
+ )
118
+
119
+ @app.on_event("startup")
120
+ async def startup_event():
121
+ global chatbot, available_models_list, available_models_map, current_llm_model_on_chatbot
122
+ print("Initializing HugChatBot...")
123
+ try:
124
+ if not os.path.exists(COOKIE_PATH_DIR):
125
+ os.makedirs(COOKIE_PATH_DIR)
126
+
127
+ if not HF_EMAIL or not HF_PASSWD:
128
+ print("Attempting to load cookies directly as credentials are not fully set.")
129
+ # Try to create a Login object just to access cookie loading methods
130
+ # This part might need adjustment based on how Login handles missing credentials
131
+ temp_sign = Login(HF_EMAIL or "dummy_email", None) # Pass dummy email if HF_EMAIL is None
132
+ cookies = temp_sign.loadCookiesFromDir(cookie_dir_path=COOKIE_PATH_DIR)
133
+ if not cookies:
134
+ raise ValueError("Credentials not set and no saved cookies found. Please set HUGGINGFACE_EMAIL and HUGGINGFACE_PASSWD or ensure cookies are present.")
135
+ print("Loaded cookies from disk.")
136
+ else:
137
+ sign = Login(HF_EMAIL, HF_PASSWD)
138
+ cookies = sign.login(cookie_dir_path=COOKIE_PATH_DIR, save_cookies=True)
139
+
140
+ chatbot = hugchat.ChatBot(cookies=cookies.get_dict())
141
+ print("HugChatBot initialized successfully.")
142
+
143
+ models_raw = chatbot.get_available_llm_models()
144
+ if not models_raw:
145
+ print("Warning: No available LLM models found from HugChat.")
146
+ return
147
+
148
+ available_models_list = [str(model_name) for model_name in models_raw]
149
+ available_models_map = {name: i for i, name in enumerate(available_models_list)}
150
+ print(f"Available models: {available_models_list}")
151
+
152
+ if available_models_list:
153
+ default_model_index = 0
154
+ chatbot.switch_llm(default_model_index)
155
+ current_llm_model_on_chatbot = available_models_list[default_model_index]
156
+ chatbot.new_conversation(switch_to=True) # Ensure new convo uses this model
157
+ print(f"Default model set to: {current_llm_model_on_chatbot}")
158
+ else:
159
+ print("No models available to set a default.")
160
+
161
+ except Exception as e:
162
+ print(f"Error during HugChatBot initialization: {e}")
163
+ chatbot = None
164
+
165
+ # --- Helper for Unsupported Endpoints ---
166
+ def not_supported_response(feature: str):
167
+ return JSONResponse(
168
+ status_code=status.HTTP_501_NOT_IMPLEMENTED,
169
+ content={"error": {
170
+ "message": f"The '{feature}' feature is not supported by this HugChat-backed API.",
171
+ "type": "not_supported_error",
172
+ "param": None,
173
+ "code": None
174
+ }}
175
+ )
176
+
177
+ # --- API Endpoints ---
178
+
179
+ @app.get("/v1/models", response_model=ModelList)
180
+ async def list_models():
181
+ if chatbot is None or not available_models_list:
182
+ raise HTTPException(status_code=503, detail="Models list not available. HugChatBot might not be initialized or no models found.")
183
+
184
+ model_cards = []
185
+ for model_id_str in available_models_list:
186
+ owned_by = "huggingface" # Default
187
+ if "/" in model_id_str:
188
+ # Try to extract owner from "owner/model_name" format
189
+ possible_owner = model_id_str.split('/')[0]
190
+ if possible_owner: # Basic check
191
+ owned_by = possible_owner
192
+
193
+ model_cards.append(ModelCard(id=model_id_str, owned_by=owned_by, created=server_start_time))
194
+
195
+ return ModelList(data=model_cards)
196
+
197
+ @app.get("/v1/models/{model_id}", response_model=ModelCard)
198
+ async def retrieve_model(model_id: str):
199
+ if chatbot is None or not available_models_list:
200
+ raise HTTPException(status_code=503, detail="Model information not available. HugChatBot might not be initialized.")
201
+
202
+ if model_id in available_models_list:
203
+ owned_by = "huggingface"
204
+ if "/" in model_id:
205
+ possible_owner = model_id.split('/')[0]
206
+ if possible_owner:
207
+ owned_by = possible_owner
208
+ return ModelCard(id=model_id, owned_by=owned_by, created=server_start_time)
209
+ else:
210
+ raise HTTPException(status_code=404, detail=f"Model '{model_id}' not found.")
211
+
212
+
213
+ @app.post("/v1/chat/completions") # response_model removed for StreamingResponse flexibility
214
+ async def chat_completions_endpoint(request: ChatCompletionRequest):
215
+ global chatbot, current_llm_model_on_chatbot
216
+
217
+ if chatbot is None:
218
+ raise HTTPException(status_code=503, detail="HugChatBot is not available. Check server logs.")
219
+ if not available_models_map:
220
+ raise HTTPException(status_code=503, detail="No LLM models loaded from HugChat.")
221
+
222
+ requested_model = request.model
223
+ if requested_model not in available_models_map:
224
+ raise HTTPException(
225
+ status_code=400,
226
+ detail=f"Model '{requested_model}' not found. Available models: {', '.join(available_models_list)}"
227
+ )
228
+
229
+ if current_llm_model_on_chatbot != requested_model:
230
+ print(f"Switching model from '{current_llm_model_on_chatbot}' to '{requested_model}'...")
231
+ try:
232
+ model_index = available_models_map[requested_model]
233
+ chatbot.switch_llm(model_index)
234
+ current_llm_model_on_chatbot = requested_model
235
+ print(f"Model switched. Creating new conversation for model: {current_llm_model_on_chatbot}")
236
+ except Exception as e:
237
+ raise HTTPException(status_code=500, detail=f"Failed to switch model: {e}")
238
+
239
+ try:
240
+ chatbot.new_conversation(switch_to=True) # Ensure new conversation for this request
241
+ # convo_info = chatbot.get_conversation_info()
242
+ # print(f"New conversation started. Active model: {convo_info.model}")
243
+ except Exception as e:
244
+ raise HTTPException(status_code=500, detail=f"Failed to create new conversation: {e}")
245
+
246
+ last_user_message_content = ""
247
+ # OpenAI typically expects a sequence. We'll primarily use the last user message for hugchat.
248
+ # For a more complex setup, one could try to feed prior messages if hugchat supported it explicitly
249
+ # in a single `chat` call beyond its internal memory.
250
+ for msg in reversed(request.messages):
251
+ if msg.role == "user":
252
+ last_user_message_content = msg.content
253
+ break
254
+
255
+ if not last_user_message_content:
256
+ # Check for system prompt if no user prompt and it's the only message.
257
+ # Though typically OpenAI clients send at least one user message.
258
+ if len(request.messages) == 1 and request.messages[0].role == "system":
259
+ last_user_message_content = request.messages[0].content # Use system as prompt
260
+ else:
261
+ raise HTTPException(status_code=400, detail="No user message found or suitable prompt in the request.")
262
+
263
+ prompt = last_user_message_content
264
+ chat_id = f"chatcmpl-{uuid.uuid4().hex}"
265
+ request_time = int(time.time())
266
+
267
+ # Handle unsupported parameters (informatively, but hugchat will ignore them)
268
+ if request.temperature is not None and request.temperature != 1.0: # Default OpenAI temp
269
+ print(f"Info: 'temperature' parameter ({request.temperature}) received but may not be supported by HugChat.")
270
+ if request.max_tokens is not None:
271
+ print(f"Info: 'max_tokens' parameter ({request.max_tokens}) received but may not be supported by HugChat.")
272
+ # ... (similar for other params like top_p, n, etc.)
273
+
274
+ if request.stream:
275
+ async def stream_generator():
276
+ try:
277
+ first_chunk_data = ChatCompletionChunk(
278
+ id=chat_id,
279
+ created=request_time,
280
+ model=current_llm_model_on_chatbot,
281
+ choices=[ChatCompletionChunkChoice(delta=DeltaMessage(role="assistant"))]
282
+ )
283
+ yield f"data: {first_chunk_data.model_dump_json(exclude_none=True)}\n\n"
284
+
285
+ full_response_text = ""
286
+ # The hugchat stream yields text chunks
287
+ for chunk_text in chatbot.chat(prompt, stream=True):
288
+ if isinstance(chunk_text, str):
289
+ full_response_text += chunk_text
290
+ chunk_data = ChatCompletionChunk(
291
+ id=chat_id,
292
+ created=request_time,
293
+ model=current_llm_model_on_chatbot,
294
+ choices=[ChatCompletionChunkChoice(delta=DeltaMessage(content=chunk_text))]
295
+ )
296
+ yield f"data: {chunk_data.model_dump_json(exclude_none=True)}\n\n"
297
+ # Add handling for other types if hugchat stream changes
298
+
299
+ # print(f"Stream complete. Full text for chat {chat_id}: {full_response_text[:100]}...")
300
+
301
+ final_chunk_data = ChatCompletionChunk(
302
+ id=chat_id,
303
+ created=request_time,
304
+ model=current_llm_model_on_chatbot,
305
+ choices=[ChatCompletionChunkChoice(delta=DeltaMessage(), finish_reason="stop")]
306
+ )
307
+ yield f"data: {final_chunk_data.model_dump_json(exclude_none=True)}\n\n"
308
+ yield "data: [DONE]\n\n"
309
+ except Exception as e:
310
+ print(f"Error during streaming for chat {chat_id}: {e}")
311
+ # Attempt to send an error in the stream if possible (before [DONE])
312
+ # This is non-standard for OpenAI, but useful for debugging
313
+ error_content = f"Error during stream: {str(e)}"
314
+ error_delta = DeltaMessage(content=error_content)
315
+ error_choice = ChatCompletionChunkChoice(delta=error_delta, finish_reason="error") # Custom
316
+ error_chunk = ChatCompletionChunk(
317
+ id=chat_id, created=request_time, model=current_llm_model_on_chatbot, choices=[error_choice]
318
+ )
319
+ try:
320
+ yield f"data: {error_chunk.model_dump_json(exclude_none=True)}\n\n"
321
+ except Exception: # If stream already broken
322
+ pass
323
+ yield "data: [DONE]\n\n" # Always end with [DONE]
324
+
325
+ return StreamingResponse(stream_generator(), media_type="text/event-stream")
326
+ else: # Non-streaming
327
+ try:
328
+ # Assuming chatbot.chat() with stream=False returns a result object
329
+ # that has wait_until_done() or .text attribute.
330
+ message_result = chatbot.chat(prompt) # hugchat's non-stream returns a Message object
331
+
332
+ response_text: str
333
+ if hasattr(message_result, 'wait_until_done'): # If it's a generator-like object
334
+ response_text = message_result.wait_until_done()
335
+ elif hasattr(message_result, 'text'): # If it's a MessageNode or similar
336
+ response_text = message_result.text
337
+ elif isinstance(message_result, str): # Direct string response
338
+ response_text = message_result
339
+ else:
340
+ print(f"Warning: Unexpected response type from chatbot.chat() (non-stream): {type(message_result)}")
341
+ # Attempt to convert to string as a fallback
342
+ try:
343
+ response_text = str(message_result)
344
+ except:
345
+ raise ValueError("Could not extract text from HugChat response.")
346
+
347
+ # print(f"Non-streamed response for chat {chat_id} / model {current_llm_model_on_chatbot}: {response_text[:100]}...")
348
+ return ChatCompletionResponse(
349
+ id=chat_id,
350
+ created=request_time,
351
+ model=current_llm_model_on_chatbot,
352
+ choices=[
353
+ ChatCompletionChoice(
354
+ message=ResponseMessage(role="assistant", content=response_text)
355
+ )
356
+ ],
357
+ usage=UsageInfo() # Mocked usage
358
+ )
359
+ except Exception as e:
360
+ print(f"Error processing non-streaming chat {chat_id}: {e}")
361
+ raise HTTPException(status_code=500, detail=f"Error processing non-streaming chat: {e}")
362
+
363
+
364
+ # --- Placeholder/Not Implemented Endpoints ---
365
+ @app.post("/v1/completions")
366
+ async def completions_legacy():
367
+ return not_supported_response("Legacy completions (/v1/completions)")
368
+
369
+ @app.post("/v1/embeddings")
370
+ async def create_embeddings():
371
+ return not_supported_response("Embeddings (/v1/embeddings)")
372
+
373
+ @app.post("/v1/audio/transcriptions")
374
+ async def audio_transcriptions():
375
+ return not_supported_response("Audio transcriptions")
376
+
377
+ @app.post("/v1/audio/translations")
378
+ async def audio_translations():
379
+ return not_supported_response("Audio translations")
380
+
381
+ @app.post("/v1/images/generations")
382
+ async def image_generations():
383
+ # Note: HuggingChat *can* have image generation assistants.
384
+ # A more advanced version could try to map this if a specific assistant ID is known
385
+ # and the request format can be adapted. For now, marking as generally not supported.
386
+ return not_supported_response("Image generations (generic API, specific assistants might work via chat)")
387
+
388
+ @app.get("/v1/files")
389
+ async def list_files_openai(): # Renamed to avoid conflict if you had other /files
390
+ return not_supported_response("File listing/management")
391
+
392
+ @app.post("/v1/files")
393
+ async def upload_file_openai():
394
+ return not_supported_response("File upload")
395
+
396
+ # ... (add more placeholders for fine-tuning, moderations etc. as needed)
397
+
398
+ if __name__ == "__main__":
399
+ if not os.path.exists(COOKIE_PATH_DIR):
400
+ try:
401
+ os.makedirs(COOKIE_PATH_DIR)
402
+ print(f"Created directory: {COOKIE_PATH_DIR}")
403
+ except OSError as e:
404
+ print(f"Error creating directory {COOKIE_PATH_DIR}: {e}")
405
+ # Decide if to exit or continue if dir creation fails
406
+ # exit(1)
407
+
408
+ print("Starting Uvicorn server...")
409
+ print(f"Credentials: EMAIL={'SET' if HF_EMAIL else 'NOT SET'}, PASSWORD={'SET' if HF_PASSWD else 'NOT SET'}")
410
+ print(f"Cookie Path: {os.path.abspath(COOKIE_PATH_DIR)}")
411
+ uvicorn.run(app, host="0.0.0.0", port=7860)