-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtest_adk.py
More file actions
1772 lines (1390 loc) · 64.6 KB
/
test_adk.py
File metadata and controls
1772 lines (1390 loc) · 64.6 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
import os
from importlib.metadata import version as pkg_version
from pathlib import Path
import pytest
from braintrust import logger
from braintrust.bt_json import bt_safe_deep_copy
from braintrust.integrations.adk import setup_adk
from braintrust.integrations.adk.tracing import _create_thread_wrapper
from braintrust.logger import Attachment
from braintrust.test_helpers import init_test_logger
from google.adk import Agent
ADK_VERSION = tuple(int(x) for x in pkg_version("google-adk").split(".")[:3])
from google.adk.agents import LlmAgent, ParallelAgent, SequentialAgent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
from pydantic import BaseModel, Field
PROJECT_NAME = "test_adk"
FIXTURES_DIR = Path(__file__).parent.parent.parent.parent.parent.parent / "internal" / "golden" / "fixtures"
setup_adk(project_name=PROJECT_NAME)
@pytest.fixture(scope="module")
def vcr_config():
"""Google ADK VCR config - needs to uppercase HTTP methods (same as google_genai)."""
record_mode = "none" if (os.environ.get("CI") or os.environ.get("GITHUB_ACTIONS")) else "once"
def before_record_request(request):
# Normalize HTTP method to uppercase for consistency (Google API quirk)
request.method = request.method.upper()
return request
return {
"record_mode": record_mode,
"cassette_library_dir": str(Path(__file__).parent / "cassettes"),
"filter_headers": [
"authorization",
"Authorization",
"x-goog-api-key",
],
"before_record_request": before_record_request,
}
@pytest.fixture
def memory_logger():
init_test_logger(PROJECT_NAME)
with logger._internal_with_memory_background_logger() as bgl:
yield bgl
async def _create_runner(agent: Agent, *, app_name: str, user_id: str, session_id: str) -> Runner:
session_service = InMemorySessionService()
await session_service.create_session(app_name=app_name, user_id=user_id, session_id=session_id)
return Runner(agent=agent, app_name=app_name, session_service=session_service)
def _extract_text_parts(contents):
texts = []
for content in contents or []:
for part in content.get("parts", []):
text = part.get("text")
if text is not None:
texts.append(text)
return texts
def test_adk_thread_context_propagation(memory_logger):
"""Runner.run should preserve Braintrust context across its thread bridge."""
import asyncio
from braintrust import current_span, start_span
from google.adk.agents import LlmAgent
from google.adk.models.base_llm import BaseLlm
from google.adk.models.llm_request import LlmRequest
from google.adk.models.llm_response import LlmResponse
from google.adk.models.registry import LLMRegistry
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
assert not memory_logger.pop()
parent_seen = []
class TestLlm(BaseLlm):
@classmethod
def supported_models(cls) -> list[str]:
return [r"test-llm-context-prop"]
async def generate_content_async(self, llm_request: LlmRequest, stream: bool = False):
parent_seen.append(current_span())
yield LlmResponse(content=types.Content(role="model", parts=[types.Part(text="ok")]))
LLMRegistry.register(TestLlm)
agent = LlmAgent(
name="echo_agent",
model="test-llm-context-prop",
instruction="Respond with ok.",
)
session_service = InMemorySessionService()
app_name = "thread_bridge_app"
user_id = "test-user"
session_id = "test-session-thread"
asyncio.run(
session_service.create_session(
app_name=app_name,
user_id=user_id,
session_id=session_id,
)
)
runner = Runner(agent=agent, app_name=app_name, session_service=session_service)
user_msg = types.Content(role="user", parts=[types.Part(text="hello")])
with start_span(name="adk_thread_parent") as parent_span:
events = list(runner.run(user_id=user_id, session_id=session_id, new_message=user_msg))
assert events
assert parent_seen
thread_root = getattr(parent_seen[0], "root_span_id", None)
assert thread_root is not None
assert thread_root == parent_span.root_span_id
def test_create_thread_wrapper_exception_does_not_double_invoke_target():
"""Regression test: target exceptions must not cause a second invocation."""
call_count = 0
def create_thread(target, *args, **kwargs):
return target(*args, **kwargs)
def target():
nonlocal call_count
call_count += 1
raise RuntimeError("boom")
with pytest.raises(RuntimeError, match="boom"):
_create_thread_wrapper(create_thread, None, (target,), {})
assert call_count == 1
@pytest.mark.vcr
@pytest.mark.asyncio
async def test_adk_multi_turn_history_is_logged(memory_logger):
"""Multi-turn session history should be visible in traced LLM requests."""
assert not memory_logger.pop()
app_name = "conversation_app"
user_id = "test-user"
session_id = "test-session-conversation"
agent = Agent(
name="conversation_agent",
model="gemini-2.0-flash",
instruction=(
"You are a concise assistant. "
"When the user says their name, acknowledge it briefly. "
"When later asked to recall it, answer with just the name."
),
)
runner = await _create_runner(agent, app_name=app_name, user_id=user_id, session_id=session_id)
async def run_message(text: str) -> str:
responses = []
user_msg = types.Content(role="user", parts=[types.Part(text=text)])
async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=user_msg):
if event.is_final_response():
responses.append(event)
assert responses
return responses[0].content.parts[0].text
first_response_text = await run_message("Hi, my name is Alice.")
second_response_text = await run_message("What name did I tell you?")
memory_logger.flush()
spans = memory_logger.pop()
invocation_spans = [row for row in spans if row["span_attributes"]["name"] == f"invocation [{app_name}]"]
assert len(invocation_spans) == 2
assert {span["metadata"]["session_id"] for span in invocation_spans} == {session_id}
assert {span["input"]["new_message"]["parts"][0]["text"] for span in invocation_spans} == {
"Hi, my name is Alice.",
"What name did I tell you?",
}
llm_spans = [row for row in spans if row["span_attributes"]["type"] == "llm"]
assert len(llm_spans) == 2
follow_up_span = next(
span for span in llm_spans if "What name did I tell you?" in _extract_text_parts(span["input"]["contents"])
)
follow_up_texts = _extract_text_parts(follow_up_span["input"]["contents"])
assert "Hi, my name is Alice." in follow_up_texts
assert "What name did I tell you?" in follow_up_texts
assert first_response_text in follow_up_texts
assert "alice" in second_response_text.lower()
@pytest.mark.asyncio
async def test_adk_generation_config_is_logged(memory_logger):
"""Sampling and stop-sequence config should be captured in the LLM span input."""
from google.adk.models.base_llm import BaseLlm
from google.adk.models.llm_request import LlmRequest
from google.adk.models.llm_response import LlmResponse
from google.adk.models.registry import LLMRegistry
assert not memory_logger.pop()
class ConfigCaptureLlm(BaseLlm):
@classmethod
def supported_models(cls) -> list[str]:
return [r"test-llm-config-capture"]
async def generate_content_async(self, llm_request: LlmRequest, stream: bool = False):
yield LlmResponse(content=types.Content(role="model", parts=[types.Part(text="configured")]))
LLMRegistry.register(ConfigCaptureLlm)
app_name = "config_app"
user_id = "test-user"
session_id = "test-session-config"
agent = LlmAgent(
name="config_agent",
model="test-llm-config-capture",
instruction="Reply with the word configured.",
generate_content_config=types.GenerateContentConfig(
max_output_tokens=23,
temperature=0.7,
top_p=0.9,
stop_sequences=["END", "\n\n"],
),
)
runner = await _create_runner(agent, app_name=app_name, user_id=user_id, session_id=session_id)
user_msg = types.Content(role="user", parts=[types.Part(text="Please answer.")])
responses = []
async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=user_msg):
if event.is_final_response():
responses.append(event)
assert responses
spans = memory_logger.pop()
llm_spans = [row for row in spans if row["span_attributes"]["type"] == "llm"]
assert llm_spans
config = llm_spans[0]["input"]["config"]
assert config["max_output_tokens"] == 23
assert config["temperature"] == 0.7
assert config["top_p"] == 0.9
assert config["stop_sequences"] == ["END", "\n\n"]
@pytest.mark.asyncio
async def test_adk_document_inline_data_attachment_conversion(memory_logger):
"""Document bytes should be logged as attachment references, not raw payloads."""
from google.adk.models.base_llm import BaseLlm
from google.adk.models.llm_request import LlmRequest
from google.adk.models.llm_response import LlmResponse
from google.adk.models.registry import LLMRegistry
assert not memory_logger.pop()
class DocumentCaptureLlm(BaseLlm):
@classmethod
def supported_models(cls) -> list[str]:
return [r"test-llm-document-capture"]
async def generate_content_async(self, llm_request: LlmRequest, stream: bool = False):
yield LlmResponse(content=types.Content(role="model", parts=[types.Part(text="document received")]))
LLMRegistry.register(DocumentCaptureLlm)
app_name = "document_app"
user_id = "test-user"
session_id = "test-session-document"
agent = LlmAgent(
name="document_agent",
model="test-llm-document-capture",
instruction="Acknowledge the uploaded document.",
)
runner = await _create_runner(agent, app_name=app_name, user_id=user_id, session_id=session_id)
pdf_path = FIXTURES_DIR / "test-document.pdf"
with open(pdf_path, "rb") as f:
pdf_data = f.read()
user_msg = types.Content(
role="user",
parts=[
types.Part(inline_data=types.Blob(mime_type="application/pdf", data=pdf_data)),
types.Part(text="Summarize this document."),
],
)
responses = []
async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=user_msg):
if event.is_final_response():
responses.append(event)
assert responses
spans = memory_logger.pop()
invocation_span = next(row for row in spans if row["span_attributes"]["name"] == f"invocation [{app_name}]")
new_message = invocation_span["input"]["new_message"]
assert len(new_message["parts"]) == 2
document_part = new_message["parts"][0]
assert "image_url" in document_part
attachment = document_part["image_url"]["url"]
assert isinstance(attachment, Attachment)
assert attachment.reference["content_type"] == "application/pdf"
assert attachment.reference["filename"] == "file.pdf"
text_part = new_message["parts"][1]
assert text_part == {"text": "Summarize this document."}
logged_payload = str(invocation_span).lower()
assert pdf_data[:8].hex() not in logged_payload
llm_span = next(row for row in spans if row["span_attributes"]["type"] == "llm")
llm_contents = llm_span["input"]["contents"]
llm_document_part = llm_contents[0]["parts"][0]
assert isinstance(llm_document_part["image_url"]["url"], Attachment)
assert llm_document_part["image_url"]["url"].reference["content_type"] == "application/pdf"
@pytest.mark.vcr
@pytest.mark.asyncio
async def test_adk_braintrust_integration(memory_logger):
assert not memory_logger.pop()
def get_weather(location: str):
"""Get the weather for a location."""
return {
"location": location,
"temperature": "72°F",
"condition": "sunny",
"humidity": "45%",
"wind": "5 mph NW",
}
agent = Agent(
name="weather_agent",
model="gemini-2.0-flash",
instruction="You are a helpful weather assistant. Use the get_weather tool to answer questions about weather.",
tools=[get_weather],
)
# Set up session
APP_NAME = "weather_app"
USER_ID = "test-user"
SESSION_ID = "test-session"
session_service = InMemorySessionService()
await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
runner = Runner(agent=agent, app_name=APP_NAME, session_service=session_service)
user_msg = types.Content(role="user", parts=[types.Part(text="What's the weather in San Francisco?")])
responses = []
async for event in runner.run_async(user_id=USER_ID, session_id=SESSION_ID, new_message=user_msg):
if event.is_final_response():
responses.append(event)
assert len(responses) > 0
assert responses[0].content
assert responses[0].content.parts
response_text = responses[0].content.parts[0].text
assert any(word in response_text.lower() for word in ["weather", "san francisco", "72", "sunny"]), (
f"Response doesn't mention weather: {response_text}"
)
spans = memory_logger.pop()
# Check that we have the expected span types
span_types = {row["span_attributes"]["type"] for row in spans}
assert "task" in span_types, "Missing 'task' spans"
assert "llm" in span_types, "Missing 'llm' spans"
# Verify the invocation span
invocation_spans = [row for row in spans if row["span_attributes"]["name"] == "invocation [weather_app]"]
assert len(invocation_spans) > 0, "Missing invocation span"
invocation_span = invocation_spans[0]
# Check invocation input
assert "input" in invocation_span, "Missing input in invocation span"
assert "new_message" in invocation_span["input"], "Missing new_message in input"
assert invocation_span["input"]["new_message"]["parts"][0]["text"] == "What's the weather in San Francisco?"
# Check metadata
assert "metadata" in invocation_span, "Missing metadata in invocation span"
assert invocation_span["metadata"]["user_id"] == "test-user"
assert invocation_span["metadata"]["session_id"] == "test-session"
# Verify LLM call spans
llm_spans = [row for row in spans if row["span_attributes"]["type"] == "llm"]
assert len(llm_spans) >= 2, "Should have at least 2 LLM calls (tool selection and response generation)"
# Check tool selection LLM call
tool_selection_spans = [span for span in llm_spans if "tool_selection" in span["span_attributes"]["name"]]
assert len(tool_selection_spans) > 0, "Missing tool selection LLM call"
tool_selection_span = tool_selection_spans[0]
assert "output" in tool_selection_span, "Missing output in tool selection span"
assert "content" in tool_selection_span["output"], "Missing content in tool selection output"
# Verify it called the get_weather function
function_call = tool_selection_span["output"]["content"]["parts"][0]["function_call"]
assert function_call["name"] == "get_weather"
assert function_call["args"]["location"] == "San Francisco"
# Check response generation LLM call
response_gen_spans = [span for span in llm_spans if "response_generation" in span["span_attributes"]["name"]]
assert len(response_gen_spans) > 0, "Missing response generation LLM call"
response_span = response_gen_spans[0]
assert "output" in response_span, "Missing output in response generation span"
response_output = response_span["output"]["content"]["parts"][0]["text"]
assert "san francisco" in response_output.lower(), "Response doesn't mention San Francisco"
assert "72" in response_output, "Response doesn't mention temperature"
@pytest.mark.vcr
@pytest.mark.asyncio
async def test_adk_nested_subagent_tool_calls_are_traced(memory_logger):
assert not memory_logger.pop()
def get_weather(location: str):
"""Get the weather for a location."""
return {
"location": location,
"temperature": "72°F",
"condition": "sunny",
}
leaf_agent = Agent(
name="weather_agent",
model="gemini-2.0-flash",
instruction="You are a helpful weather assistant. Use the get_weather tool to answer questions about weather.",
tools=[get_weather],
)
agent = SequentialAgent(
name="root_agent",
sub_agents=[
ParallelAgent(
name="parallel_weather_agent",
sub_agents=[leaf_agent],
)
],
)
app_name = "nested_weather_app"
user_id = "test-user"
session_id = "test-session-nested"
session_service = InMemorySessionService()
await session_service.create_session(app_name=app_name, user_id=user_id, session_id=session_id)
runner = Runner(agent=agent, app_name=app_name, session_service=session_service)
user_msg = types.Content(role="user", parts=[types.Part(text="What's the weather in San Francisco?")])
responses = []
async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=user_msg):
if event.is_final_response():
responses.append(event)
assert responses
assert responses[0].content
response_text = responses[0].content.parts[0].text
assert "san francisco" in response_text.lower()
spans = memory_logger.pop()
tool_spans = [row for row in spans if row["span_attributes"]["type"] == "tool"]
assert len(tool_spans) == 1, (
f"Expected one tool span, got {[row['span_attributes']['name'] for row in tool_spans]}"
)
tool_span = tool_spans[0]
assert tool_span["span_attributes"]["name"] == "tool [get_weather]"
assert tool_span["input"]["arguments"] == {"location": "San Francisco"}
assert tool_span["output"]["location"] == "San Francisco"
assert tool_span["output"]["temperature"] == "72°F"
@pytest.mark.vcr
@pytest.mark.asyncio
async def test_adk_max_tokens_captures_content(memory_logger):
"""Test that content is captured even when MAX_TOKENS finish reason occurs."""
assert not memory_logger.pop()
agent = Agent(
name="creative_agent",
model="gemini-2.0-flash",
instruction="You are a creative storyteller.",
generate_content_config=types.GenerateContentConfig(
max_output_tokens=50, # Set low to trigger MAX_TOKENS
temperature=0.7,
),
)
APP_NAME = "creative_app"
USER_ID = "test-user"
SESSION_ID = "test-session-max-tokens"
session_service = InMemorySessionService()
await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
runner = Runner(agent=agent, app_name=APP_NAME, session_service=session_service)
user_msg = types.Content(role="user", parts=[types.Part(text="Tell me a long story about a lighthouse.")])
responses = []
async for event in runner.run_async(user_id=USER_ID, session_id=SESSION_ID, new_message=user_msg):
if event.is_final_response():
responses.append(event)
assert len(responses) > 0
spans = memory_logger.pop()
# Find the LLM call span
llm_spans = [row for row in spans if row["span_attributes"]["type"] == "llm"]
assert len(llm_spans) > 0, "Missing LLM call span"
llm_span = llm_spans[0]
assert "output" in llm_span, "Missing output in LLM span"
output = llm_span["output"]
# When MAX_TOKENS is hit, we should still have content captured
# The integration should merge content from earlier events if the final event lacks it
if "finish_reason" in output and output["finish_reason"] == "MAX_TOKENS":
# This is the MAX_TOKENS case - verify we still captured content
assert "content" in output, "Content should be captured even with MAX_TOKENS"
assert output["content"] is not None, "Content should not be None"
assert "parts" in output["content"], "Content should have parts"
assert len(output["content"]["parts"]) > 0, "Content parts should not be empty"
# Verify the text was actually captured
text_content = output["content"]["parts"][0].get("text", "")
assert len(text_content) > 0, "Should have captured some text content before MAX_TOKENS"
# Verify usage metadata is present
assert "usage_metadata" in output, "Should have usage metadata"
def test_serialize_content_with_binary_data():
"""Test that _serialize_content converts binary data to Attachment references."""
from braintrust.integrations.adk.tracing import _serialize_content, _serialize_part
from braintrust.logger import Attachment
# Create a minimal PNG image (1x1 red pixel)
minimal_png = (
b"\x89PNG\r\n\x1a\n" # PNG signature
b"\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde" # IHDR
b"\x00\x00\x00\x0cIDATx\x9cc\xf8\xcf\xc0\x00\x00\x00\x03\x00\x01\x00\x18\xdd\x8d\xb4" # IDAT
b"\x00\x00\x00\x00IEND\xaeB`\x82" # IEND
)
# Create a mock Part with inline_data
class MockBlob:
def __init__(self, data, mime_type):
self.data = data
self.mime_type = mime_type
class MockPart:
def __init__(self, inline_data=None, text=None):
self.inline_data = inline_data
self.text = text
# Test serializing a Part with binary data
part_with_image = MockPart(inline_data=MockBlob(minimal_png, "image/png"))
serialized_part = _serialize_part(part_with_image)
# Verify structure
assert "image_url" in serialized_part, "Should have image_url field"
assert "url" in serialized_part["image_url"], "Should have url field"
attachment = serialized_part["image_url"]["url"]
# The Attachment object should be in the serialized output
assert isinstance(attachment, Attachment), "Should be an Attachment object"
assert attachment.reference["type"] == "braintrust_attachment"
assert attachment.reference["content_type"] == "image/png"
assert attachment.reference["filename"] == "file.png"
assert "key" in attachment.reference
# Test serializing a Part with text
part_with_text = MockPart(text="Hello, world!")
serialized_text_part = _serialize_part(part_with_text)
assert serialized_text_part == {"text": "Hello, world!"}, "Text part should serialize correctly"
# Test serializing Content with multiple parts
class MockContent:
def __init__(self, parts, role):
self.parts = parts
self.role = role
content = MockContent(
parts=[
MockPart(inline_data=MockBlob(minimal_png, "image/png")),
MockPart(text="What's in this image?"),
],
role="user",
)
serialized_content = _serialize_content(content)
assert "parts" in serialized_content
assert "role" in serialized_content
assert serialized_content["role"] == "user"
assert len(serialized_content["parts"]) == 2
# First part should be the image as Attachment
assert "image_url" in serialized_content["parts"][0]
assert isinstance(serialized_content["parts"][0]["image_url"]["url"], Attachment)
# Second part should be text
assert serialized_content["parts"][1] == {"text": "What's in this image?"}
def test_serialize_part_with_file_data():
"""Test that _serialize_part handles file_data (file references) correctly."""
from braintrust.integrations.adk.tracing import _serialize_part
class MockFileData:
def __init__(self, file_uri, mime_type):
self.file_uri = file_uri
self.mime_type = mime_type
class MockPart:
def __init__(self, file_data=None, text=None):
self.file_data = file_data
self.text = text
# Test serializing a Part with file_data
part_with_file = MockPart(file_data=MockFileData("gs://bucket/file.pdf", "application/pdf"))
serialized_part = _serialize_part(part_with_file)
assert "file_data" in serialized_part
assert serialized_part["file_data"]["file_uri"] == "gs://bucket/file.pdf"
assert serialized_part["file_data"]["mime_type"] == "application/pdf"
def test_serialize_part_with_dict():
"""Test that _serialize_part handles dict input correctly."""
from braintrust.integrations.adk.tracing import _serialize_part
# Test that dicts pass through unchanged
dict_part = {"text": "Hello", "custom": "field"}
serialized = _serialize_part(dict_part)
assert serialized == dict_part, "Dict should pass through unchanged"
def test_serialize_content_with_none():
"""Test that _serialize_content handles None correctly."""
from braintrust.integrations.adk.tracing import _serialize_content
result = _serialize_content(None)
assert result is None, "None should serialize to None"
@pytest.mark.vcr
@pytest.mark.asyncio
async def test_adk_binary_data_attachment_conversion(memory_logger):
"""Test that binary data in messages is converted to Attachment references."""
assert not memory_logger.pop()
agent = Agent(
name="vision_agent",
model="gemini-2.0-flash",
instruction="You are a helpful assistant that can analyze images.",
generate_content_config=types.GenerateContentConfig(
max_output_tokens=150,
),
)
APP_NAME = "vision_app"
USER_ID = "test-user"
SESSION_ID = "test-session-image"
session_service = InMemorySessionService()
await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
runner = Runner(agent=agent, app_name=APP_NAME, session_service=session_service)
# Load test image from fixtures
fixtures_dir = Path(__file__).parent.parent.parent.parent.parent.parent / "internal" / "golden" / "fixtures"
image_path = fixtures_dir / "test-image.png"
with open(image_path, "rb") as f:
image_data = f.read()
# Create message with inline binary data
user_msg = types.Content(
role="user",
parts=[
types.Part(inline_data=types.Blob(mime_type="image/png", data=image_data)),
types.Part(text="What color is this image?"),
],
)
responses = []
async for event in runner.run_async(user_id=USER_ID, session_id=SESSION_ID, new_message=user_msg):
if event.is_final_response():
responses.append(event)
assert len(responses) > 0
spans = memory_logger.pop()
# Find the invocation span
invocation_spans = [row for row in spans if row["span_attributes"]["name"] == "invocation [vision_app]"]
assert len(invocation_spans) > 0, "Missing invocation span"
invocation_span = invocation_spans[0]
# Verify the input contains properly serialized content
assert "input" in invocation_span, "Missing input in invocation span"
assert "new_message" in invocation_span["input"], "Missing new_message in input"
new_message = invocation_span["input"]["new_message"]
assert "parts" in new_message, "Missing parts in new_message"
assert len(new_message["parts"]) == 2, "Should have 2 parts (image and text)"
# First part should be the image as an Attachment reference
image_part = new_message["parts"][0]
assert "image_url" in image_part, "Image part should have image_url field"
assert "url" in image_part["image_url"], "image_url should have url field"
attachment_ref = image_part["image_url"]["url"]
# Verify it's an Attachment object, not raw binary data
assert isinstance(attachment_ref, Attachment), "Attachment should be an Attachment object"
ref = attachment_ref.reference
assert "key" in ref, "Attachment reference should have a key"
assert "filename" in ref, "Attachment reference should have a filename"
assert "content_type" in ref, "Attachment reference should have a content_type"
assert ref["content_type"] == "image/png", "Content type should be image/png"
assert ref["filename"] == "file.png", "Filename should be file.png"
# Second part should be the text
text_part = new_message["parts"][1]
assert "text" in text_part, "Second part should have text"
assert text_part["text"] == "What color is this image?", "Text content should match"
# Verify no raw binary data is present in the logged span
span_str = str(invocation_span)
# Check that the binary PNG signature is NOT in the logged data
assert b"\x89PNG".hex() not in span_str, "Raw binary data should not be in logged span"
assert "89504e47" not in span_str.lower(), "Raw binary data (hex) should not be in logged span"
# Find LLM spans and verify they also don't contain raw binary
llm_spans = [row for row in spans if row["span_attributes"]["type"] == "llm"]
assert len(llm_spans) > 0, "Should have LLM spans"
for llm_span in llm_spans:
if "input" in llm_span and "contents" in llm_span["input"]:
llm_str = str(llm_span["input"])
assert b"\x89PNG".hex() not in llm_str, "Raw binary data should not be in LLM span input"
assert "89504e47" not in llm_str.lower(), "Raw binary data (hex) should not be in LLM span input"
@pytest.mark.vcr
@pytest.mark.asyncio
async def test_adk_captures_metrics(memory_logger):
"""Test that token usage metrics are captured from LLM responses."""
assert not memory_logger.pop()
agent = Agent(
name="metrics_agent",
model="gemini-2.0-flash",
instruction="You are a helpful assistant.",
)
APP_NAME = "metrics_app"
USER_ID = "test-user"
SESSION_ID = "test-session-metrics"
session_service = InMemorySessionService()
await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
runner = Runner(agent=agent, app_name=APP_NAME, session_service=session_service)
user_msg = types.Content(role="user", parts=[types.Part(text="Say hello in 3 words")])
responses = []
async for event in runner.run_async(user_id=USER_ID, session_id=SESSION_ID, new_message=user_msg):
if event.is_final_response():
responses.append(event)
assert len(responses) > 0
spans = memory_logger.pop()
# Find LLM spans
llm_spans = [row for row in spans if row["span_attributes"].get("type") == "llm"]
assert len(llm_spans) > 0, "Should have LLM spans"
# Verify metrics are present in at least one LLM span
llm_span_with_metrics = None
for llm_span in llm_spans:
if "metrics" in llm_span and llm_span["metrics"]:
llm_span_with_metrics = llm_span
break
assert llm_span_with_metrics is not None, "At least one LLM span should have metrics"
metrics = llm_span_with_metrics["metrics"]
# Verify core token metrics are present
assert "prompt_tokens" in metrics, "Metrics should include prompt_tokens"
assert "completion_tokens" in metrics, "Metrics should include completion_tokens"
assert "tokens" in metrics, "Metrics should include total tokens"
# Verify token counts are reasonable
assert metrics["prompt_tokens"] > 0, "prompt_tokens should be greater than 0"
assert metrics["completion_tokens"] > 0, "completion_tokens should be greater than 0"
assert metrics["tokens"] > 0, "total tokens should be greater than 0"
assert metrics["tokens"] == metrics["prompt_tokens"] + metrics["completion_tokens"], (
"total tokens should equal prompt + completion tokens"
)
# Verify time to first token is captured for streaming responses
assert "time_to_first_token" in metrics, "Metrics should include time_to_first_token"
assert metrics["time_to_first_token"] > 0, "time_to_first_token should be greater than 0"
assert metrics["time_to_first_token"] < 10, "time_to_first_token should be reasonable (< 10 seconds)"
# Verify model name is captured in metadata
metadata = llm_span_with_metrics.get("metadata", {})
assert "model" in metadata, "Metadata should include model name"
assert metadata["model"] == "gemini-2.0-flash", "Model name should match the agent's model"
def test_determine_llm_call_type_direct_response():
"""Test that _determine_llm_call_type returns 'direct_response' when tools are available but not used."""
from braintrust.integrations.adk.tracing import _determine_llm_call_type
# Request with tools available
llm_request = {
"config": {
"tools": [
{
"function_declarations": [
{"name": "read_file", "description": "Read a file"},
{"name": "list_directory", "description": "List directory"},
]
}
]
},
"contents": [{"parts": [{"text": "What is 2+2?"}], "role": "user"}],
}
# Response without function calls
model_response = {
"content": {"parts": [{"text": "4\n"}], "role": "model"},
"finish_reason": "STOP",
}
call_type = _determine_llm_call_type(llm_request, model_response)
assert call_type == "direct_response", "Should be direct_response when tools available but not used"
def test_determine_llm_call_type_tool_selection():
"""Test that _determine_llm_call_type returns 'tool_selection' when LLM calls a tool."""
from braintrust.integrations.adk.tracing import _determine_llm_call_type
# Request with tools available
llm_request = {
"config": {
"tools": [
{
"function_declarations": [
{"name": "get_weather", "description": "Get weather"},
]
}
]
},
"contents": [{"parts": [{"text": "What's the weather?"}], "role": "user"}],
}
# Response with function call (camelCase)
model_response = {
"content": {
"parts": [{"functionCall": {"name": "get_weather", "args": {"location": "SF"}}}],
"role": "model",
},
}
call_type = _determine_llm_call_type(llm_request, model_response)
assert call_type == "tool_selection", "Should be tool_selection when LLM calls a tool"
def test_determine_llm_call_type_tool_selection_snake_case():
"""Test that _determine_llm_call_type handles snake_case function_call."""
from braintrust.integrations.adk.tracing import _determine_llm_call_type
llm_request = {
"config": {"tools": [{"function_declarations": [{"name": "search"}]}]},
"contents": [{"parts": [{"text": "Search for pizza"}], "role": "user"}],
}
# Response with function call (snake_case)
model_response = {
"content": {
"parts": [{"function_call": {"name": "search", "args": {"query": "pizza"}}}],
"role": "model",
},
}
call_type = _determine_llm_call_type(llm_request, model_response)
assert call_type == "tool_selection", "Should be tool_selection for snake_case function_call"
def test_determine_llm_call_type_response_generation():
"""Test that _determine_llm_call_type returns 'response_generation' after tool execution."""
from braintrust.integrations.adk.tracing import _determine_llm_call_type
# Request with function_response in history
llm_request = {
"config": {"tools": [{"function_declarations": [{"name": "get_weather"}]}]},
"contents": [
{"parts": [{"text": "What's the weather?"}], "role": "user"},
{"parts": [{"functionCall": {"name": "get_weather", "args": {}}}], "role": "model"},
{
"parts": [{"function_response": {"name": "get_weather", "response": {"temp": "72F"}}}],
"role": "user",
},
],
}
# Response after tool execution
model_response = {
"content": {"parts": [{"text": "It's 72 degrees"}], "role": "model"},
}
call_type = _determine_llm_call_type(llm_request, model_response)
assert call_type == "response_generation", "Should be response_generation after tool execution"
def test_determine_llm_call_type_no_tools():
"""Test that _determine_llm_call_type returns 'direct_response' when no tools configured."""
from braintrust.integrations.adk.tracing import _determine_llm_call_type
llm_request = {
"config": {},
"contents": [{"parts": [{"text": "Hello"}], "role": "user"}],
}
model_response = {
"content": {"parts": [{"text": "Hi there"}], "role": "model"},
}
call_type = _determine_llm_call_type(llm_request, model_response)
assert call_type == "direct_response", "Should be direct_response when no tools configured"
def test_determine_llm_call_type_no_response():
"""Test that _determine_llm_call_type handles missing model_response gracefully."""
from braintrust.integrations.adk.tracing import _determine_llm_call_type
llm_request = {
"config": {"tools": [{"function_declarations": [{"name": "tool1"}]}]},
"contents": [{"parts": [{"text": "Test"}], "role": "user"}],
}
# No model_response provided
call_type = _determine_llm_call_type(llm_request, None)
assert call_type == "direct_response", "Should default to direct_response when no response available"
@pytest.mark.asyncio
async def test_llm_call_span_wraps_child_spans(memory_logger):
"""Test that llm_call span is created BEFORE yielding events, so child spans have proper parent.
This test validates the fix for the issue where mcp_tool and other child spans
were losing their parent context because the llm_call span was created AFTER
all events were yielded.
The fix ensures:
1. llm_call span is created BEFORE wrapped() is called
2. Child spans (like mcp_tool) created during execution have proper parent
3. Span is updated with correct call_type after response is received
"""
from unittest.mock import MagicMock
from braintrust import current_span, start_span
from braintrust.integrations.adk import wrap_flow
# Clear any existing logs
memory_logger.pop()
# Mock Flow class
class MockFlow: