Spaces:
No application file
No application file
Update app.py
Browse files5 unmodified lines678910111213141516171819202122232425262716 unmodified lines4445464748495051525354559 unmodified lines656667686970717211 unmodified lines848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841855 unmodified linesimport re# --- Load Gemini API key securely ---# Make sure to set the GEMINI_API_KEY in your Hugging Face Space SecretsGEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")if not GEMINI_API_KEY:raise ValueError("❌ GEMINI_API_KEY not found. Please set it in your Hugging Face Space Secrets.")# --- Configure the library and initialize a client instance ---client = genai.Client()# --- Define Avatars for reuse ---AVATAR_IMAGES = {"Agent A (Optimist)": "https://i.imgur.com/2GMV9y7.png", # Neon Green Bot"Agent B (Skeptic)": "https://i.imgur.com/KzX3T21.png", # Neon Pink Bot"SYSTEM": "https://i.imgur.com/z3uxLzT.png" # System/Cog Icon}# --- UI Customization: Bright Neon Trippy Blending ---cyberpunk_css = """@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap');:root {16 unmodified linescleaned_lines = [re.sub(r'^\d+[\.\)]\s*|^\*\s*', '', line).strip() for line in lines]return [line for line in cleaned_lines if line]# --- Core Application Logic ---def generate_topics():prompt = "Generate a list of exactly 20 specific, debatable topics related to the future of coding, banking, and artificial intelligence. The topics should be concise and provocative. Format as a numbered list."try:# UPDATED MODELresponse = client.generate_content(model="models/gemini-2.5-pro", contents=prompt)topics = parse_list_from_llm(response.text)return {topics_state: topics,9 unmodified linesreturn {question_dropdown: gr.Dropdown(value=None, visible=False)}prompt = f"For the debate topic '{selected_topic}', generate a list of exactly 20 thought-provoking starting questions or controversial statements to kick off the debate. Format as a numbered list."try:# UPDATED MODELresponse = client.generate_content(model="models/gemini-2.5-pro", contents=prompt)questions = parse_list_from_llm(response.text)return {questions_state: questions,11 unmodified linesgr.Warning("Topic and Question must be selected before starting.")return [], []agent_a_persona = "You are Agent A, a tech optimist and futurist. You see the best in new technology. Your goal is to argue for the positive aspects of the debate topic. Keep your responses concise and impactful."agent_b_persona = "You are Agent B, a cautious skeptic and ethicist. You critically examine the potential downsides and risks of new technology. Your goal is to argue for the negative or cautionary aspects of the debate topic. Keep your responses concise and impactful."# UPDATED MODELagent_a_chat = client.chats.create(model="models/gemini-2.5-pro", context=agent_a_persona)agent_b_chat = client.chats.create(model="models/gemini-2.5-pro", context=agent_b_persona)current_history = [{"role": "user", "name": "SYSTEM", "content": f"**DEBATE TOPIC:** {topic}\n\n**STARTING QUESTION:** {question}", "avatar_url": AVATAR_IMAGES["SYSTEM"]}]yield current_history, current_historylast_response = questionfor i in range(10):try:time.sleep(1)response_a = agent_a_chat.send_message(f"Based on the last statement ('{last_response}'), provide your optimistic counter-argument.")current_history.append({"role": "assistant", "name": "Agent A (Optimist)", "content": response_a.text, "avatar_url": AVATAR_IMAGES["Agent A (Optimist)"]})last_response = response_a.textyield current_history, current_historytime.sleep(1)response_b = agent_b_chat.send_message(f"Based on Agent A's last statement ('{last_response}'), provide your skeptical counter-argument.")current_history.append({"role": "assistant", "name": "Agent B (Skeptic)", "content": response_b.text, "avatar_url": AVATAR_IMAGES["Agent B (Skeptic)"]})last_response = response_b.textyield current_history, current_historyexcept Exception as e:error_message = f"⚠️ An error occurred during the debate: {e}"current_history.append({"role": "user", "name": "SYSTEM", "content": error_message, "avatar_url": AVATAR_IMAGES["SYSTEM"]})yield current_history, current_historybreakcurrent_history.append({"role": "user", "name": "SYSTEM", "content": "--- DEBATE CONCLUDED ---", "avatar_url": AVATAR_IMAGES["SYSTEM"]})yield {chatbot: current_history, debate_log_state: current_history, save_row: gr.Row(visible=True)}def save_as_json(log):filepath = "debate_log.json"clean_log = [{k: v for k, v in entry.items() if k != 'avatar_url'} for entry in log]with open(filepath, "w") as f:json.dump(clean_log, f, indent=2)return gr.File(value=filepath, label="Download JSON")def save_as_html(log):filepath = "debate_log.html"html_style = """<style> body { font-family: sans-serif; background-color: #111; color: #eee; } .container { max-width: 800px; margin: auto; padding: 20px; } .message { display: flex; align-items: flex-start; margin-bottom: 1em; padding: 1em; border-radius: 8px; } .avatar { width: 40px; height: 40px; border-radius: 50%; margin-right: 15px; } .content { flex: 1; } .system { background-color: #333; } .assistant { background-color: #023020; } .assistant.skeptic { background-color: #30022b; } .speaker { font-weight: bold; margin-bottom: 0.5em; display: block; color: #00ffff;} </style>"""html_content = f"<html><head><title>Debate Log</title>{html_style}</head><body><div class='container'><h1>Debate Log</h1>"for entry in log:speaker_name = entry.get("name", "Unknown")message_content = entry.get("content", "")avatar_url = entry.get("avatar_url", "")css_class = entry.get("role", "system")if "Skeptic" in speaker_name: css_class += " skeptic"safe_message = gr.Markdown(message_content).value.replace('\n', '<br>')html_content += f'<div class="message {css_class}"><img src="{avatar_url}" class="avatar"><div class="content"><span class="speaker">{speaker_name}</span>{safe_message}</div></div>'html_content += "</div></body></html>"with open(filepath, "w", encoding='utf-8') as f: f.write(html_content)return gr.File(value=filepath, label="Download HTML")def reset_all():return {chatbot: [], debate_log_state: [], topics_state: [], questions_state: [],generate_topics_btn: gr.Button(visible=True),topic_dropdown: gr.Dropdown(value=None, choices=[], label="Step 2: Select a Topic", visible=False),question_dropdown: gr.Dropdown(value=None, choices=[], label="Step 3: Select a Starting Question", visible=False),start_debate_btn: gr.Button(visible=False), save_row: gr.Row(visible=False), download_file: None,}# --- Gradio UI Layout ---with gr.Blocks(theme=gr.themes.Base(), css=cyberpunk_css, title="AI DEBATE SIMULATOR_v2.5 Pro") as demo:debate_log_state = gr.State([])topics_state = gr.State([])questions_state = gr.State([])gr.Markdown("# 👾 AI DEBATE SIMULATOR_v2.5 Pro 👾")gr.Markdown("## A 20-Turn War of Wits Between Two AI Agents")with gr.Row():with gr.Column(scale=1):gr.Markdown("### **CONTROL PANEL**")generate_topics_btn = gr.Button("Step 1: Generate 20 Debate Topics", variant="primary")topic_dropdown = gr.Dropdown(label="Step 2: Select a Topic", visible=False, interactive=True)question_dropdown = gr.Dropdown(label="Step 3: Select a Starting Question", visible=False, interactive=True)start_debate_btn = gr.Button("Step 4: START THE DEBATE", visible=False)with gr.Row(visible=False) as save_row:save_json_btn = gr.Button("Save as JSON")save_html_btn = gr.Button("Save as HTML")download_file = gr.File(label="Download Your Log")reset_btn = gr.Button("Start New Debate (Reset All)", variant="stop")with gr.Column(scale=3):chatbot = gr.Chatbot(label="Debate Arena", type="messages", height=700)# Event handlersgenerate_topics_btn.click(fn=generate_topics, inputs=None, outputs=[topics_state, topic_dropdown, generate_topics_btn])topic_dropdown.change(fn=generate_questions, inputs=topic_dropdown, outputs=[questions_state, question_dropdown])question_dropdown.change(fn=enable_debate_button, inputs=question_dropdown, outputs=[start_debate_btn])start_debate_btn.click(fn=lambda: { generate_topics_btn: gr.Button(visible=False), topic_dropdown: gr.Dropdown(interactive=False), question_dropdown: gr.Dropdown(interactive=False), start_debate_btn: gr.Button(visible=False), }, inputs=None, outputs=[generate_topics_btn, topic_dropdown, question_dropdown, start_debate_btn]).then(fn=run_debate, inputs=[topic_dropdown, question_dropdown], outputs=[chatbot, debate_log_state, save_row])save_json_btn.click(save_as_json, inputs=debate_log_state, outputs=download_file)save_html_btn.click(save_as_html, inputs=debate_log_state, outputs=download_file)reset_btn.click(fn=reset_all, inputs=None, outputs=[chatbot, debate_log_state, topics_state, questions_state, generate_topics_btn, topic_dropdown, question_dropdown, start_debate_btn, save_row, download_file])# --- Launch the App ---if __name__ == "__main__":demo.launch(debug=True)5 unmodified lines6789101112131415161718192021222324252616 unmodified lines4344454647484950515253549 unmodified lines646566676869707111 unmodified lines83848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601615 unmodified linesimport re# --- Load Gemini API key securely ---GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")if not GEMINI_API_KEY:raise ValueError("\u274c GEMINI_API_KEY not found. Please set it in your Hugging Face Space Secrets.")# --- Initialize the client using the latest SDK pattern ---client = genai.Client()# --- Define Avatars for reuse ---AVATAR_IMAGES = {"Agent A (Optimist)": "https://i.imgur.com/2GMV9y7.png","Agent B (Skeptic)": "https://i.imgur.com/KzX3T21.png","SYSTEM": "https://i.imgur.com/z3uxLzT.png"}# --- UI CSS ---cyberpunk_css = """@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap');:root {16 unmodified linescleaned_lines = [re.sub(r'^\d+[\.\)]\s*|^\*\s*', '', line).strip() for line in lines]return [line for line in cleaned_lines if line]# --- Core logic ---def generate_topics():prompt = "Generate a list of exactly 20 specific, debatable topics related to the future of coding, banking, and artificial intelligence. The topics should be concise and provocative. Format as a numbered list."try:chat = client.chats.create(model="gemini-2.5-flash")response = chat.send_message(prompt)topics = parse_list_from_llm(response.text)return {topics_state: topics,9 unmodified linesreturn {question_dropdown: gr.Dropdown(value=None, visible=False)}prompt = f"For the debate topic '{selected_topic}', generate a list of exactly 20 thought-provoking starting questions or controversial statements to kick off the debate. Format as a numbered list."try:chat = client.chats.create(model="gemini-2.5-flash")response = chat.send_message(prompt)questions = parse_list_from_llm(response.text)return {questions_state: questions,11 unmodified linesgr.Warning("Topic and Question must be selected before starting.")return [], []agent_a = client.chats.create(model="gemini-2.5-flash")agent_b = client.chats.create(model="gemini-2.5-flash")agent_a.send_message("You are Agent A, a tech optimist and futurist. Your goal is to argue for the positive aspects of the debate topic.")agent_b.send_message("You are Agent B, a cautious skeptic and ethicist. Your goal is to argue the negative or cautionary side.")current_history = [{"role": "user", "name": "SYSTEM", "content": f"**DEBATE TOPIC:** {topic}\n\n**STARTING QUESTION:** {question}", "avatar_url": AVATAR_IMAGES["SYSTEM"]}]yield current_history, current_historylast_response = questionfor i in range(10):try:time.sleep(1)res_a = agent_a.send_message(f"Based on this: '{last_response}', provide your optimistic argument.")current_history.append({"role": "assistant", "name": "Agent A (Optimist)", "content": res_a.text, "avatar_url": AVATAR_IMAGES["Agent A (Optimist)"]})last_response = res_a.textyield current_history, current_historytime.sleep(1)res_b = agent_b.send_message(f"Respond to Agent A: '{last_response}' with a skeptical counter-argument.")current_history.append({"role": "assistant", "name": "Agent B (Skeptic)", "content": res_b.text, "avatar_url": AVATAR_IMAGES["Agent B (Skeptic)"]})last_response = res_b.textyield current_history, current_historyexcept Exception as e:current_history.append({"role": "user", "name": "SYSTEM", "content": f"\u26a0\ufe0f An error occurred: {e}", "avatar_url": AVATAR_IMAGES["SYSTEM"]})yield current_history, current_historybreakcurrent_history.append({"role": "user", "name": "SYSTEM", "content": "--- DEBATE CONCLUDED ---", "avatar_url": AVATAR_IMAGES["SYSTEM"]})yield current_history, current_history, gr.Row(visible=True)def reset_all():return {chatbot: [], debate_log_state: [], topics_state: [], questions_state: [],generate_topics_btn: gr.Button(visible=True),topic_dropdown: gr.Dropdown(value=None, choices=[], visible=False),question_dropdown: gr.Dropdown(value=None, choices=[], visible=False),start_debate_btn: gr.Button(visible=False),save_row: gr.Row(visible=False),download_file: None,}# --- Gradio UI Layout ---with gr.Blocks(css=cyberpunk_css, title="AI DEBATE SIMULATOR_v2.5") as demo:debate_log_state = gr.State([])topics_state = gr.State([])questions_state = gr.State([])gr.Markdown("# \ud83d\udc7e AI DEBATE SIMULATOR_v2.5 \ud83d\udc7e")gr.Markdown("## A 20-Turn War of Wits Between Two AI Agents")with gr.Row():with gr.Column(scale=1):generate_topics_btn = gr.Button("Step 1: Generate 20 Debate Topics", variant="primary")topic_dropdown = gr.Dropdown(label="Step 2: Select a Topic", visible=False)question_dropdown = gr.Dropdown(label="Step 3: Select a Starting Question", visible=False)start_debate_btn = gr.Button("Step 4: START THE DEBATE", visible=False)with gr.Row(visible=False) as save_row:save_row_button = gr.Button("Download Log")download_file = gr.File(label="Download File")reset_btn = gr.Button("Start New Debate", variant="stop")with gr.Column(scale=3):chatbot = gr.Chatbot(label="Debate Arena", type="messages", height=700)generate_topics_btn.click(fn=generate_topics, inputs=None, outputs=[topics_state, topic_dropdown, generate_topics_btn])topic_dropdown.change(fn=generate_questions, inputs=topic_dropdown, outputs=[questions_state, question_dropdown])question_dropdown.change(fn=enable_debate_button, inputs=question_dropdown, outputs=[start_debate_btn])start_debate_btn.click(fn=lambda: {generate_topics_btn: gr.Button(visible=False), topic_dropdown: gr.Dropdown(interactive=False), question_dropdown: gr.Dropdown(interactive=False), start_debate_btn: gr.Button(visible=False)}, inputs=None, outputs=[generate_topics_btn, topic_dropdown, question_dropdown, start_debate_btn]).then(fn=run_debate, inputs=[topic_dropdown, question_dropdown], outputs=[chatbot, debate_log_state, save_row])reset_btn.click(fn=reset_all, inputs=None, outputs=[chatbot, debate_log_state, topics_state, questions_state, generate_topics_btn, topic_dropdown, question_dropdown, start_debate_btn, save_row, download_file])# --- Launch the App ---if __name__ == "__main__":demo.launch(debug=True)
app.py+45-69