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?

OpenAI + PythonでChatBotを作る

Posted at

ローカルで動かせるChatBot作成

  • 必要なもの
    • Python3
    • 仮想環境(PyCharmだと自動で作られる )
    • Editor/IDE VScode/Cursor/PyCharmお好きなもので

Google Colabを使用して作ってみることが多いと思うのですが、ローカル環境で作ってみたいと思い試してみました。

使用したモジュールはバージョンを固定して使用しました。
openai==1.66.3

pip install openai==1.66.3

こちらのGithub参考になると思われます。使い方の例が解説されております。

Example

以下のように記載したコードを実行する。ターミナルで入力するときに、日本語入力だと入力中は表示されない罠があった😅
メモ帳に書いてコピー&ペーストした方がいいかも。英語と数字は入力中に表示できる。

from openai import OpenAI

# APIクライアントを初期化
client = OpenAI(
    api_key="my-api-key"  # あなたのAPIキーを入力
)

def ask_openai(question):
    # チャット完了リクエストを送信
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "user", "content": question}
        ]
    )
    # レスポンスを返す
    return response.choices[0].message.content

if __name__ == "__main__":
    while True:
        question = input("質問を入力してください(終了するには 'exit' と入力):")
        if question.lower() == 'exit':
            break
        answer = ask_openai(question)
        print("回答:", answer)

実行結果
スクリーンショット 2025-03-18 8.29.43.png

最後に

最近は、生成AIを活用したアプリケーションを作ることが増えてきました。AIは使えて当然の技術になったのかも知れません。今度はFastAPIを使用したものも作ってみたいと思いました。SwaggerUIを使えばフロントエンドを構築しなくても実験出来さそうなので検証用にはいいかも。

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?