-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtracing.py
More file actions
429 lines (361 loc) · 13.2 KB
/
tracing.py
File metadata and controls
429 lines (361 loc) · 13.2 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
"""DSPy-specific callback, span creation, and metadata extraction."""
from typing import Any
from braintrust.logger import current_span, start_span
from braintrust.span_types import SpanTypeAttribute
try:
from dspy.utils.callback import BaseCallback
_HAS_DSPY = True
except ImportError:
_HAS_DSPY = False
BaseCallback = object # type: ignore[assignment,misc]
class BraintrustDSpyCallback(BaseCallback):
"""Callback handler that logs DSPy execution traces to Braintrust.
This callback integrates DSPy with Braintrust's observability platform, automatically
logging language model calls, module executions, tool invocations, and evaluations.
Logged information includes:
- Input parameters and output results
- Execution latency
- Error information when exceptions occur
- Hierarchical span relationships for nested operations
Basic Example:
```python
import dspy
from braintrust import init_logger
from braintrust.integrations.dspy import BraintrustDSpyCallback
# Initialize Braintrust
init_logger(project="dspy-example")
# Configure DSPy with callback
lm = dspy.LM("openai/gpt-4o-mini")
dspy.configure(lm=lm, callbacks=[BraintrustDSpyCallback()])
# Use DSPy - execution is automatically logged
predictor = dspy.Predict("question -> answer")
result = predictor(question="What is 2+2?")
```
Advanced Example with LiteLLM Patching:
For additional detailed token metrics from LiteLLM's wrapper, patch before importing DSPy
and disable DSPy's disk cache:
```python
from braintrust.integrations.litellm import patch_litellm
patch_litellm()
import dspy
from braintrust import init_logger
from braintrust.integrations.dspy import BraintrustDSpyCallback
init_logger(project="dspy-example")
# Disable disk cache to ensure LiteLLM calls are traced
dspy.configure_cache(enable_disk_cache=False, enable_memory_cache=True)
lm = dspy.LM("openai/gpt-4o-mini")
dspy.configure(lm=lm, callbacks=[BraintrustDSpyCallback()])
```
The callback creates Braintrust spans for:
- DSPy module executions (Predict, ChainOfThought, ReAct, etc.)
- Adapter formatting and parsing steps
- LLM calls with latency metrics
- Tool calls
- Evaluation runs
For detailed token usage and cost metrics, use LiteLLM patching (see Advanced Example above).
The patched LiteLLM wrapper will create additional "Completion" spans with comprehensive metrics.
Spans are automatically nested based on the execution hierarchy.
"""
def __init__(self):
"""Initialize the Braintrust DSPy callback handler."""
if not _HAS_DSPY:
raise ImportError("DSPy is not installed. Please install it with: pip install dspy")
super().__init__()
# Map call_id to span objects for proper nesting
self._spans: dict[str, Any] = {}
def on_lm_start(
self,
call_id: str,
instance: Any,
inputs: dict[str, Any],
):
"""Log the start of a language model call.
Args:
call_id: Unique identifier for this call
instance: The LM instance being called
inputs: Input parameters to the LM
"""
metadata = {}
if hasattr(instance, "model"):
metadata["model"] = instance.model
if hasattr(instance, "provider"):
metadata["provider"] = str(instance.provider)
for key in ["temperature", "max_tokens", "top_p", "top_k", "stop"]:
if key in inputs:
metadata[key] = inputs[key]
parent = current_span()
parent_export = parent.export() if parent else None
span = start_span(
name="dspy.lm",
input=inputs,
metadata=metadata,
parent=parent_export,
)
span.set_current()
self._spans[call_id] = span
def _end_span(
self,
call_id: str,
outputs: Any | None,
exception: Exception | None = None,
):
"""Pop span by call_id, log outputs/exception, and end it."""
span = self._spans.pop(call_id, None)
if not span:
return
try:
log_data = {}
if exception:
log_data["error"] = exception
if outputs is not None:
log_data["output"] = outputs
if log_data:
span.log(**log_data)
finally:
span.unset_current()
span.end()
def on_lm_end(
self,
call_id: str,
outputs: dict[str, Any] | None,
exception: Exception | None = None,
):
"""Log the end of a language model call.
Args:
call_id: Unique identifier for this call
outputs: Output from the LM, or None if there was an exception
exception: Exception raised during execution, if any
"""
self._end_span(call_id, outputs, exception)
def on_module_start(
self,
call_id: str,
instance: Any,
inputs: dict[str, Any],
):
"""Log the start of a DSPy module execution.
Args:
call_id: Unique identifier for this call
instance: The Module instance being called
inputs: Input parameters to the module's forward() method
"""
cls = instance.__class__
cls_name = cls.__name__
module_name = f"{cls.__module__}.{cls_name}"
parent = current_span()
parent_export = parent.export() if parent else None
span = start_span(
name=f"dspy.module.{cls_name}",
input=inputs,
metadata={"module_class": module_name},
parent=parent_export,
)
span.set_current()
self._spans[call_id] = span
def on_module_end(
self,
call_id: str,
outputs: Any | None,
exception: Exception | None = None,
):
"""Log the end of a DSPy module execution.
Args:
call_id: Unique identifier for this call
outputs: Output from the module, or None if there was an exception
exception: Exception raised during execution, if any
"""
if outputs is not None:
if hasattr(outputs, "toDict"):
outputs = outputs.toDict()
elif hasattr(outputs, "__dict__"):
outputs = outputs.__dict__
self._end_span(call_id, outputs, exception)
def _start_adapter_span(
self,
call_id: str,
instance: Any,
inputs: dict[str, Any],
span_name: str,
):
"""Create and store a span for an adapter format/parse call."""
cls = instance.__class__
metadata = {"adapter_class": f"{cls.__module__}.{cls.__name__}"}
parent = current_span()
parent_export = parent.export() if parent else None
span = start_span(
name=span_name,
input=inputs,
metadata=metadata,
parent=parent_export,
)
span.set_current()
self._spans[call_id] = span
def on_adapter_format_start(
self,
call_id: str,
instance: Any,
inputs: dict[str, Any],
):
"""Log the start of an adapter format call.
Args:
call_id: Unique identifier for this call
instance: The Adapter instance being called
inputs: Input parameters to the adapter's format() method
"""
self._start_adapter_span(call_id, instance, inputs, "dspy.adapter.format")
def on_adapter_format_end(
self,
call_id: str,
outputs: list[dict[str, Any]] | None,
exception: Exception | None = None,
):
"""Log the end of an adapter format call.
Args:
call_id: Unique identifier for this call
outputs: Output from the adapter's format() method, or None if there was an exception
exception: Exception raised during execution, if any
"""
self._end_span(call_id, outputs, exception)
def on_adapter_parse_start(
self,
call_id: str,
instance: Any,
inputs: dict[str, Any],
):
"""Log the start of an adapter parse call.
Args:
call_id: Unique identifier for this call
instance: The Adapter instance being called
inputs: Input parameters to the adapter's parse() method
"""
self._start_adapter_span(call_id, instance, inputs, "dspy.adapter.parse")
def on_adapter_parse_end(
self,
call_id: str,
outputs: dict[str, Any] | None,
exception: Exception | None = None,
):
"""Log the end of an adapter parse call.
Args:
call_id: Unique identifier for this call
outputs: Output from the adapter's parse() method, or None if there was an exception
exception: Exception raised during execution, if any
"""
self._end_span(call_id, outputs, exception)
def on_tool_start(
self,
call_id: str,
instance: Any,
inputs: dict[str, Any],
):
"""Log the start of a tool invocation.
Args:
call_id: Unique identifier for this call
instance: The Tool instance being called
inputs: Input parameters to the tool
"""
tool_name = "unknown"
if hasattr(instance, "name"):
tool_name = instance.name
elif hasattr(instance, "__name__"):
tool_name = instance.__name__
elif hasattr(instance, "func") and hasattr(instance.func, "__name__"):
tool_name = instance.func.__name__
parent = current_span()
parent_export = parent.export() if parent else None
span = start_span(
name=tool_name,
span_attributes={"type": SpanTypeAttribute.TOOL},
input=inputs,
parent=parent_export,
)
span.set_current()
self._spans[call_id] = span
def on_tool_end(
self,
call_id: str,
outputs: dict[str, Any] | None,
exception: Exception | None = None,
):
"""Log the end of a tool invocation.
Args:
call_id: Unique identifier for this call
outputs: Output from the tool, or None if there was an exception
exception: Exception raised during execution, if any
"""
self._end_span(call_id, outputs, exception)
def on_evaluate_start(
self,
call_id: str,
instance: Any,
inputs: dict[str, Any],
):
"""Log the start of an evaluation run.
Args:
call_id: Unique identifier for this call
instance: The Evaluate instance
inputs: Input parameters to the evaluation
"""
metadata = {}
if hasattr(instance, "metric") and instance.metric:
if hasattr(instance.metric, "__name__"):
metadata["metric"] = instance.metric.__name__
if hasattr(instance, "num_threads"):
metadata["num_threads"] = instance.num_threads
parent = current_span()
parent_export = parent.export() if parent else None
span = start_span(
name="dspy.evaluate",
input=inputs,
metadata=metadata,
parent=parent_export,
)
span.set_current()
self._spans[call_id] = span
def on_evaluate_end(
self,
call_id: str,
outputs: Any | None,
exception: Exception | None = None,
):
"""Log the end of an evaluation run.
Args:
call_id: Unique identifier for this call
outputs: Output from the evaluation, or None if there was an exception
exception: Exception raised during execution, if any
"""
span = self._spans.pop(call_id, None)
if not span:
return
try:
log_data = {}
if exception:
log_data["error"] = exception
if outputs is not None:
log_data["output"] = outputs
if isinstance(outputs, dict):
metrics = {}
for key in ["accuracy", "score", "total", "correct"]:
if key in outputs:
try:
metrics[key] = float(outputs[key])
except (ValueError, TypeError):
pass
if metrics:
log_data["metrics"] = metrics
if log_data:
span.log(**log_data)
finally:
span.unset_current()
span.end()
def _configure_wrapper(wrapped, instance, args, kwargs):
"""Wrapper for dspy.configure that auto-adds BraintrustDSpyCallback."""
callbacks = kwargs.get("callbacks")
if callbacks is None:
callbacks = []
else:
callbacks = list(callbacks)
if not any(isinstance(cb, BraintrustDSpyCallback) for cb in callbacks):
callbacks.append(BraintrustDSpyCallback())
kwargs["callbacks"] = callbacks
return wrapped(*args, **kwargs)