Introduccion a OpenAI API - Integracion de ChatGPT

Intermedio | 45 min de lectura | 2025.12.19

Lo que aprenderas en este tutorial

✓ Obtencion de API Key
✓ Chat Completions API
✓ Streaming
✓ Function Calling
✓ Manejo de errores

Step 1: Configuracion

npm install openai
// lib/openai.ts
import OpenAI from 'openai';

export const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

Step 2: Chat basico

// app/api/chat/route.ts
import { openai } from '@/lib/openai';
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  const { message } = await request.json();

  const completion = await openai.chat.completions.create({
    model: 'gpt-4o',
    messages: [
      { role: 'system', content: 'You are a helpful assistant.' },
      { role: 'user', content: message },
    ],
    max_tokens: 1000,
  });

  return NextResponse.json({
    reply: completion.choices[0].message.content,
  });
}

Step 3: Streaming

// app/api/chat/stream/route.ts
import { openai } from '@/lib/openai';

export async function POST(request: Request) {
  const { message } = await request.json();

  const stream = await openai.chat.completions.create({
    model: 'gpt-4o',
    messages: [{ role: 'user', content: message }],
    stream: true,
  });

  const encoder = new TextEncoder();

  return new Response(
    new ReadableStream({
      async start(controller) {
        for await (const chunk of stream) {
          const content = chunk.choices[0]?.delta?.content || '';
          controller.enqueue(encoder.encode(content));
        }
        controller.close();
      },
    }),
    { headers: { 'Content-Type': 'text/plain' } }
  );
}

Step 4: Cliente (Streaming)

'use client';
import { useState } from 'react';

export function Chat() {
  const [input, setInput] = useState('');
  const [response, setResponse] = useState('');

  const handleSubmit = async () => {
    setResponse('');

    const res = await fetch('/api/chat/stream', {
      method: 'POST',
      body: JSON.stringify({ message: input }),
    });

    const reader = res.body?.getReader();
    const decoder = new TextDecoder();

    while (true) {
      const { done, value } = await reader!.read();
      if (done) break;
      setResponse((prev) => prev + decoder.decode(value));
    }
  };

  return (
    <div>
      <input value={input} onChange={(e) => setInput(e.target.value)} />
      <button onClick={handleSubmit}>Enviar</button>
      <p>{response}</p>
    </div>
  );
}

Step 5: Function Calling

const tools = [
  {
    type: 'function' as const,
    function: {
      name: 'get_weather',
      description: 'Get the current weather in a location',
      parameters: {
        type: 'object',
        properties: {
          location: { type: 'string', description: 'City name' },
        },
        required: ['location'],
      },
    },
  },
];

const completion = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'Como esta el clima en Tokyo?' }],
  tools,
});

const toolCall = completion.choices[0].message.tool_calls?.[0];
if (toolCall?.function.name === 'get_weather') {
  const args = JSON.parse(toolCall.function.arguments);
  const weather = await getWeather(args.location);
  // Devolver resultado
}

Step 6: Generacion de imagenes

const image = await openai.images.generate({
  model: 'dall-e-3',
  prompt: 'A cute cat in a space suit',
  n: 1,
  size: '1024x1024',
});

console.log(image.data[0].url);

Step 7: Manejo de errores

import OpenAI from 'openai';

try {
  const completion = await openai.chat.completions.create({...});
} catch (error) {
  if (error instanceof OpenAI.APIError) {
    console.log(error.status);  // 429, 500, etc.
    console.log(error.message);
  }
}

Resumen

OpenAI API te permite integrar ChatGPT en tu aplicacion. Mejora la UX con streaming y extiende la funcionalidad con Function Calling.

← Volver a la lista