vectoryai 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- components/__init__.py +11 -0
- components/document_loader.py +350 -0
- components/error_discovery.py +171 -0
- components/evaluators/__init__.py +0 -0
- components/evaluators/base.py +67 -0
- components/evaluators/llm_judge.py +237 -0
- components/evaluators/metrics.py +260 -0
- components/evaluators/rag_metrics.py +418 -0
- components/model_catalog.py +124 -0
- components/models.py +214 -0
- components/mteb_evaluator.py +296 -0
- components/mteb_leaderboard.py +461 -0
- components/themes.py +1305 -0
- components/ui.py +506 -0
- components/vectory_benchmark/__init__.py +14 -0
- components/vectory_benchmark/leaderboard.py +78 -0
- components/vectory_benchmark/pathology.py +465 -0
- components/vectory_benchmark/schemas.py +268 -0
- components/vectory_benchmark/scoring.py +345 -0
- components/vectory_benchmark/suite.py +27 -0
- components/vectory_benchmark/trace_parser.py +128 -0
- components/visualization.py +170 -0
- vectory_cli/__init__.py +5 -0
- vectory_cli/cli.py +151 -0
- vectory_cli/streamlit_app/.streamlit/config.toml +22 -0
- vectory_cli/streamlit_app/app.py +225 -0
- vectory_cli/streamlit_app/components/__init__.py +11 -0
- vectory_cli/streamlit_app/components/document_loader.py +350 -0
- vectory_cli/streamlit_app/components/error_discovery.py +171 -0
- vectory_cli/streamlit_app/components/evaluators/__init__.py +0 -0
- vectory_cli/streamlit_app/components/evaluators/base.py +67 -0
- vectory_cli/streamlit_app/components/evaluators/llm_judge.py +237 -0
- vectory_cli/streamlit_app/components/evaluators/metrics.py +260 -0
- vectory_cli/streamlit_app/components/evaluators/rag_metrics.py +418 -0
- vectory_cli/streamlit_app/components/model_catalog.py +124 -0
- vectory_cli/streamlit_app/components/models.py +214 -0
- vectory_cli/streamlit_app/components/mteb_evaluator.py +296 -0
- vectory_cli/streamlit_app/components/mteb_leaderboard.py +461 -0
- vectory_cli/streamlit_app/components/themes.py +1305 -0
- vectory_cli/streamlit_app/components/ui.py +506 -0
- vectory_cli/streamlit_app/components/vectory_benchmark/__init__.py +14 -0
- vectory_cli/streamlit_app/components/vectory_benchmark/leaderboard.py +78 -0
- vectory_cli/streamlit_app/components/vectory_benchmark/pathology.py +465 -0
- vectory_cli/streamlit_app/components/vectory_benchmark/schemas.py +268 -0
- vectory_cli/streamlit_app/components/vectory_benchmark/scoring.py +345 -0
- vectory_cli/streamlit_app/components/vectory_benchmark/suite.py +27 -0
- vectory_cli/streamlit_app/components/vectory_benchmark/trace_parser.py +128 -0
- vectory_cli/streamlit_app/components/visualization.py +170 -0
- vectory_cli/streamlit_app/data/sample_dataset.json +52 -0
- vectory_cli/streamlit_app/data/vectory_benchmark/example_submission.json +140 -0
- vectory_cli/streamlit_app/data/vectory_benchmark/manifest.json +283 -0
- vectory_cli/streamlit_app/docs/vectory_benchmark.md +250 -0
- vectory_cli/streamlit_app/pages/1_/360/237/223/212_Dataset.py +262 -0
- vectory_cli/streamlit_app/pages/2_/360/237/244/226_LLM_Judge.py +487 -0
- vectory_cli/streamlit_app/pages/3_/360/237/223/217_Metrics.py +366 -0
- vectory_cli/streamlit_app/pages/4_/360/237/221/244_Human_Eval.py +377 -0
- vectory_cli/streamlit_app/pages/5_/360/237/217/206_Leaderboard.py +329 -0
- vectory_cli/streamlit_app/pages/6_/360/237/247/252_Custom_Benchmark.py +764 -0
- vectory_cli/streamlit_app/pages/7_/342/232/231/357/270/217_Settings.py +352 -0
- vectory_cli/streamlit_app/pages/8_/360/237/224/215_Error_Analysis.py +705 -0
- vectory_cli/streamlit_app/pages/9_/360/237/247/255_VectoryBenchmark.py +602 -0
- vectory_cli/streamlit_app/scripts/run_vectory_benchmark.py +144 -0
- vectoryai-1.0.0.dist-info/METADATA +409 -0
- vectoryai-1.0.0.dist-info/RECORD +68 -0
- vectoryai-1.0.0.dist-info/WHEEL +5 -0
- vectoryai-1.0.0.dist-info/entry_points.txt +2 -0
- vectoryai-1.0.0.dist-info/licenses/LICENSE +21 -0
- vectoryai-1.0.0.dist-info/top_level.txt +2 -0
components/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Vectory - LLM Evaluation Platform
|
|
3
|
+
|
|
4
|
+
A powerful, professional-grade toolkit for evaluating Large Language Model outputs.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__version__ = "1.0.0"
|
|
8
|
+
__product_name__ = "Vectory"
|
|
9
|
+
__tagline__ = "Precision LLM Evaluation"
|
|
10
|
+
__author__ = "Tactical Edge"
|
|
11
|
+
__website__ = "https://vectoryai.com"
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Document loader using industry-standard libraries.
|
|
3
|
+
Replaces ad-hoc multimodal_loader.py with proper tools.
|
|
4
|
+
|
|
5
|
+
Uses:
|
|
6
|
+
- pymupdf4llm: For PDF to Markdown conversion (optimized for LLM workflows)
|
|
7
|
+
- pandas: For CSV/JSON loading
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import pandas as pd
|
|
11
|
+
import json
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Optional, List, Union
|
|
14
|
+
from io import BytesIO, StringIO
|
|
15
|
+
|
|
16
|
+
from .models import (
|
|
17
|
+
ExtractionMode,
|
|
18
|
+
ContentType,
|
|
19
|
+
ExtractedContent,
|
|
20
|
+
DocumentResult,
|
|
21
|
+
ColumnMapping,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
# Lazy imports for optional dependencies
|
|
25
|
+
_pymupdf4llm = None
|
|
26
|
+
_PIL = None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _get_pymupdf4llm():
|
|
30
|
+
global _pymupdf4llm
|
|
31
|
+
if _pymupdf4llm is None:
|
|
32
|
+
try:
|
|
33
|
+
import pymupdf4llm
|
|
34
|
+
_pymupdf4llm = pymupdf4llm
|
|
35
|
+
except ImportError:
|
|
36
|
+
raise ImportError(
|
|
37
|
+
"pymupdf4llm not installed. Run: pip install pymupdf4llm"
|
|
38
|
+
)
|
|
39
|
+
return _pymupdf4llm
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _get_pil():
|
|
43
|
+
global _PIL
|
|
44
|
+
if _PIL is None:
|
|
45
|
+
try:
|
|
46
|
+
from PIL import Image
|
|
47
|
+
_PIL = Image
|
|
48
|
+
except ImportError:
|
|
49
|
+
raise ImportError("Pillow not installed. Run: pip install Pillow")
|
|
50
|
+
return _PIL
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# ============================================================================
|
|
54
|
+
# JSON/CSV Loading (Simple, no reinvention needed)
|
|
55
|
+
# ============================================================================
|
|
56
|
+
|
|
57
|
+
def load_json(content: bytes) -> pd.DataFrame:
|
|
58
|
+
"""Load JSON or JSONL into DataFrame."""
|
|
59
|
+
text = content.decode("utf-8")
|
|
60
|
+
|
|
61
|
+
# Try JSONL first (one object per line)
|
|
62
|
+
lines = text.strip().split("\n")
|
|
63
|
+
if len(lines) > 1:
|
|
64
|
+
try:
|
|
65
|
+
records = [json.loads(line) for line in lines if line.strip()]
|
|
66
|
+
return pd.DataFrame(records)
|
|
67
|
+
except json.JSONDecodeError:
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
# Regular JSON
|
|
71
|
+
data = json.loads(text)
|
|
72
|
+
if isinstance(data, list):
|
|
73
|
+
return pd.DataFrame(data)
|
|
74
|
+
elif isinstance(data, dict):
|
|
75
|
+
# Check for common wrapper keys
|
|
76
|
+
for key in ("data", "records", "samples", "items", "examples"):
|
|
77
|
+
if key in data and isinstance(data[key], list):
|
|
78
|
+
return pd.DataFrame(data[key])
|
|
79
|
+
return pd.DataFrame([data])
|
|
80
|
+
|
|
81
|
+
raise ValueError("Unsupported JSON structure")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def load_csv(content: bytes) -> pd.DataFrame:
|
|
85
|
+
"""Load CSV with encoding detection."""
|
|
86
|
+
for encoding in ("utf-8", "utf-8-sig", "latin-1", "cp1252"):
|
|
87
|
+
try:
|
|
88
|
+
return pd.read_csv(BytesIO(content), encoding=encoding)
|
|
89
|
+
except (UnicodeDecodeError, pd.errors.ParserError):
|
|
90
|
+
continue
|
|
91
|
+
raise ValueError("Could not parse CSV with any common encoding")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ============================================================================
|
|
95
|
+
# PDF Loading using pymupdf4llm
|
|
96
|
+
# ============================================================================
|
|
97
|
+
|
|
98
|
+
def load_pdf(
|
|
99
|
+
content: bytes,
|
|
100
|
+
filename: str = "",
|
|
101
|
+
mode: ExtractionMode = ExtractionMode.MARKDOWN,
|
|
102
|
+
) -> DocumentResult:
|
|
103
|
+
"""
|
|
104
|
+
Load PDF using pymupdf4llm.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
content: PDF file bytes
|
|
108
|
+
filename: Original filename
|
|
109
|
+
mode: Extraction mode (markdown, text, or chunks)
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
DocumentResult with extracted content
|
|
113
|
+
"""
|
|
114
|
+
pymupdf4llm = _get_pymupdf4llm()
|
|
115
|
+
import fitz # PyMuPDF, installed with pymupdf4llm
|
|
116
|
+
|
|
117
|
+
try:
|
|
118
|
+
doc = fitz.open(stream=content, filetype="pdf")
|
|
119
|
+
page_count = len(doc)
|
|
120
|
+
|
|
121
|
+
if mode == ExtractionMode.MARKDOWN:
|
|
122
|
+
# Get markdown output (best for LLM consumption)
|
|
123
|
+
md_text = pymupdf4llm.to_markdown(doc)
|
|
124
|
+
extracted = [
|
|
125
|
+
ExtractedContent(
|
|
126
|
+
content_type=ContentType.TEXT,
|
|
127
|
+
text=md_text,
|
|
128
|
+
source_file=filename,
|
|
129
|
+
metadata={"format": "markdown", "page_count": page_count},
|
|
130
|
+
)
|
|
131
|
+
]
|
|
132
|
+
|
|
133
|
+
elif mode == ExtractionMode.CHUNKS:
|
|
134
|
+
# Get chunked output (good for RAG)
|
|
135
|
+
chunks = pymupdf4llm.to_markdown(doc, page_chunks=True)
|
|
136
|
+
extracted = [
|
|
137
|
+
ExtractedContent(
|
|
138
|
+
content_type=ContentType.PAGE,
|
|
139
|
+
text=chunk["text"] if isinstance(chunk, dict) else str(chunk),
|
|
140
|
+
source_file=filename,
|
|
141
|
+
page=i + 1,
|
|
142
|
+
metadata=chunk.get("metadata", {}) if isinstance(chunk, dict) else {},
|
|
143
|
+
)
|
|
144
|
+
for i, chunk in enumerate(chunks)
|
|
145
|
+
]
|
|
146
|
+
|
|
147
|
+
else: # TEXT mode
|
|
148
|
+
# Plain text extraction
|
|
149
|
+
text_parts = []
|
|
150
|
+
for page in doc:
|
|
151
|
+
text_parts.append(page.get_text())
|
|
152
|
+
extracted = [
|
|
153
|
+
ExtractedContent(
|
|
154
|
+
content_type=ContentType.TEXT,
|
|
155
|
+
text="\n\n".join(text_parts),
|
|
156
|
+
source_file=filename,
|
|
157
|
+
metadata={"format": "plain_text", "page_count": page_count},
|
|
158
|
+
)
|
|
159
|
+
]
|
|
160
|
+
|
|
161
|
+
doc.close()
|
|
162
|
+
return DocumentResult(
|
|
163
|
+
filename=filename,
|
|
164
|
+
content=extracted,
|
|
165
|
+
page_count=page_count,
|
|
166
|
+
extraction_mode=mode,
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
except Exception as e:
|
|
170
|
+
return DocumentResult(
|
|
171
|
+
filename=filename,
|
|
172
|
+
content=[],
|
|
173
|
+
page_count=0,
|
|
174
|
+
extraction_mode=mode,
|
|
175
|
+
error=str(e),
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
# ============================================================================
|
|
180
|
+
# Image Loading
|
|
181
|
+
# ============================================================================
|
|
182
|
+
|
|
183
|
+
def load_image(content: bytes, filename: str = "") -> DocumentResult:
|
|
184
|
+
"""Load image and extract basic metadata."""
|
|
185
|
+
Image = _get_pil()
|
|
186
|
+
|
|
187
|
+
try:
|
|
188
|
+
img = Image.open(BytesIO(content))
|
|
189
|
+
metadata = {
|
|
190
|
+
"format": img.format,
|
|
191
|
+
"mode": img.mode,
|
|
192
|
+
"width": img.width,
|
|
193
|
+
"height": img.height,
|
|
194
|
+
"size_bytes": len(content),
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
# Note: OCR would require pytesseract, keeping it simple
|
|
198
|
+
extracted = [
|
|
199
|
+
ExtractedContent(
|
|
200
|
+
content_type=ContentType.IMAGE,
|
|
201
|
+
text=f"[Image: {img.width}x{img.height} {img.format}]",
|
|
202
|
+
source_file=filename,
|
|
203
|
+
metadata=metadata,
|
|
204
|
+
)
|
|
205
|
+
]
|
|
206
|
+
|
|
207
|
+
return DocumentResult(
|
|
208
|
+
filename=filename,
|
|
209
|
+
content=extracted,
|
|
210
|
+
page_count=1,
|
|
211
|
+
extraction_mode=ExtractionMode.TEXT,
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
except Exception as e:
|
|
215
|
+
return DocumentResult(
|
|
216
|
+
filename=filename,
|
|
217
|
+
content=[],
|
|
218
|
+
page_count=0,
|
|
219
|
+
extraction_mode=ExtractionMode.TEXT,
|
|
220
|
+
error=str(e),
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
# ============================================================================
|
|
225
|
+
# Unified Loader
|
|
226
|
+
# ============================================================================
|
|
227
|
+
|
|
228
|
+
SUPPORTED_EXTENSIONS = {
|
|
229
|
+
".json": "json",
|
|
230
|
+
".jsonl": "json",
|
|
231
|
+
".csv": "csv",
|
|
232
|
+
".pdf": "pdf",
|
|
233
|
+
".png": "image",
|
|
234
|
+
".jpg": "image",
|
|
235
|
+
".jpeg": "image",
|
|
236
|
+
".gif": "image",
|
|
237
|
+
".bmp": "image",
|
|
238
|
+
".webp": "image",
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def load_file(
|
|
243
|
+
uploaded_file,
|
|
244
|
+
mode: ExtractionMode = ExtractionMode.MARKDOWN,
|
|
245
|
+
) -> pd.DataFrame:
|
|
246
|
+
"""
|
|
247
|
+
Load any supported file type into a DataFrame.
|
|
248
|
+
|
|
249
|
+
Args:
|
|
250
|
+
uploaded_file: Streamlit UploadedFile object
|
|
251
|
+
mode: Extraction mode for PDFs
|
|
252
|
+
|
|
253
|
+
Returns:
|
|
254
|
+
DataFrame with loaded content
|
|
255
|
+
"""
|
|
256
|
+
if uploaded_file is None:
|
|
257
|
+
raise ValueError("No file provided")
|
|
258
|
+
|
|
259
|
+
content = uploaded_file.getvalue()
|
|
260
|
+
filename = uploaded_file.name
|
|
261
|
+
ext = Path(filename).suffix.lower()
|
|
262
|
+
|
|
263
|
+
file_type = SUPPORTED_EXTENSIONS.get(ext)
|
|
264
|
+
if not file_type:
|
|
265
|
+
raise ValueError(f"Unsupported file type: {ext}")
|
|
266
|
+
|
|
267
|
+
if file_type == "json":
|
|
268
|
+
return load_json(content)
|
|
269
|
+
elif file_type == "csv":
|
|
270
|
+
return load_csv(content)
|
|
271
|
+
elif file_type == "pdf":
|
|
272
|
+
result = load_pdf(content, filename, mode)
|
|
273
|
+
if result.error:
|
|
274
|
+
raise ValueError(result.error)
|
|
275
|
+
# Convert to DataFrame for consistency
|
|
276
|
+
return pd.DataFrame([
|
|
277
|
+
{
|
|
278
|
+
"text": c.text,
|
|
279
|
+
"type": c.content_type.value,
|
|
280
|
+
"page": c.page,
|
|
281
|
+
"source_file": c.source_file,
|
|
282
|
+
**c.metadata,
|
|
283
|
+
}
|
|
284
|
+
for c in result.content
|
|
285
|
+
])
|
|
286
|
+
elif file_type == "image":
|
|
287
|
+
result = load_image(content, filename)
|
|
288
|
+
if result.error:
|
|
289
|
+
raise ValueError(result.error)
|
|
290
|
+
return pd.DataFrame([
|
|
291
|
+
{
|
|
292
|
+
"text": c.text,
|
|
293
|
+
"type": c.content_type.value,
|
|
294
|
+
"source_file": c.source_file,
|
|
295
|
+
**c.metadata,
|
|
296
|
+
}
|
|
297
|
+
for c in result.content
|
|
298
|
+
])
|
|
299
|
+
|
|
300
|
+
raise ValueError(f"Unknown file type: {file_type}")
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def load_files(
|
|
304
|
+
uploaded_files: List,
|
|
305
|
+
mode: ExtractionMode = ExtractionMode.MARKDOWN,
|
|
306
|
+
progress_callback=None,
|
|
307
|
+
) -> pd.DataFrame:
|
|
308
|
+
"""Load multiple files and combine into a single DataFrame."""
|
|
309
|
+
dfs = []
|
|
310
|
+
total = len(uploaded_files)
|
|
311
|
+
|
|
312
|
+
for i, f in enumerate(uploaded_files):
|
|
313
|
+
if progress_callback:
|
|
314
|
+
progress_callback((i + 1) / total, f"Loading {f.name}")
|
|
315
|
+
try:
|
|
316
|
+
df = load_file(f, mode)
|
|
317
|
+
dfs.append(df)
|
|
318
|
+
except Exception as e:
|
|
319
|
+
# Add error row instead of failing silently
|
|
320
|
+
dfs.append(pd.DataFrame([{
|
|
321
|
+
"source_file": f.name,
|
|
322
|
+
"error": str(e),
|
|
323
|
+
"text": "",
|
|
324
|
+
}]))
|
|
325
|
+
|
|
326
|
+
return pd.concat(dfs, ignore_index=True) if dfs else pd.DataFrame()
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
# ============================================================================
|
|
330
|
+
# Column Inference
|
|
331
|
+
# ============================================================================
|
|
332
|
+
|
|
333
|
+
def infer_columns(df: pd.DataFrame) -> ColumnMapping:
|
|
334
|
+
"""Infer semantic column roles from column names."""
|
|
335
|
+
mapping = ColumnMapping()
|
|
336
|
+
cols_lower = {c: c.lower() for c in df.columns}
|
|
337
|
+
|
|
338
|
+
patterns = {
|
|
339
|
+
"input_col": ["input", "prompt", "question", "query", "text", "source"],
|
|
340
|
+
"output_col": ["output", "response", "prediction", "generated", "completion"],
|
|
341
|
+
"expected_col": ["expected", "reference", "target", "answer", "gold", "label"],
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
for field, keywords in patterns.items():
|
|
345
|
+
for col, col_lower in cols_lower.items():
|
|
346
|
+
if any(kw in col_lower for kw in keywords):
|
|
347
|
+
setattr(mapping, field, col)
|
|
348
|
+
break
|
|
349
|
+
|
|
350
|
+
return mapping
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Helpers for AI-assisted error discovery workflows."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
import openai
|
|
8
|
+
except ImportError:
|
|
9
|
+
openai = None
|
|
10
|
+
|
|
11
|
+
try:
|
|
12
|
+
import anthropic
|
|
13
|
+
except ImportError:
|
|
14
|
+
anthropic = None
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
TAXONOMY_SYSTEM_PROMPT = """You help evaluation teams build failure-mode taxonomies from human review notes.
|
|
18
|
+
Use only the evidence in the notes. Prefer a small, coherent set of categories over many narrow labels."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build_taxonomy_prompt(
|
|
22
|
+
open_codes: list[str],
|
|
23
|
+
existing_failure_modes: dict[str, dict[str, Any]] | None = None,
|
|
24
|
+
max_codes: int = 40,
|
|
25
|
+
) -> str:
|
|
26
|
+
"""Build a prompt for clustering open-code notes into failure modes."""
|
|
27
|
+
trimmed_codes = [code.strip() for code in open_codes if code and code.strip()][:max_codes]
|
|
28
|
+
existing_failure_modes = existing_failure_modes or {}
|
|
29
|
+
|
|
30
|
+
existing_section = "None yet."
|
|
31
|
+
if existing_failure_modes:
|
|
32
|
+
existing_section = "\n".join(
|
|
33
|
+
f"- {name}: {details.get('description', '')}"
|
|
34
|
+
for name, details in existing_failure_modes.items()
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
notes_section = "\n".join(f"{i + 1}. {code}" for i, code in enumerate(trimmed_codes))
|
|
38
|
+
|
|
39
|
+
return f"""Cluster these human review notes into a concise failure-mode taxonomy.
|
|
40
|
+
|
|
41
|
+
Existing failure modes:
|
|
42
|
+
{existing_section}
|
|
43
|
+
|
|
44
|
+
Open-code notes:
|
|
45
|
+
{notes_section}
|
|
46
|
+
|
|
47
|
+
Return only valid JSON with this shape:
|
|
48
|
+
{{
|
|
49
|
+
"suggestions": [
|
|
50
|
+
{{
|
|
51
|
+
"name": "Short failure mode name",
|
|
52
|
+
"description": "One sentence definition of when this failure occurs.",
|
|
53
|
+
"examples": ["Exact or lightly shortened notes that support this mode"],
|
|
54
|
+
"rationale": "Why these notes belong together"
|
|
55
|
+
}}
|
|
56
|
+
]
|
|
57
|
+
}}
|
|
58
|
+
|
|
59
|
+
Rules:
|
|
60
|
+
- Suggest at most 8 failure modes.
|
|
61
|
+
- Do not duplicate existing failure modes; suggest refinements only when materially clearer.
|
|
62
|
+
- Use names that are specific enough for reviewers to apply consistently.
|
|
63
|
+
- Do not invent examples or failure modes not supported by the notes."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _extract_json_payload(text: str) -> Any:
|
|
67
|
+
"""Extract the first JSON object or array from a model response."""
|
|
68
|
+
stripped = text.strip()
|
|
69
|
+
if stripped.startswith("```"):
|
|
70
|
+
lines = stripped.splitlines()
|
|
71
|
+
if lines and lines[0].startswith("```"):
|
|
72
|
+
lines = lines[1:]
|
|
73
|
+
if lines and lines[-1].startswith("```"):
|
|
74
|
+
lines = lines[:-1]
|
|
75
|
+
stripped = "\n".join(lines).strip()
|
|
76
|
+
|
|
77
|
+
decoder = json.JSONDecoder()
|
|
78
|
+
for i, char in enumerate(stripped):
|
|
79
|
+
if char not in "[{":
|
|
80
|
+
continue
|
|
81
|
+
try:
|
|
82
|
+
payload, _ = decoder.raw_decode(stripped[i:])
|
|
83
|
+
return payload
|
|
84
|
+
except json.JSONDecodeError:
|
|
85
|
+
continue
|
|
86
|
+
raise ValueError("No JSON object or array found in taxonomy suggestion response")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def parse_taxonomy_suggestions(response_text: str) -> list[dict[str, Any]]:
|
|
90
|
+
"""Parse and normalize taxonomy suggestions returned by an LLM."""
|
|
91
|
+
payload = _extract_json_payload(response_text)
|
|
92
|
+
raw_suggestions = payload.get("suggestions", payload) if isinstance(payload, dict) else payload
|
|
93
|
+
if not isinstance(raw_suggestions, list):
|
|
94
|
+
raise ValueError("Taxonomy suggestion response must contain a suggestions list")
|
|
95
|
+
|
|
96
|
+
suggestions = []
|
|
97
|
+
seen_names = set()
|
|
98
|
+
for item in raw_suggestions:
|
|
99
|
+
if not isinstance(item, dict):
|
|
100
|
+
continue
|
|
101
|
+
|
|
102
|
+
name = str(item.get("name") or item.get("title") or item.get("failure_mode") or "").strip()
|
|
103
|
+
description = str(item.get("description") or item.get("definition") or "").strip()
|
|
104
|
+
rationale = str(item.get("rationale") or "").strip()
|
|
105
|
+
examples = item.get("examples") or []
|
|
106
|
+
|
|
107
|
+
if isinstance(examples, str):
|
|
108
|
+
examples = [examples]
|
|
109
|
+
examples = [str(example).strip() for example in examples if str(example).strip()]
|
|
110
|
+
|
|
111
|
+
if not name or not description:
|
|
112
|
+
continue
|
|
113
|
+
|
|
114
|
+
dedupe_key = name.casefold()
|
|
115
|
+
if dedupe_key in seen_names:
|
|
116
|
+
continue
|
|
117
|
+
seen_names.add(dedupe_key)
|
|
118
|
+
|
|
119
|
+
suggestions.append(
|
|
120
|
+
{
|
|
121
|
+
"name": name[:80],
|
|
122
|
+
"description": description,
|
|
123
|
+
"examples": examples[:5],
|
|
124
|
+
"rationale": rationale,
|
|
125
|
+
}
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
return suggestions
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def generate_taxonomy_suggestions(
|
|
132
|
+
open_codes: list[str],
|
|
133
|
+
existing_failure_modes: dict[str, dict[str, Any]] | None,
|
|
134
|
+
provider: str,
|
|
135
|
+
api_key: str,
|
|
136
|
+
model: str,
|
|
137
|
+
) -> list[dict[str, Any]]:
|
|
138
|
+
"""Call an LLM provider and return normalized taxonomy suggestions."""
|
|
139
|
+
prompt = build_taxonomy_prompt(open_codes, existing_failure_modes)
|
|
140
|
+
|
|
141
|
+
if provider == "openai":
|
|
142
|
+
if openai is None:
|
|
143
|
+
raise ImportError("openai package not installed")
|
|
144
|
+
client = openai.OpenAI(api_key=api_key)
|
|
145
|
+
response = client.chat.completions.create(
|
|
146
|
+
model=model,
|
|
147
|
+
messages=[
|
|
148
|
+
{"role": "system", "content": TAXONOMY_SYSTEM_PROMPT},
|
|
149
|
+
{"role": "user", "content": prompt},
|
|
150
|
+
],
|
|
151
|
+
max_tokens=1200,
|
|
152
|
+
temperature=0.2,
|
|
153
|
+
response_format={"type": "json_object"},
|
|
154
|
+
)
|
|
155
|
+
response_text = response.choices[0].message.content
|
|
156
|
+
elif provider == "anthropic":
|
|
157
|
+
if anthropic is None:
|
|
158
|
+
raise ImportError("anthropic package not installed")
|
|
159
|
+
client = anthropic.Anthropic(api_key=api_key)
|
|
160
|
+
response = client.messages.create(
|
|
161
|
+
model=model,
|
|
162
|
+
max_tokens=1200,
|
|
163
|
+
temperature=0.2,
|
|
164
|
+
system=TAXONOMY_SYSTEM_PROMPT,
|
|
165
|
+
messages=[{"role": "user", "content": prompt}],
|
|
166
|
+
)
|
|
167
|
+
response_text = response.content[0].text
|
|
168
|
+
else:
|
|
169
|
+
raise ValueError(f"Unsupported provider: {provider}")
|
|
170
|
+
|
|
171
|
+
return parse_taxonomy_suggestions(response_text)
|
|
File without changes
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import Any
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class BaseEvaluator(ABC):
|
|
7
|
+
"""Base class for all evaluators."""
|
|
8
|
+
|
|
9
|
+
@property
|
|
10
|
+
@abstractmethod
|
|
11
|
+
def name(self) -> str:
|
|
12
|
+
"""Return the name of the evaluator."""
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
@property
|
|
16
|
+
@abstractmethod
|
|
17
|
+
def requires_reference(self) -> bool:
|
|
18
|
+
"""Return True if this evaluator requires reference/expected outputs."""
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
@abstractmethod
|
|
22
|
+
def evaluate_single(self, output: str, reference: str = None, input_text: str = None) -> dict:
|
|
23
|
+
"""Evaluate a single output.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
output: The LLM output to evaluate
|
|
27
|
+
reference: The expected/reference output (optional)
|
|
28
|
+
input_text: The input prompt (optional)
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
Dictionary containing evaluation results
|
|
32
|
+
"""
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
def evaluate_batch(
|
|
36
|
+
self,
|
|
37
|
+
outputs: list[str],
|
|
38
|
+
references: list[str] = None,
|
|
39
|
+
inputs: list[str] = None,
|
|
40
|
+
progress_callback=None
|
|
41
|
+
) -> pd.DataFrame:
|
|
42
|
+
"""Evaluate a batch of outputs.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
outputs: List of LLM outputs
|
|
46
|
+
references: List of expected/reference outputs
|
|
47
|
+
inputs: List of input prompts
|
|
48
|
+
progress_callback: Optional callback for progress updates
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
DataFrame with evaluation results
|
|
52
|
+
"""
|
|
53
|
+
results = []
|
|
54
|
+
total = len(outputs)
|
|
55
|
+
|
|
56
|
+
for i, output in enumerate(outputs):
|
|
57
|
+
ref = references[i] if references else None
|
|
58
|
+
inp = inputs[i] if inputs else None
|
|
59
|
+
|
|
60
|
+
result = self.evaluate_single(output, ref, inp)
|
|
61
|
+
result["index"] = i
|
|
62
|
+
results.append(result)
|
|
63
|
+
|
|
64
|
+
if progress_callback:
|
|
65
|
+
progress_callback((i + 1) / total)
|
|
66
|
+
|
|
67
|
+
return pd.DataFrame(results)
|