Saltar al contenido
IntermedioTiempo de lectura 20 min·

Build Your First AI App with the OpenAI API

Now that you understand the fundamentals, it is time to write some code. Using Node.js as an example, this tutorial walks you through sending your first chat request with the OpenAI API and introduces production details such as streaming output, cost, and error handling.

PorAI Resource Hub

Prerequisites

First, register on the OpenAI platform and create an API key, then store it in an environment variable. Never hard-code it into your code or commit it to a repository.

export OPENAI_API_KEY="sk-..."

Install the SDK

The official Node.js SDK is the fastest way to get started:

npm install openai

Send Your First Chat Request

The code below sends a message to gpt-4o-mini and prints the reply. The messages array carries the conversation history, and role can be system, user, or assistant.

import OpenAI from 'openai';

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

const res = await client.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [
    { role: 'system', content: 'You are a helpful assistant.' },
    { role: 'user', content: 'Describe large language models in one sentence.' },
  ],
});

console.log(res.choices[0].message.content);

Use Streaming Output

Chat applications usually want a "print as you type" effect. Enabling stream lets you receive output as it is generated, greatly improving the experience.

const stream = await client.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [{ role: 'user', content: 'Write a short poem about spring' }],
  stream: true,
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
}

Cost and Error Handling

The API is billed by token, so be sure to set a reasonable max_tokens and monitor usage; choosing a smaller model (such as the mini series) can dramatically reduce costs.

Network requests may time out or be rate-limited, so production environments should add retries, timeouts, and exception handling, along with validation and content moderation for user input.

OpenAIAPIApp DevelopmentNode.js

Tutoriales relacionados