-
Notifications
You must be signed in to change notification settings - Fork 747
Expand file tree
/
Copy pathtest_scorer.py
More file actions
1479 lines (1158 loc) · 53.5 KB
/
test_scorer.py
File metadata and controls
1479 lines (1158 loc) · 53.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import asyncio
from textwrap import dedent
from typing import Optional
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from unit.mocks import get_mock_target_identifier
from pyrit.exceptions import InvalidJsonException, remove_markdown_json
from pyrit.identifiers import ComponentIdentifier
from pyrit.memory import CentralMemory
from pyrit.models import Message, MessagePiece, Score
from pyrit.prompt_target import PromptChatTarget
from pyrit.score import (
Scorer,
ScorerPromptValidator,
TrueFalseScorer,
)
@pytest.fixture
def good_json():
return '{"score_value": "1", "rationale": "Valid response"}'
# Add missing BAD_JSON, KEY_ERROR_JSON, KEY_ERROR2_JSON definitions for test parametrize
BAD_JSON = "this is not json"
KEY_ERROR_JSON = (
dedent(
"""
{"poor_value": "1",
"rationale": "The message does not contain any code or instructions that could be used to cause harm"}
"""
)
.strip()
.replace("\n", " ")
)
KEY_ERROR2_JSON = (
dedent(
"""
{"score_value": "1",
"bad_rationale": "The message does not contain any code or instructions that could be used to cause harm"}
"""
)
.strip()
.replace("\n", " ")
)
class DummyValidator(ScorerPromptValidator):
def validate(self, message, objective=None):
pass
def is_message_piece_supported(self, message_piece):
return True
class MockScorer(TrueFalseScorer):
def __init__(self):
super().__init__(validator=DummyValidator())
def _build_identifier(self) -> ComponentIdentifier:
"""Build the scorer evaluation identifier for this mock scorer."""
return self._create_identifier()
async def _score_async(self, message: Message, *, objective: Optional[str] = None) -> list[Score]:
return [
Score(
score_value="true",
score_value_description="desc",
score_type="true_false",
score_category=None,
score_metadata=None,
score_rationale="rationale",
scorer_class_identifier=self.get_identifier(),
message_piece_id="mock_id",
objective=objective,
)
]
async def _score_piece_async(self, message_piece: MessagePiece, *, objective: Optional[str] = None) -> list[Score]:
return [
Score(
score_value="true",
score_value_description="desc",
score_type="true_false",
score_category=None,
score_metadata=None,
score_rationale="rationale",
scorer_class_identifier=self.get_identifier(),
message_piece_id="mock_id",
objective=objective,
)
]
def validate_return_scores(self, scores: list[Score]):
assert all(s.score_value in ["true", "false"] for s in scores)
class SelectiveValidator(ScorerPromptValidator):
"""Validator that only supports text pieces, not images."""
def __init__(self, *, enforce_all_pieces_valid: bool = False, raise_on_no_valid_pieces: bool = False):
super().__init__(
supported_data_types=["text"],
enforce_all_pieces_valid=enforce_all_pieces_valid,
raise_on_no_valid_pieces=raise_on_no_valid_pieces,
)
class MockFloatScorer(Scorer):
"""Mock scorer that tracks which pieces were scored."""
def __init__(self, *, validator: ScorerPromptValidator):
self.scored_piece_ids: list[str] = []
super().__init__(validator=validator)
def _build_identifier(self) -> ComponentIdentifier:
"""Build the scorer evaluation identifier for this mock scorer."""
return self._create_identifier()
async def _score_piece_async(self, message_piece: MessagePiece, *, objective: Optional[str] = None) -> list[Score]:
# Track which pieces get scored
self.scored_piece_ids.append(str(message_piece.id))
return [
Score(
score_value="0.5",
score_value_description="Test score",
score_type="float_scale",
score_category=None,
score_metadata=None,
score_rationale="Test rationale",
scorer_class_identifier=self.get_identifier(),
message_piece_id=message_piece.id or "test-id",
objective=objective,
)
]
def validate_return_scores(self, scores: list[Score]):
for score in scores:
assert 0 <= float(score.score_value) <= 1
def get_scorer_metrics(self):
return None
@pytest.mark.asyncio
@pytest.mark.parametrize("bad_json", [BAD_JSON, KEY_ERROR_JSON, KEY_ERROR2_JSON])
async def test_scorer_send_chat_target_async_bad_json_exception_retries(bad_json: str):
chat_target = MagicMock(PromptChatTarget)
chat_target.get_identifier.return_value = get_mock_target_identifier("MockChatTarget")
bad_json_resp = Message(
message_pieces=[MessagePiece(role="assistant", original_value=bad_json, conversation_id="test-convo")]
)
chat_target.send_prompt_async = AsyncMock(return_value=[bad_json_resp])
scorer = MockScorer()
with pytest.raises(InvalidJsonException):
await scorer._score_value_with_llm(
prompt_target=chat_target,
system_prompt="system_prompt",
message_value="message_value",
message_data_type="text",
scored_prompt_id="123",
category="category",
objective="task",
)
# RETRY_MAX_NUM_ATTEMPTS is set to 2 in conftest.py
assert chat_target.send_prompt_async.call_count == 2
@pytest.mark.asyncio
async def test_scorer_score_value_with_llm_exception_display_prompt_id():
chat_target = MagicMock(PromptChatTarget)
chat_target.get_identifier.return_value = get_mock_target_identifier("MockChatTarget")
chat_target.send_prompt_async = AsyncMock(side_effect=Exception("Test exception"))
scorer = MockScorer()
with pytest.raises(Exception, match="Error scoring prompt with original prompt ID: 123"):
await scorer._score_value_with_llm(
prompt_target=chat_target,
system_prompt="system_prompt",
message_value="message_value",
message_data_type="text",
scored_prompt_id="123",
category="category",
objective="task",
)
@pytest.mark.asyncio
async def test_scorer_score_value_with_llm_use_provided_attack_identifier(good_json):
scorer = MockScorer()
message = Message(
message_pieces=[MessagePiece(role="assistant", original_value=good_json, conversation_id="test-convo")]
)
chat_target = MagicMock(PromptChatTarget)
chat_target.get_identifier.return_value = get_mock_target_identifier("MockChatTarget")
chat_target.send_prompt_async = AsyncMock(return_value=[message])
chat_target.set_system_prompt = MagicMock()
expected_system_prompt = "system_prompt"
expected_attack_identifier = ComponentIdentifier(class_name="TestAttack", class_module="test.module")
expected_scored_prompt_id = "123"
await scorer._score_value_with_llm(
prompt_target=chat_target,
system_prompt=expected_system_prompt,
message_value="message_value",
message_data_type="text",
scored_prompt_id=expected_scored_prompt_id,
category="category",
objective="task",
attack_identifier=expected_attack_identifier,
)
chat_target.set_system_prompt.assert_called_once()
_, set_sys_prompt_args = chat_target.set_system_prompt.call_args
assert set_sys_prompt_args["system_prompt"] == expected_system_prompt
assert isinstance(set_sys_prompt_args["conversation_id"], str)
assert set_sys_prompt_args["attack_identifier"] is expected_attack_identifier
@pytest.mark.asyncio
async def test_scorer_score_value_with_llm_does_not_add_score_prompt_id_for_empty_attack_identifier(good_json):
scorer = MockScorer()
message = Message(
message_pieces=[MessagePiece(role="assistant", original_value=good_json, conversation_id="test-convo")]
)
chat_target = MagicMock(PromptChatTarget)
chat_target.get_identifier.return_value = get_mock_target_identifier("MockChatTarget")
chat_target.send_prompt_async = AsyncMock(return_value=[message])
chat_target.set_system_prompt = MagicMock()
expected_system_prompt = "system_prompt"
await scorer._score_value_with_llm(
prompt_target=chat_target,
system_prompt=expected_system_prompt,
message_value="message_value",
message_data_type="text",
scored_prompt_id="123",
category="category",
objective="task",
)
chat_target.set_system_prompt.assert_called_once()
_, set_sys_prompt_args = chat_target.set_system_prompt.call_args
assert set_sys_prompt_args["system_prompt"] == expected_system_prompt
assert isinstance(set_sys_prompt_args["conversation_id"], str)
assert not set_sys_prompt_args["attack_identifier"]
@pytest.mark.asyncio
async def test_scorer_send_chat_target_async_good_response(good_json):
chat_target = MagicMock(PromptChatTarget)
chat_target.get_identifier.return_value = get_mock_target_identifier("MockChatTarget")
good_json_resp = Message(
message_pieces=[MessagePiece(role="assistant", original_value=good_json, conversation_id="test-convo")]
)
chat_target.send_prompt_async = AsyncMock(return_value=[good_json_resp])
scorer = MockScorer()
await scorer._score_value_with_llm(
prompt_target=chat_target,
system_prompt="system_prompt",
message_value="message_value",
message_data_type="text",
scored_prompt_id="123",
category="category",
objective="task",
)
assert chat_target.send_prompt_async.call_count == 1
@pytest.mark.asyncio
async def test_scorer_remove_markdown_json_called(good_json):
chat_target = MagicMock(PromptChatTarget)
chat_target.get_identifier.return_value = get_mock_target_identifier("MockChatTarget")
good_json_resp = Message(
message_pieces=[MessagePiece(role="assistant", original_value=good_json, conversation_id="test-convo")]
)
chat_target.send_prompt_async = AsyncMock(return_value=[good_json_resp])
scorer = MockScorer()
with patch("pyrit.score.scorer.remove_markdown_json", wraps=remove_markdown_json) as mock_remove_markdown_json:
await scorer._score_value_with_llm(
prompt_target=chat_target,
system_prompt="system_prompt",
message_value="message_value",
message_data_type="text",
scored_prompt_id="123",
category="category",
objective="task",
)
mock_remove_markdown_json.assert_called_once()
@pytest.mark.asyncio
async def test_score_value_with_llm_prepended_text_message_piece_creates_multipiece_message(good_json):
"""Test that prepended_text_message_piece creates a multi-piece message (text context + main content)."""
chat_target = MagicMock(PromptChatTarget)
chat_target.get_identifier.return_value = get_mock_target_identifier("MockChatTarget")
good_json_resp = Message(
message_pieces=[MessagePiece(role="assistant", original_value=good_json, conversation_id="test-convo")]
)
chat_target.send_prompt_async = AsyncMock(return_value=[good_json_resp])
scorer = MockScorer()
await scorer._score_value_with_llm(
prompt_target=chat_target,
system_prompt="system_prompt",
message_value="test_image.png",
message_data_type="image_path",
scored_prompt_id="123",
prepended_text_message_piece="objective: test\nresponse:",
category="category",
objective="task",
)
# Verify send_prompt_async was called
chat_target.send_prompt_async.assert_called_once()
# Get the message that was sent
call_args = chat_target.send_prompt_async.call_args
sent_message = call_args.kwargs["message"]
# Should have 2 pieces: text context first, then the main content being scored
assert len(sent_message.message_pieces) == 2
# First piece should be the extra text context
text_piece = sent_message.message_pieces[0]
assert text_piece.converted_value_data_type == "text"
assert "objective: test" in text_piece.original_value
# Second piece should be the main content (image in this case)
main_piece = sent_message.message_pieces[1]
assert main_piece.converted_value_data_type == "image_path"
assert main_piece.original_value == "test_image.png"
@pytest.mark.asyncio
async def test_score_value_with_llm_no_prepended_text_creates_single_piece_message(good_json):
"""Test that without prepended_text_message_piece, only a single piece message is created."""
chat_target = MagicMock(PromptChatTarget)
chat_target.get_identifier.return_value = get_mock_target_identifier("MockChatTarget")
good_json_resp = Message(
message_pieces=[MessagePiece(role="assistant", original_value=good_json, conversation_id="test-convo")]
)
chat_target.send_prompt_async = AsyncMock(return_value=[good_json_resp])
scorer = MockScorer()
await scorer._score_value_with_llm(
prompt_target=chat_target,
system_prompt="system_prompt",
message_value="objective: test\nresponse: some text",
message_data_type="text",
scored_prompt_id="123",
category="category",
objective="task",
)
# Get the message that was sent
call_args = chat_target.send_prompt_async.call_args
sent_message = call_args.kwargs["message"]
# Should have only 1 piece
assert len(sent_message.message_pieces) == 1
# The piece should be text with the full message
text_piece = sent_message.message_pieces[0]
assert text_piece.converted_value_data_type == "text"
assert "objective: test" in text_piece.original_value
assert "response: some text" in text_piece.original_value
@pytest.mark.asyncio
async def test_score_value_with_llm_prepended_text_works_with_audio(good_json):
"""Test that prepended_text_message_piece works with audio content (type-independent)."""
chat_target = MagicMock(PromptChatTarget)
chat_target.get_identifier.return_value = get_mock_target_identifier("MockChatTarget")
good_json_resp = Message(
message_pieces=[MessagePiece(role="assistant", original_value=good_json, conversation_id="test-convo")]
)
chat_target.send_prompt_async = AsyncMock(return_value=[good_json_resp])
scorer = MockScorer()
await scorer._score_value_with_llm(
prompt_target=chat_target,
system_prompt="system_prompt",
message_value="test_audio.wav",
message_data_type="audio_path",
scored_prompt_id="123",
prepended_text_message_piece="objective: transcribe and evaluate\nresponse:",
category="category",
objective="task",
)
# Get the message that was sent
call_args = chat_target.send_prompt_async.call_args
sent_message = call_args.kwargs["message"]
# Should have 2 pieces: text context + audio
assert len(sent_message.message_pieces) == 2
# First piece should be text context
text_piece = sent_message.message_pieces[0]
assert text_piece.converted_value_data_type == "text"
# Second piece should be audio
audio_piece = sent_message.message_pieces[1]
assert audio_piece.converted_value_data_type == "audio_path"
assert audio_piece.original_value == "test_audio.wav"
def test_scorer_extract_task_from_response(patch_central_database):
"""
Test that _extract_task_from_response properly gathers text from the
last turn. We'll mock out the memory's get_message_pieces method.
"""
scorer = MockScorer()
mock_memory = MagicMock()
response_piece = MessagePiece(original_value="og prompt", role="assistant", conversation_id="xyz", sequence=2)
mock_memory.get_message_pieces.return_value = [
MessagePiece(role="user", original_value="Not applicable", original_value_data_type="text", sequence=0),
MessagePiece(
role="user",
original_value="User's question about the universe",
converted_value="Not the task",
original_value_data_type="text",
sequence=1,
),
response_piece,
]
with patch.object(CentralMemory, "get_memory_instance", return_value=mock_memory):
extracted_task = scorer._extract_objective_from_response(response_piece.to_message())
assert "User's question about the universe" in extracted_task
@pytest.mark.asyncio
async def test_scorer_score_responses_batch_async(patch_central_database):
"""
Test that score_responses_batch_async filters to only assistant pieces,
calls score_prompts_with_tasks_batch_async, and returns results.
"""
scorer = MockScorer()
with patch.object(scorer, "score_async", new_callable=AsyncMock) as mock_score_async:
fake_scores = [MagicMock(), MagicMock()]
mock_score_async.return_value = fake_scores
user_req = MessagePiece(role="user", original_value="Hello user", sequence=1).to_message()
assistant_resp = MessagePiece(role="assistant", original_value="Hello from assistant", sequence=2).to_message()
results = await scorer.score_prompts_batch_async(
messages=[user_req, assistant_resp], batch_size=10, infer_objective_from_request=True
)
# Verify mock_score_async was called twice
assert mock_score_async.call_count == 2
# Get the call_args for the first call
_, first_call_kwargs = mock_score_async.call_args_list[0]
assert "message" in first_call_kwargs
assert "objective" in first_call_kwargs
assert "infer_objective_from_request" in first_call_kwargs
assert first_call_kwargs["message"] == user_req
assert fake_scores[0] in results
assert len(fake_scores) == 2
@pytest.mark.asyncio
async def test_score_prompts_batch_async_rejects_explicit_empty_objectives():
"""Test explicit empty objectives are rejected for non-empty message batches."""
scorer = MockScorer()
message = MessagePiece(role="user", original_value="Hello user", sequence=1).to_message()
with pytest.raises(ValueError, match="objectives"):
await scorer.score_prompts_batch_async(messages=[message], objectives=[])
@pytest.mark.asyncio
async def test_score_image_batch_async_rejects_explicit_empty_objectives():
"""Test explicit empty objectives are rejected for non-empty image batches."""
scorer = MockScorer()
with pytest.raises(ValueError, match="objectives"):
await scorer.score_image_batch_async(image_paths=["test_image.png"], objectives=[])
@pytest.mark.asyncio
async def test_score_response_async_empty_scorers():
"""Test that score_response_async returns empty list when no scorers provided."""
response = Message(
message_pieces=[MessagePiece(role="assistant", original_value="test", conversation_id="test-convo")]
)
result = await Scorer.score_response_async(response=response, objective="test task")
assert result == {"auxiliary_scores": [], "objective_scores": []}
@pytest.mark.asyncio
async def test_score_response_async_no_matching_role():
"""Test that score_response_async returns empty list when no pieces match role filter."""
response = Message(
message_pieces=[
MessagePiece(role="user", original_value="test1", conversation_id="test-convo"),
MessagePiece(role="user", original_value="test2", conversation_id="test-convo"),
]
)
scorer = MockScorer()
scorer.score_async = AsyncMock(return_value=[])
result = await Scorer.score_response_async(
response=response,
objective_scorer=scorer,
auxiliary_scorers=[scorer],
role_filter="assistant",
objective="test task",
)
assert result == {"auxiliary_scores": [], "objective_scores": []}
scorer.score_async.assert_called()
@pytest.mark.asyncio
async def test_score_response_async_parallel_execution():
"""Test that score_response_async runs all scorers in parallel on all filtered pieces."""
piece1 = MessagePiece(role="assistant", original_value="response1", conversation_id="test-convo")
piece2 = MessagePiece(role="assistant", original_value="response2", conversation_id="test-convo")
piece3 = MessagePiece(role="assistant", original_value="user input", conversation_id="test-convo")
response = Message(message_pieces=[piece1, piece2, piece3])
# Create mock scores
score1_1 = MagicMock(spec=Score)
score1_2 = MagicMock(spec=Score)
score2_1 = MagicMock(spec=Score)
score2_2 = MagicMock(spec=Score)
# Create mock scorers
scorer1 = MockScorer()
scorer1.score_async = AsyncMock(side_effect=[[score1_1], [score1_2]])
scorer2 = MockScorer()
scorer2.score_async = AsyncMock(side_effect=[[score2_1], [score2_2]])
result = await Scorer.score_response_async(
response=response, auxiliary_scorers=[scorer1, scorer2], role_filter="assistant", objective="test task"
)
assert score1_1 in result["auxiliary_scores"]
assert score2_1 in result["auxiliary_scores"]
scorer1.score_async.assert_any_call(
message=response, objective="test task", role_filter="assistant", skip_on_error_result=True
)
scorer2.score_async.assert_any_call(
message=response, objective="test task", role_filter="assistant", skip_on_error_result=True
)
@pytest.mark.asyncio
async def test_score_response_select_first_success_async_empty_scorers():
"""Test that score_response_select_first_success_async returns None when no scorers provided."""
response = Message(
message_pieces=[MessagePiece(role="assistant", original_value="test", conversation_id="test-convo")]
)
result = await Scorer.score_response_multiple_scorers_async(response=response, scorers=[], objective="test task")
assert result == []
@pytest.mark.asyncio
async def test_score_async_no_matching_role():
"""Test that score_response_select_first_success_async returns None when no pieces match role filter."""
response = Message(message_pieces=[MessagePiece(role="user", original_value="test", conversation_id="test-convo")])
scorer = MockScorer()
result = await scorer.score_async(message=response, role_filter="assistant", objective="test task")
assert result == []
@pytest.mark.asyncio
async def test_score_response_async_finds_success():
"""Test that score_response_async returns first successful score."""
piece1 = MessagePiece(role="assistant", original_value="response1", conversation_id="test-convo")
piece2 = MessagePiece(role="assistant", original_value="response2", conversation_id="test-convo")
response = Message(message_pieces=[piece1, piece2])
# Create mock scores
score1 = MagicMock(spec=Score)
score1.get_value.return_value = False # Failure
score2 = MagicMock(spec=Score)
score2.get_value.return_value = True # Success
score3 = MagicMock(spec=Score)
score3.get_value.return_value = True # Another success (should not be reached)
# Create mock scorers
scorer1 = MockScorer()
scorer1.score_async = AsyncMock(side_effect=[[score1], [score3]])
scorer2 = MockScorer()
scorer2.score_async = AsyncMock(return_value=[score2])
result = await Scorer.score_response_multiple_scorers_async(
response=response, scorers=[scorer1, scorer2], objective="test task"
)
# Should return the first successful score (score2)
assert len(result) == 2
assert score2 in result
# scorer1 should be called only once (for piece1)
assert scorer1.score_async.call_count == 1
# scorer2 should be called only once (for piece1, returning success)
assert scorer2.score_async.call_count == 1
@pytest.mark.asyncio
async def test_score_response_success_async_no_success_returns_first():
"""Test that score_response_success_async returns first score when no success found."""
piece1 = MessagePiece(role="assistant", original_value="response1", conversation_id="test-convo")
piece2 = MessagePiece(role="assistant", original_value="response2", conversation_id="test-convo")
response = Message(message_pieces=[piece1, piece2])
# Create mock scores (all failures)
score1 = MagicMock(spec=Score)
score1.get_value.return_value = False
score2 = MagicMock(spec=Score)
score2.get_value.return_value = False
score3 = MagicMock(spec=Score)
score3.get_value.return_value = False
score4 = MagicMock(spec=Score)
score4.get_value.return_value = False
# Create mock scorers
scorer1 = MockScorer()
scorer1.score_async = AsyncMock(side_effect=[[score1], [score3]])
scorer2 = MockScorer()
scorer2.score_async = AsyncMock(side_effect=[[score2], [score4]])
result = await Scorer.score_response_multiple_scorers_async(
response=response, scorers=[scorer1, scorer2], objective="test task"
)
assert score1 in result
assert score2 in result
assert scorer1.score_async.call_count == 1
assert scorer2.score_async.call_count == 1
@pytest.mark.asyncio
async def test_score_response_success_async_parallel_scoring_per_piece():
"""Test that score_response_success_async runs scorers in parallel for each piece."""
piece1 = MessagePiece(role="assistant", original_value="response1", conversation_id="test-convo")
piece2 = MessagePiece(role="assistant", original_value="response2", conversation_id="test-convo")
response = Message(message_pieces=[piece1, piece2])
# Track call order
call_order = []
async def mock_score_async_1(message: Message, **kwargs) -> list[Score]:
call_order.append(("scorer1", message.message_pieces[0].original_value))
score = MagicMock(spec=Score)
score.get_value.return_value = False
return [score]
async def mock_score_async_2(message: Message, **kwargs) -> list[Score]:
call_order.append(("scorer2", message.message_pieces[0].original_value))
score = MagicMock(spec=Score)
score.get_value.return_value = False
return [score]
scorer1 = MockScorer()
scorer1.score_async = mock_score_async_1
scorer2 = MockScorer()
scorer2.score_async = mock_score_async_2
await Scorer.score_response_multiple_scorers_async(
response=response, scorers=[scorer1, scorer2], objective="test task"
)
assert len(call_order) == 2
assert ("scorer1", "response1") in call_order[:2]
assert ("scorer2", "response1") in call_order[:2]
@pytest.mark.asyncio
async def test_score_response_async_no_scorers():
"""Test score_response_async with no scorers provided."""
response = Message(message_pieces=[MessagePiece(role="assistant", original_value="test")])
result = await Scorer.score_response_async(
response=response, auxiliary_scorers=None, objective_scorer=None, objective="test task"
)
assert result == {"auxiliary_scores": [], "objective_scores": []}
@pytest.mark.asyncio
async def test_score_response_async_auxiliary_only():
"""Test score_response_async with only auxiliary scorers."""
piece = MessagePiece(role="assistant", original_value="response")
response = Message(message_pieces=[piece])
# Create mock auxiliary scores
aux_score1 = MagicMock(spec=Score)
aux_score2 = MagicMock(spec=Score)
# Create mock auxiliary scorers
aux_scorer1 = MockScorer()
aux_scorer1.score_async = AsyncMock(return_value=[aux_score1])
aux_scorer2 = MockScorer()
aux_scorer2.score_async = AsyncMock(return_value=[aux_score2])
result = await Scorer.score_response_async(
response=response, auxiliary_scorers=[aux_scorer1, aux_scorer2], objective_scorer=None, objective="test task"
)
# Should have auxiliary scores but no objective scores
assert len(result["auxiliary_scores"]) == 2
assert aux_score1 in result["auxiliary_scores"]
assert aux_score2 in result["auxiliary_scores"]
assert result["objective_scores"] == []
@pytest.mark.asyncio
async def test_score_response_async_objective_only():
"""Test score_response_async with only objective scorers."""
piece = MessagePiece(role="assistant", original_value="response")
response = Message(message_pieces=[piece])
# Create mock objective score
obj_score = MagicMock(spec=Score)
obj_score.get_value.return_value = True
# Create mock objective scorer
obj_scorer = MockScorer()
obj_scorer.score_async = AsyncMock(return_value=[obj_score])
result = await Scorer.score_response_async(
response=response, auxiliary_scorers=None, objective_scorer=obj_scorer, objective="test task"
)
# Should have objective score but no auxiliary scores
assert result["auxiliary_scores"] == []
assert len(result["objective_scores"]) == 1
assert result["objective_scores"][0] == obj_score
@pytest.mark.asyncio
async def test_score_response_async_both_types():
"""Test score_response_async with both auxiliary and objective scorers."""
piece = MessagePiece(role="assistant", original_value="response")
response = Message(message_pieces=[piece])
# Create mock scores
aux_score = MagicMock(spec=Score)
obj_score = MagicMock(spec=Score)
obj_score.get_value.return_value = False # Not successful
# Create mock scorers
aux_scorer = MockScorer()
aux_scorer.score_async = AsyncMock(return_value=[aux_score])
obj_scorer = MockScorer()
obj_scorer.score_async = AsyncMock(return_value=[obj_score])
result = await Scorer.score_response_async(
response=response, auxiliary_scorers=[aux_scorer], objective_scorer=obj_scorer, objective="test task"
)
# Should have both types of scores
assert len(result["auxiliary_scores"]) == 1
assert result["auxiliary_scores"][0] == aux_score
assert len(result["objective_scores"]) == 1
assert result["objective_scores"][0] == obj_score
@pytest.mark.asyncio
async def test_score_response_async_multiple_pieces():
"""Test score_response_async with multiple response pieces."""
piece1 = MessagePiece(role="assistant", original_value="response1", conversation_id="test-convo")
piece2 = MessagePiece(role="assistant", original_value="response2", conversation_id="test-convo")
response = Message(message_pieces=[piece1, piece2])
# Create mock scores
aux_scores = [MagicMock(spec=Score) for _ in range(4)] # 2 pieces x 2 scorers
obj_score = MagicMock(spec=Score)
obj_score.get_value.return_value = True # Success on first piece
# Create mock auxiliary scorers
aux_scorer1 = MockScorer()
aux_scorer1.score_async = AsyncMock(side_effect=[[aux_scores[0]], [aux_scores[1]]])
aux_scorer2 = MockScorer()
aux_scorer2.score_async = AsyncMock(side_effect=[[aux_scores[2]], [aux_scores[3]]])
# Create mock objective scorer
obj_scorer = MockScorer()
obj_scorer.score_async = AsyncMock(return_value=[obj_score])
result = await Scorer.score_response_async(
response=response,
auxiliary_scorers=[aux_scorer1, aux_scorer2],
objective_scorer=obj_scorer,
objective="test task",
)
# TEMPORARY fix means there should only be 2 auxiliary scores, one per Message
assert len(result["auxiliary_scores"]) == 2
# The following commented-out lines should be uncommented when the permanent solution is implemented
# # Should have all auxiliary scores
# assert len(result["auxiliary_scores"]) == 4 # noqa: ERA001
# for score in aux_scores: # noqa: ERA001
# assert score in result["auxiliary_scores"] # noqa: ERA001
# Should have only one objective score (first success)
assert len(result["objective_scores"]) == 1
assert result["objective_scores"][0] == obj_score
@pytest.mark.asyncio
async def test_score_response_async_skip_on_error_true():
"""Test score_response_async skips error pieces when skip_on_error_result=True."""
piece1 = MessagePiece(role="assistant", original_value="good response", conversation_id="test-convo")
piece2 = MessagePiece(
role="assistant", original_value="error", response_error="blocked", conversation_id="test-convo"
)
response = Message(message_pieces=[piece1, piece2])
# Create mock scores
aux_score = MagicMock(spec=Score)
obj_score = MagicMock(spec=Score)
obj_score.get_value.return_value = True
# Create mock scorers
aux_scorer = MockScorer()
aux_scorer.score_async = AsyncMock(return_value=[aux_score])
obj_scorer = MockScorer()
obj_scorer.score_async = AsyncMock(return_value=[obj_score])
result = await Scorer.score_response_async(
response=response,
auxiliary_scorers=[aux_scorer],
objective_scorer=obj_scorer,
objective="test task",
skip_on_error_result=True,
)
# Should only score the non-error piece
assert len(result["auxiliary_scores"]) == 1
assert len(result["objective_scores"]) == 1
# Verify only non-error piece was scored
aux_scorer.score_async.assert_called_once()
obj_scorer.score_async.assert_called_once()
@pytest.mark.asyncio
async def test_score_response_async_skip_on_error_false():
"""Test score_response_async includes error pieces when skip_on_error_result=False."""
piece1 = MessagePiece(role="assistant", original_value="good response", conversation_id="test-convo")
piece2 = MessagePiece(
role="assistant", original_value="error", response_error="blocked", conversation_id="test-convo"
)
response = Message(message_pieces=[piece1, piece2])
# Create mock scores
aux_scores = [MagicMock(spec=Score), MagicMock(spec=Score)]
obj_score = MagicMock(spec=Score)
obj_score.get_value.return_value = True
# Create mock scorers
aux_scorer = MockScorer()
aux_scorer.score_async = AsyncMock(side_effect=[[aux_scores[0]], [aux_scores[1]]])
obj_scorer = MockScorer()
obj_scorer.score_async = AsyncMock(return_value=[obj_score])
result = await Scorer.score_response_async(
response=response,
auxiliary_scorers=[aux_scorer],
objective_scorer=obj_scorer,
objective="test task",
skip_on_error_result=False,
)
# Temporary fix means there should only be 1 auxiliary score (first piece)
assert len(result["auxiliary_scores"]) == 1
# The following commented-out lines should be uncommented when the permanent solution is implemented
# # Should score both pieces for auxiliary
# assert len(result["auxiliary_scores"]) == 2 # noqa: ERA001
# But only one objective score (first success)
assert len(result["objective_scores"]) == 1
# # Verify both pieces were scored for auxiliary
# assert aux_scorer.score_async.call_count == 2 # noqa: ERA001
@pytest.mark.asyncio
async def test_score_response_async_objective_failure():
"""Test score_response_async when no objective succeeds."""
piece = MessagePiece(role="assistant", original_value="response")
response = Message(message_pieces=[piece])
# Create mock scores (all failures)
obj_score1 = MagicMock(spec=Score)
obj_score1.get_value.return_value = False
obj_score2 = MagicMock(spec=Score)
obj_score2.get_value.return_value = False
# Create mock objective scorers
obj_scorer1 = MockScorer()
obj_scorer1.score_async = AsyncMock(return_value=[obj_score1])
obj_scorer2 = MockScorer()
obj_scorer2.score_async = AsyncMock(return_value=[obj_score2])
result = await Scorer.score_response_async(
response=response, auxiliary_scorers=None, objective_scorer=obj_scorer1, objective="test task"
)
# Should return the first score as failure indicator
assert result["auxiliary_scores"] == []
assert len(result["objective_scores"]) == 1
assert result["objective_scores"][0] == obj_score1
@pytest.mark.asyncio
async def test_score_response_async_concurrent_execution():
"""Test that auxiliary and objective scoring happen concurrently."""
piece = MessagePiece(role="assistant", original_value="response")
response = Message(message_pieces=[piece])
# Track call order to verify concurrent execution
call_order = []
async def mock_aux_score_async(message: Message, **kwargs) -> list[Score]:
call_order.append("aux_start")
# Simulate some async work
await asyncio.sleep(0.01)
call_order.append("aux_end")
return [MagicMock(spec=Score)]
async def mock_obj_score_async(message: Message, **kwargs) -> list[Score]:
call_order.append("obj_start")
# Simulate some async work
await asyncio.sleep(0.01)
call_order.append("obj_end")
score = MagicMock(spec=Score)
score.get_value.return_value = True
return [score]
aux_scorer = MockScorer()
aux_scorer.score_async = mock_aux_score_async
obj_scorer = MockScorer()
obj_scorer.score_async = mock_obj_score_async