chtGPT javascript openAI API 사용법

JavaScript에서 chatGPT API를 사용하려면 Axios나 내장 함수인 fetch를 사용하는 것과 같은 HTTP 라이브러리가 필요합니다.

Axios 라이브러리를 사용한 chatGPT API 예제

const axios = require('axios'); // Replace YOUR_API_KEY with your actual API key const apiKey = 'YOUR_API_KEY'; // Set the model engine to use (in this case, chatGPT) const modelEngine = 'text-davinci-002'; // Set the prompt (the input to the model) const prompt = 'Hello, how are you today?'; // Set the maximum number of tokens (words) to generate in the response const maxTokens = 1024; // Set the temperature parameter (controls the randomness of the response) const temperature = 0.5; async function generateResponse() { try { // Make a POST request to the completions API const response = await axios.post( 'https://api.openai.com/v1/completions', { model: modelEngine, prompt, max_tokens: maxTokens, temperature, }, { headers: { Authorization: `Bearer ${apiKey}`, }, } ); // Print the response console.log(response.data.choices[0].text); } catch (error) { console.error(error); } } generateResponse();


다음은 fetch 기능과 함께 chatGPT API를 사용하는 예입니다.

// Replace YOUR_API_KEY with your actual API key const apiKey = 'YOUR_API_KEY'; // Set the model engine to use (in this case, chatGPT) const modelEngine = 'text-davinci-002'; // Set the prompt (the input to the model) const prompt = 'Hello, how are you today?'; // Set the maximum number of tokens (words) to generate in the response const maxTokens = 1024; // Set the temperature parameter (controls the randomness of the response) const temperature = 0.5; async function generateResponse() { try { // Make a POST request to the completions API const response = await fetch('https://api.openai.com/v1/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}`, }, body: JSON.stringify({ model: modelEngine, prompt, max_tokens: maxTokens, temperature, }), }); // Get the response data as a JSON object const responseJson = await response.json(); // Print the response console.log(responseJson.choices[0].text); } catch (error) { console.error(error); } } generateResponse();







0 댓글