File size: 3,080 Bytes
7ca0188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""Deterministic, context-only passenger response templates."""

from __future__ import annotations

from typing import Any

from src.config import Settings, get_settings
from src.rag.fallback_handler import FallbackHandler


class ResponseGenerator:
    """Generate factual drafts only from supplied retrieval context."""

    def __init__(self, settings: Settings | None = None) -> None:
        self.settings = settings or get_settings()
        self.fallback = FallbackHandler()

    def generate_from_record(self, record_context: dict[str, Any], confidence: float) -> str:
        """Render known record fields without adding unstated facts."""

        name = record_context.get("name") or "The matched BER service"
        parts = [str(name)]
        location: list[str] = []
        if record_context.get("terminal"):
            location.append(f"in {record_context['terminal']}")
        if record_context.get("level"):
            location.append(f"on Level {record_context['level']}")
        if record_context.get("zone"):
            location.append(f"in the {record_context['zone']}")
        if location:
            parts[0] += " is located " + " ".join(location)
        description = record_context.get("short_description") or record_context.get("text")
        if description:
            parts.append(str(description))
        for key in ("direction_text", "accessibility_info"):
            if record_context.get(key):
                parts.append(str(record_context[key]))
        related = record_context.get("related_facilities") or []
        if related:
            names = [item.get("name", "") if isinstance(item, dict) else str(item) for item in related]
            names = [name for name in names if name]
            if names:
                parts.append("Nearby or related facilities include " + ", ".join(names))
        contact = record_context.get("contact_or_assistance")
        if contact:
            parts.append(str(contact))
        parts.append(f"Confidence: {confidence:.2f}")
        return ". ".join(part.rstrip(". ") for part in parts if part) + "."

    def generate_low_confidence_response(self, query: str, reason: str | None = None) -> str:
        return self.fallback.low_confidence(query, reason)["answer"]

    def generate_draft_answer(self, context: dict[str, Any]) -> dict[str, Any]:
        """Generate a template answer or safe fallback from complete context."""

        confidence = float(context.get("confidence_components", {}).get("final_confidence", 0.0))
        record = context.get("record_context") or context.get("selected_record")
        if not record or confidence < self.settings.final_confidence_threshold:
            return {"answer": self.generate_low_confidence_response(context.get("query", "")), "model_used": "template", "used_context": False, "fallback_triggered": True, "notes": ["Insufficient grounded context or confidence."]}
        return {"answer": self.generate_from_record(record, confidence), "model_used": "template", "used_context": True, "fallback_triggered": False, "notes": []}