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,569 @@
1
+ """The GenAI span returned by conversation item reads.
2
+
3
+ A conversation item **is** an OpenTelemetry span, so this models it as one:
4
+ identity and timing at the top level, everything else under ``attributes`` keyed
5
+ by its OpenTelemetry semantic-convention name. ``attributes.gen_ai.request.model``
6
+ is called that here because that is what the SDK wrote when it created the span.
7
+
8
+ - ``GET /v1/conversations/{id}/items`` — that turn's **delta**; concatenate in
9
+ order for the transcript, each message appearing once.
10
+ - ``GET /v1/conversations/{id}/items/{item_id}`` — the **full history** as of
11
+ that turn. This is the resumption read, and it needs no ``include``.
12
+
13
+ Full history is the detail read only because returning it per item on a list is
14
+ quadratic — turn 50 would carry fifty messages, turn 49 forty-nine, and so on.
15
+
16
+ **Absent means absent.** Nothing serializes as ``null``; a value that is not
17
+ present is a key that is not there. The typed families below are a convenience
18
+ over an open tree, not a closed set — every model allows extra keys, so an
19
+ attribute nobody modelled still arrives and still round-trips.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from datetime import datetime
25
+ from typing import Any, ClassVar, Literal
26
+
27
+ from pydantic import (
28
+ BaseModel,
29
+ ConfigDict,
30
+ Field,
31
+ SerializerFunctionWrapHandler,
32
+ model_serializer,
33
+ )
34
+
35
+ from introspection_transform.annotations import AnnotationState
36
+ from introspection_transform.genai import (
37
+ InputMessage,
38
+ OutputMessage,
39
+ SystemInstruction,
40
+ ToolDefinition,
41
+ )
42
+
43
+ __all__ = [
44
+ "ConversationCompaction",
45
+ "GenAiAgent",
46
+ "GenAiAttributes",
47
+ "GenAiConversation",
48
+ "GenAiInput",
49
+ "GenAiOperation",
50
+ "GenAiOutput",
51
+ "GenAiProvider",
52
+ "GenAiRequest",
53
+ "GenAiResponse",
54
+ "GenAiSpan",
55
+ "GenAiSpanList",
56
+ "GenAiTool",
57
+ "GenAiToolCall",
58
+ "GenAiCost",
59
+ "GenAiUsage",
60
+ "IntrospectionAgent",
61
+ "IntrospectionAttributes",
62
+ "IntrospectionContains",
63
+ "IntrospectionHistory",
64
+ "IntrospectionIngest",
65
+ "IntrospectionInvocation",
66
+ "IntrospectionNewMessages",
67
+ "IntrospectionRecipe",
68
+ "IntrospectionRun",
69
+ "IntrospectionRuntime",
70
+ "IntrospectionTask",
71
+ "SpanAttributes",
72
+ "SpanKind",
73
+ "SpanStatus",
74
+ "SpanStatusCode",
75
+ "TokenCount",
76
+ ]
77
+
78
+ SpanStatusCode = Literal["Ok", "Error", "Unset"]
79
+ """OpenTelemetry span status code values."""
80
+
81
+ SpanKind = Literal[
82
+ "UNSPECIFIED",
83
+ "INTERNAL",
84
+ "SERVER",
85
+ "CLIENT",
86
+ "PRODUCER",
87
+ "CONSUMER",
88
+ ]
89
+ """OpenTelemetry span kind values."""
90
+
91
+
92
+ class SpanModel(BaseModel):
93
+ """Open, omit-empty base for every model on this surface.
94
+
95
+ ``extra="allow"`` is not defensive boilerplate here — it is the contract.
96
+ The server returns the attribute tree as stored rather than an allow-list,
97
+ so a customer's own ``gen_ai.*`` or domain attribute arrives on a model that
98
+ never declared it. Forbidding extras would reintroduce exactly the lossiness
99
+ this representation exists to remove.
100
+
101
+ A subclass that sets ``open_schema = True`` is open in strict mode too
102
+ (``INTROSPECTION_STRICT_SCHEMA=1``): the ``gen_ai.*`` nodes and the
103
+ attribute tree itself, whose keys the GenAI conventions and providers keep
104
+ adding to. ``introspection.*`` and the span's own fields are the server's,
105
+ so a key there the SDK does not model is API drift, which strict mode
106
+ reports.
107
+
108
+ ``protected_namespaces=()`` silences Pydantic's ``model_`` warning for wire
109
+ fields like ``model``.
110
+ """
111
+
112
+ model_config = ConfigDict(extra="allow", protected_namespaces=())
113
+
114
+ @model_serializer(mode="wrap")
115
+ def _omit_empty(self, handler: SerializerFunctionWrapHandler) -> Any:
116
+ serialized = handler(self)
117
+ if not isinstance(serialized, dict):
118
+ return serialized
119
+ # Drop None only. Empty containers are dropped by the fields that
120
+ # default to them; a `0` or `""` that survived this far came from the
121
+ # server and is a real value, not a placeholder.
122
+ return {
123
+ key: value
124
+ for key, value in serialized.items()
125
+ if value is not None
126
+ }
127
+
128
+
129
+ # --- gen_ai.* -------------------------------------------------------------
130
+
131
+
132
+ class GenAiOperation(SpanModel):
133
+ """``gen_ai.operation.name`` — ``chat``, ``execute_tool``, ``invoke_agent``."""
134
+
135
+ open_schema: ClassVar[bool] = True
136
+
137
+ name: str | None = None
138
+
139
+
140
+ class GenAiProvider(SpanModel):
141
+ """``gen_ai.provider.name``. Replaced the older ``gen_ai.system``."""
142
+
143
+ open_schema: ClassVar[bool] = True
144
+
145
+ name: str | None = None
146
+
147
+
148
+ class GenAiConversation(SpanModel):
149
+ """``gen_ai.conversation.id``."""
150
+
151
+ open_schema: ClassVar[bool] = True
152
+
153
+ id: str | None = None
154
+
155
+
156
+ class GenAiAgent(SpanModel):
157
+ """``gen_ai.agent.*``."""
158
+
159
+ open_schema: ClassVar[bool] = True
160
+
161
+ id: str | None = None
162
+ name: str | None = None
163
+ description: str | None = None
164
+
165
+
166
+ class GenAiRequest(SpanModel):
167
+ """``gen_ai.request.*`` — what was asked for."""
168
+
169
+ open_schema: ClassVar[bool] = True
170
+
171
+ model: str | None = None
172
+ temperature: float | None = None
173
+ top_p: float | None = None
174
+ top_k: int | None = None
175
+ max_tokens: int | None = None
176
+ seed: int | None = None
177
+ stream: bool | None = None
178
+
179
+
180
+ class GenAiResponse(SpanModel):
181
+ """``gen_ai.response.*`` — what came back."""
182
+
183
+ open_schema: ClassVar[bool] = True
184
+
185
+ id: str | None = None
186
+ model: str | None = None
187
+ finish_reasons: list[str] | None = None
188
+
189
+
190
+ class TokenCount(SpanModel):
191
+ """A nested token count, e.g. ``gen_ai.usage.cache_read.input_tokens``."""
192
+
193
+ open_schema: ClassVar[bool] = True
194
+
195
+ input_tokens: int | None = None
196
+
197
+
198
+ class GenAiUsage(SpanModel):
199
+ """``gen_ai.usage.*``.
200
+
201
+ On an item these are that operation's usage. On a conversation summary they
202
+ are the conversation's totals — same attribute, same honest meaning for its
203
+ scope, disambiguated by which read the object came from.
204
+
205
+ Cache tokens are standard: they were a local extension until the GenAI
206
+ conventions adopted them.
207
+ """
208
+
209
+ open_schema: ClassVar[bool] = True
210
+
211
+ input_tokens: int | None = None
212
+ output_tokens: int | None = None
213
+ cache_read: TokenCount | None = None
214
+ cache_creation: TokenCount | None = None
215
+
216
+
217
+ class GenAiToolCall(SpanModel):
218
+ """``gen_ai.tool.call.*``."""
219
+
220
+ open_schema: ClassVar[bool] = True
221
+
222
+ id: str | None = None
223
+ arguments: str | None = None
224
+ result: Any = None
225
+
226
+
227
+ class GenAiTool(SpanModel):
228
+ """``gen_ai.tool.*``."""
229
+
230
+ open_schema: ClassVar[bool] = True
231
+
232
+ name: str | None = None
233
+ type: str | None = None
234
+ description: str | None = None
235
+ call: GenAiToolCall | None = None
236
+ definitions: list[ToolDefinition] | None = None
237
+
238
+
239
+ class GenAiInput(SpanModel):
240
+ """``gen_ai.input.messages``.
241
+
242
+ Full history on item detail; the turn-local delta on the items list.
243
+ """
244
+
245
+ open_schema: ClassVar[bool] = True
246
+
247
+ messages: list[InputMessage] = Field(default_factory=list)
248
+
249
+
250
+ class GenAiOutput(SpanModel):
251
+ """``gen_ai.output.messages``."""
252
+
253
+ open_schema: ClassVar[bool] = True
254
+
255
+ messages: list[OutputMessage] = Field(default_factory=list)
256
+
257
+
258
+ class GenAiCost(SpanModel):
259
+ """``gen_ai.cost.usd``.
260
+
261
+ Not part of the published semantic conventions, but this is the name the
262
+ span is *written* with — the platform's cost column is derived from
263
+ ``gen_ai.cost.usd``, so the read returns the attribute under the name it
264
+ was stored as rather than relocating it.
265
+
266
+ Scoped by which read returned the span, the same way ``gen_ai.usage.*`` is:
267
+ this operation's cost on an item, the conversation total on a summary.
268
+
269
+ Distinct from ``introspection.llm.cost_usd``, which is the *provider*-
270
+ reported figure (e.g. OpenRouter's ``usage.cost``) rather than the SDK's
271
+ own calculation. Both can be present; they are different measurements.
272
+ """
273
+
274
+ open_schema: ClassVar[bool] = True
275
+
276
+ usd: float | None = None
277
+
278
+
279
+ class GenAiAttributes(SpanModel):
280
+ """The ``gen_ai.*`` attribute family, nested as the convention names it."""
281
+
282
+ open_schema: ClassVar[bool] = True
283
+
284
+ operation: GenAiOperation | None = None
285
+ provider: GenAiProvider | None = None
286
+ conversation: GenAiConversation | None = None
287
+ agent: GenAiAgent | None = None
288
+ request: GenAiRequest | None = None
289
+ response: GenAiResponse | None = None
290
+ usage: GenAiUsage | None = None
291
+ cost: GenAiCost | None = None
292
+ tool: GenAiTool | None = None
293
+ input: GenAiInput | None = None
294
+ output: GenAiOutput | None = None
295
+ system_instructions: list[SystemInstruction] | None = None
296
+
297
+
298
+ # --- introspection.* ------------------------------------------------------
299
+
300
+
301
+ class IdNode(SpanModel):
302
+ """An ``{id}`` node — ``introspection.org.id`` and friends."""
303
+
304
+ id: str | None = None
305
+
306
+
307
+ class IntrospectionRun(IdNode):
308
+ """``introspection.run.*``."""
309
+
310
+ root_id: str | None = None
311
+ """The run at the root of a chain of delegated runs."""
312
+ parent_id: str | None = None
313
+
314
+
315
+ class IntrospectionTask(IdNode):
316
+ """``introspection.task.*``."""
317
+
318
+ run_id: str | None = None
319
+
320
+
321
+ class IntrospectionAgent(SpanModel):
322
+ """``introspection.agent.*``: which agent in a runtime's agent tree made
323
+ the call."""
324
+
325
+ kind: str | None = None
326
+ """``session`` for the top-level agent."""
327
+ depth: str | None = None
328
+ """Nesting depth, ``"0"`` at the top. A string: it travels as baggage."""
329
+ parent_id: str | None = None
330
+ invocation_id: str | None = None
331
+ invocation_index: int | None = None
332
+
333
+
334
+ class IntrospectionInvocation(SpanModel):
335
+ """``introspection.invocation.*``."""
336
+
337
+ kind: str | None = None
338
+ """``turn`` for a span that wraps one turn of the agent loop."""
339
+
340
+
341
+ class IntrospectionIngest(SpanModel):
342
+ """``introspection.ingest.*``: the processor that handled the span."""
343
+
344
+ host: str | None = None
345
+ """Processor pod name."""
346
+ ip: str | None = None
347
+ """Processor pod IP."""
348
+ node: str | None = None
349
+ """Node the pod runs on."""
350
+ time: int | None = None
351
+ """When the processor handled the span's batch, microseconds since the
352
+ epoch."""
353
+
354
+
355
+ class IntrospectionRuntime(SpanModel):
356
+ """``introspection.runtime.*``.
357
+
358
+ Two ids, not one: ``id`` is the specific runtime deployment, ``group_id``
359
+ the stable group it belongs to. Typing this as a bare ``{id}`` node loses
360
+ ``group_id`` to ``model_extra`` — silently, because the tree is open.
361
+ """
362
+
363
+ id: str | None = None
364
+ group_id: str | None = None
365
+
366
+
367
+ class IntrospectionRecipe(SpanModel):
368
+ """``introspection.recipe.*``."""
369
+
370
+ git_commit_sha: str | None = None
371
+
372
+
373
+ class IntrospectionNewMessages(SpanModel):
374
+ """``introspection.history.new_messages.*``: the half-open range of this
375
+ call's input messages that were new to the conversation."""
376
+
377
+ start: int | None = None
378
+ end: int | None = None
379
+
380
+
381
+ class IntrospectionHistory(SpanModel):
382
+ """``introspection.history.*``: where this model call sits in the
383
+ conversation's message history, as the processor's linker inferred it.
384
+
385
+ Absent on spans the linker never placed, such as tool and API calls.
386
+ ``position`` is 1-based.
387
+ """
388
+
389
+ position: int | None = None
390
+ is_new: bool | None = None
391
+ continuation_method: str | None = None
392
+ hash_hit: bool | None = None
393
+ new_messages: IntrospectionNewMessages | None = None
394
+ loaded_messages: int | None = None
395
+ """``introspection.history.loaded_messages``: input messages ``[0, n)``
396
+ of this call were loaded from a run's ``messages``, not produced by a
397
+ model call. Only the first model call of such a run carries it."""
398
+
399
+
400
+ class IntrospectionContains(SpanModel):
401
+ """``introspection.contains.*``: what a chat span's sealed input delta and
402
+ output contain.
403
+
404
+ Stamped at ingest so a read can select rows without opening them.
405
+ ``values`` are the ``contains=`` filter values the span answers, spelled
406
+ exactly as a client passes them to ``items.list(contains=...)``, such as
407
+ ``"gen_ai.input.messages.role:user"`` or
408
+ ``"gen_ai.output.messages.parts.name:<tool>"``. A name list cut at the
409
+ processor's bound carries ``"<path>:*"``. Paths and names only, never
410
+ content. ``version`` is 0 or absent on a span that was never summarized.
411
+ """
412
+
413
+ version: int | None = None
414
+ values: list[str] | None = None
415
+
416
+
417
+ class IntrospectionAttributes(SpanModel):
418
+ """The ``introspection.*`` attribute family.
419
+
420
+ Everything here is ours.
421
+ """
422
+
423
+ org: IdNode | None = None
424
+ project: IdNode | None = None
425
+ member: IdNode | None = None
426
+ run: IntrospectionRun | None = None
427
+ task: IntrospectionTask | None = None
428
+ runtime: IntrospectionRuntime | None = None
429
+ experiment: IdNode | None = None
430
+ environment: str | None = None
431
+ turn: int | None = None
432
+ history: IntrospectionHistory | None = None
433
+ recipe: IntrospectionRecipe | None = None
434
+ contains: IntrospectionContains | None = None
435
+ tool_response_ids: list[str] | None = None
436
+ """``introspection.tool_response_ids``: the id of each tool response in a
437
+ chat span's input delta, which is the id of the tool call it answers.
438
+ Stamped from contains version 2; a list the processor cut at its bound
439
+ ends in ``*``."""
440
+ tool_call_ids: list[str] | None = None
441
+ """``introspection.tool_call_ids``: the id of each tool call a chat span's
442
+ output requests. Stamped from contains version 2; a list the processor
443
+ cut at its bound ends in ``*``."""
444
+ agent: IntrospectionAgent | None = None
445
+ invocation: IntrospectionInvocation | None = None
446
+ ingest: IntrospectionIngest | None = None
447
+ byok: bool | None = None
448
+ """Whether the call used the customer's own provider key."""
449
+ termination_reason: str | None = None
450
+ """Why the agent loop ended (``completed``, ...)."""
451
+
452
+
453
+ # --- the span -------------------------------------------------------------
454
+
455
+
456
+ class SpanAttributes(SpanModel):
457
+ """The span's attribute tree.
458
+
459
+ Typed for the two families we own the meaning of; open for everything
460
+ else, so a customer attribute survives the round trip.
461
+ """
462
+
463
+ open_schema: ClassVar[bool] = True
464
+
465
+ gen_ai: GenAiAttributes | None = None
466
+ introspection: IntrospectionAttributes | None = None
467
+
468
+
469
+ class SpanStatus(SpanModel):
470
+ """OpenTelemetry span status."""
471
+
472
+ code: SpanStatusCode | None = None
473
+ message: str | None = None
474
+
475
+
476
+ class GenAiSpan(SpanModel):
477
+ """One conversation item, or one conversation summary.
478
+
479
+ Same type either way — see the module docstring for what differs.
480
+ """
481
+
482
+ trace_id: str
483
+ span_id: str | None = None
484
+ parent_span_id: str | None = None
485
+ name: str | None = None
486
+ kind: SpanKind | None = None
487
+ start_time: datetime
488
+ end_time: datetime | None = None
489
+ duration_ns: int | None = None
490
+ status: SpanStatus | None = None
491
+ resource: dict[str, Any] | None = None
492
+ attributes: SpanAttributes = Field(default_factory=SpanAttributes)
493
+ #: The span's current annotation state, on an export read with
494
+ #: ``include=["annotations"]``; absent on a span nobody annotated.
495
+ annotation: AnnotationState | None = None
496
+
497
+ @property
498
+ def conversation_id(self) -> str | None:
499
+ """``attributes.gen_ai.conversation.id``, if present."""
500
+ gen_ai = self.attributes.gen_ai
501
+ return (
502
+ gen_ai.conversation.id if gen_ai and gen_ai.conversation else None
503
+ )
504
+
505
+ @property
506
+ def model(self) -> str | None:
507
+ """The model this span ran against — requested, else responded.
508
+
509
+ The old flat shape exposed this as a server-side ``coalesce()`` named
510
+ ``model_name``, which existed in no specification. Same precedence,
511
+ now visibly the client's choice rather than a field the API invents.
512
+ """
513
+ gen_ai = self.attributes.gen_ai
514
+ if gen_ai is None:
515
+ return None
516
+ requested = gen_ai.request.model if gen_ai.request else None
517
+ return requested or (
518
+ gen_ai.response.model if gen_ai.response else None
519
+ )
520
+
521
+ @property
522
+ def input_messages(self) -> list[InputMessage]:
523
+ """``attributes.gen_ai.input.messages`` — empty rather than absent.
524
+
525
+ A convenience for the common read. Reaching four levels down to answer
526
+ "what was said" is the one place this shape is worse than the flat one,
527
+ so the accessor pays that cost once here instead of at every call site.
528
+ """
529
+ gen_ai = self.attributes.gen_ai
530
+ return list(gen_ai.input.messages) if gen_ai and gen_ai.input else []
531
+
532
+ @property
533
+ def output_messages(self) -> list[OutputMessage]:
534
+ """``attributes.gen_ai.output.messages`` — empty rather than absent."""
535
+ gen_ai = self.attributes.gen_ai
536
+ return list(gen_ai.output.messages) if gen_ai and gen_ai.output else []
537
+
538
+
539
+ class ConversationCompaction(SpanModel):
540
+ """The compaction anchor an items read started from."""
541
+
542
+ applied: bool = False
543
+ """``False`` when no compaction anchor resolved and the read started at
544
+ the beginning of the conversation."""
545
+ response_id: str | None = None
546
+ """The response id the compaction anchor names."""
547
+ cursor: str | None = None
548
+ """Opaque cursor positioned at the anchor item."""
549
+ history: list[dict[str, Any]] = Field(default_factory=list)
550
+ """Recorded compactions, oldest first: each ``response_id`` with its
551
+ ``at_compaction`` and ``since_compaction`` counts."""
552
+
553
+
554
+ class GenAiSpanList(SpanModel):
555
+ """The ``/v1/conversations/{id}/items`` envelope.
556
+
557
+ ``first_id`` and ``last_id`` are informational; pagination uses the opaque
558
+ ``next`` cursor.
559
+ """
560
+
561
+ object: Literal["list"] = "list"
562
+ data: list[GenAiSpan] = Field(default_factory=list)
563
+ compaction: ConversationCompaction | None = None
564
+ """Where an items read started when it began at the compaction anchor;
565
+ absent on a read that did not ask for it."""
566
+ first_id: str | None = None
567
+ last_id: str | None = None
568
+ has_more: bool = False
569
+ next: str | None = None