Getting Started

OpenAI API Introduction

Get started with the OpenAI API to integrate GPT-4, DALL-E, and other models into your apps.

What is the OpenAI API?

The OpenAI API gives you programmatic access to OpenAI's powerful AI models:

  • GPT-4o, GPT-4, GPT-3.5: Text generation and reasoning
  • DALL-E 3: Image generation
  • Whisper: Speech-to-text
  • TTS: Text-to-speech
  • Embeddings: Convert text to vector representations

Getting Started

  1. Create an account at platform.openai.com
  2. Generate an API key
  3. Install the SDK: npm install openai
  4. Set your API key as an environment variable: OPENAI_API_KEY

Pricing

OpenAI uses a pay-per-use model based on tokens:

  • 1 token ≈ 4 characters of English text
  • Pricing varies by model (GPT-3.5 is cheapest, GPT-4 is more powerful)
  • Monitor usage in the OpenAI dashboard

Example

javascript
import OpenAI from 'openai';

// Initialize the client (reads OPENAI_API_KEY from environment)
const openai = new OpenAI();

// Basic completion
async function generateText() {
  const completion = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      { role: "user", content: "What is the capital of France?" }
    ],
    max_tokens: 100,
  });

  console.log(completion.choices[0].message.content);
  console.log('Tokens used:', completion.usage?.total_tokens);
}

generateText();

// Python equivalent:
// from openai import OpenAI
// client = OpenAI()
// completion = client.chat.completions.create(
//   model="gpt-4o-mini",
//   messages=[{"role": "user", "content": "Hello!"}]
// )
// print(completion.choices[0].message.content)
Try it yourself — JAVASCRIPT