MatveyDM028 commited on
Commit
de71310
·
verified ·
1 Parent(s): fb8bce6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -14
app.py CHANGED
@@ -1,31 +1,57 @@
1
  from fastapi import FastAPI, HTTPException
2
  from pydantic import BaseModel
3
  from huggingface_hub import InferenceClient
 
4
 
5
  # Инициализация FastAPI
6
  app = FastAPI()
7
 
8
- # Инициализация клиента для модели
9
- client = InferenceClient("Qwen/Qwen2.5-Coder-32B-Instruct")
 
 
 
 
 
 
10
 
11
  # Модель данных для запроса
12
  class ChatRequest(BaseModel):
13
  message: str
14
- history: list[tuple[str, str]] = []
15
- system_message: str = "You are a friendly Chatbot."
16
- max_tokens: int = 512
17
- temperature: float = 0.7
18
- top_p: float = 0.95
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  # Маршрут для обработки запросов
21
  @app.post("/chat")
22
  async def chat(request: ChatRequest):
 
 
23
  try:
 
 
 
 
 
 
24
  # Формируем сообщения для модели
25
- messages = [{"role": "system", "content": request.system_message}]
26
 
27
  # Добавляем историю диалога
28
- for user_msg, assistant_msg in request.history:
29
  if user_msg:
30
  messages.append({"role": "user", "content": user_msg})
31
  if assistant_msg:
@@ -38,20 +64,35 @@ async def chat(request: ChatRequest):
38
  response = ""
39
  for message in client.chat_completion(
40
  messages,
41
- max_tokens=request.max_tokens,
42
  stream=True,
43
- temperature=request.temperature,
44
- top_p=request.top_p,
45
  ):
46
  token = message.choices[0].delta.content
47
  response += token
48
 
49
- # Возвращаем ответ
50
- return {"response": response}
 
 
 
 
51
 
52
  except Exception as e:
53
  raise HTTPException(status_code=500, detail=str(e))
54
 
 
 
 
 
 
 
 
 
 
 
 
55
  # Запуск приложения (для локального тестирования)
56
  if __name__ == "__main__":
57
  import uvicorn
 
1
  from fastapi import FastAPI, HTTPException
2
  from pydantic import BaseModel
3
  from huggingface_hub import InferenceClient
4
+ from typing import List, Tuple, Optional
5
 
6
  # Инициализация FastAPI
7
  app = FastAPI()
8
 
9
+ # Глобальные переменные для хранения состояния
10
+ client = None
11
+ system_message = "You are a friendly Chatbot."
12
+ max_tokens = 1024
13
+ temperature = 0.7
14
+ top_p = 0.95
15
+ history = []
16
+ total_tokens = 0
17
 
18
  # Модель данных для запроса
19
  class ChatRequest(BaseModel):
20
  message: str
21
+ reset_history: bool = False # Флаг для очистки истории
22
+
23
+ # Инициализация модели
24
+ def initialize_model(
25
+ model_name: str = "Qwen/Qwen2.5-Coder-32B-Instruct",
26
+ sys_message: str = "You are a friendly Chatbot.",
27
+ tokens: int = 1024,
28
+ temp: float = 0.7,
29
+ top_p_value: float = 0.95,
30
+ ):
31
+ global client, system_message, max_tokens, temperature, top_p
32
+ client = InferenceClient(model_name)
33
+ system_message = sys_message
34
+ max_tokens = tokens
35
+ temperature = temp
36
+ top_p = top_p_value
37
 
38
  # Маршрут для обработки запросов
39
  @app.post("/chat")
40
  async def chat(request: ChatRequest):
41
+ global history, total_tokens
42
+
43
  try:
44
+ # Очистка истории, если запрошено
45
+ if request.reset_history:
46
+ history = []
47
+ total_tokens = 0
48
+ return {"response": "History cleared.", "total_tokens": total_tokens}
49
+
50
  # Формируем сообщения для модели
51
+ messages = [{"role": "system", "content": system_message}]
52
 
53
  # Добавляем историю диалога
54
+ for user_msg, assistant_msg in history:
55
  if user_msg:
56
  messages.append({"role": "user", "content": user_msg})
57
  if assistant_msg:
 
64
  response = ""
65
  for message in client.chat_completion(
66
  messages,
67
+ max_tokens=max_tokens,
68
  stream=True,
69
+ temperature=temperature,
70
+ top_p=top_p,
71
  ):
72
  token = message.choices[0].delta.content
73
  response += token
74
 
75
+ # Обновляем историю и счетчик токенов
76
+ history.append((request.message, response))
77
+ total_tokens += len(response.split()) # Примерный подсчет токенов
78
+
79
+ # Возвращаем ответ и количество токенов
80
+ return {"response": response, "total_tokens": total_tokens}
81
 
82
  except Exception as e:
83
  raise HTTPException(status_code=500, detail=str(e))
84
 
85
+ # Маршрут для получения текущего состояния (история и токены)
86
+ @app.get("/status")
87
+ async def get_status():
88
+ return {
89
+ "history": history,
90
+ "total_tokens": total_tokens,
91
+ }
92
+
93
+ # Инициализация модели при запуске
94
+ initialize_model()
95
+
96
  # Запуск приложения (для локального тестирования)
97
  if __name__ == "__main__":
98
  import uvicorn