|
| 1 | +"""Atlas Vector Search helper for the Agency Swarm demo. |
| 2 | +
|
| 3 | +Loads the canonical 17-person team directory (`data/embeddings.json`, precomputed |
| 4 | +Voyage 3.5 vectors) into a collection, builds a prefilterable Atlas Vector Search index, |
| 5 | +and exposes `recall_semantic` for the agent's staffing tool. Query strings are embedded |
| 6 | +at runtime with Voyage 3.5 (`voyage-3.5`, 1024-dim) per the 100 Integs conventions. |
| 7 | +
|
| 8 | +Kept in the demo (not the core package) so the published `agency-swarm-mongodb` library |
| 9 | +stays a focused, dependency-light thread store. |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import json |
| 15 | +import time |
| 16 | +from pathlib import Path |
| 17 | +from typing import Any |
| 18 | + |
| 19 | +from pymongo import MongoClient |
| 20 | +from pymongo.driver_info import DriverInfo |
| 21 | +from pymongo.operations import SearchIndexModel |
| 22 | + |
| 23 | +from agency_swarm_mongodb import APP_NAME, DRIVER_NAME |
| 24 | + |
| 25 | +VOYAGE_MODEL = "voyage-3.5" |
| 26 | +VOYAGE_DIM = 1024 |
| 27 | +DIRECTORY_SCOPE = "corpus:team" |
| 28 | + |
| 29 | + |
| 30 | +def embed_text(text: str, *, input_type: str = "document") -> list[float]: |
| 31 | + """Embed a single string with Voyage AI 3.5 → 1024-dim vector.""" |
| 32 | + import voyageai |
| 33 | + |
| 34 | + client = voyageai.Client() # reads VOYAGE_API_KEY |
| 35 | + return client.embed([text], model=VOYAGE_MODEL, input_type=input_type).embeddings[0] |
| 36 | + |
| 37 | + |
| 38 | +class AtlasDirectory: |
| 39 | + """Employee directory backed by Atlas Vector Search (demo support, not core API).""" |
| 40 | + |
| 41 | + def __init__(self, uri: str, *, database_name: str, index_name: str = "idx_team_directory"): |
| 42 | + self.client = MongoClient( |
| 43 | + uri, |
| 44 | + appname=APP_NAME, |
| 45 | + driver=DriverInfo(name=DRIVER_NAME, version="0.1.0"), |
| 46 | + ) |
| 47 | + self.col = self.client[database_name]["team_directory"] |
| 48 | + self.index_name = index_name |
| 49 | + |
| 50 | + def seed(self, dataset: Path) -> None: |
| 51 | + docs = json.loads(dataset.read_text()) |
| 52 | + rows: list[dict[str, Any]] = [] |
| 53 | + for d in docs: |
| 54 | + skills = ", ".join( |
| 55 | + s["name"] if isinstance(s, dict) else str(s) for s in d.get("skills", []) |
| 56 | + ) |
| 57 | + rows.append( |
| 58 | + { |
| 59 | + "scope": DIRECTORY_SCOPE, |
| 60 | + "content": f"{d['name']} — {d['title']} ({d['department']}). Skills: {skills}.", |
| 61 | + "embedding": d["embedding"], # Voyage 3.5, precomputed |
| 62 | + "meta": { |
| 63 | + "name": d["name"], |
| 64 | + "title": d["title"], |
| 65 | + "department": d["department"], |
| 66 | + "availability": d.get("availability"), |
| 67 | + }, |
| 68 | + } |
| 69 | + ) |
| 70 | + self.col.delete_many({"scope": DIRECTORY_SCOPE}) |
| 71 | + self.col.insert_many(rows) |
| 72 | + |
| 73 | + def ensure_index(self, *, timeout: int = 180) -> bool: |
| 74 | + existing = {idx["name"] for idx in self.col.list_search_indexes()} |
| 75 | + if self.index_name not in existing: |
| 76 | + model = SearchIndexModel( |
| 77 | + definition={ |
| 78 | + "fields": [ |
| 79 | + {"type": "vector", "path": "embedding", |
| 80 | + "numDimensions": VOYAGE_DIM, "similarity": "cosine"}, |
| 81 | + {"type": "filter", "path": "scope"}, |
| 82 | + {"type": "filter", "path": "meta.department"}, |
| 83 | + {"type": "filter", "path": "meta.availability"}, |
| 84 | + ] |
| 85 | + }, |
| 86 | + name=self.index_name, |
| 87 | + type="vectorSearch", |
| 88 | + ) |
| 89 | + self.col.create_search_index(model) |
| 90 | + |
| 91 | + deadline = time.time() + timeout |
| 92 | + while time.time() < deadline: |
| 93 | + for idx in self.col.list_search_indexes(): |
| 94 | + if idx["name"] == self.index_name and idx.get("queryable"): |
| 95 | + return True |
| 96 | + time.sleep(3) |
| 97 | + return False |
| 98 | + |
| 99 | + def recall_semantic( |
| 100 | + self, query: str, k: int = 4, *, department: str | None = None |
| 101 | + ) -> list[dict[str, Any]]: |
| 102 | + vs_filter: dict[str, Any] = {"scope": DIRECTORY_SCOPE} |
| 103 | + if department: |
| 104 | + vs_filter["meta.department"] = department |
| 105 | + pipeline = [ |
| 106 | + { |
| 107 | + "$vectorSearch": { |
| 108 | + "index": self.index_name, |
| 109 | + "path": "embedding", |
| 110 | + "queryVector": embed_text(query, input_type="query"), |
| 111 | + "numCandidates": max(k * 20, 100), |
| 112 | + "limit": k, |
| 113 | + "filter": vs_filter, |
| 114 | + } |
| 115 | + }, |
| 116 | + {"$project": {"embedding": 0, "score": {"$meta": "vectorSearchScore"}}}, |
| 117 | + ] |
| 118 | + return list(self.col.aggregate(pipeline)) |
| 119 | + |
| 120 | + def close(self) -> None: |
| 121 | + self.client.close() |
0 commit comments