-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtrace.py
More file actions
345 lines (290 loc) · 10.4 KB
/
Copy pathtrace.py
File metadata and controls
345 lines (290 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
from __future__ import annotations
import uuid
from typing import Any, AsyncGenerator
from datetime import UTC, datetime
from contextlib import contextmanager, asynccontextmanager
from pydantic import BaseModel
from agentex import Agentex, AsyncAgentex
from agentex.types.span import Span
from agentex.lib.utils.logging import make_logger
from agentex.lib.utils.model_utils import recursive_model_dump
from agentex.lib.core.tracing.obs_ids import obs_correlation
from agentex.lib.core.tracing.span_error import set_span_error
from agentex.lib.core.tracing.span_queue import (
SpanEventType,
AsyncSpanQueue,
get_default_span_queue,
)
from agentex.lib.core.tracing.processors.tracing_processor_interface import (
SyncTracingProcessor,
AsyncTracingProcessor,
)
logger = make_logger(__name__)
class Trace:
"""
Trace is a wrapper around the Agentex API for tracing.
It provides a context manager for spans and a way to start and end spans.
It also provides a way to get spans by ID and list all spans in a trace.
"""
def __init__(
self,
processors: list[SyncTracingProcessor],
client: Agentex,
trace_id: str | None = None,
):
"""
Initialize a new trace with the specified trace ID.
Args:
trace_id: Required trace ID to use for this trace.
processors: Optional list of tracing processors to use for this trace.
"""
self.processors = processors
self.client = client
self.trace_id = trace_id
def start_span(
self,
name: str,
parent_id: str | None = None,
input: dict[str, Any] | list[dict[str, Any]] | BaseModel | None = None,
data: dict[str, Any] | list[dict[str, Any]] | BaseModel | None = None,
task_id: str | None = None,
) -> Span:
"""
Start a new span and register it with the API.
Args:
name: Name of the span.
parent_id: Optional parent span ID.
input: Optional input data for the span.
data: Optional additional data for the span.
task_id: Optional ID of the task this span belongs to.
Returns:
The newly created span.
"""
if not self.trace_id:
raise ValueError("Trace ID is required to start a span")
# Create a span using the client's spans resource
start_time = datetime.now(UTC)
serialized_input = recursive_model_dump(input) if input else None
serialized_data = recursive_model_dump(data) if data else None
# Tag the business span with the active observability trace_id/span_id
# (OTel/ddtrace) so it can be correlated to the per-turn obs trace. The
# business trace_id stays the run-level task id -- see obs_ids.py.
obs = obs_correlation()
if obs:
serialized_data = {**(serialized_data or {}), **obs}
id = str(uuid.uuid4())
span = Span(
id=id,
trace_id=self.trace_id,
name=name,
parent_id=parent_id,
start_time=start_time,
input=serialized_input,
data=serialized_data,
task_id=task_id,
)
for processor in self.processors:
processor.on_span_start(span)
return span
def end_span(
self,
span: Span,
) -> Span:
"""
End a span by updating it with any changes made to the span object.
Args:
span: The span object to update.
Returns:
The updated span.
"""
if span.end_time is None:
span.end_time = datetime.now(UTC)
span.input = recursive_model_dump(span.input) if span.input else None
span.output = recursive_model_dump(span.output) if span.output else None
span.data = recursive_model_dump(span.data) if span.data else None
for processor in self.processors:
processor.on_span_end(span)
return span
def get_span(self, span_id: str) -> Span:
"""
Get a span by ID.
Args:
span_id: The ID of the span to get.
Returns:
The requested span.
"""
# Query from Agentex API
span = self.client.spans.retrieve(span_id)
return span
def list_spans(self) -> list[Span]:
"""
List all spans in this trace.
Returns:
List of spans in this trace.
"""
# Query from Agentex API
spans = self.client.spans.list(trace_id=self.trace_id)
return spans
@contextmanager
def span(
self,
name: str,
parent_id: str | None = None,
input: dict[str, Any] | list[dict[str, Any]] | BaseModel | None = None,
data: dict[str, Any] | list[dict[str, Any]] | BaseModel | None = None,
task_id: str | None = None,
):
"""
Context manager for spans.
If trace_id is falsy, acts as a no-op context manager.
"""
if not self.trace_id:
yield None
return
span = self.start_span(name, parent_id, input, data, task_id=task_id)
try:
yield span
except Exception as exc:
set_span_error(span, exc)
raise
finally:
self.end_span(span)
class AsyncTrace:
"""
AsyncTrace is a wrapper around the Agentex API for tracing.
It provides a context manager for spans and a way to start and end spans.
It also provides a way to get spans by ID and list all spans in a trace.
"""
def __init__(
self,
processors: list[AsyncTracingProcessor],
client: AsyncAgentex,
trace_id: str | None = None,
span_queue: AsyncSpanQueue | None = None,
):
"""
Initialize a new trace with the specified trace ID.
Args:
trace_id: Required trace ID to use for this trace.
processors: Optional list of tracing processors to use for this trace.
span_queue: Optional span queue for background processing.
"""
self.processors = processors
self.client = client
self.trace_id = trace_id
self._span_queue = span_queue or get_default_span_queue()
async def start_span(
self,
name: str,
parent_id: str | None = None,
input: dict[str, Any] | list[dict[str, Any]] | BaseModel | None = None,
data: dict[str, Any] | list[dict[str, Any]] | BaseModel | None = None,
task_id: str | None = None,
) -> Span:
"""
Start a new span and register it with the API.
Args:
name: Name of the span.
parent_id: Optional parent span ID.
input: Optional input data for the span.
data: Optional additional data for the span.
task_id: Optional ID of the task this span belongs to.
Returns:
The newly created span.
"""
if not self.trace_id:
raise ValueError("Trace ID is required to start a span")
# Create a span using the client's spans resource
start_time = datetime.now(UTC)
serialized_input = recursive_model_dump(input) if input else None
serialized_data = recursive_model_dump(data) if data else None
# Tag the business span with the active observability trace_id/span_id
# (OTel/ddtrace) so it can be correlated to the per-turn obs trace. The
# business trace_id stays the run-level task id -- see obs_ids.py.
obs = obs_correlation()
if obs:
serialized_data = {**(serialized_data or {}), **obs}
id = str(uuid.uuid4())
span = Span(
id=id,
trace_id=self.trace_id,
name=name,
parent_id=parent_id,
start_time=start_time,
input=serialized_input,
data=serialized_data,
task_id=task_id,
)
if self.processors:
self._span_queue.enqueue(SpanEventType.START, span.model_copy(deep=True), self.processors)
return span
async def end_span(
self,
span: Span,
) -> Span:
"""
End a span by updating it with any changes made to the span object.
Args:
span: The span object to update.
Returns:
The updated span.
"""
if span.end_time is None:
span.end_time = datetime.now(UTC)
span.input = recursive_model_dump(span.input) if span.input else None
span.output = recursive_model_dump(span.output) if span.output else None
span.data = recursive_model_dump(span.data) if span.data else None
if self.processors:
self._span_queue.enqueue(SpanEventType.END, span.model_copy(deep=True), self.processors)
return span
async def get_span(self, span_id: str) -> Span:
"""
Get a span by ID.
Args:
span_id: The ID of the span to get.
Returns:
The requested span.
"""
# Query from Agentex API
span = await self.client.spans.retrieve(span_id)
return span
async def list_spans(self) -> list[Span]:
"""
List all spans in this trace.
Returns:
List of spans in this trace.
"""
# Query from Agentex API
spans = await self.client.spans.list(trace_id=self.trace_id)
return spans
@asynccontextmanager
async def span(
self,
name: str,
parent_id: str | None = None,
input: dict[str, Any] | list[dict[str, Any]] | BaseModel | None = None,
data: dict[str, Any] | list[dict[str, Any]] | BaseModel | None = None,
task_id: str | None = None,
) -> AsyncGenerator[Span | None, None]:
"""
Context manager for spans.
Args:
name: Name of the span.
parent_id: Optional parent span ID.
input: Optional input data for the span.
data: Optional additional data for the span.
task_id: Optional ID of the task this span belongs to.
Yields:
The span object.
"""
if not self.trace_id:
yield None
return
span = await self.start_span(name, parent_id, input, data, task_id=task_id)
try:
yield span
except Exception as exc:
set_span_error(span, exc)
raise
finally:
await self.end_span(span)