introspection-transform 0.2.0__py3-none-any.whl

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,43 @@
1
+ """GenAI spans → an ATIF trajectory, an ATIF trajectory → run messages, and a span → a training example."""
2
+
3
+ from introspection_transform.genai_span import GenAiSpan, GenAiSpanList
4
+ from introspection_transform.messages import (
5
+ AtifConversionError,
6
+ atif_to_messages,
7
+ )
8
+ from introspection_transform.projection import AtifProjection, spans_to_atif
9
+ from introspection_transform.training import (
10
+ TRAINING_FORMAT,
11
+ TrainingConversionError,
12
+ TrainingExample,
13
+ TrainingMessage,
14
+ TrainingMetadata,
15
+ TrainingSource,
16
+ dpo_pair,
17
+ sft_row,
18
+ span_to_example,
19
+ )
20
+ from introspection_transform.trajectory import (
21
+ ATIF_SCHEMA_VERSION,
22
+ AtifTrajectory,
23
+ )
24
+
25
+ __all__ = [
26
+ "ATIF_SCHEMA_VERSION",
27
+ "TRAINING_FORMAT",
28
+ "AtifConversionError",
29
+ "AtifProjection",
30
+ "AtifTrajectory",
31
+ "GenAiSpan",
32
+ "GenAiSpanList",
33
+ "TrainingConversionError",
34
+ "TrainingExample",
35
+ "TrainingMessage",
36
+ "TrainingMetadata",
37
+ "TrainingSource",
38
+ "atif_to_messages",
39
+ "dpo_pair",
40
+ "sft_row",
41
+ "span_to_example",
42
+ "spans_to_atif",
43
+ ]
@@ -0,0 +1,57 @@
1
+ """Wire models for append-only span annotations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from uuid import UUID
7
+
8
+ from pydantic import BaseModel, ConfigDict
9
+
10
+
11
+ class AnnotationTarget(BaseModel):
12
+ model_config = ConfigDict(extra="forbid")
13
+
14
+ trace_id: str
15
+ span_id: str
16
+
17
+
18
+ class AnnotationComment(BaseModel):
19
+ """One comment on an annotated span, as ``include=comments`` carries it."""
20
+
21
+ model_config = ConfigDict(extra="allow")
22
+
23
+ event_id: UUID
24
+ comment: str
25
+ #: The comment's author.
26
+ member_id: UUID
27
+ actor_member_id: UUID | None = None
28
+ actor_member_type: str | None = None
29
+ created_at: datetime
30
+
31
+
32
+ class AnnotationState(AnnotationTarget):
33
+ """Current state folded from immutable annotation events.
34
+
35
+ ``comments`` is ``None`` unless the list was read with
36
+ ``include=["comments"]``, which sets it on every row, oldest first.
37
+ """
38
+
39
+ model_config = ConfigDict(extra="allow")
40
+
41
+ conversation_id: str | None = None
42
+ labels: list[str]
43
+ assignee_member_ids: list[UUID]
44
+ #: Members whose comment completed a review.
45
+ reviewer_member_ids: list[UUID]
46
+ comment_count: int
47
+ updated_at: datetime
48
+ updated_by_member_id: UUID
49
+ assignment_event_id: UUID | None = None
50
+ comments: list[AnnotationComment] | None = None
51
+
52
+
53
+ __all__ = [
54
+ "AnnotationComment",
55
+ "AnnotationState",
56
+ "AnnotationTarget",
57
+ ]
@@ -0,0 +1,412 @@
1
+ """OTel Gen AI Semantic Convention Pydantic models.
2
+
3
+ Based on the OpenTelemetry Gen AI semantic conventions:
4
+ - https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-input-messages.json
5
+ - https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-output-messages.json
6
+ """
7
+
8
+ from typing import Annotated, Any, ClassVar, Literal
9
+
10
+ from pydantic import (
11
+ BaseModel,
12
+ ConfigDict,
13
+ Discriminator,
14
+ Field,
15
+ SerializerFunctionWrapHandler,
16
+ Tag,
17
+ model_serializer,
18
+ )
19
+
20
+ __all__ = [
21
+ "OmitNoneModel",
22
+ "BinaryPart",
23
+ "CompactionPart",
24
+ "FilePart",
25
+ "GenericPart",
26
+ "TextPart",
27
+ "ThinkingPart",
28
+ "UrlPart",
29
+ "ToolCallRequestPart",
30
+ "ToolCallResponsePart",
31
+ "MessagePart",
32
+ "InputMessage",
33
+ "OutputMessage",
34
+ "InputMessages",
35
+ "OutputMessages",
36
+ "SystemInstruction",
37
+ "SystemInstructions",
38
+ "ToolDefinition",
39
+ "ToolDefinitions",
40
+ ]
41
+
42
+
43
+ class OmitNoneModel(BaseModel):
44
+ """Base whose serialization drops ``None``-valued keys.
45
+
46
+ The semantic conventions describe attributes that are *absent* when they
47
+ have no value, not attributes that are present and null. Emitting
48
+ ``"finish_reason": null`` on every user message asserts a finish reason
49
+ exists and is null, which is a different claim from "this message has no
50
+ finish reason" — and it is the claim a reader then has to defend against.
51
+
52
+ This applies on both sides: it is what these models serialize into
53
+ ``gen_ai.input.messages`` on an emitted span, and what they serialize back
54
+ out when a conversation is read. Applying it at the base rather than at
55
+ each call site keeps the two consistent, which matters because a round trip
56
+ through the API should be an identity.
57
+
58
+ The message and part types set ``open_schema = True``: providers keep
59
+ adding keys to them, so strict decoding (``INTROSPECTION_STRICT_SCHEMA=1``)
60
+ never reports one. Other subclasses, such as the conversation summary's,
61
+ are the server's and stay closed.
62
+ """
63
+
64
+ model_config = ConfigDict(extra="allow")
65
+
66
+ @model_serializer(mode="wrap")
67
+ def _omit_none(self, handler: SerializerFunctionWrapHandler) -> Any:
68
+ serialized = handler(self)
69
+ if isinstance(serialized, dict):
70
+ return {
71
+ key: value
72
+ for key, value in serialized.items()
73
+ if value is not None
74
+ }
75
+ return serialized
76
+
77
+
78
+ class TextPart(OmitNoneModel):
79
+ """Text content part."""
80
+
81
+ open_schema: ClassVar[bool] = True
82
+
83
+ type: Literal["text"] = Field(
84
+ default="text",
85
+ description="Part type discriminator, always ``'text'``.",
86
+ )
87
+ content: str = Field(default="", description="The text content.")
88
+ text_signature: str | None = Field(
89
+ default=None,
90
+ description="Opaque per-block signature for replay continuity.",
91
+ )
92
+
93
+
94
+ class ThinkingPart(OmitNoneModel):
95
+ """Reasoning content produced by the model.
96
+
97
+ ``thinking`` is the canonical name here, matching the vocabulary the
98
+ platform writes and the one Pydantic AI and the provider SDKs use. The
99
+ semantic conventions call this ``reasoning``; that spelling is accepted so a
100
+ spec-shaped part parses, and it normalizes to ``thinking`` on the way in.
101
+
102
+ The alias is permanent rather than transitional. Telemetry is append-only:
103
+ a part type is *stored bytes*, so both spellings stay readable for as long
104
+ as spans written with either one exist.
105
+ """
106
+
107
+ open_schema: ClassVar[bool] = True
108
+
109
+ type: Literal["thinking", "reasoning"] = Field(
110
+ default="thinking",
111
+ description="Part type discriminator. ``'thinking'`` is canonical; ``'reasoning'`` is the semantic-convention spelling and is accepted on read.",
112
+ )
113
+ content: str | None = Field(
114
+ default=None, description="The thinking/reasoning summary content."
115
+ )
116
+ signature: str | None = Field(
117
+ default=None,
118
+ description="Encrypted reasoning signature (maps to OpenAI encrypted_content, Anthropic signature/redacted_thinking data).",
119
+ )
120
+ provider_name: str | None = Field(
121
+ default=None,
122
+ description="Provider that produced this thinking block (e.g. ``'anthropic'``, ``'openai'``). Used to reconstruct the correct wire format on replay.",
123
+ )
124
+ redacted: bool | None = Field(
125
+ default=None,
126
+ description="True when the thinking content was redacted but the signed payload is preserved.",
127
+ )
128
+
129
+
130
+ class ToolCallRequestPart(OmitNoneModel):
131
+ """Tool/function call request part."""
132
+
133
+ open_schema: ClassVar[bool] = True
134
+
135
+ type: Literal["tool_call"] = Field(
136
+ description="Part type discriminator, always ``'tool_call'``.",
137
+ )
138
+ name: str = Field(description="Name of the tool/function being called.")
139
+ id: str | None = Field(
140
+ default=None, description="Provider-assigned tool call ID."
141
+ )
142
+ arguments: Any = Field(
143
+ default=None,
144
+ description="Arguments passed to the tool (dict or JSON string).",
145
+ )
146
+
147
+
148
+ class ToolCallResponsePart(OmitNoneModel):
149
+ """Tool/function call response part."""
150
+
151
+ open_schema: ClassVar[bool] = True
152
+
153
+ type: Literal["tool_call_response"] = Field(
154
+ description="Part type discriminator, always ``'tool_call_response'``.",
155
+ )
156
+ response: Any = Field(description="The tool's response payload.")
157
+ id: str | None = Field(
158
+ default=None,
159
+ description="Tool call ID this response corresponds to.",
160
+ )
161
+
162
+
163
+ class BinaryPart(OmitNoneModel):
164
+ """Inline binary content, carried base64-encoded.
165
+
166
+ ``binary`` is canonical; the semantic conventions call this ``blob`` and
167
+ name the media type ``mime_type``, so both spellings are accepted and
168
+ ``media_type`` stays the field a reader can rely on.
169
+ """
170
+
171
+ open_schema: ClassVar[bool] = True
172
+
173
+ type: Literal["binary", "blob"] = Field(
174
+ default="binary",
175
+ description="Part type discriminator. ``'binary'`` is canonical; ``'blob'`` is the semantic-convention spelling.",
176
+ )
177
+ content: str | None = Field(
178
+ default=None, description="Base64-encoded content."
179
+ )
180
+ media_type: str | None = Field(
181
+ default=None, description="IANA media type of the content."
182
+ )
183
+ mime_type: str | None = Field(
184
+ default=None,
185
+ description="Semantic-convention spelling of ``media_type``, accepted on read.",
186
+ )
187
+ modality: str | None = Field(
188
+ default=None,
189
+ description="Semantic-convention modality (``image``, ``audio``, ``video``, ``document``), when the writer supplied one.",
190
+ )
191
+
192
+
193
+ class UrlPart(OmitNoneModel):
194
+ """Content referenced by URL rather than carried inline.
195
+
196
+ The modality lives in the type name here — ``image-url``, ``audio-url``,
197
+ ``video-url``, ``document-url`` — which is how the platform writes it and
198
+ how Pydantic AI models it. The semantic conventions instead use a single
199
+ ``uri`` type carrying a separate ``modality``; that shape is accepted too,
200
+ with ``uri`` read into ``url``.
201
+ """
202
+
203
+ open_schema: ClassVar[bool] = True
204
+
205
+ type: Literal[
206
+ "image-url", "audio-url", "video-url", "document-url", "uri"
207
+ ] = Field(
208
+ description="Part type discriminator; the four ``*-url`` names carry the modality, ``'uri'`` is the semantic-convention spelling."
209
+ )
210
+ url: str | None = Field(default=None, description="The referenced URL.")
211
+ uri: str | None = Field(
212
+ default=None,
213
+ description="Semantic-convention spelling of ``url``, accepted on read.",
214
+ )
215
+ media_type: str | None = Field(default=None)
216
+ mime_type: str | None = Field(default=None)
217
+ modality: str | None = Field(
218
+ default=None,
219
+ description="Set only on a semantic-convention ``uri`` part, where the type name does not carry it.",
220
+ )
221
+
222
+ @property
223
+ def target(self) -> str | None:
224
+ """The referenced location under whichever spelling was written."""
225
+ return self.url or self.uri
226
+
227
+
228
+ class FilePart(OmitNoneModel):
229
+ """Content referenced by a provider-assigned file id (semconv ``file``)."""
230
+
231
+ open_schema: ClassVar[bool] = True
232
+
233
+ type: Literal["file"] = Field(default="file")
234
+ file_id: str | None = Field(default=None)
235
+ mime_type: str | None = Field(default=None)
236
+ modality: str | None = Field(default=None)
237
+
238
+
239
+ class CompactionPart(OmitNoneModel):
240
+ """A compaction marker — history summarized to fit a context window."""
241
+
242
+ open_schema: ClassVar[bool] = True
243
+
244
+ type: Literal["compaction"] = Field(default="compaction")
245
+ content: str | None = Field(
246
+ default=None,
247
+ description="The summary that replaced the compacted turns.",
248
+ )
249
+
250
+
251
+ class GenericPart(OmitNoneModel):
252
+ """Any part type this SDK does not model.
253
+
254
+ The catch-all is the important one. Before it, the union was strictly
255
+ discriminated, so a single unmodelled part raised ``union_tag_invalid`` and
256
+ took the **whole message** with it — a conversation containing one image was
257
+ unparseable. An unknown part is not an error: the spec grows, and the
258
+ platform can write a type this build has never heard of. It degrades to
259
+ "some part, contents preserved" instead.
260
+ """
261
+
262
+ open_schema: ClassVar[bool] = True
263
+
264
+ model_config = ConfigDict(extra="allow")
265
+
266
+ type: str = Field(description="The part type as written.")
267
+
268
+
269
+ #: Every `type` that maps onto a modelled part, including the semantic-
270
+ #: convention spellings we accept as aliases. Anything absent becomes a
271
+ #: `GenericPart`.
272
+ PART_MODEL_BY_TAG: dict[str, str] = {
273
+ "text": "text",
274
+ "thinking": "thinking",
275
+ "reasoning": "thinking",
276
+ "tool_call": "tool_call",
277
+ "tool_call_response": "tool_call_response",
278
+ "binary": "binary",
279
+ "blob": "binary",
280
+ "image-url": "url",
281
+ "audio-url": "url",
282
+ "video-url": "url",
283
+ "document-url": "url",
284
+ "uri": "url",
285
+ "file": "file",
286
+ "compaction": "compaction",
287
+ }
288
+
289
+
290
+ def _part_tag(value: Any) -> str:
291
+ """Map a part's `type` onto the model that should parse it.
292
+
293
+ Aliases collapse here — `thinking`/`reasoning` are one model, as are
294
+ `binary`/`blob` and the five URL spellings — and anything unrecognized
295
+ routes to `generic` rather than failing the message.
296
+ """
297
+ raw = (
298
+ value.get("type")
299
+ if isinstance(value, dict)
300
+ else getattr(value, "type", None)
301
+ )
302
+ return (
303
+ PART_MODEL_BY_TAG.get(raw, "generic")
304
+ if isinstance(raw, str)
305
+ else "generic"
306
+ )
307
+
308
+
309
+ MessagePart = Annotated[
310
+ Annotated[TextPart, Tag("text")]
311
+ | Annotated[ThinkingPart, Tag("thinking")]
312
+ | Annotated[ToolCallRequestPart, Tag("tool_call")]
313
+ | Annotated[ToolCallResponsePart, Tag("tool_call_response")]
314
+ | Annotated[BinaryPart, Tag("binary")]
315
+ | Annotated[UrlPart, Tag("url")]
316
+ | Annotated[FilePart, Tag("file")]
317
+ | Annotated[CompactionPart, Tag("compaction")]
318
+ | Annotated[GenericPart, Tag("generic")],
319
+ Discriminator(_part_tag),
320
+ ]
321
+ """Every message part shape, tagged by `type`, with unknown types preserved."""
322
+
323
+
324
+ class InputMessage(OmitNoneModel):
325
+ """Input message in OTel Gen AI semantic convention format."""
326
+
327
+ open_schema: ClassVar[bool] = True
328
+
329
+ role: Literal["system", "user", "assistant", "tool"] = Field(
330
+ description="Message role: ``'system'``, ``'user'``, ``'assistant'``, or ``'tool'``.",
331
+ )
332
+ parts: list[MessagePart] = Field(
333
+ default_factory=list,
334
+ description=(
335
+ "Ordered list of content parts. Empty when the read omitted the "
336
+ "key: a message without content arrives without ``parts``."
337
+ ),
338
+ )
339
+ name: str | None = Field(default=None, description="Optional sender name.")
340
+
341
+
342
+ class OutputMessage(OmitNoneModel):
343
+ """Output message in OTel Gen AI semantic convention format."""
344
+
345
+ open_schema: ClassVar[bool] = True
346
+
347
+ role: Literal["system", "user", "assistant", "tool"] = Field(
348
+ description="Message role: ``'system'``, ``'user'``, ``'assistant'``, or ``'tool'``.",
349
+ )
350
+ parts: list[MessagePart] = Field(
351
+ default_factory=list,
352
+ description=(
353
+ "Ordered list of content parts. Empty when the read omitted the "
354
+ "key: a message without content arrives without ``parts``."
355
+ ),
356
+ )
357
+ finish_reason: str | None = Field(
358
+ default=None,
359
+ description="Why the model stopped generating (e.g. ``'stop'``, ``'max_tokens'``, ``'tool_calls'``).",
360
+ )
361
+ name: str | None = Field(default=None, description="Optional sender name.")
362
+
363
+
364
+ # Type aliases for validating lists of messages
365
+ InputMessages = list[InputMessage]
366
+ """List of :class:`InputMessage` instances."""
367
+
368
+ OutputMessages = list[OutputMessage]
369
+ """List of :class:`OutputMessage` instances."""
370
+
371
+
372
+ class SystemInstruction(OmitNoneModel):
373
+ """A single system instruction part (text content)."""
374
+
375
+ open_schema: ClassVar[bool] = True
376
+
377
+ type: Literal["text"] = Field(
378
+ default="text",
379
+ description="Part type discriminator, always ``'text'``.",
380
+ )
381
+ content: str = Field(description="The instruction text content.")
382
+
383
+
384
+ SystemInstructions = list[SystemInstruction]
385
+ """List of :class:`SystemInstruction` instances."""
386
+
387
+
388
+ class ToolDefinition(OmitNoneModel):
389
+ """A tool/function definition available to the model."""
390
+
391
+ open_schema: ClassVar[bool] = True
392
+
393
+ type: str | None = Field(
394
+ default=None,
395
+ description="Tool type (e.g. ``'function'``).",
396
+ )
397
+ name: str | None = Field(
398
+ default=None,
399
+ description="Name of the tool/function.",
400
+ )
401
+ description: str | None = Field(
402
+ default=None,
403
+ description="Human-readable description of what the tool does.",
404
+ )
405
+ parameters: dict[str, Any] | None = Field(
406
+ default=None,
407
+ description="JSON Schema of the tool's parameters.",
408
+ )
409
+
410
+
411
+ ToolDefinitions = list[ToolDefinition]
412
+ """List of :class:`ToolDefinition` instances."""