import gradio as gr from huggingface_hub import InferenceClient # Define available models (update with your actual model IDs) model_list = { "Safe LM": "HuggingFaceH4/zephyr-7b-beta", # Replace with your Safe LM model ID "Baseline 1": "HuggingFaceH4/zephyr-7b-beta", "Another Model": "HuggingFaceH4/zephyr-7b-beta" } def respond(message, history, system_message, max_tokens, temperature, top_p, selected_model): try: # Create an InferenceClient for the selected model client = InferenceClient(model_list.get(selected_model, "HuggingFaceH4/zephyr-7b-beta")) # Build conversation messages for the client messages = [{"role": "system", "content": system_message}] for user_msg, assistant_msg in history: if user_msg: # Only add non-empty messages messages.append({"role": "user", "content": user_msg}) if assistant_msg: # Only add non-empty messages messages.append({"role": "assistant", "content": assistant_msg}) messages.append({"role": "user", "content": message}) response = "" # Stream the response from the client for token_message in client.chat_completion( messages, max_tokens=max_tokens, stream=True, temperature=temperature, top_p=top_p, ): # Safe extraction of token with error handling try: token = token_message.choices[0].delta.content if token is not None: # Handle potential None values response += token yield response except (AttributeError, IndexError) as e: # Handle cases where token structure might be different print(f"Error extracting token: {e}") continue except Exception as e: # Return error message if the model call fails print(f"Error calling model API: {e}") yield f"Sorry, there was an error: {str(e)}" # Custom CSS for styling css = """ body { background-color: #f0f5fb; /* Light pastel blue background */ } .gradio-container { background-color: white; border-radius: 16px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); max-width: 90%; margin: 15px auto; padding-bottom: 20px; } /* Header styling with diagonal shield */ .app-header { position: relative; overflow: hidden; } .app-header::before { content: "🛡️"; position: absolute; font-size: 100px; opacity: 0.1; right: -20px; top: -30px; transform: rotate(15deg); pointer-events: none; } /* Simple styling for buttons */ #send-btn { background-color: white !important; color: #333 !important; border: 2px solid #e6c200 !important; } #send-btn:hover { background-color: #fff9e6 !important; } #clear-btn { background-color: white !important; color: #333 !important; border: 2px solid #e6c200 !important; } #clear-btn:hover { background-color: #fff9e6 !important; } /* User/assistant emoji in chat */ .user-msg::before { content: "👤 "; } .bot-msg::before { content: "🛡️ "; } /* Hide elements */ footer { display: none !important; } .footer { display: none !important; } """ with gr.Blocks(css=css) as demo: # Custom header with branding gr.HTML("""
Responsible AI for everyone