Skip to content

Commit 8cb85e5

Browse files
Refactor trace metadata handling for improved flexibility
- Updated `update_current_trace` function to accept dynamic keyword arguments, simplifying the process of updating trace metadata. - Enhanced `Trace` class to merge new metadata with existing fields, allowing for more efficient metadata management. This refactor aims to streamline trace updates and improve code maintainability.
1 parent 230a768 commit 8cb85e5

File tree

3 files changed

+33
-101
lines changed

3 files changed

+33
-101
lines changed

src/openlayer/lib/__init__.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,6 @@
3131
update_current_span = tracer.update_current_span
3232

3333

34-
# --------------------------------- OCI GenAI -------------------------------- #
35-
# Alias for backward compatibility
36-
trace_oci = trace_oci_genai
37-
38-
3934
def trace_anthropic(client):
4035
"""Trace Anthropic chat completions."""
4136
# pylint: disable=import-outside-toplevel
@@ -147,3 +142,8 @@ def trace_oci_genai(client, estimate_tokens: bool = True):
147142
raise ValueError("Invalid client. Please provide an OCI GenAI client.")
148143

149144
return oci_tracer.trace_oci_genai(client, estimate_tokens=estimate_tokens)
145+
146+
147+
# --------------------------------- OCI GenAI -------------------------------- #
148+
# Alias for backward compatibility
149+
trace_oci = trace_oci_genai

src/openlayer/lib/tracing/tracer.py

Lines changed: 8 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -526,42 +526,24 @@ def log_context(context: List[str]) -> None:
526526
logger.warning("No current step found to log context.")
527527

528528

529-
def update_current_trace(
530-
name: Optional[str] = None,
531-
tags: Optional[List[str]] = None,
532-
metadata: Optional[Dict[str, Any]] = None,
533-
thread_id: Optional[str] = None,
534-
user_id: Optional[str] = None,
535-
input: Optional[Any] = None,
536-
output: Optional[Any] = None,
537-
feedback: Optional['traces.Feedback'] = None,
538-
test_case: Optional['traces.LLMTestCase'] = None,
539-
) -> None:
529+
def update_current_trace(**kwargs) -> None:
540530
"""Updates the current trace metadata with the provided values.
541531
542532
This function allows users to set trace-level metadata dynamically
543533
during execution without having to pass it through function arguments.
544534
545-
Args:
546-
name: Optional trace name
547-
tags: Optional list of tags for the trace
548-
metadata: Optional dictionary of metadata to merge with existing metadata
549-
thread_id: Optional thread identifier
550-
user_id: Optional user identifier
551-
input: Optional trace input data
552-
output: Optional trace output data
553-
feedback: Optional feedback data
554-
test_case: Optional LLM test case data
535+
All provided key-value pairs will be stored in the trace metadata.
555536
556537
Example:
557-
>>> import openlayer
538+
>>> from openlayer.lib import trace, update_current_trace
558539
>>>
559-
>>> @openlayer.trace()
540+
>>> @trace()
560541
>>> def my_function():
561542
>>> # Update trace with user context
562-
>>> openlayer.update_current_trace(
543+
>>> update_current_trace(
563544
>>> user_id="user123",
564-
>>> metadata={"session_id": "sess456"}
545+
>>> session_id="sess456",
546+
>>> custom_field="any_value"
565547
>>> )
566548
>>> return "result"
567549
"""
@@ -574,17 +556,7 @@ def update_current_trace(
574556
)
575557
return
576558

577-
current_trace.update_metadata(
578-
name=name,
579-
tags=tags,
580-
metadata=metadata,
581-
thread_id=thread_id,
582-
user_id=user_id,
583-
input=input,
584-
output=output,
585-
feedback=feedback,
586-
test_case=test_case,
587-
)
559+
current_trace.update_metadata(**kwargs)
588560
logger.debug("Updated current trace metadata")
589561

590562

@@ -927,25 +899,9 @@ def post_process_trace(
927899
}
928900

929901
# Include trace-level metadata if set
930-
if trace_obj.name is not None:
931-
trace_data["trace_name"] = trace_obj.name
932-
if trace_obj.tags is not None:
933-
trace_data["tags"] = trace_obj.tags
934902
if trace_obj.metadata is not None:
935903
# Merge trace-level metadata (higher precedence than root step metadata)
936904
trace_data.update(trace_obj.metadata)
937-
if trace_obj.thread_id is not None:
938-
trace_data["thread_id"] = trace_obj.thread_id
939-
if trace_obj.user_id is not None:
940-
trace_data["user_id"] = trace_obj.user_id
941-
if trace_obj.input is not None:
942-
trace_data["trace_input"] = trace_obj.input
943-
if trace_obj.output is not None:
944-
trace_data["trace_output"] = trace_obj.output
945-
if trace_obj.feedback is not None:
946-
trace_data["feedback"] = trace_obj.feedback
947-
if trace_obj.test_case is not None:
948-
trace_data["test_case"] = trace_obj.test_case
949905

950906
if root_step.ground_truth:
951907
trace_data["groundTruth"] = root_step.ground_truth

src/openlayer/lib/tracing/traces.py

Lines changed: 20 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -20,56 +20,32 @@ class Trace:
2020
def __init__(self):
2121
self.steps = []
2222
self.current_step = None
23-
24-
# Enhanced trace metadata fields
25-
self.name: Optional[str] = None
26-
self.tags: Optional[List[str]] = None
2723
self.metadata: Optional[Dict[str, Any]] = None
28-
self.thread_id: Optional[str] = None
29-
self.user_id: Optional[str] = None
30-
self.input: Optional[Any] = None
31-
self.output: Optional[Any] = None
32-
self.feedback: Optional[Feedback] = None
33-
self.test_case: Optional[LLMTestCase] = None
3424

3525
def add_step(self, step: Step) -> None:
3626
"""Adds a step to the trace."""
3727
self.steps.append(step)
3828

39-
def update_metadata(
40-
self,
41-
name: Optional[str] = None,
42-
tags: Optional[List[str]] = None,
43-
metadata: Optional[Dict[str, Any]] = None,
44-
thread_id: Optional[str] = None,
45-
user_id: Optional[str] = None,
46-
input: Optional[Any] = None,
47-
output: Optional[Any] = None,
48-
feedback: Optional[Feedback] = None,
49-
test_case: Optional[LLMTestCase] = None,
50-
) -> None:
51-
"""Updates the trace metadata with the provided values."""
52-
if name is not None:
53-
self.name = name
54-
if tags is not None:
55-
self.tags = tags
56-
if metadata is not None:
57-
# Merge with existing metadata if it exists
58-
if self.metadata is None:
59-
self.metadata = {}
60-
self.metadata.update(metadata)
61-
if thread_id is not None:
62-
self.thread_id = thread_id
63-
if user_id is not None:
64-
self.user_id = user_id
65-
if input is not None:
66-
self.input = input
67-
if output is not None:
68-
self.output = output
69-
if feedback is not None:
70-
self.feedback = feedback
71-
if test_case is not None:
72-
self.test_case = test_case
29+
def update_metadata(self, **kwargs) -> None:
30+
"""Updates the trace metadata with the provided values.
31+
32+
All provided key-value pairs will be stored in self.metadata.
33+
Special handling for 'metadata' key which gets merged with existing metadata.
34+
"""
35+
# Initialize metadata if it doesn't exist
36+
if self.metadata is None:
37+
self.metadata = {}
38+
39+
# Handle special case for 'metadata' key - merge with existing
40+
if 'metadata' in kwargs:
41+
metadata_to_merge = kwargs.pop('metadata')
42+
if metadata_to_merge is not None:
43+
self.metadata.update(metadata_to_merge)
44+
45+
# Add all other kwargs to metadata
46+
for key, value in kwargs.items():
47+
if value is not None:
48+
self.metadata[key] = value
7349

7450
def to_dict(self) -> List[Dict[str, Any]]:
7551
"""Dictionary representation of the Trace."""

0 commit comments

Comments
 (0)