🍵

OpenAIの Create a model response APIを使ってChatGPTからJSONの応答を得る方法

に公開

はじめに

OpenAIの Create a model response APIを使ってChatGPTからJSONの応答を得る方法を紹介します。

この記事ではTypeScriptで実装を行っています。
例として、架空の人物のプロフィールを作成して、以下のTypeScriptの型に当てはまるJSONを出力する実装を行いました。

type ProfileType =  {
  name: string;
  age: number;
  gender: "男" | "女" | "その他";
};

関連する筆者の記事

以下の記事ではCreate chat completion APIを使ってChatGPTからJSONの応答を得る方法を3つ紹介しました。今回はこれのCreate a model response API版で、オススメの方法1つのみを紹介します。
https://zenn.dev/zozooizozzoizio/articles/995f8ce9e237dc

参考資料

OpenAI の Create chat completion の API Referenceは以下です。
https://platform.openai.com/docs/api-reference/responses/create

1. text.formatを使ってJSONの応答を得る

本記事では、最もお勧めのtext.formatを使う方法を紹介します。もし、得られたJSONを使ってAPIなどを呼び出したい場合には、toolsのfunctionを使った方法を調べてみると良いと思います。

1.1 text.formatを使った実装

text.formatを使ったTypeScriptの実装は以下の通りです。

const generateProfileWithTextFormat = async () => {
  const response = await fetch('https://api.openai.com/v1/responses', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${OPENAI_API_KEY}`,
    },
    body: JSON.stringify({
      model: 'gpt-4o-2024-08-06',
      input: [
        {
          role: 'user',
          content: [
            {
              type: 'input_text',
              text: '架空の人物のプロフィールを作成してください。',
            },
          ],
        },
      ],
      text: {
        format: {
          name: 'profile',
          description: "人物のプロフィールです。",
          type: 'json_schema',
          schema: {
            type: 'object',
            properties: {
              name: {
                type: 'string',
                description: '名前。'
              },
              gender: {
                type: 'string',
                description: '性別。',
                enum: ['男', '女', 'ノンバイナリー'],
              },
              age: {
                type: 'integer',
                description: '年齢。'
              },
            },
            required: ['name', 'gender', 'age'],
            additionalProperties: false,
          },
          strict: true,
        },
      },
    }),
  });

  const responseJson = await response.json();
  const content = responseJson.output[0].content[0];
  console.log(JSON.stringify(content, null, 2));
};

特にポイントとなるのは以下のプロパティです。

プロパティ名 説明
strict trueを指定することで、厳密なスキーマ遵守を有効にしています。
required name、gender、ageを指定することで全てのプロパティを必須としています。
additionalProperties falseを指定することで未定義のプロパティが追加されることを禁止しています。

このように厳格なスキーマ遵守と必須プロパティ指定、未定義プロパティの禁止をしても、期待する結果が得られないことがある点に注意してください。応答はZodのsafeParseなどを使って型チェックをすることをお勧めします。

1.2 text.formatを使った場合の応答

text.formatを使った場合の応答は以下の通りです。ここでは見やすさのためにoutput[0].content[0]のみを出力しています。
textに期待したJSONの応答が得られているのが分かります。

{
  "type": "output_text",
  "annotations": [],
  "logprobs": [],
  "text": "{\"name\":\"山田太郎\",\"gender\":\"男\",\"age\":20}"
}

おわりに

記事を読んでいただいてありがとうございました。今回はOpenAIの Create a model response APIを使ってChatGPTからJSONの応答を得る方法を紹介しました。実装の具体例として、どなたかの参考になれば嬉しいです。この記事が良かったら「いいね」もいただけたら嬉しいです。よろしくお願いします!

Discussion