Update 6 files

- /rag/history_manager.py
- /rag/query_processor.py
- /rag/rag_orchestrator.py
- /rag/rag_api.py
- /rag/rag_server.py
- /rag/__init__.py
This commit is contained in:
Markov Andrey
2026-06-30 14:04:31 +00:00
parent c9ee8fc19a
commit a3f52888db
6 changed files with 107 additions and 114 deletions

View File

@@ -9,12 +9,13 @@ import logging
import re
from typing import Optional, Dict, List, Any
from core.services.giga_client import GigaClient
from core.services.kb_service import KBService
from core.functions.expand_query import expand_query
from core.functions.rerank_context import rerank_context
from core.functions.critique_answer import critique_answer
from core.utils.text_utils import count_tokens
from rag.services.giga_client import GigaClient
from rag.services.kb_service import KBService
from rag.functions.expand_query import expand_query
from rag.functions.rerank_context import rerank_context
from rag.functions.critique_answer import critique_answer
from rag.utils.text_utils import count_tokens
from rag.config_models import AppConfig
logger = logging.getLogger(__name__)
@@ -28,7 +29,7 @@ class QueryProcessor:
self,
giga: GigaClient,
kb: KBService,
config,
config: AppConfig,
default_prompts: Optional[Dict[str, str]] = None
):
"""
@@ -37,7 +38,7 @@ class QueryProcessor:
Аргументы:
giga: клиент GigaChat
kb: сервис базы знаний
config: объект конфигурации
config: объект конфигурации (AppConfig)
default_prompts: словарь промптов по умолчанию
"""
self.giga = giga
@@ -73,18 +74,20 @@ class QueryProcessor:
Словарь с ключами 'answer', 'context', 'sources', 'confidence'
"""
# 1. Расширение запроса
expand_prompt = prompts.get('expand', '')
expanded = await expand_query(
giga=self.giga,
query=query,
prompt_text=prompts.get('expand', ''),
prompt_text=expand_prompt,
bot_config=self.config
)
search_query = expanded if expanded and expanded != query else query
# 2. Поиск релевантного контекста в базе знаний
top_k = self.config.rag.default_top_k
context = await self.kb.find_relevant_info(
search_query, user_jid, room_jid,
top_k=getattr(self.config, 'rag_default_top_k', 30)
top_k=top_k
)
logger.info(f"Найден контекст длиной {len(context)} символов (room={room_jid})")
@@ -103,7 +106,7 @@ class QueryProcessor:
context = ""
# 4. Переранжирование контекста (если включено и контекст достаточно длинный)
rerank_min_length = getattr(self.config, 'rerank_min_length', 5000)
rerank_min_length = self.config.rag.rerank_min_length
if intent != "FACT" and len(context) > rerank_min_length:
context = await rerank_context(
bot=None,
@@ -130,16 +133,17 @@ class QueryProcessor:
logger.debug(f"Полный запрос к GigaChat (первые 500 символов): {full_query[:500]}")
# 6. Генерация ответа
temperature = self.config.ai.temperature
answer = await self.giga.chat(
history=history,
query=full_query,
system_prompt=system_prompt,
file_id=None,
temperature=getattr(self.config, 'ai_temperature', 0.1)
temperature=temperature
)
# 7. Самокритика (если включена)
if getattr(self.config, 'enable_self_critique', False) and context:
if self.config.features.enable_self_critique and context:
critique_prompt = prompts.get('critique', '')
if critique_prompt:
logger.debug("Запуск самокритики")
@@ -159,7 +163,7 @@ class QueryProcessor:
query=full_query_retry,
system_prompt=system_prompt,
file_id=None,
temperature=getattr(self.config, 'ai_temperature', 0.1)
temperature=temperature
)
# Повторная проверка после перегенерации
if not await critique_answer(