Inteligencia Artificial

Cómo Construir tu Primer Agente de IA con LangChain en 5 Pasos

Tutorial paso a paso para construir un agente de IA funcional usando LangChain y Python. Desde setup hasta implementación de herramientas.

Equipo Nexgen
4 min de lectura
#LangChain#AI Agents#Python#LLM#Tutorial
Cómo Construir tu Primer Agente de IA con LangChain en 5 Pasos

Cómo Construir tu Primer Agente de IA con LangChain

Respuesta Directa

Un agente de IA con LangChain se construye en 5 pasos: (1) Setup de entorno, (2) Inicializar LLM, (3) Definir herramientas, (4) Crear el agente, (5) Ejecutar y probar. Todo el proceso toma ~30 minutos para un agente básico funcional.

Requisitos Previos

# Python 3.9+
pip install langchain openai python-dotenv

Variables de entorno:

OPENAI_API_KEY=tu-api-key-aqui

Paso 1: Setup del Entorno

# agent.py
from langchain.llms import OpenAI
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
import os
from dotenv import load_dotenv

load_dotenv()

# Verifica que la API key esté configurada
if not os.getenv("OPENAI_API_KEY"):
    raise ValueError("OPENAI_API_KEY no configurada")

Paso 2: Inicializar el LLM

# Inicializa el modelo
llm = OpenAI(
    temperature=0.7,  # Creatividad (0-1)
    model_name="gpt-3.5-turbo",
    max_tokens=500
)

# Prueba rápida
response = llm("¿Qué es un agente de IA?")
print(response)

Paso 3: Definir Herramientas (Tools)

Las herramientas son funciones que el agente puede usar:

def buscar_informacion(query: str) -> str:
    """Simula búsqueda de información"""
    # En producción, aquí llamarías a una API real
    resultados = {
        "clima": "El clima hoy es soleado, 25°C",
        "noticias": "Últimas noticias tech: IA avanza rápidamente"
    }
    return resultados.get(query.lower(), "No encontré información")

def calculadora(expression: str) -> str:
    """Evalúa expresiones matemáticas simples"""
    try:
        result = eval(expression)
        return f"El resultado es: {result}"
    except:
        return "Error: expresión inválida"

# Definir herramientas para el agente
tools = [
    Tool(
        name="Búsqueda",
        func=buscar_informacion,
        description="Útil para buscar información actual sobre clima o noticias"
    ),
    Tool(
        name="Calculadora",
        func=calculadora,
        description="Útil para operaciones matemáticas. Input debe ser una expresión válida"
    )
]

Paso 4: Crear el Agente

# Inicializar agente con las herramientas
agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True,  # Para ver el razonamiento
    max_iterations=3
)

Paso 5: Ejecutar y Probar

# Prueba 1: Usar herramienta de búsqueda
print("\n--- Prueba 1: Búsqueda ---")
response1 = agent.run("¿Cómo está el clima hoy?")
print(f"Respuesta: {response1}")

# Prueba 2: Usar calculadora
print("\n--- Prueba 2: Cálculo ---")
response2 = agent.run("¿Cuánto es 15 * 23?")
print(f"Respuesta: {response2}")

# Prueba 3: Razonamiento complejo
print("\n--- Prueba 3: Multi-step ---")
response3 = agent.run(
    "¿Cuál es el clima y cuánto es 100 dividido por 4?"
)
print(f"Respuesta: {response3}")

Output Esperado

--- Prueba 1: Búsqueda ---
> Entering new AgentExecutor chain...
I need to find current weather information
Action: Búsqueda
Action Input: clima
Observation: El clima hoy es soleado, 25°C
Thought: I now know the weather
Final Answer: El clima hoy está soleado con 25°C

--- Prueba 2: Cálculo ---
> Entering new AgentExecutor chain...
I need to multiply these numbers
Action: Calculadora
Action Input: 15 * 23
Observation: El resultado es: 345
Final Answer: 15 multiplicado por 23 es 345

Mejoras Avanzadas

1. Agregar Memoria

from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory(memory_key="chat_history")

agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
    memory=memory,
    verbose=True
)

2. Herramientas Reales

from langchain.tools import DuckDuckGoSearchRun

search = DuckDuckGoSearchRun()

tools.append(
    Tool(
        name="Web Search",
        func=search.run,
        description="Búsqueda en internet en tiempo real"
    )
)

3. Custom Tools con APIs

import requests

def get_weather(city: str) -> str:
    """Obtiene clima real desde API"""
    api_key = os.getenv("WEATHER_API_KEY")
    url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"

    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        temp = data["main"]["temp"] - 273.15  # Kelvin a Celsius
        description = data["weather"][0]["description"]
        return f"En {city}: {temp:.1f}°C, {description}"
    return "Error obteniendo clima"

Errores Comunes y Soluciones

Error: "Could not parse LLM output"

Causa: El LLM no siguió el formato esperado.

Solución: Ajusta temperature a un valor más bajo (ej: 0.3) y limita max_iterations.

Error: "Rate limit exceeded"

Causa: Demasiadas llamadas a la API.

Solución: Implementa retry con backoff exponencial:

from langchain.llms import OpenAI
from langchain.callbacks import get_openai_callback

llm = OpenAI(
    temperature=0.3,
    request_timeout=30,
    max_retries=3
)

Próximos Pasos

  1. Agregar más herramientas: Email, base de datos, APIs propias
  2. Implementar RAG: Combina con vectorstore para knowledge base
  3. Multi-agent systems: Varios agentes colaborando
  4. Deploy en producción: FastAPI + Docker

Recursos Adicionales

¿Necesitas ayuda construyendo agentes de IA para tu empresa? Contáctanos para una consulta gratuita.