kaval 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.
kaval-0.1.0/.gitignore ADDED
@@ -0,0 +1,14 @@
1
+ node_modules/
2
+ dist/
3
+ *.tsbuildinfo
4
+ .turbo/
5
+
6
+ # python
7
+ __pycache__/
8
+ *.egg-info/
9
+ .venv/
10
+ .pytest_cache/
11
+ sdks/python/dist/
12
+
13
+ *.tgz
14
+ .DS_Store
kaval-0.1.0/LICENSE ADDED
@@ -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 2026 Lumaa, Inc. (dba Kaval)
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.
kaval-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: kaval
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the kaval currentness API (belief in → typed freshness gap out).
5
+ Project-URL: Homepage, https://github.com/LufeMC/kaval-clients
6
+ Project-URL: Repository, https://github.com/LufeMC/kaval-clients
7
+ Project-URL: Issues, https://github.com/LufeMC/kaval-clients/issues
8
+ Author: Lumaa, Inc. (dba Kaval)
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: agents,ai,freshness,kaval,rag,verification
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Requires-Python: >=3.10
17
+ Requires-Dist: httpx<1,>=0.27
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest<9,>=8; extra == 'dev'
20
+ Description-Content-Type: text/markdown
21
+
22
+ # kaval (Python SDK)
23
+
24
+ The freshness gate for AI. Give [kaval](https://github.com/LufeMC/kaval-clients) a belief your system
25
+ already holds — a cached fact, a CRM field, an agent memory — and it checks the live world and
26
+ returns a typed freshness gap: `current` / `stale` / `contradicted` / `unsupported` / `conflicting`
27
+ / `insufficient`.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install kaval
33
+ ```
34
+
35
+ ## Gate a belief before you act on it
36
+
37
+ ```python
38
+ from kaval import KavalClient
39
+
40
+ # base_url defaults to the hosted cloud (https://api.usekaval.com).
41
+ with KavalClient(api_key="kv_live_...") as client:
42
+ decision = client.verify("Acme's CEO is Jane Doe")
43
+ if not decision["act"]:
44
+ ... # stale / contradicted — re-fetch before relying on it
45
+ ```
46
+
47
+ `verify()` returns the verdict plus `act` — `True` only when the belief is `current` and confident
48
+ (≥ 0.7 by default; override with `min_confidence`).
49
+
50
+ ### Pick a speed/depth tier
51
+
52
+ `verify(belief, mode=...)` selects a tier (default `auto`): `instant` (cache / graph-prior only, no
53
+ fetch or LLM), `fast` (cheap model, origin-only), `auto` (balanced), or `deep` (strongest model + a
54
+ cited explanation). The returned dict echoes `tier`, and on the `deep` tier adds `explanation`:
55
+
56
+ ```python
57
+ gap = client.verify("Acme's CEO is Jane Doe", mode="deep")
58
+ gap["tier"] # "deep"
59
+ gap["explanation"]["content"] # markdown rationale with [n] citations (deep only)
60
+ gap["explanation"]["citations"] # [{"url": ..., "title"?: ...}] — only from gathered evidence
61
+ gap["explanation"]["confidence"] # "high" | "medium" | "low"
62
+ ```
63
+
64
+ ### Sweep a store for drift
65
+
66
+ ```python
67
+ report = client.scan_store(["Acme is on the Enterprise plan", "Jane Doe is VP Eng at Acme"])
68
+ for r in report["riskiest"]:
69
+ print(r["belief"], "→", r["status"])
70
+
71
+ # …or get pushed the newly-stale ones (carry `state` across runs so a still-stale belief
72
+ # isn't re-delivered every sweep):
73
+ client.monitor(beliefs, webhook="https://your-app.com/hooks/stale")
74
+ ```
75
+
76
+ ## Custom base URL
77
+
78
+ Override the API base URL (e.g. a staging environment or a local proxy):
79
+
80
+ ```python
81
+ client = KavalClient(base_url="https://staging.api.usekaval.com", api_key="...")
82
+ ```
83
+
84
+ ## API
85
+
86
+ `verify` · `check` · `extract_and_check` · `scan_store` · `monitor` · `report_outcome` ·
87
+ `kaval` · `kaval_batch` · `health`. Construct with `KavalClient(base_url=?, api_key=?)` —
88
+ `base_url` defaults to `https://api.usekaval.com`. The Node/TypeScript client mirrors this surface:
89
+ `npm install kaval`.
90
+
91
+ ## Test
92
+
93
+ ```bash
94
+ pip install -e ".[dev]" # from sdks/python (development)
95
+ pytest # hermetic contract tests (httpx MockTransport)
96
+ KAVAL_BASE_URL=https://api.usekaval.com KAVAL_API_KEY=kv_live_... pytest # also runs the live test
97
+ ```
kaval-0.1.0/README.md ADDED
@@ -0,0 +1,76 @@
1
+ # kaval (Python SDK)
2
+
3
+ The freshness gate for AI. Give [kaval](https://github.com/LufeMC/kaval-clients) a belief your system
4
+ already holds — a cached fact, a CRM field, an agent memory — and it checks the live world and
5
+ returns a typed freshness gap: `current` / `stale` / `contradicted` / `unsupported` / `conflicting`
6
+ / `insufficient`.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pip install kaval
12
+ ```
13
+
14
+ ## Gate a belief before you act on it
15
+
16
+ ```python
17
+ from kaval import KavalClient
18
+
19
+ # base_url defaults to the hosted cloud (https://api.usekaval.com).
20
+ with KavalClient(api_key="kv_live_...") as client:
21
+ decision = client.verify("Acme's CEO is Jane Doe")
22
+ if not decision["act"]:
23
+ ... # stale / contradicted — re-fetch before relying on it
24
+ ```
25
+
26
+ `verify()` returns the verdict plus `act` — `True` only when the belief is `current` and confident
27
+ (≥ 0.7 by default; override with `min_confidence`).
28
+
29
+ ### Pick a speed/depth tier
30
+
31
+ `verify(belief, mode=...)` selects a tier (default `auto`): `instant` (cache / graph-prior only, no
32
+ fetch or LLM), `fast` (cheap model, origin-only), `auto` (balanced), or `deep` (strongest model + a
33
+ cited explanation). The returned dict echoes `tier`, and on the `deep` tier adds `explanation`:
34
+
35
+ ```python
36
+ gap = client.verify("Acme's CEO is Jane Doe", mode="deep")
37
+ gap["tier"] # "deep"
38
+ gap["explanation"]["content"] # markdown rationale with [n] citations (deep only)
39
+ gap["explanation"]["citations"] # [{"url": ..., "title"?: ...}] — only from gathered evidence
40
+ gap["explanation"]["confidence"] # "high" | "medium" | "low"
41
+ ```
42
+
43
+ ### Sweep a store for drift
44
+
45
+ ```python
46
+ report = client.scan_store(["Acme is on the Enterprise plan", "Jane Doe is VP Eng at Acme"])
47
+ for r in report["riskiest"]:
48
+ print(r["belief"], "→", r["status"])
49
+
50
+ # …or get pushed the newly-stale ones (carry `state` across runs so a still-stale belief
51
+ # isn't re-delivered every sweep):
52
+ client.monitor(beliefs, webhook="https://your-app.com/hooks/stale")
53
+ ```
54
+
55
+ ## Custom base URL
56
+
57
+ Override the API base URL (e.g. a staging environment or a local proxy):
58
+
59
+ ```python
60
+ client = KavalClient(base_url="https://staging.api.usekaval.com", api_key="...")
61
+ ```
62
+
63
+ ## API
64
+
65
+ `verify` · `check` · `extract_and_check` · `scan_store` · `monitor` · `report_outcome` ·
66
+ `kaval` · `kaval_batch` · `health`. Construct with `KavalClient(base_url=?, api_key=?)` —
67
+ `base_url` defaults to `https://api.usekaval.com`. The Node/TypeScript client mirrors this surface:
68
+ `npm install kaval`.
69
+
70
+ ## Test
71
+
72
+ ```bash
73
+ pip install -e ".[dev]" # from sdks/python (development)
74
+ pytest # hermetic contract tests (httpx MockTransport)
75
+ KAVAL_BASE_URL=https://api.usekaval.com KAVAL_API_KEY=kv_live_... pytest # also runs the live test
76
+ ```
@@ -0,0 +1,6 @@
1
+ """Kaval Python SDK — talk to the kaval currentness REST API."""
2
+
3
+ from .client import KavalClient, KavalError
4
+
5
+ __all__ = ["KavalClient", "KavalError"]
6
+ __version__ = "0.1.0"
@@ -0,0 +1,220 @@
1
+ """HTTP client for the kaval REST surface. Mirrors the TS SDK contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Literal, Optional
6
+
7
+ import httpx
8
+
9
+ # One of: current_later_contradicted | stale_caught_real | stale_was_false_alarm | relied_and_correct
10
+ OutcomeKind = str
11
+
12
+ # Speed/depth tier for verify(): instant (cache/prior only, no LLM) | fast | auto (default) | deep
13
+ VerifyMode = Literal["instant", "fast", "auto", "deep"]
14
+
15
+ # The hosted kaval cloud. Override with `base_url=...` to point at a self-hosted `kaval-server`.
16
+ DEFAULT_BASE_URL = "https://api.usekaval.com"
17
+
18
+
19
+ class KavalError(Exception):
20
+ """Raised when the API returns a non-2xx response."""
21
+
22
+ def __init__(self, status_code: int, payload: Any) -> None:
23
+ super().__init__(f"kaval {status_code}: {payload}")
24
+ self.status_code = status_code
25
+ self.payload = payload
26
+
27
+
28
+ def _clean(body: dict[str, Any]) -> dict[str, Any]:
29
+ """Drop None-valued keys so optional params are omitted from the request."""
30
+ return {k: v for k, v in body.items() if v is not None}
31
+
32
+
33
+ class KavalClient:
34
+ """Synchronous client: a plain-language belief in, a typed freshness gap out."""
35
+
36
+ def __init__(
37
+ self,
38
+ base_url: str = DEFAULT_BASE_URL,
39
+ api_key: Optional[str] = None,
40
+ *,
41
+ timeout: float = 30.0,
42
+ transport: Optional[httpx.BaseTransport] = None,
43
+ ) -> None:
44
+ headers = {"content-type": "application/json"}
45
+ if api_key:
46
+ headers["authorization"] = f"Bearer {api_key}"
47
+ self._http = httpx.Client(
48
+ base_url=base_url.rstrip("/"),
49
+ headers=headers,
50
+ timeout=timeout,
51
+ transport=transport,
52
+ )
53
+
54
+ def _post(self, path: str, body: dict[str, Any]) -> Any:
55
+ res = self._http.post(path, json=body)
56
+ try:
57
+ payload: Any = res.json()
58
+ except ValueError:
59
+ payload = res.text
60
+ if res.status_code >= 400:
61
+ raise KavalError(res.status_code, payload)
62
+ return payload
63
+
64
+ def check(
65
+ self,
66
+ belief: str,
67
+ *,
68
+ context: Optional[str] = None,
69
+ held_evidence: Optional[list[str]] = None,
70
+ freshness_sla: Optional[str] = None,
71
+ proof_standard: Optional[str] = None,
72
+ ) -> dict[str, Any]:
73
+ return self._post(
74
+ "/v1/check",
75
+ _clean(
76
+ {
77
+ "belief": belief,
78
+ "context": context,
79
+ "held_evidence": held_evidence,
80
+ "freshness_sla": freshness_sla,
81
+ "proof_standard": proof_standard,
82
+ }
83
+ ),
84
+ )
85
+
86
+ def verify(
87
+ self,
88
+ belief: str,
89
+ *,
90
+ context: Optional[str] = None,
91
+ url: Optional[str] = None,
92
+ held_at: Optional[str] = None,
93
+ held_content_hash: Optional[str] = None,
94
+ held_evidence: Optional[list[str]] = None,
95
+ freshness_sla: Optional[str] = None,
96
+ proof_standard: Optional[str] = None,
97
+ min_confidence: Optional[float] = None,
98
+ mode: Optional[VerifyMode] = None,
99
+ ) -> dict[str, Any]:
100
+ """Pre-action gate: the verdict plus ``act`` (True only when current and confident).
101
+ Treat ``act`` False as 'do not rely on this belief — re-fetch first'.
102
+
103
+ ``mode`` selects a speed/depth tier — instant (cache/prior only, no LLM) | fast | auto
104
+ (default) | deep (full multi-source + a cited explanation). The returned dict echoes
105
+ ``tier``, and on the deep tier adds ``explanation`` {content, citations, confidence}."""
106
+ return self._post(
107
+ "/v1/verify",
108
+ _clean(
109
+ {
110
+ "belief": belief,
111
+ "context": context,
112
+ "url": url,
113
+ "held_at": held_at,
114
+ "held_content_hash": held_content_hash,
115
+ "held_evidence": held_evidence,
116
+ "freshness_sla": freshness_sla,
117
+ "proof_standard": proof_standard,
118
+ "minConfidence": min_confidence,
119
+ "mode": mode,
120
+ }
121
+ ),
122
+ )
123
+
124
+ def extract_and_check(
125
+ self,
126
+ text: str,
127
+ *,
128
+ context: Optional[str] = None,
129
+ freshness_sla: Optional[str] = None,
130
+ ) -> dict[str, Any]:
131
+ return self._post(
132
+ "/v1/extract-and-check",
133
+ _clean({"text": text, "context": context, "freshness_sla": freshness_sla}),
134
+ )
135
+
136
+ def scan_store(
137
+ self,
138
+ beliefs: list[str],
139
+ *,
140
+ freshness_sla: Optional[str] = None,
141
+ concurrency: Optional[int] = None,
142
+ mode: Optional[VerifyMode] = None,
143
+ ) -> dict[str, Any]:
144
+ """Sweep a belief store for drift. ``mode`` is the speed/depth tier for the whole sweep
145
+ (default ``fast`` — cheap breadth; re-``verify`` a flagged belief at ``deep`` for the cited
146
+ explanation). The returned dict echoes the ``tier`` the sweep ran at."""
147
+ return self._post(
148
+ "/v1/scan-store",
149
+ _clean(
150
+ {
151
+ "beliefs": beliefs,
152
+ "freshness_sla": freshness_sla,
153
+ "concurrency": concurrency,
154
+ "mode": mode,
155
+ }
156
+ ),
157
+ )
158
+
159
+ def monitor(
160
+ self,
161
+ beliefs: list[str],
162
+ *,
163
+ freshness_sla: Optional[str] = None,
164
+ concurrency: Optional[int] = None,
165
+ mode: Optional[VerifyMode] = None,
166
+ webhook: Optional[str] = None,
167
+ state: Optional[dict[str, Any]] = None,
168
+ ) -> dict[str, Any]:
169
+ """Sweep a belief store and POST the NEWLY-risky beliefs to ``webhook`` (server-side delivery).
170
+ Pass the ``state`` from the previous response to deliver only beliefs that became risky since
171
+ then (a still-stale belief isn't re-sent every run). ``mode`` is the sweep tier (default
172
+ ``fast``); the result echoes the ``tier`` it ran at and the ``state`` to carry into the next run."""
173
+ return self._post(
174
+ "/v1/monitor",
175
+ _clean(
176
+ {
177
+ "beliefs": beliefs,
178
+ "freshness_sla": freshness_sla,
179
+ "concurrency": concurrency,
180
+ "mode": mode,
181
+ "webhook": webhook,
182
+ "state": state,
183
+ }
184
+ ),
185
+ )
186
+
187
+ def report_outcome(
188
+ self, id: str, kind: OutcomeKind, *, note: Optional[str] = None
189
+ ) -> dict[str, Any]:
190
+ return self._post("/v1/report-outcome", _clean({"id": id, "kind": kind, "note": note}))
191
+
192
+ def kaval(self, request: dict[str, Any]) -> dict[str, Any]:
193
+ """Lower-level structured passthrough (a KavalRequest)."""
194
+ return self._post("/v1/kaval", request)
195
+
196
+ def kaval_batch(
197
+ self, requests: list[dict[str, Any]], *, concurrency: Optional[int] = None
198
+ ) -> list[dict[str, Any]]:
199
+ return self._post(
200
+ "/v1/kaval-batch", _clean({"requests": requests, "concurrency": concurrency})
201
+ )
202
+
203
+ def health(self) -> dict[str, Any]:
204
+ res = self._http.get("/health")
205
+ try:
206
+ payload: Any = res.json()
207
+ except ValueError:
208
+ payload = res.text
209
+ if res.status_code >= 400:
210
+ raise KavalError(res.status_code, payload)
211
+ return payload
212
+
213
+ def close(self) -> None:
214
+ self._http.close()
215
+
216
+ def __enter__(self) -> "KavalClient":
217
+ return self
218
+
219
+ def __exit__(self, *_exc: object) -> None:
220
+ self.close()
@@ -0,0 +1,36 @@
1
+ [project]
2
+ name = "kaval"
3
+ version = "0.1.0"
4
+ description = "Python SDK for the kaval currentness API (belief in → typed freshness gap out)."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Lumaa, Inc. (dba Kaval)" }]
10
+ keywords = ["kaval", "ai", "agents", "freshness", "rag", "verification"]
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Intended Audience :: Developers",
14
+ "Programming Language :: Python :: 3",
15
+ "Topic :: Software Development :: Libraries :: Python Modules",
16
+ ]
17
+ dependencies = ["httpx>=0.27,<1"]
18
+
19
+ [project.urls]
20
+ Homepage = "https://github.com/LufeMC/kaval-clients"
21
+ Repository = "https://github.com/LufeMC/kaval-clients"
22
+ Issues = "https://github.com/LufeMC/kaval-clients/issues"
23
+
24
+ [project.optional-dependencies]
25
+ dev = ["pytest>=8,<9"]
26
+
27
+ [build-system]
28
+ requires = ["hatchling"]
29
+ build-backend = "hatchling.build"
30
+
31
+ [tool.hatch.build.targets.wheel]
32
+ packages = ["kaval"]
33
+
34
+ [tool.pytest.ini_options]
35
+ testpaths = ["tests"]
36
+ addopts = "-q"
@@ -0,0 +1,227 @@
1
+ """Hermetic contract tests: assert the client serializes requests + parses responses correctly,
2
+ using httpx.MockTransport (no network)."""
3
+
4
+ import json
5
+
6
+ import httpx
7
+ import pytest
8
+
9
+ from kaval import KavalClient, KavalError
10
+ from kaval.client import DEFAULT_BASE_URL
11
+
12
+ GAP = {
13
+ "id": "id_1",
14
+ "status": "stale",
15
+ "confidence": 0.9,
16
+ "reason": "team page changed",
17
+ "evidence": [],
18
+ "checked_at": "2026-06-24T18:04:11.000Z",
19
+ "discrepancy": {"kind": "stale", "signals": []},
20
+ }
21
+
22
+
23
+ def make_client(handler):
24
+ return KavalClient(base_url="http://test", transport=httpx.MockTransport(handler))
25
+
26
+
27
+ def test_check_sends_clean_body_and_parses_gap():
28
+ captured = {}
29
+
30
+ def handler(request: httpx.Request) -> httpx.Response:
31
+ assert request.url.path == "/v1/check"
32
+ assert request.headers["content-type"] == "application/json"
33
+ captured["body"] = json.loads(request.content)
34
+ return httpx.Response(200, json=GAP)
35
+
36
+ with make_client(handler) as c:
37
+ out = c.check("Jane Doe is at Acme", freshness_sla="14d")
38
+
39
+ assert out["status"] == "stale"
40
+ assert out["id"] == "id_1"
41
+ # None-valued optionals are omitted (clean body).
42
+ assert captured["body"] == {"belief": "Jane Doe is at Acme", "freshness_sla": "14d"}
43
+
44
+
45
+ def test_verify_returns_decision_with_act():
46
+ captured = {}
47
+
48
+ def handler(request: httpx.Request) -> httpx.Response:
49
+ assert request.url.path == "/v1/verify"
50
+ captured["body"] = json.loads(request.content)
51
+ return httpx.Response(200, json={**GAP, "act": False})
52
+
53
+ with make_client(handler) as c:
54
+ out = c.verify("Acme's CEO is Jane Doe", min_confidence=0.8)
55
+
56
+ assert out["act"] is False
57
+ assert out["status"] == "stale"
58
+ # min_confidence maps to the wire's camelCase minConfidence; None optionals are dropped.
59
+ assert captured["body"] == {"belief": "Acme's CEO is Jane Doe", "minConfidence": 0.8}
60
+
61
+
62
+ def test_verify_sends_mode_and_parses_tier():
63
+ captured = {}
64
+ resp = {
65
+ "id": "id_1",
66
+ "status": "current",
67
+ "confidence": 0.95,
68
+ "reason": "confirmed by the team page",
69
+ "evidence": [],
70
+ "checked_at": "2026-06-25T00:00:00.000Z",
71
+ "act": True,
72
+ "tier": "deep",
73
+ "explanation": {
74
+ "content": "Confirmed by the team page [1].",
75
+ "citations": [{"url": "http://acme.test/team"}],
76
+ "confidence": "high",
77
+ },
78
+ }
79
+
80
+ def handler(request: httpx.Request) -> httpx.Response:
81
+ assert request.url.path == "/v1/verify"
82
+ captured["body"] = json.loads(request.content)
83
+ return httpx.Response(200, json=resp)
84
+
85
+ with make_client(handler) as c:
86
+ out = c.verify("Acme's CEO is Jane Doe", mode="deep")
87
+
88
+ # `mode` rides the wire verbatim (no camelCase remap, unlike min_confidence).
89
+ assert captured["body"] == {"belief": "Acme's CEO is Jane Doe", "mode": "deep"}
90
+ assert out["tier"] == "deep"
91
+ assert out["explanation"]["confidence"] == "high"
92
+ assert out["explanation"]["citations"][0]["url"] == "http://acme.test/team"
93
+
94
+
95
+ def test_extract_and_check():
96
+ def handler(request: httpx.Request) -> httpx.Response:
97
+ assert request.url.path == "/v1/extract-and-check"
98
+ return httpx.Response(200, json={"beliefs": [GAP, GAP]})
99
+
100
+ with make_client(handler) as c:
101
+ out = c.extract_and_check("a paragraph")
102
+ assert len(out["beliefs"]) == 2
103
+
104
+
105
+ def test_scan_store():
106
+ def handler(request: httpx.Request) -> httpx.Response:
107
+ assert request.url.path == "/v1/scan-store"
108
+ assert json.loads(request.content)["beliefs"] == ["a", "b"]
109
+ return httpx.Response(
110
+ 200,
111
+ json={"total": 2, "summary": {"current": 1, "stale": 1}, "riskiest": [], "tier": "fast"},
112
+ )
113
+
114
+ with make_client(handler) as c:
115
+ out = c.scan_store(["a", "b"], freshness_sla="30d")
116
+ assert out["total"] == 2
117
+ assert out["summary"]["stale"] == 1
118
+
119
+
120
+ def test_scan_store_sends_mode_and_parses_tier():
121
+ captured = {}
122
+
123
+ def handler(request: httpx.Request) -> httpx.Response:
124
+ captured["body"] = json.loads(request.content)
125
+ return httpx.Response(200, json={"total": 1, "summary": {"current": 1}, "riskiest": [], "tier": "deep"})
126
+
127
+ with make_client(handler) as c:
128
+ out = c.scan_store(["a"], mode="deep")
129
+
130
+ assert captured["body"] == {"beliefs": ["a"], "mode": "deep"}
131
+ assert out["tier"] == "deep"
132
+
133
+
134
+ def test_monitor_sends_body_and_parses_result():
135
+ captured = {}
136
+
137
+ def handler(request: httpx.Request) -> httpx.Response:
138
+ assert request.url.path == "/v1/monitor"
139
+ captured["body"] = json.loads(request.content)
140
+ return httpx.Response(
141
+ 200,
142
+ json={
143
+ "total": 2,
144
+ "summary": {"current": 1, "stale": 1},
145
+ "riskiest": [],
146
+ "tier": "fast",
147
+ "checked_at": "2026-06-25T00:00:00.000Z",
148
+ "delivered": 1,
149
+ "state": {"riskyKeys": ["k1"]},
150
+ },
151
+ )
152
+
153
+ with make_client(handler) as c:
154
+ out = c.monitor(["a", "b"], webhook="http://hook.test", mode="deep")
155
+
156
+ assert captured["body"]["mode"] == "deep"
157
+ assert captured["body"]["webhook"] == "http://hook.test"
158
+ assert out["tier"] == "fast"
159
+ assert out["state"]["riskyKeys"] == ["k1"]
160
+
161
+
162
+ def test_report_outcome():
163
+ def handler(request: httpx.Request) -> httpx.Response:
164
+ assert request.url.path == "/v1/report-outcome"
165
+ assert json.loads(request.content)["kind"] == "relied_and_correct"
166
+ return httpx.Response(200, json={"ok": True})
167
+
168
+ with make_client(handler) as c:
169
+ assert c.report_outcome("id_1", "relied_and_correct")["ok"] is True
170
+
171
+
172
+ def test_kaval_structured():
173
+ def handler(request: httpx.Request) -> httpx.Response:
174
+ assert request.url.path == "/v1/kaval"
175
+ return httpx.Response(200, json=GAP)
176
+
177
+ with make_client(handler) as c:
178
+ out = c.kaval({"fact_type": "person.works_at", "subject": "Jane", "object": "Acme"})
179
+ assert out["status"] == "stale"
180
+
181
+
182
+ def test_auth_header_is_set():
183
+ def handler(request: httpx.Request) -> httpx.Response:
184
+ assert request.headers["authorization"] == "Bearer secret"
185
+ return httpx.Response(200, json=GAP)
186
+
187
+ client = KavalClient(
188
+ base_url="http://test", api_key="secret", transport=httpx.MockTransport(handler)
189
+ )
190
+ client.check("x")
191
+ client.close()
192
+
193
+
194
+ def test_error_response_raises():
195
+ def handler(request: httpx.Request) -> httpx.Response:
196
+ return httpx.Response(400, json={"error": {"code": "bad_request"}})
197
+
198
+ with make_client(handler) as c:
199
+ with pytest.raises(KavalError) as exc:
200
+ c.check("x")
201
+ assert exc.value.status_code == 400
202
+
203
+
204
+ def test_default_base_url_is_the_cloud():
205
+ assert DEFAULT_BASE_URL == "https://api.usekaval.com"
206
+
207
+ captured = {}
208
+
209
+ def handler(request: httpx.Request) -> httpx.Response:
210
+ captured["url"] = str(request.url)
211
+ return httpx.Response(200, json=GAP)
212
+
213
+ # No base_url given → defaults to the hosted cloud.
214
+ client = KavalClient(transport=httpx.MockTransport(handler))
215
+ client.check("x")
216
+ client.close()
217
+ assert captured["url"] == "https://api.usekaval.com/v1/check"
218
+
219
+
220
+ def test_health_raises_on_non_2xx():
221
+ def handler(request: httpx.Request) -> httpx.Response:
222
+ return httpx.Response(503, json={"error": {"code": "unavailable"}})
223
+
224
+ with make_client(handler) as c:
225
+ with pytest.raises(KavalError) as exc:
226
+ c.health()
227
+ assert exc.value.status_code == 503
@@ -0,0 +1,19 @@
1
+ """Opt-in live test against a running REST server. Skipped unless KAVAL_BASE_URL is set."""
2
+
3
+ import os
4
+
5
+ import pytest
6
+
7
+ from kaval import KavalClient
8
+
9
+ BASE_URL = os.environ.get("KAVAL_BASE_URL")
10
+ STATUSES = {"current", "stale", "contradicted", "unsupported", "conflicting", "insufficient"}
11
+
12
+
13
+ @pytest.mark.skipif(not BASE_URL, reason="KAVAL_BASE_URL not set")
14
+ def test_live_check_end_to_end():
15
+ with KavalClient(BASE_URL, api_key=os.environ.get("KAVAL_API_KEY")) as client:
16
+ assert client.health()["ok"] is True
17
+ gap = client.check("Satya Nadella is the CEO of Microsoft", freshness_sla="30d")
18
+ assert gap["status"] in STATUSES
19
+ assert "id" in gap