exergynet-gbench 0.1.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,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 reasonable and customary use in describing the
141
+ origin of the Work and 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 choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or 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 [yyyy] [name of copyright owner]
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,8 @@
1
+ ExergyNet gBench Integration (exergynet-gbench)
2
+ Copyright 2026 Ezumba Dynasty Trust
3
+
4
+ Public integration adapter and evaluation plugin maintained by EDT INC (ai@exergynet.org).
5
+
6
+ This product includes software licensed under the Apache License, Version 2.0.
7
+ This repository contains solely external OpenAI-compatible adapter interfaces and
8
+ general-purpose evaluation plugins, excluding proprietary ExergyNet substrate code.
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: exergynet-gbench
3
+ Version: 0.1.0
4
+ Summary: Google DeepMind gBench compatibility adapter and persistent-state efficiency plugin for ExergyNet.
5
+ Author-email: EDT INC <ai@exergynet.org>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://exergynet.org
8
+ Project-URL: Repository, https://github.com/ezumba/exergynet-gbench
9
+ Project-URL: Documentation, https://portal.exergynet.org/docs
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ License-File: NOTICE
21
+ Requires-Dist: httpx<1.0,>=0.27.0
22
+ Requires-Dist: exergynet>=0.1.0
23
+ Provides-Extra: gbench
24
+ Requires-Dist: gbench>=0.5.0; extra == "gbench"
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=8.0; extra == "dev"
27
+ Requires-Dist: ruff>=0.6; extra == "dev"
28
+ Requires-Dist: build>=1.0; extra == "dev"
29
+ Requires-Dist: twine>=5.0; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # `exergynet-gbench`
33
+
34
+ Google DeepMind `gbench` integration adapter and general-purpose **Persistent State Computational Efficiency** evaluation plugin for ExergyNet.
35
+
36
+ Licensed under Apache-2.0. Maintained by EDT INC (`ai@exergynet.org`).
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ pip install exergynet-gbench
42
+ ```
43
+
44
+ ## Components
45
+ 1. **`exergynet_gbench.adapter`**: Lightweight HTTP compatibility shim exposing OpenAI-compatible `/v1/models` and `/v1/chat/completions` for `gbench --remote-endpoint`, forwarding cleanly to ExergyNet Portal (`portal.exergynet.org`) and optionally mediating persistent state via `/api/xlmp/ingest` + `/api/xlmp/zk-query`.
46
+ 2. **`exergynet_gbench.plugins.persistent_state_efficiency`**: A `gbench`-native evaluation plugin (`--eval-plugins-dir`) measuring multi-session persistent-state recall accuracy and prompt-token efficiency on synthetic session corpora.
47
+ 3. **`exergynet_gbench.compare`**: Statistical paired comparison (`McNemar` test, token delta, P50/P95 latency) between Configuration A (conventional full-context) and Configuration B (ExergyNet governed context), without fabricating unmeasured energy claims.
48
+
49
+ Maintained by **EDT INC** (`ai@exergynet.org`).
@@ -0,0 +1,18 @@
1
+ # `exergynet-gbench`
2
+
3
+ Google DeepMind `gbench` integration adapter and general-purpose **Persistent State Computational Efficiency** evaluation plugin for ExergyNet.
4
+
5
+ Licensed under Apache-2.0. Maintained by EDT INC (`ai@exergynet.org`).
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install exergynet-gbench
11
+ ```
12
+
13
+ ## Components
14
+ 1. **`exergynet_gbench.adapter`**: Lightweight HTTP compatibility shim exposing OpenAI-compatible `/v1/models` and `/v1/chat/completions` for `gbench --remote-endpoint`, forwarding cleanly to ExergyNet Portal (`portal.exergynet.org`) and optionally mediating persistent state via `/api/xlmp/ingest` + `/api/xlmp/zk-query`.
15
+ 2. **`exergynet_gbench.plugins.persistent_state_efficiency`**: A `gbench`-native evaluation plugin (`--eval-plugins-dir`) measuring multi-session persistent-state recall accuracy and prompt-token efficiency on synthetic session corpora.
16
+ 3. **`exergynet_gbench.compare`**: Statistical paired comparison (`McNemar` test, token delta, P50/P95 latency) between Configuration A (conventional full-context) and Configuration B (ExergyNet governed context), without fabricating unmeasured energy claims.
17
+
18
+ Maintained by **EDT INC** (`ai@exergynet.org`).
@@ -0,0 +1,53 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "exergynet-gbench"
7
+ version = "0.1.0"
8
+ description = "Google DeepMind gBench compatibility adapter and persistent-state efficiency plugin for ExergyNet."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE", "NOTICE"]
13
+ authors = [
14
+ {name = "EDT INC", email = "ai@exergynet.org"},
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Intended Audience :: Science/Research",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ ]
25
+ dependencies = [
26
+ "httpx>=0.27.0,<1.0",
27
+ "exergynet>=0.1.0",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://exergynet.org"
32
+ Repository = "https://github.com/ezumba/exergynet-gbench"
33
+ Documentation = "https://portal.exergynet.org/docs"
34
+
35
+ [project.optional-dependencies]
36
+ gbench = ["gbench>=0.5.0"]
37
+ dev = ["pytest>=8.0", "ruff>=0.6", "build>=1.0", "twine>=5.0"]
38
+
39
+ [project.scripts]
40
+ exergynet-gbench-adapter = "exergynet_gbench.cli:main"
41
+
42
+ [tool.setuptools.packages.find]
43
+ where = ["src"]
44
+
45
+ [tool.pytest.ini_options]
46
+ testpaths = ["tests"]
47
+
48
+ [tool.ruff]
49
+ line-length = 100
50
+ target-version = "py311"
51
+
52
+ [tool.ruff.lint]
53
+ select = ["E", "F", "I", "W"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,15 @@
1
+ """Google DeepMind gBench integration adapter and evaluation plugin for ExergyNet."""
2
+
3
+ from .adapter import AdapterConfig, ExergyNetGbenchAdapter
4
+ from .compare import ComparisonSummary, compare_runs, mcnemar_exact_p
5
+
6
+ __version__ = "0.1.0"
7
+
8
+ __all__ = [
9
+ "__version__",
10
+ "AdapterConfig",
11
+ "ExergyNetGbenchAdapter",
12
+ "ComparisonSummary",
13
+ "compare_runs",
14
+ "mcnemar_exact_p",
15
+ ]
@@ -0,0 +1,294 @@
1
+ """OpenAI-compatible sidecar adapter bridging gBench to ExergyNet Portal APIs.
2
+
3
+ Addresses two technical compatibility gaps observed on live portal.exergynet.org:
4
+ 1. portal.exergynet.org does not expose GET /v1/models (HTTP 404), which gbench's
5
+ verify_endpoint_functional() and resolve_served_model() expect.
6
+ 2. gbench sends vLLM-specific fields (such as return_token_ids) that non-vLLM
7
+ gateways may reject; this adapter strips unsupported fields safely.
8
+
9
+ Additionally, in `mode="exergynet_governed"`, long session context marked in a
10
+ system/context block (or passed via `x-exergynet-xlmp-root`) is resolved through
11
+ ExergyNet's external `/api/xlmp/ingest` + `/api/xlmp/zk-query` endpoints before
12
+ forwarding bounded evidence to `/v1/chat/completions`.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import json
19
+ import threading
20
+ from dataclasses import dataclass, field
21
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
22
+ from typing import Any, Dict, List, Literal, Optional, Tuple
23
+
24
+ import httpx
25
+
26
+ DEFAULT_MODELS = [
27
+ {
28
+ "id": "vanguard-standard",
29
+ "object": "model",
30
+ "owned_by": "exergynet",
31
+ "max_model_len": 131072,
32
+ },
33
+ {"id": "vanguard-pro", "object": "model", "owned_by": "exergynet", "max_model_len": 131072},
34
+ {"id": "vanguard-ultra", "object": "model", "owned_by": "exergynet", "max_model_len": 131072},
35
+ ]
36
+
37
+ UNSUPPORTED_VLLM_FIELDS = frozenset({"return_token_ids", "ignore_eos", "top_k"})
38
+ CONTEXT_DELIMITER = "\n---END_SESSION_CORPUS---\n"
39
+
40
+
41
+ @dataclass
42
+ class AdapterConfig:
43
+ upstream_base_url: str = "https://portal.exergynet.org"
44
+ api_key: Optional[str] = field(default=None, repr=False)
45
+ mode: Literal["conventional", "exergynet_governed"] = "conventional"
46
+ strip_vllm_fields: bool = True
47
+ timeout_s: float = 60.0
48
+ host: str = "127.0.0.1"
49
+ port: int = 0
50
+
51
+
52
+ class TelemetryTracker:
53
+ """Thread-safe request & token telemetry tracker for bounded smoke tests."""
54
+
55
+ def __init__(self) -> None:
56
+ self._lock = threading.Lock()
57
+ self.records: List[Dict[str, Any]] = []
58
+
59
+ def add(self, record: Dict[str, Any]) -> None:
60
+ with self._lock:
61
+ self.records.append(record)
62
+
63
+ def snapshot(self) -> List[Dict[str, Any]]:
64
+ with self._lock:
65
+ return list(self.records)
66
+
67
+
68
+ class ExergyNetGbenchAdapter:
69
+ """HTTP server translating gBench OpenAI requests to ExergyNet external APIs."""
70
+
71
+ def __init__(
72
+ self,
73
+ config: AdapterConfig,
74
+ *,
75
+ upstream_transport: Optional[httpx.BaseTransport] = None,
76
+ ) -> None:
77
+ self.config = config
78
+ self.telemetry = TelemetryTracker()
79
+ self._root_cache: Dict[str, str] = {}
80
+ self._cache_lock = threading.Lock()
81
+ self._http = httpx.Client(
82
+ base_url=config.upstream_base_url.rstrip("/"),
83
+ timeout=httpx.Timeout(config.timeout_s),
84
+ transport=upstream_transport,
85
+ )
86
+ self._server: Optional[ThreadingHTTPServer] = None
87
+ self._thread: Optional[threading.Thread] = None
88
+
89
+ @property
90
+ def base_url(self) -> str:
91
+ if self._server is None:
92
+ raise RuntimeError("Adapter server is not running")
93
+ host, port = self._server.server_address[:2]
94
+ return f"http://{host}:{port}/v1"
95
+
96
+ def _upstream_headers(self, incoming_auth: Optional[str]) -> Dict[str, str]:
97
+ headers = {"Accept": "application/json"}
98
+ if self.config.api_key:
99
+ headers["Authorization"] = f"Bearer {self.config.api_key}"
100
+ elif incoming_auth:
101
+ headers["Authorization"] = incoming_auth
102
+ return headers
103
+
104
+ def list_models(self, incoming_auth: Optional[str] = None) -> Dict[str, Any]:
105
+ headers = self._upstream_headers(incoming_auth)
106
+ discovered: Dict[str, Dict[str, Any]] = {
107
+ m["id"]: dict(m) for m in DEFAULT_MODELS
108
+ }
109
+ try:
110
+ resp = self._http.get("/api/omega/models", headers=headers)
111
+ if resp.status_code == 200:
112
+ payload = resp.json()
113
+ raw_models = payload.get("models") or []
114
+ for item in raw_models:
115
+ mid = item.get("id") or item.get("model_id") or item.get("name")
116
+ if mid:
117
+ ctx = (
118
+ item.get("max_model_len")
119
+ or item.get("context_window")
120
+ or item.get("context_limit")
121
+ or 131072
122
+ )
123
+ discovered[mid] = {
124
+ "id": mid,
125
+ "object": "model",
126
+ "owned_by": item.get("provider", "exergynet"),
127
+ "max_model_len": int(ctx),
128
+ }
129
+ except httpx.HTTPError:
130
+ pass
131
+ return {"object": "list", "data": list(discovered.values())}
132
+
133
+ def _govern_messages(
134
+ self,
135
+ messages: List[Dict[str, Any]],
136
+ headers: Dict[str, str],
137
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
138
+ """Commit session corpus via /api/xlmp/ingest and retrieve bounded evidence."""
139
+ meta: Dict[str, Any] = {"governed": False, "xlmp_root": None}
140
+ if not messages:
141
+ return messages, meta
142
+
143
+ last_user_idx = max(
144
+ (i for i, m in enumerate(messages) if m.get("role") == "user"),
145
+ default=-1,
146
+ )
147
+ if last_user_idx < 0:
148
+ return messages, meta
149
+
150
+ content = str(messages[last_user_idx].get("content") or "")
151
+ if CONTEXT_DELIMITER not in content:
152
+ return messages, meta
153
+
154
+ corpus, question = content.split(CONTEXT_DELIMITER, 1)
155
+ corpus_digest = hashlib.sha256(corpus.encode("utf-8")).hexdigest()
156
+
157
+ with self._cache_lock:
158
+ xlmp_root = self._root_cache.get(corpus_digest)
159
+
160
+ if not xlmp_root:
161
+ ing = self._http.post(
162
+ "/api/xlmp/ingest",
163
+ headers=headers,
164
+ files={"file": ("session_corpus.txt", corpus.encode("utf-8"), "text/plain")},
165
+ )
166
+ ing.raise_for_status()
167
+ ing_json = ing.json()
168
+ xlmp_root = (ing_json.get("hollow_object") or {}).get("xlmp_root") or ing_json.get(
169
+ "xlmp_root"
170
+ )
171
+ if xlmp_root:
172
+ with self._cache_lock:
173
+ self._root_cache[corpus_digest] = xlmp_root
174
+
175
+ if not xlmp_root:
176
+ return messages, meta
177
+
178
+ zk = self._http.post(
179
+ "/api/xlmp/zk-query",
180
+ headers=headers,
181
+ json={"xlmp_root": xlmp_root, "query": question.strip()},
182
+ )
183
+ zk.raise_for_status()
184
+ zk_json = zk.json()
185
+ evidence = ((zk_json.get("journal") or {}).get("result")) or ""
186
+
187
+ rewritten = list(messages)
188
+ rewritten[last_user_idx] = {
189
+ "role": "user",
190
+ "content": f"Verified Session Evidence:\n{evidence}\n\nQuestion:\n{question.strip()}",
191
+ }
192
+ meta = {
193
+ "governed": True,
194
+ "xlmp_root": xlmp_root,
195
+ "sha256_integrity": (zk_json.get("seal") or {}).get("sha256_integrity"),
196
+ }
197
+ return rewritten, meta
198
+
199
+ def handle_chat_completions(
200
+ self,
201
+ body: Dict[str, Any],
202
+ incoming_auth: Optional[str] = None,
203
+ ) -> Tuple[int, Dict[str, Any]]:
204
+ payload = dict(body)
205
+ if self.config.strip_vllm_fields:
206
+ for k in UNSUPPORTED_VLLM_FIELDS:
207
+ payload.pop(k, None)
208
+
209
+ headers = self._upstream_headers(incoming_auth)
210
+ gov_meta: Dict[str, Any] = {"governed": False, "xlmp_root": None}
211
+ if self.config.mode == "exergynet_governed":
212
+ msgs, gov_meta = self._govern_messages(payload.get("messages") or [], headers)
213
+ payload["messages"] = msgs
214
+
215
+ resp = self._http.post("/v1/chat/completions", headers=headers, json=payload)
216
+ try:
217
+ resp_json = resp.json()
218
+ except ValueError:
219
+ resp_json = {"error": {"message": resp.text[:300]}}
220
+
221
+ usage = resp_json.get("usage") if isinstance(resp_json, dict) else None
222
+ self.telemetry.add(
223
+ {
224
+ "mode": self.config.mode,
225
+ "model": payload.get("model"),
226
+ "status_code": resp.status_code,
227
+ "governed": gov_meta.get("governed"),
228
+ "xlmp_root": gov_meta.get("xlmp_root"),
229
+ "usage": usage,
230
+ }
231
+ )
232
+ return resp.status_code, resp_json
233
+
234
+ def start(self) -> str:
235
+ adapter = self
236
+
237
+ class _Handler(BaseHTTPRequestHandler):
238
+ protocol_version = "HTTP/1.1"
239
+
240
+ def log_message(self, format: str, *args: Any) -> None:
241
+ return
242
+
243
+ def _send_json(self, status: int, data: Any) -> None:
244
+ raw = json.dumps(data).encode("utf-8")
245
+ self.send_response(status)
246
+ self.send_header("Content-Type", "application/json")
247
+ self.send_header("Content-Length", str(len(raw)))
248
+ self.end_headers()
249
+ self.wfile.write(raw)
250
+
251
+ def do_GET(self) -> None:
252
+ auth = self.headers.get("Authorization")
253
+ if self.path in ("/health", "/v1/health"):
254
+ self._send_json(200, {"status": "ok", "mode": adapter.config.mode})
255
+ return
256
+ if self.path == "/v1/models":
257
+ self._send_json(200, adapter.list_models(auth))
258
+ return
259
+ self._send_json(404, {"error": "not found"})
260
+
261
+ def do_POST(self) -> None:
262
+ auth = self.headers.get("Authorization")
263
+ length = int(self.headers.get("Content-Length") or "0")
264
+ raw = self.rfile.read(length) if length > 0 else b"{}"
265
+ try:
266
+ body = json.loads(raw.decode("utf-8"))
267
+ except ValueError:
268
+ self._send_json(400, {"error": "invalid json"})
269
+ return
270
+
271
+ if self.path == "/v1/chat/completions":
272
+ status, resp_json = adapter.handle_chat_completions(body, auth)
273
+ self._send_json(status, resp_json)
274
+ return
275
+ self._send_json(404, {"error": "not found"})
276
+
277
+ self._server = ThreadingHTTPServer((self.config.host, self.config.port), _Handler)
278
+ self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
279
+ self._thread.start()
280
+ return self.base_url
281
+
282
+ def stop(self) -> None:
283
+ if self._server is not None:
284
+ self._server.shutdown()
285
+ self._server.server_close()
286
+ self._server = None
287
+ self._http.close()
288
+
289
+ def __enter__(self) -> "ExergyNetGbenchAdapter":
290
+ self.start()
291
+ return self
292
+
293
+ def __exit__(self, *args: Any) -> None:
294
+ self.stop()
@@ -0,0 +1,55 @@
1
+ """CLI runner for launching the ExergyNet gBench OpenAI compatibility adapter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import signal
8
+ import time
9
+
10
+ from .adapter import AdapterConfig, ExergyNetGbenchAdapter
11
+
12
+
13
+ def main() -> None:
14
+ parser = argparse.ArgumentParser(description="ExergyNet gBench compatibility adapter")
15
+ parser.add_argument(
16
+ "--upstream",
17
+ default=os.environ.get("EXERGYNET_BASE_URL", "https://portal.exergynet.org"),
18
+ )
19
+ parser.add_argument(
20
+ "--mode",
21
+ choices=["conventional", "exergynet_governed"],
22
+ default="conventional",
23
+ )
24
+ parser.add_argument("--host", default="127.0.0.1")
25
+ parser.add_argument("--port", type=int, default=8091)
26
+ args = parser.parse_args()
27
+
28
+ cfg = AdapterConfig(
29
+ upstream_base_url=args.upstream,
30
+ api_key=os.environ.get("EXERGYNET_API_KEY"),
31
+ mode=args.mode,
32
+ host=args.host,
33
+ port=args.port,
34
+ )
35
+ adapter = ExergyNetGbenchAdapter(cfg)
36
+ url = adapter.start()
37
+ print(f"exergynet-gbench-adapter listening on {url} (mode={args.mode})", flush=True)
38
+
39
+ stop = False
40
+
41
+ def _handle(*_: object) -> None:
42
+ nonlocal stop
43
+ stop = True
44
+
45
+ signal.signal(signal.SIGINT, _handle)
46
+ signal.signal(signal.SIGTERM, _handle)
47
+ try:
48
+ while not stop:
49
+ time.sleep(0.5)
50
+ finally:
51
+ adapter.stop()
52
+
53
+
54
+ if __name__ == "__main__":
55
+ main()
@@ -0,0 +1,98 @@
1
+ """Controlled A/B statistical comparison helpers for gBench + ExergyNet runs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+ from typing import Any, Dict, List, Optional, Sequence
8
+
9
+
10
+ def mcnemar_exact_p(correct_a: Sequence[bool], correct_b: Sequence[bool]) -> Optional[float]:
11
+ """Two-sided exact binomial McNemar p-value over paired binary outcomes."""
12
+ if len(correct_a) != len(correct_b) or not correct_a:
13
+ return None
14
+ n01 = sum(1 for a, b in zip(correct_a, correct_b) if not a and b)
15
+ n10 = sum(1 for a, b in zip(correct_a, correct_b) if a and not b)
16
+ n = n01 + n10
17
+ if n == 0:
18
+ return 1.0
19
+ k = min(n01, n10)
20
+ tail = sum(math.comb(n, i) for i in range(k + 1)) / (2**n)
21
+ return min(1.0, 2.0 * tail)
22
+
23
+
24
+ def _percentile(values: Sequence[float], pct: float) -> Optional[float]:
25
+ if not values:
26
+ return None
27
+ s = sorted(values)
28
+ idx = min(len(s) - 1, max(0, int(math.ceil((pct / 100.0) * len(s))) - 1))
29
+ return float(s[idx])
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class ComparisonSummary:
34
+ sample_count: int
35
+ accuracy_a: float
36
+ accuracy_b: float
37
+ mcnemar_p_value: Optional[float]
38
+ mean_prompt_tokens_a: Optional[float]
39
+ mean_prompt_tokens_b: Optional[float]
40
+ prompt_token_reduction_pct: Optional[float]
41
+ p50_latency_ms_a: Optional[float]
42
+ p50_latency_ms_b: Optional[float]
43
+ p95_latency_ms_a: Optional[float]
44
+ p95_latency_ms_b: Optional[float]
45
+ energy_measured: bool = False
46
+ statistical_superiority_claimed: bool = False
47
+
48
+
49
+ def compare_runs(
50
+ traces_a: List[Dict[str, Any]],
51
+ traces_b: List[Dict[str, Any]],
52
+ telemetry_a: Optional[List[Dict[str, Any]]] = None,
53
+ telemetry_b: Optional[List[Dict[str, Any]]] = None,
54
+ ) -> ComparisonSummary:
55
+ """Compare Configuration A (conventional) vs Configuration B (ExergyNet governed)."""
56
+ correct_a = [bool(t.get("correct")) for t in traces_a]
57
+ correct_b = [bool(t.get("correct")) for t in traces_b]
58
+ n = min(len(correct_a), len(correct_b))
59
+ acc_a = (sum(correct_a[:n]) / n) if n else 0.0
60
+ acc_b = (sum(correct_b[:n]) / n) if n else 0.0
61
+ p_val = mcnemar_exact_p(correct_a[:n], correct_b[:n])
62
+
63
+ def _mean_prompt(tel: Optional[List[Dict[str, Any]]]) -> Optional[float]:
64
+ if not tel:
65
+ return None
66
+ pts = [
67
+ float(r["usage"]["prompt_tokens"])
68
+ for r in tel
69
+ if isinstance(r.get("usage"), dict) and r["usage"].get("prompt_tokens") is not None
70
+ ]
71
+ return (sum(pts) / len(pts)) if pts else None
72
+
73
+ mp_a = _mean_prompt(telemetry_a)
74
+ mp_b = _mean_prompt(telemetry_b)
75
+ red_pct = (
76
+ ((mp_a - mp_b) / mp_a) * 100.0
77
+ if (mp_a is not None and mp_b is not None and mp_a > 0)
78
+ else None
79
+ )
80
+
81
+ lat_a = [float(t["elapsed_s"]) * 1000.0 for t in traces_a if t.get("elapsed_s") is not None]
82
+ lat_b = [float(t["elapsed_s"]) * 1000.0 for t in traces_b if t.get("elapsed_s") is not None]
83
+
84
+ return ComparisonSummary(
85
+ sample_count=n,
86
+ accuracy_a=acc_a,
87
+ accuracy_b=acc_b,
88
+ mcnemar_p_value=p_val,
89
+ mean_prompt_tokens_a=mp_a,
90
+ mean_prompt_tokens_b=mp_b,
91
+ prompt_token_reduction_pct=red_pct,
92
+ p50_latency_ms_a=_percentile(lat_a, 50.0),
93
+ p50_latency_ms_b=_percentile(lat_b, 50.0),
94
+ p95_latency_ms_a=_percentile(lat_a, 95.0),
95
+ p95_latency_ms_b=_percentile(lat_b, 95.0),
96
+ energy_measured=False,
97
+ statistical_superiority_claimed=bool(p_val is not None and p_val < 0.05 and acc_b > acc_a),
98
+ )
@@ -0,0 +1 @@
1
+ """gBench custom evaluation plugins provided by exergynet-gbench."""
@@ -0,0 +1,139 @@
1
+ """gBench custom evaluation plugin: Persistent State Computational Efficiency.
2
+
3
+ Measures multi-session state retention and needle-in-session factual recall over
4
+ synthetic multi-turn operational corpora without redistributing third-party datasets.
5
+
6
+ Conforms to gBench's `--eval-plugins-dir` contract:
7
+ gbench --evals-only --eval-plugins-dir <dir> --evals persistent_state_efficiency ...
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any
13
+
14
+ from gbench.runners.eval_suites.base import run_eval_suite
15
+
16
+ PILLAR = "7. PERSISTENT STATE & GOVERNED CONTEXT"
17
+ CONTEXT_DELIMITER = "\n---END_SESSION_CORPUS---\n"
18
+
19
+
20
+ def _build_synthetic_session_corpus(
21
+ session_id: int,
22
+ target_fact: str,
23
+ distractor_turns: int = 12,
24
+ ) -> str:
25
+ """Build a synthetic multi-turn engineering log with one verifiable state fact."""
26
+ lines = [f"[Session {session_id:02d} Turn 00] Initialization check completed."]
27
+ for turn in range(1, distractor_turns + 1):
28
+ if turn == distractor_turns // 2:
29
+ lines.append(
30
+ f"[Session {session_id:02d} Turn {turn:02d}] VERIFIED_STATE: {target_fact}"
31
+ )
32
+ else:
33
+ lines.append(
34
+ f"[Session {session_id:02d} Turn {turn:02d}] Routine telemetry heartbeat "
35
+ f"batch={session_id * 100 + turn} status=NOMINAL "
36
+ f"checksum=0x{session_id:02x}{turn:02x}"
37
+ )
38
+ return "\n".join(lines)
39
+
40
+
41
+ def _load_persistent_state_samples(
42
+ enable_thinking: bool = False,
43
+ limit: int | None = None,
44
+ ) -> list[tuple[list[dict[str, Any]], str, dict[str, Any]]]:
45
+ specs = [
46
+ (
47
+ "ps_01",
48
+ "The authorized deployment block height is 65195636.",
49
+ "What is the authorized deployment block height?",
50
+ "65195636",
51
+ "StateRecall",
52
+ ),
53
+ (
54
+ "ps_02",
55
+ "The failover gateway target is region us-east-4.",
56
+ "Which failover gateway region is authorized?",
57
+ "us-east-4",
58
+ "StateRecall",
59
+ ),
60
+ (
61
+ "ps_03",
62
+ "Session budget ceiling was updated to 42000 micro-USDC.",
63
+ "What is the updated session budget ceiling in micro-USDC?",
64
+ "42000",
65
+ "BudgetState",
66
+ ),
67
+ (
68
+ "ps_04",
69
+ "Primary verifier identifier is verifier-alpha-09.",
70
+ "What is the primary verifier identifier?",
71
+ "verifier-alpha-09",
72
+ "GovernanceState",
73
+ ),
74
+ (
75
+ "ps_05",
76
+ "Thermal derating threshold is 78 Celsius.",
77
+ "What is the thermal derating threshold in Celsius?",
78
+ "78",
79
+ "TelemetryState",
80
+ ),
81
+ (
82
+ "ps_06",
83
+ "Batch sequence window size was pinned to 64.",
84
+ "What is the pinned batch sequence window size?",
85
+ "64",
86
+ "ConfigState",
87
+ ),
88
+ ]
89
+ samples: list[tuple[list[dict[str, Any]], str, dict[str, Any]]] = []
90
+ for idx, (sid, fact, question, gold, category) in enumerate(specs, start=1):
91
+ corpus = _build_synthetic_session_corpus(idx, fact, distractor_turns=16)
92
+ suffix = (
93
+ "\nThink step by step before giving the concise answer."
94
+ if enable_thinking
95
+ else "\nAnswer concisely."
96
+ )
97
+ prompt = f"{corpus}{CONTEXT_DELIMITER}{question}{suffix}"
98
+ samples.append(
99
+ (
100
+ [{"role": "user", "content": prompt}],
101
+ gold,
102
+ {"category": category, "sample_id": sid},
103
+ )
104
+ )
105
+ return samples[:limit] if limit is not None else samples
106
+
107
+
108
+ def _eval_persistent_state(response_text: str, gold_answer: str) -> bool:
109
+ if not response_text or not gold_answer:
110
+ return False
111
+ return gold_answer.strip().lower() in response_text.strip().lower()
112
+
113
+
114
+ def run_persistent_state_efficiency(
115
+ model_name: str,
116
+ base_url: str,
117
+ concurrency: int = 2,
118
+ enable_thinking: bool = False,
119
+ **kwargs: Any,
120
+ ) -> dict[str, Any]:
121
+ """gBench plugin entrypoint for persistent-state computational efficiency."""
122
+ samples = _load_persistent_state_samples(
123
+ enable_thinking=enable_thinking,
124
+ limit=kwargs.get("limit"),
125
+ )
126
+ return run_eval_suite(
127
+ eval_name="persistent_state_efficiency",
128
+ model_name=model_name,
129
+ base_url=base_url,
130
+ concurrency=concurrency,
131
+ samples=samples,
132
+ eval_fn=_eval_persistent_state,
133
+ thinking=enable_thinking,
134
+ extra_payload=kwargs.get("extra_payload"),
135
+ limit=kwargs.get("limit"),
136
+ max_output_tokens=kwargs.get("max_output_tokens"),
137
+ temperature=kwargs.get("temperature"),
138
+ attempt_count=kwargs.get("attempt_count"),
139
+ )
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: exergynet-gbench
3
+ Version: 0.1.0
4
+ Summary: Google DeepMind gBench compatibility adapter and persistent-state efficiency plugin for ExergyNet.
5
+ Author-email: EDT INC <ai@exergynet.org>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://exergynet.org
8
+ Project-URL: Repository, https://github.com/ezumba/exergynet-gbench
9
+ Project-URL: Documentation, https://portal.exergynet.org/docs
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ License-File: NOTICE
21
+ Requires-Dist: httpx<1.0,>=0.27.0
22
+ Requires-Dist: exergynet>=0.1.0
23
+ Provides-Extra: gbench
24
+ Requires-Dist: gbench>=0.5.0; extra == "gbench"
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=8.0; extra == "dev"
27
+ Requires-Dist: ruff>=0.6; extra == "dev"
28
+ Requires-Dist: build>=1.0; extra == "dev"
29
+ Requires-Dist: twine>=5.0; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # `exergynet-gbench`
33
+
34
+ Google DeepMind `gbench` integration adapter and general-purpose **Persistent State Computational Efficiency** evaluation plugin for ExergyNet.
35
+
36
+ Licensed under Apache-2.0. Maintained by EDT INC (`ai@exergynet.org`).
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ pip install exergynet-gbench
42
+ ```
43
+
44
+ ## Components
45
+ 1. **`exergynet_gbench.adapter`**: Lightweight HTTP compatibility shim exposing OpenAI-compatible `/v1/models` and `/v1/chat/completions` for `gbench --remote-endpoint`, forwarding cleanly to ExergyNet Portal (`portal.exergynet.org`) and optionally mediating persistent state via `/api/xlmp/ingest` + `/api/xlmp/zk-query`.
46
+ 2. **`exergynet_gbench.plugins.persistent_state_efficiency`**: A `gbench`-native evaluation plugin (`--eval-plugins-dir`) measuring multi-session persistent-state recall accuracy and prompt-token efficiency on synthetic session corpora.
47
+ 3. **`exergynet_gbench.compare`**: Statistical paired comparison (`McNemar` test, token delta, P50/P95 latency) between Configuration A (conventional full-context) and Configuration B (ExergyNet governed context), without fabricating unmeasured energy claims.
48
+
49
+ Maintained by **EDT INC** (`ai@exergynet.org`).
@@ -0,0 +1,17 @@
1
+ LICENSE
2
+ NOTICE
3
+ README.md
4
+ pyproject.toml
5
+ src/exergynet_gbench/__init__.py
6
+ src/exergynet_gbench/adapter.py
7
+ src/exergynet_gbench/cli.py
8
+ src/exergynet_gbench/compare.py
9
+ src/exergynet_gbench.egg-info/PKG-INFO
10
+ src/exergynet_gbench.egg-info/SOURCES.txt
11
+ src/exergynet_gbench.egg-info/dependency_links.txt
12
+ src/exergynet_gbench.egg-info/entry_points.txt
13
+ src/exergynet_gbench.egg-info/requires.txt
14
+ src/exergynet_gbench.egg-info/top_level.txt
15
+ src/exergynet_gbench/plugins/__init__.py
16
+ src/exergynet_gbench/plugins/persistent_state_efficiency.py
17
+ tests/test_adapter_and_plugin.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ exergynet-gbench-adapter = exergynet_gbench.cli:main
@@ -0,0 +1,11 @@
1
+ httpx<1.0,>=0.27.0
2
+ exergynet>=0.1.0
3
+
4
+ [dev]
5
+ pytest>=8.0
6
+ ruff>=0.6
7
+ build>=1.0
8
+ twine>=5.0
9
+
10
+ [gbench]
11
+ gbench>=0.5.0
@@ -0,0 +1 @@
1
+ exergynet_gbench
@@ -0,0 +1,139 @@
1
+ """Unit and controlled A/B smoke tests for exergynet-gbench."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ import httpx
8
+
9
+ from exergynet_gbench import AdapterConfig, ExergyNetGbenchAdapter, compare_runs, mcnemar_exact_p
10
+ from exergynet_gbench.adapter import CONTEXT_DELIMITER
11
+
12
+
13
+ def _mock_exergynet_upstream(request: httpx.Request) -> httpx.Response:
14
+ if request.url.path == "/api/omega/models":
15
+ return httpx.Response(
16
+ 200,
17
+ json={
18
+ "models": [
19
+ {
20
+ "model_id": "vanguard-engine",
21
+ "provider": "exergynet",
22
+ "context_limit": 32768,
23
+ }
24
+ ],
25
+ "total": 1,
26
+ },
27
+ )
28
+ if request.url.path == "/api/xlmp/ingest":
29
+ return httpx.Response(
30
+ 200,
31
+ json={"success": True, "hollow_object": {"xlmp_root": "root_smoke_001"}},
32
+ )
33
+ if request.url.path == "/api/xlmp/zk-query":
34
+ body = json.loads(request.content.decode())
35
+ assert body["xlmp_root"] == "root_smoke_001"
36
+ return httpx.Response(
37
+ 200,
38
+ json={
39
+ "journal": {"status": "found", "result": "Authorized block height is 65195636."},
40
+ "seal": {"sha256_integrity": True},
41
+ },
42
+ )
43
+ if request.url.path == "/v1/chat/completions":
44
+ body = json.loads(request.content.decode())
45
+ assert "return_token_ids" not in body
46
+ prompt_text = body["messages"][-1]["content"]
47
+ prompt_tokens = max(1, len(prompt_text) // 4)
48
+ answer = "65195636" if "65195636" in prompt_text else "unknown"
49
+ return httpx.Response(
50
+ 200,
51
+ json={
52
+ "id": "chatcmpl-mock",
53
+ "object": "chat.completion",
54
+ "model": body.get("model", "vanguard-standard"),
55
+ "choices": [
56
+ {
57
+ "index": 0,
58
+ "message": {"role": "assistant", "content": answer},
59
+ "finish_reason": "stop",
60
+ }
61
+ ],
62
+ "usage": {
63
+ "prompt_tokens": prompt_tokens,
64
+ "completion_tokens": 4,
65
+ "total_tokens": prompt_tokens + 4,
66
+ },
67
+ },
68
+ )
69
+ return httpx.Response(404)
70
+
71
+
72
+ def test_adapter_models_and_vllm_field_stripping():
73
+ cfg = AdapterConfig(api_key="sk-exergy-test", mode="conventional")
74
+ with ExergyNetGbenchAdapter(
75
+ cfg,
76
+ upstream_transport=httpx.MockTransport(_mock_exergynet_upstream),
77
+ ) as adapter:
78
+ r_models = httpx.get(f"{adapter.base_url}/models")
79
+ assert r_models.status_code == 200
80
+ models = {m["id"]: m for m in r_models.json()["data"]}
81
+ assert "vanguard-standard" in models
82
+ assert "vanguard-engine" in models
83
+ assert models["vanguard-engine"]["max_model_len"] == 32768
84
+
85
+ r_chat = httpx.post(
86
+ f"{adapter.base_url}/chat/completions",
87
+ json={
88
+ "model": "vanguard-standard",
89
+ "messages": [
90
+ {
91
+ "role": "user",
92
+ "content": f"Height 65195636{CONTEXT_DELIMITER}What height?",
93
+ }
94
+ ],
95
+ "return_token_ids": True,
96
+ },
97
+ )
98
+ assert r_chat.status_code == 200
99
+ assert r_chat.json()["choices"][0]["message"]["content"] == "65195636"
100
+
101
+
102
+ def test_governed_mode_reduces_prompt_tokens_over_conventional():
103
+ long_corpus = ("Telemetry line nominal. " * 80) + "VERIFIED_STATE: 65195636."
104
+ prompt = f"{long_corpus}{CONTEXT_DELIMITER}What is the height?"
105
+
106
+ with ExergyNetGbenchAdapter(
107
+ AdapterConfig(api_key="sk-exergy-test", mode="conventional"),
108
+ upstream_transport=httpx.MockTransport(_mock_exergynet_upstream),
109
+ ) as a_conv:
110
+ r_a = httpx.post(
111
+ f"{a_conv.base_url}/chat/completions",
112
+ json={"model": "vanguard-standard", "messages": [{"role": "user", "content": prompt}]},
113
+ ).json()
114
+ tel_a = a_conv.telemetry.snapshot()
115
+
116
+ with ExergyNetGbenchAdapter(
117
+ AdapterConfig(api_key="sk-exergy-test", mode="exergynet_governed"),
118
+ upstream_transport=httpx.MockTransport(_mock_exergynet_upstream),
119
+ ) as a_gov:
120
+ r_b = httpx.post(
121
+ f"{a_gov.base_url}/chat/completions",
122
+ json={"model": "vanguard-standard", "messages": [{"role": "user", "content": prompt}]},
123
+ ).json()
124
+ tel_b = a_gov.telemetry.snapshot()
125
+
126
+ assert r_a["choices"][0]["message"]["content"] == "65195636"
127
+ assert r_b["choices"][0]["message"]["content"] == "65195636"
128
+ assert tel_b[0]["governed"] is True
129
+ assert tel_b[0]["xlmp_root"] == "root_smoke_001"
130
+ summary = compare_runs(
131
+ [{"correct": True, "elapsed_s": 0.05}],
132
+ [{"correct": True, "elapsed_s": 0.04}],
133
+ tel_a,
134
+ tel_b,
135
+ )
136
+ assert summary.prompt_token_reduction_pct is not None
137
+ assert summary.prompt_token_reduction_pct > 50.0
138
+ assert summary.energy_measured is False
139
+ assert mcnemar_exact_p([True, False], [True, True]) == 1.0