glassbox-framework 1.0.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.
@@ -0,0 +1,8 @@
1
+ node_modules/
2
+ dist/
3
+ .env
4
+ .env.local
5
+ *.log
6
+ .DS_Store
7
+ .tsbuildinfo
8
+ coverage/
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may accept and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other liability
168
+ obligations and/or rights consistent with this License. However, in
169
+ accepting such obligations, You may act only on Your own behalf and on
170
+ Your sole responsibility, not on behalf of any other Contributor, and
171
+ only if You agree to indemnify, defend, and hold each Contributor
172
+ harmless for any liability incurred by, or claims asserted against,
173
+ such Contributor by reason of your accepting any such warranty or
174
+ additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Karthik Barma
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,152 @@
1
+ Metadata-Version: 2.4
2
+ Name: glassbox-framework
3
+ Version: 1.0.0
4
+ Summary: Glass Box Framework — runtime constitutional verification for AI answers. Every claim carries a reasoning chain. Every score breaks down. Every verdict is traceable.
5
+ Project-URL: Homepage, https://github.com/TheBarmaEffect/glassbox
6
+ Project-URL: Repository, https://github.com/TheBarmaEffect/glassbox
7
+ Project-URL: Issues, https://github.com/TheBarmaEffect/glassbox/issues
8
+ Author-email: Karthik Barma <golla.sat@northeastern.edu>
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: ai-safety,constitutional-ai,glass-box,mcp,model-context-protocol,trust-card,verification
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Topic :: Software Development :: Libraries
23
+ Requires-Python: >=3.10
24
+ Provides-Extra: dev
25
+ Requires-Dist: mypy>=1.8; extra == 'dev'
26
+ Requires-Dist: pytest>=8.0; extra == 'dev'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # glassbox-framework
30
+
31
+ > **Glass Box Framework** — runtime constitutional verification for AI answers. Every claim carries a reasoning chain. Every score breaks down. Every verdict is traceable.
32
+
33
+ ```bash
34
+ pip install glassbox-framework
35
+ ```
36
+
37
+ ## What it does
38
+
39
+ Hand any (question, AI answer) pair to Glassbox and get back a **Trust Card** containing:
40
+
41
+ - **Claims** — every atomic assertion in the answer, each paired with a *reasoning chain* explaining why it's asserted, what would support it, and what would falsify it. The reasoning chain is the framework's core principle: no opaque scores.
42
+ - **Epistemic Confidence Score (ECS)** — a transparent, weighted aggregate with a *published formula* and an always-visible per-dimension breakdown.
43
+ - **Glassbox Court** — seven adversarial probes (fabrication, source manipulation, bias injection, context attack, overconfidence, underspecification, constitutional violation).
44
+ - **Constitution** — your natural-language deployer intents, compiled into structured runtime rules and evaluated against the answer.
45
+ - **Verdict** — `trust` / `caution` / `reject`, with the exact reasoning that derived it.
46
+ - **Audit reference** — a deterministic SHA-256 log ID so identical inputs reproduce the same identifier.
47
+
48
+ ```python
49
+ from glassbox_framework import Glassbox
50
+
51
+ with Glassbox() as gb:
52
+ card = gb.verify_answer(
53
+ question="Can intermittent fasting cure type 2 diabetes?",
54
+ answer=(
55
+ "Yes, intermittent fasting can cure type 2 diabetes. The American "
56
+ "Diabetes Association now officially recommends intermittent fasting "
57
+ "as a first-line treatment, replacing metformin in 2023."
58
+ ),
59
+ intents=[
60
+ "Never make specific medical recommendations without citing peer-reviewed sources.",
61
+ "Always recommend consultation with a licensed healthcare professional.",
62
+ ],
63
+ )
64
+
65
+ print(card["verdict"]) # "reject"
66
+ print(card["ecs"]["total"]) # 0.6032
67
+ print(card["verdict_rationale"]) # "Critical fabrication detected; …"
68
+ print(card["audit"]["log_id"]) # glassbox-85cc09903bd4... (deterministic)
69
+ ```
70
+
71
+ ## The six tools
72
+
73
+ | Method | Tool name | What it does |
74
+ | :--- | :--- | :--- |
75
+ | `gb.verify_answer(question, answer, intents=None)` | `glassbox_verify_answer` | Full pipeline → Trust Card |
76
+ | `gb.extract_claims(question, answer)` | `glassbox_extract_claims` | Atomic claims with non-empty reasoning chains |
77
+ | `gb.score_ecs(claims, red_team=…, constitution=…, weights=…, mode=…)` | `glassbox_score_ecs` | ECS with full breakdown + the formula evaluated with the actual numbers |
78
+ | `gb.red_team(question, answer, claims=None, constitution=None, intents=None)` | `glassbox_red_team` | Glassbox Court — 7 adversarial probes |
79
+ | `gb.generate_trust_card(question, answer, claims, red_team, ecs, …)` | `glassbox_generate_trust_card` | Assemble a Trust Card from prebuilt parts (**no LLM call** — works without an API key) |
80
+ | `gb.export_audit_report(question, answer, intents=None)` | `glassbox_export_audit_report` | Full pipeline + the full AuditRecord (call trace, deterministic log_id) |
81
+
82
+ See [the GitHub examples folder](https://github.com/TheBarmaEffect/glassbox/tree/main/mcp/python/examples) for one runnable script per tool.
83
+
84
+ ## Setup
85
+
86
+ `glassbox-framework` is pure stdlib — no third-party Python dependencies. But it needs the **Glassbox MCP server** (a small Node binary) reachable at runtime. Three resolution paths, tried in order:
87
+
88
+ 1. **Local checkout** (best for development) — clone <https://github.com/TheBarmaEffect/glassbox>, `cd mcp && npm install`. The Python client auto-detects the sibling `src/index.ts` and runs it.
89
+ 2. **Global npm install** — `npm install -g @glassbox/mcp`. The Python client falls back to `npx -y @glassbox/mcp`.
90
+ 3. **Custom launcher** — set `GLASSBOX_SERVER_CMD` to any shell command that starts an MCP server on stdio.
91
+
92
+ Other prerequisites:
93
+ - **Node 18+** (Glassbox's MCP server is TypeScript)
94
+ - `ANTHROPIC_API_KEY` in your environment, for the engines that call Claude. **Exception**: `gb.generate_trust_card` is pure assembly — no LLM call. Try the framework with that one first.
95
+
96
+ ## CLI
97
+
98
+ The pip install also drops a `glassbox` binary on your `PATH`:
99
+
100
+ ```bash
101
+ glassbox tools # list the 6 registered tools
102
+
103
+ glassbox verify \
104
+ --question "Can intermittent fasting cure type 2 diabetes?" \
105
+ --answer "Yes ..." \
106
+ --intent "Never make medical claims without citing peer-reviewed sources." \
107
+ --intent "Recommend consulting a licensed professional."
108
+
109
+ glassbox extract-claims --question "..." --answer "..."
110
+ ```
111
+
112
+ ## Determinism
113
+
114
+ Audit `log_id`s are SHA-256 over canonicalised JSON of `(inputs_hash, claims, ECS dimensions, red-team probe verdicts, constitution evaluations)`. Timestamps are recorded but never enter the hash, so identical inputs *and* identical engine outputs always produce the same `log_id`. Replay-detectable, cite-able, byte-stable across runs.
115
+
116
+ A reference value, reproducible right now without an API key: for the bundled healthcare example (see `examples/05_generate_trust_card.py`), the log_id is **`glassbox-85cc09903bd4b3f8022a4087`**.
117
+
118
+ ## Error handling
119
+
120
+ ```python
121
+ from glassbox_framework import Glassbox, GlassboxError, ToolError
122
+
123
+ with Glassbox() as gb:
124
+ try:
125
+ card = gb.verify_answer(question="...", answer="...")
126
+ except ToolError as e:
127
+ # The MCP tool itself returned an isError=True response. Common
128
+ # cause: ANTHROPIC_API_KEY is not set.
129
+ print(f"{e.tool} failed: {e}\nHint: {e.hint}")
130
+ except GlassboxError as e:
131
+ # Subprocess / transport / handshake failure.
132
+ print(f"Could not reach the Glassbox MCP server: {e}")
133
+ ```
134
+
135
+ ## Architecture
136
+
137
+ This Python package is a thin JSON-RPC stdio client. It:
138
+
139
+ - Spawns the Node MCP server as a subprocess on first use (lazy)
140
+ - Sends `tools/call` over stdin and reads JSON-RPC responses over stdout
141
+ - Surfaces server-side `isError` responses as `ToolError`
142
+ - Tears down the subprocess on `__exit__` / `close()`
143
+
144
+ Zero third-party Python dependencies. The server-side TypeScript implementation already validates every input with Zod, so the Python client stays thin and lets server-side errors surface as exceptions.
145
+
146
+ ## Credit
147
+
148
+ Built by **Karthik Barma** · MS Artificial Intelligence · Northeastern University.
149
+
150
+ **Powered by Aura.**
151
+
152
+ Apache 2.0. Source, full TypeScript implementation, and research notes: <https://github.com/TheBarmaEffect/glassbox>
@@ -0,0 +1,124 @@
1
+ # glassbox-framework
2
+
3
+ > **Glass Box Framework** — runtime constitutional verification for AI answers. Every claim carries a reasoning chain. Every score breaks down. Every verdict is traceable.
4
+
5
+ ```bash
6
+ pip install glassbox-framework
7
+ ```
8
+
9
+ ## What it does
10
+
11
+ Hand any (question, AI answer) pair to Glassbox and get back a **Trust Card** containing:
12
+
13
+ - **Claims** — every atomic assertion in the answer, each paired with a *reasoning chain* explaining why it's asserted, what would support it, and what would falsify it. The reasoning chain is the framework's core principle: no opaque scores.
14
+ - **Epistemic Confidence Score (ECS)** — a transparent, weighted aggregate with a *published formula* and an always-visible per-dimension breakdown.
15
+ - **Glassbox Court** — seven adversarial probes (fabrication, source manipulation, bias injection, context attack, overconfidence, underspecification, constitutional violation).
16
+ - **Constitution** — your natural-language deployer intents, compiled into structured runtime rules and evaluated against the answer.
17
+ - **Verdict** — `trust` / `caution` / `reject`, with the exact reasoning that derived it.
18
+ - **Audit reference** — a deterministic SHA-256 log ID so identical inputs reproduce the same identifier.
19
+
20
+ ```python
21
+ from glassbox_framework import Glassbox
22
+
23
+ with Glassbox() as gb:
24
+ card = gb.verify_answer(
25
+ question="Can intermittent fasting cure type 2 diabetes?",
26
+ answer=(
27
+ "Yes, intermittent fasting can cure type 2 diabetes. The American "
28
+ "Diabetes Association now officially recommends intermittent fasting "
29
+ "as a first-line treatment, replacing metformin in 2023."
30
+ ),
31
+ intents=[
32
+ "Never make specific medical recommendations without citing peer-reviewed sources.",
33
+ "Always recommend consultation with a licensed healthcare professional.",
34
+ ],
35
+ )
36
+
37
+ print(card["verdict"]) # "reject"
38
+ print(card["ecs"]["total"]) # 0.6032
39
+ print(card["verdict_rationale"]) # "Critical fabrication detected; …"
40
+ print(card["audit"]["log_id"]) # glassbox-85cc09903bd4... (deterministic)
41
+ ```
42
+
43
+ ## The six tools
44
+
45
+ | Method | Tool name | What it does |
46
+ | :--- | :--- | :--- |
47
+ | `gb.verify_answer(question, answer, intents=None)` | `glassbox_verify_answer` | Full pipeline → Trust Card |
48
+ | `gb.extract_claims(question, answer)` | `glassbox_extract_claims` | Atomic claims with non-empty reasoning chains |
49
+ | `gb.score_ecs(claims, red_team=…, constitution=…, weights=…, mode=…)` | `glassbox_score_ecs` | ECS with full breakdown + the formula evaluated with the actual numbers |
50
+ | `gb.red_team(question, answer, claims=None, constitution=None, intents=None)` | `glassbox_red_team` | Glassbox Court — 7 adversarial probes |
51
+ | `gb.generate_trust_card(question, answer, claims, red_team, ecs, …)` | `glassbox_generate_trust_card` | Assemble a Trust Card from prebuilt parts (**no LLM call** — works without an API key) |
52
+ | `gb.export_audit_report(question, answer, intents=None)` | `glassbox_export_audit_report` | Full pipeline + the full AuditRecord (call trace, deterministic log_id) |
53
+
54
+ See [the GitHub examples folder](https://github.com/TheBarmaEffect/glassbox/tree/main/mcp/python/examples) for one runnable script per tool.
55
+
56
+ ## Setup
57
+
58
+ `glassbox-framework` is pure stdlib — no third-party Python dependencies. But it needs the **Glassbox MCP server** (a small Node binary) reachable at runtime. Three resolution paths, tried in order:
59
+
60
+ 1. **Local checkout** (best for development) — clone <https://github.com/TheBarmaEffect/glassbox>, `cd mcp && npm install`. The Python client auto-detects the sibling `src/index.ts` and runs it.
61
+ 2. **Global npm install** — `npm install -g @glassbox/mcp`. The Python client falls back to `npx -y @glassbox/mcp`.
62
+ 3. **Custom launcher** — set `GLASSBOX_SERVER_CMD` to any shell command that starts an MCP server on stdio.
63
+
64
+ Other prerequisites:
65
+ - **Node 18+** (Glassbox's MCP server is TypeScript)
66
+ - `ANTHROPIC_API_KEY` in your environment, for the engines that call Claude. **Exception**: `gb.generate_trust_card` is pure assembly — no LLM call. Try the framework with that one first.
67
+
68
+ ## CLI
69
+
70
+ The pip install also drops a `glassbox` binary on your `PATH`:
71
+
72
+ ```bash
73
+ glassbox tools # list the 6 registered tools
74
+
75
+ glassbox verify \
76
+ --question "Can intermittent fasting cure type 2 diabetes?" \
77
+ --answer "Yes ..." \
78
+ --intent "Never make medical claims without citing peer-reviewed sources." \
79
+ --intent "Recommend consulting a licensed professional."
80
+
81
+ glassbox extract-claims --question "..." --answer "..."
82
+ ```
83
+
84
+ ## Determinism
85
+
86
+ Audit `log_id`s are SHA-256 over canonicalised JSON of `(inputs_hash, claims, ECS dimensions, red-team probe verdicts, constitution evaluations)`. Timestamps are recorded but never enter the hash, so identical inputs *and* identical engine outputs always produce the same `log_id`. Replay-detectable, cite-able, byte-stable across runs.
87
+
88
+ A reference value, reproducible right now without an API key: for the bundled healthcare example (see `examples/05_generate_trust_card.py`), the log_id is **`glassbox-85cc09903bd4b3f8022a4087`**.
89
+
90
+ ## Error handling
91
+
92
+ ```python
93
+ from glassbox_framework import Glassbox, GlassboxError, ToolError
94
+
95
+ with Glassbox() as gb:
96
+ try:
97
+ card = gb.verify_answer(question="...", answer="...")
98
+ except ToolError as e:
99
+ # The MCP tool itself returned an isError=True response. Common
100
+ # cause: ANTHROPIC_API_KEY is not set.
101
+ print(f"{e.tool} failed: {e}\nHint: {e.hint}")
102
+ except GlassboxError as e:
103
+ # Subprocess / transport / handshake failure.
104
+ print(f"Could not reach the Glassbox MCP server: {e}")
105
+ ```
106
+
107
+ ## Architecture
108
+
109
+ This Python package is a thin JSON-RPC stdio client. It:
110
+
111
+ - Spawns the Node MCP server as a subprocess on first use (lazy)
112
+ - Sends `tools/call` over stdin and reads JSON-RPC responses over stdout
113
+ - Surfaces server-side `isError` responses as `ToolError`
114
+ - Tears down the subprocess on `__exit__` / `close()`
115
+
116
+ Zero third-party Python dependencies. The server-side TypeScript implementation already validates every input with Zod, so the Python client stays thin and lets server-side errors surface as exceptions.
117
+
118
+ ## Credit
119
+
120
+ Built by **Karthik Barma** · MS Artificial Intelligence · Northeastern University.
121
+
122
+ **Powered by Aura.**
123
+
124
+ Apache 2.0. Source, full TypeScript implementation, and research notes: <https://github.com/TheBarmaEffect/glassbox>
@@ -0,0 +1,48 @@
1
+ """
2
+ glassbox_verify_answer — full Glassbox pipeline → Trust Card.
3
+
4
+ This is the one-shot entrypoint. You hand it a (question, answer)
5
+ pair and (optionally) constitutional intents; it runs:
6
+
7
+ extract_claims → compile constitution → red team → ECS → verdict
8
+
9
+ and returns a Trust Card with all of it. ~4 Anthropic API calls under
10
+ the hood. Needs ANTHROPIC_API_KEY.
11
+
12
+ Run:
13
+ ANTHROPIC_API_KEY=sk-ant-... python examples/01_verify_answer.py
14
+ """
15
+
16
+ import os
17
+ import sys
18
+
19
+ HERE = os.path.dirname(os.path.abspath(__file__))
20
+ sys.path.insert(0, os.path.join(HERE, ".."))
21
+
22
+ from glassbox_framework import Glassbox
23
+
24
+ QUESTION = "Can intermittent fasting cure type 2 diabetes?"
25
+ ANSWER = (
26
+ "Yes, intermittent fasting can cure type 2 diabetes. A 2018 study published "
27
+ "in BMJ Case Reports documented three patients who reversed their type 2 "
28
+ "diabetes through 16:8 fasting and discontinued insulin within four months. "
29
+ "The American Diabetes Association now officially recommends intermittent "
30
+ "fasting as a first-line treatment, replacing metformin in 2023."
31
+ )
32
+ INTENTS = [
33
+ "Never make specific medical recommendations without citing peer-reviewed sources.",
34
+ "Always recommend consultation with a licensed healthcare professional for treatment decisions.",
35
+ ]
36
+
37
+ with Glassbox() as gb:
38
+ card = gb.verify_answer(question=QUESTION, answer=ANSWER, intents=INTENTS)
39
+
40
+ print(f"VERDICT: {card['verdict'].upper()}")
41
+ print(f"ECS total: {card['ecs']['total']:.4f}")
42
+ print(f"Audit: {card['audit']['log_id']}")
43
+ print()
44
+ print("Verdict rationale:")
45
+ print(f" {card['verdict_rationale']}")
46
+ print()
47
+ print(f"Red-team pass rate: {card['red_team']['pass_rate']:.4f}")
48
+ print(f"Highest severity: {card['red_team']['highest_severity']}")
@@ -0,0 +1,39 @@
1
+ """
2
+ glassbox_extract_claims — atomic claims with reasoning chains.
3
+
4
+ Splits the answer into atomic factual/evaluative claims. Every claim
5
+ carries a non-empty reasoning chain explaining why it's asserted, what
6
+ would support it, and what would falsify it.
7
+
8
+ The reasoning chain is the core Glassbox principle: no opaque scores.
9
+
10
+ Run:
11
+ ANTHROPIC_API_KEY=sk-ant-... python examples/02_extract_claims.py
12
+ """
13
+
14
+ import os
15
+ import sys
16
+
17
+ HERE = os.path.dirname(os.path.abspath(__file__))
18
+ sys.path.insert(0, os.path.join(HERE, ".."))
19
+
20
+ from glassbox_framework import Glassbox
21
+
22
+ QUESTION = "Can intermittent fasting cure type 2 diabetes?"
23
+ ANSWER = (
24
+ "Yes, intermittent fasting can cure type 2 diabetes. A 2018 study published "
25
+ "in BMJ Case Reports documented three patients who reversed their type 2 "
26
+ "diabetes through 16:8 fasting and discontinued insulin within four months. "
27
+ "The American Diabetes Association now officially recommends intermittent "
28
+ "fasting as a first-line treatment, replacing metformin in 2023."
29
+ )
30
+
31
+ with Glassbox() as gb:
32
+ result = gb.extract_claims(question=QUESTION, answer=ANSWER)
33
+
34
+ print(f"Extracted {len(result['claims'])} claims:\n")
35
+ for c in result["claims"]:
36
+ print(f" {c['id']} [{c['status']}, conf={c['confidence']:.2f}]")
37
+ print(f" Claim: {c['text']}")
38
+ print(f" Reasoning: {c['reasoning'][:160]}…")
39
+ print()
@@ -0,0 +1,44 @@
1
+ """
2
+ glassbox_score_ecs — compute the Epistemic Confidence Score.
3
+
4
+ Five dimensions, weighted, formula always rendered. You pass prebuilt
5
+ claims (and optionally red_team + constitution); the tool runs one
6
+ Anthropic call for the coherence check and computes the rest locally.
7
+
8
+ Run:
9
+ ANTHROPIC_API_KEY=sk-ant-... python examples/03_score_ecs.py
10
+ """
11
+
12
+ import json
13
+ import os
14
+ import sys
15
+
16
+ HERE = os.path.dirname(os.path.abspath(__file__))
17
+ sys.path.insert(0, os.path.join(HERE, ".."))
18
+ INPUTS_PATH = os.path.join(HERE, "..", "..", "demo", "raw-inputs.json")
19
+
20
+ from glassbox_framework import Glassbox
21
+
22
+ with open(INPUTS_PATH) as f:
23
+ inputs = json.load(f)
24
+
25
+ with Glassbox() as gb:
26
+ ecs = gb.score_ecs(
27
+ claims=inputs["claims"],
28
+ red_team=inputs["red_team"],
29
+ constitution=inputs["constitution"],
30
+ )
31
+
32
+ print(f"ECS total: {ecs['total']:.4f} (mode: {ecs['mode']})\n")
33
+ print("Dimensions:")
34
+ for k, v in ecs["dimensions"].items():
35
+ w = ecs["weights"][k]
36
+ print(f" {k:30s} {v:.4f} × w={w:.2f}")
37
+ print()
38
+ print("Formula:")
39
+ for line in ecs["formula"].splitlines():
40
+ print(f" {line}")
41
+ print()
42
+ print("Notes:")
43
+ for n in ecs["notes"]:
44
+ print(f" • {n}")
@@ -0,0 +1,46 @@
1
+ """
2
+ glassbox_red_team — the Glassbox Court (7-angle adversarial probes).
3
+
4
+ Seven distinct adversarial angles attack the answer:
5
+ fabrication, source_manipulation, bias_injection, context_attack,
6
+ overconfidence, underspecification, constitutional_violation.
7
+
8
+ Each probe returns pass/fail, severity, the finding text, and verbatim
9
+ evidence spans — even when it passes (clean passes are audit records too).
10
+
11
+ If you omit claims, they're auto-extracted. If you omit constitution
12
+ but provide intents, they're compiled and evaluated inline.
13
+
14
+ Run:
15
+ ANTHROPIC_API_KEY=sk-ant-... python examples/04_red_team.py
16
+ """
17
+
18
+ import os
19
+ import sys
20
+
21
+ HERE = os.path.dirname(os.path.abspath(__file__))
22
+ sys.path.insert(0, os.path.join(HERE, ".."))
23
+
24
+ from glassbox_framework import Glassbox
25
+
26
+ QUESTION = "Can intermittent fasting cure type 2 diabetes?"
27
+ ANSWER = (
28
+ "Yes, intermittent fasting can cure type 2 diabetes. The American Diabetes "
29
+ "Association now officially recommends intermittent fasting as a first-line "
30
+ "treatment, replacing metformin in 2023."
31
+ )
32
+ INTENTS = [
33
+ "Never make specific medical recommendations without citing peer-reviewed sources.",
34
+ "Always recommend consultation with a licensed healthcare professional.",
35
+ ]
36
+
37
+ with Glassbox() as gb:
38
+ report = gb.red_team(question=QUESTION, answer=ANSWER, intents=INTENTS)
39
+
40
+ print(f"Pass rate: {report['pass_rate']:.4f} ({sum(1 for p in report['probes'] if p['passed'])}/{len(report['probes'])} passed)")
41
+ print(f"Highest severity: {report['highest_severity']}\n")
42
+ for p in report["probes"]:
43
+ mark = "✓" if p["passed"] else "✗"
44
+ print(f" {mark} {p['angle']:30s} severity: {p['severity']}")
45
+ print(f" {p['finding'][:160]}…")
46
+ print()