Skip to content

Commit a8f1a78

Browse files
authored
Merge branch 'dev' into feature/vincilb/json-export
2 parents 0faf842 + 2933418 commit a8f1a78

184 files changed

Lines changed: 3181 additions & 681 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.editorconfig

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# This file is for EditorConfig and helps maintain consistent coding styles.
2+
3+
root = true
4+
5+
[*]
6+
indent_style = space
7+
indent_size = 4
8+
charset = utf-8
9+
end_of_line = lf
10+
insert_final_newline = true
11+
trim_trailing_whitespace = true
12+
13+
[*.md]
14+
trim_trailing_whitespace = false
15+
16+
[Makefile]
17+
indent_style = tab
18+
indent_size = 4
19+
end_of_line = lf
20+
trim_trailing_whitespace = true
21+
insert_final_newline = true

.github/workflows/run_pytest.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ jobs:
2222
run: |
2323
python -m pip install --upgrade pip
2424
pip install -e ".[dev]"
25+
pip install -e ".[llm]"
2526
- name: Test with pytest
2627
run: |
2728
coverage run -m pytest -v -s

.gitignore

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@
22
.vscode/settings.json
33
**/__pycache__/
44
**/*.egg-info/
5+
.venv/
56
.coverage
67
.ash/
8+
.temp/
9+
uv.lock
710

811
.kiro/*
912
.kiro/**/*
1013

1114
build/
12-
.temp/
15+
.temp/

.vscode/settings.json.example

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"git.openRepositoryInParentFolders": "always",
3+
"python.analysis.extraPaths": [],
4+
"notebook.formatOnSave.enabled": true,
5+
"notebook.codeActionsOnSave": {
6+
"notebook.source.fixAll": "explicit",
7+
"notebook.source.organizeImports": "explicit"
8+
},
9+
"[python]": {
10+
"editor.formatOnSave": true,
11+
"editor.defaultFormatter": "charliermarsh.ruff",
12+
"editor.codeActionsOnSave": {
13+
"source.fixAll": "explicit",
14+
"source.organizeImports": "explicit"
15+
},
16+
},
17+
"makefile.configureOnOpen": false
18+
}

AGENTS.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# General Guidance for Agentic Coding Assistants
2+
3+
## Documentation
4+
- When writing documentation, always try to say more with less.
5+
- Documentation should be minimal, and only say what needs to be said to communicate how to work with and extend the system.
6+
7+
## MKDocs Documentation Project
8+
- An MKDocs documentation project exists at [docs/](./docs/). More information can be found in the [docs/README.md](./docs/README.md) and [docs/AGENTS.md](./docs/AGENTS.md) files.
9+
10+
## Testing
11+
- Test documentation and guidelines can be found in [tests/README.md](./tests/README.md).
12+
13+
## README.md
14+
- In addition to MKDocs, The project strives to maintain developer documentation distributed in README.md files throughout the codebase. This documentation exists to help human and AI coding assistants when working with the codebase.
15+
- When creating directories or working in a directory that does not have a README.md create a README.md file and document the final state of the code and logic that's in the directory. Do this in language that an AI coding assistant trying to understand the implementation and codebas would understand.
16+
- When working in a directory, always look for a README.md and/or AGENTS.md file for important context about the directory/code contained within.

Makefile

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Simple Makefile for stickler
22

3+
# Define color codes for terminal output
4+
RED := \033[0;31m
5+
GREEN := \033[0;32m
6+
YELLOW := \033[1;33m
7+
NC := \033[0m # No Color
8+
39
install:
410
pip install -e .
511

@@ -12,3 +18,23 @@ test:
1218
clean:
1319
find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
1420
find . -type f -name "*.pyc" -delete
21+
22+
# Run linting checks and automatically fix issues
23+
lint:
24+
ruff check --fix
25+
26+
# CI/CD version of lint that only checks but doesn't modify files
27+
# Used in CI pipelines to verify code quality without making changes
28+
lint-cicd:
29+
@echo "Running code quality checks..."
30+
@if ! ruff check; then \
31+
echo -e "$(RED)ERROR: Ruff linting failed!$(NC)"; \
32+
echo -e "$(YELLOW)Please run 'make ruff-lint' locally to fix these issues.$(NC)"; \
33+
exit 1; \
34+
fi
35+
@if ! ruff format --check; then \
36+
echo -e "$(RED)ERROR: Code formatting check failed!$(NC)"; \
37+
echo -e "$(YELLOW)Please run 'make format' locally to fix these issues.$(NC)"; \
38+
exit 1; \
39+
fi
40+
@echo -e "$(GREEN)All code quality checks passed!$(NC)"

README.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# Stickler: Structured Object Evaluation for GenAI
22

3+
[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/awslabs/stickler)
4+
35
When in the course of human events, it becomes necessary to evaluate structured outputs from generative AI systems, we must acknowledge that traditional evaluation treats all fields equally. But **not all fields are created equal**.
46

57
**Stickler is a Python library that enables complex structured JSON comparison and evaluation** that lets you focus on the fields your customer actually cares about, to answer the question: "Is it doing a good job?"
@@ -117,6 +119,28 @@ result = ground_truth.compare_with(prediction, evaluator_format=True)
117119
print(f"Overall Score: {result['overall']['anls_score']:.3f}")
118120
```
119121

122+
### Confidence Evaluation
123+
124+
Evaluate prediction confidence calibration with AUROC metrics:
125+
126+
```python
127+
# Prediction with confidence scores
128+
prediction = Invoice.from_json({
129+
"invoice_number": {"value": "INV-2024-001", "confidence": 0.95},
130+
"total": {"value": 1247.50, "confidence": 0.8}
131+
})
132+
133+
# Enable confidence metrics
134+
result = ground_truth.compare_with(
135+
prediction,
136+
add_confidence_metrics=True,
137+
document_field_comparisons=True
138+
)
139+
140+
print(f"Overall Score: {result['overall_score']:.3f}")
141+
print(f"Confidence AUROC: {result['auroc_confidence_metric']:.3f}")
142+
```
143+
120144
### Dynamic Model Creation (New!)
121145

122146
Create models from JSON configuration for maximum flexibility:
@@ -654,3 +678,8 @@ print(f"Line Items: {result['field_scores']['line_items']:.3f}") # ~1.0 - match
654678
## Examples
655679

656680
Check out the `examples/` directory for more detailed usage examples and notebooks.
681+
682+
# A note for AI assisted coding agents
683+
- The project uses coding assistant agnostic context files, like README.md and AGENTS.md
684+
- When working in a directory, always look for a README.md and/or AGENTS.md file for important context about the directory/code contained within.
685+
- Read this [AGENTS.md](./AGENTS.md) file for more information

docs/docs/Contributing/code-style.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,23 @@ ruff check --fix .
2626
ruff check src/stickler/comparators/
2727
```
2828

29+
### Automatic Formatting in VS Code
30+
31+
To enable automatic code formatting and linting in VS Code:
32+
33+
1. Copy the example settings file:
34+
```bash
35+
cp .vscode/settings.json.example .vscode/settings.json
36+
```
37+
38+
2. Install the Ruff extension for VS Code (if not already installed):
39+
- Open VS Code
40+
- Go to Extensions (Cmd+Shift+X on macOS, Ctrl+Shift+X on Windows/Linux)
41+
- Search for "Ruff" by Charlie Marsh
42+
- Click Install
43+
44+
The settings file configures VS Code to automatically format Python files on save and organize imports using Ruff.
45+
2946
### CI Integration
3047

3148
Linting runs automatically on every push and pull request via GitHub Actions. While currently non-blocking, you should address linting issues before submitting PRs.
Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
---
2+
title: Confidence Integration
3+
---
4+
5+
# Confidence Integration
6+
7+
Stickler supports confidence scores alongside field values to evaluate how well prediction confidence correlates with actual accuracy.
8+
9+
## AUROC for Confidence Calibration: Theoretical Foundation
10+
11+
### What is Confidence Estimation?
12+
13+
Confidence estimation in machine learning refers to a model's ability to assess the reliability of its own predictions. Rather than simply outputting a prediction, a well-calibrated model also provides a confidence score indicating how likely that prediction is to be correct. This is crucial for production systems where understanding prediction uncertainty enables better decision-making, error handling, and human-AI collaboration.
14+
15+
In structured data extraction tasks, confidence estimation allows systems to:
16+
- Flag uncertain extractions for human review
17+
- Prioritize high-confidence predictions for automated processing
18+
- Provide transparency about model reliability to end users
19+
- Enable adaptive thresholding based on use case requirements
20+
21+
### Research Foundation and Motivation
22+
23+
The choice of AUROC for confidence evaluation is grounded in research on model calibration and confidence assessment. Other approaches to evaluating confidence, such as Expected Calibration Error (ECE), have significant limitations that motivated our selection of AUROC.
24+
25+
#### Limitations of Expected Calibration Error (ECE)
26+
27+
As noted in recent research (Jiang et al., 2025), Expected Calibration Error has a fundamental flaw:
28+
29+
> "Expected calibration error (ECE) (Guo et al., 2017a; Naeini et al., 2015) is also a standard metric to measure how closely a model's confidence matches its accuracy. However, ECE does not assess a model's ability to discriminate between correct and incorrect answers—a model with accuracy 0.5 can achieve perfect ECE by outputting a confidence of 0.5 for all of its answers. Therefore, we focus our results on the AUC."
30+
31+
This limitation means ECE can be "gamed" by models that output uniform confidence scores, making it unsuitable for evaluating whether confidence scores actually help distinguish between correct and incorrect predictions.
32+
33+
#### Why AUROC for Confidence Evaluation?
34+
35+
AUROC addresses the core question: **"Do higher confidence scores correspond to more accurate predictions?"** This discrimination ability is essential for practical applications where confidence scores guide decision-making.
36+
37+
**Mathematical Definition:**
38+
AUROC measures the probability that a randomly chosen correct prediction has higher confidence than a randomly chosen incorrect prediction. It treats confidence estimation as a binary classification problem where:
39+
- **Positive class**: Correct predictions (field matches ground truth)
40+
- **Negative class**: Incorrect predictions (field doesn't match ground truth)
41+
- **Classifier score**: Model's confidence score
42+
43+
**Advantages over alternatives:**
44+
1. **Discrimination focus**: Directly measures whether confidence correlates with accuracy
45+
2. **Threshold independence**: Evaluates performance across all possible confidence thresholds
46+
3. **Intuitive interpretation**: Values closer to 1.0 indicate better calibration
47+
4. **Robust to class imbalance**: Works well even when correct/incorrect predictions are unbalanced
48+
49+
### AUROC Calculation in Stickler
50+
51+
**AUROC (Area Under ROC Curve)** measures confidence calibration quality:
52+
53+
- **1.0**: Perfect calibration (high confidence = correct, low confidence = incorrect)
54+
- **0.5**: Random calibration (confidence doesn't correlate with accuracy)
55+
- **0.0**: Inverse calibration (high confidence = incorrect, low confidence = correct)
56+
57+
#### Implementation Details
58+
59+
1. For each field with confidence, determine if it matches ground truth
60+
2. Create binary classification: match (1) or no-match (0)
61+
3. Use confidence scores as prediction probabilities
62+
4. Calculate ROC curve and area under it
63+
64+
#### Requirements
65+
66+
- At least one field with confidence scores
67+
- Both matches and non-matches in the comparison
68+
- `document_field_comparisons=True` must be enabled
69+
70+
### Interpretation Guidelines
71+
72+
**Well-Calibrated Models (AUROC ≈ 0.8-1.0):**
73+
- High confidence predictions are predominantly correct
74+
- Low confidence predictions are predominantly incorrect
75+
- Confidence scores provide meaningful signal for decision-making
76+
77+
**Poorly-Calibrated Models (AUROC ≈ 0.0-0.3):**
78+
- High confidence predictions are predominantly incorrect
79+
- May indicate systematic overconfidence or model issues
80+
- Confidence scores mislead rather than inform
81+
82+
**Random Calibration (AUROC ≈ 0.5):**
83+
- Confidence scores don't correlate with accuracy
84+
- Model may need confidence calibration techniques
85+
- Consider post-processing methods like Platt scaling
86+
87+
### Limitations and Considerations
88+
89+
**Edge Cases:**
90+
- **All predictions correct**: AUROC undefined (no negative class)
91+
- **All predictions incorrect**: AUROC undefined (no positive class)
92+
- **Uniform confidence**: AUROC = 0.5 regardless of accuracy
93+
94+
**Sample Size Requirements:**
95+
- Reliable AUROC calculation requires sufficient examples of both correct and incorrect predictions
96+
- Very small datasets may produce unstable AUROC estimates
97+
98+
**Interpretation Context:**
99+
- AUROC should be interpreted alongside overall accuracy
100+
- High AUROC with low accuracy may indicate good uncertainty awareness
101+
- Low AUROC with high accuracy suggests overconfident correct predictions
102+
103+
### References and Further Reading
104+
105+
**Key Papers:**
106+
- Jiang, Z., et al. (2025). "Confidence Estimation in Large Language Models." [arXiv:2502.01126](https://arxiv.org/pdf/2502.01126)
107+
- Guo, C., et al. (2017). "On Calibration of Modern Neural Networks." ICML 2017
108+
- Naeini, M. P., et al. (2015). "Obtaining Well Calibrated Probabilities Using Bayesian Binning." AAAI 2015
109+
110+
**Additional Resources:**
111+
- Scikit-learn ROC AUC documentation: [sklearn.metrics.roc_auc_score](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html)
112+
113+
## JSON Structure
114+
115+
### Standard Format
116+
```json
117+
{
118+
"name": "Widget",
119+
"price": 29.99
120+
}
121+
```
122+
123+
### Confidence Format
124+
```json
125+
{
126+
"name": {"value": "Widget", "confidence": 0.95},
127+
"price": {"value": 29.99, "confidence": 0.8}
128+
}
129+
```
130+
131+
### Mixed Format
132+
```json
133+
{
134+
"name": {"value": "Widget", "confidence": 0.95},
135+
"price": 29.99,
136+
"sku": {"value": "ABC123", "confidence": 0.7}
137+
}
138+
```
139+
140+
## Confidence Structure Rules
141+
142+
A valid confidence structure must have exactly two keys:
143+
- `"value"`: The actual field value
144+
- `"confidence"`: Float between 0.0 and 1.0
145+
146+
## Nested Structures
147+
148+
Confidence works with nested objects and arrays:
149+
150+
```json
151+
{
152+
"customer": {
153+
"name": {"value": "John Doe", "confidence": 0.92},
154+
"address": {
155+
"street": {"value": "123 Main St", "confidence": 0.85},
156+
"city": "New York"
157+
}
158+
},
159+
"items": [
160+
{
161+
"product": {"value": "Laptop", "confidence": 0.89},
162+
"price": {"value": 1299.99, "confidence": 0.76}
163+
}
164+
]
165+
}
166+
```
167+
168+
## Confidence Access API
169+
170+
```python
171+
# Get individual field confidence
172+
confidence = model.get_field_confidence("name") # Returns float or None
173+
174+
# Get all confidences
175+
all_confidences = model.get_all_confidences() # Returns dict
176+
177+
# Nested field access
178+
street_conf = model.get_field_confidence("address.street")
179+
180+
# Array field access
181+
item_conf = model.get_field_confidence("items[0].product")
182+
```
183+
184+
## Field Path Format
185+
186+
Confidence paths use dot notation for nested fields and bracket notation for arrays:
187+
188+
- Simple field: `"name"`
189+
- Nested field: `"address.street"`
190+
- Array element: `"items[0].product"`
191+
- Nested in array: `"orders[1].customer.name"`

docs/docs/Guides/.nav.yml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@ nav:
33
- StructuredModel_Dynamic_Creation.md
44
- StructuredModel_Advanced_Functionality.md
55
- Universal_Aggregate_Field_Feature.md
6-
- ['*']
6+
- ['*']
7+
- Confidence_Evaluation_Guide.md

0 commit comments

Comments
 (0)