LoginSignup
0
0

More than 1 year has passed since last update.

Deno: ChatGPT API の使い方 (ky)

Last updated at Posted at 2023-04-13

こちらのプログラムを Deno で ky を使って書きました。
Curl: ChatGPT API の使い方

プログラム

deno_ky.sh
export OPENAI_API_KEY="sk-****************'
deno run --allow-net --allow-env deno_ky.ts
deno_ky.ts
// ---------------------------------------------------------------
//	deno_ky.ts
//
//					Apr/13/2023
//
// ---------------------------------------------------------------
import process from "node:process"
import ky from "https://cdn.skypack.dev/ky"

console.error ("*** 開始 ***")

const OPENAI_API_KEY = Deno.env.get("OPENAI_API_KEY")

const headers = {
	"Content-Type": "application/json",
	Authorization: `Bearer ${OPENAI_API_KEY}`,
}

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

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

const time_out = 2000

console.error ("\ttime_out = " + String(time_out))

try {
const response = await ky.post(url, { headers, json: data, timeout: time_out },)
const result = await response.json()
console.log(result.choices[0].message)
} catch (err) {
	console.error("*** error *** aaa ***")
	console.error(err.name + ': ' + err.message)
	console.error("*** error *** ccc ***")
	process.exit(-1)
}

console.error ("*** 終了 ***")
// ---------------------------------------------------------------

実行結果

タイムアウトを起こす場合

$ ./deno_ky.sh 
*** 開始 ***
	time_out = 2000
*** error *** aaa ***
TimeoutError: Request timed out
*** error *** ccc ***

タイムアウトを起こさない場合

$ ./deno_ky.sh 
*** 開始 ***
	time_out = 2000
{ role: "assistant", content: "3,776メートルです。" }
*** 終了 ***

次の値を大きくすれば、タイムアウトを起こさなくなります。

const time_out = 2000

参考情報

ky

timeout
Type: number | false
Default: 10000

Timeout in milliseconds for getting a response, including any retries. Can not be greater than 2147483647. If set to false, there will be no timeout.
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