mistralai-capabilities-base-core 0.1.85__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Mistral AI
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,13 @@
1
+ Metadata-Version: 2.4
2
+ Name: mistralai-capabilities-base-core
3
+ Version: 0.1.85
4
+ Summary: Core capability: duration and token metrics for the Mistral SDK's inference calls, their OTLP export, and the app's span export to Mistral Studio.
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Dist: mistralai>=3.7.0,<4
8
+ Requires-Dist: httpx2>=2.16.0
9
+ Requires-Dist: opentelemetry-api>=1.45.2
10
+ Requires-Dist: opentelemetry-sdk>=1.45.2
11
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.45.2
12
+ Requires-Dist: requests>=2.34.2
13
+ Requires-Python: >=3.12, <3.15
@@ -0,0 +1,34 @@
1
+ [project]
2
+ name = "mistralai-capabilities-base-core"
3
+ version = "0.1.85"
4
+ description = "Core capability: duration and token metrics for the Mistral SDK's inference calls, their OTLP export, and the app's span export to Mistral Studio."
5
+ requires-python = ">=3.12,<3.15"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ # Floors are the versions the registry's lock tests against. `httpx2` is imported directly: it is
9
+ # the HTTP library the SDK's hooks hand requests and responses in. `requests` is the OTLP/HTTP
10
+ # exporter's session, given the per-export bearer.
11
+ dependencies = [
12
+ "mistralai>=3.7.0,<4",
13
+ "httpx2>=2.16.0",
14
+ "opentelemetry-api>=1.45.2",
15
+ "opentelemetry-sdk>=1.45.2",
16
+ "opentelemetry-exporter-otlp-proto-http>=1.45.2",
17
+ "requests>=2.34.2",
18
+ ]
19
+
20
+ [build-system]
21
+ # uv_build 0.8 skips a `license-files` glob that matches nothing, while 0.13 fails on it. An app that
22
+ # vendors this package builds it from source, where the root LICENSE is not staged.
23
+ requires = ["uv_build>=0.8.22,<0.9.0"]
24
+ build-backend = "uv_build"
25
+
26
+ [tool.uv]
27
+ exclude-newer = "7 days"
28
+
29
+ [tool.uv.build-backend]
30
+ # The dist name is fixed by the CLI convention (= `<registry id>-<kind>-<capability id>`);
31
+ # `module-name` decouples the import path from it. `namespace = true` makes this a PEP-420
32
+ # portion so it ships only the `mistralai_capabilities.core` slice alongside sibling caps.
33
+ module-name = "mistralai_capabilities.core"
34
+ namespace = true
@@ -0,0 +1,2 @@
1
+ """Core capability library: inference metrics for Mistral SDK clients (`inference_metrics`) and
2
+ their OTLP export (`metrics`). An app reaches both through its `utils` package."""
@@ -0,0 +1,16 @@
1
+ """Whether the process has a meter provider of its own, rather than OpenTelemetry's stand-ins."""
2
+
3
+ from opentelemetry.metrics import NoOpMeterProvider, get_meter_provider
4
+
5
+
6
+ def meter_provider_installed() -> bool:
7
+ """True once a provider that records is set: the SDK's, a workflows worker's, or any other.
8
+
9
+ Until one is set, OpenTelemetry hands out a private proxy provider, and an explicit
10
+ ``NoOpMeterProvider`` records nothing either. Both are the API package's own classes, so they are
11
+ told apart by module, without importing the private proxy class.
12
+ """
13
+ provider = get_meter_provider()
14
+ return not isinstance(provider, NoOpMeterProvider) and not type(provider).__module__.startswith(
15
+ "opentelemetry.metrics"
16
+ )
@@ -0,0 +1,443 @@
1
+ """Duration and token metrics for the Mistral SDK's inference calls, which the SDK does not record.
2
+
3
+ Moderation and classification calls are out of scope: their responses carry no token usage, and the
4
+ GenAI semantic conventions name no operation for them.
5
+ """
6
+
7
+ import functools
8
+ import json
9
+ import logging
10
+ import time
11
+ import zlib
12
+ from collections.abc import AsyncIterator, Callable, Iterator, Mapping
13
+ from enum import StrEnum
14
+ from typing import Any, NamedTuple, Protocol
15
+
16
+ import httpx2 as httpx
17
+ from mistralai.client import Mistral
18
+ from opentelemetry.metrics import Histogram, MeterProvider, get_meter
19
+
20
+ from ._meter_provider import meter_provider_installed
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ class _MistralInferenceCallType(StrEnum):
26
+ CHAT = "chat"
27
+ TEXT_COMPLETION = "text_completion"
28
+ EMBEDDINGS = "embeddings"
29
+ INVOKE_AGENT = "invoke_agent"
30
+ GENERATE_CONTENT = "generate_content"
31
+
32
+
33
+ _OPERATIONS: Mapping[str, _MistralInferenceCallType] = {
34
+ "chat_completion_v1_chat_completions_post": _MistralInferenceCallType.CHAT,
35
+ "stream_chat": _MistralInferenceCallType.CHAT,
36
+ "fim_completion_v1_fim_completions_post": _MistralInferenceCallType.TEXT_COMPLETION,
37
+ "stream_fim": _MistralInferenceCallType.TEXT_COMPLETION,
38
+ "embeddings_v1_embeddings_post": _MistralInferenceCallType.EMBEDDINGS,
39
+ "agents_completion_v1_agents_completions_post": _MistralInferenceCallType.INVOKE_AGENT,
40
+ "stream_agents": _MistralInferenceCallType.INVOKE_AGENT,
41
+ "agents_api_v1_conversations_start": _MistralInferenceCallType.INVOKE_AGENT,
42
+ "agents_api_v1_conversations_start_stream": _MistralInferenceCallType.INVOKE_AGENT,
43
+ "agents_api_v1_conversations_append": _MistralInferenceCallType.INVOKE_AGENT,
44
+ "agents_api_v1_conversations_append_stream": _MistralInferenceCallType.INVOKE_AGENT,
45
+ "agents_api_v1_conversations_restart": _MistralInferenceCallType.INVOKE_AGENT,
46
+ "agents_api_v1_conversations_restart_stream": _MistralInferenceCallType.INVOKE_AGENT,
47
+ "ocr_v1_ocr_post": _MistralInferenceCallType.GENERATE_CONTENT,
48
+ "audio_api_v1_transcriptions_post": _MistralInferenceCallType.GENERATE_CONTENT,
49
+ "audio_api_v1_transcriptions_post_stream": _MistralInferenceCallType.GENERATE_CONTENT,
50
+ "speech_v1_audio_speech_post": _MistralInferenceCallType.GENERATE_CONTENT,
51
+ }
52
+
53
+ _USAGE_KEYS = (("input", "prompt_tokens"), ("output", "completion_tokens"))
54
+
55
+ _CALL_KEY = "_inference_metrics_call"
56
+
57
+ _DEFAULT_PORTS = {"https": 443, "http": 80}
58
+
59
+
60
+ class _Instruments(NamedTuple):
61
+ duration: Histogram
62
+ token_usage: Histogram
63
+
64
+
65
+ def _instruments(meter_provider: MeterProvider | None) -> _Instruments:
66
+ meter = get_meter("mistralai_capabilities.core", meter_provider=meter_provider)
67
+ # OTel GenAI semconv names and buckets; the Python semconv package's copies are deprecated.
68
+ return _Instruments(
69
+ meter.create_histogram(
70
+ "gen_ai.client.operation.duration",
71
+ unit="s",
72
+ description="GenAI operation duration.",
73
+ explicit_bucket_boundaries_advisory=[0.01 * 2**i for i in range(14)],
74
+ ),
75
+ meter.create_histogram(
76
+ "gen_ai.client.token.usage",
77
+ unit="{token}",
78
+ description="Number of input and output tokens used.",
79
+ explicit_bucket_boundaries_advisory=[4**i for i in range(14)],
80
+ ),
81
+ )
82
+
83
+
84
+ @functools.cache
85
+ def _global_instruments() -> _Instruments:
86
+ """The global provider's instruments, built once for every client rather than a meter per client."""
87
+ return _instruments(None)
88
+
89
+
90
+ class _MistralInferenceCall(NamedTuple):
91
+ instruments: _Instruments
92
+ operation: _MistralInferenceCallType
93
+ request_model: str | None
94
+ server_address: str
95
+ server_port: int | None
96
+ started: float
97
+
98
+
99
+ def _json_object(content: bytes) -> Mapping[str, Any] | None:
100
+ try:
101
+ value = json.loads(content)
102
+ except ValueError:
103
+ return None
104
+ return value if isinstance(value, Mapping) else None
105
+
106
+
107
+ def _request_model(request: httpx.Request) -> str | None:
108
+ # A transcription uploads its audio as a multipart form, whose body is a stream: read the model from
109
+ # the form's fields rather than the body, so the upload is not buffered.
110
+ for field in getattr(request.stream, "fields", ()):
111
+ if getattr(field, "name", None) == "model":
112
+ value = getattr(field, "value", None)
113
+ return value if isinstance(value, str) else None
114
+ if not isinstance(request.stream, httpx.ByteStream):
115
+ return None
116
+ body = _json_object(request.content)
117
+ model = body.get("model") if body is not None else None
118
+ return model if isinstance(model, str) else None
119
+
120
+
121
+ def _keep_model_and_usage(summary: dict[str, Any], line: bytes) -> None:
122
+ # Usage comes on the last events only.
123
+ if not line.startswith(b"data:"):
124
+ return
125
+ event = _json_object(line.removeprefix(b"data:").strip())
126
+ if event is not None:
127
+ summary.update({key: event[key] for key in ("model", "usage") if event.get(key)})
128
+
129
+
130
+ def _deflate_decoder() -> Callable[[bytes], bytes]:
131
+ """Zlib-wrapped deflate, or raw deflate when the start is not zlib, the fallback httpx's decoder makes.
132
+
133
+ httpx retries the first chunk alone; this keeps every chunk until zlib yields output, so the fallback
134
+ also holds when the two-byte zlib header check spans chunks.
135
+ """
136
+ decompressor = zlib.decompressobj()
137
+ unconfirmed: bytearray | None = bytearray()
138
+
139
+ def decode(chunk: bytes) -> bytes:
140
+ nonlocal decompressor, unconfirmed
141
+ if unconfirmed is None:
142
+ return decompressor.decompress(chunk)
143
+ unconfirmed += chunk
144
+ try:
145
+ decoded = decompressor.decompress(chunk)
146
+ except zlib.error:
147
+ decompressor = zlib.decompressobj(-zlib.MAX_WBITS)
148
+ decoded = decompressor.decompress(bytes(unconfirmed))
149
+ unconfirmed = None
150
+ return decoded
151
+ if decoded:
152
+ unconfirmed = None
153
+ return decoded
154
+
155
+ return decode
156
+
157
+
158
+ def _decoder(content_encoding: str) -> Callable[[bytes], bytes] | None:
159
+ """Decode the raw chunks as httpx would; None for an encoding the recorder does not read."""
160
+ encoding = content_encoding.strip().lower()
161
+ if encoding in ("", "identity"):
162
+ return lambda chunk: chunk
163
+ if encoding == "gzip":
164
+ return zlib.decompressobj(zlib.MAX_WBITS | 32).decompress
165
+ if encoding == "deflate":
166
+ return _deflate_decoder()
167
+ return None
168
+
169
+
170
+ def _is_done(line: bytes) -> bool:
171
+ return line.startswith(b"data:") and line.removeprefix(b"data:").strip() == b"[DONE]"
172
+
173
+
174
+ class _StreamUsageRecorder(httpx.SyncByteStream, httpx.AsyncByteStream):
175
+ """A streamed response's body that records the call when it closes after its end, or fails while read.
176
+
177
+ Streams report usage in their last events only, so events are parsed as they pass, keeping the latest
178
+ model and usage. The end is the first of: an event carrying usage (every stream's last event does),
179
+ the ``[DONE]`` event, after which the SDK stops reading, and the end of the body. A stream closed
180
+ before its end, cancelled or left by its reader, is neither a success nor an error: it records
181
+ nothing, as for a call cancelled before its response, which reaches no hook.
182
+ """
183
+
184
+ def __init__(
185
+ self, stream: httpx.SyncByteStream | httpx.AsyncByteStream, call: _MistralInferenceCall, content_encoding: str
186
+ ) -> None:
187
+ self._stream = stream
188
+ self._call: _MistralInferenceCall | None = call
189
+ self._summary: dict[str, Any] = {}
190
+ self._partial_line = b""
191
+ self._decode = _decoder(content_encoding)
192
+ # Whether the body was read to its end or to ``[DONE]``; ``_finish`` decides whether it ended.
193
+ self._complete = False
194
+
195
+ def __iter__(self) -> Iterator[bytes]:
196
+ if not isinstance(self._stream, httpx.SyncByteStream):
197
+ raise RuntimeError("Attempted to call a sync iterator on an async stream.")
198
+ try:
199
+ for chunk in self._stream:
200
+ self._read(chunk)
201
+ yield chunk
202
+ except Exception as error:
203
+ self._finish(error)
204
+ raise
205
+ self._complete = True
206
+
207
+ async def __aiter__(self) -> AsyncIterator[bytes]:
208
+ if not isinstance(self._stream, httpx.AsyncByteStream):
209
+ raise RuntimeError("Attempted to call an async iterator on a sync stream.")
210
+ try:
211
+ async for chunk in self._stream:
212
+ self._read(chunk)
213
+ yield chunk
214
+ except Exception as error:
215
+ self._finish(error)
216
+ raise
217
+ self._complete = True
218
+
219
+ def _read(self, raw: bytes) -> None:
220
+ if self._decode is None:
221
+ return
222
+ try:
223
+ chunk = self._decode(raw)
224
+ except zlib.error:
225
+ self._decode = None
226
+ return
227
+ # SSE lines end in \n, \r or \r\n; a final \r may be half of a \r\n split across chunks.
228
+ lines = (self._partial_line + chunk).splitlines(keepends=True)
229
+ self._partial_line = lines.pop() if lines and not lines[-1].endswith(b"\n") else b""
230
+ for line in lines:
231
+ self._complete = self._complete or _is_done(line)
232
+ _keep_model_and_usage(self._summary, line)
233
+
234
+ def close(self) -> None:
235
+ self._finish()
236
+ if isinstance(self._stream, httpx.SyncByteStream):
237
+ self._stream.close()
238
+
239
+ async def aclose(self) -> None:
240
+ self._finish()
241
+ if isinstance(self._stream, httpx.AsyncByteStream):
242
+ await self._stream.aclose()
243
+
244
+ def _finish(self, error: BaseException | None = None) -> None:
245
+ """Record the call once: on the first read error, or else when the stream closes after its end."""
246
+ call, self._call = self._call, None
247
+ if call is None:
248
+ return
249
+ try:
250
+ _keep_model_and_usage(self._summary, self._partial_line)
251
+ # Closed before its end: nothing. A body the recorder cannot decode cannot show its end, so
252
+ # its close counts as the end.
253
+ ended = self._complete or "usage" in self._summary or self._decode is None
254
+ if error is None and not ended:
255
+ return
256
+ _record_call_metrics(call, self._summary, None if error is None else type(error).__qualname__)
257
+ except Exception:
258
+ logger.warning("Failed to record inference metrics for a streamed response", exc_info=True)
259
+
260
+
261
+ def _record_call_metrics(
262
+ call: _MistralInferenceCall, body: Mapping[str, Any] | None, error_type: str | None = None
263
+ ) -> None:
264
+ """Record a finished call's duration, and its input and output tokens when ``body`` has usage."""
265
+ attributes: dict[str, str | int] = {
266
+ "gen_ai.operation.name": call.operation,
267
+ "gen_ai.provider.name": "mistral_ai",
268
+ "server.address": call.server_address,
269
+ }
270
+ if call.server_port is not None:
271
+ attributes["server.port"] = call.server_port
272
+ if call.request_model:
273
+ attributes["gen_ai.request.model"] = call.request_model
274
+ if body is not None and isinstance(response_model := body.get("model"), str) and response_model:
275
+ attributes["gen_ai.response.model"] = response_model
276
+ if error_type is not None:
277
+ attributes["error.type"] = error_type
278
+ call.instruments.duration.record(time.perf_counter() - call.started, attributes)
279
+
280
+ usage = body.get("usage") if body is not None else None
281
+ if not isinstance(usage, Mapping):
282
+ return
283
+ for token_type, key in _USAGE_KEYS:
284
+ tokens = usage.get(key)
285
+ if isinstance(tokens, int) and not (token_type == "output" and tokens == 0):
286
+ call.instruments.token_usage.record(tokens, {**attributes, "gen_ai.token.type": token_type})
287
+
288
+
289
+ def _call_of(request: httpx.Request | None) -> _MistralInferenceCall | None:
290
+ # None also once the call is recorded: the key stays, so a later attempt does not start a new call.
291
+ return None if request is None else request.extensions.get(_CALL_KEY)
292
+
293
+
294
+ def _failed_request(error: Exception | None) -> httpx.Request | None:
295
+ # Duck-typed, as the SDK's transport-error test is: a client that is not httpx2's raises its own errors.
296
+ # Its ``request`` may raise (httpx's own does without a request), and the call's error must stand.
297
+ try:
298
+ request = getattr(error, "request", None)
299
+ except Exception:
300
+ return None
301
+ return request if isinstance(getattr(request, "extensions", None), dict) else None
302
+
303
+
304
+ class _HookContext(Protocol):
305
+ operation_id: str
306
+
307
+
308
+ _TRANSPORT_ERROR_NAMES = frozenset({"NetworkError", "TimeoutException"})
309
+ _TRANSPORT_ERROR_BASES = frozenset({"TransportError", "RequestError", "HTTPError"})
310
+
311
+
312
+ def _is_transport_error(error: BaseException | None) -> bool:
313
+ """The SDK's own test (``mistralai.client.utils.retries._is_transport_error``, private, so copied).
314
+
315
+ Besides httpx2's classes, it matches by class name, for a client whose transport raises its own.
316
+ """
317
+ if isinstance(error, (httpx.NetworkError, httpx.TimeoutException)):
318
+ return True
319
+ names = {base.__name__ for base in type(error).__mro__}
320
+ return bool(names & _TRANSPORT_ERROR_NAMES) and _TRANSPORT_ERROR_BASES <= names
321
+
322
+
323
+ # The SDK times its budget from just before the first attempt's hooks and rounds to the millisecond, so
324
+ # its elapsed time runs slightly ahead of the call's. Within this margin of the budget the SDK may give
325
+ # up where the hook would wait, and the call's last failure would go unrecorded; the hook records it
326
+ # instead. The cost is the rare call retried within the margin that then recovers: it is recorded by
327
+ # that failure, not by its success.
328
+ _BUDGET_MARGIN_MS = 100
329
+
330
+
331
+ def _will_retry(hook_ctx: _HookContext, error: Exception | None, call: _MistralInferenceCall) -> bool:
332
+ """Whether the SDK retries the call after this transport error, by the rule of its retry loop.
333
+
334
+ The hook sees the client's retry config only, not a per-call ``retries=`` override: a call whose
335
+ override gives up sooner goes unrecorded, and one whose override retries when the client's config
336
+ does not is recorded by its first error only. Near the end of the budget the answer is no (see
337
+ ``_BUDGET_MARGIN_MS``), so the client's final failure is recorded.
338
+ """
339
+ config = getattr(getattr(hook_ctx, "config", None), "retry_config", None)
340
+ if getattr(config, "strategy", None) != "backoff" or not getattr(config, "retry_connection_errors", False):
341
+ return False
342
+ if not _is_transport_error(error):
343
+ return False
344
+ max_elapsed_ms = getattr(getattr(config, "backoff", None), "max_elapsed_time", None)
345
+ # The SDK compares the budget as a number, so a float one counts too.
346
+ if not isinstance(max_elapsed_ms, (int, float)) or isinstance(max_elapsed_ms, bool):
347
+ return False
348
+ return (time.perf_counter() - call.started) * 1000 + _BUDGET_MARGIN_MS <= max_elapsed_ms
349
+
350
+
351
+ # Duck-typed rather than subclassing the SDK's private hook types, so an SDK that moves them still imports.
352
+ class _InferenceMetricsHook:
353
+ def __init__(self, instruments: Callable[[], _Instruments | None]) -> None:
354
+ # None while there is nothing to record to.
355
+ self._instruments = instruments
356
+
357
+ def before_request(self, hook_ctx: _HookContext, request: httpx.Request) -> httpx.Request:
358
+ operation = _OPERATIONS.get(hook_ctx.operation_id)
359
+ # One point per call: a retry reuses the request and its call, so duration spans all attempts.
360
+ if operation is None or _CALL_KEY in request.extensions:
361
+ return request
362
+ try:
363
+ # With no provider to export to, nothing is recorded, so no request or response body is read.
364
+ instruments = self._instruments()
365
+ if instruments is None:
366
+ return request
367
+ port = request.url.port
368
+ request.extensions[_CALL_KEY] = _MistralInferenceCall(
369
+ instruments,
370
+ operation,
371
+ _request_model(request),
372
+ request.url.host,
373
+ port if port is not None else _DEFAULT_PORTS.get(request.url.scheme),
374
+ time.perf_counter(),
375
+ )
376
+ except Exception:
377
+ logger.warning("Failed to start inference metrics for a request", exc_info=True)
378
+ return request
379
+
380
+ def after_success(self, hook_ctx: _HookContext, response: httpx.Response) -> httpx.Response:
381
+ call = _call_of(response.request)
382
+ if call is None:
383
+ return response
384
+ try:
385
+ if not response.is_closed and not response.is_stream_consumed:
386
+ encoding = response.headers.get("content-encoding", "")
387
+ response.stream = _StreamUsageRecorder(response.stream, call, encoding)
388
+ return response
389
+ _record_call_metrics(call, _json_object(response.content))
390
+ except Exception:
391
+ logger.warning("Failed to record inference metrics for a response", exc_info=True)
392
+ return response
393
+
394
+ def after_error(
395
+ self, hook_ctx: _HookContext, response: httpx.Response | None, error: Exception | None
396
+ ) -> tuple[httpx.Response | None, Exception | None]:
397
+ request = response.request if response is not None else _failed_request(error)
398
+ call = _call_of(request)
399
+ if request is None or call is None:
400
+ return response, error
401
+ try:
402
+ # A transport error the SDK retries is recorded by the attempt that ends the call. A status code
403
+ # is passed here once, after the SDK's retries.
404
+ if response is None and _will_retry(hook_ctx, error, call):
405
+ return response, error
406
+ request.extensions[_CALL_KEY] = None
407
+ error_type = str(response.status_code) if response is not None else type(error).__qualname__
408
+ _record_call_metrics(call, None, error_type)
409
+ except Exception:
410
+ logger.warning("Failed to record inference metrics for a failed call", exc_info=True)
411
+ return response, error
412
+
413
+
414
+ def _installed_global_instruments() -> _Instruments | None:
415
+ return _global_instruments() if meter_provider_installed() else None
416
+
417
+
418
+ def instrument(client: Mistral, meter_provider: MeterProvider | None = None) -> Mistral:
419
+ """Record inference metrics for ``client``'s calls, via the global meter provider by default.
420
+
421
+ ``meter_provider`` is for tests; calls record nothing until a provider is passed or installed.
422
+
423
+ Retries come from the client's ``RetryConfig`` only: a per-call ``retries=`` override is not
424
+ supported. The hook sees the client's config, not the override, so it cannot tell which transport
425
+ error ends such a call: one that gives up sooner goes unrecorded, and one that retries when the
426
+ client does not is recorded at its first error. Build a client with the retry policy instead.
427
+
428
+ The SDK has no public per-client hook API, so this reaches where it keeps its own hooks; on an SDK
429
+ that keeps them elsewhere, the client is returned uninstrumented.
430
+ """
431
+ try:
432
+ hooks = client.sdk_configuration.__dict__["_hooks"]
433
+ if meter_provider is None:
434
+ hook = _InferenceMetricsHook(_installed_global_instruments)
435
+ else:
436
+ fixed = _instruments(meter_provider)
437
+ hook = _InferenceMetricsHook(lambda: fixed)
438
+ hooks.register_before_request_hook(hook)
439
+ hooks.register_after_success_hook(hook)
440
+ hooks.register_after_error_hook(hook)
441
+ except Exception:
442
+ logger.warning("Inference metrics are off: this mistralai version keeps its hooks elsewhere", exc_info=True)
443
+ return client
@@ -0,0 +1,56 @@
1
+ """OTLP export of the app's metrics. A provider already installed (a workflows worker's, or any other) is kept."""
2
+
3
+ from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
4
+ from opentelemetry.metrics import NoOpMeterProvider, get_meter_provider, set_meter_provider
5
+ from opentelemetry.sdk.metrics import MeterProvider
6
+ from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
7
+ from opentelemetry.sdk.resources import Resource
8
+
9
+ from ._meter_provider import meter_provider_installed
10
+
11
+ _MILLISECONDS = 1000
12
+
13
+ _provider: MeterProvider | None = None
14
+ # OpenTelemetry keeps a stopped provider installed and refuses a replacement, so export is once per process.
15
+ _shut_down = False
16
+
17
+
18
+ def configure_metrics(
19
+ *,
20
+ endpoint: str | None,
21
+ service_name: str,
22
+ export_interval_seconds: float = 60.0,
23
+ export_timeout_seconds: float = 5.0,
24
+ ) -> bool:
25
+ """Install the exporter to ``endpoint`` + ``/v1/metrics``; returns whether metrics are exported."""
26
+ global _provider
27
+ if _shut_down:
28
+ return False
29
+ if _provider is not None or meter_provider_installed():
30
+ return True
31
+ if not endpoint or isinstance(get_meter_provider(), NoOpMeterProvider):
32
+ return False
33
+
34
+ reader = PeriodicExportingMetricReader(
35
+ OTLPMetricExporter(endpoint=f"{endpoint.rstrip('/')}/v1/metrics"),
36
+ export_interval_millis=export_interval_seconds * _MILLISECONDS,
37
+ export_timeout_millis=export_timeout_seconds * _MILLISECONDS,
38
+ )
39
+ provider = MeterProvider(resource=Resource.create({"service.name": service_name}), metric_readers=[reader])
40
+ set_meter_provider(provider)
41
+ if get_meter_provider() is not provider:
42
+ # OpenTelemetry refused it: another provider (a NoOp one, or one set meanwhile) is installed for good.
43
+ provider.shutdown()
44
+ return meter_provider_installed()
45
+ _provider = provider
46
+ return True
47
+
48
+
49
+ def shutdown_metrics() -> None:
50
+ """Flush and stop the exporter this module installed; it cannot be configured again afterwards."""
51
+ global _provider, _shut_down
52
+ if _provider is None:
53
+ return
54
+ _provider.shutdown()
55
+ _provider = None
56
+ _shut_down = True
@@ -0,0 +1,116 @@
1
+ """OTLP export of the app's spans to Mistral Studio. A provider already installed (a workflows worker's) is kept."""
2
+
3
+ import logging
4
+ import os
5
+ import re
6
+ from collections.abc import Callable
7
+
8
+ import requests
9
+ from mistralai.extra.observability import RedactingSpanExporter
10
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
11
+ from opentelemetry.sdk.resources import Resource
12
+ from opentelemetry.sdk.trace import TracerProvider
13
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
14
+ from opentelemetry.trace import NoOpTracerProvider, ProxyTracerProvider, get_tracer_provider, set_tracer_provider
15
+
16
+ _MILLISECONDS = 1000
17
+ # Visible ASCII: anything else (a newline, a non-latin-1 character) makes http.client raise with the
18
+ # whole header value in its message, which the span processor then logs on every export.
19
+ _BEARER_TOKEN = re.compile(r"[\x21-\x7e]+")
20
+ SDK_TELEMETRY = "MISTRAL_SDK_TELEMETRY"
21
+ # The Mistral SDK's own traces URL, which observability declares; read from the environment, as the SDK does.
22
+ TRACES_ENDPOINT = "MISTRAL_OTLP_TRACES_ENDPOINT"
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ _provider: TracerProvider | None = None
27
+ # OpenTelemetry keeps a stopped provider installed and refuses a replacement, so export is once per process.
28
+ _shut_down = False
29
+
30
+
31
+ def tracer_provider_installed() -> bool:
32
+ """True once a provider that records is set, rather than OpenTelemetry's proxy or an explicit NoOp one."""
33
+ return not isinstance(get_tracer_provider(), NoOpTracerProvider | ProxyTracerProvider)
34
+
35
+
36
+ class _BearerAuth(requests.auth.AuthBase):
37
+ # Asked on every export: a deployed worker's token file rotates under the running process.
38
+ def __init__(self, token: Callable[[], str]) -> None:
39
+ self._token = token
40
+
41
+ def __call__(self, request: requests.PreparedRequest) -> requests.PreparedRequest:
42
+ # A secretKeyRef passes the key verbatim, trailing newline included; the token file is stripped too.
43
+ token = self._token().strip()
44
+ if not _BEARER_TOKEN.fullmatch(token):
45
+ raise ValueError("The app credential is not a valid bearer token; spans were not exported.")
46
+ request.headers["Authorization"] = f"Bearer {token}"
47
+ return request
48
+
49
+
50
+ def _sdk_telemetry_dedicated() -> bool:
51
+ # In `dedicated` mode the Mistral SDK sees any installed provider, skips its own and then emits no
52
+ # span at all. Off (`false`, unset) is off by choice, and `global` already joins the provider.
53
+ return os.environ.get(SDK_TELEMETRY, "").strip().lower() == "dedicated"
54
+
55
+
56
+ def configure_tracing(
57
+ *,
58
+ endpoint: str | None,
59
+ service_name: str,
60
+ token: Callable[[], str],
61
+ export_timeout_seconds: float = 5.0,
62
+ ) -> bool:
63
+ """Install a redacting OTLP/HTTP exporter to ``endpoint``, the full traces URL; returns whether spans export.
64
+
65
+ ``token`` returns the bearer Studio ingests under, and is called on every export. A process
66
+ that already has a provider keeps it, and its SDK telemetry mode is left as configured: in
67
+ ``dedicated`` mode the SDK then records no span, which is logged as a warning.
68
+ """
69
+ global _provider
70
+ if _shut_down:
71
+ return False
72
+ if _provider is not None:
73
+ return True
74
+ if tracer_provider_installed():
75
+ # The SDK is not moved onto a provider this module did not install: its exporter may not redact.
76
+ if _sdk_telemetry_dedicated():
77
+ logger.warning(
78
+ "An OpenTelemetry tracer provider was installed before configure_tracing, so the Mistral SDK "
79
+ "records no spans: in MISTRAL_SDK_TELEMETRY=dedicated mode it disables itself under another "
80
+ "provider. Set MISTRAL_SDK_TELEMETRY=global to send them to that provider, unredacted unless "
81
+ "its exporter is wrapped in RedactingSpanExporter."
82
+ )
83
+ return True
84
+ if not endpoint or isinstance(get_tracer_provider(), NoOpTracerProvider):
85
+ return False
86
+
87
+ session = requests.Session()
88
+ session.auth = _BearerAuth(token)
89
+ exporter = OTLPSpanExporter(endpoint=endpoint, session=session, timeout=export_timeout_seconds)
90
+ provider = TracerProvider(resource=Resource.create({"service.name": service_name}))
91
+ provider.add_span_processor(
92
+ BatchSpanProcessor(
93
+ RedactingSpanExporter(exporter), export_timeout_millis=export_timeout_seconds * _MILLISECONDS
94
+ )
95
+ )
96
+ set_tracer_provider(provider)
97
+ if get_tracer_provider() is not provider:
98
+ # OpenTelemetry refused it: another provider (a NoOp one, or one set meanwhile) is installed for good.
99
+ provider.shutdown()
100
+ return tracer_provider_installed()
101
+ _provider = provider
102
+ # `global` sends the SDK's spans here, nested in the request's, through the same redaction
103
+ # `dedicated` applies.
104
+ if _sdk_telemetry_dedicated():
105
+ os.environ[SDK_TELEMETRY] = "global"
106
+ return True
107
+
108
+
109
+ def shutdown_tracing() -> None:
110
+ """Flush and stop the exporter this module installed; it cannot be configured again afterwards."""
111
+ global _provider, _shut_down
112
+ if _provider is None:
113
+ return
114
+ _provider.shutdown()
115
+ _provider = None
116
+ _shut_down = True