EmoCube commited on
Commit
d0e5fb1
·
verified ·
1 Parent(s): f5df8a7

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +94 -0
main.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+ import time
3
+ import logging
4
+ from flask import Flask, request, jsonify
5
+ import requests
6
+
7
+ # === Конфигурация ===
8
+ AI_MODEL = "NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO"
9
+ HF_API_URL = "https://nymbo-serverless-textgen-hub.hf.space/gradio_api/call/bot"
10
+
11
+ # === Логгер ===
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
+
15
+ # === Инициализация Flask ===
16
+ app = Flask(__name__)
17
+
18
+ # === Корневой маршрут для проверки работоспособности ===
19
+ @app.route("/", methods=["GET"])
20
+ def index():
21
+ return "Proxy free test", 200
22
+
23
+ # === Основной OpenAI-совместимый endpoint ===
24
+ @app.route("/use", methods=["POST"])
25
+ def chat_completion():
26
+ # Логируем входной запрос
27
+ logger.info(f"📥 Запрос от клиента: {request.remote_addr}")
28
+ logger.info(f"Headers:\n{dict(request.headers)}")
29
+ logger.info(f"Body:\n{request.get_data(as_text=True)}")
30
+
31
+ try:
32
+ payload = request.get_json()
33
+ messages = payload.get("messages", [])
34
+
35
+ # Извлекаем последнее сообщение пользователя
36
+ user_msg = next((m["content"] for m in reversed(messages) if m["role"] == "user"), None)
37
+ system_msg = next((m["content"] for m in messages if m["role"] == "system"), "You are a helpful AI assistant.")
38
+
39
+ if not user_msg:
40
+ return jsonify({"error": "Missing user message"}), 400
41
+
42
+ # Подготавливаем запрос к Hugging Face Space
43
+ hf_payload = {
44
+ "data": [
45
+ [[user_msg, None]], # history
46
+ system_msg, # system_msg
47
+ 512, # max_tokens
48
+ 0.7, # temperature
49
+ 0.95, # top_p
50
+ 0, # freq_penalty
51
+ -1, # seed
52
+ AI_MODEL, # custom_model
53
+ "", # search_term
54
+ AI_MODEL # selected_model
55
+ ]
56
+ }
57
+
58
+ # Выполняем запрос
59
+ hf_response = requests.post(HF_API_URL, json=hf_payload, timeout=60)
60
+ hf_response.raise_for_status()
61
+ result = hf_response.json()
62
+
63
+ output_text = result["data"][0] if "data" in result else "❌ Unexpected response format"
64
+ print(f"\n🧠 Ответ модели:\n{output_text}\n") # ⬅️ Вывод в консоль
65
+
66
+ return jsonify({
67
+ "id": f"chatcmpl-{uuid.uuid4().hex[:12]}",
68
+ "object": "chat.completion",
69
+ "created": int(time.time()),
70
+ "model": AI_MODEL,
71
+ "choices": [
72
+ {
73
+ "index": 0,
74
+ "message": {
75
+ "role": "assistant",
76
+ "content": output_text
77
+ },
78
+ "finish_reason": "stop"
79
+ }
80
+ ],
81
+ "usage": {
82
+ "prompt_tokens": 0,
83
+ "completion_tokens": 0,
84
+ "total_tokens": 0
85
+ }
86
+ })
87
+
88
+ except Exception as e:
89
+ logger.exception("❌ Ошибка обработки запроса:")
90
+ return jsonify({"error": str(e)}), 500
91
+
92
+ # === Запуск сервера ===
93
+ if __name__ == "__main__":
94
+ app.run(host="0.0.0.0", port=7860, debug=True)