Files
rag-technical-docs-assistant/app/modules/knowledge/langchain_tool.py
T
11linear11 a73a496c54 feat(backend): deliver Phase 3 document and voice integration
Add authenticated upload, review, retry and knowledge-selection HTTP flows with bounded JSON processing and frozen OCR policy.

Preserve Gemini/OpenAI provider selection and fenced lifecycle semantics; retain FAQ preambles and uncertain vision candidates, and expose opt-in uncalibrated voice transport diagnostics.

Include frontend integration examples, aligned contracts and deterministic regressions. Validation: 1767 provider-free tests passed; all 404 PostgreSQL scenarios have passing evidence across the documented runs.
2026-10-09 17:43:52 -04:00

219 lines
9.4 KiB
Python

"""Lazy LangChain boundary over the canonical search service."""
import asyncio
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
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,
)
@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
# 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)
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,
)