-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstructured_metadata_retrieval.py
More file actions
76 lines (63 loc) · 2.21 KB
/
Copy pathstructured_metadata_retrieval.py
File metadata and controls
76 lines (63 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""Translate an application-owned structured query plan to typed MongoDB filters."""
from __future__ import annotations
import asyncio
import os
from dataclasses import dataclass
from typing import Literal
from agent_framework_mongodb import (
AndFilter,
EqualFilter,
InFilter,
MongoDBFilter,
MongoDBRAGProvider,
MongoDBRAGProviderOptions,
MongoDBRAGSearchOptions,
MongoDBSearchMode,
)
Visibility = Literal["public", "internal"]
@dataclass(frozen=True)
class RetrievalPlan:
query: str
category: str
visibility: tuple[Visibility, ...]
def to_filter(self) -> MongoDBFilter:
if not self.category.strip():
raise ValueError("category must be non-empty")
if not self.visibility:
raise ValueError("visibility must contain at least one approved value")
return AndFilter(
EqualFilter("metadata.category", self.category),
InFilter("visibility", self.visibility),
)
def required(name: str) -> str:
value = os.getenv(name, "").strip()
if not value:
raise RuntimeError(f"Set {name} before running structured metadata retrieval.")
return value
async def main() -> None:
provider = MongoDBRAGProvider(
MongoDBRAGProviderOptions(
mode=MongoDBSearchMode.FULL_TEXT,
search_index_name=required("MONGODB_RAG_SEARCH_INDEX"),
filter=EqualFilter("tenant_id", required("MONGODB_RAG_TENANT")),
metadata_fields=("metadata.category", "visibility"),
),
connection_string=required("MONGODB_URI"),
database_name=required("MONGODB_DATABASE"),
collection_name=required("MONGODB_RAG_COLLECTION"),
)
plan = RetrievalPlan(
query="How is tenant access enforced?",
category="security",
visibility=("public",),
)
async with provider:
await provider.validate_search_index()
results = await provider.search(
plan.query,
options=MongoDBRAGSearchOptions(filter=plan.to_filter(), top_k=3),
)
for result in results:
print(f"{result.score:.4f} {result.source_name or result.id}: {result.text}")
if __name__ == "__main__":
asyncio.run(main())