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,807 @@
1
+ """GenAI spans → an ATIF trajectory.
2
+
3
+ One projection, read by everything that needs a Harbor trajectory of a
4
+ conversation: the platform's ATIF export feeds it the spans it stores, and an
5
+ eval adapter feeds it the spans of a local run. Its only input is the GenAI
6
+ span the conversation reads return (:class:`GenAiSpan`), so a trajectory is a
7
+ function of the stored conversation and of nothing else.
8
+
9
+ Spans are read in chronological order. A model-call span becomes one ``agent``
10
+ step carrying its text, reasoning, tool calls and usage; the tool results that
11
+ arrive in a later span's input are attached to the step that made the call.
12
+ ``gen_ai.input.messages`` may hold the whole prompt or only the turn's new
13
+ messages, so each span's input is aligned against what its agent has already
14
+ contributed and only the new messages become steps.
15
+
16
+ An ``execute_tool`` span adds what the prompt does not hold. Its structured
17
+ ``gen_ai.tool.call.result`` goes into the observation result of the same call,
18
+ under ``extra.details``, beside the ``content`` the model read: ATIF has no
19
+ field of its own for it, and ``extra`` is the format's place for custom
20
+ result-level metadata. A tool result the prompt never echoed, such as a
21
+ session's last tool call, becomes an observation result from the span alone.
22
+ The span may be read before or after the spans holding the call and the result.
23
+
24
+ A run that opens its conversation from ``messages`` loads every message but
25
+ the last into the session without a model call. Its first model call says so
26
+ with ``introspection.history.loaded_messages = n``: input messages ``[0, n)``
27
+ were loaded. The steps built from them are marked ``is_copied_context`` and
28
+ ``extra: {"loaded": true}``, so a reader such as Harbor can tell them from
29
+ what this conversation produced.
30
+
31
+ The caller chooses which spans to pass. Steps are one linear sequence, so a
32
+ conversation with delegated agents is normally read one agent at a time.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import json
38
+ from collections.abc import Iterable, Mapping
39
+ from dataclasses import dataclass
40
+ from typing import Any
41
+
42
+ from introspection_transform.genai import (
43
+ CompactionPart,
44
+ InputMessage,
45
+ TextPart,
46
+ ThinkingPart,
47
+ ToolCallRequestPart,
48
+ ToolCallResponsePart,
49
+ )
50
+ from introspection_transform.genai_span import GenAiSpan
51
+ from introspection_transform.trajectory import (
52
+ AtifAgent,
53
+ AtifFinalMetrics,
54
+ AtifMetrics,
55
+ AtifObservation,
56
+ AtifObservationResult,
57
+ AtifStep,
58
+ AtifToolCall,
59
+ AtifTrajectory,
60
+ )
61
+
62
+ __all__ = ["AtifProjection", "spans_to_atif"]
63
+
64
+ UNKNOWN = "unknown"
65
+
66
+
67
+ #: The keys of an agent framework's tool result, ``{content, details}`` on Pi:
68
+ #: only ``details`` is structured, ``content`` is the text the model reads.
69
+ TOOL_RESULT_ENVELOPE = frozenset({"content", "details", "isError"})
70
+
71
+
72
+ def spans_to_atif(
73
+ spans: Iterable[GenAiSpan],
74
+ *,
75
+ session_id: str | None = None,
76
+ agent_name: str | None = None,
77
+ agent_version: str | None = None,
78
+ ) -> AtifTrajectory:
79
+ """Project a conversation's spans onto one ATIF trajectory.
80
+
81
+ Spans are ordered by start time first, so a list read newest-first
82
+ converts the same as one read oldest-first.
83
+
84
+ Raises:
85
+ ValueError: when the spans hold no message, or a tool call without
86
+ an id. ATIF can represent neither.
87
+ """
88
+ projection = AtifProjection(
89
+ session_id=session_id,
90
+ agent_name=agent_name,
91
+ agent_version=agent_version,
92
+ )
93
+ ordered = sorted(spans, key=lambda span: span.start_time)
94
+ # The whole list is known, so a tool span that sorts after the result can
95
+ # still reach its step, and a batch read has no late span to fall back on.
96
+ projection._expect_tool_spans(ordered)
97
+ steps: list[AtifStep] = []
98
+ for span in ordered:
99
+ steps.extend(projection.add(span))
100
+ steps.extend(projection.finish())
101
+ return projection.trajectory(steps)
102
+
103
+
104
+ class AtifProjection:
105
+ """Incremental form of :func:`spans_to_atif`, for a streamed read.
106
+
107
+ Feed spans in chronological order with :meth:`add`; each call returns the
108
+ steps that are now final. :meth:`finish` returns the rest, after which
109
+ :attr:`agent`, :attr:`final_metrics` and :attr:`notes` are complete.
110
+
111
+ A step with tool calls is held back until its agent's next model call has
112
+ been read, because that call's input is where the results arrive.
113
+
114
+ ``tool_statuses`` maps a tool call id to whether the call succeeded, for a
115
+ caller that knows the outcomes before the spans stream past. Without it
116
+ the outcome is read from the ``execute_tool`` spans, each of which ends
117
+ before the model call that receives its result. A call named there also
118
+ holds its step until its span has been read, so a span that arrives after
119
+ the result still lands on it. Any other ``execute_tool`` span that arrives
120
+ once its step has been returned stands alone as a later ``system`` step,
121
+ the shape of a result whose call was never read; those that remain at
122
+ :meth:`finish` are written after every other step, so no step id moves.
123
+ """
124
+
125
+ def __init__(
126
+ self,
127
+ *,
128
+ session_id: str | None = None,
129
+ agent_name: str | None = None,
130
+ agent_version: str | None = None,
131
+ tool_statuses: Mapping[str, bool] | None = None,
132
+ ) -> None:
133
+ self.session_id = session_id
134
+ self._agent_name = agent_name
135
+ self._agent_version = agent_version
136
+ self._service_name: str | None = None
137
+ self._tool_ok: dict[str, bool] = dict(tool_statuses or {})
138
+ self._expected: set[str] = set(tool_statuses or {})
139
+ self._outputs: dict[str, ToolSpanOutput] = {}
140
+ self._answered: dict[str, tuple[AtifStep, AtifObservationResult]] = {}
141
+ self._awaited: dict[str, AtifStep] = {}
142
+ self._released_calls: set[str] = set()
143
+ self._held: list[AtifStep] = []
144
+ self._open: dict[str, list[AtifStep]] = {}
145
+ self._calls: dict[str, AtifStep] = {}
146
+ self._history: dict[str, list[str]] = {}
147
+ self._instructions: set[tuple[str, ...]] = set()
148
+ self._models: set[str] = set()
149
+ self._step_count = 0
150
+ self._omitted_parts = 0
151
+ self._model_calls = 0
152
+ self._usage_calls = 0
153
+ self._prompt_tokens = Total()
154
+ self._completion_tokens = Total()
155
+ self._cached_tokens = Total()
156
+ self._cost_usd = Total()
157
+
158
+ def add(self, span: GenAiSpan) -> list[AtifStep]:
159
+ """Read one span and return the steps it made final."""
160
+ gen_ai = span.attributes.gen_ai
161
+ if gen_ai is None:
162
+ return []
163
+ if self._agent_name is None and gen_ai.agent and gen_ai.agent.name:
164
+ self._agent_name = gen_ai.agent.name
165
+ if self._agent_version is None:
166
+ self._agent_version = _resource_value(span, "service", "version")
167
+ if self._service_name is None:
168
+ self._service_name = _resource_value(span, "service", "name")
169
+ if self.session_id is None:
170
+ self.session_id = span.conversation_id
171
+
172
+ self._read_tool_span(span)
173
+ inputs = span.input_messages
174
+ outputs = span.output_messages
175
+ if not inputs and not outputs:
176
+ return self._settled()
177
+
178
+ lane = _lane(span)
179
+ timestamp = _timestamp(span)
180
+ instructions = tuple(
181
+ instruction.content.strip()
182
+ for instruction in gen_ai.system_instructions or []
183
+ if instruction.content.strip()
184
+ )
185
+ if instructions and instructions not in self._instructions:
186
+ self._instructions.add(instructions)
187
+ self._append(
188
+ AtifStep(
189
+ step_id=self._next_id(),
190
+ timestamp=timestamp,
191
+ source="system",
192
+ message="\n\n".join(instructions),
193
+ )
194
+ )
195
+
196
+ introspection = span.attributes.introspection
197
+ history = introspection.history if introspection else None
198
+ declared = (
199
+ history.new_messages.start
200
+ if history and history.new_messages
201
+ else None
202
+ )
203
+ loaded = history.loaded_messages if history else None
204
+ loaded_ids = {id(message) for message in inputs[: loaded or 0]}
205
+ for message in self._new_messages(lane, inputs, declared):
206
+ self._input_step(
207
+ lane, message, timestamp, loaded=id(message) in loaded_ids
208
+ )
209
+ # The results of this agent's earlier calls arrive in this input, so
210
+ # whatever is still unanswered now stays unanswered.
211
+ self._close(lane)
212
+
213
+ if outputs:
214
+ self._history.setdefault(lane, []).extend(
215
+ _message_key(message) for message in outputs
216
+ )
217
+ self._agent_step(
218
+ lane, outputs, timestamp, model=_model_name(span), span=span
219
+ )
220
+ return self._settled()
221
+
222
+ def finish(self) -> list[AtifStep]:
223
+ """Return the steps still held, and complete the totals."""
224
+ for lane in list(self._open):
225
+ self._close(lane)
226
+ self._awaited.clear()
227
+ # Spans without a single message stay refused, by :meth:`trajectory`.
228
+ if self._step_count:
229
+ for call_id, output in self._outputs.items():
230
+ self._add_result(
231
+ call_id, output.content, output.details, output.timestamp
232
+ )
233
+ self._outputs.clear()
234
+ return self._settled()
235
+
236
+ @property
237
+ def agent(self) -> AtifAgent:
238
+ """The producing agent; its model is set only when one was observed."""
239
+ return AtifAgent(
240
+ name=self._agent_name or self._service_name or UNKNOWN,
241
+ version=self._agent_version or UNKNOWN,
242
+ model_name=(
243
+ next(iter(self._models)) if len(self._models) == 1 else None
244
+ ),
245
+ )
246
+
247
+ @property
248
+ def final_metrics(self) -> AtifFinalMetrics:
249
+ """The totals; one is set only when every model call reported it.
250
+
251
+ A partial sum would read as the whole, so a metric some call left
252
+ out stays unset. The read omits a zero, so two absences are known:
253
+ a call that reported usage without cached tokens read none from the
254
+ cache, and a call that used no tokens cost nothing.
255
+ """
256
+ calls = self._model_calls
257
+ return AtifFinalMetrics(
258
+ total_prompt_tokens=_whole(self._prompt_tokens.over(calls)),
259
+ total_completion_tokens=_whole(
260
+ self._completion_tokens.over(calls)
261
+ ),
262
+ total_cached_tokens=(
263
+ _whole(self._cached_tokens.value)
264
+ if calls and self._usage_calls == calls
265
+ else None
266
+ ),
267
+ total_cost_usd=self._cost_usd.over(calls),
268
+ total_steps=self._step_count,
269
+ )
270
+
271
+ @property
272
+ def notes(self) -> str | None:
273
+ """What the projection could not carry, or ``None``."""
274
+ if not self._omitted_parts:
275
+ return None
276
+ return (
277
+ f"{self._omitted_parts} non-text message part(s) were omitted: "
278
+ "this projection writes text-only messages."
279
+ )
280
+
281
+ def trajectory(self, steps: list[AtifStep]) -> AtifTrajectory:
282
+ """Assemble the trajectory from every step the projection returned."""
283
+ if not steps:
284
+ raise ValueError("the spans hold no message to project onto ATIF")
285
+ return AtifTrajectory(
286
+ session_id=self.session_id,
287
+ agent=self.agent,
288
+ steps=steps,
289
+ notes=self.notes,
290
+ final_metrics=self.final_metrics,
291
+ )
292
+
293
+ def _next_id(self) -> int:
294
+ self._step_count += 1
295
+ return self._step_count
296
+
297
+ def _append(self, step: AtifStep) -> None:
298
+ self._held.append(step)
299
+
300
+ def _settled(self) -> list[AtifStep]:
301
+ """Pop the leading steps no later result can still change."""
302
+ waiting = {id(step) for steps in self._open.values() for step in steps}
303
+ waiting.update(id(step) for step in self._awaited.values())
304
+ count = 0
305
+ while count < len(self._held) and id(self._held[count]) not in waiting:
306
+ count += 1
307
+ settled, self._held = self._held[:count], self._held[count:]
308
+ # Only the ids outlive a returned step, so a stream holds no history.
309
+ released = {id(step) for step in settled}
310
+ for call_id, (step, _) in list(self._answered.items()):
311
+ if id(step) in released:
312
+ del self._answered[call_id]
313
+ self._released_calls.add(call_id)
314
+ return settled
315
+
316
+ def _close(self, lane: str) -> None:
317
+ for step in self._open.pop(lane, []):
318
+ for call in step.tool_calls or []:
319
+ call_id = call.tool_call_id
320
+ self._calls.pop(call_id, None)
321
+ output = (
322
+ None
323
+ if call_id in self._answered
324
+ else self._outputs.pop(call_id, None)
325
+ )
326
+ if output is not None:
327
+ self._add_result(
328
+ call_id,
329
+ output.content,
330
+ output.details,
331
+ output.timestamp,
332
+ step=step,
333
+ )
334
+ elif call_id in self._expected:
335
+ self._awaited[call_id] = step
336
+
337
+ def _expect_tool_spans(self, spans: Iterable[GenAiSpan]) -> None:
338
+ self._expected.update(filter(None, map(_tool_call_id, spans)))
339
+
340
+ def _read_tool_span(self, span: GenAiSpan) -> None:
341
+ call_id = _tool_call_id(span)
342
+ gen_ai = span.attributes.gen_ai
343
+ call = gen_ai.tool.call if gen_ai and gen_ai.tool else None
344
+ if not call_id or call is None:
345
+ return
346
+ code = span.status.code if span.status else None
347
+ if code in ("Ok", "Error"):
348
+ self._tool_ok.setdefault(call_id, code == "Ok")
349
+ self._expected.discard(call_id)
350
+ awaited = self._awaited.pop(call_id, None)
351
+ content, details = _tool_output(call.result)
352
+ failed = self._tool_ok.get(call_id) is False
353
+ if content is None and details is None and not failed:
354
+ return
355
+ output = ToolSpanOutput(_timestamp(span), content, details)
356
+ answered = self._answered.get(call_id)
357
+ if answered is not None:
358
+ self._merge(call_id, answered[1], output)
359
+ elif call_id in self._released_calls:
360
+ # The step is already with the caller and cannot change.
361
+ if details is not None or failed:
362
+ self._add_result(call_id, content, details, output.timestamp)
363
+ elif awaited is not None:
364
+ self._add_result(
365
+ call_id, content, details, output.timestamp, step=awaited
366
+ )
367
+ else:
368
+ self._outputs[call_id] = output
369
+
370
+ def _merge(
371
+ self,
372
+ call_id: str,
373
+ result: AtifObservationResult,
374
+ output: ToolSpanOutput,
375
+ ) -> None:
376
+ """Add a tool span read after its result to that result."""
377
+ if result.content is None:
378
+ result.content = output.content
379
+ extra = {
380
+ **(result.extra or {}),
381
+ **self._result_extra(call_id, output.details),
382
+ }
383
+ result.extra = extra or None
384
+
385
+ def _result_extra(
386
+ self, call_id: str | None, details: Any
387
+ ) -> dict[str, Any]:
388
+ extra: dict[str, Any] = {}
389
+ if call_id is not None and self._tool_ok.get(call_id) is False:
390
+ extra["is_error"] = True
391
+ if details is not None:
392
+ extra["details"] = details
393
+ return extra
394
+
395
+ def _new_messages(
396
+ self,
397
+ lane: str,
398
+ messages: list[InputMessage],
399
+ declared_start: int | None,
400
+ ) -> list[InputMessage]:
401
+ """The messages of ``messages`` this agent has not contributed yet.
402
+
403
+ Also advances the agent's prompt history to ``messages``.
404
+ """
405
+ history = self._history.setdefault(lane, [])
406
+ keys = [_message_key(message) for message in messages]
407
+ lead = (
408
+ 1
409
+ if len(messages) > 1
410
+ and history
411
+ and _is_compaction(messages[0])
412
+ and keys[0] not in history
413
+ else 0
414
+ )
415
+ offset, matched = _align(history, keys[lead:], declared_start)
416
+ if lead:
417
+ # A compacted prompt restarts the history at the summary; only
418
+ # the retained tail can repeat what was already contributed.
419
+ self._history[lane] = keys
420
+ return [messages[0], *messages[lead + matched :]]
421
+ if matched == len(keys) and matched > 1:
422
+ # The same prompt again: a retried call adds nothing.
423
+ return []
424
+ if 0 < matched < len(keys):
425
+ self._history[lane] = [*history[:offset], *keys]
426
+ return messages[matched:]
427
+ history.extend(keys)
428
+ return messages
429
+
430
+ def _input_step(
431
+ self,
432
+ lane: str,
433
+ message: InputMessage,
434
+ timestamp: str,
435
+ *,
436
+ loaded: bool = False,
437
+ ) -> None:
438
+ if message.role == "assistant":
439
+ self._agent_step(
440
+ lane,
441
+ [message],
442
+ timestamp,
443
+ model=None,
444
+ span=None,
445
+ loaded=loaded,
446
+ )
447
+ return
448
+ text: list[str] = []
449
+ for part in message.parts:
450
+ if isinstance(part, TextPart | CompactionPart):
451
+ if part.content:
452
+ text.append(part.content)
453
+ elif isinstance(part, ToolCallResponsePart):
454
+ self._attach_result(part, timestamp)
455
+ elif not isinstance(part, ThinkingPart):
456
+ self._omitted_parts += 1
457
+ if text:
458
+ self._append(
459
+ AtifStep(
460
+ step_id=self._next_id(),
461
+ timestamp=timestamp,
462
+ source="system" if message.role == "system" else "user",
463
+ message="\n\n".join(text),
464
+ **_loaded_marks(loaded),
465
+ )
466
+ )
467
+
468
+ def _attach_result(
469
+ self, part: ToolCallResponsePart, timestamp: str
470
+ ) -> None:
471
+ response = part.response
472
+ content = (
473
+ response if isinstance(response, str) else json.dumps(response)
474
+ )
475
+ output = self._outputs.pop(part.id, None) if part.id else None
476
+ self._add_result(
477
+ part.id,
478
+ content,
479
+ output.details if output else None,
480
+ timestamp,
481
+ step=self._calls.get(part.id) if part.id else None,
482
+ )
483
+
484
+ def _add_result(
485
+ self,
486
+ call_id: str | None,
487
+ content: str | None,
488
+ details: Any,
489
+ timestamp: str,
490
+ *,
491
+ step: AtifStep | None = None,
492
+ ) -> None:
493
+ """Add one result to the step of its call, or as a step of its own."""
494
+ extra = self._result_extra(call_id, details)
495
+ if step is None:
496
+ # ATIF only lets a result name a call of its own step, so a
497
+ # result whose call was never read stands alone.
498
+ result = AtifObservationResult(
499
+ content=content,
500
+ extra=(
501
+ {"tool_call_id": call_id, **extra}
502
+ if call_id
503
+ else extra or None
504
+ ),
505
+ )
506
+ step = AtifStep(
507
+ step_id=self._next_id(),
508
+ timestamp=timestamp,
509
+ source="system",
510
+ message="",
511
+ observation=AtifObservation(results=[result]),
512
+ )
513
+ self._append(step)
514
+ else:
515
+ result = AtifObservationResult(
516
+ source_call_id=call_id, content=content, extra=extra or None
517
+ )
518
+ if step.observation is None:
519
+ step.observation = AtifObservation(results=[])
520
+ step.observation.results.append(result)
521
+ if call_id:
522
+ self._answered[call_id] = (step, result)
523
+
524
+ def _agent_step(
525
+ self,
526
+ lane: str,
527
+ messages: list[Any],
528
+ timestamp: str,
529
+ *,
530
+ model: str | None,
531
+ span: GenAiSpan | None,
532
+ loaded: bool = False,
533
+ ) -> None:
534
+ text: list[str] = []
535
+ reasoning: list[str] = []
536
+ calls: list[AtifToolCall] = []
537
+ for message in messages:
538
+ for part in message.parts:
539
+ if isinstance(part, TextPart | CompactionPart):
540
+ if part.content:
541
+ text.append(part.content)
542
+ elif isinstance(part, ThinkingPart):
543
+ if part.content:
544
+ reasoning.append(part.content)
545
+ elif isinstance(part, ToolCallRequestPart):
546
+ if not part.id:
547
+ raise ValueError(
548
+ "ATIF cannot represent a tool call without an id"
549
+ )
550
+ calls.append(
551
+ AtifToolCall(
552
+ tool_call_id=part.id,
553
+ function_name=part.name,
554
+ arguments=_arguments(part.arguments),
555
+ )
556
+ )
557
+ else:
558
+ self._omitted_parts += 1
559
+ step = AtifStep(
560
+ step_id=self._next_id(),
561
+ timestamp=timestamp,
562
+ source="agent",
563
+ model_name=model,
564
+ message="\n\n".join(text),
565
+ reasoning_content="\n\n".join(reasoning) or None,
566
+ tool_calls=calls or None,
567
+ metrics=self._metrics(span) if span is not None else None,
568
+ llm_call_count=1 if span is not None else None,
569
+ **_loaded_marks(loaded),
570
+ )
571
+ if model:
572
+ self._models.add(model)
573
+ self._append(step)
574
+ if calls:
575
+ self._open.setdefault(lane, []).append(step)
576
+ for call in calls:
577
+ self._calls[call.tool_call_id] = step
578
+ self._answered.pop(call.tool_call_id, None)
579
+ self._awaited.pop(call.tool_call_id, None)
580
+ self._released_calls.discard(call.tool_call_id)
581
+
582
+ def _metrics(self, span: GenAiSpan) -> AtifMetrics:
583
+ gen_ai = span.attributes.gen_ai
584
+ usage = gen_ai.usage if gen_ai else None
585
+ cost = gen_ai.cost.usd if gen_ai and gen_ai.cost else None
586
+ prompt = usage.input_tokens if usage else None
587
+ completion = usage.output_tokens if usage else None
588
+ cached = (
589
+ usage.cache_read.input_tokens
590
+ if usage and usage.cache_read
591
+ else None
592
+ )
593
+ self._model_calls += 1
594
+ if usage is not None:
595
+ self._usage_calls += 1
596
+ self._prompt_tokens.add(prompt)
597
+ self._completion_tokens.add(completion)
598
+ self._cached_tokens.add(cached)
599
+ unused = prompt == 0 and completion == 0
600
+ self._cost_usd.add(0.0 if cost is None and unused else cost)
601
+ return AtifMetrics(
602
+ prompt_tokens=prompt,
603
+ completion_tokens=completion,
604
+ cached_tokens=cached,
605
+ cost_usd=cost,
606
+ )
607
+
608
+
609
+ @dataclass
610
+ class ToolSpanOutput:
611
+ """What an ``execute_tool`` span said, until a result of its call takes it."""
612
+
613
+ timestamp: str
614
+ content: str | None
615
+ details: Any
616
+
617
+
618
+ class Total:
619
+ """A sum that remembers how many model calls reported a value."""
620
+
621
+ def __init__(self) -> None:
622
+ self.value = 0.0
623
+ self.reported = 0
624
+
625
+ def add(self, value: float | None) -> None:
626
+ if value is not None:
627
+ self.value += value
628
+ self.reported += 1
629
+
630
+ def over(self, calls: int) -> float | None:
631
+ """The sum, when each of ``calls`` model calls reported a value."""
632
+ return self.value if calls and self.reported == calls else None
633
+
634
+
635
+ def _loaded_marks(loaded: bool) -> dict[str, Any]:
636
+ """How a step built from a loaded input message is marked.
637
+
638
+ ATIF's ``is_copied_context`` keeps it out of training data, and
639
+ ``extra.loaded`` says why.
640
+ """
641
+ if not loaded:
642
+ return {}
643
+ return {"is_copied_context": True, "extra": {"loaded": True}}
644
+
645
+
646
+ def _whole(value: float | None) -> int | None:
647
+ return None if value is None else int(value)
648
+
649
+
650
+ def _timestamp(span: GenAiSpan) -> str:
651
+ return span.start_time.isoformat().replace("+00:00", "Z")
652
+
653
+
654
+ def _tool_call_id(span: GenAiSpan) -> str | None:
655
+ gen_ai = span.attributes.gen_ai
656
+ call = gen_ai.tool.call if gen_ai and gen_ai.tool else None
657
+ return call.id if call else None
658
+
659
+
660
+ def _tool_output(result: Any) -> tuple[str | None, Any]:
661
+ """``gen_ai.tool.call.result`` as ``(the tool's text, structured details)``.
662
+
663
+ The attribute holds what the emitter wrote, and emitters stringify it. A
664
+ string that holds no object or array is the tool's text and has no details.
665
+ An envelope (:data:`TOOL_RESULT_ENVELOPE`) splits into its two halves, and
666
+ any other value is the details itself.
667
+ """
668
+ if result is None:
669
+ return None, None
670
+ value = result
671
+ if isinstance(result, str):
672
+ try:
673
+ value = json.loads(result)
674
+ except ValueError:
675
+ value = None
676
+ if not isinstance(value, dict | list):
677
+ return result or None, None
678
+ if (
679
+ isinstance(value, dict)
680
+ and value.keys() <= TOOL_RESULT_ENVELOPE
681
+ and ("details" in value or isinstance(value.get("content"), list))
682
+ ):
683
+ return _envelope_text(value.get("content")), value.get("details")
684
+ return result if isinstance(result, str) else json.dumps(result), value
685
+
686
+
687
+ def _envelope_text(content: Any) -> str | None:
688
+ """An envelope's content as ATIF's text; a non-text part stays as JSON."""
689
+ if content is None or content == []:
690
+ return None
691
+ if isinstance(content, str):
692
+ return content
693
+ if isinstance(content, list) and all(
694
+ isinstance(part, dict) and part.get("type") == "text"
695
+ for part in content
696
+ ):
697
+ return "\n\n".join(str(part.get("text", "")) for part in content)
698
+ return json.dumps(content)
699
+
700
+
701
+ def _lane(span: GenAiSpan) -> str:
702
+ """Prompt history is cumulative per agent, so it is kept per agent."""
703
+ agent = span.attributes.gen_ai.agent if span.attributes.gen_ai else None
704
+ if agent and agent.id:
705
+ return f"id:{agent.id}"
706
+ if agent and agent.name:
707
+ return f"name:{agent.name}"
708
+ return "root"
709
+
710
+
711
+ def _model_name(span: GenAiSpan) -> str | None:
712
+ gen_ai = span.attributes.gen_ai
713
+ if gen_ai is None:
714
+ return None
715
+ model = (gen_ai.response.model if gen_ai.response else None) or (
716
+ gen_ai.request.model if gen_ai.request else None
717
+ )
718
+ if not model:
719
+ return None
720
+ provider = gen_ai.provider.name if gen_ai.provider else None
721
+ return f"{provider}/{model}" if provider else model
722
+
723
+
724
+ def _resource_value(span: GenAiSpan, *path: str) -> str | None:
725
+ """A resource attribute, whether the resource is nested or dotted."""
726
+ resource = span.resource or {}
727
+ flat = resource.get(".".join(path))
728
+ if isinstance(flat, str) and flat:
729
+ return flat
730
+ node: Any = resource
731
+ for key in path:
732
+ node = node.get(key) if isinstance(node, dict) else None
733
+ return node if isinstance(node, str) and node else None
734
+
735
+
736
+ def _arguments(arguments: Any) -> dict[str, Any]:
737
+ """Tool arguments as the object ATIF requires.
738
+
739
+ A malformed or scalar value is kept under ``_raw``, as the trajectory-v1
740
+ projection does, so the evidence survives.
741
+ """
742
+ if arguments is None:
743
+ return {}
744
+ if isinstance(arguments, dict):
745
+ return arguments
746
+ if isinstance(arguments, str):
747
+ try:
748
+ parsed = json.loads(arguments)
749
+ except ValueError:
750
+ parsed = None
751
+ if isinstance(parsed, dict):
752
+ return parsed
753
+ return {"_raw": arguments}
754
+
755
+
756
+ def _is_compaction(message: Any) -> bool:
757
+ return any(isinstance(part, CompactionPart) for part in message.parts)
758
+
759
+
760
+ def _message_key(message: Any) -> str:
761
+ """Identity of a message for alignment.
762
+
763
+ Reasoning is left out: a model's output carries it, the same message
764
+ sent back as input may not.
765
+ """
766
+ parts: list[Any] = []
767
+ for part in message.parts:
768
+ if isinstance(part, ThinkingPart):
769
+ continue
770
+ if isinstance(part, TextPart | CompactionPart):
771
+ parts.append([part.type, part.content])
772
+ elif isinstance(part, ToolCallRequestPart):
773
+ parts.append([part.type, part.id, part.name, part.arguments])
774
+ elif isinstance(part, ToolCallResponsePart):
775
+ parts.append([part.type, part.id, part.response])
776
+ else:
777
+ parts.append(part.model_dump(mode="json"))
778
+ return json.dumps([message.role, parts], sort_keys=True, default=str)
779
+
780
+
781
+ def _align(
782
+ history: list[str], keys: list[str], declared_start: int | None
783
+ ) -> tuple[int, int]:
784
+ """Where ``keys`` repeats ``history``: ``(offset, matched length)``.
785
+
786
+ A prompt that repeats history either starts where the history starts (or
787
+ where the span declares its new messages start), or runs to the history's
788
+ end. Any other overlap is a coincidence, such as a user repeating an
789
+ earlier message, and is not taken.
790
+ """
791
+ best = (0, 0)
792
+ if not keys:
793
+ return best
794
+ anchored = {0}
795
+ if declared_start is not None and 0 <= declared_start <= len(history):
796
+ anchored.add(declared_start)
797
+ for offset in range(len(history)):
798
+ if history[offset] != keys[0]:
799
+ continue
800
+ limit = min(len(keys), len(history) - offset)
801
+ matched = 0
802
+ while matched < limit and history[offset + matched] == keys[matched]:
803
+ matched += 1
804
+ reaches_end = offset + matched == len(history)
805
+ if (offset in anchored or reaches_end) and matched >= best[1]:
806
+ best = (offset, matched)
807
+ return best