-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathopenai_agents.py
More file actions
1677 lines (1410 loc) · 66.5 KB
/
openai_agents.py
File metadata and controls
1677 lines (1410 loc) · 66.5 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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Module with the Openlayer tracing processor for OpenAI Agents SDK."""
import json
import logging
from pathlib import Path
import time
from datetime import datetime
from typing import Any, Dict, Optional, Union, List, TYPE_CHECKING
from ..tracing import tracer, steps, enums
if TYPE_CHECKING:
try:
from agents import tracing # type: ignore[import]
except ImportError:
# When agents isn't available, we'll use string literals for type annotations
pass
try:
from agents import tracing # type: ignore[import]
HAVE_AGENTS = True
except ImportError:
HAVE_AGENTS = False
tracing = None # type: ignore[assignment]
logger = logging.getLogger(__name__)
def repo_path(relative_path: Union[str, Path]) -> Path:
"""Get path relative to the current working directory."""
return Path.cwd() / relative_path
class ParsedSpanData:
"""Parsed span data with meaningful input/output extracted."""
def __init__(
self,
name: str,
span_type: str,
input_data: Optional[Dict[str, Any]] = None,
output_data: Optional[Dict[str, Any]] = None,
metadata: Optional[Dict[str, Any]] = None,
model: Optional[str] = None,
provider: Optional[str] = None,
usage: Optional[Dict[str, Any]] = None,
):
self.name = name
self.span_type = span_type
self.input_data = input_data
self.output_data = output_data
self.metadata = metadata or {}
self.model = model
self.provider = provider
self.usage = usage
def _extract_messages_from_input(input_data: Any) -> List[Dict[str, Any]]:
"""Extract and normalize messages from input data.
This helper function eliminates duplicate message processing logic.
"""
if not isinstance(input_data, (list, tuple)):
return []
prompt_messages = []
for msg in input_data:
if isinstance(msg, dict):
prompt_messages.append(msg)
elif hasattr(msg, "role") and hasattr(msg, "content"):
prompt_messages.append({"role": msg.role, "content": msg.content})
elif hasattr(msg, "__dict__"):
# Try to convert object to dict
msg_dict = vars(msg)
prompt_messages.append(msg_dict)
return prompt_messages
def _extract_response_output(response_output: Any) -> Optional[Dict[str, Any]]:
"""Extract actual output content from response.output object.
This helper function consolidates complex response extraction logic.
"""
if not response_output:
return None
try:
if isinstance(response_output, str):
# Sometimes output might be a string directly
return {"output": response_output}
if isinstance(response_output, list) and response_output:
first_item = response_output[0]
# Check if this is a function call (common for handoffs)
if (
hasattr(first_item, "type")
and first_item.type == "function_call"
and hasattr(first_item, "name")
):
# This is a function call response, create meaningful description
func_name = first_item.name
return {"output": f"Made function call: {func_name}"}
# Check if this is a ResponseOutputMessage (actual LLM response)
elif (
hasattr(first_item, "type")
and first_item.type == "message"
and hasattr(first_item, "content")
and first_item.content
):
# This is the actual LLM response in ResponseOutputMessage format
content_list = first_item.content
if isinstance(content_list, list) and content_list:
# Look for ResponseOutputText in the content
for content_item in content_list:
if (
hasattr(content_item, "type")
and content_item.type == "output_text"
and hasattr(content_item, "text")
and content_item.text
):
return {"output": content_item.text}
# No output_text found, try first content item
first_content = content_list[0]
if hasattr(first_content, "text"):
return {"output": first_content.text}
else:
return {"output": str(first_content)}
else:
return {"output": str(content_list)}
# Otherwise try to extract message content normally (legacy format)
elif hasattr(first_item, "content") and first_item.content:
# Extract text from content parts
content_parts = first_item.content
if isinstance(content_parts, list) and content_parts:
first_content = content_parts[0]
if hasattr(first_content, "text") and first_content.text:
return {"output": first_content.text}
elif hasattr(first_content, "content"):
# Sometimes the text might be in a 'content' field
return {"output": str(first_content.content)}
else:
# Fallback: try to convert the whole content to string
return {"output": str(first_content)}
elif isinstance(content_parts, str):
# Sometimes content_parts might be a string directly
return {"output": content_parts}
else:
# Fallback: convert whatever we have to string
return {"output": str(content_parts)}
elif hasattr(first_item, "text"):
# Sometimes the text might be directly on the message
return {"output": first_item.text}
else:
# No text content found - indicate this was a non-text response
return {"output": "Agent response (no text content)"}
else:
# Fallback for unknown response formats
return {"output": "Agent response (unknown format)"}
except Exception:
return None
def parse_span_data(span_data: Any) -> ParsedSpanData:
"""Parse OpenAI Agents SDK span data to extract meaningful input/output."""
try:
# First try to use the official export() method
content = {}
if hasattr(span_data, "export") and callable(getattr(span_data, "export")):
try:
content = span_data.export()
except Exception:
pass
# Get span type
span_type = content.get("type") or getattr(span_data, "type", "unknown")
# Initialize parsed data
name = _get_span_name(span_data, span_type)
input_data = None
output_data = None
metadata = content.copy()
model = None
provider = None
usage = None
# Parse based on span type
if span_type == "function":
input_data = getattr(span_data, "input", None)
output_data = getattr(span_data, "output", None)
# Try to extract function arguments from exported content
function_args = content.get("input", {})
function_name = content.get("name", "unknown_function")
function_output = content.get("output", None)
# Use content data if span attributes are empty
if not input_data and function_args:
input_data = function_args
# Parse JSON string arguments into proper objects
if input_data and isinstance(input_data, dict):
# Check if we have a single 'input' key with a JSON string value
if "input" in input_data and isinstance(input_data["input"], str):
try:
# Try to parse the JSON string
parsed_args = json.loads(input_data["input"])
input_data = parsed_args
except (json.JSONDecodeError, TypeError):
# Keep original string format if parsing fails
pass
if not output_data and function_output is not None:
output_data = function_output
metadata.pop("input", None)
metadata.pop("output", None)
elif span_type == "generation":
input_data = getattr(span_data, "input", None)
output_data = getattr(span_data, "output", None)
model = getattr(span_data, "model", None)
provider = "OpenAI"
# Extract usage information
usage_obj = getattr(span_data, "usage", None)
if usage_obj:
usage = _extract_usage_dict(usage_obj)
# Extract prompt information from input using helper function
if input_data:
prompt_messages = _extract_messages_from_input(input_data)
if prompt_messages:
input_data = {
"messages": prompt_messages,
"prompt": prompt_messages,
}
metadata.pop("input", None)
metadata.pop("output", None)
elif span_type == "response":
return _parse_response_span_data(span_data)
elif span_type == "agent":
output_data = {"output_type": getattr(span_data, "output_type", None)}
elif span_type == "handoff":
# Extract handoff information from the span data
input_data = {}
from_agent = getattr(span_data, "from_agent", None)
to_agent = getattr(span_data, "to_agent", None)
# Try to extract from the exported content as well
if from_agent is None and "from_agent" in content:
from_agent = content["from_agent"]
if to_agent is None and "to_agent" in content:
to_agent = content["to_agent"]
# If to_agent is still None, check for other fields that might indicate the
# target
if to_agent is None:
# Sometimes handoff data might be in other fields
handoff_data = getattr(span_data, "data", {})
if isinstance(handoff_data, dict):
to_agent = handoff_data.get("to_agent") or handoff_data.get(
"target_agent"
)
input_data = {
"from_agent": from_agent or "Unknown Agent",
"to_agent": to_agent or "Unknown Target",
}
elif span_type == "custom":
data = getattr(span_data, "data", {})
input_data = data.get("input")
output_data = data.get("output")
metadata.pop("data", None)
# Ensure input/output are dictionaries
if input_data is not None and not isinstance(input_data, dict):
input_data = {"input": input_data}
if output_data is not None and not isinstance(output_data, dict):
output_data = {"output": output_data}
return ParsedSpanData(
name=name,
span_type=span_type,
input_data=input_data,
output_data=output_data,
metadata=metadata,
model=model,
provider=provider,
usage=usage,
)
except Exception as e:
logger.error(f"Failed to parse span data: {e}")
return ParsedSpanData(
name="Unknown", span_type="unknown", metadata={"parse_error": str(e)}
)
def _get_span_name(span_data: Any, span_type: str) -> str:
"""Get appropriate name for the span."""
if hasattr(span_data, "name") and span_data.name:
return span_data.name
elif span_type == "generation":
return "Generation"
elif span_type == "response":
return "Response"
elif span_type == "handoff":
return "Handoff"
elif span_type == "agent":
return "Agent"
elif span_type == "function":
return "Function"
else:
return span_type.title()
def _parse_response_span_data(span_data: Any) -> ParsedSpanData:
"""Parse response span data to extract meaningful conversation content."""
response = getattr(span_data, "response", None)
if response is None:
return ParsedSpanData(
name="Response", span_type="response", metadata={"no_response": True}
)
input_data = None
output_data = None
usage = None
model = None
metadata = {}
try:
# Extract input - this might be available in some cases
if hasattr(span_data, "input") and span_data.input:
input_data = {"input": span_data.input}
# Try to extract prompt/messages from input using helper function
prompt_messages = _extract_messages_from_input(span_data.input)
if prompt_messages:
input_data["messages"] = prompt_messages
input_data["prompt"] = prompt_messages
# Extract agent instructions and tools from the response object if available
instructions = None
tools_info = None
if response and hasattr(response, "instructions") and response.instructions:
instructions = response.instructions
if response and hasattr(response, "tools") and response.tools:
tools_info = []
for tool in response.tools:
if hasattr(tool, "name") and hasattr(tool, "description"):
tools_info.append(
{"name": tool.name, "description": tool.description}
)
elif isinstance(tool, dict):
tools_info.append(
{
"name": tool.get("name", "unknown"),
"description": tool.get("description", ""),
}
)
# Create comprehensive prompt with system instructions if we found them
if instructions or tools_info:
# Start with system instructions if available
enhanced_messages = []
if instructions:
enhanced_messages.append({"role": "system", "content": instructions})
# Add tool descriptions as system context if available
if tools_info:
tools_description = "Available tools:\n" + "\n".join(
[f"- {tool['name']}: {tool['description']}" for tool in tools_info]
)
enhanced_messages.append(
{"role": "system", "content": tools_description}
)
# Add the original user messages
if input_data and "messages" in input_data:
enhanced_messages.extend(input_data["messages"])
elif (
input_data
and "input" in input_data
and isinstance(input_data["input"], list)
):
enhanced_messages.extend(input_data["input"])
# Update input_data with enhanced prompt
if not input_data:
input_data = {}
input_data["messages"] = enhanced_messages
input_data["prompt"] = enhanced_messages
input_data["instructions"] = instructions
if tools_info:
input_data["tools"] = tools_info
# Extract output from response.output using helper function
if hasattr(response, "output") and response.output:
output_data = _extract_response_output(response.output)
if not output_data:
# Try fallback approaches
try:
if hasattr(response, "text") and response.text:
output_data = {"output": response.text}
elif hasattr(response, "output"):
output_data = {"output": "Agent response (extraction failed)"}
except Exception:
output_data = {"output": "Response content extraction failed"}
# Extract model and usage
if hasattr(response, "model"):
model = response.model
if hasattr(response, "usage") and response.usage:
usage = _extract_usage_dict(response.usage)
# Add response metadata
if hasattr(response, "id"):
metadata["response_id"] = response.id
if hasattr(response, "object"):
metadata["response_object"] = response.object
if hasattr(response, "tools"):
metadata["tools_count"] = len(response.tools) if response.tools else 0
except Exception as e:
logger.error(f"Failed to parse response span data: {e}")
metadata["parse_error"] = str(e)
return ParsedSpanData(
name="Response",
span_type="response",
input_data=input_data,
output_data=output_data,
metadata=metadata,
model=model,
provider="OpenAI",
usage=usage,
)
def _extract_usage_dict(usage_obj: Any) -> Dict[str, Any]:
"""Extract usage information as a dictionary."""
if not usage_obj:
return {}
try:
# Try model_dump first (Pydantic models)
if hasattr(usage_obj, "model_dump"):
result = usage_obj.model_dump()
return result
# Try __dict__ next
elif hasattr(usage_obj, "__dict__"):
result = vars(usage_obj)
return result
# Manual extraction with multiple field name conventions
else:
# Try different field naming conventions
usage_dict = {}
# OpenAI Responses API typically uses these field names
for input_field in ["input_tokens", "prompt_tokens"]:
if hasattr(usage_obj, input_field):
usage_dict["input_tokens"] = getattr(usage_obj, input_field)
usage_dict["prompt_tokens"] = getattr(usage_obj, input_field)
break
for output_field in ["output_tokens", "completion_tokens"]:
if hasattr(usage_obj, output_field):
usage_dict["output_tokens"] = getattr(usage_obj, output_field)
usage_dict["completion_tokens"] = getattr(usage_obj, output_field)
break
for total_field in ["total_tokens"]:
if hasattr(usage_obj, total_field):
usage_dict["total_tokens"] = getattr(usage_obj, total_field)
break
# If we couldn't find specific fields, try to get all attributes
if not usage_dict:
for attr in dir(usage_obj):
if not attr.startswith("_") and not callable(
getattr(usage_obj, attr)
):
value = getattr(usage_obj, attr)
usage_dict[attr] = value
return usage_dict
except Exception:
return {"usage_extraction_error": "Failed to extract usage"}
# Global reference to the active OpenlayerTracerProcessor
_active_openlayer_processor: Optional["OpenlayerTracerProcessor"] = None
def capture_user_input(trace_id: str, user_input: str) -> None:
"""Capture user input at the application level.
This is a convenience function that forwards to the active OpenlayerTracerProcessor.
Args:
trace_id: The trace ID to associate the input with
user_input: The user's input message
"""
if _active_openlayer_processor:
_active_openlayer_processor.capture_user_input(trace_id, user_input)
def get_current_trace_id() -> Optional[str]:
"""Get the current trace ID if available.
Returns:
The current trace ID or None if not available
"""
# This would need to be implemented based on the OpenAI Agents SDK
# For now, we'll need to pass the trace_id explicitly
return None
def _extract_span_attributes(span: Any) -> Dict[str, Any]:
"""Extract common span attributes to eliminate duplicate getattr calls.
This helper function consolidates span attribute extraction patterns.
"""
return {
"span_id": getattr(span, "span_id", None),
"trace_id": getattr(span, "trace_id", None),
"parent_id": getattr(span, "parent_id", None),
}
def _extract_token_counts(usage: Dict[str, Any]) -> Dict[str, int]:
"""Extract token counts from usage data with field name variations.
This helper function eliminates duplicate token extraction logic.
"""
if not usage or not isinstance(usage, dict):
return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
# Support multiple field name conventions
prompt_tokens = usage.get("prompt_tokens") or usage.get("input_tokens", 0)
completion_tokens = usage.get("completion_tokens") or usage.get("output_tokens", 0)
total_tokens = usage.get("total_tokens", prompt_tokens + completion_tokens)
return {
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
"total_tokens": total_tokens,
}
def _configure_chat_completion_step(
step: steps.ChatCompletionStep,
start_time: float,
model: str,
provider: str,
usage: Dict[str, Any],
model_parameters: Optional[Dict[str, Any]] = None,
) -> None:
"""Configure ChatCompletionStep attributes to eliminate duplicate setup code.
This helper function consolidates ChatCompletionStep attribute setting.
"""
token_counts = _extract_token_counts(usage)
step.start_time = start_time
step.model = model
step.provider = provider
step.prompt_tokens = token_counts["prompt_tokens"]
step.completion_tokens = token_counts["completion_tokens"]
step.tokens = token_counts["total_tokens"]
step.model_parameters = model_parameters or {}
# Dynamic base class to handle inheritance when agents is available
if HAVE_AGENTS:
_BaseProcessor = tracing.TracingProcessor # type: ignore[misc]
else:
_BaseProcessor = object # type: ignore[assignment,misc]
class OpenlayerTracerProcessor(_BaseProcessor): # type: ignore[misc]
"""Tracing processor for the `OpenAI Agents SDK
<https://openai.github.io/openai-agents-python/>`_.
Traces all intermediate steps of your OpenAI Agent to Openlayer using the official
span data models and export() methods for standardized data extraction.
Requirements: Make sure to install the OpenAI Agents SDK with
``pip install openai-agents``.
Args:
**kwargs: Additional metadata to associate with all traces.
Example:
.. code-block:: python
from agents import (
Agent,
FileSearchTool,
Runner,
WebSearchTool,
function_tool,
set_trace_processors,
)
from openlayer.lib.integrations.openai_agents import (
OpenlayerTracerProcessor,
)
set_trace_processors([OpenlayerTracerProcessor()])
@function_tool
def get_weather(city: str) -> str:
return f"The weather in {city} is sunny"
haiku_agent = Agent(
name="Haiku agent",
instructions="Always respond in haiku form",
model="o3-mini",
tools=[get_weather],
)
agent = Agent(
name="Assistant",
tools=[WebSearchTool()],
instructions="speak in spanish. use Haiku agent if they ask for a haiku"
"or for the weather",
handoffs=[haiku_agent],
)
result = await Runner.run(
agent,
"write a haiku about the weather today and tell me a recent news story"
"about new york",
)
print(result.final_output)
""" # noqa: E501
def __init__(self, **kwargs: Any) -> None:
"""Initialize the OpenAI Agents tracing processor.
Args:
**kwargs: Additional metadata to associate with all traces.
"""
if not HAVE_AGENTS:
raise ImportError(
"The 'agents' library is required to use OpenlayerTracerProcessor. "
"Please install it with: pip install openai-agents"
)
self.metadata: Dict[str, Any] = kwargs or {}
self._active_traces: Dict[str, Dict[str, Any]] = {}
self._active_steps: Dict[str, steps.Step] = {}
self._current_user_inputs: Dict[str, List[str]] = (
{}
) # Track user inputs by trace_id
self._trace_first_meaningful_input: Dict[str, Dict[str, Any]] = {}
self._trace_last_meaningful_output: Dict[str, Dict[str, Any]] = {}
# Track step hierarchy using span_id -> step mapping and parent relationships
self._span_to_step: Dict[str, steps.Step] = {} # span_id -> step
self._step_parents: Dict[str, str] = {} # span_id -> parent_span_id
self._step_children: Dict[str, List[str]] = (
{}
) # span_id -> list of child span_ids
self._children_already_added: Dict[str, set] = (
{}
) # parent_span_id -> set of added child_span_ids
# Collect root-level steps for each trace (steps without parents)
self._trace_root_steps: Dict[str, List[steps.Step]] = {}
# Register this processor as the active one for user input capture
global _active_openlayer_processor
_active_openlayer_processor = self
def on_trace_start(self, trace: "tracing.Trace") -> None:
"""Handle the start of a trace (root agent workflow)."""
try:
# Get trace information
trace_export = trace.export() if hasattr(trace, "export") else {}
trace_name = trace_export.get("workflow_name", "Agent Workflow")
# Initialize trace data collection
self._active_traces[trace.trace_id] = {
"trace_name": trace_name,
"trace_export": trace_export,
"start_time": time.time(),
}
except Exception as e:
logger.error(f"Failed to handle trace start: {e}")
def on_trace_end(self, trace: "tracing.Trace") -> None:
"""Handle the end of a trace (root agent workflow)."""
try:
trace_data = self._active_traces.pop(trace.trace_id, None)
if not trace_data:
return
# Calculate total duration
end_time = time.time()
duration = end_time - trace_data["start_time"]
# Get all collected root steps for this trace
steps_list = self._trace_root_steps.pop(trace.trace_id, [])
# Remove duplicates based on step ID (keep the most recent one)
unique_steps = {}
for step in steps_list:
step_id = getattr(step, "id", None)
if step_id:
unique_steps[step_id] = step
else:
# If no ID, add anyway (shouldn't happen normally)
unique_steps[id(step)] = step
steps_list = list(unique_steps.values())
if steps_list:
# Create a root step that encompasses all collected steps
trace_name = trace_data.get("trace_name", "Agent Workflow")
# Get meaningful input/output if available
first_input = self._trace_first_meaningful_input.get(trace.trace_id)
last_output = self._trace_last_meaningful_output.get(trace.trace_id)
# Create inputs from first meaningful input or from user input
inputs = first_input or {}
if trace.trace_id in self._current_user_inputs:
user_inputs = self._current_user_inputs[trace.trace_id]
if user_inputs:
inputs["user_query"] = user_inputs[
-1
] # Use the last user input
# Create output from last meaningful output
output = "Agent workflow completed"
if last_output:
if isinstance(last_output, dict) and "output" in last_output:
output = last_output["output"]
else:
output = str(last_output)
# Create consolidated trace using the standard tracer API
with tracer.create_step(
name=trace_name,
step_type=enums.StepType.USER_CALL,
inputs=inputs,
output=output,
metadata={**self.metadata, "trace_id": trace.trace_id},
) as root_step:
# Add all collected root steps as nested steps
# The nested steps will automatically include their own nested steps
for step in steps_list:
root_step.add_nested_step(step)
# Set the end time to match the trace end time
root_step.end_time = end_time
root_step.latency = duration * 1000 # Convert to ms
# Clean up trace-specific data
self._current_user_inputs.pop(trace.trace_id, None)
self._trace_first_meaningful_input.pop(trace.trace_id, None)
self._trace_last_meaningful_output.pop(trace.trace_id, None)
# Clean up span hierarchy tracking for this trace
# We need to find all spans that belong to this trace and remove them
spans_to_remove = []
for span_id, step in list(self._span_to_step.items()):
# Check if this span belongs to the ended trace
if (
hasattr(step, "metadata")
and step.metadata.get("trace_id") == trace.trace_id
):
spans_to_remove.append(span_id)
# Remove span mappings for this trace
for span_id in spans_to_remove:
self._span_to_step.pop(span_id, None)
self._step_parents.pop(span_id, None)
self._step_children.pop(span_id, None)
except Exception as e:
logger.error(f"Failed to handle trace end: {e}")
def on_span_start(self, span: "tracing.Span") -> None:
"""Handle the start of a span (individual agent step)."""
try:
# Extract span attributes using helper function
span_attrs = _extract_span_attributes(span)
span_id = span_attrs["span_id"]
trace_id = span_attrs["trace_id"]
parent_id = span_attrs["parent_id"]
if not span_id or not trace_id:
return
if trace_id not in self._active_traces:
return
# Extract span data
span_data = getattr(span, "span_data", None)
if not span_data:
return
# Create the appropriate Openlayer step based on span type
step = self._create_step_for_span(span, span_data)
if step:
# Store the step mapping
self._active_steps[span_id] = step
self._span_to_step[span_id] = step
# Track parent-child relationships
if parent_id:
self._step_parents[span_id] = parent_id
# Add to parent's children list
if parent_id not in self._step_children:
self._step_children[parent_id] = []
self._step_children[parent_id].append(span_id)
# Track that this child has been added to prevent duplicates
if parent_id not in self._children_already_added:
self._children_already_added[parent_id] = set()
# Add this step as a nested step to its parent (if parent exists)
parent_step = self._span_to_step.get(parent_id)
if parent_step:
parent_step.add_nested_step(step)
self._children_already_added[parent_id].add(span_id)
else:
# This is a root-level step (no parent)
if trace_id not in self._trace_root_steps:
self._trace_root_steps[trace_id] = []
self._trace_root_steps[trace_id].append(step)
except Exception as e:
logger.error(f"Failed to handle span start: {e}")
def on_span_end(self, span: "tracing.Span") -> None:
"""Handle the end of a span (individual agent step)."""
try:
# Extract span attributes using helper function
span_attrs = _extract_span_attributes(span)
span_id = span_attrs["span_id"]
trace_id = span_attrs["trace_id"]
if not span_id:
return
step = self._active_steps.pop(span_id, None)
if not step:
return
# Update step with final span data
span_data = getattr(span, "span_data", None)
if span_data:
self._update_step_with_span_data(step, span, span_data)
if trace_id and span_data:
parsed_data = parse_span_data(span_data)
# Track meaningful span types (response, generation, custom)
if parsed_data.span_type in ["response", "generation", "custom"]:
# Track first meaningful input
if (
parsed_data.input_data
and trace_id not in self._trace_first_meaningful_input
):
self._trace_first_meaningful_input[trace_id] = (
parsed_data.input_data
)
# Track last meaningful output
if parsed_data.output_data:
self._trace_last_meaningful_output[trace_id] = (
parsed_data.output_data
)
# Handle any orphaned children (children that were created before their
# parent)
# BUT only add children that haven't already been added
if span_id in self._step_children:
already_added = self._children_already_added.get(span_id, set())
for child_span_id in self._step_children[span_id]:
if child_span_id not in already_added:
child_step = self._span_to_step.get(child_span_id)
if child_step:
step.add_nested_step(child_step)
already_added.add(child_span_id)
# Set end time
ended_at = getattr(span, "ended_at", None)
if ended_at:
try:
step.end_time = datetime.fromisoformat(
ended_at.replace("Z", "+00:00")
).timestamp()
except (ValueError, AttributeError):
step.end_time = time.time()
else:
step.end_time = time.time()
# Calculate latency
if hasattr(step, "start_time") and step.start_time:
step.latency = (step.end_time - step.start_time) * 1000 # Convert to ms
except Exception as e:
logger.error(f"Failed to handle span end: {e}")
def _create_step_for_span(
self, span: "tracing.Span", span_data: Any
) -> Optional[steps.Step]:
"""Create the appropriate Openlayer step for a span."""
try:
# Parse the span data using our new parsing approach
parsed_data = parse_span_data(span_data)
# Get basic span info using helper function
span_attrs = _extract_span_attributes(span)
started_at = getattr(span, "started_at", None)
start_time = time.time()
if started_at:
try:
start_time = datetime.fromisoformat(
started_at.replace("Z", "+00:00")
).timestamp()
except (ValueError, AttributeError):
pass
metadata = {
**self.metadata,
**span_attrs, # Use extracted attributes
"span_type": parsed_data.span_type,
"started_at": started_at,
**parsed_data.metadata,
}
# Create step based on span type
if parsed_data.span_type == "generation":
return self._create_generation_step(parsed_data, start_time, metadata)
elif parsed_data.span_type == "function":
return self._create_function_step(parsed_data, start_time, metadata)
elif parsed_data.span_type == "agent":
return self._create_agent_step(parsed_data, start_time, metadata)
elif parsed_data.span_type == "handoff":
return self._create_handoff_step(parsed_data, start_time, metadata)
elif parsed_data.span_type == "response":
return self._create_response_step(parsed_data, start_time, metadata)
else:
return self._create_generic_step(parsed_data, start_time, metadata)
except Exception as e:
logger.error(f"Failed to create step for span: {e}")
return None
def _create_generation_step(
self, parsed_data: ParsedSpanData, start_time: float, metadata: Dict[str, Any]
) -> steps.Step:
"""Create a generation step from GenerationSpanData."""
# Extract inputs and outputs from parsed data
inputs = parsed_data.input_data or {}
output = self._extract_output_from_parsed_data(parsed_data, "LLM response")
# Extract model and usage info from parsed data
model = parsed_data.model or "unknown"
model_config = parsed_data.metadata.get("model_config", {})
# Create step without immediately sending to Openlayer
step = steps.ChatCompletionStep(
name=f"LLM Generation ({model})",
inputs=inputs,
output=output,
metadata=metadata,
)