feat(voice): specialize prompt for Isfahan Industrial Parks, emit source excerpts, and bound generation

- Specialize voice assistant identity and agent system prompt for «شرکت شهرک‌های صنعتی اصفهان» (English instructions with Persian proper names)
- Emit bounded chunk text excerpts (up to 2000 chars) and identify primary_source in realtime sources events
- Bound OpenAI output generation via OPENAI_REALTIME_MAX_OUTPUT_TOKENS and add answer_limited event
- Handle old-turn search cancellation safely on turn supersession
- Add end-to-end search tracing pipeline and diagnostic CLI
- Add database organization title and settings update script
This commit is contained in:
amirhosein mazaheri
2026-10-12 17:35:28 +03:30
parent f14166a89f
commit 117fda7cc9
29 changed files with 1476 additions and 67 deletions
+25
View File
@@ -5,6 +5,9 @@ import math
from threading import RLock
from uuid import UUID, uuid4
import time
from typing import Any
from app.modules.knowledge.lexical import LEXICAL_POLICY
MAX_BRANCH_CANDIDATES = 50
@@ -56,11 +59,33 @@ class SearchExecution:
"""Created by the trusted caller, never populated from model arguments."""
user_id: UUID
request_id: str = field(default_factory=lambda: str(uuid4()))
trace_callback: Any = None
trace_events: list = field(default_factory=list)
_start_monotonic: float = field(default_factory=time.monotonic, init=False, repr=False)
_authority: dict | None = field(default=None, init=False, repr=False)
_epoch: int | None = field(default=None, init=False, repr=False)
_refs: dict = field(default_factory=dict, init=False, repr=False)
_lock: RLock = field(default_factory=RLock, init=False, repr=False)
def record_trace(self, stage: str, **details):
with self._lock:
now_mono = time.monotonic()
elapsed_ms = round((now_mono - self._start_monotonic) * 1000, 2)
event = {
"stage": stage,
"elapsed_ms": elapsed_ms,
"timestamp_utc": time.time(),
"request_id": self.request_id,
**details,
}
self.trace_events.append(event)
if self.trace_callback is not None:
try:
self.trace_callback(event)
except Exception:
pass
return event
def capture(self, current, epoch):
with self._lock:
if self._authority is None:
+17
View File
@@ -2,6 +2,7 @@
import asyncio
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
import logging
import math
from threading import Condition, Event
import time
@@ -12,6 +13,18 @@ from app.modules.knowledge.service import (
KnowledgeError, SearchInput, authority, sql_error, transaction,
)
import sys
tool_logger = logging.getLogger("app.search.tool")
tool_logger.setLevel(logging.INFO)
if not tool_logger.handlers and not any(h for h in logging.getLogger("app").handlers):
_tool_h = logging.StreamHandler(sys.stderr)
_tool_h.setFormatter(
logging.Formatter("%(asctime)s [%(levelname)s] [%(name)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
)
tool_logger.addHandler(_tool_h)
@dataclass(frozen=True)
class ToolContext:
@@ -90,6 +103,8 @@ class SearchToolRunner:
stopped = self._stop(ctx, deadline, cancelled)
if stopped:
return stopped
tool_logger.info("[TOOL:SEARCH_KNOWLEDGE:START] User=%s query=%r context=%r",
ctx.execution.user_id, query, context)
# Persisted authority is captured outside model input, on a worker.
with transaction(service.engine) as conn:
current, settings = authority(conn, ctx.execution.user_id)
@@ -99,6 +114,8 @@ class SearchToolRunner:
if stopped:
return stopped
result = service.search(ctx.execution, query, context)
tool_logger.info("[TOOL:SEARCH_KNOWLEDGE:COMPLETE] User=%s status=%s sources=%d",
ctx.execution.user_id, result.get("status"), len(result.get("sources", [])))
if result["status"] != "error":
# Recheck this delivery boundary after the service handoff.
with transaction(service.engine) as conn:
+79 -7
View File
@@ -21,6 +21,30 @@ from app.modules.knowledge.evidence import (
CalibratedCutoff, SearchExecution, RETRIEVAL_POLICY, MAX_BRANCH_CANDIDATES,
admit_candidates, merge_candidates,
)
import logging
import sys
import time
logger = logging.getLogger("app.search.trace")
logger.setLevel(logging.INFO)
if not logger.handlers and not any(h for h in logging.getLogger("app").handlers):
_trace_handler = logging.StreamHandler(sys.stderr)
_trace_handler.setFormatter(
logging.Formatter("%(asctime)s [%(levelname)s] [%(name)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
)
logger.addHandler(_trace_handler)
def _trace(execution, stage, **details):
elapsed_ms = 0.0
event = None
if hasattr(execution, "record_trace"):
event = execution.record_trace(stage, **details)
elapsed_ms = event.get("elapsed_ms", 0.0)
details_str = " | ".join(f"{k}={v!r}" for k, v in details.items()) if details else ""
logger.info("[%s] (+%.1fms) %s", stage, elapsed_ms, details_str)
return event
class KnowledgeError(ValueError):
@@ -53,8 +77,16 @@ def sql_error(exc):
class SearchInput(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
query: str = Field(min_length=1, max_length=2000)
context: str | None = Field(default=None, max_length=2000)
query: str = Field(
min_length=1,
max_length=2000,
description="Clean, concise search terms or entity names only (e.g. 'آقای دانش' or 'معاون برنامه ریزی'). Do NOT include conversational filler, meta-narration, or 'کاربر می‌پرسد'."
)
context: str | None = Field(
default=None,
max_length=2000,
description="Leave null unless referencing a specific formal document identifier. Never use for conversational commentary or explanations."
)
@field_validator("query", "context")
@classmethod
@@ -187,13 +219,20 @@ class SearchService:
self.provider, self.counter = provider, token_counter
self.cutoff = cutoff
def inspect(self, user_id, query, context=None):
result = self.candidates(SearchExecution(user_id), query, context)
def inspect(self, user_or_execution, query, context=None):
if isinstance(user_or_execution, SearchExecution):
execution = user_or_execution
else:
execution = SearchExecution(user_or_execution)
_trace(execution, "INSPECT_START", query=query, context=context)
result = self.candidates(execution, query, context)
result["candidates"] = admit_candidates(result["candidates"])
_trace(execution, "INSPECT_COMPLETE", candidates_count=len(result["candidates"]))
return result
def search(self, execution, query, context=None):
"""Canonical API 7.2 outcomes; missing calibration is a technical error."""
_trace(execution, "SEARCH_START", query=query, context=context, user_id=str(execution.user_id))
try:
SearchInput(query=query, context=context)
if not isinstance(self.cutoff, CalibratedCutoff):
@@ -202,15 +241,21 @@ class SearchService:
or self.cutoff.retrieval_policy != RETRIEVAL_POLICY):
raise KnowledgeError("PROFILE_MISMATCH", "Calibration differs from search profile or policy")
result = self.candidates(execution, query, context)
return self._handoff(execution, result)
response = self._handoff(execution, result)
_trace(execution, "SEARCH_COMPLETE", status=response.get("status"), sources_count=len(response.get("sources", [])))
return response
except KnowledgeError as exc:
error = exc
_trace(execution, "SEARCH_ERROR", code=exc.code, message=str(exc))
except ValidationError:
error = KnowledgeError("VALIDATION_ERROR", "Invalid search arguments", status=422)
_trace(execution, "SEARCH_ERROR", code="VALIDATION_ERROR", message=str(error))
except SQLAlchemyError as exc:
error = sql_error(exc)
_trace(execution, "SEARCH_ERROR", code=error.code, message=str(error))
except Exception:
error = KnowledgeError("SEARCH_FAILED", "Knowledge retrieval failed")
_trace(execution, "SEARCH_ERROR", code="SEARCH_FAILED", message=str(error))
return dict(status="error", sources=[], error=dict(
code=error.code, message=str(error), request_id=execution.request_id,
retryable=error.retryable))
@@ -235,9 +280,15 @@ class SearchService:
raise KnowledgeError("CONTEXT_REVOKED", "Knowledge access changed before search handoff")
rows = admit_candidates(result["candidates"], self.cutoff.distance)
allocate = references.enter_context(execution.source_handoff())
sources = allocate(rows)
_trace(execution, "CUTOFF_ADMISSION",
cutoff_distance=self.cutoff.distance,
evaluated_count=len(result["candidates"]),
admitted_count=len(rows),
status="ok" if rows else "no_evidence")
response = dict(status="ok" if rows else "no_evidence",
knowledge_revision=result["knowledge_revision"],
sources=allocate(rows),
sources=sources,
warnings=[] if rows else ["insufficient_support"])
# Transaction commit above is the handoff boundary. ExitStack then
# publishes staged reference mappings, or discards them on failure.
@@ -287,12 +338,19 @@ class SearchService:
value = normalize_search_text(value, self.settings.normalization_policy)
limits.validate_batch([value], self.counter)
patterns = exact_patterns(request.query, request.context)
_trace(execution, "QUERY_PREPROCESSED",
policy=self.settings.normalization_policy,
normalized_query=value,
patterns=list(patterns))
with transaction(self.engine) as conn:
current, snapshot = authority(conn, execution.user_id)
if not execution.capture(current, snapshot["access_epoch"]):
raise KnowledgeError("CONTEXT_REVOKED", "Knowledge access changed during execution")
compatibility(conn)
# No database connection or transaction is held during the remote call.
embed_start = time.monotonic()
_trace(execution, "EMBEDDING_DISPATCH", provider=profile.provider, model=profile.model, dimensions=profile.dimensions)
try:
vectors = self.provider.embed([value])
except EmbeddingProviderError as exc:
@@ -304,6 +362,7 @@ class SearchService:
raise KnowledgeError("INVALID_VECTOR", "Query embedding response is invalid") from None
except Exception:
raise KnowledgeError("PROVIDER_UNAVAILABLE", "Query embedding provider failed", retryable=True) from None
embed_latency_ms = round((time.monotonic() - embed_start) * 1000, 2)
verify_provider()
if not isinstance(vectors, (list, tuple)) or len(vectors) != 1:
raise KnowledgeError("INVALID_VECTOR", "Exactly one query vector required")
@@ -312,6 +371,10 @@ class SearchService:
vector.frombytes(packed_vector(vectors[0], profile.dimensions))
except EmbeddingError:
raise KnowledgeError("INVALID_VECTOR", "Query vector must have a valid float32 cosine norm") from None
_trace(execution, "EMBEDDING_RECEIVED",
latency_ms=embed_latency_ms,
dimensions=len(vector),
sample_components=[round(float(x), 4) for x in vector[:5]])
with transaction(self.engine) as conn:
try:
final, settings = authority(conn, execution.user_id)
@@ -339,6 +402,7 @@ class SearchService:
AND d.deleted_at IS NULL AND d.content_purged_at IS NULL
AND d.processing_profile->'embedding'=CAST(:profile AS jsonb)
"""
db_start = time.monotonic()
semantic = conn.execute(text(base + " ORDER BY cosine_distance,c.id LIMIT :branch_limit"),
params).mappings().all()
exact = []
@@ -346,7 +410,15 @@ class SearchService:
exact = conn.execute(text(base + " AND " + SQL_LEXICAL_TEXT +
" ~ ANY(CAST(:patterns AS text[])) ORDER BY cosine_distance,c.id LIMIT :branch_limit"),
params).mappings().all()
db_latency_ms = round((time.monotonic() - db_start) * 1000, 2)
merged = merge_candidates(semantic, exact)
_trace(execution, "DATABASE_QUERY_DONE",
latency_ms=db_latency_ms,
semantic_count=len(semantic),
exact_count=len(exact),
merged_count=len(merged),
top_3=[{"doc_id": str(r["document_id"]), "title": r["title"], "distance": round(float(r["cosine_distance"]), 4), "exact": r["exact_match"]} for r in merged[:3]])
return dict(kind="uncalibrated_candidates", semantic_quality="not_assessed",
knowledge_revision=settings["knowledge_revision"],
access_epoch=settings["access_epoch"],
candidates=merge_candidates(semantic, exact))
candidates=merged)