2
5

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を使う

Posted at

はじめに

最近話題になっているchatGPTについてjuliaから実行する方法をまとめました。
といってもPyCallを使ってpythonの関数を実行するだけなので特段難しいことはありません。

PyCallについて

PyCall.jl
julia> ]
(@v1.8) pkg> add PyCall

これでインストール完了です。
PyCallは非常に便利なライブラリでPythonの大量にあるライブラリをjuliaの中で利用できるようにしてくれます。
いかに利用例を記します

example:PyCall
using PyCall
#組み込み関数の場合
jl_float = py"float"
jl_int = py"int"

println(jl_float(3))
println(jl_int(3.0))

#ライブラリの場合
jl_np = pyimport("numpy")
jl_pd = pyimport("pandas")
sample = jl_np.array([1, 2, 3])
df = jl_pd.DataFrame(sample)

println(sample)
println(df)

実行結果
3.0
3

[1, 2, 3]
PyObject    0
0  1
1  2
2  3

自作の関数を読み込むことも可能です。
今回はここでchatGPT用の応答関数をセットします。

chatgpt
using PyCall

py"""
import openai
def chatgpt(prompt):
    openai.api_key = "<OPENAI_API_KEY>"
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "あなたは優秀な秘書です。日本語で回答してください。"},
            {"role": "user", "content": prompt},
        ],
        temperature=0.7,
    )
    return response["choices"][0]["message"]["content"]
"""
prompt = "please tell me about japan"
response = py"chatgpt"(prompt)
println(response)

実行結果
日本は、アジアの東に位置する島国です。人口は約1億2千万人で、首都は東京です。日本は、四季がはっきりしており、春には桜の花が咲き、秋には紅葉が美しいです。
また、日本は世界的に有名な文化的なアイコンを多く持っています。例えば、富士山、武士、着物、お寺、神社、そして美味しい食べ物などです。また、日本は先進技術の国としても知られており、自動車、電子機器、ロボットなどの分野で世界的に高い評価を受けています。

これでjuliaからchatGPTを利用することができるようになりました。

さいごに

流行りのchatGPTをjuliaから利用する方法もといPyCallの使い方をまとめました。
しかし、Pythonでできることをわざわざjuliaで実行する必要性はほとんどないと思います。
今後なんらかの形で活用できればと思っています。

2
5
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
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?