truegrain 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,73 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ test:
13
+ name: Python ${{ matrix.python }}
14
+ runs-on: ubuntu-latest
15
+ strategy:
16
+ fail-fast: false
17
+ matrix:
18
+ # The client uses only the standard library, so the range it supports is
19
+ # the range it is tested on rather than whatever the maintainer happens
20
+ # to run.
21
+ python: ["3.10", "3.11", "3.12", "3.13"]
22
+ steps:
23
+ - uses: actions/checkout@v4
24
+
25
+ - uses: actions/setup-python@v5
26
+ with:
27
+ python-version: ${{ matrix.python }}
28
+
29
+ - name: Install
30
+ run: pip install -e ".[dev]"
31
+
32
+ # Includes test_covers_spec.py, which fails when the engine gains an
33
+ # operation this client cannot call.
34
+ - name: Test
35
+ run: pytest -q
36
+
37
+ - name: No tests were skipped
38
+ run: |
39
+ skipped=$(pytest -q -rs 2>&1 | grep -c '^SKIPPED' || true)
40
+ if [ "$skipped" != "0" ]; then
41
+ echo "$skipped test(s) skipped; the contract suite must not be silently absent"
42
+ pytest -q -rs 2>&1 | grep '^SKIPPED'
43
+ exit 1
44
+ fi
45
+
46
+ no-dependencies:
47
+ name: Imports without any third-party package
48
+ runs-on: ubuntu-latest
49
+ steps:
50
+ - uses: actions/checkout@v4
51
+ - uses: actions/setup-python@v5
52
+ with:
53
+ python-version: "3.13"
54
+
55
+ # The point of this client is that installing it into an agent's
56
+ # environment cannot conflict with anything already there. That claim is
57
+ # only true while it imports on a bare interpreter, so it is tested rather
58
+ # than asserted in the README.
59
+ - name: Install with no extras
60
+ run: pip install .
61
+
62
+ - name: Import and use it without pandas or pyyaml
63
+ run: |
64
+ python - <<'PY'
65
+ import truegrain
66
+ from truegrain import Client, Refused, filters, tools
67
+ c = Client("http://127.0.0.1:8080", token="not-used")
68
+ assert filters.eq("orders.status", "shipped")["op"] == "eq"
69
+ assert tools.tool_specs() and tools.TOOL_NAMES
70
+ r = Refused(code="fan_out_would_inflate", reason="x", retry="modify")
71
+ assert r.should_modify() and not r.is_final()
72
+ print("imports and works on a bare interpreter:", truegrain.__version__)
73
+ PY
@@ -0,0 +1,78 @@
1
+ name: Publish
2
+
3
+ # Publishing uses PyPI Trusted Publishing, so there is no API token in this
4
+ # repository and none in an organisation secret. PyPI verifies a short-lived
5
+ # OIDC token minted by GitHub for this workflow in this repository, which means
6
+ # a leaked secret cannot be used to publish because there is no secret.
7
+ #
8
+ # Setting it up, once, on PyPI:
9
+ # Your projects -> truegrain -> Publishing -> Add a trusted publisher
10
+ # Owner: rk-chavali
11
+ # Repository: truegrain-python
12
+ # Workflow: publish.yml
13
+ # Environment: pypi
14
+ #
15
+ # For the very first release, before the project exists, use the same form under
16
+ # "Publishing" on your account and add it as a *pending* publisher.
17
+
18
+ on:
19
+ release:
20
+ types: [published]
21
+ workflow_dispatch:
22
+
23
+ permissions:
24
+ contents: read
25
+
26
+ jobs:
27
+ build:
28
+ runs-on: ubuntu-latest
29
+ steps:
30
+ - uses: actions/checkout@v4
31
+ - uses: actions/setup-python@v5
32
+ with:
33
+ python-version: "3.13"
34
+
35
+ - name: Install build tooling
36
+ run: pip install build
37
+
38
+ # The tests run again here rather than trusting the CI run on the commit.
39
+ # A release is built from a tag, and a tag can point anywhere.
40
+ - name: Test before building
41
+ run: |
42
+ pip install -e ".[dev]"
43
+ pytest -q
44
+
45
+ - name: Check the version matches the tag
46
+ if: github.event_name == 'release'
47
+ run: |
48
+ tag="${GITHUB_REF_NAME#v}"
49
+ declared=$(python -c "import truegrain; print(truegrain.__version__)")
50
+ if [ "$tag" != "$declared" ]; then
51
+ echo "tag $GITHUB_REF_NAME does not match __version__ $declared"
52
+ echo "a package whose version disagrees with its tag cannot be traced back to a commit"
53
+ exit 1
54
+ fi
55
+
56
+ - name: Build
57
+ run: python -m build
58
+
59
+ - uses: actions/upload-artifact@v4
60
+ with:
61
+ name: dist
62
+ path: dist/
63
+
64
+ publish:
65
+ needs: build
66
+ runs-on: ubuntu-latest
67
+ environment: pypi
68
+ permissions:
69
+ # The OIDC token PyPI verifies. This is the whole credential.
70
+ id-token: write
71
+ steps:
72
+ - uses: actions/download-artifact@v4
73
+ with:
74
+ name: dist
75
+ path: dist/
76
+
77
+ - name: Publish to PyPI
78
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,79 @@
1
+ name: Spec drift
2
+
3
+ # The contract lives in the engine repository. This client vendors a copy so it
4
+ # builds offline and so a contract change arrives as a reviewable diff, but a
5
+ # vendored copy is a copy that can quietly go stale.
6
+ #
7
+ # This job is what stops that. It fetches the engine's current spec, and if it
8
+ # differs from the pinned one it opens a pull request carrying the new spec. The
9
+ # client's own contract tests then run against it, so an endpoint this client
10
+ # cannot call shows up as a failing check on that pull request rather than as a
11
+ # support question.
12
+
13
+ on:
14
+ schedule:
15
+ # Daily. A contract does not move often, and a drift noticed within a day is
16
+ # noticed long before anyone depends on the new operation.
17
+ - cron: "17 6 * * *"
18
+ workflow_dispatch:
19
+
20
+ permissions:
21
+ contents: write
22
+ pull-requests: write
23
+
24
+ jobs:
25
+ compare:
26
+ runs-on: ubuntu-latest
27
+ steps:
28
+ - uses: actions/checkout@v4
29
+
30
+ - name: Fetch the engine's current spec
31
+ run: |
32
+ curl -fsSL -o /tmp/upstream.yaml \
33
+ https://raw.githubusercontent.com/rk-chavali/truegrain/main/api/openapi.yaml
34
+ curl -fsSL -o /tmp/upstream.sha \
35
+ https://api.github.com/repos/rk-chavali/truegrain/commits/main
36
+ python -c "import json;print(json.load(open('/tmp/upstream.sha'))['sha'])" > /tmp/sha.txt
37
+
38
+ - name: Compare against the pin
39
+ id: compare
40
+ run: |
41
+ if diff -q spec/openapi.yaml /tmp/upstream.yaml >/dev/null; then
42
+ echo "changed=false" >> "$GITHUB_OUTPUT"
43
+ echo "the vendored spec matches the engine"
44
+ else
45
+ echo "changed=true" >> "$GITHUB_OUTPUT"
46
+ echo "the contract moved:"
47
+ diff -u spec/openapi.yaml /tmp/upstream.yaml | head -60 || true
48
+ fi
49
+
50
+ - name: Update the pin
51
+ if: steps.compare.outputs.changed == 'true'
52
+ run: |
53
+ cp /tmp/upstream.yaml spec/openapi.yaml
54
+ cp /tmp/sha.txt spec/PINNED_AT
55
+
56
+ - name: Open a pull request
57
+ if: steps.compare.outputs.changed == 'true'
58
+ uses: peter-evans/create-pull-request@v7
59
+ with:
60
+ branch: spec-drift
61
+ title: "The engine's API contract moved"
62
+ commit-message: |
63
+ Update the vendored OpenAPI spec
64
+
65
+ The engine's contract changed. The client's own contract tests run
66
+ against this spec, so a failing check here means an operation this
67
+ client cannot call.
68
+ body: |
69
+ The engine's `api/openapi.yaml` no longer matches the copy pinned here.
70
+
71
+ The contract tests in `tests/test_covers_spec.py` run against the
72
+ vendored spec, so:
73
+
74
+ - **checks pass**: the change is additive in a way this client already
75
+ handles, or cosmetic. Merge it.
76
+ - **checks fail**: the engine gained an operation this client cannot
77
+ call, or removed one it still claims. Add or remove the method and
78
+ update `OPERATIONS` in `truegrain/client.py`.
79
+ labels: contract
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .pytest_cache/
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .venv/
8
+ .coverage
@@ -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,224 @@
1
+ Metadata-Version: 2.5
2
+ Name: truegrain
3
+ Version: 0.1.0
4
+ Summary: Python client for truegrain: governed metrics for agents, notebooks and applications.
5
+ Project-URL: Homepage, https://github.com/rk-chavali/truegrain-python
6
+ Project-URL: Documentation, https://github.com/rk-chavali/truegrain-python#readme
7
+ Project-URL: Source, https://github.com/rk-chavali/truegrain-python
8
+ Project-URL: Engine, https://github.com/rk-chavali/truegrain
9
+ Project-URL: Issues, https://github.com/rk-chavali/truegrain-python/issues
10
+ License: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agents,governance,mcp,metrics,ossie,semantic-layer
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Database :: Front-Ends
18
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
19
+ Requires-Python: >=3.10
20
+ Provides-Extra: dev
21
+ Requires-Dist: pandas>=1.5; extra == 'dev'
22
+ Requires-Dist: pytest>=7; extra == 'dev'
23
+ Requires-Dist: pyyaml>=6; extra == 'dev'
24
+ Provides-Extra: pandas
25
+ Requires-Dist: pandas>=1.5; extra == 'pandas'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # truegrain (Python)
29
+
30
+ The Python client for [truegrain](https://github.com/rk-chavali/truegrain):
31
+ governed metrics for agents, notebooks and applications.
32
+
33
+ There is no method that sends SQL, because there is no endpoint that accepts it.
34
+ The only expressible request is a semantic one.
35
+
36
+ ```bash
37
+ pip install truegrain # no dependencies
38
+ pip install truegrain[pandas] # adds to_dataframe()
39
+ ```
40
+
41
+ The client uses only the standard library. That is deliberate: this package goes
42
+ into agent environments where a dependency conflict is a real cost, and thirteen
43
+ endpoints do not justify dragging one in.
44
+
45
+ ## Use it
46
+
47
+ ```python
48
+ import os
49
+ from truegrain import Client, filters
50
+
51
+ client = Client.from_env() # SEMANTIC_URL, SEMANTIC_TOKEN
52
+
53
+ for metric in client.metrics(search="revenue"):
54
+ print(metric.name, "-", metric.description)
55
+
56
+ result = client.query(
57
+ metrics=["sales.order_revenue", "marketing.campaign_spend"],
58
+ dimensions=["sales.orders.order_date"],
59
+ grain="month",
60
+ filters=[filters.in_("sales.orders.status", "shipped", "delivered")],
61
+ order_by=[{"field": "order_date"}],
62
+ )
63
+
64
+ result.to_dataframe()
65
+ ```
66
+
67
+ Those two metrics live in different namespaces and aggregate different facts.
68
+ The engine computes each separately and joins them on the shared month, so both
69
+ numbers are correct rather than one being inflated by the join.
70
+
71
+ Every result carries the SQL that produced it and the exact version of the
72
+ definitions used:
73
+
74
+ ```python
75
+ frame = result.to_dataframe()
76
+ frame.attrs["compiled_sql"]
77
+ frame.attrs["model_version"] # sha256:eebdad0d19bb
78
+ ```
79
+
80
+ That is not a debug feature. It is how a disagreement about a number gets
81
+ settled, which is why it survives into the frame rather than being dropped at
82
+ the client boundary.
83
+
84
+ ## Refusals are answers
85
+
86
+ The engine declines questions it cannot answer correctly, and says what to do
87
+ instead. Catch `Refused` and branch on the retry class rather than on the text.
88
+
89
+ ```python
90
+ from truegrain import Refused
91
+
92
+ try:
93
+ client.query(metrics=["sales.order_revenue"],
94
+ dimensions=["sales.products.category"])
95
+ except Refused as refusal:
96
+ if refusal.should_modify():
97
+ print("try instead:", refusal.hint)
98
+ elif refusal.should_wait():
99
+ ... # the same request may work shortly
100
+ elif refusal.is_final():
101
+ ... # stop; say so rather than substituting another metric
102
+ ```
103
+
104
+ That example refuses because an order contains several products, so revenue per
105
+ category has no answer without an allocation rule. The hint names the metrics
106
+ defined at the grain where the question *is* well defined:
107
+
108
+ ```
109
+ fan_out_would_inflate: metric "order_revenue" aggregates SUM(...) over orders,
110
+ but this query repeats orders rows
111
+ hint: ... Metrics defined at the order_lines grain answer this correctly:
112
+ line_revenue, units_sold.
113
+ retry: modify
114
+ ```
115
+
116
+ The three classes matter most to an agent. Without them it either gives up on a
117
+ typo or loops forever on a denial.
118
+
119
+ | `retry` | Meaning |
120
+ |---|---|
121
+ | `modify` | Answerable, but not as written. Change the arguments. |
122
+ | `later` | Nothing is wrong with the request. Something outside it failed. |
123
+ | `never` | No version of this will succeed for you. Stop. |
124
+
125
+ ## Wiring into an agent framework
126
+
127
+ Most frameworks accept a list of function schemas and call back with a name and
128
+ arguments. `tools` produces that list and dispatches those calls, which covers
129
+ LangChain, CrewAI, the OpenAI Agents SDK, Pydantic AI and anything hand-rolled
130
+ without this library growing an adapter per framework.
131
+
132
+ ```python
133
+ from truegrain import Client, tools
134
+
135
+ client = Client.from_env()
136
+ specs = tools.tool_specs() # hand these to the framework
137
+
138
+ # when the model calls back:
139
+ result = tools.dispatch(client, name, arguments)
140
+ ```
141
+
142
+ `dispatch` returns refusals rather than raising them, because a framework
143
+ feeding the result back to a model wants the text and the retry class, not a
144
+ traceback.
145
+
146
+ If your client speaks the Model Context Protocol, skip this and point it at the
147
+ engine's MCP server instead. Same four tools, same guarantees, no code.
148
+
149
+ ```bash
150
+ claude mcp add truegrain -- /path/to/truegrain serve mcp
151
+ ```
152
+
153
+ ## Dry runs
154
+
155
+ `compile` returns the SQL a request would produce without running it, which is
156
+ useful before committing an agent to an expensive query.
157
+
158
+ ```python
159
+ compiled = client.compile(metrics=["sales.order_revenue"],
160
+ dimensions=["sales.customers.region"])
161
+ print(compiled.compiled_sql)
162
+ print(compiled.parts) # >1 means facts were aggregated separately and joined
163
+ ```
164
+
165
+ A dry run is still governed. A request you may not run returns a refusal and no
166
+ SQL, and the inspection is recorded in the audit log as `compiled` rather than
167
+ `allowed`. It shows you what a query would do; it is not a way around the gate.
168
+
169
+ ## Know what you are trusting
170
+
171
+ ```python
172
+ health = client.health()
173
+ health.governs_columns # is column-level access control configured at all
174
+ health.enforcement_notes # plain-language list of what this deployment does NOT enforce
175
+ ```
176
+
177
+ A deployment that enforces nothing says so here. Overstating a governance
178
+ guarantee is worse than not offering one.
179
+
180
+ ## Errors
181
+
182
+ | Exception | When |
183
+ |---|---|
184
+ | `Refused` | The engine understood and declined. Carries `code`, `reason`, `hint`, `retry`. |
185
+ | `Unauthorized` | Credentials missing or not recognised. |
186
+ | `TransportError` | The engine could not be reached, or answered with something unparseable. Never a statement about the request. |
187
+ | `SemanticError` | Base class for all of the above. |
188
+
189
+ ## Development
190
+
191
+ ```bash
192
+ pip install -e ".[dev]"
193
+ pytest
194
+ ```
195
+
196
+ `tests/test_covers_spec.py` checks this client against `api/openapi.yaml`: an
197
+ operation added to the engine with no method here fails the suite. The client is
198
+ hand-written rather than generated because eight endpoints do not justify a
199
+ codegen toolchain, and that test is what pays for the choice.
200
+
201
+ ## Licence
202
+
203
+ Apache 2.0.
204
+
205
+ ## How this stays in step with the engine
206
+
207
+ The engine's OpenAPI contract is vendored at `spec/openapi.yaml`, pinned to an
208
+ engine commit in `spec/PINNED_AT`.
209
+
210
+ `tests/test_covers_spec.py` checks this client against it in both directions: an
211
+ operation the engine exposes with no method here fails the build, and a method
212
+ claiming an operation the spec does not define fails it too. A scheduled job
213
+ compares the pin against the engine daily and opens a pull request when the
214
+ contract moves, so a change arrives as a reviewable diff with the contract tests
215
+ already run against it.
216
+
217
+ The client is hand-written rather than generated. A generator produces a
218
+ transport and a flat error type; the parts worth having are the ones it cannot
219
+ produce: `Refused.should_modify()`, and `run()` submitting a job and polling it
220
+ so no caller writes that loop.
221
+
222
+ ## Licence
223
+
224
+ Apache 2.0, matching the engine.