-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluate_fc.py
More file actions
1422 lines (1251 loc) · 57.5 KB
/
evaluate_fc.py
File metadata and controls
1422 lines (1251 loc) · 57.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
#!/usr/bin/env python3
"""
OpenRouter Function Calling Evaluation Script
Inspired by Berkeley Function Calling Leaderboard (BFCL) v4 Methodology
This script evaluates multiple LLMs hosted on OpenRouter for their function-calling
capabilities using AST-based substring matching for validation.
FEATURES:
- Best of N trials support for reliable evaluation
- Reliability metrics showing consistency across trials
- Parallel and sequential execution modes
- Comprehensive reporting with JSON and TXT outputs
- 30 unique test cases covering single_turn, multi_turn, and agentic scenarios
"""
import os
import sys
import json
import time
import asyncio
import logging
import argparse
from typing import List, Dict, Any, Optional, Tuple, Union
from dataclasses import dataclass, field, asdict
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed
import ast
import re
from collections import defaultdict
import requests
from dotenv import load_dotenv
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler('evaluation.log')
]
)
logger = logging.getLogger(__name__)
# Load environment variables
load_dotenv()
# ============================================================================
# CONFIGURATION - Target Models
# ============================================================================
DEFAULT_MODELS = [
"x-ai/grok-4.1-fast",
"google/gemini-3-flash-preview",
"qwen/qwen3.5-27b",
"x-ai/grok-4.20-beta",
"moonshotai/kimi-k2.5",
"qwen/qwen3.5-122b-a10b",
"minimax/minimax-m2.5",
"google/gemini-3.1-flash-lite-preview",
"qwen/qwen3.5-35b-a3b",
"qwen/qwen3.5-flash-02-23",
"anthropic/claude-haiku-4.5"
]
# ============================================================================
# DATA CLASSES
# ============================================================================
@dataclass
class TestCase:
"""Represents a single test case for function calling evaluation."""
id: str
category: str
subcategory: str
description: str
tools: List[Dict[str, Any]]
messages: List[Dict[str, str]]
expected_calls: List[Dict[str, Any]]
difficulty: str = "medium"
@dataclass
class TrialResult:
"""Represents the result of a single trial."""
trial_number: int
passed: bool
response: Optional[str]
parsed_calls: List[Dict[str, Any]]
error: Optional[str] = None
latency_ms: float = 0.0
tokens_used: int = 0
@dataclass
class TestResult:
"""Represents the result of a single test case execution with multiple trials."""
test_id: str
category: str
subcategory: str
model: str
passed: bool # Best of N: True if at least one trial passed
reliability: float # Percentage of trials that passed
trials: List[TrialResult] # All trial results
expected_calls: List[Dict[str, Any]]
error: Optional[str] = None
avg_latency_ms: float = 0.0
total_tokens: int = 0
@dataclass
class ModelScore:
"""Aggregated scores for a model across all test categories."""
model: str
overall_accuracy: float
overall_reliability: float # Average reliability across all tests
category_scores: Dict[str, float]
category_reliability: Dict[str, float]
subcategory_scores: Dict[str, float]
subcategory_reliability: Dict[str, float]
total_tests: int
passed_tests: int
avg_latency_ms: float
total_tokens: int
# ============================================================================
# BFCL V4 TEST SUITE - 30 UNIQUE TEST CASES
# ============================================================================
class BFCLTestSuite:
"""
Implements 30 unique test cases inspired by BFCL v4 methodology.
Covers single_turn (simple, multiple, parallel, parallel_multiple, relevance),
multi_turn (base, missing_params, missing_functions, long_context),
and agentic (web_search, memory, format_sensitivity) categories.
"""
def __init__(self):
self.test_cases: List[TestCase] = []
self._generate_all_tests()
def _generate_all_tests(self):
"""Generate all 30 test cases across categories."""
self._generate_single_turn_tests() # 16 tests
self._generate_multi_turn_tests() # 8 tests
self._generate_agentic_tests() # 6 tests
def _generate_single_turn_tests(self):
"""Generate 16 single-turn function calling tests."""
# === SIMPLE FUNCTION CALLING (4 tests) ===
simple_tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location"]
}
}
}
]
self.test_cases.append(TestCase(
id="single_simple_001",
category="single_turn",
subcategory="simple",
description="Simple single function call with required parameter",
tools=simple_tools,
messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
expected_calls=[{"name": "get_weather", "arguments": {"location": "Tokyo"}}],
difficulty="easy"
))
self.test_cases.append(TestCase(
id="single_simple_002",
category="single_turn",
subcategory="simple",
description="Simple function call with optional parameter specified",
tools=simple_tools,
messages=[{"role": "user", "content": "What's the weather in London in celsius?"}],
expected_calls=[{"name": "get_weather", "arguments": {"location": "London", "unit": "celsius"}}],
difficulty="easy"
))
self.test_cases.append(TestCase(
id="single_simple_003",
category="single_turn",
subcategory="simple",
description="Simple function call with different unit parameter",
tools=simple_tools,
messages=[{"role": "user", "content": "What's the weather in New York in fahrenheit?"}],
expected_calls=[{"name": "get_weather", "arguments": {"location": "New York", "unit": "fahrenheit"}}],
difficulty="easy"
))
self.test_cases.append(TestCase(
id="single_simple_004",
category="single_turn",
subcategory="simple",
description="Simple function call with city name containing spaces",
tools=simple_tools,
messages=[{"role": "user", "content": "What's the weather in San Francisco?"}],
expected_calls=[{"name": "get_weather", "arguments": {"location": "San Francisco"}}],
difficulty="easy"
))
# === MULTIPLE FUNCTION SELECTION (4 tests) ===
multi_tools = [
{
"type": "function",
"function": {
"name": "search_products",
"description": "Search for products in catalog",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"},
"category": {"type": "string"}
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Check status of an order",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string"}
},
"required": ["order_id"]
}
}
},
{
"type": "function",
"function": {
"name": "cancel_order",
"description": "Cancel an existing order",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string"},
"reason": {"type": "string"}
},
"required": ["order_id"]
}
}
}
]
self.test_cases.append(TestCase(
id="single_multiple_001",
category="single_turn",
subcategory="multiple",
description="Select correct function from multiple options - order status",
tools=multi_tools,
messages=[{"role": "user", "content": "Where is my order ORD-12345?"}],
expected_calls=[{"name": "get_order_status", "arguments": {"order_id": "ORD-12345"}}],
difficulty="medium"
))
self.test_cases.append(TestCase(
id="single_multiple_002",
category="single_turn",
subcategory="multiple",
description="Select different function from same toolset - product search",
tools=multi_tools,
messages=[{"role": "user", "content": "Find me some wireless headphones"}],
expected_calls=[{"name": "search_products", "arguments": {"query": "wireless headphones"}}],
difficulty="medium"
))
self.test_cases.append(TestCase(
id="single_multiple_003",
category="single_turn",
subcategory="multiple",
description="Select cancel function with optional reason parameter",
tools=multi_tools,
messages=[{"role": "user", "content": "Cancel order ORD-67890 because I changed my mind"}],
expected_calls=[{"name": "cancel_order", "arguments": {"order_id": "ORD-67890", "reason": "I changed my mind"}}],
difficulty="medium"
))
self.test_cases.append(TestCase(
id="single_multiple_004",
category="single_turn",
subcategory="multiple",
description="Select product search with category filter",
tools=multi_tools,
messages=[{"role": "user", "content": "Search for laptops in the electronics category"}],
expected_calls=[{"name": "search_products", "arguments": {"query": "laptops", "category": "electronics"}}],
difficulty="medium"
))
# === PARALLEL FUNCTION CALLING (4 tests) ===
self.test_cases.append(TestCase(
id="single_parallel_001",
category="single_turn",
subcategory="parallel",
description="Call same function multiple times in parallel - 3 cities",
tools=simple_tools,
messages=[{"role": "user", "content": "What's the weather in Tokyo, London, and New York?"}],
expected_calls=[
{"name": "get_weather", "arguments": {"location": "Tokyo"}},
{"name": "get_weather", "arguments": {"location": "London"}},
{"name": "get_weather", "arguments": {"location": "New York"}}
],
difficulty="medium"
))
self.test_cases.append(TestCase(
id="single_parallel_002",
category="single_turn",
subcategory="parallel",
description="Call same function multiple times in parallel - 2 cities",
tools=simple_tools,
messages=[{"role": "user", "content": "What's the weather in Paris and Berlin?"}],
expected_calls=[
{"name": "get_weather", "arguments": {"location": "Paris"}},
{"name": "get_weather", "arguments": {"location": "Berlin"}}
],
difficulty="medium"
))
self.test_cases.append(TestCase(
id="single_parallel_003",
category="single_turn",
subcategory="parallel",
description="Call same function multiple times in parallel - 4 cities",
tools=simple_tools,
messages=[{"role": "user", "content": "What's the weather in Sydney, Melbourne, Brisbane, and Perth?"}],
expected_calls=[
{"name": "get_weather", "arguments": {"location": "Sydney"}},
{"name": "get_weather", "arguments": {"location": "Melbourne"}},
{"name": "get_weather", "arguments": {"location": "Brisbane"}},
{"name": "get_weather", "arguments": {"location": "Perth"}}
],
difficulty="hard"
))
# === PARALLEL MULTIPLE FUNCTION CALLING (4 tests) ===
parallel_multi_tools = [
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "Get current time for a timezone",
"parameters": {
"type": "object",
"properties": {
"timezone": {"type": "string"}
},
"required": ["timezone"]
}
}
},
{
"type": "function",
"function": {
"name": "send_email",
"description": "Send an email",
"parameters": {
"type": "object",
"properties": {
"to": {"type": "string"},
"subject": {"type": "string"},
"body": {"type": "string"}
},
"required": ["to", "subject", "body"]
}
}
}
]
self.test_cases.append(TestCase(
id="single_parallel_multi_001",
category="single_turn",
subcategory="parallel_multiple",
description="Call different functions in parallel - email and time",
tools=parallel_multi_tools,
messages=[{"role": "user", "content": "Send an email to john@example.com about the meeting, and also tell me the current time in Tokyo"}],
expected_calls=[
{"name": "send_email", "arguments": {"to": "john@example.com", "subject": "Meeting", "body": "About the meeting"}},
{"name": "get_current_time", "arguments": {"timezone": "Tokyo"}}
],
difficulty="hard"
))
self.test_cases.append(TestCase(
id="single_parallel_multi_002",
category="single_turn",
subcategory="parallel_multiple",
description="Call different functions in parallel - time for multiple zones",
tools=parallel_multi_tools,
messages=[{"role": "user", "content": "What time is it in New York and London? Also email admin@example.com saying the report is ready."}],
expected_calls=[
{"name": "get_current_time", "arguments": {"timezone": "New York"}},
{"name": "get_current_time", "arguments": {"timezone": "London"}},
{"name": "send_email", "arguments": {"to": "admin@example.com", "subject": "Report Ready", "body": "The report is ready"}}
],
difficulty="hard"
))
self.test_cases.append(TestCase(
id="single_parallel_multi_003",
category="single_turn",
subcategory="parallel_multiple",
description="Call different functions in parallel - single email and time",
tools=parallel_multi_tools,
messages=[{"role": "user", "content": "Email hello@example.com with subject 'Hello' and body 'World', and get time in UTC"}],
expected_calls=[
{"name": "send_email", "arguments": {"to": "hello@example.com", "subject": "Hello", "body": "World"}},
{"name": "get_current_time", "arguments": {"timezone": "UTC"}}
],
difficulty="hard"
))
# === RELEVANCE DETECTION (4 tests) ===
self.test_cases.append(TestCase(
id="single_relevance_001",
category="single_turn",
subcategory="relevance",
description="Should NOT call any function - irrelevant query (joke)",
tools=simple_tools,
messages=[{"role": "user", "content": "Tell me a joke about programming"}],
expected_calls=[],
difficulty="easy"
))
self.test_cases.append(TestCase(
id="single_relevance_002",
category="single_turn",
subcategory="relevance",
description="Should call function - relevant query (weather)",
tools=simple_tools,
messages=[{"role": "user", "content": "What's the temperature in Paris?"}],
expected_calls=[{"name": "get_weather", "arguments": {"location": "Paris"}}],
difficulty="easy"
))
self.test_cases.append(TestCase(
id="single_relevance_003",
category="single_turn",
subcategory="relevance",
description="Should NOT call any function - irrelevant query (poem)",
tools=simple_tools,
messages=[{"role": "user", "content": "Write a poem about the ocean"}],
expected_calls=[],
difficulty="easy"
))
self.test_cases.append(TestCase(
id="single_relevance_004",
category="single_turn",
subcategory="relevance",
description="Should call function - relevant query (weather with unit)",
tools=simple_tools,
messages=[{"role": "user", "content": "Is it hot in Dubai right now?"}],
expected_calls=[{"name": "get_weather", "arguments": {"location": "Dubai"}}],
difficulty="easy"
))
def _generate_multi_turn_tests(self):
"""Generate 8 multi-turn conversation tests."""
# === BASE MULTI-TURN (2 tests) ===
booking_tools = [
{
"type": "function",
"function": {
"name": "search_flights",
"description": "Search for available flights",
"parameters": {
"type": "object",
"properties": {
"origin": {"type": "string"},
"destination": {"type": "string"},
"date": {"type": "string", "format": "date"}
},
"required": ["origin", "destination", "date"]
}
}
},
{
"type": "function",
"function": {
"name": "book_flight",
"description": "Book a selected flight",
"parameters": {
"type": "object",
"properties": {
"flight_id": {"type": "string"},
"passenger_name": {"type": "string"},
"seat_class": {"type": "string", "enum": ["economy", "business", "first"]}
},
"required": ["flight_id", "passenger_name"]
}
}
}
]
self.test_cases.append(TestCase(
id="multi_base_001",
category="multi_turn",
subcategory="base",
description="Multi-turn: search then book flight",
tools=booking_tools,
messages=[
{"role": "user", "content": "Find flights from NYC to London on 2024-12-25"},
{"role": "assistant", "content": "", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "search_flights", "arguments": '{"origin": "NYC", "destination": "London", "date": "2024-12-25"}'}}]},
{"role": "tool", "tool_call_id": "call_1", "content": '{"flights": [{"id": "BA112", "time": "10:00"}, {"id": "BA114", "time": "14:00"}]}'},
{"role": "user", "content": "Book the 10:00 flight for John Doe in business class"}
],
expected_calls=[{"name": "book_flight", "arguments": {"flight_id": "BA112", "passenger_name": "John Doe", "seat_class": "business"}}],
difficulty="medium"
))
self.test_cases.append(TestCase(
id="multi_base_002",
category="multi_turn",
subcategory="base",
description="Multi-turn: search then book flight - economy class",
tools=booking_tools,
messages=[
{"role": "user", "content": "Find flights from LA to Tokyo on 2024-12-20"},
{"role": "assistant", "content": "", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "search_flights", "arguments": '{"origin": "LA", "destination": "Tokyo", "date": "2024-12-20"}'}}]},
{"role": "tool", "tool_call_id": "call_1", "content": '{"flights": [{"id": "JL001", "time": "11:00"}, {"id": "JL002", "time": "16:00"}]}'},
{"role": "user", "content": "Book the 16:00 flight for Jane Smith"}
],
expected_calls=[{"name": "book_flight", "arguments": {"flight_id": "JL002", "passenger_name": "Jane Smith"}}],
difficulty="medium"
))
# === MISSING PARAMETERS (2 tests) ===
self.test_cases.append(TestCase(
id="multi_mp_001",
category="multi_turn",
subcategory="missing_params",
description="Multi-turn: missing parameter requires clarification - flight booking",
tools=booking_tools,
messages=[
{"role": "user", "content": "Book a flight for me"}
],
expected_calls=[],
difficulty="medium"
))
self.test_cases.append(TestCase(
id="multi_mp_002",
category="multi_turn",
subcategory="missing_params",
description="Multi-turn: missing parameter requires clarification - search flights",
tools=booking_tools,
messages=[
{"role": "user", "content": "Find me some flights"}
],
expected_calls=[],
difficulty="medium"
))
# === MISSING FUNCTIONS (2 tests) ===
self.test_cases.append(TestCase(
id="multi_mf_001",
category="multi_turn",
subcategory="missing_functions",
description="Multi-turn: unavailable function requires clarification - hotel",
tools=booking_tools,
messages=[
{"role": "user", "content": "Cancel my hotel reservation"}
],
expected_calls=[],
difficulty="medium"
))
self.test_cases.append(TestCase(
id="multi_mf_002",
category="multi_turn",
subcategory="missing_functions",
description="Multi-turn: unavailable function requires clarification - car rental",
tools=booking_tools,
messages=[
{"role": "user", "content": "Rent a car for me in Miami"}
],
expected_calls=[],
difficulty="medium"
))
def _generate_agentic_tests(self):
"""Generate 6 agentic capability tests."""
# === WEB SEARCH (2 tests) ===
web_search_tools = [
{
"type": "function",
"function": {
"name": "web_search",
"description": "Search the web for information",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"}
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "fetch_webpage",
"description": "Fetch content from a specific webpage URL",
"parameters": {
"type": "object",
"properties": {
"url": {"type": "string", "description": "Webpage URL"}
},
"required": ["url"]
}
}
}
]
self.test_cases.append(TestCase(
id="agentic_web_001",
category="agentic",
subcategory="web_search",
description="Web search: single search query",
tools=web_search_tools,
messages=[{"role": "user", "content": "Search for information about Python programming language"}],
expected_calls=[{"name": "web_search", "arguments": {"query": "Python programming language"}}],
difficulty="easy"
))
self.test_cases.append(TestCase(
id="agentic_web_002",
category="agentic",
subcategory="web_search",
description="Web search: current events query",
tools=web_search_tools,
messages=[{"role": "user", "content": "Search for latest news about artificial intelligence"}],
expected_calls=[{"name": "web_search", "arguments": {"query": "latest news artificial intelligence"}}],
difficulty="easy"
))
# === MEMORY (2 tests) ===
memory_tools = [
{
"type": "function",
"function": {
"name": "store_memory",
"description": "Store information in memory",
"parameters": {
"type": "object",
"properties": {
"key": {"type": "string"},
"value": {"type": "string"}
},
"required": ["key", "value"]
}
}
},
{
"type": "function",
"function": {
"name": "retrieve_memory",
"description": "Retrieve information from memory",
"parameters": {
"type": "object",
"properties": {
"key": {"type": "string"}
},
"required": ["key"]
}
}
}
]
self.test_cases.append(TestCase(
id="agentic_memory_001",
category="agentic",
subcategory="memory",
description="Memory: store and retrieve information - favorite color",
tools=memory_tools,
messages=[
{"role": "user", "content": "Remember that my favorite color is blue"},
{"role": "assistant", "content": "", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "store_memory", "arguments": '{"key": "favorite_color", "value": "blue"}'}}]},
{"role": "tool", "tool_call_id": "call_1", "content": '{"status": "stored"}'},
{"role": "user", "content": "What is my favorite color?"}
],
expected_calls=[{"name": "retrieve_memory", "arguments": {"key": "favorite_color"}}],
difficulty="medium"
))
self.test_cases.append(TestCase(
id="agentic_memory_002",
category="agentic",
subcategory="memory",
description="Memory: store and retrieve information - phone number",
tools=memory_tools,
messages=[
{"role": "user", "content": "Remember my phone number is 555-1234"},
{"role": "assistant", "content": "", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "store_memory", "arguments": '{"key": "phone_number", "value": "555-1234"}'}}]},
{"role": "tool", "tool_call_id": "call_1", "content": '{"status": "stored"}'},
{"role": "user", "content": "What is my phone number?"}
],
expected_calls=[{"name": "retrieve_memory", "arguments": {"key": "phone_number"}}],
difficulty="medium"
))
# === FORMAT SENSITIVITY (2 tests) ===
format_tools = [
{
"type": "function",
"function": {
"name": "execute_sql",
"description": "Execute SQL query on database",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"}
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "call_rest_api",
"description": "Make REST API call",
"parameters": {
"type": "object",
"properties": {
"url": {"type": "string"},
"method": {"type": "string", "enum": ["GET", "POST", "PUT", "DELETE"]},
"headers": {"type": "object"},
"body": {"type": "object"}
},
"required": ["url", "method"]
}
}
}
]
self.test_cases.append(TestCase(
id="agentic_format_001",
category="agentic",
subcategory="format_sensitivity",
description="Format sensitivity: SQL query generation - users",
tools=format_tools,
messages=[{"role": "user", "content": "Get all users from the database who signed up in the last 30 days"}],
expected_calls=[{"name": "execute_sql", "arguments": {"query": "SELECT * FROM users WHERE signup_date >= DATE_SUB(NOW(), INTERVAL 30 DAY)"}}],
difficulty="hard"
))
self.test_cases.append(TestCase(
id="agentic_format_002",
category="agentic",
subcategory="format_sensitivity",
description="Format sensitivity: REST API call generation",
tools=format_tools,
messages=[{"role": "user", "content": "Make a GET request to https://api.example.com/users"}],
expected_calls=[{"name": "call_rest_api", "arguments": {"url": "https://api.example.com/users", "method": "GET"}}],
difficulty="hard"
))
def get_tests_by_category(self, category: Optional[str] = None) -> List[TestCase]:
"""Get test cases filtered by category."""
if category is None:
return self.test_cases
return [t for t in self.test_cases if t.category == category]
def get_all_tests(self) -> List[TestCase]:
"""Get all test cases."""
return self.test_cases
# ============================================================================
# OPENROUTER API CLIENT
# ============================================================================
class OpenRouterClient:
"""Client for OpenRouter API with function calling support."""
BASE_URL = "https://openrouter.ai/api/v1"
def __init__(self, api_key: Optional[str] = None):
self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")
if not self.api_key:
raise ValueError("OpenRouter API key required. Set OPENROUTER_API_KEY env var.")
self.session = requests.Session()
self.session.headers.update({
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
"HTTP-Referer": "https://localhost",
"X-Title": "Function Calling Evaluation"
})
def chat_completion(
self,
model: str,
messages: List[Dict[str, str]],
tools: Optional[List[Dict]] = None,
temperature: float = 0.0,
max_tokens: int = 4096
) -> Dict[str, Any]:
"""Send chat completion request with optional function calling."""
payload = {
"model": model,
"messages": messages,
"temperature": temperature,
"max_tokens": max_tokens
}
if tools:
payload["tools"] = tools
payload["tool_choice"] = "auto"
try:
response = self.session.post(
f"{self.BASE_URL}/chat/completions",
json=payload,
timeout=120
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
logger.error(f"API request failed: {e}")
raise
def extract_tool_calls(self, response: Dict[str, Any]) -> List[Dict[str, Any]]:
"""Extract tool calls from API response."""
tool_calls = []
if "choices" in response and len(response["choices"]) > 0:
choice = response["choices"][0]
if "message" in choice and "tool_calls" in choice["message"]:
for tc in choice["message"]["tool_calls"]:
if tc.get("type") == "function":
try:
args = json.loads(tc["function"]["arguments"])
except (json.JSONDecodeError, KeyError):
args = tc["function"].get("arguments", {})
if isinstance(args, str):
try:
args = json.loads(args)
except:
args = {}
tool_calls.append({
"name": tc["function"]["name"],
"arguments": args
})
return tool_calls
# ============================================================================
# EVALUATION LOGIC - AST-Based Validation
# ============================================================================
class ASTValidator:
"""Validates function calls using AST-based substring matching."""
@staticmethod
def normalize_value(value: Any) -> Any:
"""Normalize a value for comparison."""
if isinstance(value, str):
return value.strip().lower()
elif isinstance(value, (list, tuple)):
return [ASTValidator.normalize_value(v) for v in value]
elif isinstance(value, dict):
return {k.lower() if isinstance(k, str) else k: ASTValidator.normalize_value(v)
for k, v in value.items()}
return value
@staticmethod
def validate_arguments(expected: Dict[str, Any], actual: Dict[str, Any]) -> bool:
"""Validate that actual arguments match expected."""
expected_norm = ASTValidator.normalize_value(expected)
actual_norm = ASTValidator.normalize_value(actual)
for key, exp_val in expected_norm.items():
if key not in actual_norm:
return False
act_val = actual_norm[key]
if isinstance(exp_val, list) and isinstance(act_val, list):
if sorted(exp_val) != sorted(act_val):
return False
elif exp_val != act_val:
return False
return True
@staticmethod
def evaluate_call(expected: Dict[str, Any], actual: Dict[str, Any]) -> bool:
"""Evaluate if a single function call matches expected."""
if expected.get("name") != actual.get("name"):
return False
expected_args = expected.get("arguments", {})
actual_args = actual.get("arguments", {})
return ASTValidator.validate_arguments(expected_args, actual_args)
@staticmethod
def evaluate_test(expected_calls: List[Dict], actual_calls: List[Dict]) -> Tuple[bool, str]:
"""Evaluate a test case against expected calls."""
if not expected_calls:
if actual_calls:
return False, f"Expected no calls but got {len(actual_calls)} call(s)"
return True, "Correctly abstained from calling any function"
if len(expected_calls) != len(actual_calls):
return False, f"Expected {len(expected_calls)} call(s), got {len(actual_calls)}"
for i, (expected, actual) in enumerate(zip(expected_calls, actual_calls)):
if not ASTValidator.evaluate_call(expected, actual):
exp_str = json.dumps(expected)
act_str = json.dumps(actual)
return False, f"Call {i+1} mismatch: expected {exp_str}, got {act_str}"
return True, "All function calls match expected"
# ============================================================================
# EVALUATION EXECUTOR
# ============================================================================
class EvaluationExecutor:
"""Executes test cases against models with sequential or parallel support."""
def __init__(self, client: OpenRouterClient, max_workers: int = 5, trials: int = 3):
self.client = client
self.max_workers = max_workers
self.trials = trials
self.validator = ASTValidator()
def run_single_trial(self, model: str, test_case: TestCase, trial_number: int) -> TrialResult:
"""Run a single trial for a test case."""
start_time = time.time()
try:
api_messages = []
for msg in test_case.messages:
if msg.get("role") in ["user", "assistant", "system"]:
api_msg = {"role": msg["role"], "content": msg.get("content", "")}
api_messages.append(api_msg)
response = self.client.chat_completion(
model=model,
messages=api_messages,
tools=test_case.tools,
temperature=0.0
)
latency_ms = (time.time() - start_time) * 1000
parsed_calls = self.client.extract_tool_calls(response)
tokens_used = response.get("usage", {}).get("total_tokens", 0)
raw_content = ""
if "choices" in response and len(response["choices"]) > 0:
raw_content = response["choices"][0].get("message", {}).get("content", "")
passed, message = self.validator.evaluate_test(test_case.expected_calls, parsed_calls)
return TrialResult(
trial_number=trial_number,
passed=passed,
response=raw_content,
parsed_calls=parsed_calls,
error=None if passed else message,
latency_ms=latency_ms,
tokens_used=tokens_used
)
except Exception as e:
latency_ms = (time.time() - start_time) * 1000
logger.error(f"Error in trial {trial_number} for test {test_case.id} with model {model}: {e}")
return TrialResult(
trial_number=trial_number,
passed=False,
response=None,
parsed_calls=[],
error=str(e),
latency_ms=latency_ms,
tokens_used=0
)