Como Construir Tu Primer Agente de IA Local (Para Desarrolladores Python)
Objetivo: Construir un script de Python que pueda “leer” tu codigo, encontrar bugs de logica y explicartelos—ejecutandose completamente en tu laptop de forma gratuita.
Fase 1: El “Cerebro” (Configuracion de Ollama)
Antes de escribir codigo, necesitamos instalar la inteligencia.
Concepto: Motor de Inferencia vs. Modelo
El Modelo (Qwen): Piensa en esto como el “Archivo de Musica” (MP3). Son los pesos matematicos congelados que saben como programar.
El Motor de Inferencia (Ollama): Piensa en esto como el “Reproductor de Musica” (Spotify). Carga el archivo masivo en tu RAM y lo reproduce.
Paso 1: Instalar Ollama
Ve a ollama.com.
Haz clic en Download (Mac/Windows/Linux).
Instalalo como una aplicacion normal.
Verifica que funciona: Abre tu terminal (Command Prompt o Terminal) y escribe:
ollama --version
(Si imprime un numero de version, estas listo.)
Paso 2: Obtener una Cuenta de Hugging Face (Opcional pero Recomendado)
Aunque Ollama descarga modelos automaticamente, como Ingeniero de IA, necesitas saber de donde vienen.
Ve a huggingface.co.
Haz clic en Sign Up y crea una cuenta.
Por que? Este es el “GitHub de la IA.” Es donde encuentras nuevos modelos (como Qwen, Llama, Mistral) para probar en el futuro.
Paso 3: Descargar el Modelo
Usaremos Qwen 2.5 Coder con soporte para herramientas. El modelo base qwen2.5-coder no soporta function calling de manera confiable, asi que usaremos una variante de la comunidad que agrega esta capacidad.
- 7B (7 Mil Millones de Parametros): El “Dev Junior.” Rapido, funciona en casi cualquier laptop (8GB RAM).
- 32B (32 Mil Millones de Parametros): El “Dev Senior.” Mas inteligente, pero requiere una laptop potente (32GB+ RAM).
Accion: En tu terminal, ejecuta este comando para descargar la version 7B (el inicio mas seguro):
ollama pull hhao/qwen2.5-coder-tools:7b
(Veras una barra de progreso descargando ~4.7 GB).
Paso 4: Probar el Cerebro
Aseguremonos de que realmente esta pensando. En tu terminal, ejecuta:
ollama run hhao/qwen2.5-coder-tools:7b
Escribe: Write a Python function to reverse a string. Si escribe codigo, tu “Cerebro” esta listo. Escribe /bye para salir.
Fase 2: La Configuracion del Proyecto
Ahora creamos el espacio de trabajo.
Paso 5: Crear la Carpeta del Proyecto
mkdir ai-bug-agent
cd ai-bug-agent
Paso 6: Crear el Entorno Virtual (.venv)
Esto mantiene tus librerias de IA separadas de tu Python del sistema.
python3 -m venv .venv
source .venv/bin/activate
# (En Windows usa: .venv\Scripts\activate)
Paso 7: Instalar Librerias
Solo necesitamos una libreria principal: openai.
Espera, por que OpenAI? Ollama es compatible con la estructura de codigo de OpenAI. Al usar esta libreria estandar, puedes cambiar tu modelo local por GPT-4 o Claude despues cambiando solo una linea de codigo.
pip install openai
Fase 3: Construyendo las “Manos” (Herramientas)
Un modelo de IA es un cerebro en un frasco. No puede ver tus archivos a menos que le demos “Ojos” (Herramientas).
Concepto: Function Calling
Normalmente, los LLMs solo generan texto. Function Calling es cuando el LLM dice: “No quiero hablar todavia. Quiero ejecutar la funcion llamada read_file.” Tu script captura esta solicitud, ejecuta el codigo y devuelve el resultado al LLM.
Paso 8: Crear tools.py
Crea un nuevo archivo llamado tools.py y pega este codigo.
import os
def list_files(directory="."):
"""
Lists all files in the directory so the Agent knows what exists.
"""
file_list = []
# Ignore junk folders to save 'Context Window' (Memory)
ignore = {'.git', '__pycache__', '.env', 'node_modules', '.venv', '.DS_Store'}
for root, dirs, files in os.walk(directory):
# Filter out hidden/ignored directories
dirs[:] = [d for d in dirs if d not in ignore and not d.startswith('.')]
for file in files:
if file.startswith('.'): continue
file_list.append(os.path.join(root, file))
return "\n".join(file_list)
def read_file(filepath):
"""
Reads the content of a specific file.
Includes a safety limit so we don't crash the model with huge files.
"""
if not os.path.exists(filepath):
return f"Error: File '{filepath}' does not exist."
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# Safety: If file is > 20,000 characters, truncate it.
if len(content) > 20000:
return (f"Error: File is too large ({len(content)} chars). "
"Reading huge files consumes your Context Window too fast.")
return content
except Exception as e:
return f"Error reading file: {str(e)}"
Fase 4: Construyendo la “Logica” (El Agente)
Ahora escribimos el cerebro que usa las herramientas.
Concepto: El System Prompt
Esta es la instruccion “Modo Dios.” Le dice a la IA quien es (Persona) y como debe comportarse (Reglas). Es la linea de codigo mas importante que escribiras.
Paso 9: Crear agent.py
Crea un nuevo archivo llamado agent.py y pega este codigo.
import sys
import json
from openai import OpenAI
from tools import list_files, read_file # Import our tools
# --- CONFIGURATION ---
# We point the OpenAI client to our LOCAL Ollama server
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="ollama", # Required dummy key
)
# Use the model we downloaded earlier
MODEL_NAME = "hhao/qwen2.5-coder-tools:7b"
# --- SYSTEM PROMPT ---
# This defines the AI's personality and instructions
SYSTEM_PROMPT = """
You are a Senior QA Analyst. You have read-only access to the file system.
Your goal is to investigate the User's Bug Report by tracing code execution.
PROTOCOL:
1. Call `list_files` to map the territory.
2. Call `read_file` on relevant files.
3. Trace imports and function calls logic.
4. When you find the bug, output the FINAL REPORT.
CONSTRAINT:
- Do NOT guess. You must see the code before you blame it.
- If the bug is a "Logic Error" (e.g. truthiness, incorrect operator), explain WHY.
FINAL OUTPUT FORMAT:
Return the final answer in this exact JSON format (no markdown):
{
"severity": "High/Medium/Low",
"file": "path/to/buggy_file.py",
"cause": "Technical explanation...",
"fix": "Code block of the fix..."
}
"""
def run_agent(user_query):
# This list is the "Context Window" - the chat history
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_query}
]
print(f"🕵️ Agent starting investigation: '{user_query}'")
# --- THE AGENT LOOP ---
# The agent will loop until it decides it's done
while True:
# 1. THINK: Ask the LLM what to do next
response = client.chat.completions.create(
model=MODEL_NAME,
messages=messages,
# We describe our tools to the LLM here
tools=[
{
"type": "function",
"function": {
"name": "list_files",
"description": "List all files in a directory",
"parameters": {"type": "object", "properties": {"directory": {"type": "string"}}}
}
},
{
"type": "function",
"function": {
"name": "read_file",
"description": "Read contents of a file",
"parameters": {
"type": "object",
"properties": {"filepath": {"type": "string"}},
"required": ["filepath"]
}
}
}
]
)
# Get the message from the model
msg = response.choices[0].message
# 2. ACT: Did the model ask to use a tool?
if msg.tool_calls:
# Add the model's "thought" to history so it remembers it asked
messages.append(msg)
for tool_call in msg.tool_calls:
func_name = tool_call.function.name
# Parse arguments (e.g., {"filepath": "main.py"})
args = json.loads(tool_call.function.arguments)
print(f"🤖 Agent is running: {func_name}({args})")
# Execute the actual Python function
if func_name == "list_files":
result = list_files(args.get("directory", "."))
elif func_name == "read_file":
result = read_file(args["filepath"])
else:
result = "Error: Unknown tool"
# 3. OBSERVE: Feed the result back to the model
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": result
})
# 4. FINISH: The model didn't ask for a tool, so it must be done
else:
print("-" * 40)
print("📝 FINAL REPORT:\n")
print(msg.content)
break
if __name__ == "__main__":
# Get the bug report from the command line argument
if len(sys.argv) > 1:
query = sys.argv[1]
else:
query = "Find the bug in the code."
run_agent(query)
Fase 5: La Prueba (Verificar que funciona)
Ahora necesitamos crear una “escena del crimen” para que el detective resuelva.
Paso 10: Crear el Repo con Bug
Crea una nueva carpeta llamada test_repo dentro de tu carpeta del proyecto.
mkdir test_repo
Crea test_repo/main.py (El llamador inocente):
def check_status(user_id):
# Returns a dictionary like {"error": "..."} or {"success": True}
# BUG: In Python, a non-empty dictionary is treated as True!
result = {"error": "Database connection failed"}
if result:
print("✅ Operation Successful!")
else:
print("❌ Operation Failed!")
if __name__ == "__main__":
check_status(1)
Paso 11: Ejecutar el Agente!
Vuelve a tu carpeta raiz y ejecuta este comando:
python agent.py "In test_repo/main.py, the code prints 'Operation Successful' even when there is an error. Tell me why."
Lo que deberias ver (La Magia):
- Pensando: El agente iniciara.
- Accion: Ejecutara
list_files. - Observacion: Ve
test_repo/main.py. - Accion: Ejecuta
read_file('test_repo/main.py'). - Reporte Final: Deberia generar una explicacion JSON diciendo: “El bug es que el diccionario
{'error': ...}evalua aTrueen el if-statement.”
Felicitaciones! Acabas de construir un Agente de IA funcional que se ejecuta localmente en tu maquina. Ahora eres un Ingeniero de IA.