takataka430’s blog

.NET系を中心に勉強したことのまとめを書きます

OpenAIを使ってみた

最近よく聞くOpenAIのAPIを使ってみました。

環境

Python 3.9.13
Visual Studio Code 1.75.0

手順

APIキーの取得

以下のページからログインします。(利用にはサインアップが必要です)
https://beta.openai.com/

ログインしたら以下のページからAPIキーを取得できます。
https://platform.openai.com/account/api-keys

コードを書く

今回はPythonのライブラリを使うので以下のコマンドでインストールします。

pip install openai

これでライブラリを使う準備は完了です。
OpenAIでできることは以下のページにまとめられています。

https://platform.openai.com/examples

今回はQ&Aのサンプルコードを少し修正して使います。

import openai

question = "Where is the Valley of Kings?"

# 本来APIキーはソースコードに含めてはいけないのですが、今回は動作確認なのでここで設定します
openai.api_key = "[OpenAIのAPIキー]"

response = openai.Completion.create(
  model="text-davinci-003",
  prompt="I am a highly intelligent question answering bot. If you ask me a question that is rooted in truth, I will give you the answer. If you ask me a question that is nonsense, trickery, or has no clear answer, I will respond with ""Unknown"". Q: " + question  + " A:",
  temperature=0,
  max_tokens=300,
  top_p=1,
  frequency_penalty=0.0,
  presence_penalty=0.0,
  stop=["\n"]
)

# 翻訳結果の表示
print(response["choices"][0]["text"])

結果は以下のようになりました。

 The Valley of the Kings is located in Egypt, on the west bank of the Nile River in Luxor.

ソースコードquestionを変更すると色々質問することができます。是非皆さんも使ってみてください!