Of course! Building a simplified version of LMSys's Chatbot Arena (LMArena) is an excellent project for learning how to integrate Hugging Face models into a web application. We'll use Streamlit for the user interface because it's fast and easy.
Here's a complete, step-by-step guide to building your own "LMArena Lite".
Core Features of Our App
- Side-by-side UI: Two text boxes to display responses from two different models.
- Anonymity: The user won't know which model is which ("Model A" vs. "Model B") until after they vote, ensuring an unbiased choice.
- Model Backend: We'll use the Hugging Face
transformers library to load and run open-source models.
- Voting: Buttons for the user to vote for "A is Better", "B is Better", or a "Tie".
- Leaderboard: A simple, in-memory leaderboard that tracks wins, losses, and ties, and calculates a win rate.
Step 1: Project Setup and Dependencies
First, create a new folder for your project and set up a virtual environment.
mkdir lmarena-lite
cd lmarena-lite
python -m venv venv
source venv/bin/activate # On Windows, use `venv\Scripts\activate`
Now, create a requirements.txt file to list our dependencies.
requirements.txt
streamlit
transformers
torch
pandas
accelerate # Recommended for faster model loading
Install them using pip:
pip install -r requirements.txt
Step 2: Choosing Your Models
For a local demo, it's crucial to pick small, fast models that don't require a massive GPU. Good starting choices are:
distilgpt2
gpt2
google-t5/t5-small
facebook/opt-125m
We'll add these to a list in our app.
Step 3: The Streamlit App (app.py)
Create a file named app.py. We'll build the code in logical blocks.
Block A: Imports and Initial Configuration
# app.py
import streamlit as st
import pandas as pd
import random
from transformers import pipeline, set_seed
# --- App Configuration ---
st.set_page_config(
page_title="LMArena Lite",
page_icon="⚔️",
layout="wide"
)
# --- Model Configuration ---
# Let's use smaller, faster models for our local demo
MODEL_LIST = [
"distilgpt2",
"gpt2",
"facebook/opt-125m",
"google-t5/t5-small"
]
# --- Caching the Model Loading ---
# This is crucial for performance. Streamlit's cache will store the loaded
# model and tokenizer, so we don't reload them on every interaction.
@st.cache_resource
def get_model(model_name):
"""Loads and caches a Hugging Face model pipeline."""
st.info(f"Loading model: {model_name}...")
if "t5" in model_name:
return pipeline("text2text-generation", model=model_name)
else:
return pipeline("text-generation", model=model_name)
Explanation:
st.set_page_config: Sets the title and icon of the app.
MODEL_LIST: A list of Hugging Face model identifiers we'll use.
@st.cache_resource: This is a powerful Streamlit decorator. It tells Streamlit to run this function only once for a given input (model_name). The returned object (the model pipeline) is stored in memory. The next time the app needs this model, it will be instantly available. This prevents reloading large models on every button click.
Block B: Session State and Leaderboard Initialization
Streamlit reruns the script from top to bottom on every user interaction. To keep track of our battle state (which models are fighting, the prompt, etc.), we use st.session_state.
# --- Session State Initialization ---
# This ensures that our variables persist across reruns of the script.
if 'leaderboard' not in st.session_state:
# Initialize a leaderboard DataFrame
st.session_state.leaderboard = pd.DataFrame({
'model': MODEL_LIST,
'wins': [0] * len(MODEL_LIST),
'losses': [0] * len(MODEL_LIST),
'ties': [0] * len(MODEL_LIST),
}).set_index('model')
if 'battle' not in st.session_state:
st.session_state.battle = {}
# --- Helper Functions ---
def start_new_battle():
"""Selects two random models for a new battle."""
models = random.sample(MODEL_LIST, 2)
random.shuffle(models) # Randomize who is Model A and Model B
st.session_state.battle = {
'model_a': models[0],
'model_b': models[1],
'prompt': "",
'response_a': "",
'response_b': "",
'voted': False
}
def update_leaderboard(winner, loser, tie=False):
"""Updates the win/loss/tie counts in the leaderboard."""
if tie:
st.session_state.leaderboard.loc[winner, 'ties'] += 1
st.session_state.leaderboard.loc[loser, 'ties'] += 1
else:
st.session_state.leaderboard.loc[winner, 'wins'] += 1
st.session_state.leaderboard.loc[loser, 'losses'] += 1
Explanation:
- We initialize a
leaderboard DataFrame and a battle dictionary in st.session_state if they don't already exist.
start_new_battle(): This function is the core of a new round. It picks two distinct models, shuffles their order for anonymity, and resets the battle state.
update_leaderboard(): Handles the logic of updating our scores after a vote.
Block C: The Main App UI
This is where we'll use Streamlit's components to build the interface.
# --- Main App UI ---
st.title("⚔️ LMArena Lite")
st.markdown("A simplified Chatbot Arena to compare Hugging Face models, built with Streamlit.")
# --- Leaderboard Sidebar ---
with st.sidebar:
st.header("🏆 Leaderboard")
# Calculate win rate and sort
ld_df = st.session_state.leaderboard.copy()
ld_df['total_games'] = ld_df['wins'] + ld_df['losses'] + ld_df['ties']
# Avoid division by zero
ld_df['win_rate'] = ld_df.apply(
lambda row: row['wins'] / row['total_games'] if row['total_games'] > 0 else 0,
axis=1
)
st.dataframe(ld_df.sort_values(by='win_rate', ascending=False),
column_config={"win_rate": st.column_config.ProgressColumn("Win Rate", format="%.2f")})
# --- Battle Setup ---
if not st.session_state.battle or st.session_state.battle.get('voted'):
if st.button("Start New Battle", type="primary"):
start_new_battle()
st.rerun() # Rerun the script to reflect the new battle state
# --- Battle Interface ---
if st.session_state.battle and not st.session_state.battle.get('voted'):
battle_state = st.session_state.battle
prompt = st.text_area("Enter your prompt:", height=100, key="prompt_input")
if st.button("Generate Responses"):
if prompt:
battle_state['prompt'] = prompt
with st.spinner("Model A is thinking..."):
model_a_pipeline = get_model(battle_state['model_a'])
response_a = model_a_pipeline(prompt, max_length=150, num_return_sequences=1)[0]['generated_text']
battle_state['response_a'] = response_a
with st.spinner("Model B is thinking..."):
model_b_pipeline = get_model(battle_state['model_b'])
response_b = model_b_pipeline(prompt, max_length=150, num_return_sequences=1)[0]['generated_text']
battle_state['response_b'] = response_b
st.rerun()
else:
st.warning("Please enter a prompt.")
# --- Display Responses and Voting Buttons ---
if battle_state.get('response_a'):
col1, col2 = st.columns(2)
with col1:
st.subheader("Model A")
st.container(height=300, border=True).write(battle_state['response_a'])
with col2:
st.subheader("Model B")
st.container(height=300, border=True).write(battle_state['response_b'])
st.markdown("---")
st.subheader("Which model's response is better?")
vote_col1, vote_col2, vote_col3 = st.columns(3)
if vote_col1.button("⬅️ Model A is better"):
update_leaderboard(winner=battle_state['model_a'], loser=battle_state['model_b'])
battle_state['voted'] = True
st.rerun()
if vote_col2.button("➡️ Model B is better"):
update_leaderboard(winner=battle_state['model_b'], loser=battle_state['model_a'])
battle_state['voted'] = True
st.rerun()
if vote_col3.button("🤝 It's a tie"):
update_leaderboard(winner=battle_state['model_a'], loser=battle_state['model_b'], tie=True)
battle_state['voted'] = True
st.rerun()
# --- Post-Vote Reveal ---
if st.session_state.battle.get('voted'):
st.success("Thank you for your vote!")
st.markdown(f"**Model A was:** `{st.session_state.battle['model_a']}`")
st.markdown(f"**Model B was:** `{st.session_state.battle['model_b']}`")
if st.button("Start Next Battle", type="primary"):
start_new_battle()
st.rerun()
Explanation:
- Leaderboard: Displayed in the sidebar. We calculate a win rate and use
st.dataframe to show it. The ProgressColumn provides a nice visual.
- Battle Setup: A "Start New Battle" button appears only if there's no active battle or the last one was voted on.
- Battle Interface:
- If a battle is active, we show a
st.text_area for the prompt.
- When "Generate Responses" is clicked, we show spinners (
st.spinner) while fetching the models and generating text.
- The responses are stored in
st.session_state. We call st.rerun() to immediately update the UI with the new responses.
- The responses are displayed side-by-side using
st.columns. st.container with a border helps visually group the text.
- Voting buttons appear below the responses. When a button is clicked, it calls
update_leaderboard, sets the voted flag to True, and reruns the app.
- Post-Vote Reveal:
- After a vote (
voted is True), we show a success message and reveal the true identities of Model A and B.
- A "Start Next Battle" button appears, allowing the user to loop back.
Step 4: Run the App
You're all set! Save the app.py file and run it from your terminal:
streamlit run app.py
Your browser should open a new tab with your LMArena Lite app running locally.
Next Steps and Improvements
This is a great starting point. Here are some ways you could extend it:
- Persistent Storage: The current leaderboard is in-memory and will reset if you stop the app. You could save the
leaderboard.csv to disk or, for a more robust solution, use a simple database like SQLite.
- More Models: Add larger or more diverse models. Be aware of your hardware limitations (RAM and VRAM).
- Elo Rating System: Instead of a simple win/loss count, implement an Elo rating system for a more accurate leaderboard, just like the real Chatbot Arena.
- Error Handling: Add
try...except blocks around the model generation in case a model fails.
- Deployment: Deploy your app to Hugging Face Spaces or Streamlit Community Cloud so others can use it. You'll likely need to request a GPU for better performance if using larger models.
- Better Text Generation: Tweak the generation parameters (
max_length, temperature, top_p, etc.) for higher-quality responses.