OpenAIのドキュメントを読みながらAPIを使ってみる

こちらのドキュメントを読みながらAPIを使ってみたいと思います。

platform.openai.com

APIキーを環境変数に登録してみます。

export OPENAI_API_KEY="your_api_key_here"

APIリクエストをPythonで実行するためOpenAI SDKをインストールします。

pip install openai

GitHubリポジトリは以下なので、読むといろいろおもしろそうです。

github.com

example.pyを作成して、テキスト生成用のコードを実行してみます。

from openai import OpenAI
client = OpenAI()

completion = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {
            "role": "user",
            "content": "Write a haiku about recursion in programming."
        }
    ]
)

print(completion.choices[0].message)

以下のレスポンスが返されました。

ChatCompletionMessage(
  content='Functions call themselves,  \nInfinite loops of wisdom,  \nDepth leads to the light.', 
  refusal=None, 
  role='assistant', 
  audio=None, 
  function_call=None, 
  tool_calls=None)

レスポンスの内容をPerplexityに聞いてみると以下の返答が返ってきました。

The OpenAI API's response structure for chat completions can be broken down as follows:

ChatCompletionMessage Object

The response is encapsulated in a

ChatCompletionMessage object, which contains several attributes:

Content

  • The content attribute contains the actual text response generated by the model12.
  • In this case, it's the haiku about recursion in programming.

Role

  • The role attribute indicates the role of the message, which is 'assistant' in this response12.
  • This signifies that the message is the AI's response to the user's prompt.

Other Attributes

  • refusal: Set to None, indicating no refusal was generated.
  • audio: Set to None, as no audio was involved in this text-based interaction.
  • function_call: Set to None, as no function was called in this response.
  • tool_calls: Set to None, suggesting no external tools were used to generate the response.

次に画像を生成するコードを実行してみました。

from openai import OpenAI
client = OpenAI()

response = client.images.generate(
    prompt="A cute baby sea otter",
    n=2,
    size="1024x1024"
)

print(response.data[0].url)

するとURLが出力されて、画像が生成されていました。

まとめ

OpenAIのSDKを使ってまずは簡単なAPIの動作確認ができたので、引き続き使い方を調査して自分のプロダクトにも活かしていきたいと思います。