Spaces:
Running
Running
Download core/tools/search.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 5.57 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/tools/search.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/tools/search.py
-
curl -L -o search.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/tools/search.py
5.57 kB
| """Hybrid tool search over an indexed registry (Postgres full-text + pgvector). | |
| Accuracy drops once more than ~30-50 tool definitions are loaded at once, so agents get a | |
| small always-loaded set and discover the rest here. Global (pack) tools have | |
| ``tenant_id IS NULL``; tenant-registered tools are scoped by RLS. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import itertools | |
| import math | |
| import re | |
| import uuid | |
| from typing import Protocol | |
| from pgvector.sqlalchemy import Vector | |
| from sqlalchemy import Integer, String, Text, delete, func, literal_column, select | |
| from sqlalchemy.dialects.postgresql import JSONB, TSVECTOR, UUID | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy.orm import Mapped, mapped_column | |
| from core.db.base import Base, TimestampMixin, new_id | |
| from core.tools.preview import canonical_json, sha256_hex | |
| from core.tools.spec import ToolSpec | |
| EMBED_DIM = 256 | |
| class Embedder(Protocol): | |
| dim: int | |
| def embed(self, text: str) -> list[float]: ... | |
| class HashingEmbedder: | |
| """Deterministic feature-hashing embedder: no network, no API key. | |
| Good enough for tool names/descriptions; swap for a real embedding model in production. | |
| """ | |
| dim = EMBED_DIM | |
| def embed(self, text: str) -> list[float]: | |
| vec = [0.0] * self.dim | |
| tokens = re.findall(r"[a-z0-9]+", text.lower()) | |
| grams = tokens + [f"{a}_{b}" for a, b in itertools.pairwise(tokens)] | |
| for g in grams: | |
| h = int.from_bytes(hashlib.blake2b(g.encode(), digest_size=8).digest(), "big") | |
| vec[h % self.dim] += 1.0 if (h >> 63) == 0 else -1.0 | |
| norm = math.sqrt(sum(v * v for v in vec)) or 1.0 | |
| return [v / norm for v in vec] | |
| class ToolIndexEntry(TimestampMixin, Base): | |
| __tablename__ = "tool_index" | |
| __rls__ = True # custom policy: global rows visible to all, writes need owner role | |
| id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=new_id) | |
| tenant_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True) | |
| name: Mapped[str] = mapped_column(String(200), nullable=False) | |
| description: Mapped[str] = mapped_column(Text, nullable=False) | |
| risk_tier: Mapped[int] = mapped_column(Integer, nullable=False) | |
| source: Mapped[str] = mapped_column(String(20), nullable=False, default="pack") | |
| spec: Mapped[dict] = mapped_column(JSONB, nullable=False) | |
| definition_hash: Mapped[str] = mapped_column(String(64), nullable=False) | |
| search_doc: Mapped[str] = mapped_column(TSVECTOR, nullable=False) | |
| embedding: Mapped[list[float]] = mapped_column(Vector(EMBED_DIM), nullable=False) | |
| def spec_document(spec: ToolSpec) -> dict: | |
| return { | |
| "name": spec.name, | |
| "description": spec.description, | |
| "risk_tier": int(spec.risk_tier), | |
| "input_schema": spec.json_schema(), | |
| "sensitive_args": list(spec.sensitive_args), | |
| "tags": list(spec.tags), | |
| } | |
| def definition_hash(spec: ToolSpec) -> str: | |
| """Pinned per tool; a changed definition is detectable (MCP rug-pull defense).""" | |
| return sha256_hex(canonical_json(spec_document(spec))) | |
| def _search_text(spec: ToolSpec) -> str: | |
| return " ".join([spec.name.replace(".", " ").replace("_", " "), spec.description, *spec.tags]) | |
| class ToolSearch: | |
| def __init__(self, embedder: Embedder | None = None) -> None: | |
| self.embedder = embedder or HashingEmbedder() | |
| async def sync_global(self, session: AsyncSession, specs: list[ToolSpec]) -> int: | |
| """Replace the global (tenant_id IS NULL) index. Must run as the owner role.""" | |
| await session.execute(delete(ToolIndexEntry).where(ToolIndexEntry.tenant_id.is_(None))) | |
| for spec in specs: | |
| await self._insert(session, spec, tenant_id=None, source="pack") | |
| return len(specs) | |
| async def index_tenant_tool( | |
| self, session: AsyncSession, spec: ToolSpec, tenant_id: uuid.UUID, source: str | |
| ) -> None: | |
| await self._insert(session, spec, tenant_id=tenant_id, source=source) | |
| async def _insert( | |
| self, session: AsyncSession, spec: ToolSpec, tenant_id: uuid.UUID | None, source: str | |
| ) -> None: | |
| text = _search_text(spec) | |
| session.add( | |
| ToolIndexEntry( | |
| tenant_id=tenant_id, | |
| name=spec.name, | |
| description=spec.description, | |
| risk_tier=int(spec.risk_tier), | |
| source=source, | |
| spec=spec_document(spec), | |
| definition_hash=definition_hash(spec), | |
| search_doc=func.to_tsvector("simple", text), | |
| embedding=self.embedder.embed(text), | |
| ) | |
| ) | |
| await session.flush() | |
| async def search(self, session: AsyncSession, query: str, k: int = 5) -> list[str]: | |
| """Top-k tool names by 0.5 * normalized text rank + 0.5 * cosine similarity.""" | |
| qvec = self.embedder.embed(query) | |
| terms = " | ".join(re.findall(r"[a-z0-9]+", query.lower())) or "''" | |
| tsq = func.to_tsquery("simple", terms) | |
| text_rank = func.ts_rank_cd(ToolIndexEntry.search_doc, tsq, 32) | |
| cosine = literal_column("1") - ToolIndexEntry.embedding.cosine_distance(qvec) | |
| score = (0.5 * text_rank + 0.5 * cosine).label("score") | |
| rows = await session.execute( | |
| select(ToolIndexEntry.name, score).order_by(score.desc()).limit(k) | |
| ) | |
| return [r.name for r in rows] | |