WmZilla - Webmaster and Marketplace

The Next Generation Webmaster and Trade Forum

JavaScript Code to Connect to ChatGPT API

zukule

New member

0

0%

Status

Offline

Posts

3

Likes

0

Rep

0

Bits

33

4

Months of Service

0%

Explanation:​

  1. Class Initialization: The GptApi class is created with a constructor to initialize the API key.
  2. Get Response: The getResponse method calls the private method chatWithGpt to get the response from the API.
  3. Chat with GPT: The chatWithGpt method sends a POST request to the ChatGPT API with the prompt and necessary headers using the Fetch API. It handles the response and errors gracefully.
  4. Error Handling: The code checks for fetch errors and API errors, providing appropriate messages.

How to Use:​

  1. Replace 'Enter your OpenAI API key here' with your actual OpenAI API key.
  2. Replace 'Enter your prompt here' with your actual prompt.
  3. Run the script in a Node.js environment or in the browser to get the response from ChatGPT.
Feel free to ask any questions or provide feedback. Happy coding!




JavaScript:
class GptApi {
    constructor(apiKey) {
        this.apiKey = apiKey;
        this.model = 'gpt-3.5-turbo';
    }

    async getResponse(prompt) {
        const response = await this.chatWithGpt(prompt);
        return response;
    }

    async chatWithGpt(prompt) {
        const data = {
            model: this.model,
            messages: [
                { role: 'user', content: prompt }
            ],
            max_tokens: 150, // You can optimize this value
            temperature: 0.7,
            top_p: 1,
            n: 1,
            stop: null
        };

        const headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + this.apiKey
        };

        const url = 'https://api.openai.com/v1/chat/completions';

        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: headers,
                body: JSON.stringify(data)
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(`API error: ${errorData.error.message}`);
            }

            const responseData = await response.json();
            return responseData.choices[0].message.content || 'No response';

        } catch (error) {
            return `Fetch error: ${error.message}`;
        }
    }
}

// Enter your API key here
const apiKey = 'Enter your OpenAI API key here';
const prompt = 'Enter your prompt here';

const gptApi = new GptApi(apiKey);
gptApi.getResponse(prompt).then(response => {
    console.log(response);
});
 

249

6,622

6,642

Top