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:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user