2024年9月14日土曜日

Ubuntu24環境でChatGPTのAPIを使う

 ChatGPTのAPIを使う一般的なやり方は、この文章で紹介しているが、あくまで一般的な内容であったため、実際自分のUbuntu24環境で試したところ、色んなところ説明不足だと気付いた。

成功したメモとして以下に残す。皆さんに役立つように。

 +

1.OSバージョン

jeff@ubuntu24:~/ChatGPT$ lsb_release -a

No LSB modules are available.

Distributor ID: Ubuntu

Description:    Ubuntu 24.04.1 LTS

Release:        24.04

Codename:       noble

2.Pythonバージョン

jeff@ubuntu24:~/ChatGPT$ python --version

Python 3.12.3

  インストールされてなければ、以下コマンドでインストールして、ソフトリンクを作成

 sudo apt-get install python3

sudo ln -s /usr/bin/python3 /usr/bin/python

3.Pythonのrequests, openaiライブラリ確認

jeff@ubuntu24:~/ChatGPT$ pip list | grep -e requests -e openai

openai                1.12.0

requests              2.31.0

  インストールされてなければ、以下コマンドでインストール

 sudo apt install python3-requests python3-openai

4.ChatGPTのAPIをコールするPythonソースコードを以下通り作成(ファイル名:API_test.py)

import requests

import openai


# OpenAI APIキーを設定

api_key =  'your-api-key-here'  # ここに自分のAPIキーを入力


# APIエンドポイントとヘッダーの設定

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

headers = {

    "Content-Type": "application/json",

    "Authorization": f"Bearer {api_key}"

}


# リクエストデータの設定

data = {

    "model": "gpt-3.5-turbo",  # 使用するモデルを指定

    "messages": [

        {"role": "system", "content": "You are a helpful assistant."},

        {"role": "user", "content": "世界中主要Linux OSを10個教えてください。"}

    ],

    "max_tokens": 150,  # 応答の最大トークン数

    "temperature": 0.7  # 応答のクリエイティビティを調整

}


# APIリクエストの送信

response = requests.post(url, headers=headers, json=data)


# 応答を確認

if response.status_code == 200:

    response_data = response.json()

    reply = response_data['choices'][0]['message']['content']

    print("ChatGPT: ", reply)

else:

    print(f"Error: {response.status_code}")

    print(response.json())

5.実行結果 (実行結果は毎回同じとは限りません。)

jeff@ubuntu24:~/ChatGPT$ python API_test.py

ChatGPT:  世界中で主要なLinux OSのいくつかは以下の通りです:


1. Ubuntu

2. Fedora

3. CentOS

4. Debian

5. Arch Linux

6. openSUSE

7. Manjaro

8. Linux Mint

9. elementary OS

10. Kali Linux

これらは人気があり、広く使用されているLinuxディストリビューションです。

以上です。実行成功しました!!!



0 件のコメント:

コメントを投稿