-
Notifications
You must be signed in to change notification settings - Fork 531
Expand file tree
/
Copy pathtest_decorators.py
More file actions
763 lines (610 loc) · 30.8 KB
/
test_decorators.py
File metadata and controls
763 lines (610 loc) · 30.8 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
from typing import AsyncGenerator
import asyncio
import pytest
from agentops.sdk.decorators import agent, operation, session, workflow, task, tool
from agentops.semconv import SpanKind
from agentops.semconv.span_attributes import SpanAttributes
from tests.unit.sdk.instrumentation_tester import InstrumentationTester
from agentops.sdk.decorators.factory import create_entity_decorator
class TestSpanNesting:
"""Tests for proper nesting of spans in the tracing hierarchy."""
def test_operation_nests_under_agent(self, instrumentation: InstrumentationTester):
"""Test that operation spans are properly nested under their agent spans."""
# Define the test agent with nested operations
@agent
class NestedAgent:
def __init__(self):
pass # No logic needed
@operation
def nested_operation(self, message):
"""Nested operation that should appear as a child of the agent"""
return f"Processed: {message}"
@operation
def main_operation(self):
"""Main operation that calls the nested operation"""
# Call the nested operation
result = self.nested_operation("test message")
return result
# Test session with the agent
@session
def test_session():
agent = NestedAgent()
return agent.main_operation()
# Run the test with our instrumentor
result = test_session()
# Verify the result
assert result == "Processed: test message"
# Get all spans captured during the test
spans = instrumentation.get_finished_spans()
# Print detailed span information for debugging
print("\nDetailed span information:")
for i, span in enumerate(spans):
parent_id = span.parent.span_id if span.parent else "None"
span_id = span.context.span_id if span.context else "None"
print(f"Span {i}: name={span.name}, span_id={span_id}, parent_id={parent_id}")
# We should have 4 spans: session, agent, and two operations
assert len(spans) == 4
# Verify span kinds
session_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.SESSION
]
agent_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.AGENT
]
operation_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TASK
]
assert len(session_spans) == 1
assert len(agent_spans) == 1
assert len(operation_spans) == 2
# Find the main_operation and nested_operation spans
main_operation = None
nested_operation = None
for span in operation_spans:
if span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "main_operation":
main_operation = span
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "nested_operation":
nested_operation = span
assert main_operation is not None, "main_operation span not found"
assert nested_operation is not None, "nested_operation span not found"
# Verify the session span is the root
session_span = session_spans[0]
assert session_span.parent is None
# Verify the agent span is a child of the session span
agent_span = agent_spans[0]
assert agent_span.parent is not None
assert session_span.context is not None
assert agent_span.parent.span_id == session_span.context.span_id
# Verify main_operation is a child of the agent span
assert main_operation.parent is not None
assert agent_span.context is not None
assert main_operation.parent.span_id == agent_span.context.span_id
# Verify nested_operation is a child of main_operation
assert nested_operation.parent is not None
assert main_operation.context is not None
assert nested_operation.parent.span_id == main_operation.context.span_id
def test_async_operations(self, instrumentation: InstrumentationTester):
"""Test that async operations are properly nested."""
# Define the test agent with async operations
@agent
class AsyncAgent:
def __init__(self):
pass
@operation
async def nested_async_operation(self, message):
"""Async operation that should appear as a child of the main operation"""
await asyncio.sleep(0.01) # Small delay to simulate async work
return f"Processed async: {message}"
@operation
async def main_async_operation(self):
"""Main async operation that calls the nested async operation"""
result = await self.nested_async_operation("test async")
return result
# Test session with the async agent
@session
async def test_async_session():
agent = AsyncAgent()
return await agent.main_async_operation()
# Run the async test
result = asyncio.run(test_async_session())
# Verify the result
assert result == "Processed async: test async"
# Get all spans captured during the test
spans = instrumentation.get_finished_spans()
# Print detailed span information for debugging
print("\nDetailed span information for async test:")
for i, span in enumerate(spans):
parent_id = span.parent.span_id if span.parent else "None"
span_id = span.context.span_id if span.context else "None"
print(f"Span {i}: name={span.name}, span_id={span_id}, parent_id={parent_id}")
# We should have 4 spans: session, agent, and two operations
assert len(spans) == 4
# Verify span kinds
session_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.SESSION
]
agent_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.AGENT
]
operation_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TASK
]
assert len(session_spans) == 1
assert len(agent_spans) == 1
assert len(operation_spans) == 2
# Find the main_operation and nested_operation spans
main_operation = None
nested_operation = None
for span in operation_spans:
if span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "main_async_operation":
main_operation = span
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "nested_async_operation":
nested_operation = span
assert main_operation is not None, "main_async_operation span not found"
assert nested_operation is not None, "nested_async_operation span not found"
# Verify the session span is the root
session_span = session_spans[0]
assert session_span.parent is None
# Verify the agent span is a child of the session span
agent_span = agent_spans[0]
assert agent_span.parent is not None
assert session_span.context is not None
assert agent_span.parent.span_id == session_span.context.span_id
# Verify main_operation is a child of the agent span
assert main_operation.parent is not None
assert agent_span.context is not None
assert main_operation.parent.span_id == agent_span.context.span_id
# Verify nested_operation is a child of main_operation
assert nested_operation.parent is not None
assert main_operation.context is not None
assert nested_operation.parent.span_id == main_operation.context.span_id
def test_generator_operations(self, instrumentation: InstrumentationTester):
"""Test that generator operations are properly nested."""
# Define the test agent with generator operations
@agent
class GeneratorAgent:
def __init__(self):
pass
@operation
def nested_generator(self, count):
"""Generator operation that should appear as a child of the main operation"""
for i in range(count):
yield f"Item {i}"
@operation
def main_generator_operation(self, count):
"""Main operation that calls the nested generator"""
results = []
for item in self.nested_generator(count):
results.append(item)
return results
# Test session with the generator agent
@session
def test_generator_session():
agent = GeneratorAgent()
return agent.main_generator_operation(3)
# Run the test
result = test_generator_session()
# Verify the result
assert result == ["Item 0", "Item 1", "Item 2"]
# Get all spans captured during the test
spans = instrumentation.get_finished_spans()
# Print detailed span information for debugging
print("\nDetailed span information for generator test:")
for i, span in enumerate(spans):
parent_id = span.parent.span_id if span.parent else "None"
span_id = span.context.span_id if span.context else "None"
print(f"Span {i}: name={span.name}, span_id={span_id}, parent_id={parent_id}")
# We should have 4 spans: session, agent, and two operations
assert len(spans) == 4
# Verify span kinds
session_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.SESSION
]
agent_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.AGENT
]
operation_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TASK
]
assert len(session_spans) == 1
assert len(agent_spans) == 1
assert len(operation_spans) == 2
# Find the main_operation and nested_operation spans
main_operation = None
nested_operation = None
for span in operation_spans:
if span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "main_generator_operation":
main_operation = span
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "nested_generator":
nested_operation = span
assert main_operation is not None, "main_generator_operation span not found"
assert nested_operation is not None, "nested_generator span not found"
# Verify the session span is the root
session_span = session_spans[0]
assert session_span.parent is None
# Verify the agent span is a child of the session span
agent_span = agent_spans[0]
assert agent_span.parent is not None
assert session_span.context is not None
assert agent_span.parent.span_id == session_span.context.span_id
# Verify main_operation is a child of the agent span
assert main_operation.parent is not None
assert agent_span.context is not None
assert main_operation.parent.span_id == agent_span.context.span_id
# Verify nested_operation is a child of main_operation
assert nested_operation.parent is not None
assert main_operation.context is not None
assert nested_operation.parent.span_id == main_operation.context.span_id
def test_async_generator_operations(self, instrumentation: InstrumentationTester):
"""Test that async generator operations are properly nested."""
# Define the test agent with async generator operations
@agent
class AsyncGeneratorAgent:
def __init__(self):
pass
@operation
async def nested_async_generator(self, count) -> AsyncGenerator[str, None]:
"""Async generator operation that should appear as a child of the main operation"""
for i in range(count):
await asyncio.sleep(0.01) # Small delay to simulate async work
yield f"Async Item {i}"
@operation
async def main_async_generator_operation(self, count):
"""Main async operation that calls the nested async generator"""
results = []
async for item in self.nested_async_generator(count):
results.append(item)
return results
# Test session with the async generator agent
@session
async def test_async_generator_session():
agent = AsyncGeneratorAgent()
return await agent.main_async_generator_operation(3)
# Run the async test
result = asyncio.run(test_async_generator_session())
# Verify the result
assert result == ["Async Item 0", "Async Item 1", "Async Item 2"]
# Get all spans captured during the test
spans = instrumentation.get_finished_spans()
# Print detailed span information for debugging
print("\nDetailed span information for async generator test:")
for i, span in enumerate(spans):
parent_id = span.parent.span_id if span.parent else "None"
span_id = span.context.span_id if span.context else "None"
print(f"Span {i}: name={span.name}, span_id={span_id}, parent_id={parent_id}")
# We should have 4 spans: session, agent, and two operations
assert len(spans) == 4
# Verify span kinds
session_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.SESSION
]
agent_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.AGENT
]
operation_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TASK
]
assert len(session_spans) == 1
assert len(agent_spans) == 1
assert len(operation_spans) == 2
# Find the main_operation and nested_operation spans
main_operation = None
nested_operation = None
for span in operation_spans:
if (
span.attributes
and span.attributes.get(SpanAttributes.OPERATION_NAME) == "main_async_generator_operation"
):
main_operation = span
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "nested_async_generator":
nested_operation = span
assert main_operation is not None, "main_async_generator_operation span not found"
assert nested_operation is not None, "nested_async_generator span not found"
# Verify the session span is the root
session_span = session_spans[0]
assert session_span.parent is None
# Verify the agent span is a child of the session span
agent_span = agent_spans[0]
assert agent_span.parent is not None
assert session_span.context is not None
assert agent_span.parent.span_id == session_span.context.span_id
# Verify main_operation is a child of the agent span
assert main_operation.parent is not None
assert agent_span.context is not None
assert main_operation.parent.span_id == agent_span.context.span_id
# Verify nested_operation is a child of main_operation
assert nested_operation.parent is not None
assert main_operation.context is not None
assert nested_operation.parent.span_id == main_operation.context.span_id
def test_complex_nesting(self, instrumentation: InstrumentationTester):
"""Test complex nesting with multiple levels of operations."""
# Define the test agent with complex nesting
@agent
class ComplexAgent:
def __init__(self):
pass
@operation
def level3_operation(self, message):
"""Level 3 operation (deepest)"""
return f"Level 3: {message}"
@operation
def level2_operation(self, message):
"""Level 2 operation that calls level 3"""
result = self.level3_operation(message)
return f"Level 2: {result}"
@operation
def level1_operation(self, message):
"""Level 1 operation that calls level 2"""
result = self.level2_operation(message)
return f"Level 1: {result}"
# Test session with the complex agent
@session
def test_complex_session():
agent = ComplexAgent()
return agent.level1_operation("test message")
# Run the test
result = test_complex_session()
# Verify the result
assert result == "Level 1: Level 2: Level 3: test message"
# Get all spans captured during the test
spans = instrumentation.get_finished_spans()
# Print detailed span information for debugging
print("\nDetailed span information for complex nesting test:")
for i, span in enumerate(spans):
parent_id = span.parent.span_id if span.parent else "None"
span_id = span.context.span_id if span.context else "None"
print(f"Span {i}: name={span.name}, span_id={span_id}, parent_id={parent_id}")
# We should have 5 spans: session, agent, and three operations
assert len(spans) == 5
# Verify span kinds
session_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.SESSION
]
agent_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.AGENT
]
operation_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TASK
]
assert len(session_spans) == 1
assert len(agent_spans) == 1
assert len(operation_spans) == 3
# Find the operation spans
level1_operation = None
level2_operation = None
level3_operation = None
for span in operation_spans:
if span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "level1_operation":
level1_operation = span
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "level2_operation":
level2_operation = span
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "level3_operation":
level3_operation = span
assert level1_operation is not None, "level1_operation span not found"
assert level2_operation is not None, "level2_operation span not found"
assert level3_operation is not None, "level3_operation span not found"
# Verify the session span is the root
session_span = session_spans[0]
assert session_span.parent is None
# Verify the agent span is a child of the session span
agent_span = agent_spans[0]
assert agent_span.parent is not None
assert session_span.context is not None
assert agent_span.parent.span_id == session_span.context.span_id
# Verify level1_operation is a child of the agent span
assert level1_operation.parent is not None
assert agent_span.context is not None
assert level1_operation.parent.span_id == agent_span.context.span_id
# Verify level2_operation is a child of level1_operation
assert level2_operation.parent is not None
assert level1_operation.context is not None
assert level2_operation.parent.span_id == level1_operation.context.span_id
# Verify level3_operation is a child of level2_operation
assert level3_operation.parent is not None
assert level2_operation.context is not None
assert level3_operation.parent.span_id == level2_operation.context.span_id
def test_workflow_and_task_nesting(self, instrumentation: InstrumentationTester):
"""Test that workflow and task decorators create proper span nesting."""
# Define a workflow with tasks
@workflow
def data_processing_workflow(data):
"""Main workflow that processes data through multiple tasks"""
result = process_input(data)
result = transform_data(result)
return result
@task
def process_input(data):
"""Task to process input data"""
return f"Processed: {data}"
@task
def transform_data(data):
"""Task to transform processed data"""
return f"Transformed: {data}"
# Test session with the workflow
@session
def test_workflow_session():
return data_processing_workflow("test data")
# Run the test
result = test_workflow_session()
# Verify the result
assert result == "Transformed: Processed: test data"
# Get all spans captured during the test
spans = instrumentation.get_finished_spans()
# Print detailed span information for debugging
print("\nDetailed span information for workflow and task test:")
for i, span in enumerate(spans):
parent_id = span.parent.span_id if span.parent else "None"
span_id = span.context.span_id if span.context else "None"
print(f"Span {i}: name={span.name}, span_id={span_id}, parent_id={parent_id}")
# We should have 4 spans: session, workflow, and two tasks
assert len(spans) == 4
# Verify span kinds
session_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.SESSION
]
workflow_spans = [
s
for s in spans
if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.WORKFLOW
]
task_spans = [
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TASK
]
assert len(session_spans) == 1
assert len(workflow_spans) == 1
assert len(task_spans) == 2
# Find the workflow and task spans
workflow_span = None
process_task = None
transform_task = None
for span in spans:
if span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "data_processing_workflow":
workflow_span = span
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "process_input":
process_task = span
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "transform_data":
transform_task = span
assert workflow_span is not None, "workflow span not found"
assert process_task is not None, "process_input task span not found"
assert transform_task is not None, "transform_data task span not found"
# Verify the session span is the root
session_span = session_spans[0]
assert session_span.parent is None
# Verify the workflow span is a child of the session span
assert workflow_span.parent is not None
assert session_span.context is not None
assert workflow_span.parent.span_id == session_span.context.span_id
# Verify process_task is a child of the workflow span
assert process_task.parent is not None
assert workflow_span.context is not None
assert process_task.parent.span_id == workflow_span.context.span_id
# Verify transform_task is a child of the workflow span
assert transform_task.parent is not None
assert workflow_span.context is not None
assert transform_task.parent.span_id == workflow_span.context.span_id
@pytest.mark.asyncio
async def test_async_context_manager():
"""
Tests async context manager functionality (__aenter__, __aexit__).
"""
# Create a simple decorated class
@create_entity_decorator("test")
class TestClass:
def __init__(self):
self.value = 42
# Cover __aenter__ and __aexit__ (normal exit)
async with TestClass() as instance:
assert hasattr(instance, "_agentops_active_span")
assert instance._agentops_active_span is not None
# Cover __aenter__ and __aexit__ (exceptional exit)
with pytest.raises(ValueError):
async with TestClass() as instance:
raise ValueError("Trigger exception for __aexit__ coverage")
class TestToolDecorator:
"""Tests for the tool decorator functionality."""
@pytest.fixture
def agent_class(self):
@agent
class TestAgent:
@tool(cost=0.01)
def process_item(self, item):
return f"Processed {item}"
@tool(cost=0.02)
async def async_process_item(self, item):
await asyncio.sleep(0.1)
return f"Async processed {item}"
@tool(cost=0.03)
def generator_process_items(self, items):
for item in items:
yield self.process_item(item)
@tool(cost=0.04)
async def async_generator_process_items(self, items):
for item in items:
await asyncio.sleep(0.1)
yield await self.async_process_item(item)
return TestAgent()
def test_sync_tool_cost(self, agent_class, instrumentation: InstrumentationTester):
"""Test synchronous tool with cost attribute."""
result = agent_class.process_item("test")
assert result == "Processed test"
spans = instrumentation.get_finished_spans()
tool_span = next(
span for span in spans if span.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TOOL
)
assert tool_span.attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.01
@pytest.mark.asyncio
async def test_async_tool_cost(self, agent_class, instrumentation: InstrumentationTester):
"""Test asynchronous tool with cost attribute."""
result = await agent_class.async_process_item("test")
assert result == "Async processed test"
spans = instrumentation.get_finished_spans()
tool_span = next(
span for span in spans if span.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TOOL
)
assert tool_span.attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.02
def test_generator_tool_cost(self, agent_class, instrumentation: InstrumentationTester):
"""Test generator tool with cost attribute."""
items = ["item1", "item2", "item3"]
results = list(agent_class.generator_process_items(items))
assert len(results) == 3
assert results[0] == "Processed item1"
assert results[1] == "Processed item2"
assert results[2] == "Processed item3"
spans = instrumentation.get_finished_spans()
tool_spans = [span for span in spans if span.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TOOL]
assert len(tool_spans) == 4 # Only one span for the generator
assert tool_spans[0].attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.01
assert tool_spans[3].attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.03
@pytest.mark.asyncio
async def test_async_generator_tool_cost(self, agent_class, instrumentation: InstrumentationTester):
"""Test async generator tool with cost attribute."""
items = ["item1", "item2", "item3"]
results = [result async for result in agent_class.async_generator_process_items(items)]
assert len(results) == 3
assert results[0] == "Async processed item1"
assert results[1] == "Async processed item2"
assert results[2] == "Async processed item3"
spans = instrumentation.get_finished_spans()
tool_span = [span for span in spans if span.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TOOL]
assert len(tool_span) == 4 # Only one span for the generator
assert tool_span[0].attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.02
assert tool_span[3].attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.04
def test_multiple_tool_calls(self, agent_class, instrumentation: InstrumentationTester):
"""Test multiple calls to the same tool."""
for i in range(3):
result = agent_class.process_item(f"item{i}")
assert result == f"Processed item{i}"
spans = instrumentation.get_finished_spans()
tool_spans = [span for span in spans if span.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TOOL]
assert len(tool_spans) == 3
for span in tool_spans:
assert span.attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.01
@pytest.mark.asyncio
async def test_parallel_tool_calls(self, agent_class, instrumentation: InstrumentationTester):
"""Test parallel execution of async tools."""
results = await asyncio.gather(
agent_class.async_process_item("item1"),
agent_class.async_process_item("item2"),
agent_class.async_process_item("item3"),
)
assert len(results) == 3
assert results[0] == "Async processed item1"
assert results[1] == "Async processed item2"
assert results[2] == "Async processed item3"
spans = instrumentation.get_finished_spans()
tool_spans = [span for span in spans if span.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TOOL]
assert len(tool_spans) == 3
for span in tool_spans:
assert span.attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.02
def test_tool_without_cost(self, agent_class, instrumentation: InstrumentationTester):
"""Test tool without cost parameter."""
@tool
def no_cost_tool(self):
return "No cost tool result"
result = no_cost_tool(agent_class)
assert result == "No cost tool result"
spans = instrumentation.get_finished_spans()
tool_span = next(
span for span in spans if span.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TOOL
)
assert SpanAttributes.LLM_USAGE_TOOL_COST not in tool_span.attributes