LoginSignup
0
1

More than 1 year has passed since last update.

Node.js: ChatGPT API の使い方 (axios)

Last updated at Posted at 2023-04-11

こちらのプログラムを Node.js の axios モジュールを使って書きました。
Curl: ChatGPT API の使い方

プログラム

axios_fuji.sh
export OPENAI_API_KEY="sk-****************'
./axios_fuji.mjs
axios_fuji.mjs
#! /usr/bin/node
// ---------------------------------------------------------------
//	axios_fuji.mjs
//
//					Apr/11/2023
//
// ---------------------------------------------------------------
console.error ("*** 開始 ***")
import axios from 'axios'

const config = {
	headers: {
		'Content-Type': 'application/json',
		'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
	}
}

const data = {
	"model": "gpt-3.5-turbo",
	"messages": [{"role": "user", "content": "富士山の高さは"}]
}

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

axios.post(url, data, config)
	.then(response => {
//		console.log(response.data)
		console.log(response.data.choices[0].message)
		console.error ("*** 終了 ***")
	})
	.catch(error => {
		console.error(error)
	})

// ---------------------------------------------------------------

実行結果

$ ./axios_fuji.sh
*** 開始 ***
{ role: 'assistant', content: '3,776.24メートルです。' }
*** 終了 ***
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1