1
0

PythonでOpenAI APIを実行する際の備忘録

Last updated at Posted at 2024-08-16

PythonでOpenAI APIを実行する際の備忘録です
基本的には、PythonでOpenAI APIを実行する方法を参照させて頂き実行すればOK
..と思ったが、openai>=1.0.0ではパッケージの利用方法に差分があるらしく以下のwarningメッセージが出力されてしまった。これに伴い、以下のようにプログラムを更新しました。

warningメッセージ

You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0

You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.

You can run `openai migrate` to automatically upgrade your codebase to use the 1.0.0 interface. 

Alternatively, you can pin your installation to the old version, e.g. `pip install openai==0.28`

A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742

プログラムを更新

openai migrateを実行したら自動でマージしてくれました

chatgpt-api.py
from openai import OpenAI

client = OpenAI(api_key='xxx')

response = client.chat.completions.create(model="gpt-3.5-turbo",
    messages=[
    {'role': 'user', 'content': 'ハローワールド!!'}],
    temperature=0.0)

print(response.choices[0].message.content)

お試し実行その1

$ python chatgpt-api.py
こんにちは! どのようにお手伝いしましょうか?

モデルの指定

プログラムの以下に該当する部分については、

model="gpt-3.5-turbo"

以下を参考に変更可能だと思われる

gpt-4o, gpt-4o-mini, gpt-4-turbo, gpt-4, and gpt-3.5-turbo

料金は以下

おそらく実験をする限りではそこまで高額にはならない。はず。。

parameterの指定

以下を参照すればOK
https://platform.openai.com/docs/api-reference/audio/createTranscription
例えば、temperatureは以下の通り

temperature

number

Optional
Defaults to 0
The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.

0.8のような高い値に設定すると出力がよりランダムになり、0.2のような低い値に設定すると出力がより焦点を絞り、決定的になります。0に設定すると、モデルはログ確率を使用して、特定のしきい値に達するまで自動的に温度を上げます。

お試し実行その2

ハローワールドだけでは味気がないので、試しに以下のようなマークダウンにチェックを促すようなリクエストをしてみました

response = client.chat.completions.create(model="gpt-4o",
    messages=[
    {
        'role': 'user', 
        'content': 'こんにちは、あなたはとある地域の住人です。 \
        あなたの住んでいるエリアでは回覧板を通じて情報共有しています。\
        回覧板が渡された際、次の人に渡すまでに該当欄にチェックが必要です。\
        以下のマークダウンで記述される表のうち、住人1の欄にチェックを意味する印をつけて回答して下さい。\
        | 確認者 | チェック | \
        | ---- | ---- | \
        | 住人1 |  | \
        | 住人2 |  | \
        | 住人3 |  | '
     }],
    temperature=0.0)

回答
ちゃんと住人1の欄にチェックをつけてくれました

こんにちは、以下の表に住人1の欄にチェックをつけました。

markdown
| 確認者 | チェック |
| ---- | ---- |
| 住人1 | ✔️ |
| 住人2 |  |
| 住人3 |  |

参考

1
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
1
0