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.
- introspection_transform/__init__.py +43 -0
- introspection_transform/annotations.py +57 -0
- introspection_transform/genai.py +412 -0
- introspection_transform/genai_span.py +569 -0
- introspection_transform/messages.py +231 -0
- introspection_transform/projection.py +807 -0
- introspection_transform/py.typed +0 -0
- introspection_transform/training.py +351 -0
- introspection_transform/trajectory.py +156 -0
- introspection_transform-0.2.0.dist-info/METADATA +75 -0
- introspection_transform-0.2.0.dist-info/RECORD +13 -0
- introspection_transform-0.2.0.dist-info/WHEEL +4 -0
- introspection_transform-0.2.0.dist-info/licenses/LICENSE +191 -0
|
File without changes
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
"""A GenAI span → one training example in ``introspection.training/v1``, and its provider views.
|
|
2
|
+
|
|
3
|
+
The format is OpenAI chat ``messages`` with ``trainable`` on every message, the
|
|
4
|
+
agent's ``tools``, an optional ``rejected`` completion and ``metadata`` no
|
|
5
|
+
provider sees (introspection-cloud ``docs/design/training-format.md``). The
|
|
6
|
+
Fireworks and Tinker training toolchains both read its SFT view; its DPO view is
|
|
7
|
+
the chosen/rejected pair.
|
|
8
|
+
|
|
9
|
+
One span is one example: its system instructions, its input messages, and its
|
|
10
|
+
output as the one trainable reply. A span from a conversation item detail read
|
|
11
|
+
carries the whole history in its input messages, so it makes a complete
|
|
12
|
+
multi-turn example; one from a list read carries only that call's new messages.
|
|
13
|
+
|
|
14
|
+
What maps:
|
|
15
|
+
|
|
16
|
+
- ``system_instructions``, and any ``system`` input message, become one
|
|
17
|
+
leading ``system`` message;
|
|
18
|
+
- a text part is text, a thinking part a ``{"type": "thinking"}`` part, a
|
|
19
|
+
compaction part the summary text the model was shown;
|
|
20
|
+
- an assistant's tool call parts become its ``tool_calls``, with the arguments
|
|
21
|
+
as a JSON string;
|
|
22
|
+
- each tool response part becomes its own ``tool`` message;
|
|
23
|
+
- ``gen_ai.tool.definitions`` become OpenAI function ``tools``.
|
|
24
|
+
|
|
25
|
+
Anything else (an image, a file, an unknown part, a tool call without an id)
|
|
26
|
+
raises :class:`TrainingConversionError` rather than being dropped, since an
|
|
27
|
+
example missing what the model saw teaches the wrong thing.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import json
|
|
33
|
+
import logging
|
|
34
|
+
from typing import Any, Literal
|
|
35
|
+
|
|
36
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
37
|
+
|
|
38
|
+
from introspection_transform.genai import (
|
|
39
|
+
CompactionPart,
|
|
40
|
+
InputMessage,
|
|
41
|
+
OutputMessage,
|
|
42
|
+
TextPart,
|
|
43
|
+
ThinkingPart,
|
|
44
|
+
ToolCallRequestPart,
|
|
45
|
+
ToolCallResponsePart,
|
|
46
|
+
)
|
|
47
|
+
from introspection_transform.genai_span import GenAiSpan
|
|
48
|
+
|
|
49
|
+
__all__ = [
|
|
50
|
+
"TRAINING_FORMAT",
|
|
51
|
+
"TrainingConversionError",
|
|
52
|
+
"TrainingExample",
|
|
53
|
+
"TrainingMessage",
|
|
54
|
+
"TrainingMetadata",
|
|
55
|
+
"TrainingSource",
|
|
56
|
+
"dpo_pair",
|
|
57
|
+
"sft_row",
|
|
58
|
+
"span_to_example",
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
logger = logging.getLogger(__name__)
|
|
62
|
+
|
|
63
|
+
TRAINING_FORMAT = "introspection.training/v1"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class TrainingConversionError(ValueError):
|
|
67
|
+
"""The span holds something a training example cannot carry."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class TrainingMessage(BaseModel):
|
|
71
|
+
"""One OpenAI chat message, with whether its tokens are trained on."""
|
|
72
|
+
|
|
73
|
+
model_config = ConfigDict(extra="forbid")
|
|
74
|
+
|
|
75
|
+
role: Literal["system", "user", "assistant", "tool"]
|
|
76
|
+
content: str | list[dict[str, str]] | None = None
|
|
77
|
+
tool_calls: list[dict[str, Any]] | None = None
|
|
78
|
+
tool_call_id: str | None = None
|
|
79
|
+
trainable: bool | None = None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class TrainingSource(BaseModel):
|
|
83
|
+
"""The span an example came from."""
|
|
84
|
+
|
|
85
|
+
conversation_id: str | None = None
|
|
86
|
+
trace_id: str
|
|
87
|
+
span_id: str | None = None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class TrainingMetadata(BaseModel):
|
|
91
|
+
"""Lineage and labels; never sent to a provider."""
|
|
92
|
+
|
|
93
|
+
model_config = ConfigDict(extra="allow")
|
|
94
|
+
|
|
95
|
+
format: Literal["introspection.training/v1"] = TRAINING_FORMAT
|
|
96
|
+
source: TrainingSource
|
|
97
|
+
labels: list[str] = Field(default_factory=list)
|
|
98
|
+
model: str | None = None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class TrainingExample(BaseModel):
|
|
102
|
+
"""One line of ``introspection.training/v1``."""
|
|
103
|
+
|
|
104
|
+
messages: list[TrainingMessage]
|
|
105
|
+
tools: list[dict[str, Any]] = Field(default_factory=list)
|
|
106
|
+
rejected: list[TrainingMessage] | None = None
|
|
107
|
+
metadata: TrainingMetadata
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def span_to_example(
|
|
111
|
+
span: GenAiSpan,
|
|
112
|
+
*,
|
|
113
|
+
labels: list[str] | None = None,
|
|
114
|
+
reply: str | None = None,
|
|
115
|
+
rejected: str | None = None,
|
|
116
|
+
) -> TrainingExample:
|
|
117
|
+
"""The training example ``span`` makes, its output the trainable reply.
|
|
118
|
+
|
|
119
|
+
``labels`` defaults to the span's annotation labels. ``reply`` replaces the
|
|
120
|
+
reply's content with a target, such as one assembled from labels, keeping
|
|
121
|
+
the span's own reply out of the example. ``rejected`` adds a worse reply
|
|
122
|
+
to the same prompt, which makes the example a preference pair.
|
|
123
|
+
|
|
124
|
+
Raises:
|
|
125
|
+
TrainingConversionError: the span has no output, or holds a part a
|
|
126
|
+
training example cannot carry (see the module docstring).
|
|
127
|
+
"""
|
|
128
|
+
if not span.output_messages:
|
|
129
|
+
raise TrainingConversionError(
|
|
130
|
+
f"span {span.span_id} has no output to train on"
|
|
131
|
+
)
|
|
132
|
+
system = (
|
|
133
|
+
[
|
|
134
|
+
instruction.content
|
|
135
|
+
for instruction in (
|
|
136
|
+
span.attributes.gen_ai.system_instructions or []
|
|
137
|
+
)
|
|
138
|
+
]
|
|
139
|
+
if span.attributes.gen_ai
|
|
140
|
+
else []
|
|
141
|
+
)
|
|
142
|
+
history: list[TrainingMessage] = []
|
|
143
|
+
for message in span.input_messages:
|
|
144
|
+
if message.role == "system":
|
|
145
|
+
system.extend(_texts(message))
|
|
146
|
+
else:
|
|
147
|
+
history.extend(_messages(message))
|
|
148
|
+
output: list[TrainingMessage] = []
|
|
149
|
+
for message in span.output_messages:
|
|
150
|
+
output.extend(_messages(message))
|
|
151
|
+
if reply is not None:
|
|
152
|
+
output = [TrainingMessage(role="assistant", content=reply)]
|
|
153
|
+
for message in history:
|
|
154
|
+
message.trainable = False
|
|
155
|
+
for message in output:
|
|
156
|
+
message.trainable = message.role == "assistant"
|
|
157
|
+
leading = (
|
|
158
|
+
[
|
|
159
|
+
TrainingMessage(
|
|
160
|
+
role="system", content="\n\n".join(system), trainable=False
|
|
161
|
+
)
|
|
162
|
+
]
|
|
163
|
+
if system
|
|
164
|
+
else []
|
|
165
|
+
)
|
|
166
|
+
if span.annotation is not None and labels is None:
|
|
167
|
+
labels = list(span.annotation.labels)
|
|
168
|
+
example = TrainingExample(
|
|
169
|
+
messages=[*leading, *history, *output],
|
|
170
|
+
tools=_tools(span),
|
|
171
|
+
rejected=(
|
|
172
|
+
[TrainingMessage(role="assistant", content=rejected)]
|
|
173
|
+
if rejected is not None
|
|
174
|
+
else None
|
|
175
|
+
),
|
|
176
|
+
metadata=TrainingMetadata(
|
|
177
|
+
source=TrainingSource(
|
|
178
|
+
conversation_id=span.conversation_id,
|
|
179
|
+
trace_id=span.trace_id,
|
|
180
|
+
span_id=span.span_id,
|
|
181
|
+
),
|
|
182
|
+
labels=labels or [],
|
|
183
|
+
model=span.model,
|
|
184
|
+
),
|
|
185
|
+
)
|
|
186
|
+
logger.debug(
|
|
187
|
+
"Converted a span to a training example",
|
|
188
|
+
extra={"span_id": span.span_id, "messages": len(example.messages)},
|
|
189
|
+
)
|
|
190
|
+
return example
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def sft_row(example: TrainingExample) -> dict[str, Any]:
|
|
194
|
+
"""The SFT row both Fireworks and Tinker read: messages and tools."""
|
|
195
|
+
row: dict[str, Any] = {
|
|
196
|
+
"messages": [_wire(message) for message in example.messages]
|
|
197
|
+
}
|
|
198
|
+
if example.tools:
|
|
199
|
+
row["tools"] = example.tools
|
|
200
|
+
return row
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def dpo_pair(example: TrainingExample) -> dict[str, Any]:
|
|
204
|
+
"""The chosen/rejected pair, in the Fireworks cookbook's DPO shape.
|
|
205
|
+
|
|
206
|
+
The prompt is every message before the first trainable one; ``chosen``
|
|
207
|
+
ends with the example's reply and ``rejected`` with its rejected one.
|
|
208
|
+
|
|
209
|
+
Raises:
|
|
210
|
+
TrainingConversionError: the example has no ``rejected`` reply.
|
|
211
|
+
"""
|
|
212
|
+
if example.rejected is None:
|
|
213
|
+
raise TrainingConversionError(
|
|
214
|
+
"a preference pair needs a rejected reply"
|
|
215
|
+
)
|
|
216
|
+
first = next(
|
|
217
|
+
index
|
|
218
|
+
for index, message in enumerate(example.messages)
|
|
219
|
+
if message.trainable
|
|
220
|
+
)
|
|
221
|
+
prompt = [
|
|
222
|
+
_wire(message, trainable=False) for message in example.messages[:first]
|
|
223
|
+
]
|
|
224
|
+
chosen = [
|
|
225
|
+
_wire(message, trainable=False) for message in example.messages[first:]
|
|
226
|
+
]
|
|
227
|
+
rejected = [
|
|
228
|
+
_wire(message, trainable=False) for message in example.rejected
|
|
229
|
+
]
|
|
230
|
+
return {
|
|
231
|
+
"chosen": {"messages": prompt + chosen},
|
|
232
|
+
"rejected": {"messages": prompt + rejected},
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _wire(
|
|
237
|
+
message: TrainingMessage, *, trainable: bool = True
|
|
238
|
+
) -> dict[str, Any]:
|
|
239
|
+
wire = message.model_dump(exclude_none=True)
|
|
240
|
+
if not trainable:
|
|
241
|
+
wire.pop("trainable", None)
|
|
242
|
+
return wire
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _texts(message: InputMessage | OutputMessage) -> list[str]:
|
|
246
|
+
texts = []
|
|
247
|
+
for part in message.parts:
|
|
248
|
+
if not isinstance(part, TextPart):
|
|
249
|
+
raise TrainingConversionError(
|
|
250
|
+
f"a {message.role} message holds a {part.type} part"
|
|
251
|
+
)
|
|
252
|
+
texts.append(part.content)
|
|
253
|
+
return texts
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _messages(message: InputMessage | OutputMessage) -> list[TrainingMessage]:
|
|
257
|
+
"""One GenAI message as chat messages: tool responses become their own."""
|
|
258
|
+
if message.role == "tool":
|
|
259
|
+
return [_tool_result(part) for part in message.parts]
|
|
260
|
+
parts: list[dict[str, str]] = []
|
|
261
|
+
calls: list[dict[str, Any]] = []
|
|
262
|
+
results: list[TrainingMessage] = []
|
|
263
|
+
for part in message.parts:
|
|
264
|
+
if isinstance(part, TextPart):
|
|
265
|
+
parts.append({"type": "text", "text": part.content})
|
|
266
|
+
elif isinstance(part, CompactionPart):
|
|
267
|
+
parts.append({"type": "text", "text": part.content or ""})
|
|
268
|
+
elif isinstance(part, ThinkingPart):
|
|
269
|
+
if part.content:
|
|
270
|
+
parts.append({"type": "thinking", "thinking": part.content})
|
|
271
|
+
elif isinstance(part, ToolCallRequestPart):
|
|
272
|
+
calls.append(_tool_call(part))
|
|
273
|
+
elif isinstance(part, ToolCallResponsePart):
|
|
274
|
+
results.append(_tool_result(part))
|
|
275
|
+
else:
|
|
276
|
+
raise TrainingConversionError(
|
|
277
|
+
f"a {message.role} message holds a {part.type} part"
|
|
278
|
+
)
|
|
279
|
+
if calls and message.role != "assistant":
|
|
280
|
+
raise TrainingConversionError(
|
|
281
|
+
f"a {message.role} message holds a tool call"
|
|
282
|
+
)
|
|
283
|
+
own = (
|
|
284
|
+
[
|
|
285
|
+
TrainingMessage(
|
|
286
|
+
role=message.role,
|
|
287
|
+
content=_content(parts),
|
|
288
|
+
tool_calls=calls or None,
|
|
289
|
+
)
|
|
290
|
+
]
|
|
291
|
+
if parts or calls
|
|
292
|
+
else []
|
|
293
|
+
)
|
|
294
|
+
return own + results
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _content(parts: list[dict[str, str]]) -> str | list[dict[str, str]] | None:
|
|
298
|
+
"""Plain text when the message is only text, else its parts."""
|
|
299
|
+
if not parts:
|
|
300
|
+
return None
|
|
301
|
+
if all(part["type"] == "text" for part in parts):
|
|
302
|
+
return "".join(part["text"] for part in parts)
|
|
303
|
+
return parts
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _tool_call(part: ToolCallRequestPart) -> dict[str, Any]:
|
|
307
|
+
if not part.id:
|
|
308
|
+
raise TrainingConversionError(f"tool call {part.name!r} has no id")
|
|
309
|
+
arguments = (
|
|
310
|
+
part.arguments
|
|
311
|
+
if isinstance(part.arguments, str)
|
|
312
|
+
else json.dumps(part.arguments if part.arguments is not None else {})
|
|
313
|
+
)
|
|
314
|
+
return {
|
|
315
|
+
"id": part.id,
|
|
316
|
+
"type": "function",
|
|
317
|
+
"function": {"name": part.name, "arguments": arguments},
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _tool_result(part: Any) -> TrainingMessage:
|
|
322
|
+
if not isinstance(part, ToolCallResponsePart):
|
|
323
|
+
raise TrainingConversionError(
|
|
324
|
+
f"a tool message holds a {part.type} part"
|
|
325
|
+
)
|
|
326
|
+
if not part.id:
|
|
327
|
+
raise TrainingConversionError("a tool response has no call id")
|
|
328
|
+
content = (
|
|
329
|
+
part.response
|
|
330
|
+
if isinstance(part.response, str)
|
|
331
|
+
else json.dumps(part.response)
|
|
332
|
+
)
|
|
333
|
+
return TrainingMessage(role="tool", tool_call_id=part.id, content=content)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _tools(span: GenAiSpan) -> list[dict[str, Any]]:
|
|
337
|
+
gen_ai = span.attributes.gen_ai
|
|
338
|
+
definitions = (
|
|
339
|
+
gen_ai.tool.definitions if gen_ai and gen_ai.tool else None
|
|
340
|
+
) or []
|
|
341
|
+
tools = []
|
|
342
|
+
for definition in definitions:
|
|
343
|
+
function: dict[str, Any] = {"name": definition.name}
|
|
344
|
+
if definition.description:
|
|
345
|
+
function["description"] = definition.description
|
|
346
|
+
if definition.parameters is not None:
|
|
347
|
+
function["parameters"] = definition.parameters
|
|
348
|
+
tools.append(
|
|
349
|
+
{"type": definition.type or "function", "function": function}
|
|
350
|
+
)
|
|
351
|
+
return tools
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Agent Trajectory Interchange Format (ATIF) — the subset the projection writes.
|
|
2
|
+
|
|
3
|
+
ATIF is Harbor's trajectory format: an object with ``schema_version``,
|
|
4
|
+
``agent`` and sequential ``steps``. It is distinct from the SDK's trajectory-v1
|
|
5
|
+
record array (``introspection_sdk.schemas.trajectory``).
|
|
6
|
+
|
|
7
|
+
Like trajectory-v1, an ATIF trajectory is a **projection** of the GenAI spans
|
|
8
|
+
stored for a conversation (see :mod:`introspection_transform.projection`), never a second
|
|
9
|
+
storage format.
|
|
10
|
+
|
|
11
|
+
These models declare only the fields the projection writes, at one pinned
|
|
12
|
+
``schema_version``. Harbor owns the format; ``tests/fixtures/atif.schema.json``
|
|
13
|
+
is Harbor's own schema, and every trajectory the projection produces is
|
|
14
|
+
validated against it.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from typing import Any, Literal
|
|
20
|
+
|
|
21
|
+
from pydantic import (
|
|
22
|
+
BaseModel,
|
|
23
|
+
ConfigDict,
|
|
24
|
+
Field,
|
|
25
|
+
SerializerFunctionWrapHandler,
|
|
26
|
+
model_serializer,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"ATIF_SCHEMA_VERSION",
|
|
31
|
+
"AtifAgent",
|
|
32
|
+
"AtifFinalMetrics",
|
|
33
|
+
"AtifMetrics",
|
|
34
|
+
"AtifObservation",
|
|
35
|
+
"AtifObservationResult",
|
|
36
|
+
"AtifStep",
|
|
37
|
+
"AtifToolCall",
|
|
38
|
+
"AtifTrajectory",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
#: The newest ATIF version whose fields the projection uses: the result-level
|
|
42
|
+
#: ``extra`` and ``llm_call_count`` both arrived in v1.7.
|
|
43
|
+
ATIF_SCHEMA_VERSION: Literal["ATIF-v1.7"] = "ATIF-v1.7"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class AtifModel(BaseModel):
|
|
47
|
+
"""Closed, omit-absent base: Harbor's models forbid unknown fields."""
|
|
48
|
+
|
|
49
|
+
model_config = ConfigDict(extra="forbid", protected_namespaces=())
|
|
50
|
+
|
|
51
|
+
@model_serializer(mode="wrap")
|
|
52
|
+
def _omit_absent(self, handler: SerializerFunctionWrapHandler) -> Any:
|
|
53
|
+
serialized = handler(self)
|
|
54
|
+
if not isinstance(serialized, dict):
|
|
55
|
+
return serialized
|
|
56
|
+
return {
|
|
57
|
+
key: value
|
|
58
|
+
for key, value in serialized.items()
|
|
59
|
+
if value is not None
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class AtifToolCall(AtifModel):
|
|
64
|
+
"""One tool invocation of an agent step."""
|
|
65
|
+
|
|
66
|
+
tool_call_id: str
|
|
67
|
+
function_name: str
|
|
68
|
+
arguments: dict[str, Any] = Field(default_factory=dict)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class AtifObservationResult(AtifModel):
|
|
72
|
+
"""The result of one tool call.
|
|
73
|
+
|
|
74
|
+
ATIF has no error field on a result. A failed call is marked
|
|
75
|
+
``extra: {"is_error": true}``. The structured result of the call's
|
|
76
|
+
``execute_tool`` span, when it has one, is ``extra: {"details": ...}``. A
|
|
77
|
+
successful call without one carries no ``extra``.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
source_call_id: str | None = None
|
|
81
|
+
content: str | None = None
|
|
82
|
+
extra: dict[str, Any] | None = None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class AtifObservation(AtifModel):
|
|
86
|
+
"""The tool results an agent step received."""
|
|
87
|
+
|
|
88
|
+
results: list[AtifObservationResult]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class AtifMetrics(AtifModel):
|
|
92
|
+
"""Usage of one model call.
|
|
93
|
+
|
|
94
|
+
``prompt_tokens`` includes cached tokens, as ``gen_ai.usage.input_tokens``
|
|
95
|
+
does.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
prompt_tokens: int | None = None
|
|
99
|
+
completion_tokens: int | None = None
|
|
100
|
+
cached_tokens: int | None = None
|
|
101
|
+
cost_usd: float | None = None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class AtifStep(AtifModel):
|
|
105
|
+
"""One step: a system prompt, a user turn, or one model call.
|
|
106
|
+
|
|
107
|
+
A step built from an input message a run's ``messages`` loaded (the
|
|
108
|
+
first model call's ``introspection.history.loaded_messages``) is marked
|
|
109
|
+
twice: ATIF's own ``is_copied_context``, and ``extra: {"loaded": true}``.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
step_id: int = Field(ge=1)
|
|
113
|
+
timestamp: str | None = None
|
|
114
|
+
source: Literal["system", "user", "agent"]
|
|
115
|
+
model_name: str | None = None
|
|
116
|
+
message: str
|
|
117
|
+
reasoning_content: str | None = None
|
|
118
|
+
tool_calls: list[AtifToolCall] | None = None
|
|
119
|
+
observation: AtifObservation | None = None
|
|
120
|
+
metrics: AtifMetrics | None = None
|
|
121
|
+
llm_call_count: int | None = Field(default=None, ge=0)
|
|
122
|
+
is_copied_context: bool | None = None
|
|
123
|
+
"""Set on a step built from a message a run loaded rather than produced
|
|
124
|
+
(see :class:`AtifStep`), so training data leaves it out, as ATIF
|
|
125
|
+
intends."""
|
|
126
|
+
extra: dict[str, Any] | None = None
|
|
127
|
+
"""Step-level metadata: ``{"loaded": true}`` on a loaded step."""
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class AtifAgent(AtifModel):
|
|
131
|
+
"""The agent system that produced the trajectory."""
|
|
132
|
+
|
|
133
|
+
name: str
|
|
134
|
+
version: str
|
|
135
|
+
model_name: str | None = None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class AtifFinalMetrics(AtifModel):
|
|
139
|
+
"""Totals over every step."""
|
|
140
|
+
|
|
141
|
+
total_prompt_tokens: int | None = None
|
|
142
|
+
total_completion_tokens: int | None = None
|
|
143
|
+
total_cached_tokens: int | None = None
|
|
144
|
+
total_cost_usd: float | None = None
|
|
145
|
+
total_steps: int | None = Field(default=None, ge=0)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class AtifTrajectory(AtifModel):
|
|
149
|
+
"""An ATIF trajectory: Harbor's object-root contract."""
|
|
150
|
+
|
|
151
|
+
schema_version: Literal["ATIF-v1.7"] = ATIF_SCHEMA_VERSION
|
|
152
|
+
session_id: str | None = None
|
|
153
|
+
agent: AtifAgent
|
|
154
|
+
steps: list[AtifStep] = Field(min_length=1)
|
|
155
|
+
notes: str | None = None
|
|
156
|
+
final_metrics: AtifFinalMetrics | None = None
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: introspection-transform
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: GenAI spans to a Harbor ATIF trajectory and to introspection.training/v1 examples, and an ATIF trajectory to the AG-UI messages that open a run
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Python: >=3.11
|
|
12
|
+
Requires-Dist: ag-ui-protocol>=1.0.0
|
|
13
|
+
Requires-Dist: pydantic>=2.10.0
|
|
14
|
+
Provides-Extra: test
|
|
15
|
+
Requires-Dist: jsonschema>=4.23.0; extra == 'test'
|
|
16
|
+
Requires-Dist: pytest-cov>=7.1.0; extra == 'test'
|
|
17
|
+
Requires-Dist: pytest>=9.0.0; extra == 'test'
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# introspection-transform
|
|
21
|
+
|
|
22
|
+
GenAI spans to a [Harbor](https://github.com/laude-institute/harbor) ATIF
|
|
23
|
+
trajectory, and an ATIF trajectory back to the AG-UI messages that open a
|
|
24
|
+
run. It is the projection `introspection-sdk` uses, published on its own so
|
|
25
|
+
an eval adapter can read a conversation's spans without installing the SDK.
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install introspection-transform
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from introspection_transform import (
|
|
33
|
+
GenAiSpanList,
|
|
34
|
+
atif_to_messages,
|
|
35
|
+
sft_row,
|
|
36
|
+
span_to_example,
|
|
37
|
+
spans_to_atif,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
spans = GenAiSpanList.model_validate_json(body).items
|
|
41
|
+
trajectory = spans_to_atif(spans, session_id="conv-1")
|
|
42
|
+
messages = atif_to_messages(trajectory, prompt="Continue the task")
|
|
43
|
+
|
|
44
|
+
# One annotated span as a training example; an item-detail read carries the whole history.
|
|
45
|
+
example = span_to_example(span, labels=["router-correct"])
|
|
46
|
+
row = sft_row(example) # {"messages": [...]} for Fireworks or Tinker SFT
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Layout
|
|
50
|
+
|
|
51
|
+
| Module | Holds |
|
|
52
|
+
| --- | --- |
|
|
53
|
+
| `introspection_transform.projection` | `spans_to_atif` and `AtifProjection`: a conversation's GenAI spans as one ATIF trajectory. |
|
|
54
|
+
| `introspection_transform.messages` | `atif_to_messages` and `AtifConversionError`: a trajectory as the `ag_ui.core` messages a run opens with. |
|
|
55
|
+
| `introspection_transform.trajectory` | The ATIF models the projection writes, at `ATIF_SCHEMA_VERSION`. |
|
|
56
|
+
| `introspection_transform.genai_span` | `GenAiSpan` and `GenAiSpanList`, the span a conversation read returns. |
|
|
57
|
+
| `introspection_transform.genai` | The OTel GenAI message and part models. |
|
|
58
|
+
| `introspection_transform.annotations` | `AnnotationState`, the annotation a span read can carry. |
|
|
59
|
+
| `introspection_transform.training` | `span_to_example`: one span as an `introspection.training/v1` example (OpenAI chat messages with `trainable` on each, `tools`, an optional `rejected` reply), and its `sft_row` and `dpo_pair` views, which the Fireworks and Tinker training toolchains read. |
|
|
60
|
+
|
|
61
|
+
`introspection-sdk` re-exports each of these from its old module
|
|
62
|
+
(`introspection_sdk.atif`, `introspection_sdk.atif_messages`,
|
|
63
|
+
`introspection_sdk.schemas.atif`, `.genai`, `.genai_span`), so code that
|
|
64
|
+
imports them from the SDK keeps working.
|
|
65
|
+
|
|
66
|
+
## Development
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
uv sync --all-extras
|
|
70
|
+
uv run ruff format --check . && uv run ruff check .
|
|
71
|
+
uv run ty check introspection_transform tests
|
|
72
|
+
uv run pytest tests/ --cov=introspection_transform
|
|
73
|
+
uv run deptry .
|
|
74
|
+
npx --yes jscpd@5.4.1
|
|
75
|
+
```
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
introspection_transform/__init__.py,sha256=PLmJY6xx2dR84--zrlvLMVI1uyc-XC18TmxF9KOi0AE,1083
|
|
2
|
+
introspection_transform/annotations.py,sha256=4_mI74nd3-4SDWSEhfoA6b9gsBM2u3E73pLb6RbtV2Q,1397
|
|
3
|
+
introspection_transform/genai.py,sha256=RwkZZNFOocQPlHBTZf0UZuUTlgi4oW-VJkda8-DFnDU,13876
|
|
4
|
+
introspection_transform/genai_span.py,sha256=2wVgxeO-GQXfpJfquDRXEHsMEwkKUY-PtsFfrYgYr0Y,18032
|
|
5
|
+
introspection_transform/messages.py,sha256=SvzCIUiJvBDOk0VSF09athMEgVICNxyPJljEU-E8BPY,8185
|
|
6
|
+
introspection_transform/projection.py,sha256=hQJJLZK-bnirZ3fedDzP3f8PPAd6Z-jOZxOprK0qtbg,29986
|
|
7
|
+
introspection_transform/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
introspection_transform/training.py,sha256=OCWkHBV2kqBU4z7uXdZqSUZUBZvpEEbksDo9Mes-SK0,11418
|
|
9
|
+
introspection_transform/trajectory.py,sha256=k__MmOOQ2F7pHBHzWn8MwQjml9kWExpgrk-GGl4FszY,4790
|
|
10
|
+
introspection_transform-0.2.0.dist-info/METADATA,sha256=u7y-EYucgenXuUi_lmmlg8wkq8gWB9mgn7XQFgzUfLA,3169
|
|
11
|
+
introspection_transform-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
12
|
+
introspection_transform-0.2.0.dist-info/licenses/LICENSE,sha256=NonLPreGDfSnju-DCu7aZV9b66BAlIeWolc6c8nKeEU,10773
|
|
13
|
+
introspection_transform-0.2.0.dist-info/RECORD,,
|