DEV Community

Cover image for En 5 Minutos: Crea una App de Next.js con IA de OpenAI
Marcos Montero
Marcos Montero

Posted on

10 1 1 1 1

En 5 Minutos: Crea una App de Next.js con IA de OpenAI

🚀 Introducción:

Descubre cómo construir una aplicación de inteligencia artificial con Next.js y OpenAI en un abrir y cerrar de ojos. En este artículo, te proporciono un adelanto de la creación de esta app, pero para capturar la magia del desarrollo en tiempo real, te invito a ver el vídeo completo que te guiará a través de cada paso con precisión.

Resumen del Proceso:

Comienza con una cuenta en OpenAI y obtén tus claves API. Configura tu proyecto Next.js y prepárate para instalar las dependencias cruciales: ai y openai. Integra el chat en tu aplicación utilizando el hook useChat, y crea una ruta API que manejará las peticiones POST para interactuar con OpenAI.

🧩 Código Clave: Desvelando la Magia del Desarrollo:

Para la API, tu archivo app/api/chat/route-.ts se verá así:

import { OpenAIStream, StreamingTextResponse } from "ai";
import OpenAI from "openai";

export const runtime = "edge";

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

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

  const res = await openai.chat.completions.create({
    model: "gpt-4-turbo-preview",
    stream: true,
    messages,
  });

  const stream = OpenAIStream(res);

  return new StreamingTextResponse(stream);
}
Enter fullscreen mode Exit fullscreen mode

Y tu componente principal en app/page.tsx incorporará el chat de esta manera:

"use client";
import { useChat } from "ai/react";

export default function Home() {
  const { messages, input, handleInputChange, handleSubmit } = useChat();

  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <h1 className="text-3xl">Fast AI app</h1>

      <form onSubmit={handleSubmit} className="flex flex-col gap-2">
        <label className="flex flex-col gap-2">
          <input
            placeholder="What are your thoughts?"
            value={input}
            onChange={handleInputChange}
            className="bg-black outline text-white p-2 rounded-sm"
          />
        </label>
        <button type="submit" className="bg-white text-black rounded-xl">
          **Ask AI**
        </button>
      </form>
      <ul>
        {messages.map((m, index) => (
          <li key={index} className="p-2 bg-white/05 rounded-xl">
            {m.role === "user" ? "**User:** " : "**AI:** "}
            {m.content}
          </li>
        ))}
      </ul>
    </main>
  );
}
Enter fullscreen mode Exit fullscreen mode

🎬 Conclusión

Con estos fragmentos de código, estás a un paso de dar vida a tu aplicación con IA. Pero para entender cada detalle, desde los estilos hasta la gestión de respuestas, el vídeo tutorial es tu recurso definitivo. Sumérgete en el código y la configuración junto a nosotros y lleva tus habilidades de desarrollo al siguiente nivel. ¡No esperes más y dale play al vídeo ahora!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay