Spaces:
Sleeping
Sleeping
update
Browse files- common/common.py +8 -0
- components/services/dialogue.py +2 -2
- routes/llm.py +39 -29
common/common.py
CHANGED
@@ -3,12 +3,20 @@ from enum import Enum
|
|
3 |
|
4 |
|
5 |
def configure_logging(level=logging.INFO, config_file_path='./common.log'):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
logging.basicConfig(
|
7 |
filename=config_file_path,
|
8 |
filemode="a",
|
9 |
level=level,
|
10 |
datefmt="%Y-%m-%d %H:%M:%S",
|
11 |
format="[%(asctime)s.%(msecs)03d] %(module)30s:%(lineno)4d %(levelname)-7s - %(message)s",
|
|
|
12 |
)
|
13 |
|
14 |
|
|
|
3 |
|
4 |
|
5 |
def configure_logging(level=logging.INFO, config_file_path='./common.log'):
|
6 |
+
|
7 |
+
formatter = logging.Formatter("[%(asctime)s.%(msecs)03d] %(module)30s:%(lineno)4d %(levelname)-7s - %(message)s")
|
8 |
+
|
9 |
+
console_handler = logging.StreamHandler()
|
10 |
+
console_handler.setLevel(level)
|
11 |
+
console_handler.setFormatter(formatter)
|
12 |
+
|
13 |
logging.basicConfig(
|
14 |
filename=config_file_path,
|
15 |
filemode="a",
|
16 |
level=level,
|
17 |
datefmt="%Y-%m-%d %H:%M:%S",
|
18 |
format="[%(asctime)s.%(msecs)03d] %(module)30s:%(lineno)4d %(levelname)-7s - %(message)s",
|
19 |
+
handlers=[console_handler]
|
20 |
)
|
21 |
|
22 |
|
components/services/dialogue.py
CHANGED
@@ -68,7 +68,7 @@ class DialogueService:
|
|
68 |
except Exception as e:
|
69 |
logger.error(f"Error in _postprocess_qe: {e}")
|
70 |
from_chat = self._get_search_query(history)
|
71 |
-
return QEResult(use_search=from_chat is not None, search_query=from_chat)
|
72 |
|
73 |
def _get_qe_request(self, history: List[Message]) -> ChatRequest:
|
74 |
"""
|
@@ -121,7 +121,7 @@ class DialogueService:
|
|
121 |
|
122 |
return QEResult(use_search=bool_var, search_query=second_part)
|
123 |
|
124 |
-
def _get_search_query(self, history: List[Message]) ->
|
125 |
"""
|
126 |
Получает запрос для поиска на основе последнего сообщения пользователя.
|
127 |
"""
|
|
|
68 |
except Exception as e:
|
69 |
logger.error(f"Error in _postprocess_qe: {e}")
|
70 |
from_chat = self._get_search_query(history)
|
71 |
+
return QEResult(use_search=from_chat is not None, search_query=from_chat.content)
|
72 |
|
73 |
def _get_qe_request(self, history: List[Message]) -> ChatRequest:
|
74 |
"""
|
|
|
121 |
|
122 |
return QEResult(use_search=bool_var, search_query=second_part)
|
123 |
|
124 |
+
def _get_search_query(self, history: List[Message]) -> Message | None:
|
125 |
"""
|
126 |
Получает запрос для поиска на основе последнего сообщения пользователя.
|
127 |
"""
|
routes/llm.py
CHANGED
@@ -117,38 +117,48 @@ async def sse_generator(request: ChatRequest, llm_api: DeepInfraApi, system_prom
|
|
117 |
"""
|
118 |
Генератор для стриминга ответа LLM через SSE.
|
119 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
yield f"data: {json.dumps(search_results_event, ensure_ascii=False)}\n\n"
|
135 |
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
|
|
|
|
149 |
|
150 |
-
|
151 |
-
|
|
|
|
|
|
|
152 |
|
153 |
|
154 |
@router.post("/chat/stream")
|
|
|
117 |
"""
|
118 |
Генератор для стриминга ответа LLM через SSE.
|
119 |
"""
|
120 |
+
try:
|
121 |
+
qe_result = await dialogue_service.get_qe_result(request.history)
|
122 |
+
|
123 |
+
except Exception as e:
|
124 |
+
logger.error(f"Error in SSE chat stream while dialogue_service.get_qe_result: {str(e)}", stack_info=True)
|
125 |
+
yield "data: {\"event\": \"error\", \"data\":\""+str(e)+"\" }\n\n"
|
126 |
|
127 |
+
try:
|
128 |
+
if qe_result.use_search and qe_result.search_query is not None:
|
129 |
+
dataset = dataset_service.get_current_dataset()
|
130 |
+
if dataset is None:
|
131 |
+
raise HTTPException(status_code=400, detail="Dataset not found")
|
132 |
+
_, scores, chunk_ids = entity_service.search_similar(qe_result.search_query, dataset.id)
|
133 |
+
chunks = entity_service.chunk_repository.get_chunks_by_ids(chunk_ids)
|
134 |
+
text_chunks = entity_service.build_text(chunks, scores)
|
135 |
+
search_results_event = {
|
136 |
+
"event": "search_results",
|
137 |
+
"data": f"{text_chunks}"
|
138 |
+
}
|
139 |
+
yield f"data: {json.dumps(search_results_event, ensure_ascii=False)}\n\n"
|
|
|
140 |
|
141 |
+
# new_message = f'<search-results>\n{text_chunks}\n</search-results>\n{last_query.content}'
|
142 |
+
|
143 |
+
try_insert_search_results(request, text_chunks)
|
144 |
+
except Exception as e:
|
145 |
+
logger.error(f"Error in SSE chat stream while searching: {str(e)}", stack_info=True)
|
146 |
+
yield "data: {\"event\": \"error\", \"data\":\""+str(e)+"\" }\n\n"
|
147 |
+
try:
|
148 |
+
# Сворачиваем историю в первое сообщение
|
149 |
+
collapsed_request = collapse_history_to_first_message(request)
|
150 |
+
|
151 |
+
# Стриминг токенов ответа
|
152 |
+
async for token in llm_api.get_predict_chat_generator(collapsed_request, system_prompt, predict_params):
|
153 |
+
token_event = {"event": "token", "data": token}
|
154 |
+
# logger.info(f"Streaming token: {token}")
|
155 |
+
yield f"data: {json.dumps(token_event, ensure_ascii=False)}\n\n"
|
156 |
|
157 |
+
# Финальное событие
|
158 |
+
yield "data: {\"event\": \"done\"}\n\n"
|
159 |
+
except Exception as e:
|
160 |
+
logger.error(f"Error in SSE chat stream while generating response: {str(e)}", stack_info=True)
|
161 |
+
yield "data: {\"event\": \"error\", \"data\":\""+str(e)+"\" }\n\n"
|
162 |
|
163 |
|
164 |
@router.post("/chat/stream")
|