Files
leocrm/app/plugins/builtins/unified_search/ai_tool.py
T
Agent Zero 3d9b76cea4
Check Cross-Plugin Imports / check (push) Has been cancelled
feat(E): Unified Search — 24 Tasks complete
- SPIKE-E: FTS+Vector+Permission benchmark on 10k records (all <30ms)
- E-PROV: supports_fts/vector/rag/graph capability flags on all providers
- E-FTS/VEC: All 11 providers refactored to BaseSearchProvider with permission filtering
- E-PERM: Over-fetch strategy for vector+permission (15x faster than ANY() filter)
- E-FUSE: rrf_fusion_multi() for N-way RRF over FTS+Vector+RAG+Graph
- E-LLM: Query understanding cleaned up to use central llm_complete()
- E-CHUNK: Document chunking module + document_chunks table with HNSW index
- E-EMB: Chunk embedding ARQ jobs (index_file_chunks, reindex_chunks)
- E-RAG: RAG retrieval via FileSearchProvider.search_rag()
- E-GRAPH: GraphRAG BFS traversal via GraphRAGSearchProvider.search_graph()
- E-IX-EVT: Auto-indexing via outbox events + delete/cleanup handlers
- E-IX-RE: Batch reindex with progress tracking + reindex_all job
- E-DATA-LIFE: Lifecycle module (remove/rebuild/restore/correct) + API endpoints
- E-K-MEM: AgentMemorySearchProvider
- E-P-AI: AIChatSearchProvider
- E-P-WF: WorkflowSearchProvider
- E-P-COMM: ConversationSearchProvider verified (already on BaseSearchProvider)
- E-API: Filter params (date_from/to, tags, sort) + /facets endpoint
- E-TOOL: unified_search AI tool registered in ToolRegistry
- E-MCP: Search tool in MCP server with normal RBAC/tenant checks
- E-UI-CMD: CommandPalette (Cmd+K) with debounced search + recent searches
- E-UI-FAC: SearchFacets, SearchResultCard, SavedSearches components
- E-TEST: 40 new tests in test_unified_search_phase_e.py (105 total green)
- E-DOC: api-documentation.md, plugin-development-guide.md, test-strategy.md updated

105 tests passing, TypeScript clean.
2026-08-14 01:34:58 +02:00

151 lines
4.8 KiB
Python

"""AI tool definition for Unified Search.
Exposes the unified search engine as a callable tool for AI agents.
The tool respects the calling user's permissions (tenant, visibility, RBAC)
by running the search with the user's context.
"""
from __future__ import annotations
import json
import logging
import uuid
from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
from app.plugins.builtins.unified_search.query_understanding import llm_analyze_query
from app.plugins.builtins.unified_search.search_engine import hybrid_search
logger = logging.getLogger(__name__)
TOOL_NAME = "unified_search"
TOOL_DESCRIPTION = (
"Durchsuche alle CRM-Daten (Kontakte, Firmen, Mails, Dateien, Kalender, Tasks) "
"mit Hybrid-Suche (Volltext + semantisch). "
"Liefert kompakte Ergebnisse mit entity_type, title, snippet und score. "
"Die Suche respektiert die Berechtigungen des aufrufenden Benutzers."
)
TOOL_PARAMETERS = {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Suchanfrage, z.B. 'Max Mustermann' oder 'Angebot 2026'",
},
"entity_types": {
"type": "array",
"items": {"type": "string"},
"description": "Optional: Nur diese Entity-Typen durchsuchen (contact, company, mail, file, event, task, ...)",
},
"limit": {
"type": "integer",
"default": 10,
"minimum": 1,
"maximum": 50,
"description": "Maximale Anzahl Ergebnisse (Standard: 10)",
},
},
"required": ["query"],
}
async def unified_search_handler(arguments: dict[str, Any], context: dict[str, Any]) -> str:
"""Execute a unified search on behalf of the calling AI agent.
Uses the user context (tenant_id, user_id, is_system_admin) from the AI
session so that visibility filtering and RBAC are respected.
"""
query = (arguments.get("query") or "").strip()
if not query:
return json.dumps({"error": "query is required"})
entity_types = arguments.get("entity_types")
if isinstance(entity_types, str):
entity_types = [t.strip() for t in entity_types.split(",") if t.strip()]
limit = int(arguments.get("limit", 10) or 10)
limit = max(1, min(limit, 50))
tenant_id = context.get("tenant_id")
user_id = context.get("user_id")
is_system_admin = bool(context.get("is_system_admin", False))
if not tenant_id:
return json.dumps({"error": "missing tenant context"})
try:
tenant_uuid = uuid.UUID(str(tenant_id))
user_uuid = uuid.UUID(str(user_id)) if user_id else None
except (ValueError, TypeError):
return json.dumps({"error": "invalid tenant/user context"})
# Build a DB session from the session factory (same pattern as other tools)
from app.core.db import get_session_factory
factory = get_session_factory()
async with factory() as db:
query_analysis = await llm_analyze_query(query, db=db, tenant_id=tenant_uuid)
results = await hybrid_search(
db=db,
query_analysis=query_analysis,
tenant_id=tenant_uuid,
entity_types=entity_types,
limit=limit,
user_id=user_uuid,
is_system_admin=is_system_admin,
)
# Compact AI-friendly output
compact = [
{
"entity_type": r.get("entity_type", ""),
"entity_id": r.get("entity_id", ""),
"title": r.get("title", ""),
"snippet": (r.get("snippet", "") or "")[:200],
"score": round(float(r.get("score", 0.0)), 4),
}
for r in results
]
return json.dumps({"count": len(compact), "results": compact}, ensure_ascii=False)
# Expose the tool definition object for direct import in verification
class _UnifiedSearchTool:
"""Lightweight tool descriptor matching the verification contract."""
name = TOOL_NAME
description = TOOL_DESCRIPTION
parameters = TOOL_PARAMETERS
handler = unified_search_handler
plugin_name = "unified_search"
required_permission = "search:read"
category = "search"
def to_openai_schema(self) -> dict[str, Any]:
return {
"type": "function",
"function": {
"name": self.name,
"description": self.description,
"parameters": self.parameters,
},
}
unified_search_tool = _UnifiedSearchTool()
def register_unified_search_tool(registry) -> None:
"""Register the unified_search tool in the AI tool registry."""
registry.register(
name=TOOL_NAME,
description=TOOL_DESCRIPTION,
parameters=TOOL_PARAMETERS,
handler=unified_search_handler,
plugin_name="unified_search",
required_permission="search:read",
category="search",
)
logger.info("Unified Search AI tool registered")