Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
214 lines (181 loc) · 6.88 KB
/
Copy pathcli.py
File metadata and controls
214 lines (181 loc) · 6.88 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
"""DiffVector CLI — CI-friendly embedding migration auditor."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Optional
import numpy as np
import typer
from dotenv import load_dotenv
from core.analytics import compute_retrieval_overlap, reduce_to_2d
from core.connectors import EmptyCollectionError, get_connector
from core.embeddings import get_embedding_provider, list_target_models
load_dotenv()
app = typer.Typer(
name="diffvector",
help="DiffVector — detect semantic drift before embedding model upgrades.",
add_completion=False,
)
def _resolve_api_key(explicit: str | None, env_var: str) -> str | None:
import os
return explicit or os.getenv(env_var)
@app.command("audit")
def audit(
source: str = typer.Option("chroma", help="Vector DB: chroma, qdrant, pinecone"),
path: Optional[str] = typer.Option(None, help="Chroma persist path"),
collection: str = typer.Option("demo", help="Collection / index name"),
url: Optional[str] = typer.Option(None, help="Qdrant URL"),
api_key: Optional[str] = typer.Option(None, help="API key (Qdrant/Pinecone/OpenAI)"),
namespace: str = typer.Option("", help="Pinecone namespace"),
target_model: str = typer.Option(
"sentence-transformers/all-MiniLM-L6-v2",
help="Target embedding model for simulation",
),
n: int = typer.Option(300, help="Sample size (50–2000)"),
topk: int = typer.Option(5, help="Top-K for overlap metric"),
min_overlap: float = typer.Option(0.6, help="Minimum mean overlap to pass CI gate"),
json_output: bool = typer.Option(False, "--json", help="Emit JSON report"),
queries_file: Optional[Path] = typer.Option(
None, "--queries", help="File with canary queries (one per line)"
),
source_model: Optional[str] = typer.Option(
None, help="Source model for canary query embedding (required with --queries)"
),
) -> None:
"""Run a read-only embedding migration audit against a vector database slice."""
try:
connector_kwargs: dict = {"collection": collection}
if source.lower() == "chroma":
connector_kwargs["path"] = path or "./chroma_db"
elif source.lower() == "qdrant":
connector_kwargs["url"] = url
connector_kwargs["api_key"] = _resolve_api_key(api_key, "QDRANT_API_KEY")
elif source.lower() == "pinecone":
connector_kwargs["index"] = collection
connector_kwargs["api_key"] = _resolve_api_key(api_key, "PINECONE_API_KEY")
connector_kwargs["namespace"] = namespace
connector = get_connector(source, **connector_kwargs)
connector.connect()
total = connector.count()
if total == 0:
typer.echo(
json.dumps({"error": "empty_collection", "count": 0})
if json_output
else "Error: collection is empty.",
err=True,
)
raise typer.Exit(code=1)
slice_ = connector.fetch_slice(n)
target_provider = get_embedding_provider(
target_model,
api_key=_resolve_api_key(api_key, "OPENAI_API_KEY"),
)
new_vectors = target_provider.embed(slice_.texts)
if queries_file and source_model:
from core.analytics import compute_canary_overlap
queries = [
line.strip()
for line in queries_file.read_text().splitlines()
if line.strip()
]
source_provider = get_embedding_provider(
source_model,
api_key=_resolve_api_key(api_key, "OPENAI_API_KEY"),
)
q_old = source_provider.embed(queries)
q_new = target_provider.embed(queries)
result = compute_canary_overlap(
slice_.ids,
slice_.vectors,
new_vectors,
q_old,
q_new,
queries,
topk=topk,
)
else:
result = compute_retrieval_overlap(
slice_.ids,
slice_.vectors,
new_vectors,
topk=topk,
)
old_2d = reduce_to_2d(slice_.vectors)
new_2d = reduce_to_2d(new_vectors)
report = {
"source": source,
"collection": collection,
"sample_size": len(slice_.ids),
"total_in_db": total,
"old_dimension": slice_.dimension,
"new_dimension": int(new_vectors.shape[1]),
"target_model": target_model,
"topk": topk,
"mean_overlap": round(result.mean_overlap, 4),
"drift_score": round(result.drift_score, 4),
"high_risk_count": result.high_risk_count,
"high_risk_pct": round(result.high_risk_pct, 2),
"passed": result.mean_overlap >= min_overlap,
"min_overlap_threshold": min_overlap,
"reduction_old_shape": list(old_2d.shape),
"reduction_new_shape": list(new_2d.shape),
}
if json_output:
typer.echo(json.dumps(report, indent=2))
else:
typer.echo("DiffVector Audit Report")
typer.echo("=" * 40)
for key, value in report.items():
typer.echo(f" {key}: {value}")
typer.echo("=" * 40)
status = "PASS" if report["passed"] else "FAIL"
typer.echo(f" Status: {status}")
if not report["passed"]:
raise typer.Exit(code=1)
except EmptyCollectionError as exc:
typer.echo(str(exc), err=True)
raise typer.Exit(code=1) from exc
except Exception as exc:
typer.echo(f"Error: {exc}", err=True)
raise typer.Exit(code=1) from exc
@app.command("models")
def models() -> None:
"""List supported target embedding models."""
for model in list_target_models():
typer.echo(model)
def _app_module_path() -> Path:
import app as app_module
path = Path(app_module.__file__).resolve()
if not path.is_file():
raise FileNotFoundError(f"DiffVector GUI module not found at {path}")
return path
@app.command("gui")
def gui(
port: int = typer.Option(8501, help="Port for the Streamlit server"),
host: str = typer.Option(
"localhost",
help="Bind address (use 0.0.0.0 inside Docker)",
),
) -> None:
"""Launch the DiffVector Streamlit GUI."""
import subprocess
import sys
app_path = _app_module_path()
cmd = [
sys.executable,
"-m",
"streamlit",
"run",
str(app_path),
"--server.port",
str(port),
"--server.address",
host,
"--browser.gatherUsageStats",
"false",
]
typer.echo(f"Starting DiffVector GUI at http://{host}:{port}")
raise typer.Exit(code=subprocess.call(cmd))
def main() -> None:
app()
if __name__ == "__main__":
main()