"""Manual Search CLI for PostgreSQL + pgvector and RAG Question Answering. Features: - Live, End-to-End Tracing through backend SearchService pipeline - Real-time logging of Latency, Vectors, SQL Queries, and Cutoff Evaluation - Free local execution using Ollama (bge-m3) and pgvector - Optional Grounded LLM Synthesis (--no-llm for 100% free offline mode) - Interactive prompt or single CLI execution Usage: # Free vector search with complete live trace: python scripts/search_cli.py "اقای دانش کیه؟" --no-llm # Test with calibrated cutoff: python scripts/search_cli.py "اقای دانش کیه؟" --no-llm --cutoff 0.3368 # Interactive mode: python scripts/search_cli.py --no-llm """ import argparse from array import array import json import os import re import sys import time from uuid import UUID # Ensure UTF-8 output on Windows terminal if sys.platform == "win32": try: sys.stdout.reconfigure(encoding="utf-8") sys.stderr.reconfigure(encoding="utf-8") except Exception: pass import httpx from sqlalchemy import text PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) if PROJECT_ROOT not in sys.path: sys.path.insert(0, PROJECT_ROOT) from app.core.config import settings as app_settings from app.infrastructure.database import create_database from app.modules.documents.settings import IngestionSettings from app.modules.knowledge.evidence import CalibratedCutoff, SearchExecution from app.modules.knowledge.service import SearchService, KnowledgeError from app.worker import factories class LiveConsoleTracer: """Renders real-time trace events with timing in standard English.""" def __init__(self, verbose=True): self.verbose = verbose self.start_mono = time.monotonic() def __call__(self, event: dict): stage = event.get("stage", "UNKNOWN") elapsed = event.get("elapsed_ms", 0.0) if stage == "INSPECT_START" or stage == "SEARCH_START": print(f"\n┌─ [STAGE 1/6: INTAKE & CONTEXT] (+{elapsed:.1f}ms)") print(f"│ • Query: \"{event.get('query')}\"") if event.get("user_id"): print(f"│ • Actor ID: {event.get('user_id')}") elif stage == "QUERY_PREPROCESSED": patterns = event.get("patterns", []) print(f"├─ [STAGE 2/6: NORMALIZATION & LEXICAL] (+{elapsed:.1f}ms)") print(f"│ • Normalized Query (NFC): \"{event.get('normalized_query')}\"") print(f"│ • Policy: {event.get('policy')}") if patterns: print(f"│ • Lexical Regex Patterns: {patterns}") else: print(f"│ • Lexical Regex Patterns: (none extracted)") elif stage == "EMBEDDING_DISPATCH": print(f"├─ [STAGE 3/6: EMBEDDING DISPATCH] (+{elapsed:.1f}ms)") print(f"│ • Provider: {event.get('provider')} | Model: {event.get('model')} (Dimensions: {event.get('dimensions')})") elif stage == "EMBEDDING_RECEIVED": print(f"├─ [STAGE 3/6: EMBEDDING RECEIVED] (+{elapsed:.1f}ms)") print(f"│ • Embedding Latency: {event.get('latency_ms', 0):.1f} ms") print(f"│ • Vector Dimensions: {event.get('dimensions')} float32") print(f"│ • Vector Sample: {event.get('sample_components')}") elif stage == "DATABASE_QUERY_DONE": print(f"├─ [STAGE 4/6: DATABASE PGVECTOR RETRIEVAL] (+{elapsed:.1f}ms)") print(f"│ • SQL Latency: {event.get('latency_ms', 0):.1f} ms") print(f"│ • Semantic Branch Candidates: {event.get('semantic_count')}") print(f"│ • Lexical Branch Candidates: {event.get('exact_count')}") print(f"│ • Total Merged Candidates: {event.get('merged_count')}") top_3 = event.get("top_3", []) if top_3: print("│ • Top-3 Ranked Candidates:") for i, c in enumerate(top_3, 1): exact_flag = " [EXACT MATCH]" if c.get("exact") else " [SEMANTIC]" print(f"│ [{i}] {c.get('title')} | Distance: {c.get('distance')}{exact_flag}") elif stage == "CUTOFF_ADMISSION": cutoff = event.get("cutoff_distance") status = event.get("status") admitted = event.get("admitted_count", 0) evaluated = event.get("evaluated_count", 0) print(f"├─ [STAGE 5/6: CUTOFF EVALUATION] (+{elapsed:.1f}ms)") print(f"│ • Configured Cutoff: {cutoff}") print(f"│ • Verdict Status: {status}") print(f"│ • Admitted Evidence: {admitted} / {evaluated}") elif stage == "SEARCH_COMPLETE" or stage == "INSPECT_COMPLETE": total = elapsed print(f"└─ [STAGE 6/6: PIPELINE COMPLETE] (+{total:.1f}ms)") print(f" • Total Retrieval Monotonic Latency: {total:.1f} ms\n") def get_default_user_and_org(conn): """Retrieve the first active user and organization ID from DB.""" row = conn.execute( text("SELECT id, organization_id, username FROM users WHERE is_enabled ORDER BY created_at LIMIT 1") ).mappings().one_or_none() if row is None: raise RuntimeError("No enabled user found in database.") return row["id"], row["organization_id"], row["username"] def ask_llm(query, chunks): """Send retrieved context and query to the configured LLM for answer synthesis.""" if not chunks: return "No relevant context found to answer the query." context_text = "\n\n---\n\n".join( [f"[Document: {c.get('title', c.get('document_title', ''))}]\n{c.get('text', c.get('chunk_text', ''))}" for c in chunks] ) system_prompt = ( "You are an organizational AI assistant. Answer the user prompt accurately " "and factually based strictly on the reference documents below." ) user_prompt = f"Reference Documents:\n{context_text}\n\nUser Question: {query}\n\nAnswer:" try: response = httpx.post( f"{app_settings.llm_base_url}/chat/completions", headers={"Authorization": f"Bearer {app_settings.api_key}"}, json={ "model": app_settings.llm_model, "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}, ], "temperature": 0.0, }, timeout=45.0, ) if response.status_code == 200: data = response.json() return data["choices"][0]["message"]["content"].strip() else: return f"[LLM Error: Status {response.status_code} - {response.text}]" except Exception as exc: return f"[LLM Request Error: {exc}]" def print_chunk_snippet(chunk, keywords): """Format and display snippet highlighting keywords.""" text_content = chunk.get("text") or chunk.get("chunk_text") or "" lines = text_content.strip().splitlines() matched_idx = [] for idx_l, line_str in enumerate(lines): for kw in keywords: if kw in line_str or kw.replace("آ", "ا") in line_str or kw.replace("ا", "آ") in line_str: matched_idx.append(idx_l) break if matched_idx: start_l = max(0, matched_idx[0] - 2) end_l = min(len(lines), max(matched_idx[-1] + 3, start_l + 10)) preview_lines = [] if start_l > 0: preview_lines.append("... [preceding lines]") for i in range(start_l, end_l): prefix = "👉 " if i in matched_idx else " " preview_lines.append(f"{prefix}{lines[i]}") if end_l < len(lines): preview_lines.append("... [remaining lines]") preview = "\n ".join(preview_lines) else: preview = "\n ".join(lines[:8]) if len(lines) > 8: preview += "\n ... [remaining lines]" print(f" Chunk Text:\n {preview}") def run_traced_search(query, user_id, org_id, engine, settings, provider, counter, top_k=3, cutoff_val=None, with_llm=False): """Run backend search with live tracing.""" print("=" * 72) print(f"🔍 EXECUTE SEARCH TRACE: \"{query}\"") print(f"⚙️ CONFIG: top_k={top_k} | cutoff={cutoff_val or 'None (Uncalibrated)'} | LLM={'Enabled' if with_llm else 'Disabled (Free/Local)'}") print("=" * 72) tracer = LiveConsoleTracer() execution = SearchExecution(user_id=user_id, trace_callback=tracer) cutoff_obj = None if cutoff_val is not None: cutoff_obj = CalibratedCutoff( profile=settings.processing_profile()["embedding"], distance=float(cutoff_val), calibration_id="custom_cli_cutoff" ) service = SearchService(engine, settings, provider, counter, cutoff=cutoff_obj) try: if cutoff_obj is not None: # Calibrated search with cutoff admission response = service.search(execution, query) admitted_sources = response.get("sources", []) chunks_to_display = admitted_sources[:top_k] else: # Inspection uncalibrated mode raw_result = service.inspect(execution, query) chunks_to_display = raw_result.get("candidates", [])[:top_k] except Exception as exc: print(f"❌ Search Error: {exc}") return # Extract clean keywords for snippet highlighting clean = re.sub(r"[؟?!.,;:()\[\]\"'\-_/]", " ", query).strip() keywords = [w for w in clean.split() if len(w) > 1] print("📑 RETRIEVAL RESULTS & SELECTED CHUNKS:") if not chunks_to_display: print(" ⚠️ No chunks retrieved or admitted.") else: for idx, c in enumerate(chunks_to_display, 1): title = c.get("title", "Document") dist = c.get("cosine_distance") dist_str = f"{dist:.4f}" if dist is not None else "N/A" exact_badge = " [EXACT MATCH]" if c.get("exact_match") else " [SEMANTIC]" print(f"\n[{idx}] Document: {title}{exact_badge}") print(f" Chunk ID: {c.get('chunk_id')}") if dist is not None: sim_pct = max(0.0, (1.0 - dist) * 100) print(f" Cosine Distance: {dist_str} | Approx Similarity: {sim_pct:.1f}%") print_chunk_snippet(c, keywords) # Optional LLM step (only if explicitly enabled) if with_llm and chunks_to_display: print("\n" + "-" * 72) print("🤖 Synthesizing answer via LLM...") answer = ask_llm(query, chunks_to_display) print("\n💡 LLM Response:") print(answer) print("-" * 72) def main(): parser = argparse.ArgumentParser(description="Manual Search CLI with Live Tracing on pgvector") parser.add_argument("query", nargs="?", help="Search query string") parser.add_argument("-k", "--top-k", type=int, default=3, help="Top K candidate chunks (default: 3)") parser.add_argument("--cutoff", type=float, default=None, help="Cosine cutoff distance (e.g. 0.3368 or 0.65)") parser.add_argument("--no-llm", action="store_true", default=True, help="Disable LLM synthesis (completely free/local)") parser.add_argument("--with-llm", action="store_true", help="Enable LLM synthesis call") args = parser.parse_args() with_llm = bool(args.with_llm and not args.no_llm) settings = IngestionSettings() _, provider_factory = factories(settings) provider, counter = provider_factory(settings.processing_profile()) engine = create_database(settings.database_url.get_secret_value()) try: with engine.connect() as conn: user_id, org_id, username = get_default_user_and_org(conn) except Exception as exc: print(f"❌ Database Connection Error: {exc}", file=sys.stderr) return 1 query_text = args.query if query_text: run_traced_search( query=query_text, user_id=user_id, org_id=org_id, engine=engine, settings=settings, provider=provider, counter=counter, top_k=args.top_k, cutoff_val=args.cutoff, with_llm=with_llm ) else: print("=" * 72) print("🚀 Interactive Live Search Tracer (pgvector)") print(f"👤 User: {username} | Org: {org_id}") print(f"🧠 Embedding Model: {settings.embedding_profile.model} (Local)") print("Type 'exit' or 'q' to quit.") print("=" * 72) while True: try: user_input = input("\n👉 Enter Query: ").strip() except (KeyboardInterrupt, EOFError): print("\nGoodbye!") break if not user_input: continue if user_input.lower() in ("exit", "quit", "q"): print("Exiting.") break run_traced_search( query=user_input, user_id=user_id, org_id=org_id, engine=engine, settings=settings, provider=provider, counter=counter, top_k=args.top_k, cutoff_val=args.cutoff, with_llm=with_llm ) return 0 if __name__ == "__main__": sys.exit(main())