- /rag/commands/expert.py - /core/services/__init__.py - /core/services/embedding_service.py - /core/services/file_service.py - /core/services/giga_client.py - /core/services/kb_service.py - /core/services/postgres_service.py - /core/services/qdrant_service.py - /core/services/reranker_service.py - /core/functions/__init__.py - /core/functions/check_consistency.py - /core/functions/check_spelling.py - /core/functions/critique_answer.py - /core/functions/expand_query.py - /core/functions/extract_metrics.py - /core/functions/file_processor.py - /core/functions/generate_document.py - /core/functions/intent_classify.py - /core/functions/rerank_context.py - /core/functions/summarize_document.py - /core/utils/__init__.py - /core/utils/arg_parser.py - /core/utils/config_loader.py - /core/utils/layout_converter.py - /core/utils/logger.py - /core/utils/text_utils.py - /core/utils/web_utils.py - /bots/commands/__init__.py - /bots/commands/base.py - /bots/commands/create.py - /core/commands/global_remove.py - /core/commands/help.py - /core/commands/info.py - /core/commands/kb.py - /core/commands/learn.py - /core/commands/other.py - /core/commands/registry.py - /core/commands/stats.py - /core/commands/template.py - /core/handlers/__init__.py - /core/handlers/message_handler.py - /core/workers/__init__.py - /core/workers/indexing_worker.py - /core/xmpp/__init__.py - /core/xmpp/client.py - /bots/commands/global_remove.py - /bots/commands/help.py - /bots/commands/info.py - /bots/commands/kb.py - /bots/commands/registry.py - /bots/commands/other.py - /bots/commands/template.py - /bots/commands/learn.py - /bots/commands/stats.py - /bots/handlers/message_handler.py - /bots/handlers/__init__.py - /bots/workers/__init__.py - /bots/workers/indexing_worker.py - /bots/xmpp/__init__.py - /bots/xmpp/client.py - /rag/services/qdrant_service.py - /rag/services/giga_client.py - /rag/services/embedding_service.py - /rag/services/reranker_service.py - /rag/services/__init__.py - /rag/services/file_service.py - /rag/services/postgres_service.py - /rag/services/kb_service.py - /rag/functions/check_spelling.py - /rag/functions/__init__.py - /rag/functions/extract_metrics.py - /rag/functions/generate_document.py - /rag/functions/expand_query.py - /rag/functions/critique_answer.py - /rag/functions/file_processor.py - /rag/functions/check_consistency.py - /rag/functions/summarize_document.py - /rag/functions/rerank_context.py - /rag/functions/intent_classify.py - /rag/utils/__init__.py - /rag/utils/layout_converter.py - /rag/utils/text_utils.py - /rag/utils/arg_parser.py - /rag/utils/config_loader.py - /rag/utils/logger.py - /rag/utils/web_utils.py
89 lines
3.2 KiB
Python
89 lines
3.2 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
Модуль классификации намерений пользователя.
|
||
Определяет тип запроса: METRICS, SUMMARY, CONTRADICTION, SURGICAL, GREETING и др.
|
||
|
||
АДАПТАЦИЯ: теперь функция принимает промпт как аргумент, а не использует глобальный.
|
||
"""
|
||
|
||
import logging
|
||
import time
|
||
from core.services.giga_client import GigaClient
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
# Список всех допустимых кодов намерений
|
||
VALID_INTENTS = {
|
||
"METRICS", "SUMMARY", "CONTRADICTION", "FACT", "PROCEDURE",
|
||
"COMPARISON", "CALCULATION", "SURGICAL", "GREETING", "TEMPLATE_FILL",
|
||
"SPELLCHECK"
|
||
}
|
||
|
||
# Кэш для классификации (in-memory)
|
||
_intent_cache = {}
|
||
_CACHE_TTL = 300 # 5 минут
|
||
|
||
|
||
async def classify_intent(
|
||
giga: GigaClient,
|
||
query: str,
|
||
prompt_text: str,
|
||
bot_config,
|
||
) -> str:
|
||
"""
|
||
Классифицирует намерение пользователя на основе текста запроса.
|
||
|
||
Аргументы:
|
||
giga (GigaClient): клиент GigaChat
|
||
query (str): исходный запрос пользователя
|
||
prompt_text (str): содержимое промпта классификации (передаётся из оркестратора)
|
||
bot_config (BotConfig): объект конфигурации бота
|
||
|
||
Возвращает:
|
||
str: один из кодов VALID_INTENTS или "GENERAL"
|
||
"""
|
||
if not prompt_text:
|
||
logger.warning("Промпт классификации пуст, возвращаем GENERAL")
|
||
return "GENERAL"
|
||
|
||
# Проверка кэша
|
||
cache_key = query.strip().lower()
|
||
now = time.time()
|
||
if cache_key in _intent_cache:
|
||
cached_time, cached_result = _intent_cache[cache_key]
|
||
if now - cached_time < _CACHE_TTL:
|
||
logger.debug(f"Кэш классификации: '{cache_key}' -> {cached_result}")
|
||
return cached_result
|
||
else:
|
||
del _intent_cache[cache_key]
|
||
|
||
# Получаем температуру из конфига
|
||
intent_cfg = getattr(bot_config, 'intent', {})
|
||
temperature = intent_cfg.get('temperature', 0.1)
|
||
if isinstance(temperature, dict):
|
||
temperature = 0.1
|
||
|
||
# Формируем полный промпт
|
||
full_prompt = f"{prompt_text}\n\nВопрос: {query}"
|
||
|
||
try:
|
||
response = await giga.chat(
|
||
history=[],
|
||
query=full_prompt,
|
||
system_prompt=None,
|
||
file_id=None,
|
||
temperature=temperature
|
||
)
|
||
answer = response.strip().upper()
|
||
|
||
if answer in VALID_INTENTS:
|
||
logger.debug(f"Классификация успешна: {answer}")
|
||
_intent_cache[cache_key] = (now, answer)
|
||
return answer
|
||
else:
|
||
logger.debug(f"Неизвестный ответ классификатора: {answer}, возвращаем GENERAL")
|
||
return "GENERAL"
|
||
|
||
except Exception as e:
|
||
logger.error(f"Ошибка классификации намерения: {e}", exc_info=True)
|
||
return "GENERAL" |