openinference-instrumentation-typesafe 0.1.1__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.
- openinference_instrumentation_typesafe-0.1.1/LICENSE +201 -0
- openinference_instrumentation_typesafe-0.1.1/PKG-INFO +121 -0
- openinference_instrumentation_typesafe-0.1.1/README.md +90 -0
- openinference_instrumentation_typesafe-0.1.1/pyproject.toml +97 -0
- openinference_instrumentation_typesafe-0.1.1/src/openinference/instrumentation/typesafe/__init__.py +72 -0
- openinference_instrumentation_typesafe-0.1.1/src/openinference/instrumentation/typesafe/_attributes.py +166 -0
- openinference_instrumentation_typesafe-0.1.1/src/openinference/instrumentation/typesafe/_wrappers.py +128 -0
- openinference_instrumentation_typesafe-0.1.1/src/openinference/instrumentation/typesafe/version.py +1 -0
|
@@ -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 The OpenInference Authors
|
|
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,121 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: openinference-instrumentation-typesafe
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: OpenInference TypeSafe AI Instrumentation
|
|
5
|
+
Project-URL: Homepage, https://github.com/Arize-ai/openinference/tree/main/python/instrumentation/openinference-instrumentation-typesafe
|
|
6
|
+
Author-email: OpenInference Authors <oss@arize.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Programming Language :: Python
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Requires-Python: <3.15,>=3.10
|
|
20
|
+
Requires-Dist: msgspec
|
|
21
|
+
Requires-Dist: openinference-instrumentation>=0.1.61
|
|
22
|
+
Requires-Dist: openinference-semantic-conventions>=0.1.37
|
|
23
|
+
Requires-Dist: opentelemetry-api
|
|
24
|
+
Requires-Dist: opentelemetry-instrumentation
|
|
25
|
+
Requires-Dist: opentelemetry-semantic-conventions
|
|
26
|
+
Requires-Dist: typing-extensions
|
|
27
|
+
Requires-Dist: wrapt
|
|
28
|
+
Provides-Extra: instruments
|
|
29
|
+
Requires-Dist: typesafe-sdk>=0.6.0; extra == 'instruments'
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# OpenInference TypeSafe AI Instrumentation
|
|
33
|
+
|
|
34
|
+
[](https://pypi.org/project/openinference-instrumentation-typesafe/)
|
|
35
|
+
|
|
36
|
+
Python auto-instrumentation library for the [TypeSafe AI](https://docs.typesafe.ai/) Python SDK ([`typesafe-sdk`](https://pypi.org/project/typesafe-sdk/)).
|
|
37
|
+
|
|
38
|
+
Calls to `TypeSafeClient.system_one` and `AsyncTypeSafeClient.system_one` are traced and exported as OpenInference LLM spans. A System One request sends a `state` plus a map of typed `questions` (Noul, Choice, Score) and returns one typed `answer` per question, so the span records:
|
|
39
|
+
|
|
40
|
+
- `input.value`: the request body (`state`, `model`, `questions`) as JSON
|
|
41
|
+
- `llm.invocation_parameters`: the call configuration, meaning the `model` and any `extra_body` fields
|
|
42
|
+
- `output.value`: the response body (`model`, `answers`, `usage`) as JSON
|
|
43
|
+
- `llm.request.model_name` (for example `jev-latest`) and `llm.response.model_name` (the resolved model, for example `jev-1.13.0`)
|
|
44
|
+
- `llm.token_count.prompt`, `llm.token_count.completion`, and `llm.token_count.total`
|
|
45
|
+
|
|
46
|
+
A System One call is not a chat exchange, so the `state` and the `answers` are recorded only as `input.value` and `output.value`, not as `llm.input_messages` / `llm.output_messages`.
|
|
47
|
+
|
|
48
|
+
The `state` and the `questions` are recorded only in `input.value`, so `TraceConfig(hide_inputs=True)` keeps the whole request — caller data and question instructions alike — off the span, and `hide_outputs=True` does the same for the answers. `llm.invocation_parameters` holds no request content, only the model and any `extra_body` fields; mask it with `hide_llm_invocation_parameters` if those are sensitive.
|
|
49
|
+
|
|
50
|
+
These traces are fully OpenTelemetry compatible and can be sent to an OpenTelemetry collector for viewing, such as [Arize Phoenix](https://github.com/Arize-ai/phoenix) or [Arize AX](https://arize.com/products/ax?utm_source=docs&utm_medium=web&utm_content=openinference).
|
|
51
|
+
|
|
52
|
+
## Supported Features
|
|
53
|
+
|
|
54
|
+
- Synchronous and asynchronous clients (`TypeSafeClient` and `AsyncTypeSafeClient`)
|
|
55
|
+
- All three question primitives, passed as SDK objects or raw dictionaries
|
|
56
|
+
- Suppressing tracing via `suppress_tracing()`
|
|
57
|
+
- Context attribute propagation (`using_session`, `using_user`, `using_attributes`, metadata, tags)
|
|
58
|
+
- Sensitive-data masking via `TraceConfig` (e.g. `hide_inputs`, `hide_outputs`)
|
|
59
|
+
|
|
60
|
+
Requires `typesafe-sdk >= 0.6.0`.
|
|
61
|
+
|
|
62
|
+
## Installation
|
|
63
|
+
|
|
64
|
+
```shell
|
|
65
|
+
pip install openinference-instrumentation-typesafe
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Quickstart
|
|
69
|
+
|
|
70
|
+
```shell
|
|
71
|
+
pip install openinference-instrumentation-typesafe typesafe-sdk arize-phoenix opentelemetry-sdk opentelemetry-exporter-otlp
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Start [Phoenix](https://github.com/Arize-ai/phoenix) as a collector (default `http://localhost:6006`), then:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
|
78
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
79
|
+
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
|
80
|
+
|
|
81
|
+
from openinference.instrumentation.typesafe import TypeSafeAIInstrumentor
|
|
82
|
+
|
|
83
|
+
endpoint = "http://127.0.0.1:6006/v1/traces"
|
|
84
|
+
tracer_provider = TracerProvider()
|
|
85
|
+
tracer_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint)))
|
|
86
|
+
|
|
87
|
+
TypeSafeAIInstrumentor().instrument(tracer_provider=tracer_provider)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Make a System One call. Set the `TYPESAFE_API_KEY` environment variable with your key.
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
from typesafe_sdk import Choice, Noul, Score, TypeSafeClient
|
|
94
|
+
|
|
95
|
+
client = TypeSafeClient()
|
|
96
|
+
response = client.system_one(
|
|
97
|
+
state={"document": "I was charged twice. Please fix this ASAP."},
|
|
98
|
+
questions={
|
|
99
|
+
"billing": Noul(instructions="Is this ticket about billing?"),
|
|
100
|
+
"tone": Choice(
|
|
101
|
+
instructions="What is the customer's tone?",
|
|
102
|
+
criteria={"calm": None, "frustrated": None, "angry": None},
|
|
103
|
+
),
|
|
104
|
+
"urgency": Score(
|
|
105
|
+
instructions="How urgent is this ticket?",
|
|
106
|
+
criteria=["can wait", "this week", "today"],
|
|
107
|
+
),
|
|
108
|
+
},
|
|
109
|
+
)
|
|
110
|
+
print(response.nouls["billing"].noul)
|
|
111
|
+
print(response.choices["tone"].choice)
|
|
112
|
+
print(response.scores["urgency"].score)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Runnable examples, including async usage and context attributes, are in the [`examples/`](./examples) directory.
|
|
116
|
+
|
|
117
|
+
## More Info
|
|
118
|
+
|
|
119
|
+
- [More info on OpenInference and Phoenix](https://docs.arize.com/phoenix)
|
|
120
|
+
- [How to customize spans to track sessions, metadata, etc.](https://github.com/Arize-ai/openinference/tree/main/python/openinference-instrumentation#customizing-spans)
|
|
121
|
+
- [How to account for private information and span payload customization](https://github.com/Arize-ai/openinference/tree/main/python/openinference-instrumentation#tracing-configuration)
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# OpenInference TypeSafe AI Instrumentation
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/openinference-instrumentation-typesafe/)
|
|
4
|
+
|
|
5
|
+
Python auto-instrumentation library for the [TypeSafe AI](https://docs.typesafe.ai/) Python SDK ([`typesafe-sdk`](https://pypi.org/project/typesafe-sdk/)).
|
|
6
|
+
|
|
7
|
+
Calls to `TypeSafeClient.system_one` and `AsyncTypeSafeClient.system_one` are traced and exported as OpenInference LLM spans. A System One request sends a `state` plus a map of typed `questions` (Noul, Choice, Score) and returns one typed `answer` per question, so the span records:
|
|
8
|
+
|
|
9
|
+
- `input.value`: the request body (`state`, `model`, `questions`) as JSON
|
|
10
|
+
- `llm.invocation_parameters`: the call configuration, meaning the `model` and any `extra_body` fields
|
|
11
|
+
- `output.value`: the response body (`model`, `answers`, `usage`) as JSON
|
|
12
|
+
- `llm.request.model_name` (for example `jev-latest`) and `llm.response.model_name` (the resolved model, for example `jev-1.13.0`)
|
|
13
|
+
- `llm.token_count.prompt`, `llm.token_count.completion`, and `llm.token_count.total`
|
|
14
|
+
|
|
15
|
+
A System One call is not a chat exchange, so the `state` and the `answers` are recorded only as `input.value` and `output.value`, not as `llm.input_messages` / `llm.output_messages`.
|
|
16
|
+
|
|
17
|
+
The `state` and the `questions` are recorded only in `input.value`, so `TraceConfig(hide_inputs=True)` keeps the whole request — caller data and question instructions alike — off the span, and `hide_outputs=True` does the same for the answers. `llm.invocation_parameters` holds no request content, only the model and any `extra_body` fields; mask it with `hide_llm_invocation_parameters` if those are sensitive.
|
|
18
|
+
|
|
19
|
+
These traces are fully OpenTelemetry compatible and can be sent to an OpenTelemetry collector for viewing, such as [Arize Phoenix](https://github.com/Arize-ai/phoenix) or [Arize AX](https://arize.com/products/ax?utm_source=docs&utm_medium=web&utm_content=openinference).
|
|
20
|
+
|
|
21
|
+
## Supported Features
|
|
22
|
+
|
|
23
|
+
- Synchronous and asynchronous clients (`TypeSafeClient` and `AsyncTypeSafeClient`)
|
|
24
|
+
- All three question primitives, passed as SDK objects or raw dictionaries
|
|
25
|
+
- Suppressing tracing via `suppress_tracing()`
|
|
26
|
+
- Context attribute propagation (`using_session`, `using_user`, `using_attributes`, metadata, tags)
|
|
27
|
+
- Sensitive-data masking via `TraceConfig` (e.g. `hide_inputs`, `hide_outputs`)
|
|
28
|
+
|
|
29
|
+
Requires `typesafe-sdk >= 0.6.0`.
|
|
30
|
+
|
|
31
|
+
## Installation
|
|
32
|
+
|
|
33
|
+
```shell
|
|
34
|
+
pip install openinference-instrumentation-typesafe
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Quickstart
|
|
38
|
+
|
|
39
|
+
```shell
|
|
40
|
+
pip install openinference-instrumentation-typesafe typesafe-sdk arize-phoenix opentelemetry-sdk opentelemetry-exporter-otlp
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Start [Phoenix](https://github.com/Arize-ai/phoenix) as a collector (default `http://localhost:6006`), then:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
|
47
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
48
|
+
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
|
49
|
+
|
|
50
|
+
from openinference.instrumentation.typesafe import TypeSafeAIInstrumentor
|
|
51
|
+
|
|
52
|
+
endpoint = "http://127.0.0.1:6006/v1/traces"
|
|
53
|
+
tracer_provider = TracerProvider()
|
|
54
|
+
tracer_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint)))
|
|
55
|
+
|
|
56
|
+
TypeSafeAIInstrumentor().instrument(tracer_provider=tracer_provider)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Make a System One call. Set the `TYPESAFE_API_KEY` environment variable with your key.
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from typesafe_sdk import Choice, Noul, Score, TypeSafeClient
|
|
63
|
+
|
|
64
|
+
client = TypeSafeClient()
|
|
65
|
+
response = client.system_one(
|
|
66
|
+
state={"document": "I was charged twice. Please fix this ASAP."},
|
|
67
|
+
questions={
|
|
68
|
+
"billing": Noul(instructions="Is this ticket about billing?"),
|
|
69
|
+
"tone": Choice(
|
|
70
|
+
instructions="What is the customer's tone?",
|
|
71
|
+
criteria={"calm": None, "frustrated": None, "angry": None},
|
|
72
|
+
),
|
|
73
|
+
"urgency": Score(
|
|
74
|
+
instructions="How urgent is this ticket?",
|
|
75
|
+
criteria=["can wait", "this week", "today"],
|
|
76
|
+
),
|
|
77
|
+
},
|
|
78
|
+
)
|
|
79
|
+
print(response.nouls["billing"].noul)
|
|
80
|
+
print(response.choices["tone"].choice)
|
|
81
|
+
print(response.scores["urgency"].score)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Runnable examples, including async usage and context attributes, are in the [`examples/`](./examples) directory.
|
|
85
|
+
|
|
86
|
+
## More Info
|
|
87
|
+
|
|
88
|
+
- [More info on OpenInference and Phoenix](https://docs.arize.com/phoenix)
|
|
89
|
+
- [How to customize spans to track sessions, metadata, etc.](https://github.com/Arize-ai/openinference/tree/main/python/openinference-instrumentation#customizing-spans)
|
|
90
|
+
- [How to account for private information and span payload customization](https://github.com/Arize-ai/openinference/tree/main/python/openinference-instrumentation#tracing-configuration)
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "openinference-instrumentation-typesafe"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "OpenInference TypeSafe AI Instrumentation"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
requires-python = ">=3.10, <3.15"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "OpenInference Authors", email = "oss@arize.com" },
|
|
14
|
+
]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: Apache Software License",
|
|
19
|
+
"Programming Language :: Python",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Programming Language :: Python :: 3.14",
|
|
26
|
+
]
|
|
27
|
+
dependencies = [
|
|
28
|
+
"opentelemetry-api",
|
|
29
|
+
"opentelemetry-instrumentation",
|
|
30
|
+
"opentelemetry-semantic-conventions",
|
|
31
|
+
"openinference-instrumentation>=0.1.61",
|
|
32
|
+
"openinference-semantic-conventions>=0.1.37",
|
|
33
|
+
"msgspec",
|
|
34
|
+
"wrapt",
|
|
35
|
+
"typing-extensions",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
[project.optional-dependencies]
|
|
39
|
+
instruments = [
|
|
40
|
+
"typesafe-sdk >= 0.6.0",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
[project.entry-points.opentelemetry_instrumentor]
|
|
44
|
+
typesafe = "openinference.instrumentation.typesafe:TypeSafeAIInstrumentor"
|
|
45
|
+
|
|
46
|
+
[project.entry-points.openinference_instrumentor]
|
|
47
|
+
typesafe = "openinference.instrumentation.typesafe:TypeSafeAIInstrumentor"
|
|
48
|
+
|
|
49
|
+
[project.urls]
|
|
50
|
+
Homepage = "https://github.com/Arize-ai/openinference/tree/main/python/instrumentation/openinference-instrumentation-typesafe"
|
|
51
|
+
|
|
52
|
+
[tool.hatch.version]
|
|
53
|
+
path = "src/openinference/instrumentation/typesafe/version.py"
|
|
54
|
+
|
|
55
|
+
[tool.hatch.build.targets.sdist]
|
|
56
|
+
include = [
|
|
57
|
+
"/src",
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
[tool.hatch.build.targets.wheel]
|
|
61
|
+
packages = ["src/openinference"]
|
|
62
|
+
|
|
63
|
+
[tool.pytest.ini_options]
|
|
64
|
+
asyncio_mode = "auto"
|
|
65
|
+
testpaths = [
|
|
66
|
+
"tests",
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
[tool.mypy]
|
|
70
|
+
strict = true
|
|
71
|
+
explicit_package_bases = true
|
|
72
|
+
exclude = [
|
|
73
|
+
"examples",
|
|
74
|
+
"dist",
|
|
75
|
+
"sdist",
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
[[tool.mypy.overrides]]
|
|
79
|
+
ignore_missing_imports = true
|
|
80
|
+
module = [
|
|
81
|
+
"wrapt",
|
|
82
|
+
"typesafe_sdk.*",
|
|
83
|
+
"openinference.instrumentation.typesafe.*",
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
[tool.ruff]
|
|
87
|
+
line-length = 100
|
|
88
|
+
target-version = "py310"
|
|
89
|
+
|
|
90
|
+
[tool.ruff.lint.per-file-ignores]
|
|
91
|
+
"*.ipynb" = ["E402", "E501"]
|
|
92
|
+
|
|
93
|
+
[tool.ruff.lint]
|
|
94
|
+
select = ["E", "F", "W", "I"]
|
|
95
|
+
|
|
96
|
+
[tool.ruff.lint.isort]
|
|
97
|
+
force-single-line = false
|
openinference_instrumentation_typesafe-0.1.1/src/openinference/instrumentation/typesafe/__init__.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from importlib import import_module
|
|
3
|
+
from typing import Any, Collection
|
|
4
|
+
|
|
5
|
+
from opentelemetry import trace as trace_api
|
|
6
|
+
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor # type: ignore
|
|
7
|
+
from wrapt import wrap_function_wrapper
|
|
8
|
+
|
|
9
|
+
from openinference.instrumentation import OITracer, TraceConfig
|
|
10
|
+
from openinference.instrumentation.typesafe.version import __version__
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
logger.addHandler(logging.NullHandler())
|
|
14
|
+
|
|
15
|
+
_instruments = ("typesafe-sdk >= 0.6.0",)
|
|
16
|
+
|
|
17
|
+
# The clients are patched through the SDK's public re-export rather than their
|
|
18
|
+
# private defining modules; wrapt sets the attribute on the same class object either
|
|
19
|
+
# way, and `typesafe_sdk._core.*` carries no compatibility promise.
|
|
20
|
+
_MODULE = "typesafe_sdk"
|
|
21
|
+
|
|
22
|
+
__all__ = ("TypeSafeAIInstrumentor",)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TypeSafeAIInstrumentor(BaseInstrumentor): # type: ignore[misc]
|
|
26
|
+
"""Traces the TypeSafe AI Python SDK (``typesafe-sdk``) as OpenInference LLM spans.
|
|
27
|
+
|
|
28
|
+
Wraps ``TypeSafeClient.system_one`` and ``AsyncTypeSafeClient.system_one``.
|
|
29
|
+
``instrument()`` accepts a ``tracer_provider`` and a ``TraceConfig``; ``uninstrument()``
|
|
30
|
+
restores the original methods.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
__slots__ = ("_original_system_one", "_original_async_system_one", "_tracer")
|
|
34
|
+
|
|
35
|
+
def instrumentation_dependencies(self) -> Collection[str]:
|
|
36
|
+
return _instruments
|
|
37
|
+
|
|
38
|
+
def _instrument(self, **kwargs: Any) -> None:
|
|
39
|
+
from openinference.instrumentation.typesafe._wrappers import (
|
|
40
|
+
_AsyncSystemOneWrapper,
|
|
41
|
+
_SystemOneWrapper,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
if not (tracer_provider := kwargs.get("tracer_provider")):
|
|
45
|
+
tracer_provider = trace_api.get_tracer_provider()
|
|
46
|
+
if not (config := kwargs.get("config")):
|
|
47
|
+
config = TraceConfig()
|
|
48
|
+
else:
|
|
49
|
+
assert isinstance(config, TraceConfig)
|
|
50
|
+
self._tracer = OITracer(
|
|
51
|
+
trace_api.get_tracer(__name__, __version__, tracer_provider),
|
|
52
|
+
config=config,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
module = import_module(_MODULE)
|
|
56
|
+
self._original_system_one = module.TypeSafeClient.system_one
|
|
57
|
+
self._original_async_system_one = module.AsyncTypeSafeClient.system_one
|
|
58
|
+
wrap_function_wrapper(
|
|
59
|
+
_MODULE,
|
|
60
|
+
"TypeSafeClient.system_one",
|
|
61
|
+
_SystemOneWrapper(tracer=self._tracer, span_name="TypeSafeClient"),
|
|
62
|
+
)
|
|
63
|
+
wrap_function_wrapper(
|
|
64
|
+
_MODULE,
|
|
65
|
+
"AsyncTypeSafeClient.system_one",
|
|
66
|
+
_AsyncSystemOneWrapper(tracer=self._tracer, span_name="AsyncTypeSafeClient"),
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
def _uninstrument(self, **kwargs: Any) -> None:
|
|
70
|
+
module = import_module(_MODULE)
|
|
71
|
+
module.TypeSafeClient.system_one = self._original_system_one
|
|
72
|
+
module.AsyncTypeSafeClient.system_one = self._original_async_system_one
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Pure attribute builders for TypeSafe AI ``system_one`` calls.
|
|
2
|
+
|
|
3
|
+
Every function here is side-effect free: it takes the SDK call arguments or the SDK
|
|
4
|
+
response object and returns a flat mapping of OpenInference span attributes.
|
|
5
|
+
|
|
6
|
+
A ``system_one`` call is modelled as an LLM span whose structured output is the map of
|
|
7
|
+
typed answers. ``input.value`` and ``output.value`` mirror the wire request and response
|
|
8
|
+
bodies, and they are the only place the request's ``state`` and ``questions`` are
|
|
9
|
+
recorded, so ``hide_inputs`` alone keeps every part of the request off the span.
|
|
10
|
+
``llm.invocation_parameters`` carries only call configuration: the ``model`` and any
|
|
11
|
+
``extra_body`` fields. See the package README for the full attribute mapping.
|
|
12
|
+
|
|
13
|
+
A ``system_one`` call is not a chat exchange: neither side is a message list, so
|
|
14
|
+
``llm.input_messages`` and ``llm.output_messages`` are deliberately not recorded.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import logging
|
|
18
|
+
from collections.abc import Mapping as AbcMapping
|
|
19
|
+
from collections.abc import Sequence as AbcSequence
|
|
20
|
+
from typing import Any, Dict, Mapping, Optional
|
|
21
|
+
|
|
22
|
+
import msgspec
|
|
23
|
+
from opentelemetry.util.types import AttributeValue
|
|
24
|
+
|
|
25
|
+
from openinference.instrumentation import (
|
|
26
|
+
TokenCount,
|
|
27
|
+
get_input_attributes,
|
|
28
|
+
get_llm_attributes,
|
|
29
|
+
get_output_attributes,
|
|
30
|
+
get_span_kind_attributes,
|
|
31
|
+
)
|
|
32
|
+
from openinference.semconv.trace import OpenInferenceMimeTypeValues, OpenInferenceSpanKindValues
|
|
33
|
+
|
|
34
|
+
logger = logging.getLogger(__name__)
|
|
35
|
+
logger.addHandler(logging.NullHandler())
|
|
36
|
+
|
|
37
|
+
LLM_PROVIDER = "typesafe"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _enc_hook(value: Any) -> Any:
|
|
41
|
+
"""Materializes what msgspec cannot encode on its own into JSON-compatible builtins.
|
|
42
|
+
|
|
43
|
+
Two kinds of value reach this hook. Pydantic models, which is what the SDK's questions,
|
|
44
|
+
answers, and usage became in ``typesafe-sdk`` 0.7.0, are dumped through their own
|
|
45
|
+
serializer, the one the SDK encodes with. Abstract containers, which the SDK accepts
|
|
46
|
+
anywhere it declares a ``Mapping`` or a ``Sequence``, are materialized the way the SDK's
|
|
47
|
+
own encoder fallback materializes them. Anything else is recorded as its string form.
|
|
48
|
+
"""
|
|
49
|
+
if callable(model_dump := getattr(value, "model_dump", None)):
|
|
50
|
+
try:
|
|
51
|
+
return model_dump(mode="json")
|
|
52
|
+
except Exception:
|
|
53
|
+
logger.exception("Failed to dump %r", type(value))
|
|
54
|
+
if isinstance(value, AbcMapping):
|
|
55
|
+
return dict(value)
|
|
56
|
+
if isinstance(value, AbcSequence):
|
|
57
|
+
return list(value)
|
|
58
|
+
return str(value)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _to_builtins(value: Any) -> Any:
|
|
62
|
+
"""Converts the SDK's question, answer, and usage objects into JSON-compatible builtins.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
value: Any value the SDK may accept or hand back: a msgspec struct (``typesafe-sdk``
|
|
66
|
+
0.6.x), a pydantic model (0.7.0 and later), or a plain builtin.
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
The value as JSON-compatible builtins, or ``str(value)`` if conversion fails.
|
|
70
|
+
"""
|
|
71
|
+
try:
|
|
72
|
+
return msgspec.to_builtins(value, str_keys=True, enc_hook=_enc_hook)
|
|
73
|
+
except Exception:
|
|
74
|
+
logger.exception("Failed to convert %r to builtins", type(value))
|
|
75
|
+
return str(value)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def get_request_attributes(
|
|
79
|
+
*,
|
|
80
|
+
state: Any,
|
|
81
|
+
questions: Any,
|
|
82
|
+
model: Optional[str],
|
|
83
|
+
extra_body: Optional[Mapping[str, Any]] = None,
|
|
84
|
+
) -> Dict[str, AttributeValue]:
|
|
85
|
+
"""Returns the span attributes that are known before the request is sent.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
state: The state the questions are asked about, a string or a JSON-compatible value.
|
|
89
|
+
questions: The map of typed questions, as SDK objects or raw dictionaries.
|
|
90
|
+
model: The requested model, or ``None`` when the client default applies.
|
|
91
|
+
extra_body: Extra top-level request body fields, if any.
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
The span kind, ``input.value``, and the request-side ``llm.*`` attributes.
|
|
95
|
+
"""
|
|
96
|
+
body: Dict[str, Any] = {
|
|
97
|
+
"state": _to_builtins(state),
|
|
98
|
+
"model": model,
|
|
99
|
+
"questions": _to_builtins(questions),
|
|
100
|
+
}
|
|
101
|
+
if extra_body:
|
|
102
|
+
# extra_body values are JSONValue, so they may hold abstract Mapping / Sequence
|
|
103
|
+
# containers that need the same conversion as state and questions.
|
|
104
|
+
body.update(_to_builtins(extra_body))
|
|
105
|
+
# The questions map is request content, not call configuration: it carries the caller's
|
|
106
|
+
# instructions. Recording it once, in input.value, keeps one masking flag in charge of
|
|
107
|
+
# everything the request says.
|
|
108
|
+
invocation_parameters = {
|
|
109
|
+
k: v for k, v in body.items() if k not in ("state", "questions") and v is not None
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
**get_span_kind_attributes(OpenInferenceSpanKindValues.LLM),
|
|
113
|
+
**get_input_attributes(body, mime_type=OpenInferenceMimeTypeValues.JSON),
|
|
114
|
+
**get_llm_attributes(
|
|
115
|
+
provider=LLM_PROVIDER,
|
|
116
|
+
request_model_name=model,
|
|
117
|
+
invocation_parameters=invocation_parameters,
|
|
118
|
+
),
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def get_response_attributes(response: Any) -> Dict[str, AttributeValue]:
|
|
123
|
+
"""Returns the span attributes derived from a ``SystemOneResponse``.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
response: The response object returned by ``system_one``.
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
``output.value``, the resolved response model name, and token counts.
|
|
130
|
+
"""
|
|
131
|
+
model = getattr(response, "model", None)
|
|
132
|
+
usage = getattr(response, "usage", None)
|
|
133
|
+
body: Dict[str, Any] = {
|
|
134
|
+
"model": model,
|
|
135
|
+
"answers": _to_builtins(getattr(response, "answers", {})),
|
|
136
|
+
"usage": _to_builtins(usage),
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
**get_llm_attributes(
|
|
140
|
+
response_model_name=model,
|
|
141
|
+
token_count=_get_token_count(usage),
|
|
142
|
+
),
|
|
143
|
+
**get_output_attributes(body, mime_type=OpenInferenceMimeTypeValues.JSON),
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _get_token_count(usage: Any) -> Optional[TokenCount]:
|
|
148
|
+
"""Returns the prompt, completion, and total token counts, or ``None`` when unreported.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
usage: The ``usage`` object on a ``SystemOneResponse``, or ``None``.
|
|
152
|
+
|
|
153
|
+
Returns:
|
|
154
|
+
A ``TokenCount`` with whichever counts the response reported, else ``None``. The
|
|
155
|
+
total is only derived when both the prompt and completion counts are present.
|
|
156
|
+
"""
|
|
157
|
+
prompt = getattr(usage, "input_tokens", None)
|
|
158
|
+
completion = getattr(usage, "output_tokens", None)
|
|
159
|
+
token_count: TokenCount = {}
|
|
160
|
+
if isinstance(prompt, int):
|
|
161
|
+
token_count["prompt"] = prompt
|
|
162
|
+
if isinstance(completion, int):
|
|
163
|
+
token_count["completion"] = completion
|
|
164
|
+
if isinstance(prompt, int) and isinstance(completion, int):
|
|
165
|
+
token_count["total"] = prompt + completion
|
|
166
|
+
return token_count or None
|
openinference_instrumentation_typesafe-0.1.1/src/openinference/instrumentation/typesafe/_wrappers.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from contextlib import AbstractContextManager
|
|
3
|
+
from inspect import Signature, signature
|
|
4
|
+
from typing import Any, Callable, Dict, Mapping, Optional, Tuple
|
|
5
|
+
|
|
6
|
+
from opentelemetry import context as context_api
|
|
7
|
+
from opentelemetry.trace import Span, Status, StatusCode
|
|
8
|
+
from opentelemetry.util.types import AttributeValue
|
|
9
|
+
|
|
10
|
+
from openinference.instrumentation import OITracer
|
|
11
|
+
from openinference.instrumentation.typesafe._attributes import (
|
|
12
|
+
get_request_attributes,
|
|
13
|
+
get_response_attributes,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
logger.addHandler(logging.NullHandler())
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _finish(span: Span, response: Any) -> None:
|
|
21
|
+
"""Records the response attributes and marks the span ``OK``."""
|
|
22
|
+
# Sampled-out spans discard every attribute, so skip the serialization entirely.
|
|
23
|
+
if span.is_recording():
|
|
24
|
+
try:
|
|
25
|
+
span.set_attributes(get_response_attributes(response))
|
|
26
|
+
except Exception:
|
|
27
|
+
logger.exception("Failed to extract response attributes")
|
|
28
|
+
span.set_status(Status(StatusCode.OK))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _fail(span: Span, exception: BaseException) -> None:
|
|
32
|
+
"""Records the exception and marks the span ``ERROR``."""
|
|
33
|
+
span.record_exception(exception)
|
|
34
|
+
span.set_status(Status(StatusCode.ERROR, f"{type(exception).__name__}: {exception}"))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _WithTracer:
|
|
38
|
+
"""Base class for the sync and async ``system_one`` wrappers."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, tracer: OITracer, span_name: str) -> None:
|
|
41
|
+
self._tracer = tracer
|
|
42
|
+
self._span_name = span_name
|
|
43
|
+
self._signature: Optional[Signature] = None
|
|
44
|
+
|
|
45
|
+
def _start_span(
|
|
46
|
+
self,
|
|
47
|
+
wrapped: Callable[..., Any],
|
|
48
|
+
instance: Any,
|
|
49
|
+
args: Tuple[Any, ...],
|
|
50
|
+
kwargs: Mapping[str, Any],
|
|
51
|
+
) -> AbstractContextManager[Span]:
|
|
52
|
+
"""Returns the span context manager for one ``system_one`` call."""
|
|
53
|
+
return self._tracer.start_as_current_span(
|
|
54
|
+
self._span_name,
|
|
55
|
+
attributes=self._request_attributes(wrapped, instance, args, kwargs),
|
|
56
|
+
record_exception=False,
|
|
57
|
+
set_status_on_exception=False,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
def _request_attributes(
|
|
61
|
+
self,
|
|
62
|
+
wrapped: Callable[..., Any],
|
|
63
|
+
instance: Any,
|
|
64
|
+
args: Tuple[Any, ...],
|
|
65
|
+
kwargs: Mapping[str, Any],
|
|
66
|
+
) -> Dict[str, AttributeValue]:
|
|
67
|
+
"""Returns the request-side attributes, or an empty mapping if extraction fails."""
|
|
68
|
+
try:
|
|
69
|
+
# Each wrapper instance wraps exactly one method, so the signature is
|
|
70
|
+
# computed once and reused across calls.
|
|
71
|
+
if self._signature is None:
|
|
72
|
+
self._signature = signature(wrapped)
|
|
73
|
+
bound = self._signature.bind(*args, **kwargs)
|
|
74
|
+
bound.apply_defaults()
|
|
75
|
+
arguments = bound.arguments
|
|
76
|
+
model = arguments["model"]
|
|
77
|
+
if model is None:
|
|
78
|
+
# Fall back to the client default (constructor arg or TYPESAFE_DEFAULT_MODEL).
|
|
79
|
+
model = getattr(getattr(instance, "_config", None), "default_model", None)
|
|
80
|
+
return get_request_attributes(
|
|
81
|
+
state=arguments["state"],
|
|
82
|
+
questions=arguments["questions"],
|
|
83
|
+
model=model,
|
|
84
|
+
extra_body=arguments["extra_body"],
|
|
85
|
+
)
|
|
86
|
+
except Exception:
|
|
87
|
+
logger.exception("Failed to extract request attributes")
|
|
88
|
+
return {}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class _SystemOneWrapper(_WithTracer):
|
|
92
|
+
def __call__(
|
|
93
|
+
self,
|
|
94
|
+
wrapped: Callable[..., Any],
|
|
95
|
+
instance: Any,
|
|
96
|
+
args: Tuple[Any, ...],
|
|
97
|
+
kwargs: Mapping[str, Any],
|
|
98
|
+
) -> Any:
|
|
99
|
+
if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
|
|
100
|
+
return wrapped(*args, **kwargs)
|
|
101
|
+
with self._start_span(wrapped, instance, args, kwargs) as span:
|
|
102
|
+
try:
|
|
103
|
+
response = wrapped(*args, **kwargs)
|
|
104
|
+
except BaseException as exception:
|
|
105
|
+
_fail(span, exception)
|
|
106
|
+
raise
|
|
107
|
+
_finish(span, response)
|
|
108
|
+
return response
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class _AsyncSystemOneWrapper(_WithTracer):
|
|
112
|
+
async def __call__(
|
|
113
|
+
self,
|
|
114
|
+
wrapped: Callable[..., Any],
|
|
115
|
+
instance: Any,
|
|
116
|
+
args: Tuple[Any, ...],
|
|
117
|
+
kwargs: Mapping[str, Any],
|
|
118
|
+
) -> Any:
|
|
119
|
+
if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
|
|
120
|
+
return await wrapped(*args, **kwargs)
|
|
121
|
+
with self._start_span(wrapped, instance, args, kwargs) as span:
|
|
122
|
+
try:
|
|
123
|
+
response = await wrapped(*args, **kwargs)
|
|
124
|
+
except BaseException as exception:
|
|
125
|
+
_fail(span, exception)
|
|
126
|
+
raise
|
|
127
|
+
_finish(span, response)
|
|
128
|
+
return response
|
openinference_instrumentation_typesafe-0.1.1/src/openinference/instrumentation/typesafe/version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.1"
|