0%
Getting Started with the ChatGPT API: Sending Requests and Handling Responses

Getting Started

Sending requests and handling responses

10-15 min

Getting Started with the ChatGPT API: Sending Requests and Handling Responses

Introduction

In this module, we will explore how to send requests to the ChatGPT API and handle the responses. We will also look at how to customize the model's behavior to meet your specific needs.

Sending Simple Requests

Basic Structure of a Request

A request to the ChatGPT API generally consists of the following elements:

  • model: The model to use (for example, "gpt-3.5-turbo")
  • messages: An array of messages that make up the conversation
  • temperature: A parameter that controls the creativity of the responses (between 0 and 1)
  • max_tokens: The maximum number of tokens to generate

Code Example

Here is an example of code for sending a simple request:

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

dotenv.config();

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

async function sendRequest(message) {
  try {
    const completion = await openai.chat.completions.create({
      model: "gpt-3.5-turbo",
      messages: [
        { role: "system", content: "Vous êtes un assistant utile." },
        { role: "user", content: message }
      ],
      temperature: 0.7,
      max_tokens: 150
    });

    return completion.choices[0].message.content;
  } catch (error) {
    console.error("Erreur lors de l'appel à l'API:", error);
    throw error;
  }
}

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!