1
3

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.

Julia: ChatGPT API の使い方

Posted at

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

プログラム

julia_fuji.sh
export OPENAI_API_KEY="sk-****************'
./julia_fuji.jl
julia_fuji.jl
#! /usr/bin/julia
#
#	julia_fuji.jl
#
#						Apr/11/2023
# --------------------------------------------------------------------
# import Pkg; Pkg.add("HTTP")
# import Pkg; Pkg.add("JSON")
using HTTP
using JSON
# --------------------------------------------------------------------
println(stderr,"*** 開始 ***")

# APIキーを設定
openai_api_key = ENV["OPENAI_API_KEY"]

# ヘッダーを設定
headers = [
    "Content-Type" => "application/json",
    "Authorization" => "Bearer $openai_api_key"
]

# API呼び出しのパラメーターを設定
params = Dict(
    "model" => "gpt-3.5-turbo",
    "messages" => [
        Dict(
            "role" => "user",
            "content" => "富士山の高さは"
        )
    ]
)

# API呼び出しを実行
response = HTTP.post(
    "https://api.openai.com/v1/chat/completions",
    headers,
    JSON.json(params)
)

# レスポンスをJSON形式にパース
json_response = JSON.parse(String(response.body))

# 結果を表示
# println(json_response)
println(json_response["choices"])
data = json_response["choices"]
content = data[1]["message"]["content"]
println(content)

println(stderr,"*** 終了 ***")
# --------------------------------------------------------------------

実行結果

$ ./julia_fuji.sh 
*** 開始 ***
Any[Dict{String, Any}("finish_reason" => "stop", "message" => Dict{String, Any}("role" => "assistant", "content" => "3776メートルです。"), "index" => 0)]
3776メートルです。
*** 終了 ***

確認したバージョン

$ julia --version
julia version 1.8.5
1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?