informatica:inteligencia_artificial:agentes
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| informatica:inteligencia_artificial:agentes [2025/10/15 10:46] – jose | informatica:inteligencia_artificial:agentes [2025/12/05 07:59] (current) – jose | ||
|---|---|---|---|
| Line 6: | Line 6: | ||
| ====== ollama ====== | ====== ollama ====== | ||
| DIR_OLLAMA=/ | DIR_OLLAMA=/ | ||
| - | docker run --name ollama -v $DIR_OLLAMA/ | + | docker run --name ollama |
| + | |||
| + | MAC ponemos mas memoria al docker: | ||
| + | docker run -d --name ollama -p 11434:11434 --memory=" | ||
| apt-get install -y curl python3-venv | apt-get install -y curl python3-venv | ||
| Instalamos ollama. Lo instala en / | Instalamos ollama. Lo instala en / | ||
| curl -fsSL https:// | curl -fsSL https:// | ||
| + | |||
| + | python3 -m venv / | ||
| + | source / | ||
| + | |||
| Arrancamos ollama: | Arrancamos ollama: | ||
| ollama serve | ollama serve | ||
| Line 17: | Line 25: | ||
| ollama pull llama3.1: | ollama pull llama3.1: | ||
| ollama pull llama3.1:8b | ollama pull llama3.1:8b | ||
| + | ollama pull codellama: | ||
| + | ollama pull qwen2.5-coder: | ||
| + | ollama pull deepseek-coder-v2: | ||
| + | | ||
| + | Para ver los que tenemos: | ||
| + | ollama list | ||
| + | |||
| + | NAME | ||
| + | llama3.1: | ||
| + | codellama: | ||
| - | python3 -m venv / | ||
| - | source / | ||
| Para ejecutar un modelo concreto: | Para ejecutar un modelo concreto: | ||
| ollama run llama3.1:8b | ollama run llama3.1:8b | ||
| - | Instalamos las tools: | + | Esto es solo LLM, si le preguntamos por algo que tenga que interactuar nos dice: |
| - | | + | |
| - | 1. Código para usar el agente: | ||
| - | |||
| - | Configuración Inicial y Modelo | ||
| - | Asegúrate de que Ollama esté ejecutándose (ollama serve) y luego define el modelo que usarás. | ||
| < | < | ||
| - | from langchain_community.chat_models import ChatOllama | + | Lo siento, pero no tengo acceso a información de tiempo real o actualizada sobre el clima. Sin embargo, puedo |
| - | from langchain_core.prompts import ChatPromptTemplate | + | sugerirte algunas formas de obtener la información |
| - | from langchain_core.output_parsers import StrOutputParser | + | |
| - | + | ||
| - | # 1. Definir el modelo | + | |
| - | MODELO_OLLAMA = " | + | |
| - | + | ||
| - | # 2. Inicializar el LLM | + | |
| - | # Esto crea una conexión con tu modelo local de Ollama | + | |
| - | llm = ChatOllama(model=MODELO_OLLAMA) | + | |
| </ | </ | ||
| - | 2. Definición de la Herramienta (Tool) | + | Ojo porque si le preguntamos lo mismo a codellama: |
| + | ollama run codellama: | ||
| - | En este paso, defines qué acciones puede tomar tu agente. Para que el modelo pueda ejecutar comandos en la terminal (como pediste antes), adaptaremos la función en el formato de LangChain. | ||
| < | < | ||
| - | from langchain_core.tools import tool | + | I can provide you with information about the weather in Madrid, but I cannot predict the future. However, I can |
| - | import subprocess | + | tell you the current weather conditions and forecast for Madrid. |
| - | # Usamos el decorador @tool de LangChain para convertir la función Python | + | According to data from AEMET (the Spanish National Meteorological Agency), the current weather conditions in |
| - | # en una herramienta que el LLM puede entender. | + | Madrid are: |
| - | @tool | + | * Temperature: 15°C (59°F) |
| - | def ejecutar_comando_terminal(comando: str) -> str: | + | * Humidity: 60% |
| - | """ | + | * Wind: 2 km/h (1.2 mph) |
| - | Ejecuta un comando en la terminal | + | * Clouds: Scattered clouds |
| - | Usa esta herramienta para probar código o scripts como Playwright. | + | |
| - | """ | + | |
| - | try: | + | |
| - | | + | |
| - | comando, | + | |
| - | shell=True, | + | |
| - | capture_output=True, | + | |
| - | text=True, | + | |
| - | timeout=30 | + | |
| - | ) | + | |
| - | + | ||
| - | if resultado.returncode == 0: | + | |
| - | return f" | + | |
| - | else: | + | |
| - | # Devuelve el error al LLM para que pueda intentar depurarlo | + | |
| - | return f" | + | |
| - | except Exception as e: | + | As for the forecast, AEMET predicts that the weather will be mostly sunny with a high of 22°C (72°F) and a low of |
| - | | + | 9°C (48°F) on Monday. There is a chance of scattered thunderstorms in the afternoon. |
| - | + | ||
| - | # Lista de herramientas disponibles para el agente | + | |
| - | tools = [ejecutar_comando_terminal] | + | |
| + | Please note that this information may not reflect the actual weather conditions in Madrid, as weather can change | ||
| + | rapidly and it's always best to check with local authorities or a reliable weather source for the most up-to-date | ||
| + | information. | ||
| </ | </ | ||
| - | + | Esto es porque | |
| - | 3. Unir y Ejecutar el Agente (El Bucle de Tools Calling) | + | >>> |
| - | + | ||
| - | Aquí es donde se produce la magia. LangChain usa el método .bind_tools() | + | |
| < | < | ||
| - | # 1. Unir el LLM con las herramientas | + | No puedo proporcionarte la temperatura exacta en Madrid AHORA MISMO. La información meteorológica actual se basa |
| - | # LangChain usa las descripciones | + | en los datos de las estaciones meteorológicas, |
| - | # que Ollama necesita. | + | haber un delay entre el momento |
| - | llm_with_tools = llm.bind_tools(tools) | + | |
| - | + | ||
| - | # 2. Definir | + | |
| - | user_question = " | + | |
| - | + | ||
| - | # 3. Primer paso: El modelo decide si usa la herramienta | + | |
| - | print(" | + | |
| - | response = llm_with_tools.invoke(user_question) | + | |
| - | + | ||
| - | # 4. Comprobar si hay llamadas a herramientas | + | |
| - | if response.tool_calls: | + | |
| - | print(f" | + | |
| - | + | ||
| - | # 5. Ejecutar la herramienta (Manualmente para este ejemplo, pero LangChain tiene wrappers de Agente | + | |
| - | + | ||
| - | # Extraer los argumentos que el LLM generó | + | |
| - | tool_call = response.tool_calls[0] | + | |
| - | func_name = tool_call[' | + | |
| - | func_args = tool_call[' | + | |
| - | + | ||
| - | # Ejecutar la función real usando los argumentos | + | |
| - | tool_output = ejecutar_comando_terminal(**func_args) | + | |
| - | + | ||
| - | print(f" | + | |
| - | print(f" | + | |
| - | # 6. Segundo paso: Enviar el resultado | + | Sin embargo, puedo proporcionarte una predicción |
| - | print(" | + | meteorológicas actuales y previstas. Por ejemplo, si la temperatura en Madrid |
| - | + | predecirse | |
| - | # Para la respuesta final, | + | por la noche. |
| - | # la respuesta del LLM y el resultado | + | |
| - | + | ||
| - | messages = [ | + | |
| - | (" | + | |
| - | | + | |
| - | (" | + | |
| - | ] | + | |
| - | + | ||
| - | # Llamar al modelo | + | |
| - | final_response = llm.invoke(messages) | + | |
| - | + | ||
| - | print(" | + | |
| - | print(final_response.content) | + | |
| - | else: | + | Por favor, tenga en cuenta que estas son solo predicciones y que la temperatura real puede variar según las |
| - | # Si no hay Tool Call, el modelo responde directamente | + | condiciones meteorológicas específicas y locales. |
| - | | + | |
| </ | </ | ||
| - | Todo el script junto | + | ====== Tools ====== |
| - | < | + | Para que el LLM tenga acceso a herramientas dinámicas, por ejemplo consulta del tiempo mañana. |
| - | import subprocess | + | pip install ollama |
| - | from langchain_community.chat_models import ChatOllama | + | |
| - | from langchain_core.tools import tool | + | |
| - | # --- PARTE 1: Configuración Inicial y Modelo --- | ||
| - | # Asegúrate de que Ollama esté ejecutándose (ollama serve) | ||
| - | MODELO_OLLAMA = " | ||
| - | llm = ChatOllama(model=MODELO_OLLAMA) | ||
| - | # ---------------------------------------------------------------------- | ||
| - | # --- PARTE 2: Definición de la Herramienta (Tool) --- | ||
| - | @tool | ||
| - | def ejecutar_comando_terminal(comando: | ||
| - | """ | ||
| - | Ejecuta un comando en la terminal (shell) del sistema operativo. | ||
| - | Usa esta herramienta para probar código o scripts como Playwright. | ||
| - | """ | ||
| - | print(f" | ||
| - | try: | ||
| - | # Usa subprocess para ejecutar el comando | ||
| - | resultado = subprocess.run( | ||
| - | comando, | ||
| - | shell=True, | ||
| - | capture_output=True, | ||
| - | text=True, | ||
| - | timeout=30 # Límite de tiempo de 30 segundos | ||
| - | ) | ||
| - | | ||
| - | if resultado.returncode == 0: | ||
| - | return f" | ||
| - | else: | ||
| - | # Devuelve el error para que el LLM lo analice | ||
| - | return f" | ||
| - | |||
| - | except Exception as e: | ||
| - | return f" | ||
| - | |||
| - | # Lista de herramientas disponibles para el agente | ||
| - | tools = [ejecutar_comando_terminal] | ||
| - | |||
| - | # ---------------------------------------------------------------------- | ||
| - | # --- PARTE 3: Unir y Ejecutar la Lógica del Agente --- | ||
| - | |||
| - | # 1. Unir el LLM con las herramientas | ||
| - | # Esto crea una " | ||
| - | llm_with_tools = llm.bind_tools(tools) | ||
| - | |||
| - | # 2. Definir la pregunta para el agente | ||
| - | # **NOTA IMPORTANTE: | ||
| - | # o un entorno Playwright configurado que responda a este comando. | ||
| - | user_question = ( | ||
| - | " | ||
| - | " | ||
| - | " | ||
| - | ) | ||
| - | |||
| - | print(f" | ||
| - | |||
| - | # 3. Primer Paso: El modelo decide si usa la herramienta | ||
| - | response = llm_with_tools.invoke(user_question) | ||
| - | |||
| - | if response.tool_calls: | ||
| - | | ||
| - | # 4. El Agente ejecuta la Herramienta | ||
| - | tool_call = response.tool_calls[0] | ||
| - | func_args = tool_call[' | ||
| - | tool_output = ejecutar_comando_terminal(**func_args) | ||
| - | | ||
| - | # 5. Segundo Paso: Enviar el resultado de vuelta al modelo para la respuesta final | ||
| - | | ||
| - | # Prepara el historial completo, incluyendo el resultado de la herramienta | ||
| - | messages = [ | ||
| - | (" | ||
| - | response, # La respuesta del LLM con la Tool Call | ||
| - | (" | ||
| - | ] | ||
| - | | ||
| - | # Llama al modelo por segunda vez para que genere la respuesta final | ||
| - | final_response = llm.invoke(messages) | ||
| - | | ||
| - | print(" | ||
| - | print(" | ||
| - | print(final_response.content) | ||
| - | print("#####################################################" | ||
| - | |||
| - | else: | ||
| - | # Si no hay Tool Call, el modelo responde directamente (no debería pasar en este caso) | ||
| - | print(f" | ||
| - | | ||
| - | </ | ||
informatica/inteligencia_artificial/agentes.1760525179.txt.gz · Last modified: by jose
