import gradio as gr import requests import os import base64 from PIL import Image import io import datetime # Configuration from environment variables OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY") DEFAULT_REPORT_EMAIL = os.getenv("REPORT_EMAIL") BREVO_API_KEY = os.getenv("BREVO_API_KEY") BREVO_FROM_EMAIL = os.getenv("BREVO_FROM_EMAIL", "noreply@yourdomain.com") # Testing/Demo Mode Configuration DEMO_MODE = os.getenv("DEMO_MODE", "true").lower() == "true" # Enable demo mode by default # Store conversation history and settings conversation_history = [] current_report_email = DEFAULT_REPORT_EMAIL # Department configurations departments = { "administration": { "name": "Administration", "email": os.getenv("ADMIN_EMAIL", "admin@demo.com"), "responsibilities": "Overall management, decision making, and coordination" }, "production": { "name": "Production", "email": os.getenv("PRODUCTION_EMAIL", "production@demo.com"), "responsibilities": "Manufacturing, quality control, and production planning" }, "magazine": { "name": "Magazine Management", "email": os.getenv("MAGAZINE_EMAIL", "magazine@demo.com"), "responsibilities": "Content creation, publishing, and distribution" } } def update_report_email(new_email): """Update the report email address""" global current_report_email if new_email and "@" in new_email and "." in new_email: current_report_email = new_email.strip() return f"โœ… Report email updated to: {current_report_email}" else: return "โŒ Please enter a valid email address" def send_email_brevo_api(to_email, subject, html_content, from_name="AI Coordination System"): """Send email using Brevo API""" try: # Demo mode: simulate email sending if DEMO_MODE or not BREVO_API_KEY: return f"๐Ÿงช [DEMO MODE] Email simulated to {to_email}" response = requests.post( "https://api.brevo.com/v3/smtp/email", headers={ "accept": "application/json", "content-type": "application/json", "api-key": BREVO_API_KEY }, json={ "sender": { "name": from_name, "email": BREVO_FROM_EMAIL }, "to": [{"email": to_email}], "subject": subject, "htmlContent": html_content }, timeout=10 ) if response.status_code == 201: return f"โœ… Email sent to {to_email}" else: error_msg = response.json().get('message', 'Unknown error') return f"โŒ Failed to send email: {error_msg}" except Exception as e: return f"โŒ Email error: {str(e)}" def get_mock_ai_response(user_message, department, user_name, has_image=False): """Generate a mock AI response for demo/testing mode""" image_section = """ === IMAGE OBSERVATIONS === โ€ข Mock analysis: Image appears to show office equipment โ€ข Suggested action: Forward to relevant department for review """ if has_image else "" responses = { "administration": { "equipment": f""" === EXECUTIVE SUMMARY === Request from {user_name} regarding equipment needs requires coordination between Administration and Production departments for budget approval and implementation. {image_section} === RECOMMENDED TARGET DEPARTMENT === Production This is primarily a production-related request that requires equipment or facility resources. === DEPARTMENTS INVOLVED === โ€ข Production โ€“ Equipment assessment and implementation โ€ข Administration โ€“ Budget approval and procurement authorization === ACTION PLAN === 1. Production department to assess equipment specifications and requirements 2. Administration to review budget implications and approve funding 3. Production to coordinate installation and training === PRIORITY === Medium โ€“ Standard equipment request requiring normal procurement timeline === FOLLOW-UP === Weekly status updates until equipment is operational """, "default": f""" === EXECUTIVE SUMMARY === Administrative request from {user_name} requires internal review and possible coordination with other departments. {image_section} === RECOMMENDED TARGET DEPARTMENT === Administration This request should be handled within the Administration department. === DEPARTMENTS INVOLVED === โ€ข Administration โ€“ Primary responsibility for coordination and decision-making === ACTION PLAN === 1. Review request details and requirements 2. Determine resource allocation and timeline 3. Coordinate with relevant stakeholders === PRIORITY === Normal โ€“ Standard administrative workflow === FOLLOW-UP === Monitor progress and provide status updates as needed """ }, "production": { "content": f""" === EXECUTIVE SUMMARY === Production request from {user_name} involves content creation, requiring Magazine department collaboration. {image_section} === RECOMMENDED TARGET DEPARTMENT === Magazine This request involves content creation and publishing activities. === DEPARTMENTS INVOLVED === โ€ข Magazine โ€“ Content development and design โ€ข Production โ€“ Material production and quality control === ACTION PLAN === 1. Magazine to develop content and design specifications 2. Production to review technical feasibility 3. Coordinate timeline for material production === PRIORITY === Medium โ€“ Requires cross-departmental coordination === FOLLOW-UP === Bi-weekly alignment meetings until project completion """, "default": f""" === EXECUTIVE SUMMARY === Production request from {user_name} requires assessment of manufacturing capabilities and resource allocation. {image_section} === RECOMMENDED TARGET DEPARTMENT === Production Internal production department matter requiring operational attention. === DEPARTMENTS INVOLVED === โ€ข Production โ€“ Manufacturing operations and quality assurance โ€ข Administration โ€“ Resource approval if needed === ACTION PLAN === 1. Assess current production capacity and requirements 2. Identify resource needs and constraints 3. Develop implementation timeline === PRIORITY === Normal โ€“ Standard production workflow === FOLLOW-UP === Regular progress monitoring through production meetings """ }, "magazine": { "printing": f""" === EXECUTIVE SUMMARY === Magazine request from {user_name} regarding printing requires Production department involvement for manufacturing execution. {image_section} === RECOMMENDED TARGET DEPARTMENT === Production Printing and manufacturing activities fall under Production responsibility. === DEPARTMENTS INVOLVED === โ€ข Magazine โ€“ Content finalization and specifications โ€ข Production โ€“ Printing operations and quality control === ACTION PLAN === 1. Magazine to finalize all content and design specifications 2. Production to schedule printing resources 3. Coordinate delivery timeline and distribution === PRIORITY === High โ€“ Publishing deadline-sensitive activity === FOLLOW-UP === Daily updates during production phase """, "default": f""" === EXECUTIVE SUMMARY === Magazine department request from {user_name} involves content development and publishing coordination. {image_section} === RECOMMENDED TARGET DEPARTMENT === Magazine Editorial and publishing matter for Magazine department handling. === DEPARTMENTS INVOLVED === โ€ข Magazine โ€“ Content creation and editorial oversight โ€ข Production โ€“ Technical production support if needed === ACTION PLAN === 1. Develop content strategy and editorial plan 2. Coordinate with relevant stakeholders 3. Execute publishing timeline === PRIORITY === Normal โ€“ Standard editorial workflow === FOLLOW-UP === Editorial review meetings and publication tracking """ } } # Determine which mock response to use message_lower = user_message.lower() dept_responses = responses.get(department, responses["administration"]) for keyword, response in dept_responses.items(): if keyword != "default" and keyword in message_lower: return response return dept_responses["default"] def analyze_coordination_needs(user_message, department, user_name, image=None): """Use LLM to analyze coordination needs and suggest actions - with image support""" # Demo/Testing Mode: Use mock responses if DEMO_MODE or not OPENROUTER_API_KEY: return get_mock_ai_response(user_message, department, user_name, has_image=image is not None) if image: # Convert image to base64 for vision model buffered = io.BytesIO() image.save(buffered, format="PNG") img_base64 = base64.b64encode(buffered.getvalue()).decode() prompt = f""" You are an Enterprise Operations Coordination AI. Analyze the request AND the attached image to determine responsibility and next actions. Write formally and professionally. No casual tone. No emojis. AVAILABLE DEPARTMENTS: - Administration: approvals, management, coordination - Production: equipment, facilities, manufacturing, maintenance - Magazine: design, content, publishing REQUEST: Requestor: {user_name} Origin Department: {department} Message: {user_message} Provide: === EXECUTIVE SUMMARY === Short professional summary === IMAGE OBSERVATIONS === Important findings from the image === RECOMMENDED TARGET DEPARTMENT === Choose ONLY ONE: Administration | Production | Magazine Reason === ACTION PLAN === Numbered steps === PRIORITY === Low | Medium | High with reason === FOLLOW-UP === Monitoring or escalation steps """ try: response = requests.post( "https://openrouter.ai/api/v1/chat/completions", headers={ "Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json", }, json={ "model": "google/gemma-3-27b-it:free", # Vision model "messages": [ { "role": "user", "content": [ { "type": "text", "text": prompt }, { "type": "image_url", "image_url": { "url": f"data:image/png;base64,{img_base64}" } } ] } ], "temperature": 0.3 }, timeout=60 ) if response.status_code == 200: data = response.json() return data["choices"][0]["message"]["content"] else: return "I'm having trouble analyzing the image right now. Please try again in a moment." except Exception as e: return f"Sorry, I couldn't process the image. Error: {str(e)}" else: # Text-only analysis prompt = f""" You are an Enterprise Operations Coordination AI used inside a professional organization. Your responsibility is to: โ€ข analyze the request โ€ข determine which department should handle it โ€ข produce a concise, executive-style coordination plan Write formally and professionally. Do NOT use conversational tone. Do NOT use emojis. Be precise, structured, and action-oriented. AVAILABLE DEPARTMENTS: - Administration: management, approvals, policies, finance, coordination - Production: manufacturing, maintenance, equipment, operations, logistics - Magazine: content creation, publishing, marketing materials, communication REQUEST: Requestor: {user_name} Origin Department: {department} Message: {user_message} Return your answer STRICTLY using this format: === EXECUTIVE SUMMARY === 2โ€“3 sentence professional summary. === RECOMMENDED TARGET DEPARTMENT === Choose ONLY ONE: Administration | Production | Magazine Brief justification. === DEPARTMENTS INVOLVED === โ€ข Department โ€“ responsibility === ACTION PLAN === 1. Step 2. Step 3. Step === PRIORITY === Low | Medium | High with reason === FOLLOW-UP === Required monitoring or reporting actions """ try: response = requests.post( "https://openrouter.ai/api/v1/chat/completions", headers={ "Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json", }, json={ "model": "google/gemma-3-27b-it:free", "messages": [{"role": "user", "content": prompt}], "temperature": 0.3 }, timeout=30 ) if response.status_code == 200: data = response.json() return data["choices"][0]["message"]["content"] else: return "I'm having trouble analyzing your request right now. Please try again in a moment." except Exception as e: return f"Sorry, I couldn't process your request. Error: {str(e)}" def send_department_email(sender_dept, recipient_dept, subject, message, user_name, urgency="Normal", image=None): """Send email between departments with optional image attachment""" try: # Determine recipient email recipient_email = departments[recipient_dept]["email"] if not recipient_email: # If no department email configured, use the current report email recipient_email = current_report_email # Create professional email content image_note = "

๐Ÿ“Ž Attachment: Image included with request

" if image else "" urgency_class = f"urgency-{urgency.lower()}" if urgency.lower() in ['high', 'medium'] else "urgency-normal" image_footer = "

Note: An image was included with this request. Please check the original system for image details.

" if image else "" html_content = f"""

๐Ÿข Inter-Department Communication

From: {departments[sender_dept]['name']}

Requested by: {user_name}

To: {departments[recipient_dept]['name']}

Date: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

Urgency: {urgency}

{image_note}
๐Ÿ‘ค Requestor Details:
Name: {user_name}
Department: {departments[sender_dept]['name']}

{subject}

{message}

This is an automated message from the AI Coordination System.

{image_footer}
""" # Send email using Brevo API from_name = f"{departments[sender_dept]['name']}" email_status = send_email_brevo_api(recipient_email, f"[{urgency}] {subject}", html_content, from_name) return email_status except Exception as e: return f"โŒ Failed to send email: {str(e)}" def send_email_report(conversation_data): """Send comprehensive coordination report to administration""" # Demo mode check if DEMO_MODE or not BREVO_API_KEY or not current_report_email: if DEMO_MODE: return "๐Ÿงช [DEMO MODE] Report email simulated successfully" else: return "Email reporting not configured - missing Brevo API key or report email" try: # Calculate department activity dept_activity = {} user_activity = {} for entry in conversation_data: dept = entry.get('department', 'Unknown') user = entry.get('user_name', 'Unknown') dept_activity[dept] = dept_activity.get(dept, 0) + 1 user_activity[user] = user_activity.get(user, 0) + 1 # Format email content subject = f"Coordination Report - {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}" # Create department activity HTML dept_activity_html = "" for dept, count in dept_activity.items(): dept_activity_html += f"

{dept.title()}: {count} interactions

" # Create user activity HTML user_activity_html = "" for user, count in user_activity.items(): if user != 'Unknown': user_activity_html += f"

{user}: {count} requests

" # Create recent activities HTML recent_activities_html = "" for i, entry in enumerate(conversation_data[-10:], 1): dept_badge = f"{entry.get('department', 'General').title()}" if entry.get('department') else "" user_badge = f"{entry.get('user_name', 'User')}" if entry.get('user_name') else "" image_indicator = " ๐Ÿ“ท" if entry.get('image_uploaded') else "" email_indicator = " ๐Ÿ“ง" if entry.get('email_sent') else "" recent_activities_html += f"""

Activity #{i}

{dept_badge} {user_badge} {image_indicator}

๐Ÿ’ฌ Message: {entry['user_input']}{email_indicator}

๐Ÿค– AI Coordination: {entry['ai_response']}

{entry['timestamp']}

""" # Create comprehensive HTML report html_content = f"""

๐Ÿค– AI Coordination System Report

Comprehensive inter-department coordination summary

Generated: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

{len(conversation_data)}

Total Interactions

{len(dept_activity)}

Active Departments

{sum(1 for entry in conversation_history if entry.get('email_sent'))}

Emails Sent

๐Ÿ“Š Department Activity

{dept_activity_html}

๐Ÿ‘ฅ User Activity

{user_activity_html if user_activity_html else "

No user activity data

"}

๐Ÿ”„ Recent Coordination Activities

{recent_activities_html if recent_activities_html else "

No recent activities

"}

๐Ÿค– AI Note: This report is automatically generated by the coordination system. All inter-department communications are logged and monitored for efficiency.

""" # Send email using Brevo API email_status = send_email_brevo_api(current_report_email, subject, html_content, "AI Coordination System") return email_status except Exception as e: return f"Failed to send report: {str(e)}" def add_to_conversation_history(user_input, department, user_name, ai_response, email_sent=False, image_uploaded=False): """Add current exchange to conversation history""" entry = { 'timestamp': datetime.datetime.now().isoformat(), 'user_input': user_input, 'department': department, 'user_name': user_name, 'ai_response': ai_response, 'email_sent': email_sent, 'image_uploaded': image_uploaded } conversation_history.append(entry) # Keep only last 50 exchanges to prevent memory issues if len(conversation_history) > 50: conversation_history.pop(0) def process_coordination_request(name, department, message, image, recipient_dept, send_email, urgency): """Process coordination requests between departments with image support""" if not message.strip(): return "Please enter a coordination message." if not department: return "Please select your department." if not name.strip(): return "Please enter your name." # Get AI analysis and suggestions (with image if provided) ai_analysis = analyze_coordination_needs(message, department, name, image) # Prepare response response_parts = [] # Add demo mode indicator if active if DEMO_MODE: response_parts.append("๐Ÿงช **DEMO MODE ACTIVE** - Using simulated AI responses") response_parts.append(f"**๐Ÿ‘ค Request from:** {name} | **๐Ÿข Department:** {departments[department]['name']}") if image: response_parts.append("**๐Ÿ“ท Image attached and analyzed**") response_parts.append(f"\n**๐Ÿค– Coordination Guidance:**\n{ai_analysis}") # Send email if requested email_status = "" if send_email and recipient_dept: subject = f"Coordination Request from {departments[department]['name']} - {name}" # Build email message email_lines = [ f"Requestor: {name}", f"Department: {departments[department]['name']}", "", "Message:", message, "" ] if image: email_lines.append("Note: An image was included with this request. Please check the system for visual details.") email_lines.append("") email_lines.extend([ "---", "Coordination Suggestions:", ai_analysis ]) email_message = "\n".join(email_lines) email_status = send_department_email(department, recipient_dept, subject, email_message, name, urgency, image) response_parts.append(f"\n**๐Ÿ“ง Email Status:** {email_status}") full_response = "\n".join(response_parts) # Add to conversation history add_to_conversation_history( user_input=message, department=department, user_name=name, ai_response=full_response, email_sent=bool(send_email and recipient_dept), image_uploaded=image is not None ) return full_response def get_conversation_stats(): """Get statistics about current coordination activities""" if not conversation_history: return "No coordination activities yet" total_exchanges = len(conversation_history) dept_activity = {} user_activity = {} emails_sent = sum(1 for entry in conversation_history if entry.get('email_sent')) images_uploaded = sum(1 for entry in conversation_history if entry.get('image_uploaded')) for entry in conversation_history: dept = entry.get('department', 'Unknown') user = entry.get('user_name', 'Unknown') dept_activity[dept] = dept_activity.get(dept, 0) + 1 if user != 'Unknown': user_activity[user] = user_activity.get(user, 0) + 1 stats_text = f"๐Ÿ“Š **Coordination Summary:**\n" stats_text += f"โ€ข Total Activities: {total_exchanges}\n" stats_text += f"โ€ข Emails Sent: {emails_sent}\n" stats_text += f"โ€ข Images Shared: {images_uploaded}\n\n" stats_text += "**Department Activity:**\n" for dept, count in dept_activity.items(): stats_text += f"โ€ข {dept.title()}: {count} requests\n" if user_activity: stats_text += f"\n**Active Team Members:** {', '.join(user_activity.keys())}" return stats_text def clear_conversation(): """Clear the conversation history""" global conversation_history conversation_history = [] return "๐Ÿ—‘๏ธ Coordination history cleared!" def get_current_email(): """Get the current report email address""" return current_report_email if current_report_email else "demo@example.com" def clear_form(): """Clear the form fields""" return ["", None, "", None, "administration", "Normal", False] def load_sample_request(sample_type): """Load sample requests for testing""" samples = { "Equipment Request": { "name": "John Smith", "dept": "production", "message": "We need to upgrade our printing equipment. The current machines are outdated and causing quality issues.", "recipient": "administration", "urgency": "Medium" }, "Content Collaboration": { "name": "Sarah Johnson", "dept": "magazine", "message": "Need production support for our next magazine issue. We have special requirements for paper quality and binding.", "recipient": "production", "urgency": "High" }, "Budget Approval": { "name": "Mike Chen", "dept": "production", "message": "Requesting budget approval for preventive maintenance on critical machinery.", "recipient": "administration", "urgency": "Normal" } } if sample_type in samples: s = samples[sample_type] return s["name"], s["dept"], s["message"], s["recipient"], s["urgency"] return "", "administration", "", None, "Normal" def get_system_status(): """Get current system configuration status""" status_lines = [] status_lines.append("**System Configuration:**") status_lines.append(f"โ€ข Demo Mode: {'๐Ÿงช ENABLED' if DEMO_MODE else 'โœ… DISABLED'}") status_lines.append(f"โ€ข OpenRouter API: {'โœ… Configured' if OPENROUTER_API_KEY else 'โŒ Not configured (using demo)'}") status_lines.append(f"โ€ข Brevo Email API: {'โœ… Configured' if BREVO_API_KEY else 'โŒ Not configured (simulated)'}") status_lines.append(f"โ€ข Report Email: {current_report_email if current_report_email else 'โŒ Not set'}") return "\n".join(status_lines) # Gradio Interface with gr.Blocks( theme=gr.themes.Soft(), title="AI Coordination System" ) as ui: gr.Markdown("# ๐Ÿข AI Department Coordination System") gr.Markdown("*Streamline communication between Administration, Production, and Magazine Management*") # Demo mode banner if DEMO_MODE: gr.Markdown("""
๐Ÿงช DEMO MODE ACTIVE
This space is running in demo mode with simulated AI responses. To enable full functionality, configure the required API keys in Settings โ†’ Repository Secrets.
""") with gr.Row(): with gr.Column(scale=1): with gr.Accordion("โš™๏ธ System Settings", open=False): gr.Markdown("### Email Configuration") email_input = gr.Textbox( label="Administration Report Email", value=get_current_email, placeholder="admin@company.com" ) email_status = gr.Textbox( label="Email Status", value=get_current_email, interactive=False, max_lines=2 ) update_email_btn = gr.Button("๐Ÿ’พ Save Email", variant="primary") gr.Markdown("### System Status") system_status = gr.Textbox( label="Configuration", value=get_system_status, interactive=False, max_lines=6 ) with gr.Accordion("๐Ÿงช Testing & Samples", open=True): gr.Markdown("### Quick Test Samples") sample_selector = gr.Radio( choices=["Equipment Request", "Content Collaboration", "Budget Approval"], label="Load Sample Request" ) load_sample_btn = gr.Button("๐Ÿ“‹ Load Sample", variant="secondary") gr.Markdown("---") gr.Markdown("### ๐Ÿ“ New Coordination Request") with gr.Group(): gr.Markdown("#### ๐Ÿ‘ค Your Information") name_input = gr.Textbox( label="Your Name", placeholder="Enter your full name" ) department_dropdown = gr.Dropdown( choices=["administration", "production", "magazine"], label="Your Department", value="administration" ) with gr.Group(): gr.Markdown("#### ๐Ÿ’ฌ Request Details") message_input = gr.Textbox( label="What do you need help with?", lines=4, placeholder="Describe what you need from other departments..." ) image_input = gr.Image( label="๐Ÿ“ท Attach Image (Optional)", type="pil" ) with gr.Group(): gr.Markdown("#### ๐Ÿ“ง Notification Options") recipient_dropdown = gr.Dropdown( choices=["administration", "production", "magazine"], label="Notify Department" ) urgency_dropdown = gr.Dropdown( choices=["Normal", "Medium", "High"], value="Normal", label="Priority Level" ) send_email_checkbox = gr.Checkbox( label="Send email notification", value=True ) with gr.Row(): submit_btn = gr.Button("๐Ÿš€ Get Coordination Help", variant="primary") clear_form_btn = gr.Button("๐Ÿ—‘๏ธ Clear Form", variant="secondary") with gr.Row(): report_btn = gr.Button("๐Ÿ“‹ Submit & Send Report", variant="secondary") clear_btn = gr.Button("๐Ÿ—‚๏ธ Clear History", variant="stop") stats_btn = gr.Button("๐Ÿ“ˆ View Stats") status_display = gr.Textbox( label="System Status", interactive=False, max_lines=2 ) stats_display = gr.Textbox( label="Activity Summary", interactive=False, max_lines=8 ) with gr.Column(scale=2): gr.Markdown("### ๐Ÿ’ก Coordination Guidance") output = gr.Textbox( label="Recommended Actions", lines=20, show_copy_button=True ) with gr.Accordion("๐Ÿข Department Overview", open=True): gr.Markdown(""" **Administration**: Overall management, decision making, and coordination **Production**: Manufacturing, quality control, and production planning **Magazine Management**: Content creation, publishing, and distribution *The AI will analyze your message and any attached images to provide specific coordination recommendations.* --- **Testing Tips:** - Use the sample requests to quickly test functionality - Try different departments and priority levels - Upload images to test vision capabilities (if API configured) - Monitor the activity log to see coordination history """) with gr.Accordion("๐Ÿ“œ Recent Activity", open=False): history_display = gr.JSON( label="Activity Log", value=lambda: conversation_history[-10:] if conversation_history else [] ) # Event handlers update_email_btn.click( fn=update_report_email, inputs=[email_input], outputs=email_status ) email_input.submit( fn=update_report_email, inputs=[email_input], outputs=email_status ) load_sample_btn.click( fn=load_sample_request, inputs=[sample_selector], outputs=[name_input, department_dropdown, message_input, recipient_dropdown, urgency_dropdown] ) submit_btn.click( fn=process_coordination_request, inputs=[name_input, department_dropdown, message_input, image_input, recipient_dropdown, send_email_checkbox, urgency_dropdown], outputs=output ).then( fn=lambda: conversation_history[-10:] if conversation_history else [], inputs=[], outputs=history_display ) report_btn.click( fn=lambda name, dept, msg, img, rec, send, urg: process_coordination_request(name, dept, msg, img, rec, send, urg) + "\n\n---\n" + send_email_report(conversation_history), inputs=[name_input, department_dropdown, message_input, image_input, recipient_dropdown, send_email_checkbox, urgency_dropdown], outputs=output ).then( fn=lambda: conversation_history[-10:] if conversation_history else [], inputs=[], outputs=history_display ) message_input.submit( fn=process_coordination_request, inputs=[name_input, department_dropdown, message_input, image_input, recipient_dropdown, send_email_checkbox, urgency_dropdown], outputs=output ).then( fn=lambda: conversation_history[-10:] if conversation_history else [], inputs=[], outputs=history_display ) clear_btn.click( fn=clear_conversation, inputs=[], outputs=status_display ).then( fn=lambda: [], inputs=[], outputs=history_display ) clear_form_btn.click( fn=clear_form, inputs=[], outputs=[name_input, image_input, message_input, recipient_dropdown, department_dropdown, urgency_dropdown, send_email_checkbox] ) stats_btn.click( fn=get_conversation_stats, inputs=[], outputs=stats_display ) if __name__ == "__main__": ui.launch(share=True)