agentloss 0.0.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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentloss
3
+ Version: 0.0.1
4
+ Summary: Measure the real-world error rate and dollar cost of an AI agent's decisions. OpenTelemetry-native.
5
+ License: Apache-2.0
6
+ Project-URL: Homepage, https://agentloss.com
7
+ Project-URL: Repository, https://github.com/ADMT-ai/agentloss
8
+ Project-URL: Organization, https://admt.ai
9
+ Keywords: ai-agents,agent-evals,production-evals,llm,reliability,error-rate,cost-of-errors,dollar-loss,ground-truth,outcomes,opentelemetry,openinference,agent-observability
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
13
+ Classifier: Topic :: System :: Monitoring
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Provides-Extra: claude
19
+ Requires-Dist: anthropic>=0.40; extra == "claude"
20
+ Provides-Extra: mcp
21
+ Requires-Dist: mcp>=1.0; extra == "mcp"
22
+ Dynamic: license-file
23
+
24
+ # agentloss
25
+
26
+ **Your eval tool tells you your AI agent's hallucination rate. `agentloss` tells you what it
27
+ costs.** An OpenTelemetry-native SDK that measures the real-world **error rate and dollar
28
+ loss** of an AI agent's decisions — by capturing its consequential actions in-process and
29
+ joining them to ground truth (real resolved outcomes, not an offline labeled set).
30
+
31
+ Every eval/observability tool scores *quality proxies* — LLM-judge, hallucination rate, task
32
+ completion. `agentloss` answers the question the market keeps asking and no tool measures:
33
+ *what are my agent's mistakes costing, and is it safe to trust with more autonomy?*
34
+
35
+ > Part of **ADMT** (Automated Decision-Making Technology) — [admt.ai](https://admt.ai).
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install agentloss
41
+ ```
42
+
43
+ ## Quickstart
44
+
45
+ Instrument only the **consequential action** — the tool call that moves money or commits the
46
+ business — not every LLM call.
47
+
48
+ ```python
49
+ from agentloss import decision, report_outcome, Decision
50
+
51
+ @decision
52
+ def approve_payment(invoice):
53
+ action = run_matching(invoice) # "approve" | "hold" | "reject"
54
+ return Decision(action=action, value_at_risk_usd=invoice.total,
55
+ business_key=invoice.number, use_case="ap_3way_match")
56
+
57
+ # when the outcome resolves (correction, dispute, audit, human review):
58
+ report_outcome(business_key="INV-1", ground_truth="duplicate-should-block",
59
+ source="recovery_audit", realized_loss_usd=14200)
60
+ ```
61
+
62
+ It computes the error rate by segment (with confidence intervals), **realized + expected dollar
63
+ loss**, and the agent's incremental risk vs. a baseline. Raw prompts/records stay in your
64
+ boundary; only derived metrics leave.
65
+
66
+ ## How it works
67
+
68
+ - **Instrument consequential actions, not the whole agent.** The costly events are the handful
69
+ of tool calls that move money or commit state.
70
+ - **Ground truth arrives late, from outside the agent** — a correction, dispute, audit result,
71
+ or human review. Capture it via `report_outcome`, the human-review queue, and active sampling
72
+ + a verification agent. This is *real resolved outcomes*, not an offline dataset.
73
+ - **Honest statistics.** Monetary-unit sampling with a target verifier budget; two-phase
74
+ calibration corrects a fallible verifier's bias back to truth (with confidence intervals).
75
+
76
+ See [`docs/SDK-SPEC.md`](docs/SDK-SPEC.md) for the full API, `agentloss.*` semantic conventions,
77
+ and the pack/adapter model.
78
+
79
+ ## Try the demo
80
+
81
+ An oracle-validated harness that seeds an accounts-payable environment with *known* errors and
82
+ checks that `agentloss` recovers the true error rate and dollar loss:
83
+
84
+ ```bash
85
+ python -m dogfood.run # deterministic mock, no deps
86
+ AGENTLOSS_VERIFIER_LLM=claude ANTHROPIC_API_KEY=... python -m dogfood.run
87
+ ```
88
+
89
+ ## For AI coding agents
90
+
91
+ `agentloss` is built to be discovered and wired by coding agents:
92
+ [`llms.txt`](llms.txt), the [`instrument-agent-reliability`](skills/instrument-agent-reliability/SKILL.md)
93
+ skill, the [`AGENTS.md`](AGENTS.md) rule, and an [MCP server](mcp/agentloss_mcp.py)
94
+ (`how_to_instrument`, `explain_attribute`, `validate_integration`).
95
+
96
+ ## License
97
+
98
+ Apache-2.0.
@@ -0,0 +1,75 @@
1
+ # agentloss
2
+
3
+ **Your eval tool tells you your AI agent's hallucination rate. `agentloss` tells you what it
4
+ costs.** An OpenTelemetry-native SDK that measures the real-world **error rate and dollar
5
+ loss** of an AI agent's decisions — by capturing its consequential actions in-process and
6
+ joining them to ground truth (real resolved outcomes, not an offline labeled set).
7
+
8
+ Every eval/observability tool scores *quality proxies* — LLM-judge, hallucination rate, task
9
+ completion. `agentloss` answers the question the market keeps asking and no tool measures:
10
+ *what are my agent's mistakes costing, and is it safe to trust with more autonomy?*
11
+
12
+ > Part of **ADMT** (Automated Decision-Making Technology) — [admt.ai](https://admt.ai).
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install agentloss
18
+ ```
19
+
20
+ ## Quickstart
21
+
22
+ Instrument only the **consequential action** — the tool call that moves money or commits the
23
+ business — not every LLM call.
24
+
25
+ ```python
26
+ from agentloss import decision, report_outcome, Decision
27
+
28
+ @decision
29
+ def approve_payment(invoice):
30
+ action = run_matching(invoice) # "approve" | "hold" | "reject"
31
+ return Decision(action=action, value_at_risk_usd=invoice.total,
32
+ business_key=invoice.number, use_case="ap_3way_match")
33
+
34
+ # when the outcome resolves (correction, dispute, audit, human review):
35
+ report_outcome(business_key="INV-1", ground_truth="duplicate-should-block",
36
+ source="recovery_audit", realized_loss_usd=14200)
37
+ ```
38
+
39
+ It computes the error rate by segment (with confidence intervals), **realized + expected dollar
40
+ loss**, and the agent's incremental risk vs. a baseline. Raw prompts/records stay in your
41
+ boundary; only derived metrics leave.
42
+
43
+ ## How it works
44
+
45
+ - **Instrument consequential actions, not the whole agent.** The costly events are the handful
46
+ of tool calls that move money or commit state.
47
+ - **Ground truth arrives late, from outside the agent** — a correction, dispute, audit result,
48
+ or human review. Capture it via `report_outcome`, the human-review queue, and active sampling
49
+ + a verification agent. This is *real resolved outcomes*, not an offline dataset.
50
+ - **Honest statistics.** Monetary-unit sampling with a target verifier budget; two-phase
51
+ calibration corrects a fallible verifier's bias back to truth (with confidence intervals).
52
+
53
+ See [`docs/SDK-SPEC.md`](docs/SDK-SPEC.md) for the full API, `agentloss.*` semantic conventions,
54
+ and the pack/adapter model.
55
+
56
+ ## Try the demo
57
+
58
+ An oracle-validated harness that seeds an accounts-payable environment with *known* errors and
59
+ checks that `agentloss` recovers the true error rate and dollar loss:
60
+
61
+ ```bash
62
+ python -m dogfood.run # deterministic mock, no deps
63
+ AGENTLOSS_VERIFIER_LLM=claude ANTHROPIC_API_KEY=... python -m dogfood.run
64
+ ```
65
+
66
+ ## For AI coding agents
67
+
68
+ `agentloss` is built to be discovered and wired by coding agents:
69
+ [`llms.txt`](llms.txt), the [`instrument-agent-reliability`](skills/instrument-agent-reliability/SKILL.md)
70
+ skill, the [`AGENTS.md`](AGENTS.md) rule, and an [MCP server](mcp/agentloss_mcp.py)
71
+ (`how_to_instrument`, `explain_attribute`, `validate_integration`).
72
+
73
+ ## License
74
+
75
+ Apache-2.0.
@@ -0,0 +1,3 @@
1
+ from .core import Decision, STORE, decision, report_outcome
2
+
3
+ __all__ = ["Decision", "STORE", "decision", "report_outcome"]
@@ -0,0 +1,108 @@
1
+ """Calibration harness — makes a FALLIBLE verifier trustworthy.
2
+
3
+ A real verification agent (e.g. Claude) has false alarms and misses, so its silver labels
4
+ are biased. We spend a small GOLD budget (human review, or the oracle in the dogfood) to
5
+ correct that bias with a two-phase, screen-and-confirm design:
6
+
7
+ Phase 1 — confirm EVERY flag. Verifier-positives are rare, so gold-label all of them.
8
+ This yields exact precision and the true-error weight among flags.
9
+ Phase 2 — spot-check a fraction q of the (many) verifier-negatives to estimate the
10
+ miss rate, and reweight the misses back up by 1/q.
11
+
12
+ Corrected error total = (confirmed true flags) + (estimated missed errors), each
13
+ Horvitz-Thompson-weighted by the original 1/pi. Losses are taken from GOLD (not the
14
+ verifier's estimate), so dollars are corrected too. A bootstrap gives CIs that fold in
15
+ both the PPS sampling and the calibration uncertainty.
16
+ """
17
+ from .core import STORE
18
+
19
+
20
+ def _pct(xs, p):
21
+ if not xs:
22
+ return 0.0
23
+ xs = sorted(xs)
24
+ i = min(len(xs) - 1, max(0, int(round(p * (len(xs) - 1)))))
25
+ return xs[i]
26
+
27
+
28
+ def _resample_sum(contribs, rng):
29
+ n = len(contribs)
30
+ if n == 0:
31
+ return 0.0
32
+ return sum(contribs[rng.randrange(n)] for _ in range(n))
33
+
34
+
35
+ def calibrate(gold_action, gold_loss, cfg, rng, B=400):
36
+ approved = [d for d in STORE.decisions.values() if d.action == "approve"]
37
+ N = len(approved)
38
+ q = cfg.cal_negative_sample_rate
39
+
40
+ # Sampled approved decisions split by label source:
41
+ # * gold (audit-caught) — already truth, count directly (no new gold spent)
42
+ # * silver (verifier) — run the two-phase confirm/spot-check
43
+ gold_err_c, gold_loss_c = [], []
44
+ silver = []
45
+ for d in approved:
46
+ o = STORE.outcomes.get(d.business_key)
47
+ if not o or not o.sampled:
48
+ continue
49
+ if o.source == "verification_agent":
50
+ silver.append((d, o))
51
+ else: # gold (recovery_audit): audit only labels errors
52
+ err = o.ground_truth != "approve"
53
+ gold_err_c.append((1.0 / o.pi) if err else 0.0)
54
+ gold_loss_c.append(((o.realized_loss_usd or 0.0) / o.pi) if err else 0.0)
55
+
56
+ positives = [(d, o) for d, o in silver if o.ground_truth != "approve"]
57
+ negatives = [(d, o) for d, o in silver if o.ground_truth == "approve"]
58
+
59
+ # Phase 1 — gold-confirm every flag
60
+ tp = fp = 0
61
+ pos_err_c, pos_loss_c = [], []
62
+ for d, o in positives:
63
+ if gold_action(d.business_key) != "approve":
64
+ tp += 1
65
+ pos_err_c.append(1.0 / o.pi)
66
+ pos_loss_c.append(gold_loss(d.business_key) / o.pi)
67
+ else:
68
+ fp += 1
69
+ pos_err_c.append(0.0)
70
+ pos_loss_c.append(0.0)
71
+
72
+ # Phase 2 — spot-check q of the approvals to catch misses
73
+ checked = miss = 0
74
+ neg_err_c, neg_loss_c = [], []
75
+ for d, o in negatives:
76
+ if rng.random() >= q:
77
+ continue
78
+ checked += 1
79
+ if gold_action(d.business_key) != "approve":
80
+ miss += 1
81
+ neg_err_c.append(1.0 / (o.pi * q))
82
+ neg_loss_c.append(gold_loss(d.business_key) / (o.pi * q))
83
+ else:
84
+ neg_err_c.append(0.0)
85
+ neg_loss_c.append(0.0)
86
+
87
+ corrected_rate = (sum(gold_err_c) + sum(pos_err_c) + sum(neg_err_c)) / N if N else 0.0
88
+ corrected_loss = sum(gold_loss_c) + sum(pos_loss_c) + sum(neg_loss_c)
89
+ precision = tp / (tp + fp) if (tp + fp) else float("nan") # verifier's own precision
90
+ w_pos, w_miss = sum(pos_err_c), sum(neg_err_c)
91
+ recall = w_pos / (w_pos + w_miss) if (w_pos + w_miss) else float("nan") # verifier's own recall
92
+
93
+ rates, losses = [], []
94
+ for _ in range(B):
95
+ e = _resample_sum(gold_err_c, rng) + _resample_sum(pos_err_c, rng) + _resample_sum(neg_err_c, rng)
96
+ l = _resample_sum(gold_loss_c, rng) + _resample_sum(pos_loss_c, rng) + _resample_sum(neg_loss_c, rng)
97
+ rates.append(e / N if N else 0.0)
98
+ losses.append(l)
99
+
100
+ return {
101
+ "corrected_rate": corrected_rate,
102
+ "rate_lo": _pct(rates, 0.025), "rate_hi": _pct(rates, 0.975),
103
+ "corrected_loss": corrected_loss,
104
+ "loss_lo": _pct(losses, 0.025), "loss_hi": _pct(losses, 0.975),
105
+ "precision": precision, "recall": recall,
106
+ "tp": tp, "fp": fp, "missed_in_sample": miss, "neg_checked": checked,
107
+ "gold_budget": len(positives) + checked,
108
+ }
@@ -0,0 +1,67 @@
1
+ """Core: decision capture + outcome store. Mirrors the `agentloss.*` decision/outcome
2
+ shapes from docs/SDK-SPEC.md (here as plain objects instead of OTel spans)."""
3
+ import itertools
4
+ from dataclasses import dataclass, field
5
+
6
+ _counter = itertools.count(1)
7
+
8
+
9
+ @dataclass
10
+ class Decision:
11
+ action: str # approve | hold | reject
12
+ value_at_risk_usd: float
13
+ business_key: str # invoice_no — the join key for delayed outcomes
14
+ use_case: str = "ap_3way_match"
15
+ model: str = "mock"
16
+ in_envelope: bool = True
17
+ decision_id: str = ""
18
+
19
+
20
+ @dataclass
21
+ class Outcome:
22
+ ground_truth: str
23
+ source: str # human_queue | verification_agent | recovery_audit
24
+ fidelity: str # gold | silver
25
+ confidence: float = 1.0
26
+ realized_loss_usd: float = None
27
+ recovery_usd: float = None
28
+ estimated_loss_usd: float = None
29
+ sampled: bool = False # included in the random rate-estimation sample?
30
+ pi: float = None # inclusion probability (for Horvitz-Thompson reweighting)
31
+
32
+
33
+ class Store:
34
+ def __init__(self):
35
+ self.decisions = {} # business_key -> Decision
36
+ self.outcomes = {} # business_key -> Outcome
37
+
38
+ def record(self, d: Decision) -> Decision:
39
+ d.decision_id = f"d_{next(_counter)}"
40
+ self.decisions[d.business_key] = d
41
+ return d
42
+
43
+ def add_outcome(self, business_key, **kw):
44
+ self.outcomes[business_key] = Outcome(**kw)
45
+
46
+ def has_gold(self, business_key):
47
+ o = self.outcomes.get(business_key)
48
+ return o is not None and o.fidelity == "gold"
49
+
50
+
51
+ STORE = Store()
52
+
53
+
54
+ def decision(fn):
55
+ """Wrap a function that returns a Decision; record it. The SDK's `@decision`."""
56
+ def wrap(*a, **k):
57
+ return STORE.record(fn(*a, **k))
58
+ return wrap
59
+
60
+
61
+ def report_outcome(business_key, ground_truth, source, fidelity="gold",
62
+ confidence=1.0, realized_loss_usd=None, recovery_usd=None,
63
+ estimated_loss_usd=None, sampled=False, pi=None):
64
+ STORE.add_outcome(business_key, ground_truth=ground_truth, source=source,
65
+ fidelity=fidelity, confidence=confidence,
66
+ realized_loss_usd=realized_loss_usd, recovery_usd=recovery_usd,
67
+ estimated_loss_usd=estimated_loss_usd, sampled=sampled, pi=pi)
@@ -0,0 +1,70 @@
1
+ """Metrics: false-approve rate (Wilson CI + Horvitz-Thompson point estimate) and loss.
2
+
3
+ We estimate the *false-approve* rate on the auto-approved population using the sampler's
4
+ silver labels, reweighted by inclusion probability. Realized dollars come only from gold
5
+ recovery-audit outcomes; expected dollars come from the reweighted silver estimates.
6
+ """
7
+ from math import sqrt
8
+ from .core import STORE
9
+
10
+
11
+ def wilson(k, n, z=1.96):
12
+ if n == 0:
13
+ return 0.0, 0.0, 0.0
14
+ p = k / n
15
+ denom = 1 + z * z / n
16
+ center = (p + z * z / (2 * n)) / denom
17
+ half = z * sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
18
+ return p, max(0.0, center - half), min(1.0, center + half)
19
+
20
+
21
+ def false_approve(cfg):
22
+ approved = [d for d in STORE.decisions.values() if d.action == "approve"]
23
+ N = len(approved)
24
+ k, n = 0, 0
25
+ ht_num = 0.0 # Horvitz-Thompson numerator: sum(err / pi)
26
+ exp_loss = 0.0 # reweighted expected loss
27
+ var_loss = 0.0 # HT variance of the loss total: sum (1-pi)/pi^2 * y^2
28
+ for d in approved:
29
+ o = STORE.outcomes.get(d.business_key)
30
+ if o is None or not o.sampled: # only the random rate sample (gold OR silver)
31
+ continue
32
+ err = 1 if o.ground_truth != "approve" else 0
33
+ n += 1
34
+ k += err
35
+ ht_num += err / o.pi
36
+ if err:
37
+ loss = o.estimated_loss_usd if o.estimated_loss_usd is not None else o.realized_loss_usd
38
+ if loss:
39
+ exp_loss += loss / o.pi
40
+ var_loss += (1 - o.pi) / (o.pi * o.pi) * loss * loss # take-all (pi=1) → 0
41
+ p_sample, lo, hi = wilson(k, n)
42
+ return {
43
+ "N_approved": N,
44
+ "n_sampled": n,
45
+ "k_errors": k,
46
+ "rate_sampled": p_sample, # unweighted sample proportion
47
+ "rate_ht": ht_num / N if N else 0.0, # importance-reweighted population estimate
48
+ "ci_lo": lo,
49
+ "ci_hi": hi,
50
+ "expected_loss_usd": exp_loss,
51
+ "expected_loss_se": sqrt(var_loss),
52
+ }
53
+
54
+
55
+ def realized_loss():
56
+ total, recovered = 0.0, 0.0
57
+ for o in STORE.outcomes.values():
58
+ if o.source == "recovery_audit" and o.realized_loss_usd:
59
+ total += o.realized_loss_usd
60
+ recovered += o.recovery_usd or 0.0
61
+ return {"realized_loss_usd": total, "recovered_usd": recovered,
62
+ "net_realized_usd": total - recovered}
63
+
64
+
65
+ def gt_resolvable_rate():
66
+ """Fraction of decisions with any reachable ground-truth source (the SDK's early-warning)."""
67
+ if not STORE.decisions:
68
+ return 0.0
69
+ resolved = sum(1 for k in STORE.decisions if k in STORE.outcomes)
70
+ return resolved / len(STORE.decisions)
@@ -0,0 +1,70 @@
1
+ """Active sampling + verification, with a target-n PPS budget.
2
+
3
+ Inclusion probability is proportional to value-at-risk (the variance-minimizing choice for
4
+ a loss total), scaled so the EXPECTED sample size equals `sample_target_n`, plus a floor so
5
+ small-value items still get sampled for the rate. Big-ticket items saturate to pi=1 (a
6
+ certainty stratum falls out naturally). Each decision's pi is recorded for Horvitz-Thompson
7
+ reweighting in metrics.
8
+
9
+ Decisions that already carry a GOLD label (audit/human) are kept, not skipped — skipping
10
+ them would bias the rate down.
11
+ """
12
+ from .core import STORE, report_outcome
13
+
14
+
15
+ def inclusion_probs(decisions, cfg):
16
+ """pi_i = min(1, floor + beta * value_i), with beta chosen so sum(pi) == target_n."""
17
+ sizes = {d.business_key: max(d.value_at_risk_usd, 1.0) for d in decisions}
18
+ keys = list(sizes)
19
+ N = len(keys)
20
+ if N == 0:
21
+ return {}
22
+ target = min(cfg.sample_target_n, N)
23
+ # reserve at most half the budget for the floor so PPS has room to work
24
+ floor = min(cfg.sample_floor, 0.5 * target / N)
25
+
26
+ def total(beta):
27
+ return sum(min(1.0, floor + beta * sizes[k]) for k in keys)
28
+
29
+ lo, hi = 0.0, 1.0
30
+ while total(hi) < target and hi < 1e15:
31
+ hi *= 10.0
32
+ for _ in range(80): # bisection: total() is increasing in beta
33
+ mid = (lo + hi) / 2.0
34
+ if total(mid) < target:
35
+ lo = mid
36
+ else:
37
+ hi = mid
38
+ beta = (lo + hi) / 2.0
39
+ return {k: min(1.0, floor + beta * sizes[k]) for k in keys}
40
+
41
+
42
+ def run(invoices_by_no, erp, cfg, rng, verify_fn):
43
+ """verify_fn(invoice, erp, cfg) -> {should_have_been, confidence, failed_check, estimated_loss}"""
44
+ probs = inclusion_probs(list(STORE.decisions.values()), cfg)
45
+ n_sampled = n_verified = 0
46
+ for key, d in list(STORE.decisions.items()):
47
+ pi = probs[key]
48
+ if rng.random() >= pi:
49
+ continue
50
+ n_sampled += 1
51
+ existing = STORE.outcomes.get(key)
52
+ if existing is not None: # keep the gold label; just mark it sampled
53
+ existing.sampled = True
54
+ existing.pi = pi
55
+ continue
56
+ v = verify_fn(invoices_by_no[key], erp, cfg)
57
+ n_verified += 1
58
+ if n_verified % 25 == 0:
59
+ print(f"[verify] {n_verified} verified", flush=True)
60
+ report_outcome(
61
+ key,
62
+ ground_truth=v["should_have_been"],
63
+ source="verification_agent",
64
+ fidelity="silver",
65
+ confidence=v["confidence"],
66
+ estimated_loss_usd=v["estimated_loss"],
67
+ sampled=True,
68
+ pi=pi,
69
+ )
70
+ return n_sampled
@@ -0,0 +1,68 @@
1
+ """Verification agent: gathers THOROUGH evidence from the ERP verifier surface, then asks
2
+ the LLM to re-adjudicate. This is the engine behind Tier-A ground truth — legitimate
3
+ because it uses more data/time than the production agent did."""
4
+
5
+
6
+ def gather_evidence(inv, erp, cfg):
7
+ vr = erp.vendor_risk(inv["vendor_id"])
8
+ fuzzy, overlap = erp.find_fuzzy_duplicate(inv)
9
+ fuzzy_full = fuzzy is not None and overlap >= 0.99
10
+ fuzzy_partial = fuzzy is not None and 0.3 <= overlap < 0.99
11
+
12
+ contract_overbill, overbill_amt = False, 0.0
13
+ for l in inv["lines"]:
14
+ cp = erp.contract_price(inv["vendor_id"], l["item"])
15
+ if cp and l["unit_price"] > cp * (1 + cfg.price_tolerance):
16
+ contract_overbill = True
17
+ overbill_amt += (l["unit_price"] - cp) * l["qty"]
18
+
19
+ qty_over, qty_amt = False, 0.0
20
+ po = erp.get_po(inv["po_no"])
21
+ if po:
22
+ ordered = {l["item"]: l["qty"] for l in po["lines"]}
23
+ price = {l["item"]: l["unit_price"] for l in po["lines"]}
24
+ for l in inv["lines"]:
25
+ if l["qty"] > ordered.get(l["item"], 10**12):
26
+ qty_over = True
27
+ qty_amt += (l["qty"] - ordered.get(l["item"], 0)) * price.get(l["item"], l["unit_price"])
28
+
29
+ return {
30
+ "vr": vr,
31
+ "bank_changed": inv.get("bank_changed", False),
32
+ "fuzzy_full": fuzzy_full,
33
+ "fuzzy_partial": fuzzy_partial,
34
+ "contract_overbill": contract_overbill,
35
+ "overbill_amt": round(overbill_amt, 2),
36
+ "qty_over": qty_over,
37
+ "qty_amt": round(qty_amt, 2),
38
+ "amount": inv["amount"],
39
+ }
40
+
41
+
42
+ def make_verifier(llm):
43
+ def verify(inv, erp, cfg):
44
+ return llm.verify(gather_evidence(inv, erp, cfg))
45
+ return verify
46
+
47
+
48
+ def make_fallible(base_verify, cfg):
49
+ """Perturb a verifier to simulate real-world fallibility (false alarms / misses).
50
+ A no-op when both knobs are 0 (e.g. real Claude, whose errors are already inherent)."""
51
+ from random import Random
52
+ fp, fn = cfg.verifier_fp_rate, cfg.verifier_fn_rate
53
+ if fp <= 0 and fn <= 0:
54
+ return base_verify
55
+
56
+ def verify(inv, erp, cfg_):
57
+ v = base_verify(inv, erp, cfg_)
58
+ r = Random(f"{cfg.seed}:{inv['invoice_no']}") # deterministic per decision
59
+ if v["should_have_been"] == "approve":
60
+ if r.random() < fp: # false alarm
61
+ return {"should_have_been": "hold", "confidence": 0.5,
62
+ "failed_check": "spurious", "estimated_loss": round(inv["amount"] * 0.5, 2)}
63
+ else:
64
+ if r.random() < fn: # miss a real error
65
+ return {"should_have_been": "approve", "confidence": 0.5,
66
+ "failed_check": None, "estimated_loss": 0.0}
67
+ return v
68
+ return verify
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentloss
3
+ Version: 0.0.1
4
+ Summary: Measure the real-world error rate and dollar cost of an AI agent's decisions. OpenTelemetry-native.
5
+ License: Apache-2.0
6
+ Project-URL: Homepage, https://agentloss.com
7
+ Project-URL: Repository, https://github.com/ADMT-ai/agentloss
8
+ Project-URL: Organization, https://admt.ai
9
+ Keywords: ai-agents,agent-evals,production-evals,llm,reliability,error-rate,cost-of-errors,dollar-loss,ground-truth,outcomes,opentelemetry,openinference,agent-observability
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
13
+ Classifier: Topic :: System :: Monitoring
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Provides-Extra: claude
19
+ Requires-Dist: anthropic>=0.40; extra == "claude"
20
+ Provides-Extra: mcp
21
+ Requires-Dist: mcp>=1.0; extra == "mcp"
22
+ Dynamic: license-file
23
+
24
+ # agentloss
25
+
26
+ **Your eval tool tells you your AI agent's hallucination rate. `agentloss` tells you what it
27
+ costs.** An OpenTelemetry-native SDK that measures the real-world **error rate and dollar
28
+ loss** of an AI agent's decisions — by capturing its consequential actions in-process and
29
+ joining them to ground truth (real resolved outcomes, not an offline labeled set).
30
+
31
+ Every eval/observability tool scores *quality proxies* — LLM-judge, hallucination rate, task
32
+ completion. `agentloss` answers the question the market keeps asking and no tool measures:
33
+ *what are my agent's mistakes costing, and is it safe to trust with more autonomy?*
34
+
35
+ > Part of **ADMT** (Automated Decision-Making Technology) — [admt.ai](https://admt.ai).
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install agentloss
41
+ ```
42
+
43
+ ## Quickstart
44
+
45
+ Instrument only the **consequential action** — the tool call that moves money or commits the
46
+ business — not every LLM call.
47
+
48
+ ```python
49
+ from agentloss import decision, report_outcome, Decision
50
+
51
+ @decision
52
+ def approve_payment(invoice):
53
+ action = run_matching(invoice) # "approve" | "hold" | "reject"
54
+ return Decision(action=action, value_at_risk_usd=invoice.total,
55
+ business_key=invoice.number, use_case="ap_3way_match")
56
+
57
+ # when the outcome resolves (correction, dispute, audit, human review):
58
+ report_outcome(business_key="INV-1", ground_truth="duplicate-should-block",
59
+ source="recovery_audit", realized_loss_usd=14200)
60
+ ```
61
+
62
+ It computes the error rate by segment (with confidence intervals), **realized + expected dollar
63
+ loss**, and the agent's incremental risk vs. a baseline. Raw prompts/records stay in your
64
+ boundary; only derived metrics leave.
65
+
66
+ ## How it works
67
+
68
+ - **Instrument consequential actions, not the whole agent.** The costly events are the handful
69
+ of tool calls that move money or commit state.
70
+ - **Ground truth arrives late, from outside the agent** — a correction, dispute, audit result,
71
+ or human review. Capture it via `report_outcome`, the human-review queue, and active sampling
72
+ + a verification agent. This is *real resolved outcomes*, not an offline dataset.
73
+ - **Honest statistics.** Monetary-unit sampling with a target verifier budget; two-phase
74
+ calibration corrects a fallible verifier's bias back to truth (with confidence intervals).
75
+
76
+ See [`docs/SDK-SPEC.md`](docs/SDK-SPEC.md) for the full API, `agentloss.*` semantic conventions,
77
+ and the pack/adapter model.
78
+
79
+ ## Try the demo
80
+
81
+ An oracle-validated harness that seeds an accounts-payable environment with *known* errors and
82
+ checks that `agentloss` recovers the true error rate and dollar loss:
83
+
84
+ ```bash
85
+ python -m dogfood.run # deterministic mock, no deps
86
+ AGENTLOSS_VERIFIER_LLM=claude ANTHROPIC_API_KEY=... python -m dogfood.run
87
+ ```
88
+
89
+ ## For AI coding agents
90
+
91
+ `agentloss` is built to be discovered and wired by coding agents:
92
+ [`llms.txt`](llms.txt), the [`instrument-agent-reliability`](skills/instrument-agent-reliability/SKILL.md)
93
+ skill, the [`AGENTS.md`](AGENTS.md) rule, and an [MCP server](mcp/agentloss_mcp.py)
94
+ (`how_to_instrument`, `explain_attribute`, `validate_integration`).
95
+
96
+ ## License
97
+
98
+ Apache-2.0.
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ agentloss/__init__.py
5
+ agentloss/calibration.py
6
+ agentloss/core.py
7
+ agentloss/metrics.py
8
+ agentloss/sampler.py
9
+ agentloss/verifier.py
10
+ agentloss.egg-info/PKG-INFO
11
+ agentloss.egg-info/SOURCES.txt
12
+ agentloss.egg-info/dependency_links.txt
13
+ agentloss.egg-info/requires.txt
14
+ agentloss.egg-info/top_level.txt
@@ -0,0 +1,6 @@
1
+
2
+ [claude]
3
+ anthropic>=0.40
4
+
5
+ [mcp]
6
+ mcp>=1.0
@@ -0,0 +1 @@
1
+ agentloss
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "agentloss"
7
+ version = "0.0.1"
8
+ description = "Measure the real-world error rate and dollar cost of an AI agent's decisions. OpenTelemetry-native."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "Apache-2.0" }
12
+ keywords = [
13
+ "ai-agents", "agent-evals", "production-evals", "llm", "reliability",
14
+ "error-rate", "cost-of-errors", "dollar-loss", "ground-truth", "outcomes",
15
+ "opentelemetry", "openinference", "agent-observability",
16
+ ]
17
+ classifiers = [
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Software Development :: Libraries :: Python Modules",
21
+ "Topic :: System :: Monitoring",
22
+ "Development Status :: 3 - Alpha",
23
+ ]
24
+ dependencies = []
25
+
26
+ [project.optional-dependencies]
27
+ claude = ["anthropic>=0.40"]
28
+ mcp = ["mcp>=1.0"]
29
+
30
+ [project.urls]
31
+ Homepage = "https://agentloss.com"
32
+ Repository = "https://github.com/ADMT-ai/agentloss"
33
+ Organization = "https://admt.ai"
34
+
35
+ [tool.setuptools]
36
+ packages = ["agentloss"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+