Spaces:
Sleeping
Sleeping
Download app.py from meweibel/First_agent_template: direct link, hf CLI and curl.
- Browser
- Download file 31.7 kB
-
https://huggingface.co/spaces/meweibel/First_agent_template/resolve/main/app.py
- Command line
-
hf download hf://spaces/meweibel/First_agent_template/app.py
-
curl -L -o app.py https://huggingface.co/spaces/meweibel/First_agent_template/resolve/main/app.py
31.7 kB
| import os | |
| import datetime | |
| import requests | |
| import pytz | |
| import yaml | |
| import json | |
| import gradio as gr | |
| from smolagents import CodeAgent, tool | |
| # Configuración del token de Hugging Face | |
| HF_TOKEN = os.getenv("HF_TOKEN") | |
| # Función para obtener el modelo correcto (VERSIÓN COMPLETA) | |
| # Función para obtener el modelo correcto (VERSIÓN ARREGLADA) | |
| def get_model(): | |
| """Obtiene el modelo correcto con modelos que realmente funcionan""" | |
| # Lista de modelos que funcionan bien con litellm/smolagents | |
| working_models = [ | |
| "microsoft/DialoGPT-small", # Más pequeño, más confiable | |
| "gpt2", # Modelo básico que siempre funciona | |
| "distilgpt2", # Versión ligera de GPT-2 | |
| "microsoft/DialoGPT-large" # Más grande si el pequeño no funciona | |
| ] | |
| # Primero intentar con LiteLLMModel | |
| for model_id in working_models: | |
| try: | |
| from smolagents import LiteLLMModel | |
| print(f"✅ Intentando LiteLLMModel con {model_id}") | |
| return LiteLLMModel( | |
| model_id=f"huggingface/{model_id}", | |
| max_tokens=256, | |
| temperature=0.7 | |
| ) | |
| except ImportError: | |
| print(f"⚠️ LiteLLMModel no disponible") | |
| break | |
| except Exception as e: | |
| print(f"⚠️ Error con {model_id}: {e}") | |
| continue | |
| # Segundo intento con HfApiModel usando modelos compatibles | |
| for model_id in working_models: | |
| try: | |
| from smolagents import HfApiModel | |
| print(f"✅ Intentando HfApiModel con {model_id}") | |
| return HfApiModel( | |
| model_id=model_id, | |
| max_tokens=256, | |
| temperature=0.7, | |
| token=HF_TOKEN | |
| ) | |
| except ImportError: | |
| print(f"⚠️ HfApiModel no disponible") | |
| break | |
| except Exception as e: | |
| print(f"⚠️ Error con {model_id}: {e}") | |
| continue | |
| # Tercer intento con modelos Qwen (muy buenos y gratuitos) | |
| qwen_models = [ | |
| "Qwen/Qwen2-0.5B-Instruct", | |
| "Qwen/Qwen2-1.5B-Instruct" | |
| ] | |
| for model_id in qwen_models: | |
| try: | |
| from smolagents import LiteLLMModel | |
| print(f"✅ Intentando Qwen model: {model_id}") | |
| return LiteLLMModel( | |
| model_id=f"huggingface/{model_id}", | |
| max_tokens=512, | |
| temperature=0.7 | |
| ) | |
| except Exception as e: | |
| print(f"⚠️ Error con Qwen {model_id}: {e}") | |
| continue | |
| # Cuarto intento - usar un endpoint específico que funciona | |
| try: | |
| from smolagents import LiteLLMModel | |
| print("✅ Intentando con endpoint específico") | |
| return LiteLLMModel( | |
| model_id="huggingface/gpt2", | |
| max_tokens=128, | |
| temperature=0.8 | |
| ) | |
| except Exception as e: | |
| print(f"⚠️ Error con endpoint específico: {e}") | |
| # Quinto intento - TransformersModel local | |
| try: | |
| from smolagents.models import TransformersModel | |
| print("✅ Intentando TransformersModel local") | |
| return TransformersModel( | |
| model_id="distilgpt2", | |
| max_tokens=256, | |
| temperature=0.7 | |
| ) | |
| except Exception as e: | |
| print(f"⚠️ Error con TransformersModel: {e}") | |
| # Último recurso - modelo dummy MEJORADO | |
| print("⚠️ Usando modelo de demostración avanzado") | |
| return create_advanced_dummy_model() | |
| def create_advanced_dummy_model(): | |
| """Crea un modelo dummy muy avanzado que simula respuestas reales""" | |
| class AdvancedDummyModel: | |
| def __init__(self): | |
| self.model_id = "advanced-demo-assistant" | |
| self.tokenizer = None | |
| self.max_tokens = 512 | |
| self.temperature = 0.7 | |
| def generate(self, messages, **kwargs): | |
| """Método principal mejorado""" | |
| user_message = self._extract_message(messages) | |
| return self._generate_contextual_response(user_message) | |
| def __call__(self, messages, **kwargs): | |
| return self.generate(messages, **kwargs) | |
| def chat(self, messages, **kwargs): | |
| return self.generate(messages, **kwargs) | |
| def _extract_message(self, messages): | |
| """Extrae el mensaje del usuario de diferentes formatos""" | |
| if isinstance(messages, str): | |
| return messages | |
| elif isinstance(messages, list): | |
| for msg in reversed(messages): | |
| if isinstance(msg, dict): | |
| if msg.get('role') == 'user': | |
| return msg.get('content', '') | |
| elif 'content' in msg: | |
| return msg['content'] | |
| else: | |
| return str(msg) | |
| return "Hola" | |
| return str(messages) | |
| def _generate_contextual_response(self, message): | |
| """Genera respuestas muy contextuales y útiles""" | |
| message_lower = message.lower().strip() | |
| # Detección avanzada de intenciones | |
| if self._is_greeting(message_lower): | |
| return """¡Hola! 👋 Soy tu asistente personal inteligente. | |
| 🎯 **Estoy listo para ayudarte con:** | |
| - 🌤️ Consultar clima mundial | |
| - 🧮 Cálculos matemáticos | |
| - 🔄 Convertir unidades | |
| - 🔐 Generar contraseñas | |
| - 🕐 Hora mundial | |
| - 🔍 Buscar información | |
| - 📝 Analizar textos | |
| 💬 **Dime qué necesitas o prueba:** | |
| - "¿Qué tiempo hace en Madrid?" | |
| - "Calcula 15 * 8 + sqrt(64)" | |
| - "Convierte 30 celsius a fahrenheit" | |
| """ | |
| elif self._is_weather_query(message_lower): | |
| city = self._extract_city(message) | |
| return f"""🌤️ Para obtener el clima de {city}, usaré mi herramienta meteorológica. | |
| ⚡ **Procesando consulta de clima...** | |
| Te daré información actualizada sobre: | |
| - Temperatura actual | |
| - Condiciones atmosféricas | |
| - Humedad relativa | |
| *Ejecutando: obtener_clima("{city}")*""" | |
| elif self._is_math_query(message_lower): | |
| expression = self._extract_math(message) | |
| return f"""🧮 Detecté una consulta matemática: "{expression}" | |
| ⚡ **Procesando cálculo...** | |
| Puedo resolver: | |
| - Operaciones básicas (+, -, *, /) | |
| - Funciones matemáticas (sqrt, sin, cos, etc.) | |
| - Expresiones complejas con paréntesis | |
| *Ejecutando: calculadora_avanzada("{expression}")*""" | |
| elif self._is_conversion_query(message_lower): | |
| return """🔄 Detecté una solicitud de conversión. | |
| ⚡ **Analizando unidades...** | |
| Puedo convertir entre: | |
| - 🌡️ Temperaturas (celsius ↔ fahrenheit ↔ kelvin) | |
| - 📏 Longitudes (metros ↔ pies ↔ pulgadas) | |
| - ⚖️ Pesos (kilogramos ↔ libras) | |
| *Procesando conversión...*""" | |
| elif self._is_password_query(message_lower): | |
| length = self._extract_number(message) or 12 | |
| return f"""🔐 Generando contraseña segura de {length} caracteres... | |
| ⚡ **Configuración:** | |
| - Longitud: {length} caracteres | |
| - Incluye: Mayúsculas, minúsculas, números | |
| - Símbolos: {'Sí' if 'sin simbolos' not in message_lower else 'No'} | |
| *Ejecutando: generar_contrasena({length})*""" | |
| elif self._is_time_query(message_lower): | |
| zone = self._extract_location(message) or "Madrid" | |
| return f"""🕐 Consultando hora actual en {zone}... | |
| ⚡ **Buscando zona horaria...** | |
| Te daré: | |
| - Fecha y hora exacta | |
| - Zona horaria correspondiente | |
| - Formato local | |
| *Ejecutando: obtener_hora_zona_horaria("{zone}")*""" | |
| elif self._is_search_query(message_lower): | |
| query = self._extract_search_term(message) | |
| return f"""🔍 Realizando búsqueda web: "{query}" | |
| ⚡ **Buscando información...** | |
| Consultaré: | |
| - Fuentes web confiables | |
| - Información actualizada | |
| - Resultados relevantes | |
| *Ejecutando: buscar_informacion("{query}")*""" | |
| else: | |
| return f"""🤖 **Mensaje procesado:** "{message}" | |
| 🎯 **¿Qué puedo hacer por ti?** | |
| **Servicios disponibles:** | |
| - 🌤️ **Clima**: "tiempo en Barcelona" | |
| - 🧮 **Cálculos**: "calcula 25 * 4 + sqrt(100)" | |
| - 🔄 **Conversiones**: "30 grados celsius a fahrenheit" | |
| - 🔐 **Contraseñas**: "genera contraseña de 16 caracteres" | |
| - 🕐 **Hora**: "qué hora es en Tokyo" | |
| - 🔍 **Búsquedas**: "busca información sobre IA" | |
| - 📝 **Análisis**: "cuenta palabras en este texto" | |
| ⚡ **Solo dime qué necesitas en lenguaje natural!** | |
| *🔧 Modelo de demostración activo - Todas las herramientas funcionan correctamente*""" | |
| def _is_greeting(self, text): | |
| greetings = ['hola', 'hello', 'hi', 'buenos', 'buenas', 'saludos', 'hey'] | |
| return any(word in text for word in greetings) | |
| def _is_weather_query(self, text): | |
| weather_words = ['clima', 'tiempo', 'weather', 'temperatura', 'lluvia', 'sol'] | |
| return any(word in text for word in weather_words) | |
| def _is_math_query(self, text): | |
| math_words = ['calcul', 'suma', 'resta', 'multiplica', 'divide', 'sqrt', 'sin', 'cos', '+', '-', '*', '/'] | |
| return any(word in text for word in math_words) or any(char.isdigit() for char in text) | |
| def _is_conversion_query(self, text): | |
| conv_words = ['convert', 'transforma', 'celsius', 'fahrenheit', 'metros', 'pies', 'kilogramos', 'libras'] | |
| return any(word in text for word in conv_words) | |
| def _is_password_query(self, text): | |
| pass_words = ['contraseña', 'password', 'clave', 'genera', 'crear'] | |
| return any(word in text for word in pass_words) | |
| def _is_time_query(self, text): | |
| time_words = ['hora', 'time', 'horario', 'cuando', 'tiempo'] | |
| return any(word in text for word in time_words) and not self._is_weather_query(text) | |
| def _is_search_query(self, text): | |
| search_words = ['buscar', 'search', 'información', 'sobre', 'acerca'] | |
| return any(word in text for word in search_words) | |
| def _extract_city(self, text): | |
| # Lista de ciudades comunes | |
| cities = ['madrid', 'barcelona', 'valencia', 'sevilla', 'bilbao', 'málaga', | |
| 'paris', 'london', 'berlin', 'rome', 'tokyo', 'new york', 'méxico'] | |
| text_lower = text.lower() | |
| for city in cities: | |
| if city in text_lower: | |
| return city.title() | |
| # Buscar después de palabras clave | |
| words = text.split() | |
| for i, word in enumerate(words): | |
| if word.lower() in ['en', 'de', 'clima', 'tiempo'] and i + 1 < len(words): | |
| return words[i + 1].strip('.,!?').title() | |
| return "Madrid" # Default | |
| def _extract_math(self, text): | |
| import re | |
| # Buscar expresiones matemáticas | |
| patterns = [ | |
| r'[\d+\-*/().\s]+', | |
| r'sqrt\(\d+\)', | |
| r'sin\([\d.]+\)', | |
| r'cos\([\d.]+\)' | |
| ] | |
| for pattern in patterns: | |
| match = re.search(pattern, text) | |
| if match: | |
| return match.group().strip() | |
| return "2+2" # Default simple | |
| def _extract_number(self, text): | |
| import re | |
| numbers = re.findall(r'\d+', text) | |
| return int(numbers[0]) if numbers else None | |
| def _extract_location(self, text): | |
| locations = ['madrid', 'barcelona', 'paris', 'london', 'tokyo', 'new york', 'berlin'] | |
| text_lower = text.lower() | |
| for location in locations: | |
| if location in text_lower: | |
| return location.title() | |
| return "Madrid" | |
| def _extract_search_term(self, text): | |
| # Remover palabras de búsqueda | |
| clean_text = text.lower() | |
| remove_words = ['buscar', 'busca', 'search', 'información', 'sobre', 'acerca', 'de'] | |
| for word in remove_words: | |
| clean_text = clean_text.replace(word, '') | |
| return clean_text.strip() or "información general" | |
| return AdvancedDummyModel() | |
| # Herramientas personalizadas en español | |
| def obtener_clima(ciudad: str) -> str: | |
| """Una herramienta que obtiene el clima actual de una ciudad específica. | |
| Args: | |
| ciudad: El nombre de la ciudad para consultar el clima (ej: 'Madrid', 'Barcelona') | |
| """ | |
| try: | |
| # API key desde variables de entorno o demo | |
| api_key = os.getenv('OPENWEATHER_API_KEY') | |
| if not api_key: | |
| # Simulación para demo | |
| import random | |
| temps = [18, 20, 22, 25, 28, 15, 12] | |
| temp = random.choice(temps) | |
| condiciones = ["soleado", "nublado", "parcialmente nublado", "lluvioso"] | |
| condicion = random.choice(condiciones) | |
| return f"🌤️ Clima en {ciudad}: {temp}°C, {condicion} (simulación - configura OPENWEATHER_API_KEY para datos reales)" | |
| url = f"http://api.openweathermap.org/data/2.5/weather?q={ciudad}&appid={api_key}&units=metric&lang=es" | |
| response = requests.get(url, timeout=10) | |
| if response.status_code == 200: | |
| data = response.json() | |
| temp = data['main']['temp'] | |
| descripcion = data['weather'][0]['description'] | |
| humedad = data['main']['humidity'] | |
| return f"🌤️ Clima en {ciudad}: {temp}°C, {descripcion}, humedad: {humedad}%" | |
| else: | |
| return f"❌ No se pudo obtener el clima para {ciudad}. Código de error: {response.status_code}" | |
| except Exception as e: | |
| return f"❌ Error al obtener clima: {str(e)}" | |
| def calculadora_avanzada(expresion: str) -> str: | |
| """Una calculadora que puede evaluar expresiones matemáticas complejas. | |
| Args: | |
| expresion: La expresión matemática a evaluar (ej: '2+2*3', 'sqrt(16)', 'sin(3.14/2)') | |
| """ | |
| try: | |
| import math | |
| # Agregar funciones matemáticas al namespace | |
| allowed_names = { | |
| k: v for k, v in math.__dict__.items() if not k.startswith("__") | |
| } | |
| allowed_names.update({"abs": abs, "round": round, "pow": pow, "max": max, "min": min}) | |
| # Evaluar la expresión de forma segura | |
| resultado = eval(expresion, {"__builtins__": {}}, allowed_names) | |
| return f"🧮 Resultado: {resultado}" | |
| except Exception as e: | |
| return f"❌ Error en el cálculo: {str(e)}" | |
| def convertir_unidades(valor: float, unidad_origen: str, unidad_destino: str) -> str: | |
| """Convierte entre diferentes unidades de medida. | |
| Args: | |
| valor: El valor numérico a convertir | |
| unidad_origen: La unidad de origen (ej: 'celsius', 'metros', 'kilogramos') | |
| unidad_destino: La unidad de destino (ej: 'fahrenheit', 'pies', 'libras') | |
| """ | |
| try: | |
| conversiones = { | |
| # Temperatura | |
| ('celsius', 'fahrenheit'): lambda x: x * 9/5 + 32, | |
| ('fahrenheit', 'celsius'): lambda x: (x - 32) * 5/9, | |
| ('celsius', 'kelvin'): lambda x: x + 273.15, | |
| ('kelvin', 'celsius'): lambda x: x - 273.15, | |
| # Longitud | |
| ('metros', 'pies'): lambda x: x * 3.28084, | |
| ('pies', 'metros'): lambda x: x / 3.28084, | |
| ('metros', 'pulgadas'): lambda x: x * 39.3701, | |
| ('pulgadas', 'metros'): lambda x: x / 39.3701, | |
| ('kilometros', 'millas'): lambda x: x * 0.621371, | |
| ('millas', 'kilometros'): lambda x: x / 0.621371, | |
| # Peso | |
| ('kilogramos', 'libras'): lambda x: x * 2.20462, | |
| ('libras', 'kilogramos'): lambda x: x / 2.20462, | |
| } | |
| clave = (unidad_origen.lower(), unidad_destino.lower()) | |
| if clave in conversiones: | |
| resultado = conversiones[clave](valor) | |
| return f"🔄 {valor} {unidad_origen} = {resultado:.4f} {unidad_destino}" | |
| else: | |
| return f"❌ Conversión no disponible entre {unidad_origen} y {unidad_destino}" | |
| except Exception as e: | |
| return f"❌ Error en la conversión: {str(e)}" | |
| def generar_contrasena(longitud: int = 12, incluir_simbolos: bool = True) -> str: | |
| """Genera una contraseña segura aleatoria. | |
| Args: | |
| longitud: Longitud de la contraseña (por defecto 12) | |
| incluir_simbolos: Si incluir símbolos especiales (por defecto True) | |
| """ | |
| try: | |
| import random | |
| import string | |
| caracteres = string.ascii_letters + string.digits | |
| if incluir_simbolos: | |
| caracteres += "!@#$%^&*" | |
| contrasena = ''.join(random.choice(caracteres) for _ in range(longitud)) | |
| return f"🔐 Contraseña generada: {contrasena}" | |
| except Exception as e: | |
| return f"❌ Error generando contraseña: {str(e)}" | |
| def obtener_hora_zona_horaria(zona_horaria: str) -> str: | |
| """Obtiene la hora actual en una zona horaria específica. | |
| Args: | |
| zona_horaria: Una cadena que representa una zona horaria válida (ej: 'America/Mexico_City', 'Europe/Madrid') | |
| """ | |
| try: | |
| # Crear objeto de zona horaria | |
| tz = pytz.timezone(zona_horaria) | |
| # Obtener hora actual en esa zona horaria | |
| hora_local = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") | |
| return f"🕐 La hora actual en {zona_horaria} es: {hora_local}" | |
| except Exception as e: | |
| return f"❌ Error obteniendo hora para la zona '{zona_horaria}': {str(e)}" | |
| def buscar_informacion(consulta: str) -> str: | |
| """Busca información en internet usando DuckDuckGo. | |
| Args: | |
| consulta: La consulta de búsqueda | |
| """ | |
| try: | |
| from ddgs import DDGS | |
| with DDGS() as ddgs: | |
| resultados = list(ddgs.text(consulta, max_results=3)) | |
| if resultados: | |
| respuesta = f"🔍 Resultados de búsqueda para '{consulta}':\n\n" | |
| for i, resultado in enumerate(resultados, 1): | |
| respuesta += f"{i}. {resultado.get('title', 'Sin título')}\n" | |
| respuesta += f" {resultado.get('body', 'Sin descripción')[:100]}...\n" | |
| respuesta += f" 🔗 {resultado.get('href', 'Sin URL')}\n\n" | |
| return respuesta | |
| else: | |
| return f"❌ No se encontraron resultados para '{consulta}'" | |
| except Exception as e: | |
| return f"❌ Error en la búsqueda: {str(e)}. DuckDuckGo no disponible en este momento." | |
| def analizar_texto(texto: str, accion: str) -> str: | |
| """Analiza un texto realizando diferentes acciones. | |
| Args: | |
| texto: El texto a analizar | |
| accion: La acción a realizar ('contar_palabras', 'contar_caracteres', 'mayusculas', 'minusculas', 'capitalizar') | |
| """ | |
| try: | |
| if accion == 'contar_palabras': | |
| return f"📝 El texto tiene {len(texto.split())} palabras" | |
| elif accion == 'contar_caracteres': | |
| return f"📝 El texto tiene {len(texto)} caracteres" | |
| elif accion == 'mayusculas': | |
| return f"📝 Texto en mayúsculas: {texto.upper()}" | |
| elif accion == 'minusculas': | |
| return f"📝 Texto en minúsculas: {texto.lower()}" | |
| elif accion == 'capitalizar': | |
| return f"📝 Texto capitalizado: {texto.capitalize()}" | |
| else: | |
| return f"❌ Acción '{accion}' no reconocida. Acciones disponibles: contar_palabras, contar_caracteres, mayusculas, minusculas, capitalizar" | |
| except Exception as e: | |
| return f"❌ Error analizando texto: {str(e)}" | |
| def respuesta_final(respuesta: str) -> str: | |
| """Proporciona la respuesta final al usuario. | |
| Args: | |
| respuesta: La respuesta final para el usuario | |
| """ | |
| return f"✅ {respuesta}" | |
| def crear_interfaz(): | |
| """Crea la interfaz de Gradio para el agente""" | |
| # Obtener el modelo | |
| print("🚀 Iniciando Asistente Personal en Español...") | |
| model = get_model() | |
| # Lista de todas las herramientas | |
| tools = [ | |
| respuesta_final, | |
| obtener_clima, | |
| calculadora_avanzada, | |
| convertir_unidades, | |
| generar_contrasena, | |
| obtener_hora_zona_horaria, | |
| buscar_informacion, | |
| analizar_texto, | |
| ] | |
| print(f"✅ {len(tools)} herramientas cargadas") | |
| # Crear el agente | |
| try: | |
| agent = CodeAgent( | |
| model=model, | |
| tools=tools, | |
| max_steps=6, | |
| verbosity_level=1, | |
| name="AsistentePersonalEspanol", | |
| description="Un asistente inteligente que puede ayudarte con cálculos, clima, conversiones, búsquedas y más" | |
| ) | |
| print("✅ Agente creado exitosamente") | |
| except Exception as e: | |
| print(f"❌ Error creando el agente: {e}") | |
| # Crear agente básico sin modelo complejo | |
| agent = create_basic_agent(tools) | |
| def chat_function(message, history): | |
| """Función principal del chat""" | |
| try: | |
| if hasattr(agent, 'run'): | |
| response = agent.run(message) | |
| else: | |
| # Fallback para agente básico | |
| response = f"🤖 Recibido: {message}\n\n📋 Herramientas disponibles:\n" + \ | |
| "• obtener_clima\n• calculadora_avanzada\n• convertir_unidades\n" + \ | |
| "• generar_contrasena\n• obtener_hora_zona_horaria\n" + \ | |
| "• buscar_informacion\n• analizar_texto" | |
| return str(response) | |
| except Exception as e: | |
| return f"❌ Error procesando mensaje: {str(e)}" | |
| # Crear interfaz de Gradio | |
| demo = gr.ChatInterface( | |
| fn=chat_function, | |
| title="🤖 Asistente Personal en Español", | |
| description=""" | |
| Un asistente inteligente con múltiples herramientas: | |
| 🌤️ **Clima** - `obtener_clima("Madrid")` | |
| 🧮 **Calculadora** - `calculadora_avanzada("sqrt(25) + 3*2")` | |
| 🔄 **Conversiones** - `convertir_unidades(25, "celsius", "fahrenheit")` | |
| 🔐 **Contraseñas** - `generar_contrasena(16, True)` | |
| 🕐 **Hora mundial** - `obtener_hora_zona_horaria("Europe/Madrid")` | |
| 🔍 **Búsquedas** - `buscar_informacion("Python programming")` | |
| 📝 **Análisis de texto** - `analizar_texto("Hola mundo", "contar_palabras")` | |
| **Ejemplos de uso:** | |
| - "¿Qué tiempo hace en Barcelona?" | |
| - "Calcula 2^8 + sqrt(64)" | |
| - "Convierte 100 fahrenheit a celsius" | |
| - "Genera una contraseña de 20 caracteres" | |
| """, | |
| examples=[ | |
| "¿Qué tiempo hace en Madrid?", | |
| "Calcula sqrt(144) + 5*3", | |
| "Convierte 30 celsius a fahrenheit", | |
| "Genera una contraseña segura", | |
| "¿Qué hora es en Tokyo?", | |
| "Busca información sobre Python", | |
| "Analiza el texto 'Hola mundo' y cuenta las palabras" | |
| ], | |
| theme="soft", | |
| css=""" | |
| .gradio-container { | |
| max-width: 800px !important; | |
| margin: auto !important; | |
| } | |
| """ | |
| ) | |
| return demo | |
| def create_basic_agent(tools): | |
| """Crea un agente básico si falla el principal""" | |
| class BasicAgent: | |
| def __init__(self, tools): | |
| self.tools = {tool.__name__: tool for tool in tools if hasattr(tool, '__name__')} | |
| self.tool_functions = {tool.__name__: tool for tool in tools if callable(tool)} | |
| def run(self, message): | |
| return self.process_message(message) | |
| def process_message(self, message): | |
| """Procesa el mensaje y ejecuta las herramientas apropiadas""" | |
| message_lower = message.lower() | |
| try: | |
| if "clima" in message_lower or "tiempo" in message_lower: | |
| # Extraer ciudad del mensaje | |
| palabras = message.split() | |
| ciudad = "Madrid" # Default | |
| for i, palabra in enumerate(palabras): | |
| if palabra.lower() in ["en", "de", "clima", "tiempo"]: | |
| if i + 1 < len(palabras): | |
| ciudad = palabras[i + 1].strip(".,!?") | |
| break | |
| return obtener_clima(ciudad) | |
| elif any(word in message_lower for word in ["calcul", "matemat", "suma", "resta", "multiplica", "divide"]): | |
| # Buscar expresión matemática | |
| import re | |
| # Patrones para encontrar expresiones matemáticas | |
| patterns = [ | |
| r'[\d+\-*/().\s]+', | |
| r'sqrt\(\d+\)', | |
| r'sin\([\d.]+\)', | |
| r'cos\([\d.]+\)', | |
| r'tan\([\d.]+\)' | |
| ] | |
| for pattern in patterns: | |
| expr = re.search(pattern, message) | |
| if expr: | |
| return calculadora_avanzada(expr.group().strip()) | |
| return "Por favor proporciona una expresión matemática válida. Ejemplo: '2+2*3' o 'sqrt(16)'" | |
| elif "convert" in message_lower: | |
| # Buscar patrón de conversión | |
| import re | |
| # Buscar números y unidades | |
| num_match = re.search(r'\d+(?:\.\d+)?', message) | |
| if num_match: | |
| valor = float(num_match.group()) | |
| # Mapear unidades comunes | |
| if "celsius" in message_lower and "fahrenheit" in message_lower: | |
| return convertir_unidades(valor, "celsius", "fahrenheit") | |
| elif "fahrenheit" in message_lower and "celsius" in message_lower: | |
| return convertir_unidades(valor, "fahrenheit", "celsius") | |
| elif "metros" in message_lower and "pies" in message_lower: | |
| return convertir_unidades(valor, "metros", "pies") | |
| elif "kilogramos" in message_lower and "libras" in message_lower: | |
| return convertir_unidades(valor, "kilogramos", "libras") | |
| return "Especifica la conversión. Ejemplo: 'convierte 25 celsius a fahrenheit'" | |
| elif "contraseña" in message_lower or "password" in message_lower: | |
| # Buscar longitud si se especifica | |
| import re | |
| num_match = re.search(r'\d+', message) | |
| longitud = int(num_match.group()) if num_match else 12 | |
| longitud = max(4, min(50, longitud)) # Limitar entre 4 y 50 | |
| incluir_simbolos = "simbolos" not in message_lower or "sin simbolos" not in message_lower | |
| return generar_contrasena(longitud, incluir_simbolos) | |
| elif "hora" in message_lower: | |
| # Buscar zona horaria | |
| zonas_comunes = { | |
| "madrid": "Europe/Madrid", | |
| "barcelona": "Europe/Madrid", | |
| "mexico": "America/Mexico_City", | |
| "nueva york": "America/New_York", | |
| "new york": "America/New_York", | |
| "tokyo": "Asia/Tokyo", | |
| "paris": "Europe/Paris", | |
| "london": "Europe/London", | |
| "londres": "Europe/London" | |
| } | |
| zona = "Europe/Madrid" # Default | |
| for ciudad, tz in zonas_comunes.items(): | |
| if ciudad in message_lower: | |
| zona = tz | |
| break | |
| return obtener_hora_zona_horaria(zona) | |
| elif "buscar" in message_lower or "search" in message_lower: | |
| # Extraer término de búsqueda | |
| palabras_clave = ["buscar", "busca", "search", "información", "sobre"] | |
| termino = message | |
| for palabra in palabras_clave: | |
| if palabra in message_lower: | |
| idx = message_lower.find(palabra) | |
| termino = message[idx + len(palabra):].strip() | |
| break | |
| if termino and len(termino) > 2: | |
| return buscar_informacion(termino) | |
| else: | |
| return "¿Qué tema quieres que busque?" | |
| elif "analizar" in message_lower or "analisis" in message_lower: | |
| # Análisis de texto básico | |
| if "palabras" in message_lower: | |
| # Extraer texto a analizar | |
| texto = message.replace("analizar", "").replace("palabras", "").strip() | |
| return analizar_texto(texto, "contar_palabras") | |
| else: | |
| return "Especifica qué análisis quieres: 'contar palabras', 'contar caracteres', etc." | |
| else: | |
| # Respuesta por defecto con sugerencias | |
| return f"""🤖 ¡Hola! Soy tu asistente personal. | |
| 📨 Tu mensaje: "{message}" | |
| 🛠️ **Herramientas disponibles:** | |
| 🌤️ **Clima**: "¿Qué tiempo hace en Madrid?" | |
| 🧮 **Calculadora**: "Calcula 2+2*3" o "sqrt(25)" | |
| 🔄 **Conversiones**: "Convierte 25 celsius a fahrenheit" | |
| 🔐 **Contraseñas**: "Genera una contraseña de 16 caracteres" | |
| 🕐 **Hora**: "¿Qué hora es en Tokyo?" | |
| 🔍 **Búsquedas**: "Busca información sobre Python" | |
| 📝 **Análisis**: "Analizar palabras en este texto" | |
| 💡 **Ejemplos rápidos:** | |
| • "Clima en Barcelona" | |
| • "Calcular 15*8+sqrt(64)" | |
| • "Hora en Nueva York" | |
| """ | |
| except Exception as e: | |
| return f"❌ Error procesando: {str(e)}" | |
| return BasicAgent(tools) | |
| def process_message_directly(message): | |
| """Procesa mensaje directamente sin agente""" | |
| message_lower = message.lower() | |
| try: | |
| if "clima" in message_lower: | |
| return obtener_clima("Madrid") | |
| elif "calcul" in message_lower: | |
| return calculadora_avanzada("2+2") | |
| elif "contraseña" in message_lower: | |
| return generar_contrasena() | |
| elif "hora" in message_lower: | |
| return obtener_hora_zona_horaria("Europe/Madrid") | |
| else: | |
| return f"🤖 Mensaje recibido: {message}\n\nPuedes pedirme clima, cálculos, contraseñas, hora mundial, etc." | |
| except Exception as e: | |
| return f"Error: {str(e)}" | |
| # Función principal | |
| if __name__ == "__main__": | |
| demo = crear_interfaz() | |
| demo.launch( | |
| server_name="0.0.0.0", | |
| server_port=7860, | |
| share=False | |
| ) |