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,231 @@
1
+ """An ATIF trajectory → the AG-UI messages that open a run.
2
+
3
+ A Harbor adapter's ``load()`` seeds an agent's session from a previous
4
+ trajectory (Harbor's ``trajectory.json``) and then runs the task instruction.
5
+ On Introspection that is one call: :func:`atif_to_messages` turns the
6
+ trajectory into run ``messages``, with the instruction as the last user
7
+ message, and ``tasks.runs.create(task_id, messages=...)`` loads every message
8
+ but the last into an empty conversation and runs the last as the prompt.
9
+
10
+ What maps, step by step, in order:
11
+
12
+ - a ``user`` step becomes a user message;
13
+ - an ``agent`` step becomes an assistant message with its text and tool
14
+ calls, followed by one tool message per observation result, paired with
15
+ its call by ``source_call_id``. A result marked ``extra.is_error`` carries
16
+ its content as the tool message's ``error`` too;
17
+ - a ``system`` step is left out, as Harbor's own loaders leave it out: the
18
+ Runtime's recipe owns the system prompt.
19
+
20
+ Reasoning, metrics and ``extra`` have no AG-UI field and are left out, and
21
+ an agent step with neither text, tool calls nor results adds no message. Anything
22
+ else that the messages cannot carry raises :class:`AtifConversionError`
23
+ rather than being dropped: a tool call without exactly one result in its own
24
+ step, a result naming no call of its step (also on a step without calls),
25
+ non-text content, an empty user
26
+ message, and a list whose last message is not a user message.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import json
32
+ import logging
33
+ from collections.abc import Mapping
34
+ from typing import Any
35
+
36
+ from ag_ui.core import (
37
+ AssistantMessage,
38
+ FunctionCall,
39
+ Message,
40
+ ToolCall,
41
+ ToolMessage,
42
+ UserMessage,
43
+ )
44
+ from pydantic import BaseModel
45
+
46
+ __all__ = ["AtifConversionError", "atif_to_messages"]
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+
51
+ class AtifConversionError(ValueError):
52
+ """The trajectory holds something run ``messages`` cannot express.
53
+
54
+ ``step_id`` names the step at fault, or is ``None`` when the fault is the
55
+ trajectory as a whole.
56
+ """
57
+
58
+ def __init__(self, message: str, *, step_id: int | None = None) -> None:
59
+ super().__init__(
60
+ message if step_id is None else f"step {step_id}: {message}"
61
+ )
62
+ self.step_id = step_id
63
+
64
+
65
+ def atif_to_messages(
66
+ trajectory: Mapping[str, Any] | BaseModel,
67
+ *,
68
+ prompt: str | None = None,
69
+ ) -> list[Message]:
70
+ """The run ``messages`` that load ``trajectory`` and then run ``prompt``.
71
+
72
+ ``trajectory`` is an ATIF trajectory: the parsed ``trajectory.json``, an
73
+ :class:`~introspection_transform.trajectory.AtifTrajectory`, or Harbor's own
74
+ ``Trajectory`` model. Only its own ``steps`` are read, never a subagent's
75
+ trajectory.
76
+
77
+ ``prompt``, the task instruction, is appended as the last user message.
78
+ Without it the trajectory's last kept step must be a user step, which
79
+ then runs as the prompt.
80
+
81
+ Raises:
82
+ AtifConversionError: a step the messages cannot express (see the
83
+ module docstring), or no user message last.
84
+ """
85
+ data = (
86
+ trajectory.model_dump(mode="json")
87
+ if isinstance(trajectory, BaseModel)
88
+ else trajectory
89
+ )
90
+ steps = data.get("steps")
91
+ if not isinstance(steps, list):
92
+ raise AtifConversionError("the trajectory has no steps list")
93
+ messages: list[Message] = []
94
+ for step in steps:
95
+ messages.extend(_step_messages(step))
96
+ if prompt is not None:
97
+ messages.append(UserMessage(id="prompt", content=prompt))
98
+ if not messages or not isinstance(messages[-1], UserMessage):
99
+ raise AtifConversionError(
100
+ "the last message must be a user message: pass the task "
101
+ "instruction as prompt"
102
+ )
103
+ logger.debug(
104
+ "Converted an ATIF trajectory to run messages",
105
+ extra={"steps": len(steps), "messages": len(messages)},
106
+ )
107
+ return messages
108
+
109
+
110
+ def _step_messages(step: Mapping[str, Any]) -> list[Message]:
111
+ step_id = step.get("step_id")
112
+ source = step.get("source")
113
+ if source == "system":
114
+ return []
115
+ text = _text(step.get("message"), step_id)
116
+ if source == "user":
117
+ if step.get("tool_calls") or step.get("observation"):
118
+ raise AtifConversionError(
119
+ "a user step with tool calls or an observation has no "
120
+ "message form",
121
+ step_id=step_id,
122
+ )
123
+ if not text:
124
+ raise AtifConversionError(
125
+ "a user message needs text", step_id=step_id
126
+ )
127
+ return [UserMessage(id=f"atif-step-{step_id}", content=text)]
128
+ if source == "agent":
129
+ return _agent_messages(step, step_id, text)
130
+ raise AtifConversionError(
131
+ f"unknown step source {source!r}", step_id=step_id
132
+ )
133
+
134
+
135
+ def _agent_messages(
136
+ step: Mapping[str, Any], step_id: Any, text: str
137
+ ) -> list[Message]:
138
+ calls = [
139
+ _tool_call(call, step_id) for call in step.get("tool_calls") or []
140
+ ]
141
+ if not text and not calls:
142
+ if (step.get("observation") or {}).get("results"):
143
+ # A result answers a call; with none in its step it pairs with
144
+ # nothing, and dropping the step would lose it unseen.
145
+ raise AtifConversionError(
146
+ "an observation result without a tool call in its step "
147
+ "pairs with nothing",
148
+ step_id=step_id,
149
+ )
150
+ return []
151
+ messages: list[Message] = [
152
+ AssistantMessage(
153
+ id=f"atif-step-{step_id}",
154
+ content=text or None,
155
+ tool_calls=calls or None,
156
+ )
157
+ ]
158
+ results = _results_by_call(step, step_id, {call.id for call in calls})
159
+ for call in calls:
160
+ result = results.get(call.id)
161
+ if result is None:
162
+ raise AtifConversionError(
163
+ f"tool call {call.id!r} has no result in its step",
164
+ step_id=step_id,
165
+ )
166
+ content = _text(result.get("content"), step_id)
167
+ failed = bool((result.get("extra") or {}).get("is_error"))
168
+ messages.append(
169
+ ToolMessage(
170
+ id=f"atif-step-{step_id}-result-{call.id}",
171
+ content=content,
172
+ tool_call_id=call.id,
173
+ error=(content or "the tool call failed") if failed else None,
174
+ )
175
+ )
176
+ return messages
177
+
178
+
179
+ def _tool_call(call: Mapping[str, Any], step_id: Any) -> ToolCall:
180
+ call_id = call.get("tool_call_id")
181
+ name = call.get("function_name")
182
+ if not call_id or not name:
183
+ raise AtifConversionError(
184
+ "a tool call needs a tool_call_id and a function_name",
185
+ step_id=step_id,
186
+ )
187
+ return ToolCall(
188
+ id=call_id,
189
+ function=FunctionCall(
190
+ name=name, arguments=json.dumps(call.get("arguments") or {})
191
+ ),
192
+ )
193
+
194
+
195
+ def _results_by_call(
196
+ step: Mapping[str, Any], step_id: Any, call_ids: set[str]
197
+ ) -> dict[str, Mapping[str, Any]]:
198
+ observation = step.get("observation") or {}
199
+ results: dict[str, Mapping[str, Any]] = {}
200
+ for result in observation.get("results") or []:
201
+ call_id = result.get("source_call_id")
202
+ if call_id not in call_ids:
203
+ raise AtifConversionError(
204
+ f"observation result for {call_id!r} names no tool call of "
205
+ "its step",
206
+ step_id=step_id,
207
+ )
208
+ if call_id in results:
209
+ raise AtifConversionError(
210
+ f"tool call {call_id!r} has more than one result",
211
+ step_id=step_id,
212
+ )
213
+ results[call_id] = result
214
+ return results
215
+
216
+
217
+ def _text(content: Any, step_id: Any) -> str:
218
+ """A message or result as text; ATIF's text-only part lists join."""
219
+ if content is None:
220
+ return ""
221
+ if isinstance(content, str):
222
+ return content
223
+ if isinstance(content, list) and all(
224
+ isinstance(part, Mapping) and part.get("type") == "text"
225
+ for part in content
226
+ ):
227
+ return "\n\n".join(str(part.get("text") or "") for part in content)
228
+ raise AtifConversionError(
229
+ "non-text content (an image or other part) has no message form",
230
+ step_id=step_id,
231
+ )