-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathtest_foundry_evals.py
More file actions
2739 lines (2252 loc) · 106 KB
/
test_foundry_evals.py
File metadata and controls
2739 lines (2252 loc) · 106 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
# Copyright (c) Microsoft. All rights reserved.
"""Tests for the AgentEvalConverter, FoundryEvals, and eval helper functions."""
from __future__ import annotations
import json
from dataclasses import dataclass
from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
from agent_framework import AgentExecutorResponse, AgentResponse, Content, FunctionTool, Message, WorkflowEvent
from agent_framework._evaluation import (
AgentEvalConverter,
ConversationSplit,
EvalItem,
EvalNotPassedError,
EvalResults,
_extract_agent_eval_data,
_extract_overall_query,
evaluate_agent,
evaluate_workflow,
)
from agent_framework._workflows._workflow import WorkflowRunResult
from openai import AsyncOpenAI
from agent_framework_foundry._foundry_evals import (
FoundryEvals,
_build_item_schema,
_build_testing_criteria,
_extract_per_evaluator,
_extract_result_counts,
_filter_tool_evaluators,
_resolve_default_evaluators,
_resolve_evaluator,
_resolve_openai_client,
)
class _AsyncPage:
"""Async-iterable mock for OpenAI SDK pagination pages."""
def __init__(self, items: list[Any]) -> None:
self._items = items
def __aiter__(self) -> _AsyncPage:
self._iter = iter(self._items)
return self
async def __anext__(self) -> Any:
try:
return next(self._iter)
except StopIteration:
raise StopAsyncIteration from None
def _make_tool(name: str) -> MagicMock:
"""Create a mock FunctionTool for use in tests."""
t = MagicMock()
t.name = name
t.description = f"{name} tool"
t.parameters = MagicMock(return_value={"type": "object"})
return t
@dataclass
class _MockResultCounts:
"""Mock matching the OpenAI SDK ResultCounts Pydantic model shape."""
passed: int = 0
failed: int = 0
errored: int = 0
total: int = 0
def _rc(passed: int = 0, failed: int = 0, errored: int = 0) -> _MockResultCounts:
"""Shorthand to create a ResultCounts-compatible mock."""
return _MockResultCounts(passed=passed, failed=failed, errored=errored, total=passed + failed + errored)
# ---------------------------------------------------------------------------
# _resolve_evaluator
# ---------------------------------------------------------------------------
class TestResolveEvaluator:
def test_short_name(self) -> None:
assert _resolve_evaluator("relevance") == "builtin.relevance"
assert _resolve_evaluator("tool_call_accuracy") == "builtin.tool_call_accuracy"
assert _resolve_evaluator("violence") == "builtin.violence"
def test_already_qualified(self) -> None:
assert _resolve_evaluator("builtin.relevance") == "builtin.relevance"
assert _resolve_evaluator("builtin.custom") == "builtin.custom"
def test_unknown_raises(self) -> None:
with pytest.raises(ValueError, match="Unknown evaluator 'bogus'"):
_resolve_evaluator("bogus")
# ---------------------------------------------------------------------------
# AgentEvalConverter.convert_message
# ---------------------------------------------------------------------------
class TestConvertMessage:
def test_user_text_message(self) -> None:
msg = Message("user", ["Hello, world!"])
result = AgentEvalConverter.convert_message(msg)
assert len(result) == 1
assert result[0] == {"role": "user", "content": [{"type": "text", "text": "Hello, world!"}]}
def test_system_message(self) -> None:
msg = Message("system", ["You are helpful."])
result = AgentEvalConverter.convert_message(msg)
assert result[0] == {"role": "system", "content": [{"type": "text", "text": "You are helpful."}]}
def test_assistant_text_message(self) -> None:
msg = Message("assistant", ["Here is the answer."])
result = AgentEvalConverter.convert_message(msg)
assert len(result) == 1
assert result[0]["role"] == "assistant"
assert result[0]["content"] == [{"type": "text", "text": "Here is the answer."}]
assert len(result[0]["content"]) == 1
def test_assistant_with_tool_call(self) -> None:
msg = Message(
"assistant",
[
Content.from_function_call(
call_id="call_1",
name="get_weather",
arguments=json.dumps({"location": "Seattle"}),
),
],
)
result = AgentEvalConverter.convert_message(msg)
assert len(result) == 1
assert result[0]["role"] == "assistant"
tc = result[0]["content"][0]
assert tc["type"] == "tool_call"
assert tc["tool_call_id"] == "call_1"
assert tc["name"] == "get_weather"
assert tc["arguments"] == {"location": "Seattle"}
def test_assistant_text_and_tool_call(self) -> None:
msg = Message(
"assistant",
[
Content.from_text("Let me check that."),
Content.from_function_call(
call_id="call_2",
name="search",
arguments={"query": "flights"},
),
],
)
result = AgentEvalConverter.convert_message(msg)
assert len(result) == 1
assert result[0]["content"][0] == {"type": "text", "text": "Let me check that."}
tc = result[0]["content"][1]
assert tc["type"] == "tool_call"
assert tc["arguments"] == {"query": "flights"}
def test_tool_result_message(self) -> None:
msg = Message(
"tool",
[
Content.from_function_result(
call_id="call_1",
result="72°F, sunny",
),
],
)
result = AgentEvalConverter.convert_message(msg)
assert len(result) == 1
assert result[0]["role"] == "tool"
assert result[0]["tool_call_id"] == "call_1"
assert result[0]["content"] == [{"type": "tool_result", "tool_result": "72°F, sunny"}]
def test_multiple_tool_results(self) -> None:
msg = Message(
"tool",
[
Content.from_function_result(call_id="call_1", result="r1"),
Content.from_function_result(call_id="call_2", result="r2"),
],
)
result = AgentEvalConverter.convert_message(msg)
assert len(result) == 2
assert result[0]["tool_call_id"] == "call_1"
assert result[1]["tool_call_id"] == "call_2"
def test_non_string_result_kept_as_object(self) -> None:
msg = Message(
"tool",
[
Content.from_function_result(
call_id="call_1",
result={"temp": 72, "unit": "F"},
),
],
)
result = AgentEvalConverter.convert_message(msg)
tr = result[0]["content"][0]
assert tr["type"] == "tool_result"
assert tr["tool_result"] == {"temp": 72, "unit": "F"}
def test_empty_message(self) -> None:
msg = Message("user", [])
result = AgentEvalConverter.convert_message(msg)
assert result[0] == {"role": "user", "content": [{"type": "text", "text": ""}]}
def test_user_image_from_data(self) -> None:
"""Image created via Content.from_data() emits input_image."""
img = Content.from_data(data=b"\x89PNG\r\n\x1a\n", media_type="image/png")
msg = Message("user", [img])
result = AgentEvalConverter.convert_message(msg)
assert len(result) == 1
assert result[0]["role"] == "user"
part = result[0]["content"][0]
assert part["type"] == "input_image"
assert part["image_url"].startswith("data:image/png;base64,")
assert part["detail"] == "auto"
def test_user_image_from_uri(self) -> None:
"""Image created via Content.from_uri() with an external URL."""
img = Content.from_uri("https://example.com/photo.jpg", media_type="image/jpeg")
msg = Message("user", [img])
result = AgentEvalConverter.convert_message(msg)
assert len(result) == 1
part = result[0]["content"][0]
assert part["type"] == "input_image"
assert part["image_url"] == "https://example.com/photo.jpg"
assert part["detail"] == "auto"
def test_user_image_uri_without_media_type(self) -> None:
"""URI content without media_type still emits input_image (no detail key)."""
img = Content("uri", uri="https://example.com/pic.png")
msg = Message("user", [img])
result = AgentEvalConverter.convert_message(msg)
part = result[0]["content"][0]
assert part["type"] == "input_image"
assert part["image_url"] == "https://example.com/pic.png"
assert "detail" not in part
def test_mixed_text_and_image(self) -> None:
"""Message with text + image produces both content parts."""
msg = Message(
"user",
[
Content.from_text("What's in this image?"),
Content.from_uri("https://example.com/cat.jpg", media_type="image/jpeg"),
],
)
result = AgentEvalConverter.convert_message(msg)
assert len(result) == 1
assert len(result[0]["content"]) == 2
assert result[0]["content"][0] == {"type": "text", "text": "What's in this image?"}
assert result[0]["content"][1]["type"] == "input_image"
assert result[0]["content"][1]["image_url"] == "https://example.com/cat.jpg"
# ---------------------------------------------------------------------------
# AgentEvalConverter.convert_messages
# ---------------------------------------------------------------------------
class TestConvertMessages:
def test_full_conversation(self) -> None:
messages = [
Message("user", ["What's the weather?"]),
Message(
"assistant",
[Content.from_function_call(call_id="c1", name="get_weather", arguments='{"loc": "SEA"}')],
),
Message("tool", [Content.from_function_result(call_id="c1", result="Sunny")]),
Message("assistant", ["It's sunny in Seattle!"]),
]
result = AgentEvalConverter.convert_messages(messages)
assert len(result) == 4
assert result[0]["role"] == "user"
assert result[1]["role"] == "assistant"
assert result[1]["content"][0]["type"] == "tool_call"
assert result[1]["content"][0]["name"] == "get_weather"
assert result[2]["role"] == "tool"
assert result[2]["content"][0]["type"] == "tool_result"
assert result[3]["role"] == "assistant"
assert result[3]["content"] == [{"type": "text", "text": "It's sunny in Seattle!"}]
def test_multimodal_conversation_preserves_images(self) -> None:
"""Full conversation with image content flows through convert_messages."""
messages = [
Message(
"user",
[
Content.from_text("Describe this image"),
Content.from_uri("https://example.com/photo.jpg", media_type="image/jpeg"),
],
),
Message("assistant", ["This is a photo of a sunset over the ocean."]),
]
result = AgentEvalConverter.convert_messages(messages)
assert len(result) == 2
# User message has text + image
user_content = result[0]["content"]
assert len(user_content) == 2
assert user_content[0] == {"type": "text", "text": "Describe this image"}
assert user_content[1]["type"] == "input_image"
assert user_content[1]["image_url"] == "https://example.com/photo.jpg"
# Assistant response is text
assert result[1]["content"] == [{"type": "text", "text": "This is a photo of a sunset over the ocean."}]
# ---------------------------------------------------------------------------
# AgentEvalConverter.extract_tools
# ---------------------------------------------------------------------------
class TestExtractTools:
def test_extracts_function_tools(self) -> None:
tool = FunctionTool(
name="get_weather",
description="Get weather for a location",
func=lambda location: f"Sunny in {location}",
)
agent = MagicMock()
agent.default_options = {"tools": [tool]}
result = AgentEvalConverter.extract_tools(agent)
assert len(result) == 1
assert result[0]["name"] == "get_weather"
assert result[0]["description"] == "Get weather for a location"
assert "parameters" in result[0]
def test_skips_non_function_tools(self) -> None:
agent = MagicMock()
agent.default_options = {"tools": [{"type": "web_search"}, "some_string"]}
result = AgentEvalConverter.extract_tools(agent)
assert len(result) == 0
def test_no_tools(self) -> None:
agent = MagicMock()
agent.default_options = {}
assert AgentEvalConverter.extract_tools(agent) == []
def test_no_default_options(self) -> None:
agent = MagicMock(spec=[]) # No attributes
assert AgentEvalConverter.extract_tools(agent) == []
# ---------------------------------------------------------------------------
# AgentEvalConverter.to_eval_item (now returns EvalItem)
# ---------------------------------------------------------------------------
class TestToEvalItem:
def test_string_query(self) -> None:
response = AgentResponse(messages=[Message("assistant", ["The weather is sunny."])])
item = AgentEvalConverter.to_eval_item(query="What's the weather?", response=response)
assert isinstance(item, EvalItem)
assert item.query == "What's the weather?"
assert item.response == "The weather is sunny."
assert len(item.conversation) == 2
assert item.conversation[0].role == "user"
assert item.conversation[1].role == "assistant"
def test_message_query(self) -> None:
input_msgs = [
Message("system", ["Be helpful."]),
Message("user", ["Hello"]),
]
response = AgentResponse(messages=[Message("assistant", ["Hi there!"])])
item = AgentEvalConverter.to_eval_item(query=input_msgs, response=response)
assert item.query == "Hello" # Only user messages
assert len(item.conversation) == 3 # system + user + assistant
def test_with_context(self) -> None:
response = AgentResponse(messages=[Message("assistant", ["Answer."])])
item = AgentEvalConverter.to_eval_item(
query="Question?",
response=response,
context="Some reference document.",
)
assert item.context == "Some reference document."
def test_with_explicit_tools(self) -> None:
tool = FunctionTool(
name="search",
description="Search the web",
func=lambda q: f"Results for {q}",
)
response = AgentResponse(messages=[Message("assistant", ["Found it."])])
item = AgentEvalConverter.to_eval_item(
query="Find info",
response=response,
tools=[tool],
)
assert item.tools is not None
assert len(item.tools) == 1
assert item.tools[0].name == "search"
def test_with_agent_tools(self) -> None:
tool = FunctionTool(name="calc", description="Calculate", func=lambda x: str(x))
agent = MagicMock()
agent.default_options = {"tools": [tool]}
response = AgentResponse(messages=[Message("assistant", ["42"])])
item = AgentEvalConverter.to_eval_item(
query="What is 6*7?",
response=response,
agent=agent,
)
assert item.tools is not None
assert item.tools[0].name == "calc"
def test_explicit_tools_override_agent(self) -> None:
agent_tool = FunctionTool(name="agent_tool", description="from agent", func=lambda: "")
explicit_tool = FunctionTool(name="explicit_tool", description="explicit", func=lambda: "")
agent = MagicMock()
agent.default_options = {"tools": [agent_tool]}
response = AgentResponse(messages=[Message("assistant", ["Done"])])
item = AgentEvalConverter.to_eval_item(
query="Test",
response=response,
agent=agent,
tools=[explicit_tool],
)
assert item.tools is not None
assert len(item.tools) == 1
assert item.tools[0].name == "explicit_tool"
def test_split_messages_format(self) -> None:
"""split_messages() should split conversation at last user message."""
response = AgentResponse(messages=[Message("assistant", ["Answer"])])
item = AgentEvalConverter.to_eval_item(
query="Q",
response=response,
tools=[FunctionTool(name="t", description="d", func=lambda: "")],
)
query_msgs, response_msgs = item.split_messages()
# Single-turn: query has just the user msg, response has the assistant msg
assert len(query_msgs) == 1
assert query_msgs[0].role == "user"
assert len(response_msgs) == 1
assert response_msgs[0].role == "assistant"
# Tools preserved on item
assert item.tools is not None
assert len(item.tools) == 1
assert item.tools[0].name == "t"
def test_split_messages_multiturn_preserves_interleaving(self) -> None:
"""Multi-turn split_messages() splits at last user message, preserving interleaving."""
conversation = [
Message("user", ["What's the weather?"]),
Message("assistant", ["It's sunny in Seattle."]),
Message("user", ["And tomorrow?"]),
Message("assistant", [Content(type="function_call", name="get_forecast")]),
Message("tool", [Content(type="function_result", result="Rain expected")]),
Message("assistant", ["Rain is expected tomorrow."]),
]
item = EvalItem(conversation=conversation)
query_msgs, response_msgs = item.split_messages()
# query_messages: everything up to and including the last user message
assert len(query_msgs) == 3 # user, assistant, user
assert query_msgs[0].role == "user"
assert query_msgs[1].role == "assistant" # interleaved!
assert query_msgs[2].role == "user"
# response_messages: everything after the last user message
assert len(response_msgs) == 3 # assistant(tool_call), tool, assistant
assert response_msgs[0].role == "assistant"
assert response_msgs[1].role == "tool"
assert response_msgs[2].role == "assistant"
def test_split_messages_full_split(self) -> None:
"""ConversationSplit.FULL splits after the first user message."""
conversation = [
Message("user", ["What's the weather?"]),
Message("assistant", ["It's 62°F in Seattle."]),
Message("user", ["And tomorrow?"]),
Message("assistant", ["Rain is expected tomorrow."]),
]
item = EvalItem(conversation=conversation)
query_msgs, response_msgs = item.split_messages(split=ConversationSplit.FULL)
# query_messages: just the first user message
assert len(query_msgs) == 1
assert query_msgs[0].role == "user"
assert query_msgs[0].text == "What's the weather?"
# response_messages: everything after the first user message
assert len(response_msgs) == 3
assert response_msgs[0].role == "assistant"
assert response_msgs[1].role == "user"
assert response_msgs[2].role == "assistant"
def test_split_messages_full_split_with_system(self) -> None:
"""FULL split includes system messages before the first user message in query."""
conversation = [
Message("system", ["You are a weather assistant."]),
Message("user", ["What's the weather?"]),
Message("assistant", ["It's sunny."]),
]
item = EvalItem(conversation=conversation)
query_msgs, response_msgs = item.split_messages(split=ConversationSplit.FULL)
# query includes system + first user
assert len(query_msgs) == 2
assert query_msgs[0].role == "system"
assert query_msgs[1].role == "user"
assert len(response_msgs) == 1
def test_split_messages_full_split_with_tools(self) -> None:
"""FULL split puts all tool interactions in response_messages."""
conversation = [
Message("user", ["What's the weather?"]),
Message("assistant", [Content(type="function_call", name="get_weather")]),
Message("tool", [Content(type="function_result", result="62°F")]),
Message("assistant", ["It's 62°F."]),
Message("user", ["Thanks!"]),
Message("assistant", ["You're welcome!"]),
]
item = EvalItem(conversation=conversation)
query_msgs, response_msgs = item.split_messages(split=ConversationSplit.FULL)
assert len(query_msgs) == 1
assert len(response_msgs) == 5
def test_split_messages_last_turn_is_default(self) -> None:
"""Default split_messages() uses LAST_TURN split."""
conversation = [
Message("user", ["Hello"]),
Message("assistant", ["Hi there"]),
Message("user", ["Bye"]),
Message("assistant", ["Goodbye"]),
]
item = EvalItem(conversation=conversation)
q_default, r_default = item.split_messages()
q_explicit, r_explicit = item.split_messages(split=ConversationSplit.LAST_TURN)
assert [m.role for m in q_default] == [m.role for m in q_explicit]
assert [m.text for m in q_default] == [m.text for m in q_explicit]
assert [m.role for m in r_default] == [m.role for m in r_explicit]
assert [m.text for m in r_default] == [m.text for m in r_explicit]
def test_per_turn_items_simple(self) -> None:
"""per_turn_items produces one EvalItem per user message."""
conversation = [
Message("user", ["What's the weather?"]),
Message("assistant", ["It's 62°F."]),
Message("user", ["And tomorrow?"]),
Message("assistant", ["Rain expected."]),
]
items = EvalItem.per_turn_items(conversation)
assert len(items) == 2
# Turn 1
assert items[0].query == "What's the weather?"
assert items[0].response == "It's 62°F."
assert len(items[0].conversation) == 2
# Turn 2 — includes cumulative context; query joins all user texts in query split
assert items[1].query == "What's the weather? And tomorrow?"
assert items[1].response == "Rain expected."
assert len(items[1].conversation) == 4
def test_per_turn_items_with_tools(self) -> None:
"""per_turn_items handles tool calls within a turn."""
conversation = [
Message("user", ["Check weather"]),
Message("assistant", [Content(type="function_call", name="get_weather")]),
Message("tool", [Content(type="function_result", result="sunny")]),
Message("assistant", ["It's sunny."]),
Message("user", ["Thanks"]),
Message("assistant", ["You're welcome!"]),
]
tool_objs = [_make_tool("get_weather")]
items = EvalItem.per_turn_items(conversation, tools=tool_objs)
assert len(items) == 2
# Turn 1: response includes tool_call, tool_result, and final assistant
assert items[0].response == "It's sunny."
assert items[0].tools == tool_objs
assert len(items[0].conversation) == 4 # user, assistant(tool), tool, assistant
# Turn 2
assert items[1].response == "You're welcome!"
assert len(items[1].conversation) == 6 # full conversation
def test_per_turn_items_empty(self) -> None:
"""per_turn_items returns empty list when no user messages."""
items = EvalItem.per_turn_items([Message("assistant", ["Hello"])])
assert items == []
def test_per_turn_items_single_turn(self) -> None:
"""per_turn_items with single turn produces one item."""
conversation = [
Message("user", ["Hi"]),
Message("assistant", ["Hello!"]),
]
items = EvalItem.per_turn_items(conversation)
assert len(items) == 1
assert items[0].query == "Hi"
assert items[0].response == "Hello!"
def test_custom_splitter_callable(self) -> None:
"""Custom callable splitter is used by split_messages()."""
conversation = [
Message("user", ["Remember my name is Alice"]),
Message("assistant", ["Got it, Alice!"]),
Message("user", ["What's the capital of France?"]),
Message("assistant", [Content(type="function_call", name="retrieve_memory", call_id="m1")]),
Message("tool", [Content(type="function_result", call_id="m1", result="User name: Alice")]),
Message("assistant", ["The capital of France is Paris, Alice!"]),
]
def split_before_memory(conv):
"""Split just before the memory retrieval tool call."""
for i, msg in enumerate(conv):
for c in msg.contents:
if c.name == "retrieve_memory":
return conv[:i], conv[i:]
return EvalItem._split_last_turn_static(conv)
item = EvalItem(conversation=conversation)
query_msgs, response_msgs = item.split_messages(split=split_before_memory)
# split_before_memory finds "retrieve_memory" at conv[3] (assistant tool_call msg)
# query = conv[:3] = [user, assistant, user]
# response = conv[3:] = [assistant(tool_call), tool, assistant]
assert len(query_msgs) == 3
assert query_msgs[-1].role == "user"
assert len(response_msgs) == 3
assert response_msgs[0].role == "assistant" # the tool_call msg
def test_custom_splitter_with_fallback(self) -> None:
"""Custom splitter falls back to _split_last_turn_static when pattern not found."""
conversation = [
Message("user", ["Hello"]),
Message("assistant", ["Hi there!"]),
]
def split_before_memory(conv):
for i, msg in enumerate(conv):
for c in msg.contents:
if c.name == "retrieve_memory":
return conv[:i], conv[i:]
return EvalItem._split_last_turn_static(conv)
item = EvalItem(conversation=conversation)
query_msgs, response_msgs = item.split_messages(split=split_before_memory)
# Falls back to last-turn split
assert len(query_msgs) == 1
assert query_msgs[0].role == "user"
assert len(response_msgs) == 1
assert response_msgs[0].role == "assistant"
def test_custom_splitter_lambda(self) -> None:
"""A lambda works as a custom splitter."""
conversation = [
Message("user", ["A"]),
Message("assistant", ["B"]),
Message("user", ["C"]),
Message("assistant", ["D"]),
]
# Split at index 2 (arbitrary)
item = EvalItem(conversation=conversation)
query_msgs, response_msgs = item.split_messages(split=lambda conv: (conv[:2], conv[2:]))
assert len(query_msgs) == 2
assert len(response_msgs) == 2
def test_split_strategy_on_item_used_by_split_messages(self) -> None:
"""split_strategy field on EvalItem is used as default by split_messages()."""
conversation = [
Message("user", ["First"]),
Message("assistant", ["Response 1"]),
Message("user", ["Second"]),
Message("assistant", ["Response 2"]),
]
item = EvalItem(
conversation=conversation,
split_strategy=ConversationSplit.FULL,
)
# split_messages() with no split arg should use item.split_strategy
query_msgs, response_msgs = item.split_messages()
assert len(query_msgs) == 1 # FULL: just first user msg
assert query_msgs[0].text == "First"
assert len(response_msgs) == 3
def test_explicit_split_overrides_item_split_strategy(self) -> None:
"""Explicit split= arg to split_messages() overrides item.split_strategy."""
conversation = [
Message("user", ["First"]),
Message("assistant", ["Response 1"]),
Message("user", ["Second"]),
Message("assistant", ["Response 2"]),
]
item = EvalItem(
conversation=conversation,
split_strategy=ConversationSplit.FULL,
)
# Explicit split= should override split_strategy
query_msgs, response_msgs = item.split_messages(split=ConversationSplit.LAST_TURN)
assert len(query_msgs) == 3 # LAST_TURN: up to last user
assert query_msgs[-1].text == "Second"
assert len(response_msgs) == 1
def test_no_split_defaults_to_last_turn(self) -> None:
"""When neither split= nor split_strategy is set, defaults to LAST_TURN."""
conversation = [
Message("user", ["Hello"]),
Message("assistant", ["Hi"]),
]
item = EvalItem(conversation=conversation)
assert item.split_strategy is None
query_msgs, response_msgs = item.split_messages()
assert len(query_msgs) == 1
assert query_msgs[0].role == "user"
# ---------------------------------------------------------------------------
# _build_testing_criteria
# ---------------------------------------------------------------------------
class TestBuildTestingCriteria:
def test_without_data_mapping(self) -> None:
criteria = _build_testing_criteria(["relevance", "coherence"], "gpt-4o")
assert len(criteria) == 2
assert criteria[0]["evaluator_name"] == "builtin.relevance"
assert criteria[0]["initialization_parameters"] == {"deployment_name": "gpt-4o"}
assert "data_mapping" not in criteria[0]
def test_with_data_mapping(self) -> None:
criteria = _build_testing_criteria(["relevance", "groundedness"], "gpt-4o", include_data_mapping=True)
assert "data_mapping" in criteria[0]
# Quality evaluators should NOT have conversation
assert criteria[0]["data_mapping"] == {
"query": "{{item.query}}",
"response": "{{item.response}}",
}
# Groundedness has an extra context mapping
assert "context" in criteria[1]["data_mapping"]
assert "conversation" not in criteria[1]["data_mapping"]
def test_tool_evaluator_includes_tool_definitions(self) -> None:
criteria = _build_testing_criteria(["relevance", "tool_call_accuracy"], "gpt-4o", include_data_mapping=True)
# relevance: string query/response
assert criteria[0]["data_mapping"]["query"] == "{{item.query}}"
assert criteria[0]["data_mapping"]["response"] == "{{item.response}}"
assert "tool_definitions" not in criteria[0]["data_mapping"]
# tool_call_accuracy: array query/response + tool_definitions
assert criteria[1]["data_mapping"]["query"] == "{{item.query_messages}}"
assert criteria[1]["data_mapping"]["response"] == "{{item.response_messages}}"
assert criteria[1]["data_mapping"]["tool_definitions"] == "{{item.tool_definitions}}"
def test_agent_evaluators_use_message_arrays(self) -> None:
agent_evals = ["task_adherence", "intent_resolution", "task_completion"]
criteria = _build_testing_criteria(agent_evals, "gpt-4o", include_data_mapping=True)
for c in criteria:
assert c["data_mapping"]["query"] == "{{item.query_messages}}", f"{c['name']}"
assert c["data_mapping"]["response"] == "{{item.response_messages}}", f"{c['name']}"
def test_quality_evaluators_use_strings(self) -> None:
quality_evals = ["coherence", "relevance", "fluency"]
criteria = _build_testing_criteria(quality_evals, "gpt-4o", include_data_mapping=True)
for c in criteria:
assert c["data_mapping"]["query"] == "{{item.query}}", f"{c['name']}"
assert c["data_mapping"]["response"] == "{{item.response}}", f"{c['name']}"
def test_similarity_includes_ground_truth(self) -> None:
criteria = _build_testing_criteria(["similarity"], "gpt-4o", include_data_mapping=True)
assert criteria[0]["data_mapping"]["ground_truth"] == "{{item.ground_truth}}"
def test_all_tool_evaluators_include_tool_definitions(self) -> None:
tool_evals = [
"tool_call_accuracy",
"tool_selection",
"tool_input_accuracy",
"tool_output_utilization",
"tool_call_success",
]
criteria = _build_testing_criteria(tool_evals, "gpt-4o", include_data_mapping=True)
for c in criteria:
assert "tool_definitions" in c["data_mapping"], f"{c['name']} missing tool_definitions"
# ---------------------------------------------------------------------------
# _build_item_schema
# ---------------------------------------------------------------------------
class TestBuildItemSchema:
def test_without_context(self) -> None:
schema = _build_item_schema(has_context=False)
assert "context" not in schema["properties"]
assert schema["required"] == ["query", "response"]
def test_with_context(self) -> None:
schema = _build_item_schema(has_context=True)
assert "context" in schema["properties"]
def test_with_tools(self) -> None:
schema = _build_item_schema(has_tools=True)
assert "tool_definitions" in schema["properties"]
def test_with_ground_truth(self) -> None:
schema = _build_item_schema(has_ground_truth=True)
assert "ground_truth" in schema["properties"]
def test_with_context_and_tools(self) -> None:
schema = _build_item_schema(has_context=True, has_tools=True)
assert "context" in schema["properties"]
assert "tool_definitions" in schema["properties"]
# ---------------------------------------------------------------------------
# FoundryEvals (constructor, name, select, evaluate via dataset)
# ---------------------------------------------------------------------------
class TestFoundryEvals:
def test_constructor_with_openai_client(self) -> None:
mock_client = MagicMock()
fe = FoundryEvals(client=mock_client, model="gpt-4o")
assert fe.name == "Microsoft Foundry"
def test_constructor_with_project_client(self) -> None:
mock_oai = MagicMock(spec=AsyncOpenAI)
mock_project = MagicMock()
mock_project.get_openai_client.return_value = mock_oai
fe = FoundryEvals(project_client=mock_project, model="gpt-4o")
assert fe.name == "Microsoft Foundry"
mock_project.get_openai_client.assert_called_once()
def test_constructor_no_client_auto_creates_from_env(self) -> None:
"""When no client/project_client given, auto-creates FoundryChatClient from env."""
import os
from unittest.mock import patch
with patch.dict(os.environ, {}, clear=True), pytest.raises((ValueError, Exception)):
FoundryEvals(model="gpt-4o")
def test_name_property(self) -> None:
fe = FoundryEvals(client=MagicMock(), model="gpt-4o")
assert fe.name == "Microsoft Foundry"
def test_evaluators_passed_in_constructor(self) -> None:
fe = FoundryEvals(
client=MagicMock(),
model="gpt-4o",
evaluators=["relevance", "coherence"],
)
assert fe._evaluators == ["relevance", "coherence"]
async def test_evaluate_calls_evals_api(self) -> None:
mock_client = MagicMock()
mock_eval = MagicMock()
mock_eval.id = "eval_123"
mock_client.evals.create = AsyncMock(return_value=mock_eval)
mock_run = MagicMock()
mock_run.id = "run_456"
mock_client.evals.runs.create = AsyncMock(return_value=mock_run)
mock_completed = MagicMock()
mock_completed.status = "completed"
mock_completed.result_counts = _rc(passed=2)
mock_completed.report_url = "https://portal.azure.com/eval/run_456"
mock_completed.per_testing_criteria_results = None
mock_client.evals.runs.retrieve = AsyncMock(return_value=mock_completed)
# Mock output_items.list so _fetch_output_items exercises the full flow
mock_output_item = MagicMock()
mock_output_item.id = "output_item_1"
mock_output_item.status = "pass"
mock_output_item.sample = MagicMock(error=None, usage=None, input=[], output=[])
mock_result = MagicMock(status="pass", score=5, reason="Relevant response")
mock_result.name = "relevance" # MagicMock(name=...) sets display name, not .name attr
mock_output_item.results = [mock_result]
mock_client.evals.runs.output_items.list = AsyncMock(return_value=_AsyncPage([mock_output_item]))
items = [
EvalItem(conversation=[Message("user", ["Hello"]), Message("assistant", ["Hi there!"])]),
EvalItem(conversation=[Message("user", ["Weather?"]), Message("assistant", ["Sunny."])]),
]
fe = FoundryEvals(
client=mock_client,
model="gpt-4o",
evaluators=[FoundryEvals.RELEVANCE],
)
results = await fe.evaluate(items)
assert isinstance(results, EvalResults)
assert results.status == "completed"
assert results.eval_id == "eval_123"
assert results.run_id == "run_456"
assert results.report_url == "https://portal.azure.com/eval/run_456"
assert results.all_passed
assert results.passed == 2
assert results.failed == 0
# Verify per-item output_items were fetched
assert len(results.items) == 1
assert results.items[0].item_id == "output_item_1"
assert results.items[0].status == "pass"
assert len(results.items[0].scores) == 1
assert results.items[0].scores[0].name == "relevance"
assert results.items[0].scores[0].score == 5
# Verify evals.create was called with correct structure
create_call = mock_client.evals.create.call_args
assert create_call.kwargs["name"] == "Agent Framework Eval"
assert create_call.kwargs["data_source_config"]["type"] == "custom"
# Verify evals.runs.create was called with JSONL data source
run_call = mock_client.evals.runs.create.call_args
assert run_call.kwargs["data_source"]["type"] == "jsonl"
content = run_call.kwargs["data_source"]["source"]["content"]
assert len(content) == 2
async def test_evaluate_uses_default_evaluators(self) -> None:
mock_client = MagicMock()
mock_eval = MagicMock()
mock_eval.id = "eval_1"
mock_client.evals.create = AsyncMock(return_value=mock_eval)
mock_run = MagicMock()
mock_run.id = "run_1"
mock_client.evals.runs.create = AsyncMock(return_value=mock_run)
mock_completed = MagicMock()
mock_completed.status = "completed"
mock_completed.result_counts = _rc(passed=1)
mock_completed.report_url = None
mock_completed.per_testing_criteria_results = None
mock_client.evals.runs.retrieve = AsyncMock(return_value=mock_completed)
fe = FoundryEvals(client=mock_client, model="gpt-4o")
await fe.evaluate([EvalItem(conversation=[Message("user", ["Hi"]), Message("assistant", ["Hello"])])])
# Verify default evaluators were used
create_call = mock_client.evals.create.call_args
criteria = create_call.kwargs["testing_criteria"]
names = {c["name"] for c in criteria}
assert "relevance" in names
assert "coherence" in names
assert "task_adherence" in names
async def test_evaluate_uses_dataset_path(self) -> None:
"""Items use the JSONL dataset path."""
mock_client = MagicMock()
mock_eval = MagicMock()
mock_eval.id = "eval_ds"
mock_client.evals.create = AsyncMock(return_value=mock_eval)
mock_run = MagicMock()
mock_run.id = "run_ds"
mock_client.evals.runs.create = AsyncMock(return_value=mock_run)
mock_completed = MagicMock()
mock_completed.status = "completed"
mock_completed.result_counts = _rc(passed=1)
mock_completed.report_url = None
mock_completed.per_testing_criteria_results = None
mock_client.evals.runs.retrieve = AsyncMock(return_value=mock_completed)
items = [
EvalItem(
conversation=[Message("user", ["What's the weather?"]), Message("assistant", ["Sunny"])],
),
]
fe = FoundryEvals(client=mock_client, model="gpt-4o")
await fe.evaluate(items)
run_call = mock_client.evals.runs.create.call_args
ds = run_call.kwargs["data_source"]
assert ds["type"] == "jsonl"
content = ds["source"]["content"]
assert content[0]["item"]["query"] == "What's the weather?"
async def test_evaluate_with_tool_items_uses_dataset_path(self) -> None:
"""Items with tool_definitions use the dataset path."""
mock_client = MagicMock()
mock_eval = MagicMock()
mock_eval.id = "eval_tool"
mock_client.evals.create = AsyncMock(return_value=mock_eval)
mock_run = MagicMock()
mock_run.id = "run_tool"
mock_client.evals.runs.create = AsyncMock(return_value=mock_run)
mock_completed = MagicMock()