Skip to content

Commit e08cf3f

Browse files
fix(tracer): handle missing active trace and improve error logging in LiteLLM integration
1 parent 5997612 commit e08cf3f

File tree

2 files changed

+17
-6
lines changed

2 files changed

+17
-6
lines changed

src/openlayer/lib/integrations/litellm_tracer.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Module with methods used to trace LiteLLM completions."""
22

3+
import contextvars
34
import json
45
import logging
56
import time
@@ -153,6 +154,7 @@ def stream_chunks(
153154
latest_usage_data = {"total_tokens": None, "prompt_tokens": None, "completion_tokens": None}
154155
provider = "unknown"
155156
latest_chunk_metadata = {}
157+
captured_context = contextvars.copy_context()
156158

157159
try:
158160
i = 0
@@ -253,14 +255,15 @@ def stream_chunks(
253255
**latest_chunk_metadata, # Add all LiteLLM-specific metadata
254256
},
255257
)
256-
add_to_trace(**trace_args)
258+
captured_context.run(add_to_trace, **trace_args)
257259

258260
# pylint: disable=broad-except
259261
except Exception as e:
260-
logger.error(
261-
"Failed to trace the LiteLLM completion request with Openlayer. %s",
262-
e,
263-
)
262+
if logger is not None:
263+
logger.error(
264+
"Failed to trace the LiteLLM completion request with Openlayer. %s",
265+
e,
266+
)
264267

265268

266269
def handle_non_streaming_completion(

src/openlayer/lib/tracing/tracer.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1349,6 +1349,14 @@ def _handle_trace_completion(
13491349
logger.debug("Ending the trace...")
13501350
current_trace = get_current_trace()
13511351

1352+
if current_trace is None:
1353+
logger.warning(
1354+
"Cannot complete trace for step '%s': no active trace found. "
1355+
"This can happen when OPENLAYER_DISABLE_PUBLISH=true or trace context was lost.",
1356+
step_name,
1357+
)
1358+
return
1359+
13521360
trace_data, input_variable_names = post_process_trace(current_trace)
13531361

13541362
config = dict(
@@ -1644,7 +1652,7 @@ async def _invoke_with_context(
16441652

16451653

16461654
def post_process_trace(
1647-
trace_obj: traces.Trace,
1655+
trace_obj: Optional[traces.Trace],
16481656
) -> Tuple[Dict[str, Any], List[str]]:
16491657
"""Post processing of the trace data before uploading to Openlayer.
16501658

0 commit comments

Comments
 (0)