-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest_client.py
More file actions
6130 lines (5203 loc) · 268 KB
/
Copy pathtest_client.py
File metadata and controls
6130 lines (5203 loc) · 268 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
"""Tests for OptimizationClient."""
import dataclasses
import json
from typing import Any, Dict
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from ldai import AIAgentConfig, LDAIClient
from ldai.client import Evaluator
from ldai.models import LDMessage, ModelConfig
from ldai.tracker import TokenUsage
from ldclient import Context
from ldai_optimizer.client import (
OptimizationClient,
_MAX_STANDARD_HISTORY_LENGTH,
_compute_validation_count,
_find_model_config,
_strip_provider_prefix,
_trim_history,
)
from ldai_optimizer.util import judge_passed
from ldai_optimizer.dataclasses import (
AIJudgeCallConfig,
GroundTruthOptimizationOptions,
GroundTruthSample,
JudgeResult,
OptimizationContext,
OptimizationFromConfigOptions,
OptimizationJudge,
OptimizationJudgeContext,
OptimizationOptions,
OptimizationResponse,
ToolDefinition,
)
from ldai_optimizer.prompts import (
build_new_variation_prompt,
variation_prompt_acceptance_criteria,
variation_prompt_cost_optimization,
variation_prompt_feedback,
variation_prompt_improvement_instructions,
variation_prompt_overfit_warning,
variation_prompt_preamble,
)
from ldai_optimizer.util import estimate_cost, interpolate_variables
from ldai_optimizer.util import (
restore_variable_placeholders,
)
# ---------------------------------------------------------------------------
# Shared helpers / fixtures
# ---------------------------------------------------------------------------
LD_CONTEXT = Context.create("test-user")
AGENT_INSTRUCTIONS = "You are a helpful assistant. Answer using {{language}}."
VARIATION_RESPONSE = json.dumps({
"current_instructions": "You are an improved assistant.",
"current_parameters": {"temperature": 0.5},
"model": "gpt-4o",
})
JUDGE_PASS_RESPONSE = json.dumps({"score": 1.0, "rationale": "Perfect answer."})
JUDGE_FAIL_RESPONSE = json.dumps({"score": 0.2, "rationale": "Off topic."})
def _make_agent_config(
instructions: str = AGENT_INSTRUCTIONS,
model_name: str = "gpt-4o",
parameters: Dict[str, Any] | None = None,
) -> AIAgentConfig:
return AIAgentConfig(
key="test-agent",
enabled=True,
create_tracker=MagicMock,
evaluator=Evaluator.noop(),
model=ModelConfig(name=model_name, parameters=parameters or {}),
instructions=instructions,
)
def _make_ldai_client(agent_config: AIAgentConfig | None = None) -> MagicMock:
mock = MagicMock(spec=LDAIClient)
mock.agent_config.return_value = agent_config or _make_agent_config()
mock._client = MagicMock()
mock._client.variation.return_value = {"instructions": AGENT_INSTRUCTIONS}
return mock
def _make_options(
*,
handle_agent_call=None,
handle_judge_call=None,
judges=None,
max_attempts: int = 3,
variable_choices=None,
**extra,
) -> OptimizationOptions:
if handle_agent_call is None:
handle_agent_call = AsyncMock(return_value=OptimizationResponse(output="The capital of France is Paris."))
if handle_judge_call is None:
handle_judge_call = AsyncMock(return_value=OptimizationResponse(output=JUDGE_PASS_RESPONSE))
if judges is None:
judges = {
"accuracy": OptimizationJudge(
threshold=0.8,
acceptance_statement="The response must be accurate and concise.",
)
}
return OptimizationOptions(
context_choices=[LD_CONTEXT],
max_attempts=max_attempts,
model_choices=["gpt-4o", "gpt-4o-mini"],
judge_model="gpt-4o",
variable_choices=variable_choices or [{"language": "English"}],
handle_agent_call=handle_agent_call,
handle_judge_call=handle_judge_call,
judges=judges,
**extra,
)
def _make_client(ldai: MagicMock | None = None) -> OptimizationClient:
client = OptimizationClient(ldai or _make_ldai_client())
return client
# ---------------------------------------------------------------------------
# Util functions
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# _strip_provider_prefix
# ---------------------------------------------------------------------------
class TestStripProviderPrefix:
def test_strips_known_anthropic_prefix(self):
assert _strip_provider_prefix("Anthropic.claude-opus-4-5") == "claude-opus-4-5"
def test_strips_known_openai_prefix(self):
assert _strip_provider_prefix("OpenAI.gpt-4o") == "gpt-4o"
def test_strips_known_bedrock_prefix(self):
# "Bedrock.us.amazon.nova-pro-v1:0" → region prefix is preserved
assert _strip_provider_prefix("Bedrock.us.amazon.nova-pro-v1:0") == "us.amazon.nova-pro-v1:0"
def test_does_not_strip_bedrock_region_prefix(self):
# Raw Bedrock cross-region ID has no provider prefix — must be unchanged
assert _strip_provider_prefix("us.amazon.nova-pro-v1:0") == "us.amazon.nova-pro-v1:0"
def test_does_not_strip_eu_region_prefix(self):
assert _strip_provider_prefix("eu.anthropic.claude-3-5-sonnet-20241022-v2:0") == "eu.anthropic.claude-3-5-sonnet-20241022-v2:0"
def test_no_period_returns_unchanged(self):
assert _strip_provider_prefix("gpt-4o") == "gpt-4o"
def test_empty_string_returns_unchanged(self):
assert _strip_provider_prefix("") == ""
def test_preserves_dots_in_model_name_after_stripping(self):
# Multiple dots after the provider prefix are preserved
assert _strip_provider_prefix("Anthropic.claude-3.5-sonnet") == "claude-3.5-sonnet"
# ---------------------------------------------------------------------------
# _find_model_config
# ---------------------------------------------------------------------------
class TestFindModelConfig:
def test_returns_none_when_no_configs(self):
assert _find_model_config("gpt-4o", []) is None
def test_returns_none_when_no_id_match(self):
configs = [{"id": "claude-3", "key": "Anthropic.claude-3", "global": True}]
assert _find_model_config("gpt-4o", configs) is None
def test_returns_single_match(self):
configs = [{"id": "gpt-4o", "key": "OpenAI.gpt-4o", "global": False}]
result = _find_model_config("gpt-4o", configs)
assert result is not None
assert result["key"] == "OpenAI.gpt-4o"
def test_prefers_global_match_over_non_global(self):
configs = [
{"id": "gpt-4o", "key": "project.gpt-4o", "global": False},
{"id": "gpt-4o", "key": "global.gpt-4o", "global": True},
]
result = _find_model_config("gpt-4o", configs)
assert result is not None
assert result["key"] == "global.gpt-4o"
def test_prefers_global_match_regardless_of_list_order(self):
configs = [
{"id": "gpt-4o", "key": "global.gpt-4o", "global": True},
{"id": "gpt-4o", "key": "project.gpt-4o", "global": False},
]
result = _find_model_config("gpt-4o", configs)
assert result["key"] == "global.gpt-4o"
def test_falls_back_to_non_global_when_no_global_exists(self):
configs = [
{"id": "gpt-4o", "key": "project.gpt-4o", "global": False},
]
result = _find_model_config("gpt-4o", configs)
assert result is not None
assert result["key"] == "project.gpt-4o"
def test_treats_missing_global_field_as_non_global(self):
configs = [
{"id": "gpt-4o", "key": "no-global-field.gpt-4o"},
{"id": "gpt-4o", "key": "global.gpt-4o", "global": True},
]
result = _find_model_config("gpt-4o", configs)
assert result["key"] == "global.gpt-4o"
# ---------------------------------------------------------------------------
# _extract_agent_tools
# ---------------------------------------------------------------------------
class TestExtractAgentTools:
def setup_method(self):
self.client = _make_client()
self.client._agent_key = "test-agent"
self.client._options = _make_options()
self.client._agent_config = _make_agent_config()
self.client._initialize_class_members_from_config(_make_agent_config())
def test_returns_empty_list_when_no_tools(self):
result = self.client._extract_agent_tools({})
assert result == []
def test_returns_empty_list_when_tools_key_is_empty(self):
result = self.client._extract_agent_tools({"tools": []})
assert result == []
def test_returns_structured_output_tool_from_dict(self):
tool_dict = {
"name": "lookup",
"description": "Looks up data",
"input_schema": {"type": "object", "properties": {}},
}
result = self.client._extract_agent_tools({"tools": [tool_dict]})
assert len(result) == 1
assert isinstance(result[0], ToolDefinition)
assert result[0].name == "lookup"
def test_passes_through_existing_structured_output_tool(self):
tool = ToolDefinition(
name="my-tool", description="desc", input_schema={}
)
result = self.client._extract_agent_tools({"tools": [tool]})
assert result == [tool]
def test_wraps_single_non_list_tool(self):
tool_dict = {"name": "single", "description": "x", "input_schema": {}}
result = self.client._extract_agent_tools({"tools": tool_dict})
assert len(result) == 1
assert result[0].name == "single"
def test_converts_object_with_to_dict(self):
mock_tool = MagicMock()
mock_tool.to_dict.return_value = {
"name": "converted",
"description": "via to_dict",
"input_schema": {},
}
result = self.client._extract_agent_tools({"tools": [mock_tool]})
assert len(result) == 1
assert result[0].name == "converted"
# ---------------------------------------------------------------------------
# _evaluate_response
# ---------------------------------------------------------------------------
class TestIsTokenLimitExceeded:
def _client_with_limit(self, limit):
client = _make_client()
client._options = _make_options(token_limit=limit)
return client
def test_no_limit_returns_false(self):
client = self._client_with_limit(None)
client._total_token_usage = 9999
assert client._is_token_limit_exceeded() is False
def test_zero_limit_treated_as_no_limit(self):
client = self._client_with_limit(0)
client._total_token_usage = 0
assert client._is_token_limit_exceeded() is False
def test_zero_limit_with_high_usage_returns_false(self):
client = self._client_with_limit(0)
client._total_token_usage = 100_000
assert client._is_token_limit_exceeded() is False
def test_positive_limit_not_yet_reached(self):
client = self._client_with_limit(1000)
client._total_token_usage = 999
assert client._is_token_limit_exceeded() is False
def test_positive_limit_exactly_reached(self):
client = self._client_with_limit(1000)
client._total_token_usage = 1000
assert client._is_token_limit_exceeded() is True
def test_positive_limit_exceeded(self):
client = self._client_with_limit(1000)
client._total_token_usage = 1001
assert client._is_token_limit_exceeded() is True
class TestEvaluateResponse:
def setup_method(self):
self.client = _make_client()
self.client._options = _make_options()
def _ctx_with_scores(self, scores: Dict[str, JudgeResult]) -> OptimizationContext:
return OptimizationContext(
scores=scores,
completion_response="Some response.",
current_instructions="Do X.",
current_parameters={},
current_variables={},
iteration=1,
)
def test_passes_when_all_judges_meet_threshold(self):
ctx = self._ctx_with_scores({"accuracy": JudgeResult(score=0.9)})
assert self.client._evaluate_response(ctx) is True
def test_fails_when_judge_below_threshold(self):
ctx = self._ctx_with_scores({"accuracy": JudgeResult(score=0.5)})
assert self.client._evaluate_response(ctx) is False
def test_fails_when_judge_result_missing(self):
ctx = self._ctx_with_scores({})
assert self.client._evaluate_response(ctx) is False
def test_passes_at_exact_threshold(self):
ctx = self._ctx_with_scores({"accuracy": JudgeResult(score=0.8)})
assert self.client._evaluate_response(ctx) is True
def test_no_judges_always_passes(self):
options = _make_options(judges=None, handle_agent_call=AsyncMock(return_value=OptimizationResponse(output="x")))
# Need on_turn to satisfy validation — inject directly
options_with_on_turn = OptimizationOptions(
context_choices=[LD_CONTEXT],
max_attempts=1,
model_choices=["gpt-4o"],
judge_model="gpt-4o",
variable_choices=[{}],
handle_agent_call=AsyncMock(return_value=OptimizationResponse(output="x")),
handle_judge_call=AsyncMock(return_value=OptimizationResponse(output=JUDGE_PASS_RESPONSE)),
judges={"j": OptimizationJudge(threshold=1.0, acceptance_statement="x")},
on_turn=lambda ctx: True,
)
self.client._options = options_with_on_turn
# Without judges, _evaluate_response returns True
options_no_judges = MagicMock()
options_no_judges.judges = None
self.client._options = options_no_judges
ctx = self._ctx_with_scores({})
assert self.client._evaluate_response(ctx) is True
def test_multiple_judges_all_must_pass(self):
self.client._options = _make_options(
judges={
"a": OptimizationJudge(threshold=0.8, acceptance_statement="A"),
"b": OptimizationJudge(threshold=0.9, acceptance_statement="B"),
}
)
ctx = self._ctx_with_scores({
"a": JudgeResult(score=0.9),
"b": JudgeResult(score=0.7), # fails
})
assert self.client._evaluate_response(ctx) is False
def test_multiple_judges_all_passing(self):
self.client._options = _make_options(
judges={
"a": OptimizationJudge(threshold=0.8, acceptance_statement="A"),
"b": OptimizationJudge(threshold=0.8, acceptance_statement="B"),
}
)
ctx = self._ctx_with_scores({
"a": JudgeResult(score=0.9),
"b": JudgeResult(score=1.0),
})
assert self.client._evaluate_response(ctx) is True
# ---------------------------------------------------------------------------
# _evaluate_acceptance_judge
# ---------------------------------------------------------------------------
class TestEvaluateAcceptanceJudge:
def setup_method(self):
self.client = _make_client()
agent_config = _make_agent_config()
self.client._agent_key = "test-agent"
self.client._agent_config = agent_config
self.client._initialize_class_members_from_config(agent_config)
self.handle_judge_call = AsyncMock(return_value=OptimizationResponse(output=JUDGE_PASS_RESPONSE))
self.client._options = _make_options(handle_judge_call=self.handle_judge_call)
async def test_returns_parsed_score_and_rationale(self):
judge = OptimizationJudge(
threshold=0.8, acceptance_statement="Must be concise."
)
result = await self.client._evaluate_acceptance_judge(
judge_key="conciseness",
optimization_judge=judge,
completion_response="Paris.",
iteration=1,
reasoning_history="",
user_input="What is the capital of France?",
)
assert result.score == 1.0
assert result.rationale == "Perfect answer."
async def test_handle_judge_call_receives_correct_key_and_config(self):
judge = OptimizationJudge(
threshold=0.8, acceptance_statement="Must answer the question."
)
await self.client._evaluate_acceptance_judge(
judge_key="relevance",
optimization_judge=judge,
completion_response="Some answer.",
iteration=1,
reasoning_history="",
user_input="What time is it?",
)
call_args = self.handle_judge_call.call_args
key, config, ctx, _ = call_args.args
assert key == "relevance"
assert isinstance(config, AIJudgeCallConfig)
assert isinstance(ctx, OptimizationJudgeContext)
async def test_messages_has_system_and_user_turns(self):
judge = OptimizationJudge(
threshold=0.8, acceptance_statement="Must be factual."
)
await self.client._evaluate_acceptance_judge(
judge_key="facts",
optimization_judge=judge,
completion_response="The sky is blue.",
iteration=1,
reasoning_history="",
user_input="What colour is the sky?",
)
_, config, _, _ = self.handle_judge_call.call_args.args
roles = [m.role for m in config.messages]
assert roles == ["system", "user"]
async def test_messages_system_content_matches_instructions(self):
judge = OptimizationJudge(
threshold=0.8, acceptance_statement="Be concise."
)
await self.client._evaluate_acceptance_judge(
judge_key="brevity",
optimization_judge=judge,
completion_response="Yes.",
iteration=1,
reasoning_history="",
user_input="Is Paris in France?",
)
_, config, _, _ = self.handle_judge_call.call_args.args
system_msg = next(m for m in config.messages if m.role == "system")
assert system_msg.content == config.instructions
async def test_messages_user_content_matches_context_user_input(self):
judge = OptimizationJudge(
threshold=0.8, acceptance_statement="Answer directly."
)
await self.client._evaluate_acceptance_judge(
judge_key="directness",
optimization_judge=judge,
completion_response="Paris.",
iteration=1,
reasoning_history="",
user_input="Capital of France?",
)
_, config, ctx, _ = self.handle_judge_call.call_args.args
user_msg = next(m for m in config.messages if m.role == "user")
assert user_msg.content == ctx.user_input
async def test_acceptance_statement_in_instructions(self):
statement = "Response must mention the Eiffel Tower."
judge = OptimizationJudge(threshold=0.8, acceptance_statement=statement)
await self.client._evaluate_acceptance_judge(
judge_key="tower",
optimization_judge=judge,
completion_response="Paris has the Eiffel Tower.",
iteration=1,
reasoning_history="",
user_input="Tell me about Paris.",
)
call_args = self.handle_judge_call.call_args
_, config, _, _ = call_args.args
assert statement in config.instructions
async def test_no_structured_output_tool_in_judge_config(self):
"""Structured output tool must not be injected — judges return plain JSON."""
judge = OptimizationJudge(threshold=0.8, acceptance_statement="Be brief.")
await self.client._evaluate_acceptance_judge(
judge_key="brevity",
optimization_judge=judge,
completion_response="Yes.",
iteration=1,
reasoning_history="",
user_input="Is Paris in France?",
)
call_args = self.handle_judge_call.call_args
_, config, _, _ = call_args.args
tools = config.model.get_parameter("tools") or []
assert tools == []
async def test_agent_tools_included_in_config_tools(self):
agent_tool = ToolDefinition(
name="lookup", description="Lookup data", input_schema={}
)
judge = OptimizationJudge(threshold=0.8, acceptance_statement="Use tool.")
await self.client._evaluate_acceptance_judge(
judge_key="tool-use",
optimization_judge=judge,
completion_response="I looked it up.",
iteration=1,
reasoning_history="",
user_input="Find me something.",
agent_tools=[agent_tool],
)
call_args = self.handle_judge_call.call_args
_, config, _, _ = call_args.args
tools = config.model.get_parameter("tools") or []
tool_names = [t["name"] for t in tools]
assert tool_names == ["lookup"]
async def test_variables_in_context(self):
judge = OptimizationJudge(threshold=0.8, acceptance_statement="Be accurate.")
variables = {"language": "French", "topic": "geography"}
await self.client._evaluate_acceptance_judge(
judge_key="accuracy",
optimization_judge=judge,
completion_response="Paris.",
iteration=1,
reasoning_history="",
user_input="Capital?",
variables=variables,
)
call_args = self.handle_judge_call.call_args
_, _, ctx, _ = call_args.args
assert ctx.current_variables == variables
async def test_duration_context_added_when_latency_optimization_true_and_duration_provided(self):
"""When latency_optimization=True and agent_duration_ms is provided,
the judge instructions mention the duration."""
self.client._options = _make_options(
handle_judge_call=self.handle_judge_call, latency_optimization=True
)
judge = OptimizationJudge(threshold=0.8, acceptance_statement="Be accurate.")
await self.client._evaluate_acceptance_judge(
judge_key="speed",
optimization_judge=judge,
completion_response="Here is the answer.",
iteration=2,
reasoning_history="",
user_input="Tell me something.",
agent_duration_ms=1500.0,
)
_, config, _, _ = self.handle_judge_call.call_args.args
assert "1500ms" in config.instructions
assert "state the duration" in config.instructions
async def test_duration_context_includes_baseline_comparison_when_history_present(self):
"""When a baseline duration is captured, the judge instructions include a baseline comparison."""
self.client._options = _make_options(
handle_judge_call=self.handle_judge_call, latency_optimization=True
)
self.client._history = [
OptimizationContext(
scores={},
completion_response="old response",
current_instructions="Do X.",
current_parameters={},
current_variables={},
iteration=1,
duration_ms=2000.0,
)
]
self.client._baseline_duration_ms = 2000.0
judge = OptimizationJudge(threshold=0.8, acceptance_statement="Be accurate.")
await self.client._evaluate_acceptance_judge(
judge_key="latency",
optimization_judge=judge,
completion_response="Here is the answer.",
iteration=2,
reasoning_history="",
user_input="Tell me something.",
agent_duration_ms=1500.0,
)
_, config, _, _ = self.handle_judge_call.call_args.args
assert "1500ms" in config.instructions
assert "2000ms" in config.instructions
assert "faster" in config.instructions
async def test_duration_context_says_slower_when_candidate_is_slower(self):
"""When the candidate is slower than baseline, the instructions say 'slower'."""
self.client._options = _make_options(
handle_judge_call=self.handle_judge_call, latency_optimization=True
)
self.client._history = [
OptimizationContext(
scores={},
completion_response="old response",
current_instructions="Do X.",
current_parameters={},
current_variables={},
iteration=1,
duration_ms=1000.0,
)
]
self.client._baseline_duration_ms = 1000.0
judge = OptimizationJudge(threshold=0.8, acceptance_statement="Be accurate.")
await self.client._evaluate_acceptance_judge(
judge_key="speed",
optimization_judge=judge,
completion_response="Here is the answer.",
iteration=2,
reasoning_history="",
user_input="Tell me something.",
agent_duration_ms=1800.0,
)
_, config, _, _ = self.handle_judge_call.call_args.args
assert "slower" in config.instructions
async def test_duration_context_not_added_when_latency_optimization_is_none(self):
"""When latency_optimization is None (not set), duration is not injected."""
judge = OptimizationJudge(threshold=0.8, acceptance_statement="Be accurate.")
await self.client._evaluate_acceptance_judge(
judge_key="accuracy",
optimization_judge=judge,
completion_response="Paris.",
iteration=1,
reasoning_history="",
user_input="Capital of France?",
agent_duration_ms=2000.0,
)
_, config, _, _ = self.handle_judge_call.call_args.args
assert "2000ms" not in config.instructions
async def test_duration_context_not_added_when_agent_duration_ms_is_none(self):
"""When agent_duration_ms is None, no duration block is added even if latency_optimization=True."""
self.client._options = _make_options(
handle_judge_call=self.handle_judge_call, latency_optimization=True
)
judge = OptimizationJudge(threshold=0.8, acceptance_statement="Be accurate.")
await self.client._evaluate_acceptance_judge(
judge_key="speed",
optimization_judge=judge,
completion_response="Here is the answer.",
iteration=1,
reasoning_history="",
user_input="Tell me something.",
agent_duration_ms=None,
)
_, config, _, _ = self.handle_judge_call.call_args.args
assert "mention the duration" not in config.instructions
async def test_returns_zero_score_on_missing_acceptance_statement(self):
judge = OptimizationJudge(threshold=0.8, acceptance_statement=None)
result = await self.client._evaluate_acceptance_judge(
judge_key="broken",
optimization_judge=judge,
completion_response="Anything.",
iteration=1,
reasoning_history="",
user_input="Hello?",
)
assert result.score == 0.0
self.handle_judge_call.assert_not_called()
async def test_returns_zero_score_on_parse_failure(self):
self.handle_judge_call.return_value = OptimizationResponse(output="not json at all")
judge = OptimizationJudge(threshold=0.8, acceptance_statement="Be clear.")
result = await self.client._evaluate_acceptance_judge(
judge_key="clarity",
optimization_judge=judge,
completion_response="Clear answer.",
iteration=1,
reasoning_history="",
user_input="Explain X.",
)
assert result.score == 0.0
# ---------------------------------------------------------------------------
# _evaluate_config_judge
# ---------------------------------------------------------------------------
class TestEvaluateConfigJudge:
def setup_method(self):
self.mock_ldai = _make_ldai_client()
self.client = _make_client(self.mock_ldai)
agent_config = _make_agent_config()
self.client._agent_key = "test-agent"
self.client._agent_config = agent_config
self.client._initialize_class_members_from_config(agent_config)
self.handle_judge_call = AsyncMock(return_value=OptimizationResponse(output=JUDGE_PASS_RESPONSE))
self.client._options = _make_options(handle_judge_call=self.handle_judge_call)
def _make_raw_variation(self, enabled: bool = True) -> Dict[str, Any]:
"""Raw variation dict as returned by _client.variation for a judge flag."""
return {
"_ldMeta": {"enabled": enabled},
"messages": [
{"role": "system", "content": "You are an evaluator."},
{"role": "user", "content": "Evaluate this response."},
],
"model": {"name": "gpt-4o", "parameters": {}},
}
async def test_calls_handle_judge_call_with_correct_config_type(self):
self.mock_ldai._client.variation.return_value = self._make_raw_variation()
judge = OptimizationJudge(threshold=0.8, judge_key="ld-judge-key")
await self.client._evaluate_config_judge(
judge_key="quality",
optimization_judge=judge,
completion_response="Good answer.",
iteration=1,
reasoning_history="",
user_input="What is X?",
)
call_args = self.handle_judge_call.call_args
key, config, ctx, _ = call_args.args
assert key == "quality"
assert isinstance(config, AIJudgeCallConfig)
assert "You are an evaluator." in config.instructions
assert isinstance(ctx, OptimizationJudgeContext)
async def test_messages_has_system_and_user_turns(self):
self.mock_ldai._client.variation.return_value = self._make_raw_variation()
judge = OptimizationJudge(threshold=0.8, judge_key="ld-judge-key")
await self.client._evaluate_config_judge(
judge_key="quality",
optimization_judge=judge,
completion_response="Good answer.",
iteration=1,
reasoning_history="",
user_input="What is X?",
)
_, config, _, _ = self.handle_judge_call.call_args.args
roles = [m.role for m in config.messages]
assert roles == ["system", "user"]
async def test_messages_system_content_matches_instructions(self):
self.mock_ldai._client.variation.return_value = self._make_raw_variation()
judge = OptimizationJudge(threshold=0.8, judge_key="ld-judge-key")
await self.client._evaluate_config_judge(
judge_key="quality",
optimization_judge=judge,
completion_response="Good answer.",
iteration=1,
reasoning_history="",
user_input="What is X?",
)
_, config, _, _ = self.handle_judge_call.call_args.args
system_msg = next(m for m in config.messages if m.role == "system")
assert system_msg.content == config.instructions
async def test_messages_user_content_matches_context_user_input(self):
self.mock_ldai._client.variation.return_value = self._make_raw_variation()
judge = OptimizationJudge(threshold=0.8, judge_key="ld-judge-key")
await self.client._evaluate_config_judge(
judge_key="quality",
optimization_judge=judge,
completion_response="Good answer.",
iteration=1,
reasoning_history="",
user_input="What is X?",
)
_, config, ctx, _ = self.handle_judge_call.call_args.args
user_msg = next(m for m in config.messages if m.role == "user")
assert user_msg.content == ctx.user_input
async def test_messages_user_content_contains_ld_user_message(self):
self.mock_ldai._client.variation.return_value = self._make_raw_variation()
judge = OptimizationJudge(threshold=0.8, judge_key="ld-judge-key")
await self.client._evaluate_config_judge(
judge_key="quality",
optimization_judge=judge,
completion_response="Good answer.",
iteration=1,
reasoning_history="",
user_input="What is X?",
)
_, config, _, _ = self.handle_judge_call.call_args.args
user_msg = next(m for m in config.messages if m.role == "user")
assert "Evaluate this response." in user_msg.content
async def test_returns_zero_score_when_judge_disabled(self):
self.mock_ldai._client.variation.return_value = self._make_raw_variation(enabled=False)
judge = OptimizationJudge(threshold=0.8, judge_key="ld-judge-key")
result = await self.client._evaluate_config_judge(
judge_key="quality",
optimization_judge=judge,
completion_response="Some answer.",
iteration=1,
reasoning_history="",
user_input="What?",
)
assert result.score == 0.0
self.handle_judge_call.assert_not_called()
async def test_system_only_template_auto_generates_user_message(self):
"""When the flag template has only a system message, a user turn is synthesised."""
self.mock_ldai._client.variation.return_value = {
"_ldMeta": {"enabled": True},
"messages": [{"role": "system", "content": "You are an evaluator."}],
"model": {"name": "gpt-4o", "parameters": {}},
}
judge = OptimizationJudge(threshold=0.8, judge_key="ld-judge-key")
await self.client._evaluate_config_judge(
judge_key="quality",
optimization_judge=judge,
completion_response="The answer is 42.",
iteration=1,
reasoning_history="",
user_input="What is the answer?",
)
_, config, _, _ = self.handle_judge_call.call_args.args
user_msg = next(m for m in config.messages if m.role == "user")
assert "The answer is 42." in user_msg.content
async def test_template_variables_interpolated_into_messages(self):
"""Custom agent variables are interpolated into judge template messages."""
self.mock_ldai._client.variation.return_value = {
"_ldMeta": {"enabled": True},
"messages": [
{"role": "system", "content": "Evaluate in {{language}}."},
{"role": "user", "content": "Evaluate this response."},
],
"model": {"name": "gpt-4o", "parameters": {}},
}
judge = OptimizationJudge(threshold=0.8, judge_key="ld-judge-key")
await self.client._evaluate_config_judge(
judge_key="quality",
optimization_judge=judge,
completion_response="Answer.",
iteration=1,
reasoning_history="",
user_input="Q?",
variables={"language": "Spanish"},
)
_, config, _, _ = self.handle_judge_call.call_args.args
assert "Spanish" in config.instructions
async def test_reserved_variables_interpolated_into_template_messages(self):
"""message_history and response_to_evaluate are interpolated when present in the template."""
self.mock_ldai._client.variation.return_value = {
"_ldMeta": {"enabled": True},
"messages": [
{"role": "system", "content": "History: {{message_history}}"},
{"role": "user", "content": "Response: {{response_to_evaluate}}"},
],
"model": {"name": "gpt-4o", "parameters": {}},
}
judge = OptimizationJudge(threshold=0.8, judge_key="ld-judge-key")
await self.client._evaluate_config_judge(
judge_key="quality",
optimization_judge=judge,
completion_response="My answer.",
iteration=1,
reasoning_history="",
user_input="Q?",
)
_, config, _, _ = self.handle_judge_call.call_args.args
system_msg = next(m for m in config.messages if m.role == "system")
assert "History:" in system_msg.content
user_msg = next(m for m in config.messages if m.role == "user")
assert "My answer." in user_msg.content
async def test_agent_tools_included_without_evaluation_tool(self):
self.mock_ldai._client.variation.return_value = self._make_raw_variation()
agent_tool = ToolDefinition(name="search", description="Search", input_schema={})
judge = OptimizationJudge(threshold=0.8, judge_key="ld-judge-key")
await self.client._evaluate_config_judge(
judge_key="quality",
optimization_judge=judge,
completion_response="Answer.",
iteration=1,
reasoning_history="",
user_input="Q?",
agent_tools=[agent_tool],
)
_, config, _, _ = self.handle_judge_call.call_args.args
tools = config.model.get_parameter("tools") or []
names = [t["name"] for t in tools]
assert names == ["search"]
# ---------------------------------------------------------------------------
# _execute_agent_turn
# ---------------------------------------------------------------------------
class TestExecuteAgentTurn:
def setup_method(self):
self.agent_response = "Paris is the capital of France."
self.handle_agent_call = AsyncMock(return_value=OptimizationResponse(output=self.agent_response))
self.handle_judge_call = AsyncMock(return_value=OptimizationResponse(output=JUDGE_PASS_RESPONSE))
self.client = _make_client()
agent_config = _make_agent_config()
self.client._agent_key = "test-agent"
self.client._agent_config = agent_config
self.client._initialize_class_members_from_config(agent_config)
self.client._options = _make_options(
handle_agent_call=self.handle_agent_call,
handle_judge_call=self.handle_judge_call,
)
def _make_context(self, user_input: str = "What is the capital of France?") -> OptimizationContext:
return OptimizationContext(
scores={},
completion_response="",
current_instructions=AGENT_INSTRUCTIONS,
current_parameters={},
current_variables={"language": "English"},
current_model="gpt-4o",
user_input=user_input,
iteration=1,
)
async def test_calls_handle_agent_call_with_config_and_context(self):
ctx = self._make_context()
await self.client._execute_agent_turn(ctx, iteration=1)
self.handle_agent_call.assert_called_once()
key, config, passed_ctx, _ = self.handle_agent_call.call_args.args
assert key == "test-agent"
assert isinstance(config, AIAgentConfig)
assert passed_ctx is ctx
async def test_completion_response_stored_in_returned_context(self):
ctx = self._make_context()
result = await self.client._execute_agent_turn(ctx, iteration=1)
assert result.completion_response == self.agent_response
async def test_judge_scores_stored_in_returned_context(self):
ctx = self._make_context()
result = await self.client._execute_agent_turn(ctx, iteration=1)
assert "accuracy" in result.scores
assert result.scores["accuracy"].score == 1.0
async def test_variables_interpolated_into_agent_config_instructions(self):
ctx = self._make_context()
await self.client._execute_agent_turn(ctx, iteration=1)
_, config, _, _ = self.handle_agent_call.call_args.args
assert "{{language}}" not in config.instructions
assert "English" in config.instructions
async def test_raises_on_agent_call_failure(self):
self.handle_agent_call.side_effect = RuntimeError("LLM unavailable")
ctx = self._make_context()
with pytest.raises(RuntimeError, match="LLM unavailable"):
await self.client._execute_agent_turn(ctx, iteration=1)
# ---------------------------------------------------------------------------
# _generate_new_variation
# ---------------------------------------------------------------------------
class TestGenerateNewVariation:
def setup_method(self):
self.handle_agent_call = AsyncMock(return_value=OptimizationResponse(output=VARIATION_RESPONSE))
self.client = _make_client()
agent_config = _make_agent_config()
self.client._agent_key = "test-agent"
self.client._agent_config = agent_config
self.client._initial_instructions = AGENT_INSTRUCTIONS
self.client._initialize_class_members_from_config(agent_config)
self.client._options = _make_options(handle_agent_call=self.handle_agent_call)
async def test_updates_current_instructions(self):
await self.client._generate_new_variation(iteration=1, variables={"language": "English"})
assert self.client._current_instructions == "You are an improved assistant."
async def test_updates_current_parameters(self):
await self.client._generate_new_variation(iteration=1, variables={})
assert self.client._current_parameters == {"temperature": 0.5}
async def test_updates_current_model(self):