File size: 20,078 Bytes
7ca0188 830c01e 7ca0188 830c01e 7ca0188 830c01e 7ca0188 830c01e 7ca0188 830c01e 7ca0188 830c01e 7ca0188 830c01e 7ca0188 830c01e 418205d 830c01e 418205d 830c01e 418205d 830c01e 7ca0188 830c01e | 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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 | """Privacy-aware Neon logging with local CSV fallback."""
from __future__ import annotations
import csv
import json
import re
from pathlib import Path
from typing import Any
from src.config import Settings, get_settings
from src.logging_layer.neon_client import NeonClient
from src.utils.ids import (
generate_event_id,
generate_interaction_id,
generate_session_id,
)
from src.utils.sanitization import sanitize_text
from src.utils.timing import current_utc_iso
INTERACTION_FIELDS = (
"interaction_id",
"session_id",
"timestamp",
"data_source",
"test_run_id",
"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",
"expected_intent",
"intent_correct",
"fallback_reason",
)
FEEDBACK_FIELDS = (
"feedback_id",
"interaction_id",
"session_id",
"rating",
"comment_sanitized",
"frustration_flag",
"created_at",
)
API_FIELDS = (
"api_call_id",
"interaction_id",
"provider",
"api_type",
"success",
"status_code",
"duration_ms",
"error_sanitized",
"created_at",
)
VALID_FEEDBACK_RATINGS = {"helpful", "not_helpful", "neutral"}
FRUSTRATION_PATTERN = re.compile(
r"\b(wrong|not helpful|confused|useless|frustrated|again|still not)\b",
re.IGNORECASE,
)
TEST_RUN_INSERT = """INSERT INTO test_runs (
run_id, test_type, tool, configuration_version, started_at
) VALUES (
:run_id, :test_type, :tool, :configuration_version, :started_at
) ON CONFLICT (run_id) DO NOTHING"""
SESSION_INSERT = """INSERT INTO chat_sessions (
session_id, started_at, user_type, channel
) VALUES (
:session_id, :started_at, :user_type, :channel
) ON CONFLICT (session_id) DO NOTHING"""
SESSION_UPDATE = """UPDATE chat_sessions
SET ended_at = :ended_at, completed = :completed
WHERE session_id = :session_id"""
INTERACTION_INSERT = """INSERT INTO chat_interactions (
interaction_id, session_id, timestamp, data_source, test_run_id,
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
) VALUES (
:interaction_id, :session_id, :timestamp, :data_source,
NULLIF(:test_run_id, ''), :configuration_version, :input_modality,
:sanitized_query, :transcribed_text_sanitized, :image_category,
:predicted_intent, :intent_confidence,
CAST(:extracted_entities_json AS JSONB), :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,
CAST(:sources_used_json AS JSONB), CAST(:safety_notes_json AS JSONB)
)"""
INTENT_INSERT = """INSERT INTO intent_predictions (
prediction_id, interaction_id, expected_intent, predicted_intent,
confidence, correct, model_source, all_scores_json
) VALUES (
:id, :interaction_id, :expected, :predicted, :confidence, :correct,
:source, CAST(:scores AS JSONB)
)"""
RETRIEVAL_INSERT = """INSERT INTO retrieval_results (
retrieval_id, interaction_id, retrieval_type, top_k_results_json,
selected_record_id, selected_record_name, similarity_score,
expected_record_id, retrieval_correct
) VALUES (
:id, :interaction_id, :type, CAST(:results AS JSONB), :record_id,
:record_name, :score, :expected_record_id, :retrieval_correct
)"""
VISION_INSERT = """INSERT INTO vision_events (
vision_event_id, interaction_id, ocr_used, ocr_text_sanitized,
ocr_confidence, clip_used, clip_category, clip_confidence,
qwen_invoked, qwen_success, qwen_reason, processing_time_ms
) VALUES (
:id, :interaction_id, :ocr_used, :ocr_text, :ocr_confidence,
:clip_used, :clip_category, :clip_confidence, :qwen_invoked,
:qwen_success, :qwen_reason, :processing_time_ms
)"""
FALLBACK_INSERT = """INSERT INTO fallback_events (
fallback_id, interaction_id, fallback_reason, route, intent,
confidence, recommended_action
) VALUES (
:id, :interaction_id, :reason, :route, :intent, :confidence, :action
)"""
FEEDBACK_INSERT = """INSERT INTO feedback_events (
feedback_id, interaction_id, session_id, rating, comment_sanitized,
frustration_flag, created_at
) VALUES (
:feedback_id, :interaction_id, :session_id, :rating,
:comment_sanitized, :frustration_flag, :created_at
)"""
API_CALL_INSERT = """INSERT INTO api_call_logs (
api_call_id, interaction_id, provider, api_type, success, status_code,
duration_ms, error_sanitized, created_at
) VALUES (
:api_call_id, NULLIF(:interaction_id, ''), :provider, :api_type,
:success, :status_code, :duration_ms, :error_sanitized, :created_at
)"""
def detect_frustration(rating: str, comment: str | None = None) -> bool:
"""Return whether explicit feedback contains a controlled friction signal."""
clean_comment = sanitize_text(comment)
return rating == "not_helpful" or bool(FRUSTRATION_PATTERN.search(clean_comment))
class AnalyticsLogger:
def __init__(
self, settings: Settings | None = None, neon_client: NeonClient | None = None
) -> None:
self.settings = settings or get_settings()
self.neon = neon_client or NeonClient(self.settings)
self.sessions = set()
@staticmethod
def _append(path: str, fields: tuple[str, ...], row: dict[str, Any]) -> None:
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
exists = target.is_file() and target.stat().st_size > 0
with target.open("a", encoding="utf-8", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=fields, extrasaction="ignore")
if not exists:
writer.writeheader()
writer.writerow({field: row.get(field, "") for field in fields})
def _store(
self,
query: str,
params: dict[str, Any],
path: str | None = None,
fields: tuple[str, ...] | None = None,
) -> str:
if self.neon.is_configured() and self.neon.execute(query, params):
return "neon"
if self.settings.fallback_to_csv_logs and path and fields:
self._append(path, fields, params)
return "csv"
return "memory"
def ensure_test_run(
self, run_id: str | None, data_source: str, tool: str | None = None
) -> bool:
"""Create the referenced test run before storing interaction events."""
run_id = (run_id or "").strip()
if not run_id or not self.neon.is_configured():
return True
tool_name = tool or (
{
"locust": "locust",
"hypothesis": "hypothesis",
"structured_test": "gradio",
}.get(data_source, "novaguide")
)
return self.neon.execute(
TEST_RUN_INSERT,
{
"run_id": run_id,
"test_type": data_source,
"tool": tool_name,
"configuration_version": self.settings.configuration_version,
"started_at": current_utc_iso(),
},
)
def start_session(
self,
session_id: str | None = None,
user_type: str = "anonymous",
channel: str = "gradio",
) -> dict[str, Any]:
sid = session_id or generate_session_id()
self.sessions.add(sid)
stored = "csv" if self.settings.fallback_to_csv_logs else "memory"
if self.neon.is_configured():
stored = self._store(
SESSION_INSERT,
{
"session_id": sid,
"started_at": current_utc_iso(),
"user_type": user_type,
"channel": channel,
},
)
return {"success": True, "session_id": sid, "stored_in": stored, "error": None}
def end_session(self, session_id: str, completed: bool = True) -> bool:
self.sessions.discard(session_id)
return (
self.neon.execute(
SESSION_UPDATE,
{
"ended_at": current_utc_iso(),
"completed": completed,
"session_id": session_id,
},
)
if self.neon.is_configured()
else True
)
def _build_interaction_row(
self,
interaction_id: str,
session_id: str,
response: dict[str, Any],
user: dict[str, Any],
expected_intent: str | None,
task_completed: bool | None,
) -> dict[str, Any]:
"""Build the normalised analytics record for one chatbot interaction."""
intent = response.get("intent", "")
debug = response.get("debug", {}) or {}
image_result = user.get("image_result", {}) or {}
speech_result = user.get("speech_result", {}) or {}
qwen_result = image_result.get("qwen") or {}
return {
"interaction_id": interaction_id,
"session_id": session_id,
"timestamp": current_utc_iso(),
"data_source": user.get("data_source")
or self.settings.analytics_data_source,
"test_run_id": user.get("test_run_id", ""),
"configuration_version": user.get("configuration_version")
or self.settings.configuration_version,
"input_modality": user.get("modality") or response.get("modality", "text"),
"sanitized_query": sanitize_text(user.get("text")),
"transcribed_text_sanitized": sanitize_text(user.get("transcribed_text")),
"image_category": sanitize_text(user.get("image_category")),
"predicted_intent": intent,
"intent_confidence": float(response.get("intent_confidence", 0)),
"extracted_entities_json": json.dumps(response.get("entities", {})),
"route": response.get("route", ""),
"matched_record_id": response.get("matched_record_id") or "",
"matched_record_name": response.get("matched_record_name") or "",
"retrieval_score": float(response.get("retrieval_score", 0)),
"final_confidence": float(response.get("final_confidence", 0)),
"fallback_triggered": bool(response.get("fallback_triggered")),
"response_time_ms": int(response.get("response_time_ms", 0)),
"time_to_first_response_ms": int(
response.get(
"time_to_first_response_ms", response.get("response_time_ms", 0)
)
),
"intent_latency_ms": int(debug.get("intent_latency_ms", 0) or 0),
"retrieval_latency_ms": int(debug.get("retrieval_latency_ms", 0) or 0),
"vision_latency_ms": int(image_result.get("processing_time_ms", 0) or 0),
"speech_latency_ms": int(speech_result.get("processing_time_ms", 0) or 0),
"task_completed": None if task_completed is None else bool(task_completed),
"model_used": debug.get("llm_model")
or ("qwen_vl" if qwen_result.get("success") else "template"),
"sources_used_json": json.dumps(response.get("sources_used", {})),
"safety_notes_json": json.dumps(response.get("safety_notes", [])),
"expected_intent": expected_intent or "",
"intent_correct": (
None if expected_intent is None else expected_intent == intent
),
"fallback_reason": (
debug.get("routing_reason", "")
if response.get("fallback_triggered")
else ""
),
}
def log_interaction(
self,
session_id: str,
response: dict[str, Any],
user_input: dict[str, Any] | None = None,
expected_intent: str | None = None,
task_completed: bool | None = None,
) -> dict[str, Any]:
user = user_input or {}
iid = generate_interaction_id()
intent = response.get("intent", "")
debug = response.get("debug", {}) or {}
image_result = user.get("image_result", {}) or {}
row = self._build_interaction_row(
iid,
session_id,
response,
user,
expected_intent,
task_completed,
)
self.ensure_test_run(row["test_run_id"], row["data_source"])
query = INTERACTION_INSERT
stored = self._store(
query, row, self.settings.local_interactions_log, INTERACTION_FIELDS
)
if stored == "neon":
self.neon.execute(
INTENT_INSERT,
{
"id": generate_event_id("pred"),
"interaction_id": iid,
"expected": expected_intent,
"predicted": intent,
"confidence": row["intent_confidence"],
"correct": (
None if expected_intent is None else expected_intent == intent
),
"source": debug.get("intent_source", ""),
"scores": "{}",
},
)
if row["matched_record_id"]:
self.neon.execute(
RETRIEVAL_INSERT,
{
"id": generate_event_id("ret"),
"interaction_id": iid,
"type": row["route"],
"results": json.dumps(debug.get("retrieval_results", [])),
"record_id": row["matched_record_id"],
"record_name": row["matched_record_name"],
"score": row["retrieval_score"],
"expected_record_id": user.get("expected_record_id") or None,
"retrieval_correct": (
None
if not user.get("expected_record_id")
else user.get("expected_record_id")
== row["matched_record_id"]
),
},
)
if image_result:
self.neon.execute(
VISION_INSERT,
{
"id": generate_event_id("vision"),
"interaction_id": iid,
"ocr_used": bool(
(image_result.get("ocr") or {}).get("success")
),
"ocr_text": sanitize_text(
(image_result.get("ocr") or {}).get("text")
),
"ocr_confidence": float(
(image_result.get("ocr") or {}).get("confidence", 0) or 0
),
"clip_used": bool(image_result.get("success")),
"clip_category": sanitize_text(
image_result.get("predicted_category")
),
"clip_confidence": float(
image_result.get("confidence", 0) or 0
),
"qwen_invoked": bool(
(image_result.get("qwen") or {}).get("invoked")
),
"qwen_success": bool(
(image_result.get("qwen") or {}).get("success")
),
"qwen_reason": sanitize_text(
(image_result.get("qwen") or {}).get("reason")
),
"processing_time_ms": int(
image_result.get("processing_time_ms", 0) or 0
),
},
)
if row["fallback_triggered"]:
self.neon.execute(
FALLBACK_INSERT,
{
"id": generate_event_id("fb"),
"interaction_id": iid,
"reason": row["fallback_reason"],
"route": row["route"],
"intent": intent,
"confidence": row["intent_confidence"],
"action": "Use official BER information or rephrase.",
},
)
success = stored in {"neon", "csv"}
return {
"success": success,
"interaction_id": iid if success else "",
"session_id": session_id,
"stored_in": stored,
"error": None if success else "Analytics persistence unavailable.",
}
def log_feedback(
self,
interaction_id: str,
session_id: str,
rating: str,
comment: str | None = None,
) -> dict[str, Any]:
rating = rating if rating in VALID_FEEDBACK_RATINGS else "neutral"
clean = sanitize_text(comment)
frustrated = detect_frustration(rating, clean)
row = {
"feedback_id": generate_event_id("feedback"),
"interaction_id": interaction_id,
"session_id": session_id,
"rating": rating,
"comment_sanitized": clean,
"frustration_flag": frustrated,
"created_at": current_utc_iso(),
}
stored = self._store(
FEEDBACK_INSERT,
row,
self.settings.local_feedback_log,
FEEDBACK_FIELDS,
)
return {
"success": True,
"feedback_id": row["feedback_id"],
"stored_in": stored,
"frustration_flag": frustrated,
"error": None,
}
def log_api_call(
self,
interaction_id: str | None,
provider: str,
api_type: str,
success: bool,
status_code: int | None = None,
duration_ms: int | None = None,
error: str | None = None,
) -> dict[str, Any]:
row = {
"api_call_id": generate_event_id("api"),
"interaction_id": interaction_id or "",
"provider": sanitize_text(provider),
"api_type": sanitize_text(api_type),
"success": bool(success),
"status_code": "" if status_code is None else status_code,
"duration_ms": "" if duration_ms is None else duration_ms,
"error_sanitized": sanitize_text(error),
"created_at": current_utc_iso(),
}
stored = self._store(
API_CALL_INSERT,
row,
self.settings.local_api_call_log,
API_FIELDS,
)
return {
"success": True,
"api_call_id": row["api_call_id"],
"stored_in": stored,
"error": None,
}
def export_local_logs(self) -> dict[str, Any]:
return {
"interactions": self.settings.local_interactions_log,
"feedback": self.settings.local_feedback_log,
"api_calls": self.settings.local_api_call_log,
"success": True,
}
|