1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonからのChatgpt APIへのリクエストを改善する

Last updated at Posted at 2025-02-03

はじめに

皆様お疲れ様です!
TechoesインフラチームのTです。
今回は以前公開したChatgpt APIを利用してCFNテンプレートを生成する記事で使用したPythonコードを久しぶりに実行したところエラーを吐いていたので解消と解決方法の共有ができればと思います。
よろしければ以前の記事にも目を通していただけてたらと思います。

実行環境

  • Windows: 11 Home 24H2
  • Python: 3.13.1
  • モデル: gpt-4o
  • openai: 1.60.1

現状

まず、現状を把握するために現在のコードと実際に吐いているエラーを見てみましょう。

現在のコード

test.py
from openai import OpenAI

client = OpenAI(
    api_key="xxxxx",
)
chat_completion = client.chat.completions.create(
    messages=[
        {
            "role": "user",
            "content": "Hello!",
        }
    ],
    model="gpt-4o",
)

print(chat_completion.choices[0].message.content)
print(chat_completion.usage.completion_tokens)
print(chat_completion.usage.prompt_tokens)
print(chat_completion.usage.total_tokens)

エラー文

Error
Traceback (most recent call last):
  File "C:\xxx\xxx\xxx\test.py", line 1, in <module>
    from openai import OpenAI
ModuleNotFoundError: No module named 'openai'

エラーについてひも解く

注目していただきたいのはエラーのこの部分です。

Error
ModuleNotFoundError: No module named 'openai'

検索をかけてみたところ、下記の結果になりました。
no module namedエラーは、Pythonが指定されたモジュールを見つけられない場合に発生します。

トラブルシューティングの方法としてエラー文を検索することで解決に向かう場合が経験上多いのでエラー文は重要な手掛かりになります。

修正

最初エラーを見たときになんでno module namedが出るんだと戸惑いましたがpythonのバージョンを確認したところ3.11.4から3.13.1に自分で上げていたことを忘れていました。
ということでopenaiを改めてインストールしていきます。

Command
pip install

image.png

image.png
インストールが完了したので早速実行してみましょう。
py test.py
image.png

所感

今回はエラーのトラブルシューティング方法の一例をあげてみました。
これからの時期、新卒などで新しくこの業界に携わる方が多いかと思いますので参考になれば幸いです。

参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?