kaikaidai commited on
Commit
dbd97ea
·
verified ·
1 Parent(s): 6ba7a5f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +805 -0
app.py ADDED
@@ -0,0 +1,805 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import json
3
+ import gradio as gr
4
+ import re
5
+ import random
6
+ import time
7
+ from collections import defaultdict
8
+ from functools import partial
9
+ import openai
10
+ from openai import OpenAI
11
+ import anthropic
12
+ import pandas as pd
13
+ from together import Together
14
+ import os
15
+ from dotenv import load_dotenv
16
+
17
+ load_dotenv()
18
+
19
+ anthropic_client = anthropic.Anthropic()
20
+ openai_client = OpenAI()
21
+ together_client = Together()
22
+
23
+ # Model and ELO score data
24
+ DEFAULT_ELO = 1000 # Starting ELO for new models
25
+ elo_scores = defaultdict(lambda: DEFAULT_ELO)
26
+ vote_counts = defaultdict(int)
27
+ model_data = {
28
+ 'Meta Llama 3.1 70B Instruct Turbo': {
29
+ 'organization': 'Meta',
30
+ 'license': 'Open Source',
31
+ 'api_model': 'meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo'
32
+ },
33
+ 'Meta Llama 3.1 405B Instruct Turbo': {
34
+ 'organization': 'Meta',
35
+ 'license': 'Open Source',
36
+ 'api_model': 'meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo'
37
+ },
38
+ 'Gemma 2 27B': {
39
+ 'organization': 'Google',
40
+ 'license': 'Open Source',
41
+ 'api_model': 'google/gemma-2-27b-it'
42
+ },
43
+ 'Gemma 2 9B': {
44
+ 'organization': 'Google',
45
+ 'license': 'Open Source',
46
+ 'api_model': 'google/gemma-2-9b-it'
47
+ },
48
+ 'Qwen 2 Instruct (72B)': {
49
+ 'organization': 'Alibaba',
50
+ 'license': 'Open Source',
51
+ 'api_model': 'Qwen/Qwen2-72B-Instruct'
52
+ },
53
+ 'Mistral (7B) Instruct v0.3': {
54
+ 'organization': 'Mistral AI',
55
+ 'license': 'Open Source',
56
+ 'api_model': 'mistralai/Mistral-7B-Instruct-v0.3'
57
+ },
58
+ 'GPT-4o': {
59
+ 'organization': 'OpenAI',
60
+ 'license': 'Proprietary',
61
+ 'api_model': 'gpt-4o'
62
+ },
63
+ 'GPT-4 Turbo': {
64
+ 'organization': 'OpenAI',
65
+ 'license': 'Proprietary',
66
+ 'api_model': 'gpt-4-turbo'
67
+ },
68
+ 'GPT-3.5 Turbo': {
69
+ 'organization': 'OpenAI',
70
+ 'license': 'Proprietary',
71
+ 'api_model': 'gpt-3.5-turbo'
72
+ },
73
+ 'Claude 3 Haiku': {
74
+ 'organization': 'Anthropic',
75
+ 'license': 'Proprietary',
76
+ 'api_model': 'claude-3-haiku-20240307'
77
+ },
78
+ 'Claude 3 Sonnet': {
79
+ 'organization': 'Anthropic',
80
+ 'license': 'Proprietary',
81
+ 'api_model': 'claude-3-sonnet-20240229'
82
+ },
83
+ 'Claude 3 Opus': {
84
+ 'organization': 'Anthropic',
85
+ 'license': 'Proprietary',
86
+ 'api_model': 'claude-3-opus-20240229'
87
+ },
88
+ 'Meta Llama 3.1 8B Instruct Turbo': {
89
+ 'organization': 'Meta',
90
+ 'license': 'Open Source',
91
+ 'api_model': 'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo'
92
+ },
93
+ 'Meta Llama 3.1 70B Instruct Turbo': {
94
+ 'organization': 'Meta',
95
+ 'license': 'Open Source',
96
+ 'api_model': 'meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo'
97
+ },
98
+ }
99
+
100
+ current_session_id = 0
101
+ voting_data = []
102
+
103
+ def get_new_session_id():
104
+ global current_session_id
105
+ current_session_id += 1
106
+ return f"user{current_session_id}"
107
+
108
+ def store_vote_data(prompt, response_a, response_b, model_a, model_b, winner, judge_id):
109
+ vote_entry = {
110
+ "timestamp": datetime.now().isoformat(),
111
+ "prompt": prompt,
112
+ "response_a": response_a,
113
+ "response_b": response_b,
114
+ "model_a": model_a,
115
+ "model_b": model_b,
116
+ "winner": winner,
117
+ "judge_id": judge_id,
118
+ }
119
+ voting_data.append(vote_entry)
120
+
121
+ # Optionally save to file after each vote
122
+ with open('voting_data.json', 'w') as f:
123
+ json.dump(voting_data, f, indent=2)
124
+
125
+ def parse_variables(prompt):
126
+ # Extract variables enclosed in double curly braces
127
+ variables = re.findall(r'{{(.*?)}}', prompt)
128
+ # Remove duplicates while preserving order
129
+ seen = set()
130
+ variables = [x.strip() for x in variables if not (x.strip() in seen or seen.add(x.strip()))]
131
+ return variables
132
+
133
+ def get_final_prompt(eval_prompt, variable_values):
134
+ # Replace variables in the eval prompt with their values
135
+ for var, val in variable_values.items():
136
+ eval_prompt = eval_prompt.replace('{{' + var + '}}', val)
137
+ return eval_prompt
138
+
139
+ # Add this near the top with other constants
140
+ SYSTEM_PROMPT = """Please act as an impartial judge and evaluate based on the user's instruction. Your output format should be a JSON as follows: {{"feedback": "(write a feedback for the evaluation criteria)", "result": "(a score based on the evaluation criteria)"}}"""
141
+
142
+ def get_openai_response(model_name, prompt):
143
+ try:
144
+ response = openai_client.chat.completions.create(
145
+ model=model_name,
146
+ messages=[
147
+ {"role": "system", "content": SYSTEM_PROMPT},
148
+ {"role": "user", "content": prompt}
149
+ ]
150
+ )
151
+ return response.choices[0].message.content
152
+ except Exception as e:
153
+ return f"Error with OpenAI model {model_name}: {str(e)}"
154
+
155
+ def get_anthropic_response(model_name, prompt):
156
+ try:
157
+ response = anthropic_client.messages.create(
158
+ model=model_name,
159
+ max_tokens=1000,
160
+ temperature=0,
161
+ system=SYSTEM_PROMPT,
162
+ messages=[
163
+ {"role": "user", "content": [{"type": "text", "text": prompt}]}
164
+ ]
165
+ )
166
+ return response.content[0].text
167
+ except Exception as e:
168
+ return f"Error with Anthropic model {model_name}: {str(e)}"
169
+
170
+ def get_model_response(model_name, prompt):
171
+ model_info = model_data.get(model_name)
172
+ if not model_info:
173
+ return "Model not found or unsupported."
174
+
175
+ api_model = model_info['api_model']
176
+ organization = model_info['organization']
177
+
178
+ try:
179
+ if organization == 'OpenAI':
180
+ return get_openai_response(api_model, prompt)
181
+ elif organization == 'Anthropic':
182
+ return get_anthropic_response(api_model, prompt)
183
+ else:
184
+ # All other organizations use Together API
185
+ return get_together_response(api_model, prompt)
186
+ except Exception as e:
187
+ return f"Error with {organization} model {model_name}: {str(e)}"
188
+
189
+ def submit_prompt(eval_prompt, *variable_values):
190
+ try:
191
+ variables = parse_variables(eval_prompt)
192
+ variable_values_dict = {var: val for var, val in zip(variables, variable_values)}
193
+ final_prompt = get_final_prompt(eval_prompt, variable_values_dict)
194
+
195
+ models = list(model_data.keys())
196
+ model1, model2 = random.sample(models, 2)
197
+ model_a, model_b = (model1, model2) if random.random() < 0.5 else (model2, model1)
198
+
199
+ response_a = get_model_response(model_a, final_prompt)
200
+ response_b = get_model_response(model_b, final_prompt)
201
+
202
+ return (
203
+ response_a, # response_a textbox
204
+ response_b, # response_b textbox
205
+ gr.update(visible=True), # action_buttons_row
206
+ gr.update(visible=True), # regenerate_button
207
+ model_a, # model_a_state
208
+ model_b # model_b_state
209
+ )
210
+ except Exception as e:
211
+ print(f"Error in submit_prompt: {str(e)}")
212
+ # Return default values in case of error
213
+ return (
214
+ "Error generating response",
215
+ "Error generating response",
216
+ gr.update(visible=False),
217
+ gr.update(visible=False),
218
+ None,
219
+ None
220
+ )
221
+
222
+ def vote(choice, model_a, model_b, prompt, response_a, response_b, judge_id):
223
+ # Update ELO scores based on user choice
224
+ elo_a = elo_scores[model_a]
225
+ elo_b = elo_scores[model_b]
226
+ K = 32 # ELO K-factor
227
+
228
+ # Calculate expected scores
229
+ Ea = 1 / (1 + 10 ** ((elo_b - elo_a) / 400))
230
+ Eb = 1 / (1 + 10 ** ((elo_a - elo_b) / 400))
231
+
232
+ # Assign actual scores
233
+ if choice == 'A':
234
+ Sa, Sb = 1, 0
235
+ elif choice == 'B':
236
+ Sa, Sb = 0, 1
237
+ else:
238
+ Sa, Sb = 0.5, 0.5
239
+
240
+ # Update scores and vote counts
241
+ elo_scores[model_a] += K * (Sa - Ea)
242
+ elo_scores[model_b] += K * (Sb - Eb)
243
+ vote_counts[model_a] += 1
244
+ vote_counts[model_b] += 1
245
+
246
+ # Store the vote data
247
+ store_vote_data(prompt, response_a, response_b, model_a, model_b, choice, judge_id)
248
+
249
+ # Return updates for UI components
250
+ return {
251
+ action_buttons_row: gr.update(visible=False),
252
+ model_name_a: gr.update(value=f"*Model: {model_a}*"),
253
+ model_name_b: gr.update(value=f"*Model: {model_b}*"),
254
+ send_btn: gr.update(interactive=True),
255
+ regenerate_button: gr.update(visible=True, interactive=True)
256
+ }
257
+
258
+ def get_leaderboard():
259
+ # Generate leaderboard data
260
+ leaderboard = []
261
+ for model, elo in elo_scores.items():
262
+ votes = vote_counts[model]
263
+ ci = 1.96 * (400 / (votes + 1) ** 0.5) # Approximate 95% confidence interval
264
+ data = {
265
+ 'Model': model,
266
+ 'ELO Score': f"{elo:.2f}",
267
+ '95% CI': f"±{ci:.2f}",
268
+ '# Votes': votes,
269
+ 'Organization': model_data[model]['organization'],
270
+ 'License': model_data[model]['license'],
271
+ }
272
+ leaderboard.append(data)
273
+ # Sort by ELO score
274
+ leaderboard.sort(key=lambda x: float(x['ELO Score']), reverse=True)
275
+ return leaderboard
276
+
277
+ def regenerate_prompt(model_a, model_b, eval_prompt, *variable_values):
278
+ variables = parse_variables(eval_prompt)
279
+ variable_values_dict = {var: val for var, val in zip(variables, variable_values)}
280
+ final_prompt = get_final_prompt(eval_prompt, variable_values_dict)
281
+
282
+ # Get available models excluding the previous ones
283
+ available_models = [m for m in model_data.keys() if m not in (model_a, model_b)]
284
+
285
+ # If we have enough models for new pairs
286
+ if len(available_models) >= 2:
287
+ model1, model2 = random.sample(available_models, 2)
288
+ else:
289
+ # Fallback to allowing previous models if necessary
290
+ model1, model2 = random.sample(list(model_data.keys()), 2)
291
+
292
+ response_a = get_model_response(model1, final_prompt)
293
+ response_b = get_model_response(model2, final_prompt)
294
+
295
+ # Parse the responses
296
+ score_a, critique_a = parse_model_response(response_a)
297
+ score_b, critique_b = parse_model_response(response_b)
298
+
299
+ return (
300
+ score_a, # score_a textbox
301
+ critique_a, # critique_a textbox
302
+ score_b, # score_b textbox
303
+ critique_b, # critique_b textbox
304
+ gr.update(visible=True), # action_buttons_row
305
+ gr.update(value="*Model: Unknown*"), # model_name_a
306
+ gr.update(value="*Model: Unknown*"), # model_name_b
307
+ model1, # model_a_state
308
+ model2 # model_b_state
309
+ )
310
+
311
+ # Add these constants at the top of your file
312
+ K_FACTOR = 32 # Standard chess K-factor, adjust as needed
313
+ DEFAULT_ELO = 1500 # Starting ELO for new models
314
+
315
+ def calculate_elo_change(rating_a, rating_b, winner):
316
+ """Calculate ELO rating changes for both players."""
317
+ expected_a = 1 / (1 + 10 ** ((rating_b - rating_a) / 400))
318
+ expected_b = 1 - expected_a
319
+
320
+ if winner == "A":
321
+ score_a, score_b = 1, 0
322
+ elif winner == "B":
323
+ score_a, score_b = 0, 1
324
+ else: # Handle ties
325
+ score_a, score_b = 0.5, 0.5
326
+
327
+ change_a = K_FACTOR * (score_a - expected_a)
328
+ change_b = K_FACTOR * (score_b - expected_b)
329
+
330
+ return change_a, change_b
331
+
332
+ def update_leaderboard():
333
+ """Calculate current ELO ratings from voting history."""
334
+ ratings = defaultdict(lambda: DEFAULT_ELO)
335
+ matches = defaultdict(int)
336
+ wins = defaultdict(int)
337
+
338
+ # Load voting data
339
+ try:
340
+ with open('voting_data.json', 'r') as f:
341
+ voting_data = json.load(f)
342
+ except FileNotFoundError:
343
+ return pd.DataFrame()
344
+
345
+ # Process each vote
346
+ for vote in voting_data:
347
+ model_a = vote['model_a']
348
+ model_b = vote['model_b']
349
+ winner = vote['winner']
350
+
351
+ # Skip if models aren't in current model_data
352
+ if model_a not in model_data or model_b not in model_data:
353
+ continue
354
+
355
+ # Update match counts
356
+ matches[model_a] += 1
357
+ matches[model_b] += 1
358
+ if winner == "A":
359
+ wins[model_a] += 1
360
+ elif winner == "B":
361
+ wins[model_b] += 1
362
+ else: # Handle ties
363
+ wins[model_a] += 0.5
364
+ wins[model_b] += 0.5
365
+
366
+ # Update ELO ratings
367
+ change_a, change_b = calculate_elo_change(ratings[model_a], ratings[model_b], winner)
368
+ ratings[model_a] += change_a
369
+ ratings[model_b] += change_b
370
+
371
+ # Create leaderboard DataFrame
372
+ leaderboard_data = []
373
+ for model in model_data.keys(): # Only include current models
374
+ win_rate = (wins[model] / matches[model] * 100) if matches[model] > 0 else 0
375
+ ci = 1.96 * (400 / (matches[model] + 1) ** 0.5) if matches[model] > 0 else 0 # Confidence interval
376
+ leaderboard_data.append({
377
+ 'Model': model,
378
+ 'ELO': round(ratings[model], 1),
379
+ '95% CI': f"±{ci:.1f}",
380
+ 'Matches': matches[model],
381
+ 'Win Rate': f"{win_rate:.1f}%",
382
+ 'Organization': model_data[model]['organization'],
383
+ 'License': model_data[model]['license']
384
+ })
385
+
386
+ # Sort by ELO rating
387
+ df = pd.DataFrame(leaderboard_data)
388
+ return df.sort_values('ELO', ascending=False).reset_index(drop=True)
389
+
390
+ # Update the display_leaderboard function
391
+ def display_leaderboard():
392
+ df = update_leaderboard()
393
+ return gr.DataFrame(
394
+ value=df,
395
+ headers=['Model', 'ELO', '95% CI', 'Matches', 'Organization', 'License'],
396
+ datatype=['str', 'number', 'str', 'number', 'str', 'str', 'str'],
397
+ row_count=(len(df) + 1, 'dynamic'),
398
+ )
399
+
400
+ # Update the leaderboard table definition in the UI
401
+ leaderboard_table = gr.Dataframe(
402
+ headers=['Model', 'ELO', '95% CI', 'Matches', 'Organization', 'License'],
403
+ datatype=['str', 'number', 'str', 'number', 'str', 'str', 'str']
404
+ )
405
+
406
+ def get_together_response(model_name, prompt):
407
+ try:
408
+ response = together_client.chat.completions.create(
409
+ model=model_name,
410
+ messages=[
411
+ {"role": "system", "content": SYSTEM_PROMPT},
412
+ {"role": "user", "content": prompt}
413
+ ],
414
+ stream=False
415
+ )
416
+ return response.choices[0].message.content
417
+ except Exception as e:
418
+ return f"Error with Together model {model_name}: {str(e)}"
419
+
420
+ def parse_model_response(response):
421
+ try:
422
+ # Parse JSON response
423
+ data = json.loads(response)
424
+ return data.get('result', 'N/A'), data.get('feedback', 'N/A')
425
+ except:
426
+ # If JSON parsing fails, return original response
427
+ return 'Error', response
428
+
429
+ with gr.Blocks(theme='default', css="""
430
+ .prompt-row {
431
+ align-items: flex-start !important;
432
+ }
433
+ .send-button-row {
434
+ display: flex;
435
+ justify-content: flex-end;
436
+ margin-top: 8px;
437
+ }
438
+ """) as demo:
439
+ judge_id = gr.State(get_new_session_id())
440
+ gr.Markdown("# Judge Arena")
441
+ gr.Markdown("*Free LLM Evals to test your GenAI application.*")
442
+
443
+ with gr.Tabs():
444
+ with gr.TabItem("Judge Arena"):
445
+ # Add introduction section with side-by-side rules and scoring
446
+ gr.Markdown("""
447
+ # How the Arena Works:
448
+
449
+ ## Test two anonymous LLM judges side by side
450
+ Try out different eval metrics - from simple hallucination detection to qualitative interpretations
451
+ """)
452
+
453
+ with gr.Row():
454
+ with gr.Column():
455
+ gr.Markdown("""
456
+ ## 🤺 Battle Rules:
457
+ - Both AIs stay anonymous - if either reveals its identity, the duel is void
458
+ - Evaluate anything: coding, analysis, creative writing, math, or general knowledge
459
+ """)
460
+ with gr.Column():
461
+ gr.Markdown("""
462
+ ## 🧮 Scoring System:
463
+ - Choose the LLM judge that most aligned with your choice as a human
464
+ - If both score the same - choose the critique that you prefer more!
465
+ - Your votes shape our real-time leaderboard
466
+ """)
467
+
468
+ # Add divider heading
469
+ gr.Markdown("""
470
+ # Start Voting Now
471
+ """)
472
+
473
+ # Model Responses side-by-side
474
+ with gr.Row():
475
+ with gr.Column():
476
+ gr.Markdown("### Model A")
477
+ score_a = gr.Textbox(label="Score", interactive=False)
478
+ critique_a = gr.TextArea(label="Critique", lines=8, interactive=False)
479
+ model_name_a = gr.Markdown("*Model: Unknown*")
480
+ with gr.Column():
481
+ gr.Markdown("### Model B")
482
+ score_b = gr.Textbox(label="Score", interactive=False)
483
+ critique_b = gr.TextArea(label="Critique", lines=8, interactive=False)
484
+ model_name_b = gr.Markdown("*Model: Unknown*")
485
+ # Initially hide vote buttons and regenerate button
486
+ with gr.Row(visible=False) as action_buttons_row:
487
+ vote_a = gr.Button("Choose A", variant="primary")
488
+ vote_tie = gr.Button("Tie", variant="secondary")
489
+ vote_b = gr.Button("Choose B", variant="primary")
490
+ regenerate_button = gr.Button("Regenerate with different models", variant="secondary", visible=False)
491
+ # Eval Prompt and Variables below
492
+ with gr.Row(elem_classes="prompt-row"):
493
+ eval_prompt = gr.TextArea(
494
+ label="Eval Prompt",
495
+ lines=1,
496
+ value="""You are assessing a chat bot response to a user's input based on the helpfulness of the response.\n
497
+
498
+ Score:
499
+
500
+ A score of 1 means that the response's answer meets all of the evaluation criteria.
501
+
502
+ A score of 0 means that the response's answer does not meet all of the evaluation criteria.
503
+
504
+ Here is the data:\n
505
+
506
+ [BEGIN DATA]
507
+
508
+ ***
509
+
510
+ [User Query]: {{input}}
511
+
512
+ ***
513
+
514
+ [Response]: {{response}}
515
+
516
+ ***
517
+
518
+ [END DATA]""",
519
+ placeholder="Type your eval prompt here... denote variables like a ground truth response with {{variable}} to be populated below.",
520
+ show_label=True,
521
+ scale=8
522
+ )
523
+ with gr.Row(elem_classes="send-button-row"):
524
+ send_btn = gr.Button(
525
+ value="Send",
526
+ variant="primary",
527
+ size="lg",
528
+ scale=1 # Make button larger
529
+ )
530
+ gr.Markdown("### Variable Mapping")
531
+ # Create inputs for up to 5 variables, with first two visible by default
532
+ variable_rows = []
533
+ for i in range(5):
534
+ # Set initial visibility True for first two rows (input and response)
535
+ initial_visibility = True if i < 2 else False
536
+ with gr.Row(visible=initial_visibility) as var_row:
537
+ with gr.Column(scale=0.2, min_width=80):
538
+ # Set initial labels for input and response
539
+ initial_label = "**input:**" if i == 0 else "**response:**" if i == 1 else "Variable"
540
+ var_label = gr.Markdown(initial_label)
541
+ with gr.Column(scale=1):
542
+ # Set initial values for input and response
543
+ initial_value = "Hello! Can you tell me the weather today?" if i == 0 else \
544
+ "Hi there! It is 27 degrees Celsius today. Would you like the weather for the week ahead?" if i == 1 else ""
545
+ var_input = gr.Textbox(label="", container=False, value=initial_value)
546
+ variable_rows.append((var_row, var_label, var_input))
547
+
548
+ # Add spacing and acknowledgements at the bottom
549
+ gr.Markdown("""
550
+ <br><br><br>
551
+ # Acknowledgements
552
+
553
+ We thank [LMSYS Org](https://lmsys.org/) for their hard work on the Chatbot Arena and fully credit them for the inspiration to build this.
554
+
555
+ We thank [Clementine Fourrier](https://huggingface.co/clefourrier) and Hugging Face for their guidance and partnership in setting this up.
556
+ """)
557
+
558
+ with gr.TabItem("Leaderboard"):
559
+ refresh_button = gr.Button("Refresh")
560
+ leaderboard_table = gr.Dataframe(
561
+ headers=['Model', 'ELO', '95% CI', 'Matches', 'Organization', 'License'],
562
+ datatype=['str', 'number', 'str', 'number', 'str', 'str']
563
+ )
564
+
565
+ with gr.TabItem("Policy"):
566
+ gr.Markdown("""
567
+ # About Atla
568
+
569
+ Atla is an applied research organization that trains models as evaluators to capture human preferences. We're a team of researchers, engineers, and operational leaders, with experience spanning a variety of disciplines, all working together to build reliable and understandable AI systems. Our research is informed by our experiences conducting AI safety research at the UK AI Task Force, OpenAI and the Stanford Existential Risks Initiative.
570
+
571
+ # Our Mission
572
+
573
+ By creating advanced evaluation models, we enable AI developers to identify and fix risks, leading to safer, more reliable AI that can be trusted and widely used. Our aim is to surpass the current state-of-the-art evaluation methods by training models specifically for evaluation. AIs will probably become very powerful, and perform tasks that are difficult for us to verify. We want to enable humans to oversee AI systems that are solving tasks too difficult for humans to evaluate. We have written more about [our approach to scalable oversight](https://www.atla-ai.com/post/scaling-alignment) on our blog.
574
+
575
+ # Judge Arena Policy
576
+
577
+ ## Overview
578
+
579
+ Judge Arena is an open-source platform dedicated to improving the standard of evaluation of generative AI models in their role as judges. Users can run evals and assess anonymized responses from two competing model judges, choosing the better judgement or declaring a tie. This policy outlines our commitments and guidelines to ensure a fair, open, and collaborative environment for both users and model providers.
580
+
581
+ ## Transparency
582
+
583
+ - **Open-Source**: Judge Arena's code is open-source and available on GitHub. This approach allows anyone to review, replicate, or modify the platform to suit their needs. We use proprietary model provider APIs where provided and Together AI's API to serve leading open-source models.
584
+ - **Community Engagement**: We actively encourage contributions from the community. Feedback, code contributions, and discussions are welcome to improve the platform's functionality, fairness, and transparency.
585
+ - **Methodology**: All processes related to model evaluation, rating calculations, and model selection are openly documented. This transparency ensures that our processes are understandable and reproducible by others.
586
+ - **Data Sharing**: Periodically, we will share 20% of the collected evaluation data with the community. This data includes anonymized prompts, model responses, and aggregated evaluation results.
587
+
588
+ ## Model Inclusion Criteria
589
+
590
+ Judge Arena is specifically designed to assess AI models that function as evaluators (a.k.a judges), including but not limited to powerful general-purpose models and the latest language models designed for evaluation tasks. Models are eligible for inclusion if they meet the following criteria:
591
+
592
+ - **Judge Capability**: The model must possess the ability to score AND critique responses, content, or other models' outputs effectively.
593
+ - **Adaptable:** The model must be prompt-able to be evaluate in different scoring formats, for different criteria.
594
+ - **Accessibility**:
595
+ - **Public API Access**: Models accessible through public APIs without restrictive barriers.
596
+ - **Open-Source Models**: Models with publicly available weights that can be downloaded and run by the community.
597
+
598
+ ## Evaluation Methodology
599
+
600
+ - **User Participation**: Users run evaluations and select preferred model responses based on quality, relevance, and accuracy contributing to the model's overall rating.
601
+ - **Blind Testing**: All model evaluations are conducted blindly. Users are not informed which model produced which response to eliminate bias.
602
+ - **Data Collection**: We collect sufficient data to ensure statistical significance in our evaluations. We additionally show the 95% confidence interval in the leaderboard to provide a signal of reliability.
603
+ - **Anomaly Detection**: We monitor user activity to detect and mitigate anomalous behavior or voting patterns that could skew results.
604
+
605
+ ## Leaderboard Management
606
+
607
+ - **ELO Ranking System**: Models are ranked on a public leaderboard based on aggregated user evaluations. We use an ELO rating system to rank AI judges on the public leaderboard. Each model begins with an initial rating of 1500 (as is used by the International Chess Federation), and we use a K-factor of 32 to determine the maximum rating adjustment after each evaluation.
608
+ - **Minimum Period**: Listed models remain accessible on Judge Arena for a minimum period of two weeks to allow for comprehensive community evaluation.
609
+ - **Deprecation Policy**: Models may be removed from the leaderboard if they become inaccessible, are no longer publicly available.
610
+
611
+ ## Privacy and Data Protection
612
+
613
+ - **Anonymization**: All shared data is anonymized to prevent the identification of individual users.
614
+
615
+ ## Policy Updates and Communication
616
+
617
+ - **Ongoing Revisions**: This policy may be updated to reflect changes in our practices or in response to community feedback.
618
+ - **Notification of Changes**: Policy changes will be communicated to users and stakeholders on this page.
619
+
620
+ # FAQ
621
+
622
+ **Isn't this the same as Chatbot Arena?**
623
+
624
+ - We are big fans of what the LMSYS team have done with Chatbot Arena and fully credit them for the inspiration to develop this. We were looking for a dynamic leaderboard that graded on AI judge capabilities and didn't manage to find one, so we created Judge Arena. This UI is designed especially for evals; to match the format of the model-based eval prompts that you would use in your LLM evaluation / monitoring tool.
625
+
626
+ \n\n**Why should I trust this leaderboard?**
627
+
628
+ - We have listed out our efforts to be fully transparent in the policies above. All of the code for this leaderboard is open-source and can be found on our [Github](https://github.com/atla-ai/judge-arena).
629
+
630
+ \n\n**Who funds this effort?**
631
+
632
+ - Atla currently funds this out of our own pocket. We are looking for API credits (with no strings attached) to support this effort - please get in touch if you or someone you know might be able to help.
633
+
634
+ \n\n**What is Atla working on?**
635
+
636
+ - We are training a general-purpose evaluator that you will soon be able to run in this Judge Arena. Our next step will be to open-source a powerful model that the community can use to run fast and accurate evaluations.
637
+
638
+ ## Get in touch
639
+
640
+ Feel free to email us at [support@atla-ai.com](mailto:support@atla-ai.com) or leave feedback on our [Github](https://github.com/atla-ai/judge-arena)!
641
+ """)
642
+
643
+ # Define state variables for model tracking
644
+ model_a_state = gr.State()
645
+ model_b_state = gr.State()
646
+
647
+ # Update variable inputs based on the eval prompt
648
+ def update_variables(eval_prompt):
649
+ variables = parse_variables(eval_prompt)
650
+ updates = []
651
+ for i in range(5):
652
+ var_row, var_label, var_input = variable_rows[i]
653
+ if i < len(variables):
654
+ updates.extend([
655
+ gr.update(visible=True), # var_row
656
+ gr.update(value=f"**{variables[i]}:**"), # var_label
657
+ gr.update(visible=True) # var_input
658
+ ])
659
+ else:
660
+ updates.extend([
661
+ gr.update(visible=False), # var_row
662
+ gr.update(), # var_label
663
+ gr.update(visible=False, value="") # var_input
664
+ ])
665
+ return updates
666
+
667
+ eval_prompt.change(fn=update_variables, inputs=eval_prompt, outputs=[item for sublist in variable_rows for item in sublist])
668
+
669
+ # Regenerate button functionality
670
+ regenerate_button.click(
671
+ fn=regenerate_prompt,
672
+ inputs=[model_a_state, model_b_state, eval_prompt] + [var_input for _, _, var_input in variable_rows],
673
+ outputs=[
674
+ score_a,
675
+ critique_a,
676
+ score_b,
677
+ critique_b,
678
+ action_buttons_row,
679
+ model_name_a,
680
+ model_name_b,
681
+ model_a_state,
682
+ model_b_state
683
+ ]
684
+ )
685
+
686
+ # Update model names after responses are generated
687
+ def update_model_names(model_a, model_b):
688
+ return gr.update(value=f"*Model: {model_a}*"), gr.update(value=f"*Model: {model_b}*")
689
+
690
+ # Store the last submitted prompt and variables for comparison
691
+ last_submission = gr.State({})
692
+
693
+ def handle_input_changes(prompt, *variables):
694
+ """Enable send button and disable regenerate button if inputs have changed"""
695
+ last_inputs = last_submission.value
696
+ current_inputs = {"prompt": prompt, "variables": variables}
697
+ inputs_changed = last_inputs != current_inputs
698
+ return [
699
+ gr.update(interactive=True), # Always keep send button enabled
700
+ gr.update(visible=False) # Hide regenerate button when inputs change
701
+ ]
702
+
703
+ # Update the vote button click handlers
704
+ vote_a.click(
705
+ fn=lambda *args: vote('A', *args),
706
+ inputs=[model_a_state, model_b_state, eval_prompt, score_a, score_b, judge_id],
707
+ outputs=[action_buttons_row, model_name_a, model_name_b, send_btn, regenerate_button]
708
+ )
709
+
710
+ vote_b.click(
711
+ fn=lambda *args: vote('B', *args),
712
+ inputs=[model_a_state, model_b_state, eval_prompt, score_a, score_b, judge_id],
713
+ outputs=[action_buttons_row, model_name_a, model_name_b, send_btn, regenerate_button]
714
+ )
715
+
716
+ vote_tie.click(
717
+ fn=lambda *args: vote('Tie', *args),
718
+ inputs=[model_a_state, model_b_state, eval_prompt, score_a, score_b, judge_id],
719
+ outputs=[action_buttons_row, model_name_a, model_name_b, send_btn, regenerate_button]
720
+ )
721
+
722
+ # Update the send button handler to store the submitted inputs
723
+ def submit_and_store(prompt, *variables):
724
+ last_submission.value = {"prompt": prompt, "variables": variables}
725
+ response_a, response_b, buttons_visible, regen_visible, model_a, model_b = submit_prompt(prompt, *variables)
726
+
727
+ # Parse the responses
728
+ score_a, critique_a = parse_model_response(response_a)
729
+ score_b, critique_b = parse_model_response(response_b)
730
+
731
+ return (
732
+ score_a,
733
+ critique_a,
734
+ score_b,
735
+ critique_b,
736
+ buttons_visible,
737
+ gr.update(visible=False), # Hide regenerate button on new submission
738
+ model_a,
739
+ model_b,
740
+ gr.update(value="*Model: Unknown*"),
741
+ gr.update(value="*Model: Unknown*")
742
+ )
743
+
744
+ send_btn.click(
745
+ fn=submit_and_store,
746
+ inputs=[eval_prompt] + [var_input for _, _, var_input in variable_rows],
747
+ outputs=[
748
+ score_a,
749
+ critique_a,
750
+ score_b,
751
+ critique_b,
752
+ action_buttons_row,
753
+ regenerate_button,
754
+ model_a_state,
755
+ model_b_state,
756
+ model_name_a, # Add model name outputs
757
+ model_name_b
758
+ ]
759
+ )
760
+
761
+ # Update the input change handlers to also disable regenerate button
762
+ def handle_input_changes(prompt, *variables):
763
+ """Enable send button and disable regenerate button if inputs have changed"""
764
+ last_inputs = last_submission.value
765
+ current_inputs = {"prompt": prompt, "variables": variables}
766
+ inputs_changed = last_inputs != current_inputs
767
+ return [
768
+ gr.update(interactive=inputs_changed), # send button
769
+ gr.update(interactive=not inputs_changed) # regenerate button
770
+ ]
771
+
772
+ # Update the change handlers for prompt and variables
773
+ eval_prompt.change(
774
+ fn=handle_input_changes,
775
+ inputs=[eval_prompt] + [var_input for _, _, var_input in variable_rows],
776
+ outputs=[send_btn, regenerate_button]
777
+ )
778
+
779
+ for _, _, var_input in variable_rows:
780
+ var_input.change(
781
+ fn=handle_input_changes,
782
+ inputs=[eval_prompt] + [var_input for _, _, var_input in variable_rows],
783
+ outputs=[send_btn, regenerate_button]
784
+ )
785
+
786
+ # Update the leaderboard
787
+ def update_leaderboard():
788
+ leaderboard = get_leaderboard()
789
+ data = [
790
+ [
791
+ entry['Model'],
792
+ float(entry['ELO Score']),
793
+ entry['95% CI'],
794
+ entry['# Votes'],
795
+ entry['Organization'],
796
+ entry['License']
797
+ ] for entry in leaderboard
798
+ ]
799
+ return gr.update(value=data)
800
+
801
+ refresh_button.click(fn=update_leaderboard, inputs=None, outputs=leaderboard_table)
802
+
803
+ demo.launch()
804
+
805
+