llmvalidate 1.2.0__tar.gz → 1.3.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: llmvalidate
3
- Version: 1.2.0
3
+ Version: 1.3.0
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(
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "llmvalidate"
7
- version = "1.2.0"
7
+ version = "1.3.0"
8
8
  description = "Oncoshot LLM validation framework"
9
9
  readme = "readme.md"
10
10
  requires-python = ">=3.11"
@@ -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(
@@ -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.2.0"
4
+ __version__ = "1.3.0"
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
@@ -844,7 +844,8 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
844
844
  comparison_callback = None,
845
845
  max_workers: int | None = 1,
846
846
  use_threads: bool = True,
847
- hierarchy = {}):
847
+ hierarchy = {},
848
+ derived_fields = ()):
848
849
  """
849
850
  Performs validation by applying a structuring callback to an input dataset and evaluating performance.
850
851
 
@@ -864,6 +865,33 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
864
865
  If None and structure_callback is also None, fields will be automatically inferred
865
866
  from columns that have corresponding "Res: " columns.
866
867
 
868
+ - **derived_fields (collection of str, optional)**:
869
+ Names in ``fields`` that the ``comparison_callback`` **creates** during scoring, so
870
+ they are exempt from the "must already be a column in source_df" check. Default
871
+ ``()`` (no derived fields) keeps the current behavior: every scored field must be an
872
+ input column.
873
+
874
+ This splits a distinction ``fields`` otherwise conflates: a name in ``fields`` is
875
+ both *the column holding the labels* and *the name of the thing being scored*. Those
876
+ usually coincide, but need not — a ``comparison_callback`` can derive what it scores
877
+ from a different column (e.g. score a ``spans`` field computed from a ``labels``
878
+ column) and write the field plus its own ``TP:``/``FP:``/``FN:`` counts onto the row.
879
+ For such a field only the second meaning applies and there is no input column to
880
+ require, which is what ``derived_fields`` declares. The check is kept for every other
881
+ field because it is what catches a misspelled field name.
882
+
883
+ Rules, each failing fast with a clear message:
884
+ - a name in ``derived_fields`` that is not in ``fields`` is a ``ValueError`` — it
885
+ exempts nothing and is usually a typo;
886
+ - a non-empty ``derived_fields`` with ``comparison_callback=None`` is a
887
+ ``ValueError`` — nothing would create the column;
888
+ - a bare string (``derived_fields='spans'``) is a ``TypeError``, rather than a silent
889
+ iteration over its characters;
890
+ - a derived field that *is* present in ``source_df`` anyway is accepted with no error
891
+ and no warning, so datasets carrying placeholder columns keep working unchanged;
892
+ - a derived field still missing after scoring is a ``ValueError`` naming it, instead
893
+ of a bare ``KeyError`` raised later from inside ``get_metrics``.
894
+
867
895
  - **structure_callback (callable, optional)**:
868
896
  A callback function that will be applied to each row to generate structured predictions.
869
897
  If None, assumes that source_df already contains "Res: " columns with results.
@@ -904,6 +932,17 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
904
932
  if source_df.index.has_duplicates:
905
933
  raise ValueError("Please remove duplicate values in index column")
906
934
 
935
+ # derived_fields is a collection of field names, so a bare string is a caller mistake:
936
+ # it would iterate into single characters ('spans' -> 's', 'p', 'a', ...) and silently
937
+ # exempt names nobody declared. Fail fast with a clear message, the same way the
938
+ # hierarchy shape is checked in compare_results_all.
939
+ if isinstance(derived_fields, (str, bytes)):
940
+ raise TypeError(
941
+ "derived_fields must be a collection of field names, not a single string; "
942
+ f"pass ({derived_fields!r},) to declare one derived field"
943
+ )
944
+ derived_fields = tuple(derived_fields)
945
+
907
946
  # Infer fields from columns if both structure_callback and fields are None
908
947
  if structure_callback is None and fields is None:
909
948
  inferred_fields = infer_fields(source_df)
@@ -917,8 +956,29 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
917
956
  if structure_callback is not None and fields is None:
918
957
  raise ValueError("fields parameter is required when structure_callback is provided")
919
958
 
920
- # Validate that all specified fields exist in source_df
921
- missing_fields = [field for field in fields if field not in source_df.columns]
959
+ # A derived field is one of the scored fields, so a name outside 'fields' exempts
960
+ # nothing — that is a caller mistake (typically a typo), not a feature.
961
+ unknown_derived_fields = [field for field in derived_fields if field not in fields]
962
+ if unknown_derived_fields:
963
+ raise ValueError(
964
+ f"The following derived_fields are not in fields: {unknown_derived_fields}. "
965
+ "derived_fields must be a subset of fields (they are scored fields whose column "
966
+ "the comparison_callback creates)"
967
+ )
968
+
969
+ # A derived field exists only because the comparison_callback writes it, so without a
970
+ # callback nothing would ever create the column.
971
+ if derived_fields and comparison_callback is None:
972
+ raise ValueError(
973
+ f"derived_fields {list(derived_fields)} require a comparison_callback to create "
974
+ "them; with comparison_callback=None nothing adds those columns"
975
+ )
976
+
977
+ # Validate that all specified fields exist in source_df. Derived fields are exempt: the
978
+ # comparison_callback creates them during scoring, so there is no input column to find
979
+ # (compare_results_all already tolerates a scored field that is not yet a column).
980
+ missing_fields = [field for field in fields
981
+ if field not in source_df.columns and field not in derived_fields]
922
982
  if missing_fields:
923
983
  raise ValueError(f"The following fields are missing from source_df: {missing_fields}")
924
984
 
@@ -952,6 +1012,17 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
952
1012
  # Analyse the results and calculate the metrics
953
1013
  res_df = compare_results_all(res_df, fields, hierarchy=hierarchy, comparison_callback=comparison_callback, raw_text_column_name=raw_text_column_name)
954
1014
 
1015
+ # Scoring is done, so a declared derived field must exist by now. Report it here:
1016
+ # get_metrics reads field_df[field] unguarded, so an undelivered derived field would
1017
+ # otherwise surface as a bare `KeyError: '<field>'` from deep inside it.
1018
+ undelivered_derived_fields = [field for field in derived_fields if field not in res_df.columns]
1019
+ if undelivered_derived_fields:
1020
+ raise ValueError(
1021
+ f"The following derived_fields are still missing after comparison: "
1022
+ f"{undelivered_derived_fields}. They were exempted from the source_df column "
1023
+ "check because comparison_callback was expected to create them during scoring"
1024
+ )
1025
+
955
1026
  # Save results
956
1027
  if output_folder:
957
1028
  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.2.0
3
+ Version: 1.3.0
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(
File without changes
File without changes