Download src/evaluation/dashboard.py from danishk84/NovaGuide: direct link, hf CLI and curl.
- Browser
- Download file 31.5 kB
-
https://huggingface.co/spaces/danishk84/NovaGuide/resolve/main/src/evaluation/dashboard.py
- Command line
-
hf download hf://spaces/danishk84/NovaGuide/src/evaluation/dashboard.py
-
curl -L -o dashboard.py https://huggingface.co/spaces/danishk84/NovaGuide/resolve/main/src/evaluation/dashboard.py
31.5 kB
| """Neon-backed, source-labelled CBAO dashboard metrics and Plotly figures.""" | |
| from __future__ import annotations | |
| from datetime import datetime, timezone | |
| from typing import Any | |
| import pandas as pd | |
| import plotly.express as px | |
| import plotly.graph_objects as go | |
| from sklearn.metrics import precision_recall_fscore_support | |
| from src.logging_layer.neon_client import NeonClient | |
| DEFAULT_BEHAVIOUR_SOURCES = ("manual_user", "structured_test", "model_evaluation") | |
| ALL_DATA_SOURCES = ( | |
| "manual_user", | |
| "structured_test", | |
| "model_evaluation", | |
| "synthetic", | |
| "locust", | |
| "hypothesis", | |
| ) | |
| def _empty_figure( | |
| title: str, message: str = "No matching evidence is available." | |
| ) -> go.Figure: | |
| figure = go.Figure() | |
| figure.add_annotation(text=message, x=0.5, y=0.5, showarrow=False) | |
| figure.update_layout( | |
| title=title, height=350, xaxis_visible=False, yaxis_visible=False | |
| ) | |
| return figure | |
| class CBAODashboard: | |
| """Build examiner-facing metrics without mixing incompatible data sources.""" | |
| def __init__(self, neon: NeonClient | None = None) -> None: | |
| self.neon = neon or NeonClient() | |
| def _filters( | |
| data_sources: list[str] | None, | |
| modality: str | None, | |
| days: str | int | None, | |
| configuration_version: str | None, | |
| ) -> tuple[str, dict[str, Any]]: | |
| sources = [ | |
| item | |
| for item in (data_sources or DEFAULT_BEHAVIOUR_SOURCES) | |
| if item in ALL_DATA_SOURCES | |
| ] | |
| if not sources: | |
| sources = list(DEFAULT_BEHAVIOUR_SOURCES) | |
| params: dict[str, Any] = { | |
| f"source_{index}": value for index, value in enumerate(sources) | |
| } | |
| clauses = [ | |
| "ci.data_source IN (" | |
| + ",".join(f":source_{i}" for i in range(len(sources))) | |
| + ")" | |
| ] | |
| if modality and modality != "all": | |
| clauses.append("ci.input_modality = :modality") | |
| params["modality"] = modality | |
| if str(days or "all").lower() != "all": | |
| try: | |
| day_count = max(1, min(3650, int(days))) | |
| except (TypeError, ValueError): | |
| day_count = 30 | |
| clauses.append("ci.timestamp >= NOW() - (:days * INTERVAL '1 day')") | |
| params["days"] = day_count | |
| if configuration_version and configuration_version != "all": | |
| clauses.append("ci.configuration_version = :configuration_version") | |
| params["configuration_version"] = configuration_version | |
| return " AND ".join(clauses), params | |
| def _interaction_frame( | |
| self, | |
| data_sources: list[str] | None = None, | |
| modality: str = "all", | |
| days: str | int = "30", | |
| configuration_version: str = "all", | |
| ) -> pd.DataFrame: | |
| where, params = self._filters( | |
| data_sources, modality, days, configuration_version | |
| ) | |
| rows = self.neon.fetch_all( | |
| f""" | |
| SELECT ci.interaction_id, ci.session_id, ci.timestamp, ci.data_source, | |
| ci.test_run_id, ci.configuration_version, ci.input_modality, | |
| ci.predicted_intent, ci.intent_confidence, ci.image_category, | |
| ci.route, ci.matched_record_id, ci.retrieval_score, | |
| ci.final_confidence, ci.fallback_triggered, ci.response_time_ms, | |
| ci.time_to_first_response_ms, ci.intent_latency_ms, | |
| ci.retrieval_latency_ms, ci.vision_latency_ms, ci.speech_latency_ms, | |
| ci.task_completed, ci.model_used, | |
| ip.expected_intent, ip.correct AS intent_correct, | |
| rr.selected_record_id, rr.similarity_score, | |
| rr.expected_record_id, rr.retrieval_correct, | |
| fb.fallback_reason, | |
| ve.ocr_used, ve.ocr_confidence, ve.clip_used, ve.clip_category, | |
| ve.clip_confidence, ve.qwen_invoked, ve.qwen_success | |
| FROM chat_interactions ci | |
| LEFT JOIN intent_predictions ip ON ip.interaction_id = ci.interaction_id | |
| LEFT JOIN retrieval_results rr ON rr.interaction_id = ci.interaction_id | |
| LEFT JOIN fallback_events fb ON fb.interaction_id = ci.interaction_id | |
| LEFT JOIN vision_events ve ON ve.interaction_id = ci.interaction_id | |
| WHERE {where} | |
| ORDER BY ci.timestamp DESC | |
| LIMIT 5000 | |
| """, | |
| params, | |
| ) | |
| frame = pd.DataFrame(rows) | |
| if frame.empty: | |
| return frame | |
| frame["timestamp"] = pd.to_datetime( | |
| frame["timestamp"], utc=True, errors="coerce" | |
| ) | |
| numeric = ( | |
| "intent_confidence", | |
| "retrieval_score", | |
| "final_confidence", | |
| "response_time_ms", | |
| "time_to_first_response_ms", | |
| "intent_latency_ms", | |
| "retrieval_latency_ms", | |
| "vision_latency_ms", | |
| "speech_latency_ms", | |
| "similarity_score", | |
| "ocr_confidence", | |
| "clip_confidence", | |
| ) | |
| for column in numeric: | |
| if column in frame: | |
| frame[column] = pd.to_numeric(frame[column], errors="coerce") | |
| return frame | |
| def _feedback_frame(self, where: str, params: dict[str, Any]) -> pd.DataFrame: | |
| rows = self.neon.fetch_all( | |
| f"""SELECT fe.rating, fe.frustration_flag, fe.created_at | |
| FROM feedback_events fe | |
| JOIN chat_interactions ci ON ci.interaction_id = fe.interaction_id | |
| WHERE {where} | |
| ORDER BY fe.created_at DESC LIMIT 5000""", | |
| params, | |
| ) | |
| return pd.DataFrame(rows) | |
| def metrics(self) -> dict[str, Any]: | |
| """Compatibility KPI method used by existing callers and tests.""" | |
| if not self.neon.is_configured(): | |
| return {"status": "Neon is not configured"} | |
| frame = self._interaction_frame() | |
| if frame.empty: | |
| return { | |
| "interactions": 0, | |
| "sessions": 0, | |
| "avg_response_ms": None, | |
| "fallback_rate_pct": None, | |
| "completion_rate_pct": None, | |
| "feedback_count": 0, | |
| "helpful_rate_pct": None, | |
| } | |
| where, params = self._filters(None, "all", "30", "all") | |
| ratings = self._feedback_frame(where, params) | |
| completed = ( | |
| frame["task_completed"].dropna() | |
| if "task_completed" in frame | |
| else pd.Series(dtype=bool) | |
| ) | |
| helpful = ( | |
| ratings["rating"].eq("helpful") | |
| if not ratings.empty and "rating" in ratings | |
| else pd.Series(dtype=bool) | |
| ) | |
| return { | |
| "interactions": int(len(frame)), | |
| "sessions": int(frame["session_id"].nunique()), | |
| "avg_response_ms": round(float(frame["response_time_ms"].mean()), 1), | |
| "fallback_rate_pct": round( | |
| float(frame["fallback_triggered"].fillna(False).mean() * 100), 1 | |
| ), | |
| "completion_rate_pct": ( | |
| round(float(completed.astype(bool).mean() * 100), 1) | |
| if len(completed) | |
| else None | |
| ), | |
| "feedback_count": int(len(ratings)), | |
| "helpful_rate_pct": ( | |
| round(float(helpful.mean() * 100), 1) if len(helpful) else None | |
| ), | |
| } | |
| def _kpi_markdown( | |
| frame: pd.DataFrame, feedback: pd.DataFrame, sources: list[str] | |
| ) -> str: | |
| now = datetime.now(timezone.utc).strftime("%d %b %Y %H:%M UTC") | |
| if frame.empty: | |
| return ( | |
| "### No matching analytics evidence\n\n" | |
| f"Filters: `{', '.join(sources)}` · Refreshed {now}. " | |
| "No rates are reported as zero when their denominator is absent." | |
| ) | |
| fallback = frame["fallback_triggered"].fillna(False).astype(bool) | |
| completed = frame["task_completed"].dropna() | |
| response = frame["response_time_ms"].dropna() | |
| labelled = frame[ | |
| frame["expected_intent"].notna() & frame["intent_correct"].notna() | |
| ] | |
| helpful = ( | |
| feedback["rating"].eq("helpful") | |
| if not feedback.empty | |
| else pd.Series(dtype=bool) | |
| ) | |
| def value(number: float | None, suffix: str = "") -> str: | |
| return "Not measurable" if number is None else f"{number:,.1f}{suffix}" | |
| completion = ( | |
| float(completed.astype(bool).mean() * 100) if len(completed) else None | |
| ) | |
| intent_accuracy = ( | |
| float(labelled["intent_correct"].astype(bool).mean() * 100) | |
| if len(labelled) | |
| else None | |
| ) | |
| helpful_rate = float(helpful.mean() * 100) if len(helpful) else None | |
| median = float(response.median()) if len(response) else None | |
| p95 = float(response.quantile(0.95)) if len(response) else None | |
| return ( | |
| "### Executive overview\n\n" | |
| f"**Interactions:** {len(frame):,} · **Sessions:** {frame['session_id'].nunique():,} · " | |
| f"**Fallback:** {fallback.mean() * 100:.1f}% · " | |
| f"**Completion:** {value(completion, '%')} · " | |
| f"**Median latency:** {value(median, ' ms')} · **p95 latency:** {value(p95, ' ms')} · " | |
| f"**Intent accuracy:** {value(intent_accuracy, '%')} (`n={len(labelled)}`) · " | |
| f"**Helpful:** {value(helpful_rate, '%')} (`n={len(feedback)}`)\n\n" | |
| f"Sources: `{', '.join(sources)}` · Refreshed {now}." | |
| ) | |
| def dashboard( | |
| self, | |
| data_sources: list[str] | None = None, | |
| modality: str = "all", | |
| days: str = "30", | |
| configuration_version: str = "all", | |
| ) -> tuple[Any, ...]: | |
| """Return dashboard summary, figures and audit tables for Gradio.""" | |
| sources = [ | |
| item | |
| for item in (data_sources or DEFAULT_BEHAVIOUR_SOURCES) | |
| if item in ALL_DATA_SOURCES | |
| ] | |
| if not self.neon.is_configured(): | |
| empty = _empty_figure( | |
| "Dashboard unavailable", | |
| "Configure the DATABASE_URL Hugging Face secret.", | |
| ) | |
| return ( | |
| "### Dashboard unavailable\n\nNeon PostgreSQL is not configured.", | |
| *([empty] * 15), | |
| [], | |
| [], | |
| [], | |
| [], | |
| ) | |
| frame = self._interaction_frame(sources, modality, days, configuration_version) | |
| where, params = self._filters(sources, modality, days, configuration_version) | |
| feedback = self._feedback_frame(where, params) | |
| summary = self._kpi_markdown( | |
| frame, feedback, sources or list(DEFAULT_BEHAVIOUR_SOURCES) | |
| ) | |
| if frame.empty: | |
| empty = _empty_figure("No matching evidence") | |
| return (summary, *([empty] * 15), [], [], [], []) | |
| daily = frame.dropna(subset=["timestamp"]).copy() | |
| daily["date"] = daily["timestamp"].dt.date | |
| trend = daily.groupby("date", as_index=False).agg( | |
| interactions=("interaction_id", "count"), | |
| fallback_rate=( | |
| "fallback_triggered", | |
| lambda s: s.fillna(False).mean() * 100, | |
| ), | |
| ) | |
| if trend.empty: | |
| overview = _empty_figure("Interaction trend") | |
| elif len(trend) == 1: | |
| hourly = ( | |
| daily.assign(hour=daily["timestamp"].dt.floor("h")) | |
| .groupby("hour", as_index=False) | |
| .agg( | |
| interactions=("interaction_id", "count"), | |
| fallback_rate=( | |
| "fallback_triggered", | |
| lambda s: s.fillna(False).mean() * 100, | |
| ), | |
| ) | |
| ) | |
| overview = px.bar( | |
| hourly, | |
| x="hour", | |
| y="interactions", | |
| color="fallback_rate", | |
| text_auto=True, | |
| title="Same-day interaction volume by hour", | |
| labels={ | |
| "hour": "Hour", | |
| "interactions": "Interactions", | |
| "fallback_rate": "Fallback %", | |
| }, | |
| ) | |
| else: | |
| overview = px.line( | |
| trend, | |
| x="date", | |
| y=["interactions", "fallback_rate"], | |
| markers=True, | |
| title="Daily interaction volume and fallback trend", | |
| ) | |
| intents = ( | |
| frame["predicted_intent"] | |
| .fillna("unknown") | |
| .value_counts() | |
| .rename_axis("intent") | |
| .reset_index(name="count") | |
| ) | |
| intent_chart = px.bar( | |
| intents, x="count", y="intent", orientation="h", title="Intent distribution" | |
| ) | |
| confidence_chart = px.histogram( | |
| frame, | |
| x="intent_confidence", | |
| color="predicted_intent", | |
| nbins=20, | |
| title="Intent confidence distribution", | |
| ) | |
| confidence_chart.add_vline( | |
| x=0.55, line_dash="dash", annotation_text="runtime threshold" | |
| ) | |
| fallback_by = ( | |
| frame.assign( | |
| fallback=frame["fallback_triggered"].fillna(False).astype(bool) | |
| ) | |
| .groupby( | |
| ["predicted_intent", "input_modality"], dropna=False, as_index=False | |
| ) | |
| .agg( | |
| interactions=("interaction_id", "count"), | |
| fallback_rate=("fallback", "mean"), | |
| ) | |
| ) | |
| fallback_by["fallback_rate"] *= 100 | |
| fallback_chart = px.bar( | |
| fallback_by, | |
| x="predicted_intent", | |
| y="fallback_rate", | |
| color="input_modality", | |
| barmode="group", | |
| title="Fallback rate by intent and modality", | |
| ) | |
| modality_summary = frame.groupby( | |
| "input_modality", dropna=False, as_index=False | |
| ).agg( | |
| interactions=("interaction_id", "count"), | |
| completion_rate=( | |
| "task_completed", | |
| lambda s: ( | |
| s.dropna().astype(bool).mean() * 100 | |
| if len(s.dropna()) | |
| else float("nan") | |
| ), | |
| ), | |
| median_latency_ms=("response_time_ms", "median"), | |
| ) | |
| modality_chart = px.bar( | |
| modality_summary, | |
| x="input_modality", | |
| y="interactions", | |
| color="completion_rate", | |
| title="Modality usage and completion", | |
| ) | |
| retrieval = frame[frame["matched_record_id"].fillna("").ne("")].copy() | |
| retrieval_chart = ( | |
| px.histogram( | |
| retrieval, | |
| x="retrieval_score", | |
| color="input_modality", | |
| nbins=20, | |
| title="RAG similarity distribution", | |
| ) | |
| if not retrieval.empty | |
| else _empty_figure("RAG similarity distribution") | |
| ) | |
| sessions = frame.groupby("session_id", as_index=False).agg( | |
| turns=("interaction_id", "count"), | |
| fallbacks=("fallback_triggered", lambda s: s.fillna(False).sum()), | |
| completed=( | |
| "task_completed", | |
| lambda s: s.dropna().astype(bool).any() if len(s.dropna()) else False, | |
| ), | |
| ) | |
| session_chart = ( | |
| px.histogram(sessions, x="turns", title="Session length distribution") | |
| if not sessions.empty | |
| else _empty_figure("Session length") | |
| ) | |
| ordered = frame.dropna( | |
| subset=["timestamp", "session_id", "predicted_intent"] | |
| ).sort_values(["session_id", "timestamp"]) | |
| pairs: list[tuple[str, str]] = [] | |
| for _session, group in ordered.groupby("session_id"): | |
| values = list(dict.fromkeys(group["predicted_intent"].astype(str).tolist())) | |
| pairs.extend( | |
| (left, right) | |
| for index, left in enumerate(values) | |
| for right in values[index + 1 :] | |
| ) | |
| if pairs: | |
| pair_frame = pd.DataFrame(pairs, columns=["intent_a", "intent_b"]) | |
| matrix = pd.crosstab(pair_frame["intent_a"], pair_frame["intent_b"]) | |
| cooccurrence_chart = px.imshow( | |
| matrix, text_auto=True, title="Session intent co-occurrence" | |
| ) | |
| session_count = max(1, ordered["session_id"].nunique()) | |
| intent_sessions = ( | |
| ordered.groupby("predicted_intent")["session_id"].nunique().to_dict() | |
| ) | |
| pair_counts = ( | |
| pair_frame.groupby(["intent_a", "intent_b"]) | |
| .size() | |
| .reset_index(name="sessions_together") | |
| ) | |
| rules: list[dict[str, Any]] = [] | |
| for row in pair_counts.itertuples(index=False): | |
| support = row.sessions_together / session_count | |
| p_a = intent_sessions.get(row.intent_a, 0) / session_count | |
| p_b = intent_sessions.get(row.intent_b, 0) / session_count | |
| confidence = row.sessions_together / max( | |
| 1, intent_sessions.get(row.intent_a, 0) | |
| ) | |
| lift = support / (p_a * p_b) if p_a and p_b else 0.0 | |
| rules.append( | |
| { | |
| "intent_a": row.intent_a, | |
| "intent_b": row.intent_b, | |
| "support": round(support, 4), | |
| "confidence": round(confidence, 4), | |
| "lift": round(lift, 4), | |
| "sessions": int(row.sessions_together), | |
| } | |
| ) | |
| association_table = sorted( | |
| rules, key=lambda item: (item["lift"], item["support"]), reverse=True | |
| ) | |
| else: | |
| cooccurrence_chart = _empty_figure( | |
| "Session intent co-occurrence", | |
| "At least two intents in one session are required.", | |
| ) | |
| association_table = [] | |
| latency_columns = [ | |
| "intent_latency_ms", | |
| "retrieval_latency_ms", | |
| "vision_latency_ms", | |
| "speech_latency_ms", | |
| ] | |
| latency = ( | |
| frame[latency_columns] | |
| .median() | |
| .rename_axis("component") | |
| .reset_index(name="median_ms") | |
| ) | |
| latency_chart = px.bar( | |
| latency, x="component", y="median_ms", title="Median component latency" | |
| ) | |
| latency_distribution = px.histogram( | |
| frame, | |
| x="response_time_ms", | |
| color="input_modality", | |
| nbins=30, | |
| title="End-to-end response-time distribution", | |
| ) | |
| vision = frame[ | |
| (frame["clip_used"] == True) | |
| | (frame["ocr_used"] == True) | |
| | (frame["qwen_invoked"] == True) | |
| ].copy() # noqa: E712 | |
| if vision.empty: | |
| vision_chart = _empty_figure("Vision route evidence") | |
| else: | |
| vision_melt = pd.DataFrame( | |
| { | |
| "route": ["CLIP", "OCR", "Qwen"], | |
| "events": [ | |
| vision["clip_used"].fillna(False).sum(), | |
| vision["ocr_used"].fillna(False).sum(), | |
| vision["qwen_invoked"].fillna(False).sum(), | |
| ], | |
| } | |
| ) | |
| vision_chart = px.bar( | |
| vision_melt, x="route", y="events", title="Vision route evidence" | |
| ) | |
| labelled = frame[ | |
| frame["expected_intent"].notna() & frame["intent_correct"].notna() | |
| ].copy() | |
| intent_table = [] | |
| if not labelled.empty: | |
| labels = sorted( | |
| set(labelled["expected_intent"].astype(str)) | |
| | set(labelled["predicted_intent"].astype(str)) | |
| ) | |
| precision, recall, f1, support = precision_recall_fscore_support( | |
| labelled["expected_intent"].astype(str), | |
| labelled["predicted_intent"].astype(str), | |
| labels=labels, | |
| zero_division=0, | |
| ) | |
| confidences = ( | |
| labelled.groupby("predicted_intent")["intent_confidence"] | |
| .mean() | |
| .to_dict() | |
| ) | |
| intent_table = [ | |
| { | |
| "intent": label, | |
| "precision": round(float(precision[i]), 4), | |
| "recall": round(float(recall[i]), 4), | |
| "f1": round(float(f1[i]), 4), | |
| "support": int(support[i]), | |
| "avg_confidence": round(float(confidences.get(label, 0)), 4), | |
| } | |
| for i, label in enumerate(labels) | |
| ] | |
| confusion = pd.crosstab( | |
| labelled["expected_intent"], labelled["predicted_intent"] | |
| ) | |
| confusion_chart = px.imshow( | |
| confusion, | |
| text_auto=True, | |
| title=f"Intent confusion matrix (n={len(labelled)})", | |
| ) | |
| else: | |
| confusion_chart = _empty_figure( | |
| "Intent confusion matrix", | |
| "No interactions with expected intent labels.", | |
| ) | |
| if feedback.empty or "rating" not in feedback: | |
| feedback_chart = _empty_figure( | |
| "Satisfaction and inferred friction", "No feedback has been collected." | |
| ) | |
| else: | |
| feedback_counts = ( | |
| feedback.assign( | |
| friction=feedback.get("frustration_flag", False) | |
| .fillna(False) | |
| .map({True: "inferred friction", False: "no friction flag"}) | |
| ) | |
| .groupby(["rating", "friction"], as_index=False) | |
| .size() | |
| ) | |
| feedback_chart = px.bar( | |
| feedback_counts, | |
| x="rating", | |
| y="size", | |
| color="friction", | |
| barmode="group", | |
| title="Feedback and inferred friction indicators", | |
| ) | |
| # Load evidence is queried independently so selecting Locust is not | |
| # required and never changes passenger-behaviour KPIs. | |
| locust = self._interaction_frame(["locust"], "all", days, configuration_version) | |
| if locust.empty: | |
| load_chart = _empty_figure( | |
| "Load-test performance", | |
| "No Locust run is stored for this time/configuration filter.", | |
| ) | |
| else: | |
| load_summary = locust.groupby( | |
| "test_run_id", dropna=False, as_index=False | |
| ).agg( | |
| requests=("interaction_id", "count"), | |
| median_ms=("response_time_ms", "median"), | |
| p95_ms=("response_time_ms", lambda s: s.quantile(0.95)), | |
| failure_rate=( | |
| "fallback_triggered", | |
| lambda s: s.fillna(False).mean() * 100, | |
| ), | |
| ) | |
| load_chart = px.bar( | |
| load_summary, | |
| x="test_run_id", | |
| y="p95_ms", | |
| color="failure_rate", | |
| hover_data=["requests", "median_ms"], | |
| title="Load-test p95 latency and failure proxy", | |
| ) | |
| optimization_rows = self.neon.fetch_all( | |
| """SELECT experiment_name, configuration_version, model_name, precision_name, | |
| metric_name, metric_value, sample_size, created_at | |
| FROM optimization_results ORDER BY created_at DESC LIMIT 1000""" | |
| ) | |
| optimization = pd.DataFrame(optimization_rows) | |
| if optimization.empty: | |
| optimization_chart = _empty_figure( | |
| "Optimization comparison", | |
| "No executed optimization results are stored.", | |
| ) | |
| else: | |
| optimization_chart = px.bar( | |
| optimization, | |
| x="configuration_version", | |
| y="metric_value", | |
| color="metric_name", | |
| facet_row="experiment_name", | |
| barmode="group", | |
| title="Baseline versus optimized configurations", | |
| hover_data=["model_name", "precision_name", "sample_size"], | |
| ) | |
| fallback_table = ( | |
| fallback_by.sort_values(["fallback_rate", "interactions"], ascending=False) | |
| .round(3) | |
| .to_dict("records") | |
| ) | |
| data_quality = [ | |
| { | |
| "measure": "Dashboard interactions", | |
| "sample_size": len(frame), | |
| "rule": "Filtered by explicit data_source", | |
| }, | |
| { | |
| "measure": "Labelled intent cases", | |
| "sample_size": len(labelled), | |
| "rule": "Accuracy excludes unlabelled interactions", | |
| }, | |
| { | |
| "measure": "Feedback responses", | |
| "sample_size": len(feedback), | |
| "rule": "No feedback is reported as not measurable", | |
| }, | |
| { | |
| "measure": "Retrieved interactions", | |
| "sample_size": len(retrieval), | |
| "rule": "RAG charts require a selected record", | |
| }, | |
| { | |
| "measure": "Labelled retrieval cases", | |
| "sample_size": int(frame["retrieval_correct"].notna().sum()), | |
| "rule": "Retrieval accuracy excludes unlabelled interactions", | |
| }, | |
| { | |
| "measure": "Locust requests (independent dataset)", | |
| "sample_size": len(locust), | |
| "rule": "Load evidence is isolated from passenger behaviour metrics", | |
| }, | |
| ] | |
| return ( | |
| summary, | |
| overview, | |
| intent_chart, | |
| confidence_chart, | |
| confusion_chart, | |
| fallback_chart, | |
| modality_chart, | |
| retrieval_chart, | |
| vision_chart, | |
| session_chart, | |
| cooccurrence_chart, | |
| latency_chart, | |
| latency_distribution, | |
| feedback_chart, | |
| load_chart, | |
| optimization_chart, | |
| intent_table, | |
| fallback_table, | |
| association_table, | |
| data_quality, | |
| ) | |
| def render(self) -> tuple[str, list[list[str]]]: | |
| metrics = self.metrics() | |
| if "status" in metrics: | |
| return ( | |
| f"**Dashboard unavailable:** {metrics['status']}.", | |
| [["status", str(metrics["status"])]], | |
| ) | |
| rows = [ | |
| [ | |
| key.replace("_", " ").title(), | |
| "Not measurable" if value is None else str(value), | |
| ] | |
| for key, value in metrics.items() | |
| ] | |
| return ( | |
| "### Executive KPI snapshot\n\n" | |
| + " · ".join(f"**{row[0]}:** {row[1]}" for row in rows), | |
| rows, | |
| ) | |
| def interaction_review( | |
| self, interaction_id: str | None | |
| ) -> tuple[str, dict[str, Any]]: | |
| interaction_id = (interaction_id or "").strip() | |
| if not interaction_id: | |
| return "Enter an interaction ID.", {} | |
| if not self.neon.is_configured(): | |
| return "Review unavailable: Neon is not configured.", {} | |
| rows = self.neon.fetch_all( | |
| """ | |
| SELECT interaction_id, timestamp, data_source, configuration_version, | |
| input_modality, sanitized_query, transcribed_text_sanitized, | |
| image_category, predicted_intent, intent_confidence, | |
| extracted_entities_json, route, matched_record_id, | |
| matched_record_name, retrieval_score, final_confidence, | |
| fallback_triggered, response_time_ms, time_to_first_response_ms, | |
| intent_latency_ms, retrieval_latency_ms, vision_latency_ms, | |
| speech_latency_ms, task_completed, model_used, | |
| sources_used_json, safety_notes_json | |
| FROM chat_interactions WHERE interaction_id = :interaction_id LIMIT 1 | |
| """, | |
| {"interaction_id": interaction_id}, | |
| ) | |
| if not rows: | |
| return "No matching interaction was found.", {} | |
| return "Interaction evidence loaded.", rows[0] | |
| def search_interactions( | |
| self, | |
| search_text: str | None = None, | |
| data_sources: list[str] | None = None, | |
| modality: str = "all", | |
| limit: int | float = 25, | |
| ) -> tuple[str, list[dict[str, Any]], Any]: | |
| """Search sanitized evidence without requiring a known interaction ID.""" | |
| if not self.neon.is_configured(): | |
| return ( | |
| "Search unavailable: Neon is not configured.", | |
| [], | |
| {"choices": [], "value": None}, | |
| ) | |
| sources = [ | |
| item | |
| for item in (data_sources or DEFAULT_BEHAVIOUR_SOURCES) | |
| if item in ALL_DATA_SOURCES | |
| ] | |
| if not sources: | |
| sources = list(DEFAULT_BEHAVIOUR_SOURCES) | |
| try: | |
| row_limit = max(1, min(100, int(limit))) | |
| except (TypeError, ValueError): | |
| row_limit = 25 | |
| params: dict[str, Any] = { | |
| f"source_{index}": value for index, value in enumerate(sources) | |
| } | |
| clauses = [ | |
| "ci.data_source IN (" | |
| + ",".join(f":source_{index}" for index in range(len(sources))) | |
| + ")" | |
| ] | |
| if modality and modality != "all": | |
| clauses.append("ci.input_modality = :modality") | |
| params["modality"] = modality | |
| term = (search_text or "").strip() | |
| if term: | |
| params["term"] = f"%{term}%" | |
| clauses.append( | |
| "(ci.interaction_id ILIKE :term OR ci.sanitized_query ILIKE :term " | |
| "OR ci.predicted_intent ILIKE :term OR ci.matched_record_id ILIKE :term " | |
| "OR ci.matched_record_name ILIKE :term OR ci.image_category ILIKE :term)" | |
| ) | |
| params["limit"] = row_limit | |
| rows = self.neon.fetch_all( | |
| f""" | |
| SELECT ci.timestamp, ci.interaction_id, ci.data_source, | |
| ci.input_modality, ci.sanitized_query, ci.predicted_intent, | |
| ci.intent_confidence, ci.matched_record_id, ci.matched_record_name, | |
| ci.final_confidence, ci.fallback_triggered | |
| FROM chat_interactions ci | |
| WHERE {' AND '.join(clauses)} | |
| ORDER BY ci.timestamp DESC | |
| LIMIT :limit | |
| """, | |
| params, | |
| ) | |
| choices = [ | |
| ( | |
| f"{row.get('interaction_id')} | {str(row.get('sanitized_query') or '')[:70]}", | |
| row.get("interaction_id"), | |
| ) | |
| for row in rows | |
| if row.get("interaction_id") | |
| ] | |
| dropdown = {"choices": choices, "value": choices[0][1] if choices else None} | |
| if not rows: | |
| return "No matching sanitized interactions were found.", [], dropdown | |
| scope = "recent interactions" if not term else f"matches for `{term}`" | |
| return ( | |
| f"Found **{len(rows)}** {scope}. Choose one below to load its full evidence.", | |
| rows, | |
| dropdown, | |
| ) | |