reliamesh-sdk 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.
- reliamesh_sdk-0.1.0/LICENSE +202 -0
- reliamesh_sdk-0.1.0/NOTICE +4 -0
- reliamesh_sdk-0.1.0/PKG-INFO +128 -0
- reliamesh_sdk-0.1.0/README.md +112 -0
- reliamesh_sdk-0.1.0/pyproject.toml +23 -0
- reliamesh_sdk-0.1.0/setup.cfg +4 -0
- reliamesh_sdk-0.1.0/src/reliamesh_sdk/__init__.py +7 -0
- reliamesh_sdk-0.1.0/src/reliamesh_sdk/client.py +224 -0
- reliamesh_sdk-0.1.0/src/reliamesh_sdk/events.py +129 -0
- reliamesh_sdk-0.1.0/src/reliamesh_sdk.egg-info/PKG-INFO +128 -0
- reliamesh_sdk-0.1.0/src/reliamesh_sdk.egg-info/SOURCES.txt +11 -0
- reliamesh_sdk-0.1.0/src/reliamesh_sdk.egg-info/dependency_links.txt +1 -0
- reliamesh_sdk-0.1.0/src/reliamesh_sdk.egg-info/top_level.txt +1 -0
|
@@ -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,128 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: reliamesh-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Content-minimizing reliability events for AI agents
|
|
5
|
+
Author: Prefiler Labs Private Limited
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/PrefilerLabs/reliamesh
|
|
8
|
+
Project-URL: Repository, https://github.com/PrefilerLabs/reliamesh
|
|
9
|
+
Project-URL: Issues, https://github.com/PrefilerLabs/reliamesh/issues
|
|
10
|
+
Project-URL: Documentation, https://github.com/PrefilerLabs/reliamesh/blob/main/sdk/python/README.md
|
|
11
|
+
Requires-Python: >=3.12
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
License-File: NOTICE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# ReliaMesh Python SDK
|
|
18
|
+
|
|
19
|
+
Content-minimizing reliability events for AI agents. Python 3.12+, no runtime
|
|
20
|
+
dependencies. Owned by Prefiler Labs Private Limited; Apache-2.0.
|
|
21
|
+
|
|
22
|
+
For a published release, install from PyPI:
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
python -m pip install reliamesh-sdk==0.1.0
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Or install from this source checkout:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
python -m pip install ./sdk/python
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
import os
|
|
36
|
+
from reliamesh_sdk import Client, event
|
|
37
|
+
|
|
38
|
+
client = Client(
|
|
39
|
+
endpoint=os.environ["RELIAMESH_ENDPOINT"],
|
|
40
|
+
api_key=os.environ["RELIAMESH_API_KEY"],
|
|
41
|
+
)
|
|
42
|
+
client.emit(event(
|
|
43
|
+
deployment_id="production-eu1", agent_id="invoice-agent",
|
|
44
|
+
operation="validation", outcome="failure",
|
|
45
|
+
failure_type="malformed_output", model="model-alias", prompt_version="v3",
|
|
46
|
+
latency_ms=140, input_tokens=80, output_tokens=30,
|
|
47
|
+
))
|
|
48
|
+
client.flush()
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Use opaque stable identifiers; never put customer content, secrets, email
|
|
52
|
+
addresses, or raw prompts in identifier fields. The schema restricts shape, not
|
|
53
|
+
meaning. Hashing predictable personal data does not make it safe.
|
|
54
|
+
|
|
55
|
+
## Observe execution
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
with client.observe(deployment_id="production-eu1", agent_id="invoice-agent",
|
|
59
|
+
operation="tool", tool="document-validator", tool_version="2"):
|
|
60
|
+
run_tool() # Your application function; return values are never inspected.
|
|
61
|
+
client.flush()
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The context manager records elapsed time, success or failure, and a generic
|
|
65
|
+
exception classification. It never reads the exception message or stack. Original
|
|
66
|
+
application exceptions propagate. A timeout is classified as `timeout`; other
|
|
67
|
+
exceptions use the operation's generic failure type. Application validation must
|
|
68
|
+
emit explicit events for malformed output, loops, fallback, retry escalation, or
|
|
69
|
+
incomplete tasks. A successful HTTP call cannot establish task success.
|
|
70
|
+
|
|
71
|
+
## Delivery contract
|
|
72
|
+
|
|
73
|
+
- No default endpoint, network discovery, background thread, automatic exporter,
|
|
74
|
+
exit hook, or outbound telemetry. `emit` and `observe` enqueue locally;
|
|
75
|
+
`flush`, `summary`, and `incidents` initiate requests to your chosen endpoint.
|
|
76
|
+
- Endpoints require HTTPS, except loopback HTTP for local use. Redirects are
|
|
77
|
+
rejected. TLS uses Python's normal certificate validation.
|
|
78
|
+
- Default queue capacity: 1,000 events, at most 100 events and 128 KiB per request. Queue capacity is
|
|
79
|
+
configurable from 1 to 10,000. The queue lives only in memory.
|
|
80
|
+
- Default socket timeout: 2 seconds, configurable up to 30 seconds. This bounds
|
|
81
|
+
individual socket operations, not the entire flush. Flush processes only the
|
|
82
|
+
number of events queued at entry, so concurrent producers cannot extend it
|
|
83
|
+
indefinitely.
|
|
84
|
+
- Only HTTP 429 and 503 retry, up to two retries by default (maximum three).
|
|
85
|
+
Exponential delays are bounded to one second. Retry bodies and event IDs are
|
|
86
|
+
identical so the server can deduplicate them. Transport errors and other
|
|
87
|
+
statuses are not retried. The client verifies ingestion acknowledgement counts.
|
|
88
|
+
- Default `failure_mode="drop"` drops invalid, overflowing, or unsuccessfully sent
|
|
89
|
+
events. `failure_mode="raise"` raises `SDKError`/`DeliveryError`. An attempted
|
|
90
|
+
failed batch is dropped in either mode. Raise mode leaves later batches queued.
|
|
91
|
+
- Read `client.counters`: `enqueued`, `sent`, `dropped`, `failed_batches`,
|
|
92
|
+
`retries`, and `queued`. `sent` counts acknowledged input events, including
|
|
93
|
+
deduplicated events. Errors omit response bodies and credentials.
|
|
94
|
+
- `summary()` and `incidents()` return decoded authenticated API responses;
|
|
95
|
+
read failures always raise `DeliveryError`.
|
|
96
|
+
|
|
97
|
+
This is best-effort instrumentation, not durable message delivery. Export on a
|
|
98
|
+
dedicated application worker or with `await asyncio.to_thread(client.flush)` in
|
|
99
|
+
async applications. Do not call synchronous `flush()` on a latency-sensitive event
|
|
100
|
+
loop. In-process queuing and counters are thread-safe; forked processes need their
|
|
101
|
+
own client. Drain on a controlled shutdown if losing queued observations matters.
|
|
102
|
+
|
|
103
|
+
## OpenTelemetry adapter
|
|
104
|
+
|
|
105
|
+
`from_otel_attributes(attributes, deployment_id=..., agent_id=..., outcome=...)`
|
|
106
|
+
constructs an event without exporting it or installing span processors. It maps
|
|
107
|
+
selected standard names from the [OpenTelemetry GenAI attribute registry](https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/):
|
|
108
|
+
|
|
109
|
+
| Input | Event field |
|
|
110
|
+
| --- | --- |
|
|
111
|
+
| `gen_ai.provider.name` | `provider` |
|
|
112
|
+
| `gen_ai.request.model` | `model` |
|
|
113
|
+
| `gen_ai.usage.input_tokens` / `output_tokens` | `input_tokens` / `output_tokens` |
|
|
114
|
+
| `telemetry.sdk.name` / `version` | `sdk` / `sdk_version` |
|
|
115
|
+
| `gen_ai.operation.name` | `operation`, via the fixed map below |
|
|
116
|
+
|
|
117
|
+
`chat`, `text_completion`, `generate_content`, and `embeddings` map to `model`;
|
|
118
|
+
`invoke_agent` maps to `agent`; `execute_tool` maps to `tool`. Unknown operations
|
|
119
|
+
require an explicit application mapping and raise `ValueError`.
|
|
120
|
+
|
|
121
|
+
ReliaMesh-specific extensions `reliamesh.model.version`, `reliamesh.prompt.version`,
|
|
122
|
+
`reliamesh.agent.version`, `reliamesh.framework.name`, `reliamesh.framework.version`,
|
|
123
|
+
`reliamesh.tool.name`, and `reliamesh.tool.version` map to the corresponding flat
|
|
124
|
+
event fields. These extensions are not official OpenTelemetry conventions.
|
|
125
|
+
The caller explicitly supplies outcome, failure type, duration, and synthetic
|
|
126
|
+
status. All unlisted attributes, messages, exception details, and span events are
|
|
127
|
+
ignored. Invalid allowlisted values are rejected. Never pass prompt text as a
|
|
128
|
+
version identifier.
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# ReliaMesh Python SDK
|
|
2
|
+
|
|
3
|
+
Content-minimizing reliability events for AI agents. Python 3.12+, no runtime
|
|
4
|
+
dependencies. Owned by Prefiler Labs Private Limited; Apache-2.0.
|
|
5
|
+
|
|
6
|
+
For a published release, install from PyPI:
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
python -m pip install reliamesh-sdk==0.1.0
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Or install from this source checkout:
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
python -m pip install ./sdk/python
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
import os
|
|
20
|
+
from reliamesh_sdk import Client, event
|
|
21
|
+
|
|
22
|
+
client = Client(
|
|
23
|
+
endpoint=os.environ["RELIAMESH_ENDPOINT"],
|
|
24
|
+
api_key=os.environ["RELIAMESH_API_KEY"],
|
|
25
|
+
)
|
|
26
|
+
client.emit(event(
|
|
27
|
+
deployment_id="production-eu1", agent_id="invoice-agent",
|
|
28
|
+
operation="validation", outcome="failure",
|
|
29
|
+
failure_type="malformed_output", model="model-alias", prompt_version="v3",
|
|
30
|
+
latency_ms=140, input_tokens=80, output_tokens=30,
|
|
31
|
+
))
|
|
32
|
+
client.flush()
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Use opaque stable identifiers; never put customer content, secrets, email
|
|
36
|
+
addresses, or raw prompts in identifier fields. The schema restricts shape, not
|
|
37
|
+
meaning. Hashing predictable personal data does not make it safe.
|
|
38
|
+
|
|
39
|
+
## Observe execution
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
with client.observe(deployment_id="production-eu1", agent_id="invoice-agent",
|
|
43
|
+
operation="tool", tool="document-validator", tool_version="2"):
|
|
44
|
+
run_tool() # Your application function; return values are never inspected.
|
|
45
|
+
client.flush()
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The context manager records elapsed time, success or failure, and a generic
|
|
49
|
+
exception classification. It never reads the exception message or stack. Original
|
|
50
|
+
application exceptions propagate. A timeout is classified as `timeout`; other
|
|
51
|
+
exceptions use the operation's generic failure type. Application validation must
|
|
52
|
+
emit explicit events for malformed output, loops, fallback, retry escalation, or
|
|
53
|
+
incomplete tasks. A successful HTTP call cannot establish task success.
|
|
54
|
+
|
|
55
|
+
## Delivery contract
|
|
56
|
+
|
|
57
|
+
- No default endpoint, network discovery, background thread, automatic exporter,
|
|
58
|
+
exit hook, or outbound telemetry. `emit` and `observe` enqueue locally;
|
|
59
|
+
`flush`, `summary`, and `incidents` initiate requests to your chosen endpoint.
|
|
60
|
+
- Endpoints require HTTPS, except loopback HTTP for local use. Redirects are
|
|
61
|
+
rejected. TLS uses Python's normal certificate validation.
|
|
62
|
+
- Default queue capacity: 1,000 events, at most 100 events and 128 KiB per request. Queue capacity is
|
|
63
|
+
configurable from 1 to 10,000. The queue lives only in memory.
|
|
64
|
+
- Default socket timeout: 2 seconds, configurable up to 30 seconds. This bounds
|
|
65
|
+
individual socket operations, not the entire flush. Flush processes only the
|
|
66
|
+
number of events queued at entry, so concurrent producers cannot extend it
|
|
67
|
+
indefinitely.
|
|
68
|
+
- Only HTTP 429 and 503 retry, up to two retries by default (maximum three).
|
|
69
|
+
Exponential delays are bounded to one second. Retry bodies and event IDs are
|
|
70
|
+
identical so the server can deduplicate them. Transport errors and other
|
|
71
|
+
statuses are not retried. The client verifies ingestion acknowledgement counts.
|
|
72
|
+
- Default `failure_mode="drop"` drops invalid, overflowing, or unsuccessfully sent
|
|
73
|
+
events. `failure_mode="raise"` raises `SDKError`/`DeliveryError`. An attempted
|
|
74
|
+
failed batch is dropped in either mode. Raise mode leaves later batches queued.
|
|
75
|
+
- Read `client.counters`: `enqueued`, `sent`, `dropped`, `failed_batches`,
|
|
76
|
+
`retries`, and `queued`. `sent` counts acknowledged input events, including
|
|
77
|
+
deduplicated events. Errors omit response bodies and credentials.
|
|
78
|
+
- `summary()` and `incidents()` return decoded authenticated API responses;
|
|
79
|
+
read failures always raise `DeliveryError`.
|
|
80
|
+
|
|
81
|
+
This is best-effort instrumentation, not durable message delivery. Export on a
|
|
82
|
+
dedicated application worker or with `await asyncio.to_thread(client.flush)` in
|
|
83
|
+
async applications. Do not call synchronous `flush()` on a latency-sensitive event
|
|
84
|
+
loop. In-process queuing and counters are thread-safe; forked processes need their
|
|
85
|
+
own client. Drain on a controlled shutdown if losing queued observations matters.
|
|
86
|
+
|
|
87
|
+
## OpenTelemetry adapter
|
|
88
|
+
|
|
89
|
+
`from_otel_attributes(attributes, deployment_id=..., agent_id=..., outcome=...)`
|
|
90
|
+
constructs an event without exporting it or installing span processors. It maps
|
|
91
|
+
selected standard names from the [OpenTelemetry GenAI attribute registry](https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/):
|
|
92
|
+
|
|
93
|
+
| Input | Event field |
|
|
94
|
+
| --- | --- |
|
|
95
|
+
| `gen_ai.provider.name` | `provider` |
|
|
96
|
+
| `gen_ai.request.model` | `model` |
|
|
97
|
+
| `gen_ai.usage.input_tokens` / `output_tokens` | `input_tokens` / `output_tokens` |
|
|
98
|
+
| `telemetry.sdk.name` / `version` | `sdk` / `sdk_version` |
|
|
99
|
+
| `gen_ai.operation.name` | `operation`, via the fixed map below |
|
|
100
|
+
|
|
101
|
+
`chat`, `text_completion`, `generate_content`, and `embeddings` map to `model`;
|
|
102
|
+
`invoke_agent` maps to `agent`; `execute_tool` maps to `tool`. Unknown operations
|
|
103
|
+
require an explicit application mapping and raise `ValueError`.
|
|
104
|
+
|
|
105
|
+
ReliaMesh-specific extensions `reliamesh.model.version`, `reliamesh.prompt.version`,
|
|
106
|
+
`reliamesh.agent.version`, `reliamesh.framework.name`, `reliamesh.framework.version`,
|
|
107
|
+
`reliamesh.tool.name`, and `reliamesh.tool.version` map to the corresponding flat
|
|
108
|
+
event fields. These extensions are not official OpenTelemetry conventions.
|
|
109
|
+
The caller explicitly supplies outcome, failure type, duration, and synthetic
|
|
110
|
+
status. All unlisted attributes, messages, exception details, and span events are
|
|
111
|
+
ignored. Invalid allowlisted values are rejected. Never pass prompt text as a
|
|
112
|
+
version identifier.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "reliamesh-sdk"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Content-minimizing reliability events for AI agents"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.12"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
license-files = ["LICENSE", "NOTICE"]
|
|
13
|
+
authors = [{name = "Prefiler Labs Private Limited"}]
|
|
14
|
+
dependencies = []
|
|
15
|
+
|
|
16
|
+
[project.urls]
|
|
17
|
+
Homepage = "https://github.com/PrefilerLabs/reliamesh"
|
|
18
|
+
Repository = "https://github.com/PrefilerLabs/reliamesh"
|
|
19
|
+
Issues = "https://github.com/PrefilerLabs/reliamesh/issues"
|
|
20
|
+
Documentation = "https://github.com/PrefilerLabs/reliamesh/blob/main/sdk/python/README.md"
|
|
21
|
+
|
|
22
|
+
[tool.setuptools.packages.find]
|
|
23
|
+
where = ["src"]
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Explicit, content-minimizing reliability instrumentation. No implicit exports."""
|
|
2
|
+
|
|
3
|
+
from .client import Client, DeliveryError, SDKError
|
|
4
|
+
from .events import event, from_otel_attributes, validate_event
|
|
5
|
+
|
|
6
|
+
__version__ = "0.1.0"
|
|
7
|
+
__all__ = ["Client", "DeliveryError", "SDKError", "event", "from_otel_attributes", "validate_event"]
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Bounded synchronous delivery with explicit endpoints and explicit flush."""
|
|
2
|
+
|
|
3
|
+
import ipaddress
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from collections import deque
|
|
9
|
+
from contextlib import contextmanager
|
|
10
|
+
from http.client import HTTPException
|
|
11
|
+
from urllib.error import HTTPError, URLError
|
|
12
|
+
from urllib.parse import urlsplit
|
|
13
|
+
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
|
14
|
+
|
|
15
|
+
from .events import event, validate_event
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SDKError(Exception):
|
|
19
|
+
"""SDK error with no telemetry values or secrets in its message."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DeliveryError(SDKError):
|
|
23
|
+
"""A bounded export failed. Response bodies are intentionally omitted."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class _NoRedirect(HTTPRedirectHandler):
|
|
27
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
28
|
+
return None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _endpoint(value: str) -> str:
|
|
32
|
+
try:
|
|
33
|
+
parsed = urlsplit(value)
|
|
34
|
+
hostname = parsed.hostname
|
|
35
|
+
port = parsed.port
|
|
36
|
+
if (not hostname or parsed.username is not None or parsed.password is not None
|
|
37
|
+
or parsed.query or parsed.fragment or "\\" in value
|
|
38
|
+
or any(ord(character) <= 32 for character in value)
|
|
39
|
+
or (port is not None and not 1 <= port <= 65535)):
|
|
40
|
+
raise ValueError
|
|
41
|
+
try:
|
|
42
|
+
local = ipaddress.ip_address(hostname).is_loopback
|
|
43
|
+
except ValueError:
|
|
44
|
+
local = hostname == "localhost"
|
|
45
|
+
if parsed.scheme != "https" and not (parsed.scheme == "http" and local):
|
|
46
|
+
raise ValueError
|
|
47
|
+
except (ValueError, TypeError, AttributeError):
|
|
48
|
+
raise ValueError("endpoint must be HTTPS or loopback HTTP without credentials/query/fragment") from None
|
|
49
|
+
return value.rstrip("/")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Client:
|
|
53
|
+
"""No worker, persistence, automatic shutdown hook, or implicit cloud endpoint.
|
|
54
|
+
|
|
55
|
+
`emit` and `observe` only enqueue. `flush` performs synchronous I/O and drops
|
|
56
|
+
each attempted batch after success or final failure. `failure_mode='raise'`
|
|
57
|
+
additionally raises for invalid events, a full queue, or delivery failure.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(self, *, endpoint: str, api_key: str, timeout: float = 2.0,
|
|
61
|
+
max_retries: int = 2, queue_capacity: int = 1000,
|
|
62
|
+
failure_mode: str = "drop"):
|
|
63
|
+
self.endpoint = _endpoint(endpoint)
|
|
64
|
+
if (not isinstance(api_key, str) or not 1 <= len(api_key) <= 512
|
|
65
|
+
or any(not 33 <= ord(character) <= 126 for character in api_key)):
|
|
66
|
+
raise ValueError("api_key must be nonempty visible ASCII")
|
|
67
|
+
if type(timeout) not in (int, float) or not 0 < timeout <= 30 or not math.isfinite(timeout):
|
|
68
|
+
raise ValueError("timeout must be greater than zero and at most 30 seconds")
|
|
69
|
+
if type(max_retries) is not int or not 0 <= max_retries <= 3:
|
|
70
|
+
raise ValueError("max_retries must be between zero and three")
|
|
71
|
+
if type(queue_capacity) is not int or not 1 <= queue_capacity <= 10000:
|
|
72
|
+
raise ValueError("queue_capacity must be between one and 10000")
|
|
73
|
+
if failure_mode not in ("drop", "raise"):
|
|
74
|
+
raise ValueError("failure_mode must be drop or raise")
|
|
75
|
+
self._api_key = api_key
|
|
76
|
+
self.timeout = timeout
|
|
77
|
+
self.max_retries = max_retries
|
|
78
|
+
self.queue_capacity = queue_capacity
|
|
79
|
+
self.failure_mode = failure_mode
|
|
80
|
+
self._queue = deque()
|
|
81
|
+
self._lock = threading.Lock()
|
|
82
|
+
self._flush_lock = threading.Lock()
|
|
83
|
+
self._opener = build_opener(_NoRedirect())
|
|
84
|
+
self._counts = dict(enqueued=0, sent=0, dropped=0, failed_batches=0, retries=0)
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def counters(self) -> dict:
|
|
88
|
+
with self._lock:
|
|
89
|
+
return {**self._counts, "queued": len(self._queue)}
|
|
90
|
+
|
|
91
|
+
def _increment(self, name, count=1):
|
|
92
|
+
with self._lock:
|
|
93
|
+
self._counts[name] += count
|
|
94
|
+
|
|
95
|
+
def emit(self, value) -> bool:
|
|
96
|
+
"""Validate and enqueue a copy. This method performs no network activity."""
|
|
97
|
+
try:
|
|
98
|
+
validated = validate_event(value)
|
|
99
|
+
except (ValueError, TypeError):
|
|
100
|
+
self._increment("dropped")
|
|
101
|
+
if self.failure_mode == "raise":
|
|
102
|
+
raise SDKError("event rejected by local validation") from None
|
|
103
|
+
return False
|
|
104
|
+
with self._lock:
|
|
105
|
+
if len(self._queue) >= self.queue_capacity:
|
|
106
|
+
self._counts["dropped"] += 1
|
|
107
|
+
if self.failure_mode == "raise":
|
|
108
|
+
raise SDKError("event queue is full")
|
|
109
|
+
return False
|
|
110
|
+
self._queue.append(validated)
|
|
111
|
+
self._counts["enqueued"] += 1
|
|
112
|
+
return True
|
|
113
|
+
|
|
114
|
+
def _request(self, path: str, payload: dict | None = None) -> dict | list:
|
|
115
|
+
encoded = None if payload is None else json.dumps(payload, separators=(",", ":"), allow_nan=False).encode()
|
|
116
|
+
headers = {"Authorization": "Bearer " + self._api_key,
|
|
117
|
+
"Accept": "application/json", "User-Agent": "reliamesh-sdk/0.1.0"}
|
|
118
|
+
if encoded is not None:
|
|
119
|
+
headers["Content-Type"] = "application/json"
|
|
120
|
+
# _endpoint restricts schemes; redirects cannot forward credentials.
|
|
121
|
+
request = Request(self.endpoint + path, data=encoded, headers=headers) # noqa: S310
|
|
122
|
+
for attempt in range(self.max_retries + 1):
|
|
123
|
+
try:
|
|
124
|
+
with self._opener.open(request, timeout=self.timeout) as response:
|
|
125
|
+
body = response.read(1_048_577)
|
|
126
|
+
if len(body) > 1_048_576:
|
|
127
|
+
raise DeliveryError("server response exceeds SDK size limit")
|
|
128
|
+
result = json.loads(body)
|
|
129
|
+
if not isinstance(result, (dict, list)):
|
|
130
|
+
raise DeliveryError("server returned an invalid response")
|
|
131
|
+
return result
|
|
132
|
+
except HTTPError as exc:
|
|
133
|
+
status = exc.code
|
|
134
|
+
exc.close()
|
|
135
|
+
if status in (429, 503) and attempt < self.max_retries:
|
|
136
|
+
self._increment("retries")
|
|
137
|
+
time.sleep(min(0.2 * 2**attempt, 1.0))
|
|
138
|
+
continue
|
|
139
|
+
raise DeliveryError(f"request failed with HTTP {status}") from None
|
|
140
|
+
except (URLError, OSError, ValueError, HTTPException):
|
|
141
|
+
raise DeliveryError("request failed or returned invalid JSON") from None
|
|
142
|
+
raise DeliveryError("request failed")
|
|
143
|
+
|
|
144
|
+
def flush(self) -> int:
|
|
145
|
+
"""Send at most the queue present at entry, in batches of 100 events.
|
|
146
|
+
|
|
147
|
+
Only HTTP 429 and 503 retry; retries reuse the identical event IDs/body.
|
|
148
|
+
Delivery is best effort, not a durable delivery guarantee. Unattempted
|
|
149
|
+
batches remain queued if raise mode stops a flush on the first failure.
|
|
150
|
+
"""
|
|
151
|
+
sent = 0
|
|
152
|
+
with self._flush_lock:
|
|
153
|
+
with self._lock:
|
|
154
|
+
remaining = len(self._queue)
|
|
155
|
+
while remaining:
|
|
156
|
+
with self._lock:
|
|
157
|
+
batch = []
|
|
158
|
+
payload_size = len(b'{"events":[]}')
|
|
159
|
+
while len(batch) < min(100, remaining):
|
|
160
|
+
candidate = self._queue[0]
|
|
161
|
+
event_size = len(json.dumps(candidate, separators=(",", ":"), allow_nan=False).encode())
|
|
162
|
+
addition = event_size + bool(batch)
|
|
163
|
+
if batch and payload_size + addition > 131_072:
|
|
164
|
+
break
|
|
165
|
+
batch.append(self._queue.popleft())
|
|
166
|
+
payload_size += addition
|
|
167
|
+
remaining -= len(batch)
|
|
168
|
+
try:
|
|
169
|
+
result = self._request("/v1/events", {"events": batch})
|
|
170
|
+
if (not isinstance(result, dict) or result.get("schema_version") != "1.0"
|
|
171
|
+
or type(result.get("accepted")) is not int
|
|
172
|
+
or type(result.get("duplicates")) is not int
|
|
173
|
+
or result["accepted"] < 0 or result["duplicates"] < 0
|
|
174
|
+
or result["accepted"] + result["duplicates"] != len(batch)):
|
|
175
|
+
raise DeliveryError("server returned an invalid ingestion acknowledgement")
|
|
176
|
+
except DeliveryError:
|
|
177
|
+
self._increment("failed_batches")
|
|
178
|
+
self._increment("dropped", len(batch))
|
|
179
|
+
if self.failure_mode == "raise":
|
|
180
|
+
raise
|
|
181
|
+
else:
|
|
182
|
+
sent += len(batch)
|
|
183
|
+
self._increment("sent", len(batch))
|
|
184
|
+
return sent
|
|
185
|
+
|
|
186
|
+
def summary(self) -> dict | list:
|
|
187
|
+
"""Retrieve authenticated tenant summary; failures always raise DeliveryError."""
|
|
188
|
+
return self._request("/v1/summary")
|
|
189
|
+
|
|
190
|
+
def incidents(self) -> dict | list:
|
|
191
|
+
"""Retrieve authenticated tenant incidents; failures always raise DeliveryError."""
|
|
192
|
+
return self._request("/v1/incidents")
|
|
193
|
+
|
|
194
|
+
@contextmanager
|
|
195
|
+
def observe(self, *, deployment_id: str, agent_id: str, operation: str = "agent",
|
|
196
|
+
synthetic: bool = False, **measurements):
|
|
197
|
+
"""Measure duration and classify exceptions without reading their messages.
|
|
198
|
+
|
|
199
|
+
Does not infer semantic success. Emit explicit failure events for invalid
|
|
200
|
+
outputs, incomplete tasks, loops, fallback, or other application findings.
|
|
201
|
+
"""
|
|
202
|
+
start = time.perf_counter()
|
|
203
|
+
outcome, failure_type = "success", None
|
|
204
|
+
try:
|
|
205
|
+
yield
|
|
206
|
+
except BaseException as exc:
|
|
207
|
+
outcome = "failure"
|
|
208
|
+
failure_type = "timeout" if isinstance(exc, TimeoutError) else {
|
|
209
|
+
"agent": "agent_error", "model": "model_error", "tool": "tool_error",
|
|
210
|
+
"validation": "validation_failure",
|
|
211
|
+
}.get(operation, "unknown")
|
|
212
|
+
raise
|
|
213
|
+
finally:
|
|
214
|
+
try:
|
|
215
|
+
self.emit(event(deployment_id=deployment_id, agent_id=agent_id,
|
|
216
|
+
operation=operation, outcome=outcome, failure_type=failure_type,
|
|
217
|
+
latency_ms=min((time.perf_counter() - start) * 1000, 86_400_000),
|
|
218
|
+
synthetic=synthetic, **measurements))
|
|
219
|
+
except (SDKError, ValueError, TypeError) as exc:
|
|
220
|
+
if not isinstance(exc, SDKError):
|
|
221
|
+
self._increment("dropped")
|
|
222
|
+
# Never replace the original application exception.
|
|
223
|
+
if outcome == "success" and self.failure_mode == "raise":
|
|
224
|
+
raise SDKError("observation could not be recorded") from None
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Schema 1.0 event construction without third-party dependencies."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import re
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from datetime import UTC, datetime
|
|
7
|
+
from uuid import UUID, uuid4
|
|
8
|
+
|
|
9
|
+
IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,63}\Z")
|
|
10
|
+
OPERATIONS = frozenset({"agent", "model", "tool", "validation"})
|
|
11
|
+
FAILURE_TYPES = frozenset({
|
|
12
|
+
"agent_error", "model_error", "tool_error", "malformed_output", "validation_failure",
|
|
13
|
+
"timeout", "retry_exhausted", "retry_explosion", "loop_detected", "fallback_activated",
|
|
14
|
+
"task_incomplete", "unknown",
|
|
15
|
+
})
|
|
16
|
+
IDENTIFIERS = frozenset({
|
|
17
|
+
"deployment_id", "agent_id", "provider", "model", "model_version", "framework",
|
|
18
|
+
"framework_version", "sdk", "sdk_version", "tool", "tool_version", "prompt_version",
|
|
19
|
+
"agent_version",
|
|
20
|
+
})
|
|
21
|
+
COUNTERS = {"input_tokens": 10**9, "output_tokens": 10**9, "retry_count": 10**6}
|
|
22
|
+
REQUIRED = frozenset({"schema_version", "event_id", "timestamp", "deployment_id", "agent_id",
|
|
23
|
+
"operation", "outcome"})
|
|
24
|
+
FIELDS = REQUIRED | IDENTIFIERS | COUNTERS.keys() | {"failure_type", "latency_ms", "synthetic"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def validate_event(value: Mapping) -> dict:
|
|
28
|
+
"""Copy and validate an event; error text never includes supplied values."""
|
|
29
|
+
if not isinstance(value, Mapping) or set(value) - FIELDS or REQUIRED - set(value):
|
|
30
|
+
raise ValueError("event has missing or unsupported fields")
|
|
31
|
+
result = dict(value)
|
|
32
|
+
if result["schema_version"] != "1.0":
|
|
33
|
+
raise ValueError("unsupported event schema version")
|
|
34
|
+
try:
|
|
35
|
+
if not isinstance(result["event_id"], str):
|
|
36
|
+
raise ValueError
|
|
37
|
+
result["event_id"] = str(UUID(result["event_id"]))
|
|
38
|
+
except (ValueError, TypeError, AttributeError):
|
|
39
|
+
raise ValueError("event_id must be a UUID") from None
|
|
40
|
+
try:
|
|
41
|
+
timestamp = datetime.fromisoformat(result["timestamp"])
|
|
42
|
+
if timestamp.tzinfo is None or timestamp.utcoffset() is None:
|
|
43
|
+
raise ValueError
|
|
44
|
+
result["timestamp"] = timestamp.astimezone(UTC).isoformat()
|
|
45
|
+
except (ValueError, TypeError, OverflowError):
|
|
46
|
+
raise ValueError("timestamp must be an ISO 8601 time with timezone") from None
|
|
47
|
+
for key in IDENTIFIERS & result.keys():
|
|
48
|
+
if not isinstance(result[key], str) or not IDENTIFIER.fullmatch(result[key]):
|
|
49
|
+
raise ValueError("event identifiers must use 1-64 safe ASCII characters")
|
|
50
|
+
if not isinstance(result["operation"], str) or result["operation"] not in OPERATIONS:
|
|
51
|
+
raise ValueError("unsupported operation")
|
|
52
|
+
if result["outcome"] not in ("success", "failure"):
|
|
53
|
+
raise ValueError("unsupported outcome")
|
|
54
|
+
failure = result.get("failure_type")
|
|
55
|
+
if result["outcome"] == "failure":
|
|
56
|
+
if not isinstance(failure, str) or failure not in FAILURE_TYPES:
|
|
57
|
+
raise ValueError("failure outcome requires a supported failure_type")
|
|
58
|
+
elif failure is not None:
|
|
59
|
+
raise ValueError("success outcome must not include a failure_type")
|
|
60
|
+
for key, maximum in COUNTERS.items():
|
|
61
|
+
if key in result and (type(result[key]) is not int or not 0 <= result[key] <= maximum):
|
|
62
|
+
raise ValueError("event counter is outside allowed bounds")
|
|
63
|
+
if "latency_ms" in result:
|
|
64
|
+
latency = result["latency_ms"]
|
|
65
|
+
if (type(latency) not in (int, float) or not 0 <= latency <= 86_400_000
|
|
66
|
+
or not math.isfinite(latency)):
|
|
67
|
+
raise ValueError("latency_ms is outside allowed bounds")
|
|
68
|
+
if "synthetic" in result and type(result["synthetic"]) is not bool:
|
|
69
|
+
raise ValueError("synthetic must be boolean")
|
|
70
|
+
return result
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def event(*, deployment_id: str, agent_id: str, operation: str, outcome: str,
|
|
74
|
+
failure_type: str | None = None, timestamp: datetime | None = None,
|
|
75
|
+
event_id: str | None = None, synthetic: bool = False, **measurements) -> dict:
|
|
76
|
+
"""Construct a strict protocol event. Unknown metadata is rejected, never exported."""
|
|
77
|
+
result = {
|
|
78
|
+
"schema_version": "1.0", "event_id": event_id or str(uuid4()),
|
|
79
|
+
"timestamp": (timestamp if timestamp is not None else datetime.now(UTC)).isoformat(),
|
|
80
|
+
"deployment_id": deployment_id, "agent_id": agent_id,
|
|
81
|
+
"operation": operation, "outcome": outcome, "synthetic": synthetic,
|
|
82
|
+
}
|
|
83
|
+
if failure_type is not None:
|
|
84
|
+
result["failure_type"] = failure_type
|
|
85
|
+
if set(measurements) & result.keys():
|
|
86
|
+
raise ValueError("duplicate event fields")
|
|
87
|
+
result.update(measurements)
|
|
88
|
+
return validate_event(result)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
_OTEL_FIELDS = {
|
|
92
|
+
"gen_ai.provider.name": "provider",
|
|
93
|
+
"gen_ai.request.model": "model",
|
|
94
|
+
"gen_ai.usage.input_tokens": "input_tokens",
|
|
95
|
+
"gen_ai.usage.output_tokens": "output_tokens",
|
|
96
|
+
"telemetry.sdk.name": "sdk",
|
|
97
|
+
"telemetry.sdk.version": "sdk_version",
|
|
98
|
+
"reliamesh.model.version": "model_version",
|
|
99
|
+
"reliamesh.prompt.version": "prompt_version",
|
|
100
|
+
"reliamesh.agent.version": "agent_version",
|
|
101
|
+
"reliamesh.framework.name": "framework",
|
|
102
|
+
"reliamesh.framework.version": "framework_version",
|
|
103
|
+
"reliamesh.tool.name": "tool",
|
|
104
|
+
"reliamesh.tool.version": "tool_version",
|
|
105
|
+
}
|
|
106
|
+
_OTEL_OPERATIONS = {
|
|
107
|
+
"chat": "model", "text_completion": "model", "generate_content": "model",
|
|
108
|
+
"embeddings": "model", "invoke_agent": "agent", "execute_tool": "tool",
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def from_otel_attributes(attributes: Mapping, *, deployment_id: str, agent_id: str,
|
|
113
|
+
outcome: str, failure_type: str | None = None,
|
|
114
|
+
latency_ms: float | None = None, synthetic: bool = False) -> dict:
|
|
115
|
+
"""Pure whitelist mapping; does not export, inspect spans, or capture content.
|
|
116
|
+
|
|
117
|
+
`reliamesh.*` names are local extensions, not official OTel conventions.
|
|
118
|
+
The caller explicitly supplies the outcome and failure classification.
|
|
119
|
+
"""
|
|
120
|
+
operation = attributes.get("gen_ai.operation.name")
|
|
121
|
+
if not isinstance(operation, str) or operation not in _OTEL_OPERATIONS:
|
|
122
|
+
raise ValueError("unsupported OpenTelemetry operation; map it explicitly")
|
|
123
|
+
selected = {target: attributes[source] for source, target in _OTEL_FIELDS.items()
|
|
124
|
+
if source in attributes}
|
|
125
|
+
if latency_ms is not None:
|
|
126
|
+
selected["latency_ms"] = latency_ms
|
|
127
|
+
return event(deployment_id=deployment_id, agent_id=agent_id,
|
|
128
|
+
operation=_OTEL_OPERATIONS[operation], outcome=outcome,
|
|
129
|
+
failure_type=failure_type, synthetic=synthetic, **selected)
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: reliamesh-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Content-minimizing reliability events for AI agents
|
|
5
|
+
Author: Prefiler Labs Private Limited
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/PrefilerLabs/reliamesh
|
|
8
|
+
Project-URL: Repository, https://github.com/PrefilerLabs/reliamesh
|
|
9
|
+
Project-URL: Issues, https://github.com/PrefilerLabs/reliamesh/issues
|
|
10
|
+
Project-URL: Documentation, https://github.com/PrefilerLabs/reliamesh/blob/main/sdk/python/README.md
|
|
11
|
+
Requires-Python: >=3.12
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
License-File: NOTICE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# ReliaMesh Python SDK
|
|
18
|
+
|
|
19
|
+
Content-minimizing reliability events for AI agents. Python 3.12+, no runtime
|
|
20
|
+
dependencies. Owned by Prefiler Labs Private Limited; Apache-2.0.
|
|
21
|
+
|
|
22
|
+
For a published release, install from PyPI:
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
python -m pip install reliamesh-sdk==0.1.0
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Or install from this source checkout:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
python -m pip install ./sdk/python
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
import os
|
|
36
|
+
from reliamesh_sdk import Client, event
|
|
37
|
+
|
|
38
|
+
client = Client(
|
|
39
|
+
endpoint=os.environ["RELIAMESH_ENDPOINT"],
|
|
40
|
+
api_key=os.environ["RELIAMESH_API_KEY"],
|
|
41
|
+
)
|
|
42
|
+
client.emit(event(
|
|
43
|
+
deployment_id="production-eu1", agent_id="invoice-agent",
|
|
44
|
+
operation="validation", outcome="failure",
|
|
45
|
+
failure_type="malformed_output", model="model-alias", prompt_version="v3",
|
|
46
|
+
latency_ms=140, input_tokens=80, output_tokens=30,
|
|
47
|
+
))
|
|
48
|
+
client.flush()
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Use opaque stable identifiers; never put customer content, secrets, email
|
|
52
|
+
addresses, or raw prompts in identifier fields. The schema restricts shape, not
|
|
53
|
+
meaning. Hashing predictable personal data does not make it safe.
|
|
54
|
+
|
|
55
|
+
## Observe execution
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
with client.observe(deployment_id="production-eu1", agent_id="invoice-agent",
|
|
59
|
+
operation="tool", tool="document-validator", tool_version="2"):
|
|
60
|
+
run_tool() # Your application function; return values are never inspected.
|
|
61
|
+
client.flush()
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The context manager records elapsed time, success or failure, and a generic
|
|
65
|
+
exception classification. It never reads the exception message or stack. Original
|
|
66
|
+
application exceptions propagate. A timeout is classified as `timeout`; other
|
|
67
|
+
exceptions use the operation's generic failure type. Application validation must
|
|
68
|
+
emit explicit events for malformed output, loops, fallback, retry escalation, or
|
|
69
|
+
incomplete tasks. A successful HTTP call cannot establish task success.
|
|
70
|
+
|
|
71
|
+
## Delivery contract
|
|
72
|
+
|
|
73
|
+
- No default endpoint, network discovery, background thread, automatic exporter,
|
|
74
|
+
exit hook, or outbound telemetry. `emit` and `observe` enqueue locally;
|
|
75
|
+
`flush`, `summary`, and `incidents` initiate requests to your chosen endpoint.
|
|
76
|
+
- Endpoints require HTTPS, except loopback HTTP for local use. Redirects are
|
|
77
|
+
rejected. TLS uses Python's normal certificate validation.
|
|
78
|
+
- Default queue capacity: 1,000 events, at most 100 events and 128 KiB per request. Queue capacity is
|
|
79
|
+
configurable from 1 to 10,000. The queue lives only in memory.
|
|
80
|
+
- Default socket timeout: 2 seconds, configurable up to 30 seconds. This bounds
|
|
81
|
+
individual socket operations, not the entire flush. Flush processes only the
|
|
82
|
+
number of events queued at entry, so concurrent producers cannot extend it
|
|
83
|
+
indefinitely.
|
|
84
|
+
- Only HTTP 429 and 503 retry, up to two retries by default (maximum three).
|
|
85
|
+
Exponential delays are bounded to one second. Retry bodies and event IDs are
|
|
86
|
+
identical so the server can deduplicate them. Transport errors and other
|
|
87
|
+
statuses are not retried. The client verifies ingestion acknowledgement counts.
|
|
88
|
+
- Default `failure_mode="drop"` drops invalid, overflowing, or unsuccessfully sent
|
|
89
|
+
events. `failure_mode="raise"` raises `SDKError`/`DeliveryError`. An attempted
|
|
90
|
+
failed batch is dropped in either mode. Raise mode leaves later batches queued.
|
|
91
|
+
- Read `client.counters`: `enqueued`, `sent`, `dropped`, `failed_batches`,
|
|
92
|
+
`retries`, and `queued`. `sent` counts acknowledged input events, including
|
|
93
|
+
deduplicated events. Errors omit response bodies and credentials.
|
|
94
|
+
- `summary()` and `incidents()` return decoded authenticated API responses;
|
|
95
|
+
read failures always raise `DeliveryError`.
|
|
96
|
+
|
|
97
|
+
This is best-effort instrumentation, not durable message delivery. Export on a
|
|
98
|
+
dedicated application worker or with `await asyncio.to_thread(client.flush)` in
|
|
99
|
+
async applications. Do not call synchronous `flush()` on a latency-sensitive event
|
|
100
|
+
loop. In-process queuing and counters are thread-safe; forked processes need their
|
|
101
|
+
own client. Drain on a controlled shutdown if losing queued observations matters.
|
|
102
|
+
|
|
103
|
+
## OpenTelemetry adapter
|
|
104
|
+
|
|
105
|
+
`from_otel_attributes(attributes, deployment_id=..., agent_id=..., outcome=...)`
|
|
106
|
+
constructs an event without exporting it or installing span processors. It maps
|
|
107
|
+
selected standard names from the [OpenTelemetry GenAI attribute registry](https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/):
|
|
108
|
+
|
|
109
|
+
| Input | Event field |
|
|
110
|
+
| --- | --- |
|
|
111
|
+
| `gen_ai.provider.name` | `provider` |
|
|
112
|
+
| `gen_ai.request.model` | `model` |
|
|
113
|
+
| `gen_ai.usage.input_tokens` / `output_tokens` | `input_tokens` / `output_tokens` |
|
|
114
|
+
| `telemetry.sdk.name` / `version` | `sdk` / `sdk_version` |
|
|
115
|
+
| `gen_ai.operation.name` | `operation`, via the fixed map below |
|
|
116
|
+
|
|
117
|
+
`chat`, `text_completion`, `generate_content`, and `embeddings` map to `model`;
|
|
118
|
+
`invoke_agent` maps to `agent`; `execute_tool` maps to `tool`. Unknown operations
|
|
119
|
+
require an explicit application mapping and raise `ValueError`.
|
|
120
|
+
|
|
121
|
+
ReliaMesh-specific extensions `reliamesh.model.version`, `reliamesh.prompt.version`,
|
|
122
|
+
`reliamesh.agent.version`, `reliamesh.framework.name`, `reliamesh.framework.version`,
|
|
123
|
+
`reliamesh.tool.name`, and `reliamesh.tool.version` map to the corresponding flat
|
|
124
|
+
event fields. These extensions are not official OpenTelemetry conventions.
|
|
125
|
+
The caller explicitly supplies outcome, failure type, duration, and synthetic
|
|
126
|
+
status. All unlisted attributes, messages, exception details, and span events are
|
|
127
|
+
ignored. Invalid allowlisted values are rejected. Never pass prompt text as a
|
|
128
|
+
version identifier.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
NOTICE
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
src/reliamesh_sdk/__init__.py
|
|
6
|
+
src/reliamesh_sdk/client.py
|
|
7
|
+
src/reliamesh_sdk/events.py
|
|
8
|
+
src/reliamesh_sdk.egg-info/PKG-INFO
|
|
9
|
+
src/reliamesh_sdk.egg-info/SOURCES.txt
|
|
10
|
+
src/reliamesh_sdk.egg-info/dependency_links.txt
|
|
11
|
+
src/reliamesh_sdk.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
reliamesh_sdk
|