-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathABxJudge.py
2472 lines (2190 loc) · 137 KB
/
ABxJudge.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import os
import venv
import subprocess
import signal # Added for CLI stop handling
# --- Venv Setup ---
# Determine if we need to set up or reactivate the virtual environment
VENV_DIR = ".venv"
REQUIRED_PACKAGES = [
"gradio",
"pandas",
"requests",
"tenacity",
"Pillow", # For image handling (needed for dummy image in CLI test)
]
def ensure_venv():
"""Checks for venv, creates/installs if needed, and re-executes if not active."""
venv_path = os.path.abspath(VENV_DIR)
# Check if the current Python executable is from the target venv
is_in_venv = sys.prefix == venv_path
venv_exists = os.path.isdir(venv_path)
if is_in_venv:
# Already running in the correct venv, proceed
print(f"Running inside the '{VENV_DIR}' virtual environment.")
return True # Indicate we are ready to proceed
print(f"Not running inside the target '{VENV_DIR}' virtual environment.")
if not venv_exists:
print(f"Creating virtual environment in '{venv_path}'...")
try:
venv.create(venv_path, with_pip=True)
print("Virtual environment created successfully.")
except Exception as e:
print(f"Error creating virtual environment: {e}", file=sys.stderr)
sys.exit(1) # Exit if creation fails
# Determine the Python executable path within the venv
if sys.platform == "win32":
python_executable = os.path.join(venv_path, "Scripts", "python.exe")
pip_executable = os.path.join(venv_path, "Scripts", "pip.exe")
else:
python_executable = os.path.join(venv_path, "bin", "python")
pip_executable = os.path.join(venv_path, "bin", "pip")
if not os.path.exists(python_executable):
print(f"Error: Python executable not found at '{python_executable}'. Venv creation might have failed.", file=sys.stderr)
sys.exit(1)
if not os.path.exists(pip_executable):
print(f"Error: Pip executable not found at '{pip_executable}'. Venv creation might have failed.", file=sys.stderr)
sys.exit(1)
# Install requirements into the venv using pip from the venv
print(f"Installing/checking required packages in '{venv_path}'...")
install_command = [pip_executable, "install"] + REQUIRED_PACKAGES
try:
# Run pip install, capture output for clarity/debugging
result = subprocess.run(install_command, check=True, capture_output=True, text=True, encoding='utf-8')
print("Packages installed/verified successfully.")
# print(result.stdout) # Uncomment to see pip output
if result.stderr:
# Show pip's stderr for warnings etc.
print("--- pip stderr ---\n", result.stderr, "\n--- end pip stderr ---")
except subprocess.CalledProcessError as e:
print(f"Error installing packages using command: {' '.join(e.cmd)}", file=sys.stderr)
print(f"Pip stdout:\n{e.stdout}", file=sys.stderr)
print(f"Pip stderr:\n{e.stderr}", file=sys.stderr)
sys.exit(1) # Exit if installation fails
except Exception as e:
print(f"An unexpected error occurred during package installation: {e}", file=sys.stderr)
sys.exit(1)
# Re-execute the script using the venv's Python interpreter
print(f"\nRestarting script using Python from '{venv_path}'...\n{'='*20}\n")
script_path = os.path.abspath(sys.argv[0])
# os.execv replaces the current process, inheriting stdio etc.
# Arguments must include the executable name as argv[0] for the new process
try:
os.execv(python_executable, [python_executable, script_path] + sys.argv[1:])
# If execv is successful, this line is never reached
except OSError as e:
print(f"Error restarting script with '{python_executable}': {e}", file=sys.stderr)
# Fallback attempt with subprocess if execv fails (less ideal)
print("Attempting restart with subprocess as fallback...")
try:
subprocess.check_call([python_executable, script_path] + sys.argv[1:])
sys.exit(0) # Exit cleanly if subprocess worked
except Exception as sub_e:
print(f"Subprocess restart also failed: {sub_e}", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Unexpected error during script restart: {e}", file=sys.stderr)
sys.exit(1)
# This should not be reached if re-execution happens
return False # Indicate re-execution was attempted
# --- Original Script Imports (ensure they are accessible after venv check) ---
# It's generally okay to keep imports here, as the script restarts if not in venv
import gradio as gr
import json
import logging
import time
import pandas as pd
# import os # Already imported above
import re
import requests
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple, Union
from tenacity import retry, stop_after_attempt, wait_exponential
import csv
import io
import tempfile # Added for JSONL download
from urllib.parse import urlparse
import base64
import mimetypes
# import signal # Already imported above
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger("model_tester")
@dataclass
class ModelEndpoint:
"""Simple model endpoint configuration."""
name: str
api_url: str
api_key: Optional[str] # API key can be optional (e.g., for local Ollama)
model_id: str
max_tokens: int = 1024
temperature: float = 0.0
file_upload_method: str = "JSON (Embedded Data)" # Options: "JSON (Embedded Data)", "Multipart Form Data"
def to_dict(self):
"""Convert to dictionary."""
return {
"name": self.name,
"api_url": self.api_url,
"model_id": self.model_id,
"max_tokens": self.max_tokens,
"temperature": self.temperature,
}
@dataclass
class TestCase:
"""Test case containing a key to query and actual value for evaluation."""
key: str # The input/prompt for the model
value: str # The reference value/ground truth
image_path_or_url: Optional[str] = None # Path or URL to an image for multimodal input
id: Optional[str] = None # Unique ID for the test case
@dataclass
class ModelResponse:
"""Model response for a test case."""
test_id: str
model_name: str
output: str
latency: float
@dataclass
class EvaluationResult:
"""Evaluation result from the LM judge."""
test_id: str
champion_output: str
challenger_output: str
winner: str # "MODEL_A_WINS", "MODEL_B_WINS", or "TIE" (extracted from reasoning)
confidence: float # Extracted confidence score (e.g., 4/5 -> 0.8)
reasoning: str # Full response from the judge model
# Global preprocessing settings (can be updated through UI)
PREPROCESS_ENABLED = True
MAX_LENGTH = 8000
REMOVE_SPECIAL_CHARS = True
NORMALIZE_WHITESPACE = True
# CSV preprocessing settings (specific to CSV format)
DETECT_DELIMITER = True
FIX_QUOTES = True
REMOVE_CONTROL_CHARS = True
NORMALIZE_NEWLINES = True
SKIP_BAD_LINES = True
SHOW_SAMPLE = True # Show sample data after loading & preprocessing
# Global flag to signal stopping the test run
STOP_REQUESTED = False
# --- Text Preprocessing Function ---
def preprocess_text(text, max_length=None, remove_special_chars=None, normalize_whitespace=None):
"""
Preprocess text (key or value) before using in prompts or comparisons.
- Truncate to prevent token limits
- Remove problematic characters
- Normalize whitespace
"""
# Use global settings if not specified
if max_length is None: max_length = MAX_LENGTH
if remove_special_chars is None: remove_special_chars = REMOVE_SPECIAL_CHARS
if normalize_whitespace is None: normalize_whitespace = NORMALIZE_WHITESPACE
# Skip preprocessing if disabled globally
if not PREPROCESS_ENABLED:
return str(text) if text is not None else ""
if text is None: return ""
text = str(text) # Ensure it's a string
# Truncate
if len(text) > max_length:
text = text[:max_length] + "... [truncated]"
if remove_special_chars:
# Remove control characters and other potentially problematic characters
text = re.sub(r'[\x00-\x1F\x7F-\x9F]', '', text)
# Remove any XML/HTML-like tags that might interfere
text = re.sub(r'<[^>]+>', '', text)
if normalize_whitespace:
# Normalize whitespace (multiple spaces, tabs, newlines to single space)
text = re.sub(r'\s+', ' ', text)
# But preserve paragraph breaks for readability (optional, maybe confusing)
# text = re.sub(r'\n\s*\n', '\n\n', text)
text = text.strip()
return text
# --- Model Runner Class ---
class ModelRunner:
"""Handles model API calls."""
def __init__(self, endpoint: ModelEndpoint, prompt_template: str):
self.endpoint = endpoint
self.prompt_template = prompt_template
def _load_and_encode_file(self, file_path_or_url: str) -> Tuple[Optional[str], Optional[str]]:
"""Loads file from path/URL, base64 encodes it, and returns (base64_string, mime_type) or (None, None)."""
try:
file_bytes = None
if urlparse(file_path_or_url).scheme in ['http', 'https']:
logger.info(f"Downloading file from URL: {file_path_or_url}")
response = requests.get(file_path_or_url, stream=True, timeout=20) # Increased timeout
response.raise_for_status()
file_bytes = response.content
logger.info(f"Successfully downloaded {len(file_bytes)} bytes from URL.")
# Try to get mime type from headers first
mime_type = response.headers.get('content-type')
else:
logger.info(f"Reading file from local path: {file_path_or_url}")
if not os.path.exists(file_path_or_url):
raise FileNotFoundError(f"File not found at path: {file_path_or_url}")
with open(file_path_or_url, "rb") as f:
file_bytes = f.read()
mime_type, _ = mimetypes.guess_type(file_path_or_url)
if not file_bytes:
raise ValueError("Failed to load file bytes.")
# Use application/octet-stream as a generic default if type cannot be guessed
mime_type = mime_type or 'application/octet-stream'
base64_data = base64.b64encode(file_bytes).decode('utf-8')
logger.info(f"Successfully encoded file to base64. Mime type: {mime_type}")
logger.info(f"Successfully loaded and encoded file from {file_path_or_url[:50]}... Type: {mime_type}, Size: {len(base64_data)} chars base64")
return base64_data, mime_type
except FileNotFoundError:
logger.error(f"File not found: {file_path_or_url}")
return None, None
except requests.exceptions.RequestException as e:
logger.error(f"Failed to download file from URL {file_path_or_url}: {e}")
return None, None
except Exception as e:
logger.error(f"Failed to load or encode file {file_path_or_url}: {e}")
return None, None
def _prepare_base64_data(self, file_path_or_url: str) -> Tuple[Optional[str], Optional[str]]:
"""
Loads file from path/URL, determines mime type, base64 encodes it.
Returns (base64_string, mime_type) or (None, None) on error.
(This is essentially the same logic as the original _load_and_encode_file)
"""
# Re-using the logic from _load_and_encode_file for now.
# Consider consolidating later if _load_and_encode_file is removed.
return self._load_and_encode_file(file_path_or_url)
def _prepare_local_file_path(self, file_path_or_url: str) -> Optional[str]:
"""
Ensures a local file path exists for the given input.
If input is a URL, downloads it to a temporary file.
Returns the local path or None on error. Tracks temp files for cleanup.
"""
try:
parsed_url = urlparse(file_path_or_url)
if parsed_url.scheme in ['http', 'https']:
logger.info(f"Downloading URL for multipart upload: {file_path_or_url}")
response = requests.get(file_path_or_url, stream=True, timeout=30) # Increased timeout for downloads
response.raise_for_status()
# Create a temporary file
# Suffix might help identify the file type, but not strictly necessary
suffix = os.path.splitext(parsed_url.path)[1]
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=suffix) # Keep file after close
with temp_file:
for chunk in response.iter_content(chunk_size=8192):
temp_file.write(chunk)
local_path = temp_file.name
logger.info(f"Downloaded URL to temporary file: {local_path}")
# Track temporary files for cleanup (needs instance variable)
if not hasattr(self, '_temp_files'):
self._temp_files = []
self._temp_files.append(local_path)
return local_path
else:
# It's already a local path, verify it exists
if os.path.exists(file_path_or_url):
logger.info(f"Using existing local file path for multipart: {file_path_or_url}")
return file_path_or_url
else:
logger.error(f"Local file path not found: {file_path_or_url}")
return None
except requests.exceptions.RequestException as e:
logger.error(f"Failed to download URL {file_path_or_url} for multipart: {e}")
return None
except Exception as e:
logger.error(f"Error preparing local file path {file_path_or_url}: {e}")
return None
def _cleanup_temp_files(self):
"""Removes any temporary files created during URL downloads."""
if hasattr(self, '_temp_files'):
for temp_path in self._temp_files:
try:
os.remove(temp_path)
logger.info(f"Cleaned up temporary file: {temp_path}")
except OSError as e:
logger.warning(f"Failed to clean up temporary file {temp_path}: {e}")
self._temp_files = [] # Reset the list
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=10),
)
def generate(
self,
test_case: TestCase,
# Allow passing pre-loaded data, e.g., from the judge
base64_data: Optional[str] = None,
mime_type_override: Optional[str] = None
) -> ModelResponse:
"""Call the model API with the test case, potentially including file data based on endpoint configuration."""
start_time = time.time()
# Variables to hold prepared file data based on method
base64_data_loaded = None
mime_type_loaded = None
local_file_path_for_multipart = None # Path to file (potentially temporary) for multipart upload
logger.info(f"Inside generate for model '{self.endpoint.name}', test_id: {test_case.id}. File path/URL from test case: {test_case.image_path_or_url}")
try:
# Determine the required upload method early
upload_method = self.endpoint.file_upload_method
logger.info(f"Using file upload method: '{upload_method}' for endpoint '{self.endpoint.name}'")
# Preprocess the input key using the global settings
preprocessed_key = preprocess_text(test_case.key)
# Format prompt using the preprocessed key
prompt = ""
try:
# For judge prompts, the "key" is already the full prompt
if test_case.id and test_case.id.startswith("judge"):
prompt = preprocessed_key # Use directly, assume already preprocessed if needed
else:
# Use simple replacement first, escaping existing braces in the key
safe_key = preprocessed_key.replace("{", "{{").replace("}", "}}")
prompt = self.prompt_template.replace("{key}", safe_key)
except Exception as e:
logger.warning(f"Error formatting prompt template with replace: {str(e)}. Falling back.")
try:
prompt = self.prompt_template.format(key=preprocessed_key)
except Exception as e2:
logger.error(f"Error formatting prompt template: {str(e2)}. Using concatenation.")
prompt = f"{self.prompt_template}\n\nINPUT: {preprocessed_key}"
# --- File Handling Logic (Prepare based on selected method) ---
if test_case.image_path_or_url:
logger.info(f"Test case {test_case.id} includes file reference: {test_case.image_path_or_url}. Preparing based on method '{upload_method}'.")
if upload_method == "JSON (Embedded Data)":
# Use existing logic for now, will move to _prepare_base64_data helper later
# Prioritize pre-loaded data if provided (e.g., by judge)
if base64_data:
logger.info(f"Using pre-loaded base64 data for JSON method (test case {test_case.id}). Mime type override: {mime_type_override}")
base64_data_loaded = base64_data
mime_type_loaded = mime_type_override or 'application/octet-stream' # Use override or default
else:
logger.info(f"Loading file for JSON method: {test_case.image_path_or_url}")
base64_data_loaded, mime_type_loaded = self._load_and_encode_file(test_case.image_path_or_url)
logger.info(f"Result from _load_and_encode_file - Has data: {bool(base64_data_loaded)}, Mime type: {mime_type_loaded}")
if base64_data_loaded is None:
# Handle file loading failure
logger.error(f"Failed to load file for JSON method (test case {test_case.id}). Returning error.")
return ModelResponse(test_id=test_case.id or "unknown", model_name=self.endpoint.name, output=f"Error: Failed to load file {test_case.image_path_or_url} for JSON method", latency=time.time() - start_time)
elif upload_method == "Multipart Form Data":
# Call the actual helper function
local_file_path_for_multipart = self._prepare_local_file_path(test_case.image_path_or_url)
if local_file_path_for_multipart is None:
logger.error(f"Failed to prepare local file for Multipart method (test case {test_case.id}). Returning error.")
return ModelResponse(test_id=test_case.id or "unknown", model_name=self.endpoint.name, output=f"Error: Failed to prepare file {test_case.image_path_or_url} for Multipart method", latency=time.time() - start_time)
else:
logger.error(f"Unknown file_upload_method configured: {upload_method}")
return ModelResponse(test_id=test_case.id or "unknown", model_name=self.endpoint.name, output=f"Error: Invalid file_upload_method '{upload_method}'", latency=time.time() - start_time)
# else: No file involved in this test case, proceed with text-only call
# --- API Call Routing ---
response_text = ""
try:
if upload_method == "JSON (Embedded Data)":
logger.info("Routing to _call_json_api.")
# Call the new JSON API wrapper function
response_text = self._call_json_api(prompt, base64_data_loaded, mime_type_loaded)
elif upload_method == "Multipart Form Data":
logger.info("Routing to _call_multipart_api.")
# Call the new Multipart API function
response_text = self._call_multipart_api(prompt, local_file_path_for_multipart)
else:
# Should have been caught during file prep, but defensive check
logger.error(f"Invalid file_upload_method '{upload_method}' reached API call routing.")
response_text = f"Error: Invalid file upload method configuration '{upload_method}'."
# Exception handling remains the same, but applies to the new call structure
except requests.exceptions.RequestException as req_err:
logger.error(f"API request failed for {self.endpoint.name}: {req_err}")
if hasattr(req_err, 'response') and req_err.response is not None:
logger.error(f"Response status: {req_err.response.status_code}, Response text: {req_err.response.text[:500]}")
response_text = f"Error: API request failed. Details: {str(req_err)}"
except (KeyError, IndexError, TypeError, json.JSONDecodeError, ValueError) as parse_err:
logger.error(f"Failed to parse response or invalid response structure from {self.endpoint.name}: {parse_err}")
response_text = f"Error: Failed to parse API response. Details: {str(parse_err)}"
except Exception as e:
logger.error(f"Unexpected error calling API for {self.endpoint.name}: {str(e)}", exc_info=True)
response_text = f"Error: An unexpected error occurred. Details: {str(e)}"
end_time = time.time()
# Clean up temporary files regardless of success or failure
self._cleanup_temp_files()
return ModelResponse(
test_id=test_case.id or "unknown", # Ensure test_id is never None
model_name=self.endpoint.name,
output=str(response_text), # Ensure output is always string
latency=end_time - start_time,
)
except Exception as e:
logger.error(f"Unexpected error in generate method for {self.endpoint.name}: {str(e)}", exc_info=True)
# Re-raise to trigger tenacity retry
raise
finally:
# Ensure cleanup happens even if retry fails or other unexpected errors occur
self._cleanup_temp_files()
def _prepare_headers(self, is_json_request=True):
"""Prepares common headers. Adjusts Content-Type based on request type."""
# Start with common headers
headers = {}
# Only add Authorization header if api_key is present and not empty
if self.endpoint.api_key and self.endpoint.api_key.strip():
# Check for specific API key types if needed (e.g., Anthropic uses x-api-key)
if "anthropic" in self.endpoint.api_url.lower():
headers["x-api-key"] = self.endpoint.api_key
headers["anthropic-version"] = "2023-06-01" # Required header
elif "generativelanguage.googleapis.com" in self.endpoint.api_url.lower():
# Gemini API key is usually in the URL, not header
pass
else:
# Default to Bearer token for OpenAI compatible and others
headers["Authorization"] = f"Bearer {self.endpoint.api_key}"
# Set Content-Type based on whether it's a JSON request or not (e.g., multipart)
if is_json_request:
headers["Content-Type"] = "application/json"
# For multipart/form-data, requests library handles Content-Type automatically when 'files' param is used.
# Add OpenRouter specific headers if applicable
# Only add Authorization header if api_key is present and not empty
if self.endpoint.api_key and self.endpoint.api_key.strip():
headers["Authorization"] = f"Bearer {self.endpoint.api_key}"
# Add OpenRouter specific headers if applicable
if self.endpoint.api_url and "openrouter.ai" in self.endpoint.api_url.lower():
# These might be optional now, but good practice
headers["HTTP-Referer"] = "http://localhost" # Can be anything, localhost is common
headers["X-Title"] = "Model A/B Testing Tool"
return headers
# --- New API Call Functions ---
def _call_json_api(self, prompt: str, base64_data: Optional[str], mime_type: Optional[str]) -> str:
"""
Wrapper for JSON-based API calls. Detects API type and calls the appropriate formatter.
"""
logger.info(f"Executing JSON API call for endpoint: {self.endpoint.name}")
headers = self._prepare_headers(is_json_request=True) # Ensure JSON content type
# Determine API type based on URL (similar to previous logic)
api_url_lower = self.endpoint.api_url.lower() if self.endpoint.api_url else ""
is_openai_compatible = "/v1/chat/completions" in api_url_lower or \
"openai" in api_url_lower or \
"openrouter.ai" in api_url_lower or \
"mistral" in api_url_lower or \
"together.ai" in api_url_lower or \
"groq.com" in api_url_lower or \
"fireworks.ai" in api_url_lower or \
"deepinfra.com" in api_url_lower or \
"lmstudio.ai" in api_url_lower or \
":1234/v1" in api_url_lower
is_anthropic_compatible = "/v1/messages" in api_url_lower or "anthropic" in api_url_lower
is_gemini = "generativelanguage.googleapis.com" in api_url_lower
is_ollama = ("/api/generate" in api_url_lower and \
("localhost:11434" in api_url_lower or "127.0.0.1:11434" in api_url_lower)) or \
("ollama" in api_url_lower and "/api/generate" in api_url_lower)
payload = {}
api_url_to_call = self.endpoint.api_url # Default URL
# Call appropriate formatting function
if is_openai_compatible:
payload = self._format_openai_json(prompt, base64_data, mime_type)
elif is_anthropic_compatible:
payload = self._format_anthropic_json(prompt, base64_data, mime_type)
elif is_gemini:
payload = self._format_gemini_json(prompt, base64_data, mime_type)
# Gemini API key goes in URL parameter
if self.endpoint.api_key:
api_url_to_call = f"{self.endpoint.api_url}?key={self.endpoint.api_key}"
else:
raise ValueError("Gemini API key is required but not provided.")
elif is_ollama:
payload = self._format_ollama_json(prompt, base64_data)
else:
# Fallback: Use generic API call logic (which currently assumes OpenAI text-only)
logger.warning(f"Could not determine specific JSON API type for {self.endpoint.api_url}. Using generic fallback.")
# The generic call handles its own request formatting and execution
return self._call_generic_api(prompt) # Return directly
# Make the actual request
try:
payload_size_kb = len(json.dumps(payload)) / 1024
logger.info(f"Sending JSON request to {api_url_to_call}. Payload size: {payload_size_kb:.2f} KB")
if payload_size_kb > 4000: logger.warning(f"Payload size ({payload_size_kb:.2f} KB) is large.")
response = requests.post(api_url_to_call, headers=headers, json=payload, timeout=180)
response.raise_for_status()
result = response.json()
# Parse response based on API type (This parsing logic should ideally move too)
# TODO: Move response parsing into dedicated functions or handle within formatters?
if is_openai_compatible:
if not result.get("choices") or not result["choices"][0].get("message"): raise ValueError("Invalid OpenAI response format")
content = result["choices"][0]["message"].get("content")
return content if content is not None else f"Error: Response content was null (Finish Reason: {result['choices'][0].get('finish_reason')})"
elif is_anthropic_compatible:
if not result.get("content"): raise ValueError("Invalid Anthropic response format")
text_content = next((block.get("text", "") for block in result.get("content", []) if block.get("type") == "text"), "")
return text_content if text_content else "[No text content found in response]"
elif is_gemini:
if not result.get("candidates"): raise ValueError("Invalid Gemini response format")
candidate = result["candidates"][0]
if not candidate.get("content") or not candidate["content"].get("parts"): raise ValueError("Invalid Gemini response format")
text_response = "".join(part["text"] for part in candidate["content"]["parts"] if "text" in part)
return text_response if text_response else "[No text content found in response]"
elif is_ollama:
if "response" in result: return result["response"]
elif "error" in result: raise ValueError(f"Ollama API Error: {result['error']}")
else: raise ValueError("Invalid Ollama response format")
else:
# Should not be reached if generic fallback worked
raise ValueError("Unhandled API type in JSON response parsing.")
except requests.exceptions.RequestException as e:
logger.error(f"JSON API request failed: {str(e)}")
if hasattr(e, 'response') and e.response is not None: logger.error(f"Response content: {e.response.text[:500]}")
raise # Re-raise to be caught by the main generate method's handler
except (KeyError, IndexError, ValueError, json.JSONDecodeError) as e:
logger.error(f"Failed to parse JSON API response: {str(e)}")
logger.error(f"Full response: {result if 'result' in locals() else 'Response not available'}")
raise # Re-raise
def _call_multipart_api(self, prompt: str, local_file_path: Optional[str]) -> str:
"""
Handles API calls using multipart/form-data.
(Placeholder - Needs implementation based on target API, e.g., Whisper)
"""
logger.info(f"Executing Multipart API call for endpoint: {self.endpoint.name}")
if not local_file_path:
return "Error: No local file path provided for multipart upload."
# Prepare headers (Requests handles Content-Type for multipart)
headers = self._prepare_headers(is_json_request=False)
# Prepare data and files dictionary - THIS IS HIGHLY API-SPECIFIC
# Example for OpenAI Whisper:
data = {'model': self.endpoint.model_id}
if prompt: # Whisper uses 'prompt' for context/hints
data['prompt'] = prompt
# Add other potential fields like 'language', 'response_format' based on API
files = {}
try:
# Use a context manager to ensure the file is closed
with open(local_file_path, 'rb') as f:
files['file'] = (os.path.basename(local_file_path), f)
logger.info(f"Preparing multipart request with file: {os.path.basename(local_file_path)}")
# Make the request
response = requests.post(
self.endpoint.api_url,
headers=headers,
data=data,
files=files,
timeout=180 # Timeout for upload + processing
)
response.raise_for_status()
result = response.json()
# Parse the response - AGAIN, API-SPECIFIC
# Example for Whisper:
if 'text' in result:
return result['text']
else:
raise ValueError(f"Unexpected response format from multipart API: {result}")
except requests.exceptions.RequestException as e:
logger.error(f"Multipart API request failed: {str(e)}")
if hasattr(e, 'response') and e.response is not None: logger.error(f"Response content: {e.response.text[:500]}")
raise
except (KeyError, ValueError, json.JSONDecodeError) as e:
logger.error(f"Failed to parse Multipart API response: {str(e)}")
logger.error(f"Full response: {result if 'result' in locals() else 'Response not available'}")
raise
except FileNotFoundError:
logger.error(f"File not found for multipart upload: {local_file_path}")
return f"Error: File not found at {local_file_path}"
except Exception as e:
logger.error(f"Unexpected error during multipart call: {e}", exc_info=True)
raise
# --- JSON Formatting Functions (Placeholders) ---
def _format_openai_json(self, prompt: str, base64_data: Optional[str], mime_type: Optional[str]) -> Dict[str, Any]:
"""Formats the payload for OpenAI-compatible chat completion APIs."""
logger.debug("Formatting payload for OpenAI JSON")
messages = []
if base64_data:
mime_type = mime_type or 'image/jpeg' # Default mime type
messages.append({
"role": "user",
"content": [
{"type": "text", "text": prompt},
{"type": "image_url", "image_url": {"url": f"data:{mime_type};base64,{base64_data}"}}
]
})
else:
messages.append({"role": "user", "content": prompt})
return {
"model": self.endpoint.model_id,
"messages": messages,
"max_tokens": self.endpoint.max_tokens,
"temperature": self.endpoint.temperature,
}
def _format_anthropic_json(self, prompt: str, base64_data: Optional[str], mime_type: Optional[str]) -> Dict[str, Any]:
"""Formats the payload for Anthropic messages API."""
logger.debug("Formatting payload for Anthropic JSON")
content = [{"type": "text", "text": prompt}]
if base64_data:
mime_type = mime_type or 'image/jpeg'
supported_mime_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
if mime_type not in supported_mime_types:
logger.warning(f"MIME type '{mime_type}' may not be directly supported by Claude.")
content.append({
"type": "image",
"source": {"type": "base64", "media_type": mime_type, "data": base64_data}
})
return {
"model": self.endpoint.model_id,
"messages": [{"role": "user", "content": content}],
"max_tokens": self.endpoint.max_tokens,
"temperature": self.endpoint.temperature,
}
def _format_gemini_json(self, prompt: str, base64_data: Optional[str], mime_type: Optional[str]) -> Dict[str, Any]:
"""Formats the payload for Google Gemini API."""
logger.debug("Formatting payload for Gemini JSON")
parts = [{"text": prompt}]
if base64_data:
mime_type = mime_type or 'application/octet-stream' # Gemini supports various types
parts.append({"inline_data": {"mime_type": mime_type, "data": base64_data}})
return {
"contents": [{"parts": parts}],
"generationConfig": {
"temperature": self.endpoint.temperature,
"maxOutputTokens": self.endpoint.max_tokens,
}
}
def _format_ollama_json(self, prompt: str, base64_data: Optional[str]) -> Dict[str, Any]:
"""Formats the payload for Ollama generate API."""
logger.debug("Formatting payload for Ollama JSON")
data = {
"model": self.endpoint.model_id,
"prompt": prompt,
"stream": False,
}
if base64_data:
data["images"] = [base64_data] # Ollama expects a list
return data
class LMJudge:
"""Uses a language model to judge between champion and challenger outputs."""
DEFAULT_EVALUATION_PROMPT = """
# Model Response Evaluation
You are evaluating two AI model responses based on the input query, potentially an accompanying image, and potentially a reference value.
## Input Query
{key}
{image_context_section}
{reference_section}
## Model A (Champion: {champion_name}) Response
{champion_output}
## Model B (Challenger: {challenger_name}) Response
{challenger_output}
## Evaluation Instructions
Compare Model A and Model B based on the Input Query{reference_value_instruction}. Consider:
1. Relevance and accuracy in addressing the Input Query.
{reference_value_criteria}
{clarity_criteria_number}. Clarity, conciseness, and quality of the response.
{overall_criteria_number}. Overall usefulness.
## Required Response Format
You MUST start your response with a clear verdict and confidence rating:
VERDICT: [Choose ONE: MODEL_A_WINS, MODEL_B_WINS, or TIE]
CONFIDENCE: [Number]/5 (where 1=low confidence, 5=high confidence)
Then provide a detailed explanation of your reasoning. Be explicit about which model performed better and why, or why they were tied. Include specific examples from each response that influenced your decision.
Example format:
VERDICT: MODEL_A_WINS
CONFIDENCE: 4/5
[Your detailed reasoning here...]
"""
def __init__(
self,
endpoint: ModelEndpoint,
evaluation_prompt_template: str = DEFAULT_EVALUATION_PROMPT,
):
self.endpoint = endpoint
self.evaluation_prompt_template = evaluation_prompt_template
# The judge runner uses a simple placeholder template, as the full prompt
# is formatted within the evaluate method before being passed as the 'key'.
# Judge model runner needs access to the file loading method.
self.model_runner = ModelRunner(endpoint, "{key}") # Pass-through template for prompt
def evaluate(
self,
test_case: TestCase,
champion_response: ModelResponse,
challenger_response: ModelResponse
) -> EvaluationResult:
"""Evaluate champion vs challenger outputs using a dynamically built prompt."""
# Preprocess all inputs to ensure they're clean strings
# Use the same preprocess_text function for consistency
# Note: We don't pass the image to the judge, only the text inputs/outputs.
preprocessed_key = preprocess_text(test_case.key)
preprocessed_value = preprocess_text(test_case.value) # Preprocess reference value too
preprocessed_champion = preprocess_text(champion_response.output)
preprocessed_challenger = preprocess_text(challenger_response.output)
# Prepare context for the evaluation prompt template
has_reference = bool(preprocessed_value)
reference_section_text = f"\n## Reference Value\n\n{preprocessed_value}\n" if has_reference else "\n## Reference Value\nN/A"
reference_value_instruction_text = ' and Reference Value' if has_reference else ''
reference_value_criteria_text = '2. Factual correctness compared to the Reference Value (if provided).' if has_reference else ''
clarity_criteria_number_text = '3' if has_reference else '2'
overall_criteria_number_text = '4' if has_reference else '3'
# Add image context section if an image was provided in the original test case
has_image = bool(test_case.image_path_or_url)
image_context_section_text = "\n## Input Image\nAn image was provided with the input query. Consider it as context when evaluating the responses.\n" if has_image else ""
# Format the evaluation prompt using the template and context
try:
evaluation_prompt = self.evaluation_prompt_template.format(
key=preprocessed_key,
image_context_section=image_context_section_text, # Added image context
reference_section=reference_section_text,
champion_name=champion_response.model_name,
champion_output=preprocessed_champion,
challenger_name=challenger_response.model_name,
challenger_output=preprocessed_challenger,
reference_value_instruction=reference_value_instruction_text,
reference_value_criteria=reference_value_criteria_text,
clarity_criteria_number=clarity_criteria_number_text,
overall_criteria_number=overall_criteria_number_text
)
except KeyError as e:
logger.error(f"Missing key in judge prompt template: {e}. Using default prompt structure.")
# Fallback to a basic structure if formatting fails
evaluation_prompt = f"Evaluate Model A vs Model B.\nInput: {preprocessed_key}\nRef: {preprocessed_value}\nA: {preprocessed_champion}\nB: {preprocessed_challenger}\nFormat: VERDICT: [MODEL_A_WINS/MODEL_B_WINS/TIE]\nCONFIDENCE: [1-5]/5\nReasoning: ..."
except Exception as e:
logger.error(f"Error formatting judge prompt template: {e}. Using basic prompt.")
evaluation_prompt = f"Evaluate Model A vs Model B.\nInput: {preprocessed_key}\nRef: {preprocessed_value}\nA: {preprocessed_champion}\nB: {preprocessed_challenger}\nFormat: VERDICT: [MODEL_A_WINS/MODEL_B_WINS/TIE]\nCONFIDENCE: [1-5]/5\nReasoning: ..."
# Log the prompt for debugging (truncated)
logger.info(f"Using Judge evaluation prompt (truncated): {evaluation_prompt[:500]}...")
# Create a TestCase specifically for the judge call.
# Crucially, pass the original image_path_or_url from the test_case.
# The judge's model_runner.generate method will handle loading the file
# based on the judge's endpoint.file_upload_method configuration.
judge_test_case = TestCase(
key=evaluation_prompt,
value="", # No value needed for judge call itself
image_path_or_url=test_case.image_path_or_url, # Pass original file reference
id=f"judge-{test_case.id or 'unknown'}"
)
# Call the judge's generate method. It will handle file loading internally.
# We no longer need to pass base64_data or mime_type_override here.
judge_response_obj = self.model_runner.generate(
test_case=judge_test_case
)
# Log the response for debugging (truncated)
logger.info(f"Judge raw response (truncated): {judge_response_obj.output[:500]}...")
# Parse the judge's decision from the raw output string
parsed_result = self.parse_judge_response(judge_response_obj.output)
return EvaluationResult(
test_id=test_case.id or "unknown",
champion_output=champion_response.output, # Store original, not preprocessed
challenger_output=challenger_response.output, # Store original, not preprocessed
winner=parsed_result["winner"],
confidence=parsed_result["confidence"],
reasoning=judge_response_obj.output, # Store the full raw response as reasoning
)
def parse_judge_response(self, response_text: str) -> Dict[str, Any]:
"""
Parse the judge's raw response string to extract verdict and confidence.
Uses more flexible regex patterns to handle various response formats.
"""
verdict = "UNDETERMINED"
confidence = 0.0
# Log the first part of the response for debugging
logger.debug(f"Parsing judge response (first 100 chars): {response_text[:100]}")
# 1. Extract VERDICT (Case-insensitive search for the explicit line)
verdict_match = re.search(r"^\s*VERDICT:\s*(MODEL_A_WINS|MODEL_B_WINS|TIE)\s*$", response_text, re.IGNORECASE | re.MULTILINE)
if verdict_match:
verdict = verdict_match.group(1).upper()
logger.info(f"Parsed VERDICT line: {verdict}")
else:
# Fallback: Look for bracketed verdicts (common LLM-as-judge pattern)
bracket_match = re.search(r"\[\[\s*(MODEL_A_WINS|MODEL_B_WINS|TIE)\s*\]\]", response_text, re.IGNORECASE)
if bracket_match:
verdict = bracket_match.group(1).upper()
logger.info(f"Parsed bracketed verdict: {verdict}")
else:
# Fallback: Look for simpler A/B/TIE in brackets
simple_bracket_match = re.search(r"\[\[\s*([AB]|TIE)\s*\]\]", response_text, re.IGNORECASE)
if simple_bracket_match:
verdict_text = simple_bracket_match.group(1).upper()
if verdict_text == "A": verdict = "MODEL_A_WINS"
elif verdict_text == "B": verdict = "MODEL_B_WINS"
else: verdict = "TIE"
logger.info(f"Parsed simple bracketed verdict: {verdict}")
# 2. Extract CONFIDENCE (Case-insensitive search for the explicit line)
confidence_match = re.search(r"^\s*CONFIDENCE:\s*(\d(?:\.\d)?)\s*/\s*5\s*$", response_text, re.IGNORECASE | re.MULTILINE)
if confidence_match:
try:
confidence_score = float(confidence_match.group(1))
# Clamp confidence between 1 and 5, then normalize to 0.2-1.0 range
confidence = max(0.2, min(1.0, confidence_score / 5.0))
logger.info(f"Parsed CONFIDENCE line: {confidence_score}/5 -> {confidence}")
except ValueError:
logger.warning(f"Could not parse CONFIDENCE value: {confidence_match.group(1)}")
else:
# Fallback: Look for rating/score patterns if confidence line missing
score_match = re.search(r"(?:rating|score)[:\s]*(\d(?:\.\d)?)\s*/\s*(\d+)", response_text, re.IGNORECASE)
if score_match:
try:
score = float(score_match.group(1))
scale = float(score_match.group(2))
if scale > 0:
# Normalize to 0-1 range, clamping between 0.2 and 1.0
confidence = max(0.2, min(1.0, score / scale))
logger.info(f"Parsed score/rating: {score}/{scale} -> {confidence}")
except ValueError:
pass # Ignore if parsing fails
# 3. Final checks and fallbacks if parsing failed
if verdict == "UNDETERMINED":
logger.warning(f"Could not reliably parse VERDICT from judge response: {response_text[:200]}...")
# Simple keyword check as a last resort (less reliable)
if "model a wins" in response_text.lower() and "model b wins" not in response_text.lower():
verdict = "MODEL_A_WINS"
elif "model b wins" in response_text.lower() and "model a wins" not in response_text.lower():
verdict = "MODEL_B_WINS"
elif "tie" in response_text.lower() or "comparable" in response_text.lower():
verdict = "TIE"
# If we have a verdict but no confidence, assign a default moderate confidence
if verdict != "UNDETERMINED" and confidence == 0.0:
confidence = 0.6 # Default confidence when parsing fails but verdict is found
logger.info(f"Could not parse CONFIDENCE, assigning default {confidence} for verdict {verdict}")
# Log the final parsed values
logger.info(f"Final parsed judge result - Winner: {verdict}, Confidence: {confidence:.2f}")
return {
"winner": verdict,
"confidence": confidence,
# Reasoning is the full response text, handled in evaluate method
}
class ResultAggregator:
"""Collects evaluation results and calculates summary statistics."""
def aggregate(self, evaluation_results: List[EvaluationResult]) -> Dict[str, Any]:
"""Aggregates results, calculating counts and percentages."""
total_evaluations = len(evaluation_results)
verdict_counts = {"MODEL_A_WINS": 0, "MODEL_B_WINS": 0, "TIE": 0, "UNDETERMINED": 0, "JUDGE_ERROR": 0}
confidence_sum = 0
valid_verdicts = 0
# Track which test cases had undetermined verdicts for logging
undetermined_cases = []
judge_error_cases = []
for result in evaluation_results:
verdict = result.winner # Use the pre-parsed winner
if verdict in verdict_counts:
verdict_counts[verdict] += 1
if verdict != "UNDETERMINED" and verdict != "JUDGE_ERROR":
confidence_sum += result.confidence
valid_verdicts += 1
elif verdict == "UNDETERMINED":
undetermined_cases.append(result.test_id)
elif verdict == "JUDGE_ERROR":
judge_error_cases.append(result.test_id)
else:
# Should not happen if parsing is robust, but handle defensively
logger.warning(f"Unexpected verdict '{verdict}' encountered for test_id {result.test_id}. Counting as UNDETERMINED.")
verdict_counts["UNDETERMINED"] += 1
undetermined_cases.append(result.test_id)
# Log summary of problematic cases
if undetermined_cases:
logger.warning(f"Found {len(undetermined_cases)} undetermined verdicts: {undetermined_cases[:5]}" +
(f"... and {len(undetermined_cases)-5} more" if len(undetermined_cases) > 5 else ""))
if judge_error_cases:
logger.warning(f"Found {len(judge_error_cases)} judge errors: {judge_error_cases[:5]}" +
(f"... and {len(judge_error_cases)-5} more" if len(judge_error_cases) > 5 else ""))
# Calculate percentages based on determined verdicts only (excluding UNDETERMINED and JUDGE_ERROR)
determined_verdicts = total_evaluations - verdict_counts["UNDETERMINED"] - verdict_counts["JUDGE_ERROR"]
verdict_percentages = {}
if determined_verdicts > 0:
verdict_percentages["MODEL_A_WINS"] = round(
(verdict_counts["MODEL_A_WINS"] / determined_verdicts) * 100, 2
)
verdict_percentages["MODEL_B_WINS"] = round(
(verdict_counts["MODEL_B_WINS"] / determined_verdicts) * 100, 2