zhiminy commited on
Commit
9c68964
0 Parent(s):
Files changed (5) hide show
  1. .gitignore +3 -0
  2. README.md +82 -0
  3. app.py +782 -0
  4. context_window.json +23 -0
  5. requirements.txt +7 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ *.env
2
+ *.venv
3
+ *.pem
README.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: SE-Arena
3
+ emoji: 🛠️
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: "5.7.1"
8
+ app_file: app.py
9
+ hf_oauth: true
10
+ pinned: false
11
+ ---
12
+
13
+ # SE Arena: Explore and Test the Best SE Chatbots with Long-Context Interactions
14
+
15
+ Welcome to **SE Arena**, an open-source platform for evaluating software engineering-focused chatbots. SE Arena is designed to benchmark foundation models (FMs), including large language models (LLMs), in iterative and context-rich workflows characteristic of software engineering (SE) tasks.
16
+
17
+ ## Key Features
18
+
19
+ - **Interactive Evaluation**: Test chatbots in multi-round conversations tailored for debugging, code generation, and requirement refinement.
20
+ - **Transparent Leaderboard**: View model rankings across diverse SE workflows, updated in real-time using advanced metrics.
21
+ - **Advanced Pairwise Comparisons**: Evaluate chatbots using metrics like Elo score, PageRank, and Newman modularity to understand their global dominance and task-specific strengths.
22
+ - **Open-Source**: Built on [Hugging Face Spaces](https://huggingface.co/spaces/SE-Arena/Software-Engineering-Arena), fostering transparency and community-driven innovation.
23
+
24
+ ## Why SE Arena?
25
+
26
+ Existing evaluation frameworks often fall short in addressing the complex, iterative nature of SE tasks. SE Arena fills this gap by:
27
+
28
+ - Supporting long-context, multi-turn evaluations.
29
+ - Allowing comparisons of anonymous models without bias.
30
+ - Providing rich, multidimensional metrics for nuanced evaluations.
31
+
32
+ ## How It Works
33
+
34
+ 1. **Submit a Prompt**: Sign in and input your SE-related task (e.g., debugging, code reviews).
35
+ 2. **Compare Responses**: Two chatbots respond to your query side-by-side.
36
+ 3. **Vote**: Choose the better response, mark as tied, or select "Can't Decide."
37
+ 4. **Iterative Testing**: Continue the conversation with follow-up prompts to test long-context understanding.
38
+
39
+ ## Metrics Used
40
+
41
+ SE Arena goes beyond traditional Elo scores by incorporating:
42
+
43
+ - **Eigenvector Centrality**: Highlights models that perform well against high-quality competitors.
44
+ - **PageRank**: Accounts for cyclic dependencies and emphasizes importance in dense sub-networks.
45
+ - **Newman Modularity**: Groups models into clusters based on similar performance patterns, helping users identify task-specific expertise.
46
+
47
+ ## Getting Started
48
+
49
+ ### Prerequisites
50
+
51
+ - A [Hugging Face](https://huggingface.co) account.
52
+ - Basic knowledge of software engineering workflows.
53
+
54
+ ### Usage
55
+
56
+ 1. Navigate to the [SE Arena platform](https://huggingface.co/spaces/SE-Arena/Software-Engineering-Arena).
57
+ 2. Sign in with your Hugging Face account.
58
+ 3. Enter your SE task prompt and start evaluating model responses.
59
+ 4. Vote on the better response or continue multi-round interactions to test contextual understanding.
60
+
61
+ ## Contributing
62
+
63
+ We welcome contributions from the community! Here's how you can help:
64
+
65
+ 1. **Submit Prompts**: Share your SE-related tasks to enrich our evaluation dataset.
66
+ 2. **Report Issues**: Found a bug or have a feature request? Open an issue in this repository.
67
+ 3. **Enhance the Codebase**: Fork the repository, make your changes, and submit a pull request.
68
+
69
+ ## Privacy Policy
70
+
71
+ Your interactions are anonymized and used solely for improving SE Arena and foundation model benchmarking. By using SE Arena, you agree to our [Terms of Service](#).
72
+
73
+ ## Future Plans
74
+
75
+ - **Enhanced Metrics**: Add round-wise analysis and context-aware metrics.
76
+ - **Domain-Specific Sub-Leaderboards**: Focused rankings for debugging, requirement refinement, etc.
77
+ - **Integration of Advanced Context Compression**: Techniques like LongRope and SelfExtend for long-term memory.
78
+ - **Support for Multimodal Models**: Evaluate models integrating text, code, and other modalities.
79
+
80
+ ## Contact
81
+
82
+ For inquiries or feedback, please [open an issue](https://github.com/zhimin-z/SE-Arena/issues/new) in this repository. We welcome your contributions and suggestions!
app.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dotenv
2
+ import evalica
3
+ import io
4
+ import json
5
+ import os
6
+ import random
7
+ import threading
8
+
9
+ import aisuite as ai
10
+ import gradio as gr
11
+ import pandas as pd
12
+
13
+ from huggingface_hub import upload_file, hf_hub_download, HfFolder, HfApi
14
+ from datetime import datetime
15
+ from gradio_leaderboard import Leaderboard
16
+
17
+ # Load environment variables
18
+ dotenv.load_dotenv()
19
+
20
+ # Retrieve the secret from the environment
21
+ gcp_credentials = os.environ.get("GCP_CREDENTIALS")
22
+
23
+ # Write it to a file
24
+ credentials_path = (
25
+ "/tmp/gcp_credentials.json" # Ensure this path is secure and temporary
26
+ )
27
+ with open(credentials_path, "w") as f:
28
+ f.write(gcp_credentials)
29
+
30
+ # Set the environment variable for GCP SDKs
31
+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = credentials_path
32
+
33
+ # Timeout in seconds for model response
34
+ TIMEOUT = 60
35
+
36
+ # Initialize AISuite Client
37
+ client = ai.Client()
38
+
39
+ # Hint string constant
40
+ SHOW_HINT_STRING = True # Set to False to hide the hint string altogether
41
+ HINT_STRING = "Once signed in, your votes will be recorded securely."
42
+
43
+ # Load context length limits
44
+ with open("context_window.json", "r") as file:
45
+ context_window = json.load(file)
46
+
47
+ # Get list of available models
48
+ available_models = list(context_window.keys())
49
+ if len(available_models) < 2:
50
+ raise ValueError(
51
+ "Insufficient models in context_window.json. At least two are required."
52
+ )
53
+
54
+ # Initialize global variables
55
+ models_state = {}
56
+ conversation_state = {}
57
+
58
+ # Define functions here
59
+
60
+
61
+ # Truncate prompt
62
+ def truncate_prompt(prompt, model_alias, models):
63
+ model_name = models[model_alias]
64
+ context_length = context_window.get(model_name, 4096)
65
+ while len(json.dumps({"role": "user", "content": prompt})) > context_length:
66
+ prompt = prompt[:-10] if len(prompt) > 10 else prompt[:1]
67
+ return prompt
68
+
69
+
70
+ def chat_with_models(user_input, model_alias, models, conversation_state, timeout=TIMEOUT):
71
+ model_name = models[model_alias]
72
+ truncated_input = truncate_prompt(user_input, model_alias, models)
73
+ conversation_state.setdefault(model_name, []).append(
74
+ {"role": "user", "content": user_input}
75
+ )
76
+
77
+ response_event = threading.Event() # Event to signal response completion
78
+ model_response = {"content": None, "error": None}
79
+
80
+ def request_model_response():
81
+ try:
82
+ response = client.chat.completions.create(
83
+ model=model_name,
84
+ messages=[{"role": "user", "content": truncated_input}],
85
+ )
86
+ model_response["content"] = response.choices[0].message.content
87
+ except Exception as e:
88
+ model_response["error"] = f"{model_name} model is not available. Error: {e}"
89
+ finally:
90
+ response_event.set() # Signal that the response is completed
91
+
92
+ # Start the model request in a separate thread
93
+ response_thread = threading.Thread(target=request_model_response)
94
+ response_thread.start()
95
+
96
+ # Wait for the specified timeout
97
+ response_event_occurred = response_event.wait(timeout)
98
+
99
+ if not response_event_occurred:
100
+ # Timeout occurred, raise a TimeoutError to be handled in the Gradio interface
101
+ raise TimeoutError(
102
+ f"The {model_alias} model did not respond within {timeout} seconds."
103
+ )
104
+ elif model_response["error"]:
105
+ # An error occurred during model response
106
+ raise Exception(model_response["error"])
107
+ else:
108
+ # Successful response
109
+ formatted_response = f"```\n{model_response['content']}\n```"
110
+ conversation_state[model_name].append(
111
+ {"role": "assistant", "content": model_response["content"]}
112
+ )
113
+ return formatted_response
114
+
115
+
116
+ def save_content_to_hf(content, repo_name):
117
+ """
118
+ Save feedback content to Hugging Face repository organized by month and year.
119
+
120
+ Args:
121
+ content (dict): Feedback data to be saved.
122
+ month_year (str): Year and month string in the format "YYYY_MM".
123
+ repo_name (str): Hugging Face repository name.
124
+ """
125
+ # Ensure the user is authenticated with HF
126
+ token = HfFolder.get_token()
127
+ if token is None:
128
+ raise ValueError("Please log in to Hugging Face using `huggingface-cli login`.")
129
+
130
+ # Serialize the content to JSON and encode it as bytes
131
+ json_content = json.dumps(content, indent=4).encode("utf-8")
132
+
133
+ # Create a binary file-like object
134
+ file_like_object = io.BytesIO(json_content)
135
+
136
+ # Get the current year and month
137
+ month_year = datetime.now().strftime("%Y_%m")
138
+ day_hour_minute_second = datetime.now().strftime("%d_%H%M%S")
139
+
140
+ # Define the path in the repository
141
+ filename = f"{month_year}/{day_hour_minute_second}.json"
142
+
143
+ # Upload to Hugging Face repository
144
+ upload_file(
145
+ path_or_fileobj=file_like_object,
146
+ path_in_repo=filename,
147
+ repo_id=repo_name,
148
+ repo_type="dataset",
149
+ use_auth_token=token,
150
+ )
151
+
152
+
153
+ def load_content_from_hf(repo_name="SE-Arena/votes"):
154
+ """
155
+ Read feedback content from a Hugging Face repository based on the current month and year.
156
+
157
+ Args:
158
+ repo_name (str): Hugging Face repository name.
159
+
160
+ Returns:
161
+ list: Aggregated feedback data read from the repository.
162
+ """
163
+
164
+ # Get the current year and month
165
+ year_month = datetime.now().strftime("%Y_%m")
166
+ feedback_data = []
167
+
168
+ try:
169
+ api = HfApi()
170
+
171
+ # List all files in the repository
172
+ repo_files = api.list_repo_files(repo_id="SE-Arena/votes", repo_type="dataset")
173
+
174
+ # Filter files by current year and month
175
+ feedback_files = [file for file in repo_files if year_month in file]
176
+
177
+ if not feedback_files:
178
+ raise FileNotFoundError(
179
+ f"No feedback files found for {year_month} in {repo_name}."
180
+ )
181
+
182
+ # Download and aggregate data
183
+ for file in feedback_files:
184
+ local_path = hf_hub_download(
185
+ repo_id=repo_name, filename=file, repo_type="dataset"
186
+ )
187
+ with open(local_path, "r") as f:
188
+ data = json.load(f)
189
+ if isinstance(data, list):
190
+ feedback_data.extend(data)
191
+ elif isinstance(data, dict):
192
+ feedback_data.append(data)
193
+
194
+ return feedback_data
195
+
196
+ except:
197
+ raise Exception("Error loading feedback data from Hugging Face repository.")
198
+
199
+
200
+ def get_leaderboard_data():
201
+ # Load feedback data from the Hugging Face repository
202
+ try:
203
+ feedback_data = load_content_from_hf()
204
+ feedback_df = pd.DataFrame(feedback_data)
205
+ except:
206
+ # If no feedback exists, return an empty DataFrame
207
+ return pd.DataFrame(
208
+ columns=[
209
+ "Rank",
210
+ "Model",
211
+ "Elo Score",
212
+ "Average Win Rate",
213
+ "Bradley-Terry Coefficient",
214
+ "Eigenvector Centrality Value",
215
+ "PageRank Score",
216
+ "Newman Modularity Score",
217
+ ]
218
+ )
219
+
220
+ feedback_df["winner"] = feedback_df["winner"].map(
221
+ {
222
+ "left": evalica.Winner.X,
223
+ "right": evalica.Winner.Y,
224
+ "tie": evalica.Winner.Draw,
225
+ }
226
+ )
227
+
228
+ # Calculate scores using various metrics
229
+ avr_result = evalica.average_win_rate(
230
+ feedback_df["left"], feedback_df["right"], feedback_df["winner"]
231
+ )
232
+ bt_result = evalica.bradley_terry(
233
+ feedback_df["left"], feedback_df["right"], feedback_df["winner"]
234
+ )
235
+ newman_result = evalica.newman(
236
+ feedback_df["left"], feedback_df["right"], feedback_df["winner"]
237
+ )
238
+ eigen_result = evalica.eigen(
239
+ feedback_df["left"], feedback_df["right"], feedback_df["winner"]
240
+ )
241
+ elo_result = evalica.elo(
242
+ feedback_df["left"], feedback_df["right"], feedback_df["winner"]
243
+ )
244
+ pagerank_result = evalica.pagerank(
245
+ feedback_df["left"], feedback_df["right"], feedback_df["winner"]
246
+ )
247
+
248
+ # Combine all results into a single DataFrame
249
+ ranking_df = pd.DataFrame(
250
+ {
251
+ "Model": elo_result.scores.index,
252
+ "Elo Score": elo_result.scores.values,
253
+ "Average Win Rate": avr_result.scores.values * 100,
254
+ "Bradley-Terry Coefficient": bt_result.scores.values,
255
+ "Eigenvector Centrality Value": eigen_result.scores.values,
256
+ "PageRank Score": pagerank_result.scores.values,
257
+ "Newman Modularity Score": newman_result.scores.values,
258
+ }
259
+ )
260
+
261
+ # Add a Rank column based on Elo scores
262
+ ranking_df["Rank"] = (
263
+ ranking_df["Elo Score"].rank(ascending=False, method="min").astype(int)
264
+ )
265
+
266
+ # Round all numeric columns to two decimal places
267
+ ranking_df = ranking_df.round(
268
+ {
269
+ "Elo Score": 2,
270
+ "Average Win Rate": 2,
271
+ "Bradley-Terry Coefficient": 2,
272
+ "Eigenvector Centrality Value": 2,
273
+ "PageRank Score": 2,
274
+ "Newman Modularity Score": 2,
275
+ }
276
+ )
277
+
278
+ # Reorder columns to make 'Rank' the first column
279
+ ranking_df = ranking_df.sort_values(by="Rank").reset_index(drop=True)
280
+
281
+ ranking_df = ranking_df[
282
+ [
283
+ "Rank",
284
+ "Model",
285
+ "Elo Score",
286
+ "Average Win Rate",
287
+ "Bradley-Terry Coefficient",
288
+ "Eigenvector Centrality Value",
289
+ "PageRank Score",
290
+ "Newman Modularity Score",
291
+ ]
292
+ ]
293
+
294
+ return ranking_df
295
+
296
+
297
+ # Function to enable or disable submit buttons based on textbox content
298
+ def toggle_submit_button(text):
299
+ if not text or text.strip() == "":
300
+ return gr.update(interactive=False)
301
+ else:
302
+ return gr.update(interactive=True)
303
+
304
+
305
+ # Gradio Interface
306
+ with gr.Blocks() as app:
307
+ user_authenticated = gr.State(False)
308
+ models_state = gr.State({})
309
+ conversation_state = gr.State({})
310
+
311
+ with gr.Tab("🏆Leaderboard"):
312
+ # Add title and description as a Markdown component
313
+ leaderboard_intro = gr.Markdown(
314
+ """
315
+ # 🏆 Software Engineering Arena Leaderboard: Community-Driven Evaluation of Top SE Chatbots
316
+
317
+ The Software Engineering (SE) Arena is an open-source platform designed to evaluate language models through human preference, fostering transparency and collaboration. Developed by researchers at [Software Analysis and Intelligence Lab (SAIL)](https://sail.cs.queensu.ca), the platform empowers the community to assess and compare the performance of leading foundation models in SE tasks. For technical details, check out our [paper](https://arxiv.org/abs/your-paper-link).
318
+ """,
319
+ elem_classes="leaderboard-intro",
320
+ )
321
+ # Initialize the leaderboard with the DataFrame containing the expected columns
322
+ leaderboard_component = Leaderboard(
323
+ value=get_leaderboard_data(),
324
+ select_columns=[
325
+ "Rank",
326
+ "Model",
327
+ "Elo Score",
328
+ "Average Win Rate",
329
+ ],
330
+ search_columns=["Model"],
331
+ filter_columns=[
332
+ "Elo Score",
333
+ "Average Win Rate",
334
+ "Bradley-Terry Coefficient",
335
+ "Eigenvector Centrality Value",
336
+ "PageRank Score",
337
+ "Newman Modularity Score",
338
+ ],
339
+ )
340
+ with gr.Tab("⚔️Arena"):
341
+ # Add title and description as a Markdown component
342
+ arena_intro = gr.Markdown(
343
+ """
344
+ # ⚔️ Software Engineering (SE) Arena: Explore and Test the Best SE Chatbots with Long-Context Interactions
345
+
346
+ ## 📜How It Works
347
+ - **Blind Comparison**: Submit any software engineering-related query to two anonymous chatbots, including top models like ChatGPT, Gemini, Claude, Llama, and others.
348
+ - **Interactive Voting**: Engage in multi-turn dialogues and compare responses. Continue the conversation until you're confident in choosing the better model.
349
+ - **Fair Play Rules**: Votes are valid only when chatbot identities remain anonymous—revealed identities disqualify the session.
350
+
351
+ **Note:** Due to budget constraints, responses that take longer than one minute to generate will be discarded.
352
+ """,
353
+ elem_classes="arena-intro",
354
+ )
355
+ # Add Hugging Face Sign In button and message
356
+ with gr.Row():
357
+ # Define the markdown text with or without the hint string
358
+ markdown_text = "## Please sign in using the button on the right to vote!"
359
+ if SHOW_HINT_STRING:
360
+ markdown_text += f"\n{HINT_STRING}"
361
+ hint_markdown = gr.Markdown(markdown_text, elem_classes="markdown-text")
362
+ login_button = gr.Button(
363
+ "Sign in with Hugging Face", elem_id="oauth-button"
364
+ )
365
+
366
+ # Components with initial non-interactive state
367
+ shared_input = gr.Textbox(
368
+ label="Enter your prompt for both models",
369
+ lines=2,
370
+ interactive=False, # Initially non-interactive
371
+ )
372
+ send_first = gr.Button(
373
+ "Submit", visible=True, interactive=False
374
+ ) # Initially non-interactive
375
+
376
+ # Add event listener to shared_input to toggle send_first button
377
+ shared_input.change(
378
+ fn=toggle_submit_button, inputs=shared_input, outputs=send_first
379
+ )
380
+
381
+ user_prompt_md = gr.Markdown(value="", visible=False)
382
+
383
+ with gr.Column():
384
+ shared_input
385
+ user_prompt_md
386
+
387
+ with gr.Row():
388
+ response_a_title = gr.Markdown(value="", visible=False)
389
+ response_b_title = gr.Markdown(value="", visible=False)
390
+
391
+ with gr.Row():
392
+ response_a = gr.Markdown(label="Response from Model A")
393
+ response_b = gr.Markdown(label="Response from Model B")
394
+
395
+ # Add a popup component for timeout notification
396
+ with gr.Row(visible=False) as timeout_popup:
397
+ timeout_message = gr.Markdown(
398
+ "### Timeout\n\nOne of the models did not respond within 1 minute. Please try again."
399
+ )
400
+ close_popup_btn = gr.Button("Okay")
401
+
402
+ def close_timeout_popup():
403
+ # Re-enable or disable the submit buttons based on the current textbox content
404
+ shared_input_state = gr.update(interactive=True)
405
+ send_first_state = toggle_submit_button(shared_input.value)
406
+
407
+ model_a_input_state = gr.update(interactive=True)
408
+ model_a_send_state = toggle_submit_button(model_a_input.value)
409
+
410
+ model_b_input_state = gr.update(interactive=True)
411
+ model_b_send_state = toggle_submit_button(model_b_input.value)
412
+
413
+ return (
414
+ gr.update(visible=False), # Hide the timeout popup
415
+ shared_input_state, # Update shared_input
416
+ send_first_state, # Update send_first button
417
+ model_a_input_state, # Update model_a_input
418
+ model_a_send_state, # Update model_a_send button
419
+ model_b_input_state, # Update model_b_input
420
+ model_b_send_state, # Update model_b_send button
421
+ )
422
+
423
+ # Multi-round inputs, initially hidden
424
+ with gr.Row(visible=False) as multi_round_inputs:
425
+ model_a_input = gr.Textbox(label="Model A Input", lines=1)
426
+ model_a_send = gr.Button(
427
+ "Send to Model A", interactive=False
428
+ ) # Initially disabled
429
+
430
+ model_b_input = gr.Textbox(label="Model B Input", lines=1)
431
+ model_b_send = gr.Button(
432
+ "Send to Model B", interactive=False
433
+ ) # Initially disabled
434
+
435
+ # Add event listeners to model_a_input and model_b_input to toggle their submit buttons
436
+ model_a_input.change(
437
+ fn=toggle_submit_button, inputs=model_a_input, outputs=model_a_send
438
+ )
439
+
440
+ model_b_input.change(
441
+ fn=toggle_submit_button, inputs=model_b_input, outputs=model_b_send
442
+ )
443
+
444
+ close_popup_btn.click(
445
+ close_timeout_popup,
446
+ inputs=[],
447
+ outputs=[
448
+ timeout_popup,
449
+ shared_input,
450
+ send_first,
451
+ model_a_input,
452
+ model_a_send,
453
+ model_b_input,
454
+ model_b_send,
455
+ ],
456
+ )
457
+
458
+ # Function to update model titles and responses
459
+ def update_model_titles_and_responses(
460
+ user_input, models_state, conversation_state
461
+ ):
462
+ # Dynamically select two random models
463
+ if len(available_models) < 2:
464
+ raise ValueError(
465
+ "Insufficient models in context_window.json. At least two are required."
466
+ )
467
+ selected_models = random.sample(available_models, 2)
468
+ models = {"Model A": selected_models[0], "Model B": selected_models[1]}
469
+
470
+ # Update the states
471
+ models_state.clear()
472
+ models_state.update(models)
473
+ conversation_state.clear()
474
+ conversation_state.update({name: [] for name in models.values()})
475
+
476
+ try:
477
+ response_a = chat_with_models(
478
+ user_input, "Model A", models_state, conversation_state
479
+ )
480
+ response_b = chat_with_models(
481
+ user_input, "Model B", models_state, conversation_state
482
+ )
483
+ except TimeoutError as e:
484
+ # Handle the timeout by resetting components, showing a popup, and disabling inputs
485
+ return (
486
+ gr.update(
487
+ value="", interactive=False, visible=True
488
+ ), # Disable shared_input
489
+ gr.update(value="", visible=False), # Hide user_prompt_md
490
+ gr.update(value="", visible=False), # Hide Model A title
491
+ gr.update(value="", visible=False), # Hide Model B title
492
+ gr.update(value=""), # Clear response from Model A
493
+ gr.update(value=""), # Clear response from Model B
494
+ gr.update(visible=False), # Hide multi-round inputs
495
+ gr.update(visible=False), # Hide vote panel
496
+ gr.update(visible=True, interactive=False), # Disable submit button
497
+ gr.update(interactive=False), # Disable feedback selection
498
+ models_state,
499
+ conversation_state,
500
+ gr.update(visible=True), # Show the timeout popup
501
+ )
502
+ except Exception as e:
503
+ raise gr.Error(str(e))
504
+
505
+ # Determine the initial state of the multi-round send buttons
506
+ model_a_send_state = toggle_submit_button("")
507
+ model_b_send_state = toggle_submit_button("")
508
+
509
+ return (
510
+ gr.update(visible=False), # Hide shared_input
511
+ gr.update(
512
+ value=f"**Your Prompt:**\n\n{user_input}", visible=True
513
+ ), # Show user_prompt_md
514
+ gr.update(value=f"### Model A:", visible=True),
515
+ gr.update(value=f"### Model B:", visible=True),
516
+ gr.update(value=response_a), # Show Model A response
517
+ gr.update(value=response_b), # Show Model B response
518
+ gr.update(visible=True), # Show multi-round inputs
519
+ gr.update(visible=True), # Show vote panel
520
+ gr.update(visible=False), # Hide submit button
521
+ gr.update(interactive=True), # Enable feedback selection
522
+ models_state,
523
+ conversation_state,
524
+ gr.update(visible=False), # Hide the timeout popup if it was visible
525
+ model_a_send_state, # Set model_a_send button state
526
+ model_b_send_state, # Set model_b_send button state
527
+ )
528
+
529
+ # Feedback panel, initially hidden
530
+ with gr.Row(visible=False) as vote_panel:
531
+ feedback = gr.Radio(
532
+ choices=["Model A", "Model B", "Can't Decide"],
533
+ label="Which model do you prefer?",
534
+ value="Can't Decide",
535
+ interactive=False, # Initially not interactive
536
+ )
537
+ submit_feedback_btn = gr.Button("Submit Feedback", interactive=False)
538
+
539
+ # Function to handle login
540
+ def handle_login():
541
+ """
542
+ Handle user login using Hugging Face OAuth with automatic redirection.
543
+ """
544
+ try:
545
+ # Use Hugging Face OAuth to initiate login
546
+ HfApi()
547
+
548
+ # Wait for user authentication and get the token
549
+ print(
550
+ "Redirected to Hugging Face for authentication. Please complete the login."
551
+ )
552
+ token = HfFolder.get_token()
553
+ if not token:
554
+ raise Exception("Authentication token not found.")
555
+
556
+ # If token is successfully retrieved, update the interface state
557
+ return (
558
+ gr.update(visible=False), # Hide the login button
559
+ gr.update(interactive=True), # Enable shared_input
560
+ gr.update(interactive=True), # Enable send_first button
561
+ gr.update(interactive=True), # Enable feedback radio buttons
562
+ gr.update(interactive=True), # Enable submit_feedback_btn
563
+ gr.update(visible=False), # Hide the hint string
564
+ )
565
+ except Exception as e:
566
+ # Handle login failure
567
+ print(f"Login failed: {e}")
568
+ return (
569
+ gr.update(visible=True), # Keep the login button visible
570
+ gr.update(interactive=False), # Keep shared_input disabled
571
+ gr.update(interactive=False), # Keep send_first disabled
572
+ gr.update(
573
+ interactive=False
574
+ ), # Keep feedback radio buttons disabled
575
+ gr.update(interactive=False), # Keep submit_feedback_btn disabled
576
+ gr.update(visible=True), # Show the hint string
577
+ )
578
+
579
+ # Handle the login button click
580
+ login_button.click(
581
+ handle_login,
582
+ inputs=[],
583
+ outputs=[
584
+ login_button, # Hide the login button after successful login
585
+ shared_input, # Enable shared_input
586
+ send_first, # Enable send_first button
587
+ feedback, # Enable feedback radio buttons
588
+ submit_feedback_btn, # Enable submit_feedback_btn
589
+ hint_markdown, # Hide the hint string
590
+ ],
591
+ )
592
+
593
+ # First round handling
594
+ send_first.click(
595
+ update_model_titles_and_responses,
596
+ inputs=[shared_input, models_state, conversation_state],
597
+ outputs=[
598
+ shared_input, # shared_input
599
+ user_prompt_md, # user_prompt_md
600
+ response_a_title, # response_a_title
601
+ response_b_title, # response_b_title
602
+ response_a, # response_a
603
+ response_b, # response_b
604
+ multi_round_inputs, # multi_round_inputs
605
+ vote_panel, # vote_panel
606
+ send_first, # send_first
607
+ feedback, # feedback
608
+ models_state, # models_state
609
+ conversation_state, # conversation_state
610
+ timeout_popup, # timeout_popup
611
+ model_a_send, # model_a_send state
612
+ model_b_send, # model_b_send state
613
+ ],
614
+ )
615
+
616
+ # Handle subsequent rounds
617
+ def handle_model_a_send(user_input, models_state, conversation_state):
618
+ try:
619
+ response = chat_with_models(
620
+ user_input, "Model A", models_state, conversation_state
621
+ )
622
+ # Clear the input box and disable the send button
623
+ return (
624
+ response,
625
+ conversation_state,
626
+ gr.update(visible=False),
627
+ gr.update(
628
+ value="", interactive=True
629
+ ), # Clear and enable model_a_input
630
+ gr.update(interactive=False), # Disable model_a_send button
631
+ )
632
+ except TimeoutError as e:
633
+ # Disable inputs when timeout occurs
634
+ return (
635
+ gr.update(value=""), # Clear response
636
+ conversation_state,
637
+ gr.update(visible=True), # Show the timeout popup
638
+ gr.update(interactive=False), # Disable model_a_input
639
+ gr.update(interactive=False), # Disable model_a_send
640
+ )
641
+ except Exception as e:
642
+ raise gr.Error(str(e))
643
+
644
+ def handle_model_b_send(user_input, models_state, conversation_state):
645
+ try:
646
+ response = chat_with_models(
647
+ user_input, "Model B", models_state, conversation_state
648
+ )
649
+ # Clear the input box and disable the send button
650
+ return (
651
+ response,
652
+ conversation_state,
653
+ gr.update(visible=False),
654
+ gr.update(
655
+ value="", interactive=True
656
+ ), # Clear and enable model_b_input
657
+ gr.update(interactive=False), # Disable model_b_send button
658
+ )
659
+ except TimeoutError as e:
660
+ # Disable inputs when timeout occurs
661
+ return (
662
+ gr.update(value=""), # Clear response
663
+ conversation_state,
664
+ gr.update(visible=True), # Show the timeout popup
665
+ gr.update(interactive=False), # Disable model_b_input
666
+ gr.update(interactive=False), # Disable model_b_send
667
+ )
668
+ except Exception as e:
669
+ raise gr.Error(str(e))
670
+
671
+ model_a_send.click(
672
+ handle_model_a_send,
673
+ inputs=[model_a_input, models_state, conversation_state],
674
+ outputs=[
675
+ response_a,
676
+ conversation_state,
677
+ timeout_popup,
678
+ model_a_input,
679
+ model_a_send,
680
+ ],
681
+ )
682
+ model_b_send.click(
683
+ handle_model_b_send,
684
+ inputs=[model_b_input, models_state, conversation_state],
685
+ outputs=[
686
+ response_b,
687
+ conversation_state,
688
+ timeout_popup,
689
+ model_b_input,
690
+ model_b_send,
691
+ ],
692
+ )
693
+
694
+ def submit_feedback(vote, models_state, conversation_state):
695
+ # Get current timestamp
696
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
697
+
698
+ # Map vote to actual model names
699
+ match vote:
700
+ case "Model A":
701
+ winner_model = "left"
702
+ case "Model B":
703
+ winner_model = "right"
704
+ case "Can't Decide":
705
+ winner_model = "tie"
706
+
707
+ # Create feedback entry
708
+ feedback_entry = {
709
+ "left": models_state["Model A"],
710
+ "right": models_state["Model B"],
711
+ "winner": winner_model,
712
+ "timestamp": timestamp,
713
+ }
714
+
715
+ # Save feedback back to the Hugging Face dataset
716
+ save_content_to_hf(feedback_entry, "SE-Arena/votes")
717
+
718
+ # Save conversations back to the Hugging Face dataset
719
+ save_content_to_hf(conversation_state, "SE-Arena/conversations")
720
+
721
+ # Clear state
722
+ models_state.clear()
723
+ conversation_state.clear()
724
+
725
+ # Recalculate leaderboard
726
+ leaderboard_data = get_leaderboard_data()
727
+
728
+ # Adjust output count to match the interface definition
729
+ return (
730
+ gr.update(
731
+ value="", interactive=True, visible=True
732
+ ), # Clear and show shared_input
733
+ gr.update(value="", visible=False), # Hide user_prompt_md
734
+ gr.update(value="", visible=False), # Hide response_a_title
735
+ gr.update(value="", visible=False), # Hide response_b_title
736
+ gr.update(value=""), # Clear Model A response
737
+ gr.update(value=""), # Clear Model B response
738
+ gr.update(visible=False), # Hide multi-round inputs
739
+ gr.update(visible=False), # Hide vote panel
740
+ gr.update(
741
+ value="Submit", interactive=True, visible=True
742
+ ), # Update send_first button
743
+ gr.update(
744
+ value="Can't Decide", interactive=True
745
+ ), # Reset feedback selection
746
+ leaderboard_data, # Updated leaderboard data
747
+ )
748
+
749
+ # Update the click event for the submit feedback button
750
+ submit_feedback_btn.click(
751
+ submit_feedback,
752
+ inputs=[feedback, models_state, conversation_state],
753
+ outputs=[
754
+ shared_input, # Reset shared_input
755
+ user_prompt_md, # Hide user_prompt_md
756
+ response_a_title, # Hide Model A title
757
+ response_b_title, # Hide Model B title
758
+ response_a, # Clear Model A response
759
+ response_b, # Clear Model B response
760
+ multi_round_inputs, # Hide multi-round input section
761
+ vote_panel, # Hide vote panel
762
+ send_first, # Reset and update send_first button
763
+ feedback, # Reset feedback selection
764
+ leaderboard_component, # Update leaderboard data dynamically
765
+ ],
766
+ )
767
+
768
+ # Add Terms of Service at the bottom
769
+ terms_of_service = gr.Markdown(
770
+ """
771
+ ## Terms of Service
772
+
773
+ Users are required to agree to the following terms before using the service:
774
+
775
+ - The service is a **research preview**. It only provides limited safety measures and may generate offensive content.
776
+ - It must not be used for any illegal, harmful, violent, racist, or sexual purposes.
777
+ - Please **do not upload any private information**.
778
+ - The service collects user dialogue data, including both text and images, and reserves the right to distribute it under a **Creative Commons Attribution (CC-BY)** or a similar license.
779
+ """
780
+ )
781
+
782
+ app.launch()
context_window.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "anthropic:claude-3-5-sonnet-latest": 200000,
3
+ "anthropic:claude-3-5-haiku-latest": 200000,
4
+ "anthropic:claude-3-sonnet-20240229": 200000,
5
+ "anthropic:claude-3-haiku-20240307": 200000,
6
+ "anthropic:claude-3-opus-latest": 200000,
7
+ "google:gemini-1.5-flash": 1048576,
8
+ "google:gemini-1.5-pro": 2097152,
9
+ "groq:gemma2-9b-it": 8192,
10
+ "groq:gemma-7b-it": 8192,
11
+ "groq:llama-3.1-8b-instant": 128000,
12
+ "groq:llama-3.1-70b-versatile": 128000,
13
+ "groq:llama-3.2-1b-preview": 128000,
14
+ "groq:llama-3.2-3b-preview": 128000,
15
+ "openai:gpt-3.5-turbo": 16385,
16
+ "openai:gpt-4": 8192,
17
+ "openai:gpt-4-turbo": 128000,
18
+ "openai:gpt-4o": 128000,
19
+ "openai:chatgpt-4o-latest": 128000,
20
+ "openai:gpt-4o-mini": 128000,
21
+ "openai:o1-preview": 128000,
22
+ "openai:o1-mini": 128000
23
+ }
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ aisuite[all]
2
+ evalica
3
+ gradio[oauth]
4
+ gradio_leaderboard
5
+ huggingface_hub
6
+ python-dotenv
7
+ vertexai