File tree Expand file tree Collapse file tree 2 files changed +17
-6
lines changed
Expand file tree Collapse file tree 2 files changed +17
-6
lines changed Original file line number Diff line number Diff line change 11"""Module with methods used to trace LiteLLM completions."""
22
3+ import contextvars
34import json
45import logging
56import 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
266269def handle_non_streaming_completion (
Original file line number Diff line number Diff 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
16461654def 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
You can’t perform that action at this time.
0 commit comments