Practical Use of the OpenAI API

Practical Use of the OpenAI API

Introduction

The OpenAI API provides simple, powerful access to the most advanced language models. This tutorial walks you through the steps needed to start using the API in your projects.

Initial Setup

1. Installation

For Python:

pip install openai

For Node.js:

npm install openai

2. Configuring the API Key

Create a .env file at the root of your project:

OPENAI_API_KEY=votre_clé_api_ici

In Python:

import os
from dotenv import load_dotenv
from openai import OpenAI

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

In JavaScript:

import OpenAI from 'openai';
import dotenv from 'dotenv';

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

Basic Usage

1. Simple Text Generation

Python:

def generate_text(prompt):
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "user", "content": prompt}
        ]
    )
    return response.choices[0].message.content

JavaScript:

async function generateText(prompt) {
    const response = await openai.chat.completions.create({
        model: "gpt-3.5-turbo",
        messages: [
            { role: "user", content: prompt }
        ]
    });
    return response.choices[0].message.content;
}