Tutorial Destacado Acceso Libre 20 Feb, 2026

Tutorial: Integrar OpenAI API en Python paso a paso

Desde tu primera llamada a GPT hasta un sistema completo con streaming, function calling y manejo de errores. Código production-ready.

#openai #gpt #python #api #ia

Contenido

OpenAI API en Python: De cero a producción

Instalación

pip install openai python-dotenv

Llamada básica

from openai import OpenAI
import os

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "Eres un asistente útil."},
        {"role": "user", "content": "Explica qué es una API en una frase."},
    ],
    temperature=0.7,
    max_tokens=150,
)

print(response.choices[0].message.content)

Streaming (respuesta en tiempo real)

stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Cuenta una historia corta"}],
    stream=True,
)

for chunk in stream:
    content = chunk.choices[0].delta.content
    if content:
        print(content, end="", flush=True)

Function Calling (Tool Use)

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Obtiene el clima de una ciudad",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "Nombre de la ciudad"},
            },
            "required": ["city"],
        },
    },
}]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "¿Cómo está el clima en Santo Domingo?"}],
    tools=tools,
)

tool_call = response.choices[0].message.tool_calls[0]
print(f"Función: {tool_call.function.name}")
print(f"Args: {tool_call.function.arguments}")

Manejo de errores para producción

from openai import RateLimitError, APIConnectionError
import time

def call_gpt(messages, retries=3):
    for attempt in range(retries):
        try:
            return client.chat.completions.create(
                model="gpt-4o",
                messages=messages,
            )
        except RateLimitError:
            wait = 2 ** attempt
            time.sleep(wait)
        except APIConnectionError:
            time.sleep(5)
    raise Exception("OpenAI API no disponible después de varios intentos")

Recurso Externo

Este recurso incluye un enlace externo. Regístrate para acceder.

Inicia Sesión para Acceder

Únete a la Comunidad

Regístrate gratis para descargar archivos, guardar recursos en favoritos, ganar XP y acceder a cursos y el foro de la comunidad.

¿Ya tienes cuenta? Inicia sesión

Erik Taveras

Autor

Erik Taveras

Recursos Relacionados