0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Node.js: ChatGPT API の使い方 (node-fetch)

Posted at

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

プログラム

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

import fetch from 'node-fetch'

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

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

fetch(url, {
	method: 'POST',
	headers: {
	  'Content-Type': 'application/json',
	  'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
	},
	body: JSON.stringify(requestBody)
})
.then(res => res.json())
.then(data => {
//	console.log(data)
	console.log(data.choices[0].message)
	console.error ("*** 終了 ***")
	})
.catch(err => console.error(err))


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

実行結果

$ ./fetch_fuji.sh 
*** 開始 ***
{ role: 'assistant', content: '富士山の高さは3776メートルで、日本最高峰です。' }
*** 終了 ***
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?