Hamza4100/ai-workflow-agent
0
1"""2Streamlit Interface for M1 - Hugging Face Spaces Deployment3Replicates the functionality of ui_es.html in a Streamlit interface4Supports English and Spanish languages5"""6 7import streamlit as st8import asyncio9import json10from decision_agent import DecisionAgent11from tools.n8n_builder import N8NWorkflowBuilder12from tools.comfyui_builder import ComfyUIWorkflowBuilder13from tools.github_search import GitHubSearchTool14from tools.web_search import WebSearchTool15from chat_handler import SessionManager16 17# ========================================18# LANGUAGE TRANSLATIONS19# ========================================20TRANSLATIONS = {21"en": {22"title": "AI Workflow Agent",23"subtitle": "AI Decision Making System - Milestone 1",24"sidebar_config": "⚙️ Configuration",25"sidebar_llm": "🧠 Intelligent AI Mode (Gemini)",26"sidebar_llm_help": "Enable to use Gemini AI analysis. Disable for fast keyword mode.",27"sidebar_language": "🌐 Language / Idioma",28"sidebar_stats": "📊 M1 Statistics",29"sidebar_endpoints": "21 API endpoints",30"sidebar_templates": "16 workflow templates",31"sidebar_modes": "2 modes: Fast and AI",32"sidebar_status": "🚀 Status",33"sidebar_current_mode": "Current Mode:",34"sidebar_latency": "Latency:",35"sidebar_info": "📝 Information",36"sidebar_description": "Workflow analysis and generation system.",37"sidebar_milestone": "Milestone 1 - Completed ✅",38"mode_intelligent": "🧠 Intelligent AI",39"mode_fast": "⚡ Fast",40 41 # Tabs42"tab_home": "🏠 Home",43"tab_analyze": "🧠 AI Analysis",44"tab_build": "⚙️ Build Workflow",45"tab_github": "🔍 GitHub Search",46"tab_web": "🌐 Web Search",47"tab_chat": "💬 Chat",48 49 # Home tab50"home_welcome": "Welcome to M1 Dashboard",51"home_features": "✨ Main Features:",52"home_feature_1": "🧠 **AI Analysis**: Analyzes your needs and recommends the best tool",53"home_feature_2": "⚙️ **Workflow Generation**: Creates n8n and ComfyUI workflows",54"home_feature_3": "🔍 **Smart Search**: Search GitHub and web",55"home_feature_4": "💬 **AI Chat**: Conversational assistant for automation",56"home_getting_started": "🚀 Getting Started:",57"home_step_1": "1. Enable **AI Mode** in the sidebar for intelligent analysis",58"home_step_2": "2. Navigate through tabs to explore features",59"home_step_3": "3. Try example queries in each tab",60"home_modes": "💡 Modes:",61"home_mode_fast": "**⚡ Fast**: <100ms, predefined templates",62"home_mode_intelligent": "**🧠 Intelligent**: 2-3s, deep analysis with Gemini",63"home_tip": "📌 **Tip**: Start with fast mode to test, then enable AI mode for deep analysis.",64 65 # AI Analysis tab66"analyze_title": "Let AI analyze your automation needs",67"analyze_query": "Your Query",68"analyze_placeholder": "Describe what you want to automate...",69"analyze_examples": "💡 View Example Queries",70"analyze_example_1": "Example 1: Automated Emails",71"analyze_example_2": "Example 2: AI Art Generation",72"analyze_example_3": "Example 3: CRM Sync",73"analyze_btn": "Analyze with AI ✨",74"analyze_result": "🧠 AI Analysis Result",75"analyze_project_type": "Project Type",76"analyze_confidence": "Confidence",77"analyze_method": "Method",78"analyze_explanation": "📝 Explanation:",79"analyze_tools": "🔧 Suggested Tools:",80"analyze_steps": "📋 Next Steps:",81"error_empty_query": "❌ Please enter a query",82"analyzing": "Analyzing...",83 84 # Build Workflow tab85"build_title": "Generate complete workflows from descriptions",86"build_description": "Workflow Description",87"build_placeholder": "Describe the workflow you want to create...",88"build_tool": "Tool",89"build_tool_help": "n8n for automation, ComfyUI for AI image generation",90"build_examples": "💡 View Example Workflows",91"build_example_1": "Example 1: Webhook + Email",92"build_example_2": "Example 2: Twitter Monitor",93"build_example_3": "Example 3: AI Photos",94"build_btn": "Generate Workflow 🚀",95"build_result": "✅ Workflow Generated!",96"build_type": "Type",97"build_nodes": "Nodes",98"build_method": "Method",99"build_ai_analysis": "📊 AI Analysis:",100"build_explanation": "Explanation:",101"build_confidence": "Confidence:",102"build_json": "📄 Workflow JSON:",103"generating": "Generating workflow...",104"generated_ai": "🧠 Generated with AI",105"generated_template": "⚡ Generated with templates",106 107 # GitHub Search tab108"github_title": "Find relevant open source projects",109"github_keywords": "Search Keywords",110"github_placeholder": "e.g., workflow automation",111"github_max": "Maximum Results",112"github_examples": "💡 View Search Examples",113"github_btn": "Search GitHub 🔍",114"github_results": "🔍 GitHub Results ({} found)",115"github_description": "Description:",116"github_language": "Language:",117"github_docker": "🐳 **Docker:** Yes",118"github_url": "URL:",119"github_no_results": "📭 No repositories found",120"searching_github": "Searching GitHub...",121 122 # Web Search tab123"web_title": "Search the web using DuckDuckGo",124"web_query": "Search Query",125"web_placeholder": "e.g., n8n automation examples",126"web_max": "Maximum Results",127"web_btn": "Search Web 🔍",128"web_results": "🌐 Search Results ({} found)",129"web_no_title": "No title",130"web_no_description": "No description",131"web_no_results": "📭 No results found",132"searching_web": "Searching the web...",133 134 # Chat tab135"chat_title": "Chat with AI about your automation needs",136"chat_placeholder": "Ask the AI assistant anything...",137"chat_examples": "💡 View Conversation Starters",138"chat_example_1": "I want to create a bot that answers questions",139"chat_example_2": "Help me automate my social media posts",140"chat_example_3": "I need to process CSV files",141"chat_thinking": "Thinking...",142"chat_tools": "Suggested tools:",143 144 # Footer145"footer_notes": "📝 Notes:",146"footer_fast": "**Fast mode (keywords)**: <100ms, uses predefined templates",147"footer_intelligent": "**Intelligent mode (Gemini)**: 2-3s, deep AI analysis",148"footer_requirements": "**Requirements**: Gemini API key for intelligent mode (free at [Google AI Studio](https://aistudio.google.com/app/apikeys))",149"footer_milestone": "🚀 **Milestone 1** - Basic AI decision-making system completed",150 151 # Example texts152"ex_email": "I need to send automated emails to 1000 clients every morning",153"ex_ai_art": "I want to generate AI art from text descriptions and post to Instagram",154"ex_crm": "Process customer data from Shopify and sync with CRM",155"ex_chatbot": "Create a chatbot that answers questions from my documentation",156"ex_webhook": "Create a flow that receives customer data from webhook and sends confirmation email",157"ex_twitter": "Build a flow that monitors Twitter for mentions and sends Slack notifications",158"ex_photos": "Generate professional photos from uploaded photos",159"ex_automation": "workflow automation",160"ex_ml": "machine learning deployment",161"ex_image_gen": "AI image generation",162"ex_bot": "I want to create a bot that answers customer questions from my website",163"ex_social": "Help me automate my social media posts",164"ex_csv": "I need to process CSV files and generate reports"165},166"es": {167"title": "Agente de Flujo de Trabajo IA",168"subtitle": "Sistema de Toma de Decisiones IA - Milestone 1",169"sidebar_config": "⚙️ Configuración",170"sidebar_llm": "🧠 Modo IA Inteligente (Gemini)",171"sidebar_llm_help": "Activar para usar análisis con Gemini AI. Desactivar para modo rápido con palabras clave.",172"sidebar_language": "🌐 Language / Idioma",173"sidebar_stats": "📊 Estadísticas M1",174"sidebar_endpoints": "21 endpoints API activos",175"sidebar_templates": "16 plantillas de flujos",176"sidebar_modes": "2 modos: Rápido y IA",177"sidebar_status": "🚀 Estado",178"sidebar_current_mode": "Modo Actual:",179"sidebar_latency": "Latencia:",180"sidebar_info": "📝 Información",181"sidebar_description": "Sistema de análisis y generación de flujos de trabajo.",182"sidebar_milestone": "Milestone 1 - Completado ✅",183"mode_intelligent": "🧠 IA Inteligente",184"mode_fast": "⚡ Rápido",185 186 # Tabs187"tab_home": "🏠 Inicio",188"tab_analyze": "🧠 Análisis IA",189"tab_build": "⚙️ Construir Flujo",190"tab_github": "🔍 Búsqueda GitHub",191"tab_web": "🌐 Búsqueda Web",192"tab_chat": "💬 Chat",193 194 # Home tab195"home_welcome": "Bienvenido al Panel M1",196"home_features": "✨ Características Principales:",197"home_feature_1": "🧠 **Análisis IA**: Analiza tus necesidades y recomienda la mejor herramienta",198"home_feature_2": "⚙️ **Generación de Flujos**: Crea flujos de trabajo de n8n y ComfyUI",199"home_feature_3": "🔍 **Búsqueda Inteligente**: Busca en GitHub y la web",200"home_feature_4": "💬 **Chat IA**: Asistente conversacional para automatización",201"home_getting_started": "🚀 Comenzar:",202"home_step_1": "1. Activa el **Modo IA** en la barra lateral para análisis inteligente",203"home_step_2": "2. Navega por las pestañas para explorar características",204"home_step_3": "3. Prueba las consultas de ejemplo en cada pestaña",205"home_modes": "💡 Modos:",206"home_mode_fast": "**⚡ Rápido**: <100ms, plantillas predefinidas",207"home_mode_intelligent": "**🧠 Inteligente**: 2-3s, análisis profundo con Gemini",208"home_tip": "📌 **Tip**: Comienza con el modo rápido para probar, luego activa el modo IA para análisis profundo.",209 210 # AI Analysis tab211"analyze_title": "Permite que la IA analice tus necesidades de automatización",212"analyze_query": "Tu Consulta",213"analyze_placeholder": "Describe lo que deseas automatizar...",214"analyze_examples": "💡 Ver Consultas de Ejemplo",215"analyze_example_1": "Ejemplo 1: Correos Automatizados",216"analyze_example_2": "Ejemplo 2: Generación de Arte IA",217"analyze_example_3": "Ejemplo 3: Sincronización CRM",218"analyze_btn": "Analizar con IA ✨",219"analyze_result": "🧠 Resultado del Análisis IA",220"analyze_project_type": "Tipo de Proyecto",221"analyze_confidence": "Confianza",222"analyze_method": "Método",223"analyze_explanation": "📝 Explicación:",224"analyze_tools": "🔧 Herramientas Sugeridas:",225"analyze_steps": "📋 Próximos Pasos:",226"error_empty_query": "❌ Por favor ingrese una consulta",227"analyzing": "Analizando...",228 229 # Build Workflow tab230"build_title": "Genera flujos de trabajo completos a partir de descripciones",231"build_description": "Descripción del Flujo de Trabajo",232"build_placeholder": "Describe el flujo de trabajo que deseas crear...",233"build_tool": "Herramienta",234"build_tool_help": "n8n para automatización, ComfyUI para generación de imágenes IA",235"build_examples": "💡 Ver Flujos de Ejemplo",236"build_example_1": "Ejemplo 1: Webhook + Email",237"build_example_2": "Ejemplo 2: Monitor Twitter",238"build_example_3": "Ejemplo 3: Fotos IA",239"build_btn": "Generar Flujo de Trabajo 🚀",240"build_result": "✅ ¡Flujo de Trabajo Generado!",241"build_type": "Tipo",242"build_nodes": "Nodos",243"build_method": "Método",244"build_ai_analysis": "📊 Análisis IA:",245"build_explanation": "Explicación:",246"build_confidence": "Confianza:",247"build_json": "📄 JSON del Flujo de Trabajo:",248"generating": "Generando flujo de trabajo...",249"generated_ai": "🧠 Generado con IA",250"generated_template": "⚡ Generado con plantillas",251 252 # GitHub Search tab253"github_title": "Encuentra proyectos de código abierto relevantes",254"github_keywords": "Palabras Clave de Búsqueda",255"github_placeholder": "ej., automatización de flujos de trabajo",256"github_max": "Resultados Máximos",257"github_examples": "💡 Ver Ejemplos de Búsqueda",258"github_btn": "Buscar en GitHub 🔍",259"github_results": "🔍 Resultados de GitHub ({} encontrados)",260"github_description": "Descripción:",261"github_language": "Lenguaje:",262"github_docker": "🐳 **Docker:** Sí",263"github_url": "URL:",264"github_no_results": "📭 No se encontraron repositorios",265"searching_github": "Buscando en GitHub...",266 267 # Web Search tab268"web_title": "Busca en la web usando DuckDuckGo",269"web_query": "Consulta de Búsqueda",270"web_placeholder": "ej., ejemplos de automatización n8n",271"web_max": "Resultados Máximos",272"web_btn": "Buscar en Web 🔍",273"web_results": "🌐 Resultados de Búsqueda ({} encontrados)",274"web_no_title": "Sin título",275"web_no_description": "Sin descripción",276"web_no_results": "📭 No se encontraron resultados",277"searching_web": "Buscando en la web...",278 279 # Chat tab280"chat_title": "Conversa con la IA sobre tus necesidades de automatización",281"chat_placeholder": "Pregunta al asistente IA cualquier cosa...",282"chat_examples": "💡 Ver Iniciadores de Conversación",283"chat_example_1": "Quiero crear un bot que responda preguntas",284"chat_example_2": "Ayúdame a automatizar mis publicaciones",285"chat_example_3": "Necesito procesar archivos CSV",286"chat_thinking": "Pensando...",287"chat_tools": "Herramientas sugeridas:",288 289 # Footer290"footer_notes": "📝 Notas:",291"footer_fast": "**Modo Rápido (palabras clave)**: <100ms, usa plantillas predefinidas",292"footer_intelligent": "**Modo Inteligente (Gemini)**: 2-3s, análisis profundo con IA",293"footer_requirements": "**Requisitos**: Clave API de Gemini para modo inteligente (gratis en [Google AI Studio](https://aistudio.google.com/app/apikeys))",294"footer_milestone": "🚀 **Milestone 1** - Sistema de toma de decisiones IA básico completado",295 296 # Example texts297"ex_email": "Necesito enviar correos electrónicos automatizados a 1000 clientes cada mañana",298"ex_ai_art": "Quiero generar arte IA a partir de descripciones de texto y publicar en Instagram",299"ex_crm": "Procesar datos de clientes de Shopify y sincronizar con CRM",300"ex_chatbot": "Crear un chatbot que responda preguntas de mi documentación",301"ex_webhook": "Crear un flujo que reciba datos de clientes desde webhook y envíe correo de confirmación",302"ex_twitter": "Construir un flujo que monitoree Twitter para menciones y envíe notificaciones de Slack",303"ex_photos": "Generar fotos profesionales a partir de fotos subidas",304"ex_automation": "automatización de flujos de trabajo",305"ex_ml": "implementación de aprendizaje automático",306"ex_image_gen": "generación de imágenes IA",307"ex_bot": "Quiero crear un bot que responda preguntas de clientes desde mi sitio web",308"ex_social": "Ayúdame a automatizar mis publicaciones en redes sociales",309"ex_csv": "Necesito procesar archivos CSV y generar reportes"310}311}312 313def t(key: str, lang: str = "es") -> str:314 """Get translation for key in specified language"""315 return TRANSLATIONS.get(lang, {}).get(key, TRANSLATIONS["en"].get(key, key))316 317# Page config318st.set_page_config(319page_title="M1 - Agente de Flujo de Trabajo IA",320page_icon="🤖",321layout="wide",322initial_sidebar_state="expanded"323)324 325# Custom CSS326st.markdown("""327<style>328.main-header {329font-size: 2.5rem;330font-weight: bold;331color: #1f77b4;332margin-bottom: 0.5rem;333}334.sub-header {335font-size: 1.2rem;336color: #666;337margin-bottom: 2rem;338}339.feature-box {340padding: 1rem;341border-radius: 0.5rem;342background-color: #f0f2f6;343margin-bottom: 1rem;344}345.success-message {346padding: 1rem;347border-radius: 0.5rem;348background-color: #d4edda;349border: 1px solid #c3e6cb;350color: #155724;351}352.error-message {353padding: 1rem;354border-radius: 0.5rem;355background-color: #f8d7da;356border: 1px solid #f5c6cb;357color: #721c24;358}359</style>360""", unsafe_allow_html=True)361 362# Initialize components363@st.cache_resource364def init_components():365 """Initialize all M1 components (cached)"""366 return {367 'decision_agent': DecisionAgent(),368 'n8n_builder': N8NWorkflowBuilder(),369 'comfyui_builder': ComfyUIWorkflowBuilder(),370 'github_tool': GitHubSearchTool(),371 'web_tool': WebSearchTool(),372 'session_manager': SessionManager()373 }374 375components = init_components()376 377# Helper to run async functions378def run_async(coro):379 """Run async function in sync context"""380 try:381 loop = asyncio.get_event_loop()382 except RuntimeError:383 loop = asyncio.new_event_loop()384 asyncio.set_event_loop(loop)385 return loop.run_until_complete(coro)386 387# ========================================388# SIDEBAR - Global Settings389# ========================================390with st.sidebar:391 # Language selector392 lang = st.selectbox(393 "🌐 Language / Idioma",394 options=["es", "en"],395 format_func=lambda x: "🇪🇸 Español" if x == "es" else "🇬🇧 English",396 index=0397 )398 399 st.markdown("---")400 st.markdown(f"## {t('sidebar_config', lang)}")401 402 # Initialize use_llm in session state if not present403 if 'use_llm' not in st.session_state:404 st.session_state.use_llm = True405 406 use_llm = st.checkbox(407 t('sidebar_llm', lang),408 value=st.session_state.use_llm,409 key='use_llm_checkbox'410 )411 412 st.markdown(f"""413### {t('sidebar_stats', lang)}414- **{t('sidebar_endpoints', lang)}**415- **{t('sidebar_templates', lang)}**416- **{t('sidebar_modes', lang)}**417 418### {t('sidebar_status', lang)}419- **{t('sidebar_current_mode', lang)}** {t('mode_intelligent', lang) if use_llm else t('mode_fast', lang)}420- **{t('sidebar_latency', lang)}** {"2-3s" if use_llm else "<100ms"}421""")422 423 st.markdown("---")424 st.markdown(f"""425### {t('sidebar_info', lang)}426{t('sidebar_description', lang)}427 428**{t('sidebar_milestone', lang)}**429""")430 431# ========================================432# MAIN CONTENT433# ========================================434 435# Header436st.markdown(f'<div class="main-header">🤖 {t("title", lang)}</div>', unsafe_allow_html=True)437st.markdown(f'<div class="sub-header">{t("subtitle", lang)}</div>', unsafe_allow_html=True)438 439# Tabs440tab_home, tab_analyze, tab_build, tab_github, tab_web, tab_chat = st.tabs([441t("tab_home", lang),442t("tab_analyze", lang),443t("tab_build", lang),444t("tab_github", lang),445t("tab_web", lang),446t("tab_chat", lang)447])448 449# ========================================450# TAB 1: HOME451# ========================================452with tab_home:453 st.markdown(f"## {t('home_welcome', lang)}")454 455 col1, col2 = st.columns(2)456 457 with col1:458 st.markdown(f"""459### {t('home_features', lang)}460 461- {t('home_feature_1', lang)}462- {t('home_feature_2', lang)}463- {t('home_feature_3', lang)}464- {t('home_feature_4', lang)}465""")466 467 with col2:468 st.markdown(f"""469### {t('home_getting_started', lang)}470 471{t('home_step_1', lang)}472{t('home_step_2', lang)}473{t('home_step_3', lang)}474 475### {t('home_modes', lang)}476- {t('home_mode_fast', lang)}477- {t('home_mode_intelligent', lang)}478""")479 480 st.info(f"{t('home_tip', lang)}")481 482# ========================================483# TAB 2: AI ANALYSIS484# ========================================485with tab_analyze:486 st.markdown(f"### {t('analyze_title', lang)}")487 488 col1, col2 = st.columns([1, 1])489 490 with col1:491 # Handle example button clicks492 if 'analysis_example' not in st.session_state:493 st.session_state.analysis_example = ""494 495 with st.expander(t('analyze_examples', lang)):496 if st.button(t('analyze_example_1', lang), key="ex1"):497 st.session_state.analysis_example = t('ex_email', lang)498 if st.button(t('analyze_example_2', lang), key="ex2"):499 st.session_state.analysis_example = t('ex_ai_art', lang)500 if st.button(t('analyze_example_3', lang), key="ex3"):501 st.session_state.analysis_example = t('ex_crm', lang)502 503 analysis_query = st.text_area(504 t('analyze_query', lang),505 value=st.session_state.analysis_example,506 placeholder=t('analyze_placeholder', lang),507 height=150,508 key="analysis_query"509 )510 511 analyze_btn = st.button(t('analyze_btn', lang), type="primary", use_container_width=True, key="analyze_btn")512 513 with col2:514 if analyze_btn:515 if not analysis_query:516 st.error(t('error_empty_query', lang))517 else:518 with st.spinner(t('analyzing', lang)):519 try:520 result = run_async(components['decision_agent'].analyze(521 analysis_query,522 context={'use_llm': use_llm}523 ))524 525 st.markdown(f"## {t('analyze_result', lang)}")526 527 col_a, col_b, col_c = st.columns(3)528 with col_a:529 st.metric(t('analyze_project_type', lang), result['project_type'].upper())530 with col_b:531 st.metric(t('analyze_confidence', lang), f"{result['confidence']*100:.0f}%")532 with col_c:533 st.metric(t('analyze_method', lang), result.get('classification_method', 'N/A'))534 535 st.markdown(f"### {t('analyze_explanation', lang)}")536 st.write(result['explanation'])537 538 st.markdown(f"### {t('analyze_tools', lang)}")539 for tool in result.get('suggested_tools', []):540 st.write(f"- {tool}")541 542 st.markdown(f"### {t('analyze_steps', lang)}")543 for i, step in enumerate(result.get('next_steps', []), 1):544 st.write(f"{i}. {step}")545 546 except Exception as e:547 st.error(f"❌ Error: {str(e)}")548 549# ========================================550# TAB 3: BUILD WORKFLOW551# ========================================552with tab_build:553 st.markdown(f"### {t('build_title', lang)}")554 555 col1, col2 = st.columns([1, 1])556 557 with col1:558 # Handle example button clicks559 if 'build_example' not in st.session_state:560 st.session_state.build_example = ""561 562 with st.expander(t('build_examples', lang)):563 if st.button(t('build_example_1', lang), key="build_ex1"):564 st.session_state.build_example = t('ex_webhook', lang)565 if st.button(t('build_example_2', lang), key="build_ex2"):566 st.session_state.build_example = t('ex_twitter', lang)567 if st.button(t('build_example_3', lang), key="build_ex3"):568 st.session_state.build_example = t('ex_photos', lang)569 570 build_description = st.text_area(571 t('build_description', lang),572 value=st.session_state.build_example,573 placeholder=t('build_placeholder', lang),574 height=150,575 key="build_description"576 )577 578 build_tool = st.radio(579 t('build_tool', lang),580 options=["n8n", "comfyui"],581 help=t('build_tool_help', lang),582 horizontal=True583 )584 585 build_btn = st.button(t('build_btn', lang), type="primary", use_container_width=True, key="build_btn")586 587 with col2:588 if build_btn:589 if not build_description:590 st.error(t('error_empty_query', lang))591 else:592 with st.spinner(t('generating', lang)):593 try:594 if build_tool == "n8n":595 workflow = run_async(components['n8n_builder'].generate_workflow(596 build_description,597 context={'use_llm': use_llm}598 ))599 else:600 workflow = run_async(components['comfyui_builder'].generate_workflow(601 build_description,602 context={'use_llm': use_llm}603 ))604 605 enhanced = workflow.get('meta', {}).get('generated_with_llm', False)606 status = t('generated_ai', lang) if enhanced else t('generated_template', lang)607 608 st.markdown(f"## {t('build_result', lang)}")609 610 col_a, col_b, col_c = st.columns(3)611 with col_a:612 st.metric(t('build_type', lang), build_tool.upper())613 with col_b:614 st.metric(t('build_nodes', lang), len(workflow.get('nodes', [])))615 with col_c:616 st.metric(t('build_method', lang), status)617 618 # Show workflow summary619 st.markdown("### 📋 Workflow Summary")620 st.markdown(f"**Name:** {workflow.get('name', 'N/A')}")621 622 # Show nodes in readable format623 nodes = workflow.get('nodes', [])624 if nodes:625 st.markdown("**Nodes:**")626 for i, node in enumerate(nodes, 1):627 node_name = node.get('name', 'Unknown')628 node_type = node.get('type', 'unknown').split('.')[-1]629 st.write(f"{i}. **{node_name}** (`{node_type}`)")630 631 # Show connections632 connections = workflow.get('connections', {})633 if connections:634 st.markdown("**Flow:**")635 flow_text = " → ".join([node.get('name', f"Node {i+1}") for i, node in enumerate(nodes)])636 st.info(flow_text)637 638 # Show AI analysis if available639 if enhanced and 'llm_analysis' in workflow.get('meta', {}):640 analysis = workflow['meta']['llm_analysis']641 with st.expander("🧠 AI Analysis Details", expanded=False):642 st.write(f"**{t('build_explanation', lang)}** {analysis.get('explanation', 'N/A')}")643 st.write(f"**{t('build_confidence', lang)}** {analysis.get('confidence', 0)*100:.0f}%")644 645 # Show JSON in collapsible section646 with st.expander(f"📄 {t('build_json', lang)}", expanded=False):647 st.code(json.dumps(workflow, indent=2, ensure_ascii=False), language="json")648 649 # Download button650 json_str = json.dumps(workflow, indent=2, ensure_ascii=False)651 st.download_button(652 label="⬇️ Download Workflow JSON",653 data=json_str,654 file_name=f"{workflow.get('name', 'workflow')}.json",655 mime="application/json"656 )657 658 except Exception as e:659 st.error(f"❌ Error: {str(e)}")660 661# ========================================662# TAB 4: GITHUB SEARCH663# ========================================664with tab_github:665 st.markdown(f"### {t('github_title', lang)}")666 667 col1, col2 = st.columns([1, 2])668 669 with col1:670 github_keywords = st.text_input(671 t('github_keywords', lang),672 placeholder=t('github_placeholder', lang)673 )674 675 github_max = st.slider(676 t('github_max', lang),677 min_value=1,678 max_value=10,679 value=5680 )681 682 with st.expander(t('github_examples', lang)):683 if st.button(t('ex_automation', lang), key="gh_ex1"):684 st.session_state.github_keywords_input = t('ex_automation', lang)685 st.rerun()686 if st.button(t('ex_ml', lang), key="gh_ex2"):687 st.session_state.github_keywords_input = t('ex_ml', lang)688 st.rerun()689 if st.button(t('ex_image_gen', lang), key="gh_ex3"):690 st.session_state.github_keywords_input = t('ex_image_gen', lang)691 st.rerun()692 693 github_btn = st.button(t('github_btn', lang), type="primary", use_container_width=True)694 695 with col2:696 if github_btn:697 if not github_keywords:698 st.error(t('error_empty_query', lang))699 else:700 with st.spinner(t('searching_github', lang)):701 try:702 results = run_async(components['github_tool'].search(703 github_keywords,704 max_results=int(github_max)705 ))706 707 if not results:708 st.info(t('github_no_results', lang))709 else:710 st.markdown(f"## {t('github_results', lang).format(len(results))}")711 712 for i, repo in enumerate(results, 1):713 with st.expander(f"**{i}. {repo.get('full_name', 'N/A')}** ⭐ {repo.get('stars', 0):,}"):714 st.write(f"**{t('github_description', lang)}** {repo.get('description', t('web_no_description', lang))}")715 st.write(f"**{t('github_language', lang)}** {repo.get('language', 'N/A')}")716 if repo.get('has_docker'):717 st.write(t('github_docker', lang))718 st.markdown(f"**{t('github_url', lang)}** [{repo.get('url', 'N/A')}]({repo.get('url', '#')})")719 720 except Exception as e:721 st.error(f"❌ Error: {str(e)}")722 723# ========================================724# TAB 5: WEB SEARCH725# ========================================726with tab_web:727 st.markdown(f"### {t('web_title', lang)}")728 729 col1, col2 = st.columns([1, 2])730 731 with col1:732 web_query = st.text_input(733 t('web_query', lang),734 placeholder=t('web_placeholder', lang)735 )736 737 web_max = st.slider(738 t('web_max', lang),739 min_value=1,740 max_value=10,741 value=5,742 key="web_max_slider"743 )744 745 web_btn = st.button(t('web_btn', lang), type="primary", use_container_width=True, key="web_btn")746 747 with col2:748 if web_btn:749 if not web_query:750 st.error(t('error_empty_query', lang))751 else:752 with st.spinner(t('searching_web', lang)):753 try:754 results = run_async(components['web_tool'].search(755 web_query,756 max_results=int(web_max)757 ))758 759 if not results:760 st.info(t('web_no_results', lang))761 else:762 st.markdown(f"## {t('web_results', lang).format(len(results))}")763 764 for i, result in enumerate(results, 1):765 with st.expander(f"**{i}. {result.get('title', t('web_no_title', lang))}**"):766 st.write(result.get('snippet', t('web_no_description', lang)))767 st.markdown(f"🔗 [{result.get('url', 'N/A')}]({result.get('url', '#')})")768 769 except Exception as e:770 st.error(f"❌ Error: {str(e)}")771 772# ========================================773# TAB 6: CHAT774# ========================================775with tab_chat:776 st.markdown(f"### {t('chat_title', lang)}")777 778 # Initialize chat history779 if 'chat_history' not in st.session_state:780 st.session_state.chat_history = []781 if 'chat_session' not in st.session_state:782 st.session_state.chat_session = components['session_manager'].create_session()783 784 # Display chat history785 for message in st.session_state.chat_history:786 with st.chat_message(message["role"]):787 st.write(message["content"])788 789 # Chat input790 chat_input = st.chat_input(t('chat_placeholder', lang))791 792 if chat_input:793 # Add user message794 st.session_state.chat_history.append({"role": "user", "content": chat_input})795 st.session_state.chat_session.add_message("user", chat_input)796 797 with st.chat_message("user"):798 st.write(chat_input)799 800 # Get AI response801 with st.chat_message("assistant"):802 with st.spinner(t('chat_thinking', lang)):803 try:804 result = run_async(components['decision_agent'].analyze(805 chat_input,806 context={'use_llm': use_llm}807 ))808 809 response = f"{result['explanation']}\n\n**{t('chat_tools', lang)}** {', '.join(result.get('suggested_tools', []))}"810 st.write(response)811 812 # Add to history813 st.session_state.chat_history.append({"role": "assistant", "content": response})814 st.session_state.chat_session.add_message("assistant", response)815 816 except Exception as e:817 error_msg = f"❌ Error: {str(e)}"818 st.error(error_msg)819 st.session_state.chat_history.append({"role": "assistant", "content": error_msg})820 821 # Example starters822 with st.expander(t('chat_examples', lang)):823 if st.button(t('chat_example_1', lang), key="chat_ex1"):824 st.session_state.pending_chat = t('ex_bot', lang)825 st.rerun()826 if st.button(t('chat_example_2', lang), key="chat_ex2"):827 st.session_state.pending_chat = t('ex_social', lang)828 st.rerun()829 if st.button(t('chat_example_3', lang), key="chat_ex3"):830 st.session_state.pending_chat = t('ex_csv', lang)831 st.rerun()832 833# ========================================834# FOOTER835# ========================================836st.markdown("---")837st.markdown(f"""838### {t('footer_notes', lang)}839- {t('footer_fast', lang)}840- {t('footer_intelligent', lang)}841- {t('footer_requirements', lang)}842 843{t('footer_milestone', lang)}844""")845 