Add new file
This commit is contained in:
84
core/functions/extract_metrics.py
Normal file
84
core/functions/extract_metrics.py
Normal file
@@ -0,0 +1,84 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Модуль извлечения метрик (KPI) из текста.
|
||||
Использует промпт metrics_extract.txt.
|
||||
|
||||
АДАПТАЦИЯ: теперь функция принимает промпт как аргумент.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import List, Dict
|
||||
from core.services.giga_client import GigaClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def extract_metrics(
|
||||
giga: GigaClient,
|
||||
context: str,
|
||||
prompt_text: str,
|
||||
bot_config,
|
||||
) -> List[Dict]:
|
||||
"""
|
||||
Извлекает числовые показатели, KPI, статистические величины из контекста.
|
||||
|
||||
Аргументы:
|
||||
giga (GigaClient): клиент GigaChat
|
||||
context (str): текст для анализа
|
||||
prompt_text (str): содержимое промпта для извлечения метрик
|
||||
bot_config (BotConfig): объект конфигурации
|
||||
|
||||
Возвращает:
|
||||
List[Dict]: список метрик с полями metric_name, value, unit, period, source_fragment
|
||||
"""
|
||||
if not prompt_text:
|
||||
logger.warning("Промпт извлечения метрик пуст")
|
||||
return []
|
||||
|
||||
if not context or len(context) < 20:
|
||||
logger.debug("Контекст слишком короткий для извлечения метрик")
|
||||
return []
|
||||
|
||||
metrics_cfg = getattr(bot_config, 'metrics', {})
|
||||
temperature = metrics_cfg.get('temperature', 0.1)
|
||||
if isinstance(temperature, dict):
|
||||
temperature = 0.1
|
||||
|
||||
full_prompt = f"{prompt_text}\n\nТекст для анализа:\n{context}"
|
||||
|
||||
try:
|
||||
response = await giga.chat(
|
||||
history=[],
|
||||
query=full_prompt,
|
||||
system_prompt=None,
|
||||
file_id=None,
|
||||
temperature=temperature
|
||||
)
|
||||
raw_answer = response.strip()
|
||||
|
||||
# Пытаемся распарсить JSON
|
||||
try:
|
||||
metrics = json.loads(raw_answer)
|
||||
if isinstance(metrics, list):
|
||||
return metrics[:15]
|
||||
except json.JSONDecodeError:
|
||||
# Fallback: построчный разбор
|
||||
logger.debug("Не удалось распарсить JSON, пробуем построчный разбор")
|
||||
lines = raw_answer.split('\n')
|
||||
result = []
|
||||
for line in lines:
|
||||
if ':' in line:
|
||||
parts = line.split(':', 1)
|
||||
result.append({
|
||||
"metric_name": parts[0].strip(),
|
||||
"value": parts[1].strip(),
|
||||
"unit": "",
|
||||
"period": "",
|
||||
"source_fragment": ""
|
||||
})
|
||||
return result
|
||||
return []
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка извлечения метрик: {e}", exc_info=True)
|
||||
return []
|
||||
Reference in New Issue
Block a user