service.py

파일 다운로드

"""웹·일괄 실행이 공유하는 관찰·캐시 입구."""
import json
import time
from pathlib import Path
from answers import answer_question, resolve_request
from cache import AnswerCache, cache_allowed, cache_key, runtime_signature
from tool_dispatcher import support_answer, wants_order_lookup
from rag_schema import parse_rag_response
from usage import RUNTIME, usage_scope, summarize_events
from vector_search import validate_index
from embedding_client import embedding_config
from search_cli import load_rows
import settings

ROOT = Path(__file__).resolve().parent


def check_assets(root=ROOT):
    import hashlib
    root = Path(root)
    data = root / 'data'
    meta = json.loads((data / 'document_build.json').read_text())
    for key, name in [('source_sha256', 'source/documents.json'), ('chunks_sha256', 'chunks.jsonl')]:
        if hashlib.sha256((data / name).read_bytes()).hexdigest() != meta[key]:
            raise ValueError('문서 전처리 재생성 필요: ' + name)
    validate_index(json.loads((data / 'search_index.json').read_text()), load_rows(data / 'chunks.jsonl'),
                   embedding_config(), {key: meta[key] for key in ['chunk_version', 'max_chars']})
    return True


def reply_support(question, history=None, current_user_id='U001'):
    started = time.perf_counter()
    order = wants_order_lookup(question)
    signature = runtime_signature()
    eligible = not order and cache_allowed(question, history)
    day = resolve_request(question, history)[1]
    cache = AnswerCache(RUNTIME / 'answers.db') if eligible else None
    key = cache_key(question, history, day, signature) if eligible else None
    # 캐시를 보기 전에 문서·조각·인덱스의 연결부터 확인한다.
    if not order and not settings.DEMO_MODE:
        check_assets()
    with usage_scope('order' if order else 'rag') as scope:
        saved = cache.get(key) if cache else None
        if saved is not None:
            parse_rag_response(json.dumps(saved['response'], ensure_ascii=False))
            result = {**saved, 'usage': None, 'trace': {'decision': 'answer_cache_hit'}}
            cache_status = 'HIT'
        else:
            result = support_answer(question, history, current_user_id) if order else answer_question(question, history)
            cache_status = 'MISS' if eligible else 'BYPASS'
            if cache and result.get('model') and result['response']['sources'] and not result['response']['needs_followup']:
                cache.put(key, {k: result[k] for k in ['response', 'source_details', 'model']})
        metrics = {**summarize_events(scope['events']), 'request_id': scope['request_id'],
                   'cache': cache_status, 'signature': signature['id'],
                   'elapsed_seconds': round(time.perf_counter()-started, 6)}
        return {**result, 'service_metrics': metrics}