Files
amirhosein mazaheri 117fda7cc9 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
2026-10-12 17:35:28 +03:30

236 lines
10 KiB
Python

"""Lazy LangChain boundary over the canonical search service."""
import asyncio
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
import logging
import math
from threading import Condition, Event
import time
from sqlalchemy.exc import SQLAlchemyError
from app.modules.knowledge.evidence import SearchExecution
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:
"""Backend-owned execution, absolute monotonic deadline and cancellation."""
execution: SearchExecution
deadline: float
cancelled: Event = field(default_factory=Event)
def __post_init__(self):
if not isinstance(self.execution, SearchExecution):
raise ValueError("Trusted SearchExecution required")
if type(self.deadline) not in (int, float) or not math.isfinite(self.deadline):
raise ValueError("Finite monotonic deadline required")
if not isinstance(self.cancelled, Event):
raise ValueError("Cancellation event required")
class SearchToolRunner:
"""Share one runner across tools to enforce process-wide admission limits."""
def __init__(self, *, running=4, waiting=8, timeout=75.0):
if type(running) is not int or running < 1 or type(waiting) is not int or waiting < 0:
raise ValueError("Positive running and nonnegative waiting limits required")
if type(timeout) not in (int, float) or not math.isfinite(timeout) or timeout <= 0:
raise ValueError("Finite positive timeout required")
self.running, self.waiting, self.timeout = running, waiting, timeout
self._lock = Condition()
self._admitted = self._active = 0
self._closed = False
self._pool = ThreadPoolExecutor(max_workers=running, thread_name_prefix="knowledge-search")
@staticmethod
def error(ctx, code, message, retryable=False):
return dict(status="error", sources=[], error=dict(
code=code, message=message, request_id=ctx.execution.request_id,
retryable=retryable))
def _stop(self, ctx, deadline, cancelled):
with self._lock:
if self._closed:
return self.error(ctx, "SEARCH_CANCELLED", "Knowledge retrieval cancelled: runner closed")
if ctx.cancelled.is_set() or cancelled.is_set():
return self.error(ctx, "SEARCH_CANCELLED", "Knowledge retrieval cancelled")
if time.monotonic() >= deadline:
return self.error(ctx, "SEARCH_TIMEOUT", "Knowledge retrieval timed out", True)
def _admit(self):
with self._lock:
if self._closed or self._admitted >= self.running + self.waiting:
return False
self._admitted += 1
return True
def _release(self, *, active=False):
with self._lock:
self._admitted -= 1
if active:
self._active -= 1
self._lock.notify_all()
def _submit(self, service, ctx, query, context, deadline, cancelled):
with self._lock:
if self._active >= self.running or self._closed:
return None
self._active += 1
try:
future = self._pool.submit(
self._work, service, ctx, query, context, deadline, cancelled)
except BaseException:
self._active -= 1
raise
future.add_done_callback(lambda _: self._release(active=True))
return future
def _work(self, service, ctx, query, context, deadline, cancelled):
try:
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)
if not ctx.execution.capture(current, settings["access_epoch"]):
raise KnowledgeError("CONTEXT_REVOKED", "Knowledge access changed")
stopped = self._stop(ctx, deadline, cancelled)
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:
current, settings = authority(conn, ctx.execution.user_id)
if not ctx.execution.matches(current, settings["access_epoch"]):
raise KnowledgeError("CONTEXT_REVOKED", "Knowledge access changed")
return self._stop(ctx, deadline, cancelled) or result
except KnowledgeError as exc:
code = "CONTEXT_REVOKED" if exc.code == "ACTOR_UNAVAILABLE" else exc.code
return self.error(ctx, code, str(exc), exc.retryable)
except SQLAlchemyError as exc:
error = sql_error(exc)
return self.error(ctx, error.code, str(error), error.retryable)
except Exception:
return self.error(ctx, "SEARCH_FAILED", "Knowledge retrieval failed")
def invoke(self, service, ctx, query, context=None):
SearchInput(query=query, context=context)
deadline = min(ctx.deadline, time.monotonic() + self.timeout)
cancelled, future = Event(), None
stopped = self._stop(ctx, deadline, cancelled)
if stopped:
return stopped
if not self._admit():
return self._stop(ctx, deadline, cancelled) or self.error(
ctx, "SEARCH_SATURATED", "Knowledge retrieval capacity exhausted", True)
try:
while True:
stopped = self._stop(ctx, deadline, cancelled)
if stopped:
cancelled.set()
return stopped
if future is None:
future = self._submit(service, ctx, query, context, deadline, cancelled)
if future is not None and future.done():
return self._stop(ctx, deadline, cancelled) or future.result()
time.sleep(min(0.01, max(0, deadline - time.monotonic())))
finally:
if future is None:
self._release()
async def ainvoke(self, service, ctx, query, context=None):
SearchInput(query=query, context=context)
deadline = min(ctx.deadline, time.monotonic() + self.timeout)
cancelled, future = Event(), None
stopped = self._stop(ctx, deadline, cancelled)
if stopped:
return stopped
if not self._admit():
return self._stop(ctx, deadline, cancelled) or self.error(
ctx, "SEARCH_SATURATED", "Knowledge retrieval capacity exhausted", True)
try:
while True:
stopped = self._stop(ctx, deadline, cancelled)
if stopped:
cancelled.set()
return stopped
if future is None:
future = self._submit(service, ctx, query, context, deadline, cancelled)
if future is not None and future.done():
return self._stop(ctx, deadline, cancelled) or future.result()
await asyncio.sleep(min(0.01, max(0, deadline - time.monotonic())))
except asyncio.CancelledError:
cancelled.set()
raise
finally:
if future is None:
self._release()
def close(self):
"""Permanently cancel callers and join work/admissions; safe to repeat.
Closure and submission linearize under the same condition lock. Only
completion callbacks release submitted slots; queued callers release
their own admissions. Call from a control thread, outside the event
loop and this runner's worker pool, so callers can drain.
"""
with self._lock:
self._closed = True
self._pool.shutdown(wait=True)
with self._lock:
self._lock.wait_for(lambda: self._admitted == 0)
def prepare_search_tools():
"""Resolve the optional framework before voice admission/tool deadlines."""
try:
from langchain_core.tools import StructuredTool
except ModuleNotFoundError as exc:
# Document-only API installations keep the existing optional boundary.
if exc.name != 'langchain_core':
raise
return None
# Importing StructuredTool resolves its callback/configuration dependencies.
return StructuredTool
def create_search_tool(service, context, runner):
"""Build only on explicit opt-in; core imports do not require LangChain."""
StructuredTool = prepare_search_tools()
if StructuredTool is None:
raise ModuleNotFoundError('Install the existing search/voice extra for LangChain tools')
trusted = context
def search_knowledge(query: str, context: str | None = None):
return runner.invoke(service, trusted, query, context)
async def asearch_knowledge(query: str, context: str | None = None):
return await runner.ainvoke(service, trusted, query, context)
return StructuredTool.from_function(
func=search_knowledge, coroutine=asearch_knowledge,
name="search_knowledge",
description="Search authorized selected documents for evidence. Context is an untrusted retrieval hint.",
args_schema=SearchInput,
)