llmvalidate 1.2.0__tar.gz → 1.3.1__tar.gz
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.
- {llmvalidate-1.2.0/src/llmvalidate.egg-info → llmvalidate-1.3.1}/PKG-INFO +46 -2
- {llmvalidate-1.2.0 → llmvalidate-1.3.1}/pyproject.toml +1 -1
- {llmvalidate-1.2.0 → llmvalidate-1.3.1}/readme.md +45 -1
- {llmvalidate-1.2.0 → llmvalidate-1.3.1}/src/llmvalidate/__init__.py +1 -1
- {llmvalidate-1.2.0 → llmvalidate-1.3.1}/src/llmvalidate/validation.py +213 -16
- {llmvalidate-1.2.0 → llmvalidate-1.3.1/src/llmvalidate.egg-info}/PKG-INFO +46 -2
- {llmvalidate-1.2.0 → llmvalidate-1.3.1}/LICENSE +0 -0
- {llmvalidate-1.2.0 → llmvalidate-1.3.1}/setup.cfg +0 -0
- {llmvalidate-1.2.0 → llmvalidate-1.3.1}/src/llmvalidate/cells.py +0 -0
- {llmvalidate-1.2.0 → llmvalidate-1.3.1}/src/llmvalidate/sortable_date.py +0 -0
- {llmvalidate-1.2.0 → llmvalidate-1.3.1}/src/llmvalidate/structured.py +0 -0
- {llmvalidate-1.2.0 → llmvalidate-1.3.1}/src/llmvalidate/utils.py +0 -0
- {llmvalidate-1.2.0 → llmvalidate-1.3.1}/src/llmvalidate.egg-info/SOURCES.txt +0 -0
- {llmvalidate-1.2.0 → llmvalidate-1.3.1}/src/llmvalidate.egg-info/dependency_links.txt +0 -0
- {llmvalidate-1.2.0 → llmvalidate-1.3.1}/src/llmvalidate.egg-info/requires.txt +0 -0
- {llmvalidate-1.2.0 → llmvalidate-1.3.1}/src/llmvalidate.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: llmvalidate
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.3.1
|
|
4
4
|
Summary: Oncoshot LLM validation framework
|
|
5
5
|
License: MIT
|
|
6
6
|
Project-URL: Homepage, https://github.com/Oncoshot/llm-validation-framework
|
|
@@ -132,7 +132,7 @@ results_df, metrics_df = validate(
|
|
|
132
132
|
|
|
133
133
|
### DataFrame Format
|
|
134
134
|
- **Unique index** - Each row must have a unique identifier (e.g., "Patient ID")
|
|
135
|
-
- **Label columns** - Ground truth values for each field you want to validate
|
|
135
|
+
- **Label columns** - Ground truth values for each field you want to validate (unless the field is declared in `derived_fields` — see [Derived fields](#derived-fields-scored-but-not-an-input-column))
|
|
136
136
|
- **Result columns** (Mode 1 only) - LLM predictions as `Res: {Field Name}` columns
|
|
137
137
|
- **Raw text column** (Mode 2 only) - Source text for LLM inference (e.g., "medical_report")
|
|
138
138
|
|
|
@@ -377,6 +377,47 @@ The final row contains bootstrap parameters for reference: sample size (N) and c
|
|
|
377
377
|
|
|
378
378
|
## 🛠️ Advanced Configuration
|
|
379
379
|
|
|
380
|
+
### Derived Fields (scored, but not an input column)
|
|
381
|
+
|
|
382
|
+
Every name in `fields` must normally be a column in `source_df` — that check is what catches a
|
|
383
|
+
misspelled field name. But `fields` conflates two things: *the column holding the labels* and
|
|
384
|
+
*the name of the thing being scored*. They usually coincide, and sometimes they don't: a
|
|
385
|
+
`comparison_callback` can derive what it scores from a **different** column and write the field
|
|
386
|
+
plus its own counts onto the row. Such a field has no input column to require.
|
|
387
|
+
|
|
388
|
+
Declare those names in `derived_fields` to exempt them from the check (and only them):
|
|
389
|
+
|
|
390
|
+
```python
|
|
391
|
+
def comparison_callback(row, i, raw_text_column_name):
|
|
392
|
+
# gold labels live in 'labels'; the scored 'spans' field is derived from them here
|
|
393
|
+
golden_spans = spans_from(row["labels"])
|
|
394
|
+
row["spans"] = golden_spans
|
|
395
|
+
row["TP: spans"] = ...
|
|
396
|
+
row["FP: spans"] = ...
|
|
397
|
+
row["FN: spans"] = ...
|
|
398
|
+
|
|
399
|
+
results_df, metrics_df = validate(
|
|
400
|
+
source_df=df, # has a 'labels' column, but no 'spans' column
|
|
401
|
+
fields=["spans"],
|
|
402
|
+
structure_callback=my_callback,
|
|
403
|
+
comparison_callback=comparison_callback,
|
|
404
|
+
derived_fields=("spans",), # 'spans' is created during scoring, not read from input
|
|
405
|
+
)
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
Default `()` means no derived fields — every scored field must be an input column, as before.
|
|
409
|
+
Each rule fails fast with a clear message:
|
|
410
|
+
|
|
411
|
+
| Situation | Result |
|
|
412
|
+
|-----------|--------|
|
|
413
|
+
| Derived field absent from `source_df` | ✅ accepted — the callback creates it |
|
|
414
|
+
| Derived field **present** in `source_df` anyway (e.g. a legacy column of `[]` placeholders) | ✅ accepted, no warning — behaves exactly as before |
|
|
415
|
+
| A scored field that is neither in `source_df` nor declared derived | ❌ `ValueError` — the original missing-column error, unchanged |
|
|
416
|
+
| A name in `derived_fields` that is not in `fields` | ❌ `ValueError` — it exempts nothing; usually a typo |
|
|
417
|
+
| Non-empty `derived_fields` with `comparison_callback=None` | ❌ `ValueError` — nothing would create the column |
|
|
418
|
+
| A bare string (`derived_fields="spans"`) | ❌ `TypeError` — rather than iterating its characters |
|
|
419
|
+
| Declared derived field still missing after scoring | ❌ `ValueError` naming it — rather than a bare `KeyError` from inside the metrics step |
|
|
420
|
+
|
|
380
421
|
### Parallel Processing
|
|
381
422
|
```python
|
|
382
423
|
validate(
|
|
@@ -439,7 +480,10 @@ llm-validation-framework/
|
|
|
439
480
|
|-------|----------|
|
|
440
481
|
| **"Cannot infer fields"** | Ensure DataFrame has both `{Field}` and `Res: {Field}` columns when `structure_callback=None` |
|
|
441
482
|
| **"Missing fields"** | Verify `fields` parameter contains column names that exist in your DataFrame |
|
|
483
|
+
| **"have no result column to score"** / **"were not scored"** | Make `structure_callback` return a key named exactly as each field in `fields` (or score the field in a `comparison_callback`), or remove the field from `fields` |
|
|
484
|
+
| **"source_df has no rows"** | Pass a DataFrame with at least one case; the message names the fields that have no rows to score |
|
|
442
485
|
| **"Duplicate index"** | Use `df.reset_index(drop=True)` or ensure your DataFrame index has unique values |
|
|
486
|
+
| **"Please remove duplicate column names"** | Rename or drop the columns named in the message so every column name is unique |
|
|
443
487
|
| **Import/dependency errors** | Run `pip install -r requirements.txt` and verify Python 3.11+ |
|
|
444
488
|
| **Slow performance** | Enable parallel processing with `max_workers=None` and `use_threads=True` for LLM API calls |
|
|
445
489
|
|
|
@@ -108,7 +108,7 @@ results_df, metrics_df = validate(
|
|
|
108
108
|
|
|
109
109
|
### DataFrame Format
|
|
110
110
|
- **Unique index** - Each row must have a unique identifier (e.g., "Patient ID")
|
|
111
|
-
- **Label columns** - Ground truth values for each field you want to validate
|
|
111
|
+
- **Label columns** - Ground truth values for each field you want to validate (unless the field is declared in `derived_fields` — see [Derived fields](#derived-fields-scored-but-not-an-input-column))
|
|
112
112
|
- **Result columns** (Mode 1 only) - LLM predictions as `Res: {Field Name}` columns
|
|
113
113
|
- **Raw text column** (Mode 2 only) - Source text for LLM inference (e.g., "medical_report")
|
|
114
114
|
|
|
@@ -353,6 +353,47 @@ The final row contains bootstrap parameters for reference: sample size (N) and c
|
|
|
353
353
|
|
|
354
354
|
## 🛠️ Advanced Configuration
|
|
355
355
|
|
|
356
|
+
### Derived Fields (scored, but not an input column)
|
|
357
|
+
|
|
358
|
+
Every name in `fields` must normally be a column in `source_df` — that check is what catches a
|
|
359
|
+
misspelled field name. But `fields` conflates two things: *the column holding the labels* and
|
|
360
|
+
*the name of the thing being scored*. They usually coincide, and sometimes they don't: a
|
|
361
|
+
`comparison_callback` can derive what it scores from a **different** column and write the field
|
|
362
|
+
plus its own counts onto the row. Such a field has no input column to require.
|
|
363
|
+
|
|
364
|
+
Declare those names in `derived_fields` to exempt them from the check (and only them):
|
|
365
|
+
|
|
366
|
+
```python
|
|
367
|
+
def comparison_callback(row, i, raw_text_column_name):
|
|
368
|
+
# gold labels live in 'labels'; the scored 'spans' field is derived from them here
|
|
369
|
+
golden_spans = spans_from(row["labels"])
|
|
370
|
+
row["spans"] = golden_spans
|
|
371
|
+
row["TP: spans"] = ...
|
|
372
|
+
row["FP: spans"] = ...
|
|
373
|
+
row["FN: spans"] = ...
|
|
374
|
+
|
|
375
|
+
results_df, metrics_df = validate(
|
|
376
|
+
source_df=df, # has a 'labels' column, but no 'spans' column
|
|
377
|
+
fields=["spans"],
|
|
378
|
+
structure_callback=my_callback,
|
|
379
|
+
comparison_callback=comparison_callback,
|
|
380
|
+
derived_fields=("spans",), # 'spans' is created during scoring, not read from input
|
|
381
|
+
)
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
Default `()` means no derived fields — every scored field must be an input column, as before.
|
|
385
|
+
Each rule fails fast with a clear message:
|
|
386
|
+
|
|
387
|
+
| Situation | Result |
|
|
388
|
+
|-----------|--------|
|
|
389
|
+
| Derived field absent from `source_df` | ✅ accepted — the callback creates it |
|
|
390
|
+
| Derived field **present** in `source_df` anyway (e.g. a legacy column of `[]` placeholders) | ✅ accepted, no warning — behaves exactly as before |
|
|
391
|
+
| A scored field that is neither in `source_df` nor declared derived | ❌ `ValueError` — the original missing-column error, unchanged |
|
|
392
|
+
| A name in `derived_fields` that is not in `fields` | ❌ `ValueError` — it exempts nothing; usually a typo |
|
|
393
|
+
| Non-empty `derived_fields` with `comparison_callback=None` | ❌ `ValueError` — nothing would create the column |
|
|
394
|
+
| A bare string (`derived_fields="spans"`) | ❌ `TypeError` — rather than iterating its characters |
|
|
395
|
+
| Declared derived field still missing after scoring | ❌ `ValueError` naming it — rather than a bare `KeyError` from inside the metrics step |
|
|
396
|
+
|
|
356
397
|
### Parallel Processing
|
|
357
398
|
```python
|
|
358
399
|
validate(
|
|
@@ -415,7 +456,10 @@ llm-validation-framework/
|
|
|
415
456
|
|-------|----------|
|
|
416
457
|
| **"Cannot infer fields"** | Ensure DataFrame has both `{Field}` and `Res: {Field}` columns when `structure_callback=None` |
|
|
417
458
|
| **"Missing fields"** | Verify `fields` parameter contains column names that exist in your DataFrame |
|
|
459
|
+
| **"have no result column to score"** / **"were not scored"** | Make `structure_callback` return a key named exactly as each field in `fields` (or score the field in a `comparison_callback`), or remove the field from `fields` |
|
|
460
|
+
| **"source_df has no rows"** | Pass a DataFrame with at least one case; the message names the fields that have no rows to score |
|
|
418
461
|
| **"Duplicate index"** | Use `df.reset_index(drop=True)` or ensure your DataFrame index has unique values |
|
|
462
|
+
| **"Please remove duplicate column names"** | Rename or drop the columns named in the message so every column name is unique |
|
|
419
463
|
| **Import/dependency errors** | Run `pip install -r requirements.txt` and verify Python 3.11+ |
|
|
420
464
|
| **Slow performance** | Enable parallel processing with `max_workers=None` and `use_threads=True` for LLM API calls |
|
|
421
465
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Managed by python-semantic-release — do not edit by hand; the release workflow rewrites
|
|
2
2
|
# this line. Set to 0.7.0 once by hand to clear the drift from ONC-12379, during which the
|
|
3
3
|
# release never reached this file and it stayed at 0.0.0 across every published version.
|
|
4
|
-
__version__ = "1.
|
|
4
|
+
__version__ = "1.3.1"
|
|
5
5
|
|
|
6
6
|
# `structured` is pydantic-only and cheap, so it is imported eagerly: consumers that
|
|
7
7
|
# only need the extraction contract (StructuredResult / StructuredField) get it without
|
|
@@ -64,6 +64,28 @@ def calculate_binary_metrics(TP, FP, FN, TN):
|
|
|
64
64
|
|
|
65
65
|
return precision, recall, f1_score, f2_score, accuracy, specificity
|
|
66
66
|
|
|
67
|
+
def _raise_on_duplicate_columns(df):
|
|
68
|
+
"""Raises ValueError naming the column names 'df' has more than once.
|
|
69
|
+
|
|
70
|
+
A row is scored by column name, so with a name used twice there is no telling which of
|
|
71
|
+
the columns a label, a result or a count belongs to.
|
|
72
|
+
"""
|
|
73
|
+
duplicated = df.columns[df.columns.duplicated()].unique().tolist()
|
|
74
|
+
if duplicated:
|
|
75
|
+
raise ValueError(f"Please remove duplicate column names: {duplicated}")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _row_cells(row):
|
|
79
|
+
"""The cells of 'row' by column, each value exactly as the row holds it.
|
|
80
|
+
|
|
81
|
+
A NumPy scalar stays the NumPy scalar it is (`row.to_dict()` would turn it into a Python
|
|
82
|
+
number): `np.float32(0.1)` equals the prediction `0.1`, while the Python float it
|
|
83
|
+
converts to, `0.10000000149011612`, does not. A missing value likewise stays the
|
|
84
|
+
`pd.NA`, NaN or None it is.
|
|
85
|
+
"""
|
|
86
|
+
return dict(zip(row.index, row.array))
|
|
87
|
+
|
|
88
|
+
|
|
67
89
|
def compare_results_all(df, fields, hierarchy={}, comparison_callback=None, raw_text_column_name: str = "raw_text"):
|
|
68
90
|
""" For each case from df calls and for each field from 'fields' compares results with 'Res: '+field
|
|
69
91
|
and adds columns 'Inc: '+field, 'Cor: '+field, 'Mis: '+field, 'Spu: '+field, 'Par: '+field
|
|
@@ -83,8 +105,15 @@ def compare_results_all(df, fields, hierarchy={}, comparison_callback=None, raw_
|
|
|
83
105
|
'Spu: ' for Spurious
|
|
84
106
|
'Par: ' for Partial (only when the field has a hierarchy entry)
|
|
85
107
|
'TN: ' for True Negative (scalar fields only; not defined for list fields)
|
|
108
|
+
A count that is not defined for a case (the case has no label for the field) is NaN,
|
|
109
|
+
and so is a per-case score with nothing to divide by; the '... items' cell of such
|
|
110
|
+
a case is None.
|
|
111
|
+
|
|
112
|
+
Raises ValueError if 'df' has duplicate column names.
|
|
86
113
|
"""
|
|
87
114
|
|
|
115
|
+
_raise_on_duplicate_columns(df)
|
|
116
|
+
|
|
88
117
|
fields = [f for f in fields if f in df] #ignore fields which are not in columns (they may be added later by comparison_callback)
|
|
89
118
|
|
|
90
119
|
# hierarchy is a per-field map {field: {child: parent}}; fail fast with a clear
|
|
@@ -117,14 +146,19 @@ def compare_results_all(df, fields, hierarchy={}, comparison_callback=None, raw_
|
|
|
117
146
|
modified_rows = []
|
|
118
147
|
# Iterate over the rows of the DataFrame
|
|
119
148
|
for i, row in df.iterrows():
|
|
149
|
+
# The cells of the row by column: the input cells, then every derived cell in the
|
|
150
|
+
# order it is first set. They are collected in a dict and the row is built from it
|
|
151
|
+
# once: a dict takes a new key in constant time, where a pandas Series is rebuilt,
|
|
152
|
+
# so the cost of a cell does not depend on how wide the row is.
|
|
153
|
+
cells = _row_cells(row)
|
|
120
154
|
|
|
121
155
|
for field in fields:
|
|
122
|
-
expected =
|
|
156
|
+
expected = cells[field]
|
|
123
157
|
|
|
124
|
-
if 'Res: ' + field not in
|
|
158
|
+
if 'Res: ' + field not in cells:
|
|
125
159
|
continue
|
|
126
160
|
|
|
127
|
-
actual =
|
|
161
|
+
actual = cells['Res: ' + field]
|
|
128
162
|
|
|
129
163
|
# Shape already validated up front; None/missing -> no hierarchy for this field.
|
|
130
164
|
field_hierarchy = hierarchy.get(field) or {}
|
|
@@ -147,10 +181,10 @@ def compare_results_all(df, fields, hierarchy={}, comparison_callback=None, raw_
|
|
|
147
181
|
res['Correct'], res['Partial'], res['Incorrect'], res['Spurious'], res['Missing'], TN_case
|
|
148
182
|
)
|
|
149
183
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
184
|
+
cells['Precision: ' + field] = precision
|
|
185
|
+
cells['Recall: ' + field] = recall
|
|
186
|
+
cells['F1 score: ' + field] = f1_score
|
|
187
|
+
cells['F2 score: ' + field] = f2_score
|
|
154
188
|
|
|
155
189
|
if not field_hierarchy:
|
|
156
190
|
#we don't want useless columns if no hierarchy for this field anyway
|
|
@@ -169,12 +203,12 @@ def compare_results_all(df, fields, hierarchy={}, comparison_callback=None, raw_
|
|
|
169
203
|
# None (undefined) when the case was not labeled for this field.
|
|
170
204
|
# TN is not defined for list fields (see get_metrics).
|
|
171
205
|
if res['Correct'] is None:
|
|
172
|
-
|
|
206
|
+
cells['TN: ' + field] = np.nan
|
|
173
207
|
#row['TN: ' + field + ' items'] = None
|
|
174
208
|
else:
|
|
175
209
|
TN_case = 1 if (is_scalar_empty(normalize(expected))
|
|
176
210
|
and is_scalar_empty(normalize(actual))) else 0
|
|
177
|
-
|
|
211
|
+
cells['TN: ' + field] = TN_case
|
|
178
212
|
# a TN case has no extracted item: the matched "item" is the
|
|
179
213
|
# no-information marker itself therefore pointless to add
|
|
180
214
|
# row['TN: ' + field + ' items'] = ['-'] if TN_case else []
|
|
@@ -182,14 +216,22 @@ def compare_results_all(df, fields, hierarchy={}, comparison_callback=None, raw_
|
|
|
182
216
|
# Iterate over the key-value pairs in the result dictionary
|
|
183
217
|
for key, value in res.items():
|
|
184
218
|
# Create a new column in the DataFrame using the key
|
|
185
|
-
# Assign the corresponding value to the column
|
|
186
|
-
|
|
219
|
+
# Assign the corresponding value to the column. An undefined count is stored
|
|
220
|
+
# as NaN, so that arithmetic and comparisons on it in a comparison_callback
|
|
221
|
+
# give NaN and False where None would raise.
|
|
222
|
+
cells[key[:3] + ': ' + field] = np.nan if value is None else value
|
|
187
223
|
|
|
188
224
|
# Iterate over the key-value pairs in the result items dictionary
|
|
189
225
|
for key, value in res_items.items():
|
|
190
226
|
# Create a new column in the DataFrame using the key
|
|
191
227
|
# Assign the corresponding value to the column
|
|
192
|
-
|
|
228
|
+
cells[key[:3] + ': ' + field + ' items'] = value
|
|
229
|
+
|
|
230
|
+
# The callback gets the finished row: the input columns followed by every cell
|
|
231
|
+
# derived above, each value as it was read or set (an input cell keeps its type, a
|
|
232
|
+
# count stays an int whatever else the row holds). It may read it, overwrite cells
|
|
233
|
+
# and add its own.
|
|
234
|
+
row = pd.Series(cells, dtype=object, name=i)
|
|
193
235
|
|
|
194
236
|
if comparison_callback:
|
|
195
237
|
comparison_callback(row, i, raw_text_column_name)
|
|
@@ -286,6 +328,21 @@ def _confidence_column(field, columns):
|
|
|
286
328
|
return None
|
|
287
329
|
|
|
288
330
|
|
|
331
|
+
def _fields_without_scores(columns, fields):
|
|
332
|
+
"""Fields from 'fields' that `get_metrics` cannot aggregate from 'columns'.
|
|
333
|
+
|
|
334
|
+
`get_metrics` reads a field's counts unguarded: 'TP: ', 'FP: ' and 'FN: ' when a
|
|
335
|
+
'TP: ' column exists for it, otherwise 'Cor: ', 'Mis: ' and 'Spu: '. A field lacking
|
|
336
|
+
any column of its set has not been scored.
|
|
337
|
+
"""
|
|
338
|
+
unscored = []
|
|
339
|
+
for field in fields:
|
|
340
|
+
prefixes = ('TP: ', 'FP: ', 'FN: ') if 'TP: ' + field in columns else ('Cor: ', 'Mis: ', 'Spu: ')
|
|
341
|
+
if any(prefix + field not in columns for prefix in prefixes):
|
|
342
|
+
unscored.append(field)
|
|
343
|
+
return unscored
|
|
344
|
+
|
|
345
|
+
|
|
289
346
|
def get_metrics(res_df, fields):
|
|
290
347
|
""" For results dataframe generated by validate
|
|
291
348
|
produces dataframe with metrics for all available confidence levels and overall
|
|
@@ -844,7 +901,8 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
|
|
|
844
901
|
comparison_callback = None,
|
|
845
902
|
max_workers: int | None = 1,
|
|
846
903
|
use_threads: bool = True,
|
|
847
|
-
hierarchy = {}
|
|
904
|
+
hierarchy = {},
|
|
905
|
+
derived_fields = ()):
|
|
848
906
|
"""
|
|
849
907
|
Performs validation by applying a structuring callback to an input dataset and evaluating performance.
|
|
850
908
|
|
|
@@ -864,12 +922,43 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
|
|
|
864
922
|
If None and structure_callback is also None, fields will be automatically inferred
|
|
865
923
|
from columns that have corresponding "Res: " columns.
|
|
866
924
|
|
|
925
|
+
- **derived_fields (collection of str, optional)**:
|
|
926
|
+
Names in ``fields`` that the ``comparison_callback`` **creates** during scoring, so
|
|
927
|
+
they are exempt from the "must already be a column in source_df" check. Default
|
|
928
|
+
``()`` (no derived fields) keeps the current behavior: every scored field must be an
|
|
929
|
+
input column.
|
|
930
|
+
|
|
931
|
+
This splits a distinction ``fields`` otherwise conflates: a name in ``fields`` is
|
|
932
|
+
both *the column holding the labels* and *the name of the thing being scored*. Those
|
|
933
|
+
usually coincide, but need not — a ``comparison_callback`` can derive what it scores
|
|
934
|
+
from a different column (e.g. score a ``spans`` field computed from a ``labels``
|
|
935
|
+
column) and write the field plus its own ``TP:``/``FP:``/``FN:`` counts onto the row.
|
|
936
|
+
For such a field only the second meaning applies and there is no input column to
|
|
937
|
+
require, which is what ``derived_fields`` declares. The check is kept for every other
|
|
938
|
+
field because it is what catches a misspelled field name.
|
|
939
|
+
|
|
940
|
+
Rules, each failing fast with a clear message:
|
|
941
|
+
- a name in ``derived_fields`` that is not in ``fields`` is a ``ValueError`` — it
|
|
942
|
+
exempts nothing and is usually a typo;
|
|
943
|
+
- a non-empty ``derived_fields`` with ``comparison_callback=None`` is a
|
|
944
|
+
``ValueError`` — nothing would create the column;
|
|
945
|
+
- a bare string (``derived_fields='spans'``) is a ``TypeError``, rather than a silent
|
|
946
|
+
iteration over its characters;
|
|
947
|
+
- a derived field that *is* present in ``source_df`` anyway is accepted with no error
|
|
948
|
+
and no warning, so datasets carrying placeholder columns keep working unchanged;
|
|
949
|
+
- a derived field still missing after scoring is a ``ValueError`` naming it, instead
|
|
950
|
+
of a bare ``KeyError`` raised later from inside ``get_metrics``.
|
|
951
|
+
|
|
867
952
|
- **structure_callback (callable, optional)**:
|
|
868
953
|
A callback function that will be applied to each row to generate structured predictions.
|
|
869
954
|
If None, assumes that source_df already contains "Res: " columns with results.
|
|
870
955
|
|
|
871
956
|
- **comparison_callback (callable, optional)**:
|
|
872
957
|
A callback function that will be applied to each row to generate comparison results.
|
|
958
|
+
It receives the row after the built-in scoring and may score a field itself by
|
|
959
|
+
writing that field's ``TP:``/``FP:``/``FN:`` (or ``Cor:``/``Mis:``/``Spu:``) counts
|
|
960
|
+
onto the row. On the row it receives, a built-in count that is not defined for the
|
|
961
|
+
case (no label for the field) is NaN, and the matching ``... items`` cell is None.
|
|
873
962
|
|
|
874
963
|
- **hierarchy (dict, optional)**:
|
|
875
964
|
A PER-FIELD nested map ``{field: {child: parent}}`` enabling partial (hierarchical)
|
|
@@ -896,6 +985,29 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
|
|
|
896
985
|
- The **results** DataFrame with row-level details.
|
|
897
986
|
- The **metrics** DataFrame with aggregated performance statistics.
|
|
898
987
|
|
|
988
|
+
### Raises:
|
|
989
|
+
- **ValueError** when a scored field cannot be scored, naming every such field instead
|
|
990
|
+
of a bare ``KeyError`` raised later from inside ``get_metrics``. A field is scored
|
|
991
|
+
either by the built-in comparison, which needs its ``Res: <field>`` column, or by the
|
|
992
|
+
``comparison_callback`` writing its counts. So:
|
|
993
|
+
- with ``comparison_callback=None``, every field must have a ``Res: <field>`` column
|
|
994
|
+
once the structuring pass is done: ``structure_callback`` must return a key named
|
|
995
|
+
exactly as the field for at least one row, and the column must not be listed in
|
|
996
|
+
``drop_columns``. This is reported before the comparison runs;
|
|
997
|
+
- with a ``comparison_callback``, a field with no ``Res: <field>`` column is accepted
|
|
998
|
+
as long as the callback writes its counts, so this is reported after the
|
|
999
|
+
comparison, for the fields that still have none.
|
|
1000
|
+
A field whose result is returned for some rows only has a ``Res: <field>`` column and
|
|
1001
|
+
is scored: the rows without a result count as an empty prediction.
|
|
1002
|
+
- **ValueError** / **TypeError** for the input mistakes described under the parameters
|
|
1003
|
+
above (duplicate index values, missing label or result columns, ``derived_fields``
|
|
1004
|
+
misuse).
|
|
1005
|
+
- **ValueError** naming the fields when ``source_df`` has no rows, so that none of them
|
|
1006
|
+
has a row to score. It is raised after the checks on columns and fields above, and
|
|
1007
|
+
before ``structure_callback`` is called or any file is written.
|
|
1008
|
+
- **ValueError** naming the duplicated names when ``source_df`` has duplicate column
|
|
1009
|
+
names, or when the structuring pass leaves the results with any.
|
|
1010
|
+
|
|
899
1011
|
### Notes:
|
|
900
1012
|
- The output CSV files are saved with filenames prefixed by the current timestamp to avoid overwriting previous runs.
|
|
901
1013
|
- The source df should have index with unique values for proper processing.
|
|
@@ -904,6 +1016,19 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
|
|
|
904
1016
|
if source_df.index.has_duplicates:
|
|
905
1017
|
raise ValueError("Please remove duplicate values in index column")
|
|
906
1018
|
|
|
1019
|
+
_raise_on_duplicate_columns(source_df)
|
|
1020
|
+
|
|
1021
|
+
# derived_fields is a collection of field names, so a bare string is a caller mistake:
|
|
1022
|
+
# it would iterate into single characters ('spans' -> 's', 'p', 'a', ...) and silently
|
|
1023
|
+
# exempt names nobody declared. Fail fast with a clear message, the same way the
|
|
1024
|
+
# hierarchy shape is checked in compare_results_all.
|
|
1025
|
+
if isinstance(derived_fields, (str, bytes)):
|
|
1026
|
+
raise TypeError(
|
|
1027
|
+
"derived_fields must be a collection of field names, not a single string; "
|
|
1028
|
+
f"pass ({derived_fields!r},) to declare one derived field"
|
|
1029
|
+
)
|
|
1030
|
+
derived_fields = tuple(derived_fields)
|
|
1031
|
+
|
|
907
1032
|
# Infer fields from columns if both structure_callback and fields are None
|
|
908
1033
|
if structure_callback is None and fields is None:
|
|
909
1034
|
inferred_fields = infer_fields(source_df)
|
|
@@ -917,8 +1042,29 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
|
|
|
917
1042
|
if structure_callback is not None and fields is None:
|
|
918
1043
|
raise ValueError("fields parameter is required when structure_callback is provided")
|
|
919
1044
|
|
|
920
|
-
#
|
|
921
|
-
|
|
1045
|
+
# A derived field is one of the scored fields, so a name outside 'fields' exempts
|
|
1046
|
+
# nothing — that is a caller mistake (typically a typo), not a feature.
|
|
1047
|
+
unknown_derived_fields = [field for field in derived_fields if field not in fields]
|
|
1048
|
+
if unknown_derived_fields:
|
|
1049
|
+
raise ValueError(
|
|
1050
|
+
f"The following derived_fields are not in fields: {unknown_derived_fields}. "
|
|
1051
|
+
"derived_fields must be a subset of fields (they are scored fields whose column "
|
|
1052
|
+
"the comparison_callback creates)"
|
|
1053
|
+
)
|
|
1054
|
+
|
|
1055
|
+
# A derived field exists only because the comparison_callback writes it, so without a
|
|
1056
|
+
# callback nothing would ever create the column.
|
|
1057
|
+
if derived_fields and comparison_callback is None:
|
|
1058
|
+
raise ValueError(
|
|
1059
|
+
f"derived_fields {list(derived_fields)} require a comparison_callback to create "
|
|
1060
|
+
"them; with comparison_callback=None nothing adds those columns"
|
|
1061
|
+
)
|
|
1062
|
+
|
|
1063
|
+
# Validate that all specified fields exist in source_df. Derived fields are exempt: the
|
|
1064
|
+
# comparison_callback creates them during scoring, so there is no input column to find
|
|
1065
|
+
# (compare_results_all already tolerates a scored field that is not yet a column).
|
|
1066
|
+
missing_fields = [field for field in fields
|
|
1067
|
+
if field not in source_df.columns and field not in derived_fields]
|
|
922
1068
|
if missing_fields:
|
|
923
1069
|
raise ValueError(f"The following fields are missing from source_df: {missing_fields}")
|
|
924
1070
|
|
|
@@ -928,6 +1074,13 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
|
|
|
928
1074
|
if missing_res_columns:
|
|
929
1075
|
raise ValueError(f"When structure_callback is None, the following result columns must be present in source_df: {missing_res_columns}")
|
|
930
1076
|
|
|
1077
|
+
# With no rows there is nothing to structure and nothing to score. Reported here, after
|
|
1078
|
+
# the checks on columns and fields and before anything is run or written.
|
|
1079
|
+
if len(source_df) == 0 and len(fields) > 0:
|
|
1080
|
+
raise ValueError(
|
|
1081
|
+
f"source_df has no rows, so the following fields have no rows to score: {list(fields)}"
|
|
1082
|
+
)
|
|
1083
|
+
|
|
931
1084
|
if output_folder:
|
|
932
1085
|
os.makedirs(output_folder, exist_ok=True)
|
|
933
1086
|
|
|
@@ -947,11 +1100,55 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
|
|
|
947
1100
|
# Save results
|
|
948
1101
|
if output_folder:
|
|
949
1102
|
res_df.to_csv(os.path.join(output_folder, f"{file_prefix} results.csv"))
|
|
950
|
-
|
|
1103
|
+
|
|
1104
|
+
# Without a comparison_callback the built-in comparison is the only thing that scores a
|
|
1105
|
+
# field, and it skips a field that has no 'Res: ' column. Such a field is already known
|
|
1106
|
+
# here to end up without counts, so report it before the comparison runs. The results
|
|
1107
|
+
# saved just above stay on disk to show what the structuring pass did return.
|
|
1108
|
+
if comparison_callback is None:
|
|
1109
|
+
fields_without_result = [
|
|
1110
|
+
field for field in _fields_without_scores(res_df.columns, fields)
|
|
1111
|
+
if field not in res_df.columns or 'Res: ' + field not in res_df.columns
|
|
1112
|
+
]
|
|
1113
|
+
if fields_without_result:
|
|
1114
|
+
raise ValueError(
|
|
1115
|
+
f"The following fields have no result column to score: {fields_without_result}. "
|
|
1116
|
+
"Each scored field needs a 'Res: <field>' column: structure_callback must "
|
|
1117
|
+
"return a key named exactly as the field for at least one row (if every row "
|
|
1118
|
+
"failed, see the 'Sys: exception' column) and the column must not be listed "
|
|
1119
|
+
"in drop_columns. Otherwise remove the field from fields, or score it in a "
|
|
1120
|
+
"comparison_callback"
|
|
1121
|
+
)
|
|
1122
|
+
|
|
951
1123
|
###################################
|
|
952
1124
|
# Analyse the results and calculate the metrics
|
|
953
1125
|
res_df = compare_results_all(res_df, fields, hierarchy=hierarchy, comparison_callback=comparison_callback, raw_text_column_name=raw_text_column_name)
|
|
954
1126
|
|
|
1127
|
+
# Scoring is done, so a declared derived field must exist by now. Report it here:
|
|
1128
|
+
# get_metrics reads field_df[field] unguarded, so an undelivered derived field would
|
|
1129
|
+
# otherwise surface as a bare `KeyError: '<field>'` from deep inside it.
|
|
1130
|
+
undelivered_derived_fields = [field for field in derived_fields if field not in res_df.columns]
|
|
1131
|
+
if undelivered_derived_fields:
|
|
1132
|
+
raise ValueError(
|
|
1133
|
+
f"The following derived_fields are still missing after comparison: "
|
|
1134
|
+
f"{undelivered_derived_fields}. They were exempted from the source_df column "
|
|
1135
|
+
"check because comparison_callback was expected to create them during scoring"
|
|
1136
|
+
)
|
|
1137
|
+
|
|
1138
|
+
# A comparison_callback may score a field itself, so a field with no 'Res: ' column is
|
|
1139
|
+
# only known to be unscored once the callback has run on every row. Report it here:
|
|
1140
|
+
# get_metrics reads the counts unguarded, so an unscored field would otherwise surface
|
|
1141
|
+
# as a bare `KeyError: 'Cor: <field>'` from deep inside it.
|
|
1142
|
+
unscored_fields = _fields_without_scores(res_df.columns, fields)
|
|
1143
|
+
if unscored_fields:
|
|
1144
|
+
raise ValueError(
|
|
1145
|
+
f"The following fields were not scored: {unscored_fields}. A field is scored "
|
|
1146
|
+
"from its 'Res: <field>' column, which structure_callback creates by "
|
|
1147
|
+
"returning a key named exactly as the field, or by a comparison_callback "
|
|
1148
|
+
"that writes its 'TP: '/'FP: '/'FN: ' (or 'Cor: '/'Mis: '/'Spu: ') counts "
|
|
1149
|
+
"onto the row. Provide one of the two, or remove the field from fields"
|
|
1150
|
+
)
|
|
1151
|
+
|
|
955
1152
|
# Save results
|
|
956
1153
|
if output_folder:
|
|
957
1154
|
res_df.to_csv(os.path.join(output_folder, f"{file_prefix} results.csv"))
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: llmvalidate
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.3.1
|
|
4
4
|
Summary: Oncoshot LLM validation framework
|
|
5
5
|
License: MIT
|
|
6
6
|
Project-URL: Homepage, https://github.com/Oncoshot/llm-validation-framework
|
|
@@ -132,7 +132,7 @@ results_df, metrics_df = validate(
|
|
|
132
132
|
|
|
133
133
|
### DataFrame Format
|
|
134
134
|
- **Unique index** - Each row must have a unique identifier (e.g., "Patient ID")
|
|
135
|
-
- **Label columns** - Ground truth values for each field you want to validate
|
|
135
|
+
- **Label columns** - Ground truth values for each field you want to validate (unless the field is declared in `derived_fields` — see [Derived fields](#derived-fields-scored-but-not-an-input-column))
|
|
136
136
|
- **Result columns** (Mode 1 only) - LLM predictions as `Res: {Field Name}` columns
|
|
137
137
|
- **Raw text column** (Mode 2 only) - Source text for LLM inference (e.g., "medical_report")
|
|
138
138
|
|
|
@@ -377,6 +377,47 @@ The final row contains bootstrap parameters for reference: sample size (N) and c
|
|
|
377
377
|
|
|
378
378
|
## 🛠️ Advanced Configuration
|
|
379
379
|
|
|
380
|
+
### Derived Fields (scored, but not an input column)
|
|
381
|
+
|
|
382
|
+
Every name in `fields` must normally be a column in `source_df` — that check is what catches a
|
|
383
|
+
misspelled field name. But `fields` conflates two things: *the column holding the labels* and
|
|
384
|
+
*the name of the thing being scored*. They usually coincide, and sometimes they don't: a
|
|
385
|
+
`comparison_callback` can derive what it scores from a **different** column and write the field
|
|
386
|
+
plus its own counts onto the row. Such a field has no input column to require.
|
|
387
|
+
|
|
388
|
+
Declare those names in `derived_fields` to exempt them from the check (and only them):
|
|
389
|
+
|
|
390
|
+
```python
|
|
391
|
+
def comparison_callback(row, i, raw_text_column_name):
|
|
392
|
+
# gold labels live in 'labels'; the scored 'spans' field is derived from them here
|
|
393
|
+
golden_spans = spans_from(row["labels"])
|
|
394
|
+
row["spans"] = golden_spans
|
|
395
|
+
row["TP: spans"] = ...
|
|
396
|
+
row["FP: spans"] = ...
|
|
397
|
+
row["FN: spans"] = ...
|
|
398
|
+
|
|
399
|
+
results_df, metrics_df = validate(
|
|
400
|
+
source_df=df, # has a 'labels' column, but no 'spans' column
|
|
401
|
+
fields=["spans"],
|
|
402
|
+
structure_callback=my_callback,
|
|
403
|
+
comparison_callback=comparison_callback,
|
|
404
|
+
derived_fields=("spans",), # 'spans' is created during scoring, not read from input
|
|
405
|
+
)
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
Default `()` means no derived fields — every scored field must be an input column, as before.
|
|
409
|
+
Each rule fails fast with a clear message:
|
|
410
|
+
|
|
411
|
+
| Situation | Result |
|
|
412
|
+
|-----------|--------|
|
|
413
|
+
| Derived field absent from `source_df` | ✅ accepted — the callback creates it |
|
|
414
|
+
| Derived field **present** in `source_df` anyway (e.g. a legacy column of `[]` placeholders) | ✅ accepted, no warning — behaves exactly as before |
|
|
415
|
+
| A scored field that is neither in `source_df` nor declared derived | ❌ `ValueError` — the original missing-column error, unchanged |
|
|
416
|
+
| A name in `derived_fields` that is not in `fields` | ❌ `ValueError` — it exempts nothing; usually a typo |
|
|
417
|
+
| Non-empty `derived_fields` with `comparison_callback=None` | ❌ `ValueError` — nothing would create the column |
|
|
418
|
+
| A bare string (`derived_fields="spans"`) | ❌ `TypeError` — rather than iterating its characters |
|
|
419
|
+
| Declared derived field still missing after scoring | ❌ `ValueError` naming it — rather than a bare `KeyError` from inside the metrics step |
|
|
420
|
+
|
|
380
421
|
### Parallel Processing
|
|
381
422
|
```python
|
|
382
423
|
validate(
|
|
@@ -439,7 +480,10 @@ llm-validation-framework/
|
|
|
439
480
|
|-------|----------|
|
|
440
481
|
| **"Cannot infer fields"** | Ensure DataFrame has both `{Field}` and `Res: {Field}` columns when `structure_callback=None` |
|
|
441
482
|
| **"Missing fields"** | Verify `fields` parameter contains column names that exist in your DataFrame |
|
|
483
|
+
| **"have no result column to score"** / **"were not scored"** | Make `structure_callback` return a key named exactly as each field in `fields` (or score the field in a `comparison_callback`), or remove the field from `fields` |
|
|
484
|
+
| **"source_df has no rows"** | Pass a DataFrame with at least one case; the message names the fields that have no rows to score |
|
|
442
485
|
| **"Duplicate index"** | Use `df.reset_index(drop=True)` or ensure your DataFrame index has unique values |
|
|
486
|
+
| **"Please remove duplicate column names"** | Rename or drop the columns named in the message so every column name is unique |
|
|
443
487
|
| **Import/dependency errors** | Run `pip install -r requirements.txt` and verify Python 3.11+ |
|
|
444
488
|
| **Slow performance** | Enable parallel processing with `max_workers=None` and `use_threads=True` for LLM API calls |
|
|
445
489
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|