Created
February 12, 2025 20:04
-
-
Save reouno/be28ed70752d90b8b41647b6ec427e1f to your computer and use it in GitHub Desktop.
ChatGPT_API_JSON_output.ipynb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "nbformat": 4, | |
| "nbformat_minor": 0, | |
| "metadata": { | |
| "colab": { | |
| "provenance": [], | |
| "include_colab_link": true | |
| }, | |
| "kernelspec": { | |
| "name": "python3", | |
| "display_name": "Python 3" | |
| }, | |
| "language_info": { | |
| "name": "python" | |
| } | |
| }, | |
| "cells": [ | |
| { | |
| "cell_type": "markdown", | |
| "metadata": { | |
| "id": "view-in-github", | |
| "colab_type": "text" | |
| }, | |
| "source": [ | |
| "<a href=\"https://colab.research.google.com/gist/reouno/be28ed70752d90b8b41647b6ec427e1f/chatgpt_api_json_output.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>" | |
| ] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "source": [ | |
| "# ChatGPT APIの出力をpydanticで定義したJSONフォーマットに固定\n", | |
| "\n", | |
| "**詳しくは公式ドキュメントなどを参照:** https://platform.openai.com/docs/guides/structured-outputs\n", | |
| "\n", | |
| "\n" | |
| ], | |
| "metadata": { | |
| "id": "rSSXQjUAJBB1" | |
| } | |
| }, | |
| { | |
| "cell_type": "code", | |
| "execution_count": 1, | |
| "metadata": { | |
| "colab": { | |
| "base_uri": "https://localhost:8080/" | |
| }, | |
| "id": "eU1lVp3WI8Bx", | |
| "outputId": "9006e138-149a-46b3-f4a7-59197d48b6e6" | |
| }, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "name": "stdout", | |
| "text": [ | |
| "Requirement already satisfied: openai in /usr/local/lib/python3.11/dist-packages (1.61.1)\n", | |
| "Requirement already satisfied: anyio<5,>=3.5.0 in /usr/local/lib/python3.11/dist-packages (from openai) (3.7.1)\n", | |
| "Requirement already satisfied: distro<2,>=1.7.0 in /usr/local/lib/python3.11/dist-packages (from openai) (1.9.0)\n", | |
| "Requirement already satisfied: httpx<1,>=0.23.0 in /usr/local/lib/python3.11/dist-packages (from openai) (0.28.1)\n", | |
| "Requirement already satisfied: jiter<1,>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from openai) (0.8.2)\n", | |
| "Requirement already satisfied: pydantic<3,>=1.9.0 in /usr/local/lib/python3.11/dist-packages (from openai) (2.10.6)\n", | |
| "Requirement already satisfied: sniffio in /usr/local/lib/python3.11/dist-packages (from openai) (1.3.1)\n", | |
| "Requirement already satisfied: tqdm>4 in /usr/local/lib/python3.11/dist-packages (from openai) (4.67.1)\n", | |
| "Requirement already satisfied: typing-extensions<5,>=4.11 in /usr/local/lib/python3.11/dist-packages (from openai) (4.12.2)\n", | |
| "Requirement already satisfied: idna>=2.8 in /usr/local/lib/python3.11/dist-packages (from anyio<5,>=3.5.0->openai) (3.10)\n", | |
| "Requirement already satisfied: certifi in /usr/local/lib/python3.11/dist-packages (from httpx<1,>=0.23.0->openai) (2025.1.31)\n", | |
| "Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.11/dist-packages (from httpx<1,>=0.23.0->openai) (1.0.7)\n", | |
| "Requirement already satisfied: h11<0.15,>=0.13 in /usr/local/lib/python3.11/dist-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai) (0.14.0)\n", | |
| "Requirement already satisfied: annotated-types>=0.6.0 in /usr/local/lib/python3.11/dist-packages (from pydantic<3,>=1.9.0->openai) (0.7.0)\n", | |
| "Requirement already satisfied: pydantic-core==2.27.2 in /usr/local/lib/python3.11/dist-packages (from pydantic<3,>=1.9.0->openai) (2.27.2)\n" | |
| ] | |
| } | |
| ], | |
| "source": [ | |
| "!pip install openai" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "source": [ | |
| "import openai\n", | |
| "import json\n", | |
| "from pydantic import BaseModel, Field\n", | |
| "\n", | |
| "# OpenAI APIのAPIキーの設定\n", | |
| "client = openai.OpenAI(\n", | |
| " api_key=\"APIキーを設定\",\n", | |
| ")\n", | |
| "\n", | |
| "\n", | |
| "# Output JSON format definition\n", | |
| "class CalendarEvent(BaseModel):\n", | |
| " name: str = Field(..., description=\"イベント名\")\n", | |
| " date: str = Field(..., description=\"イベント開催日\")\n", | |
| " participants: list[str] = Field(..., description=\"イベント参加者リスト\")\n", | |
| "\n", | |
| "\n", | |
| "completion = client.beta.chat.completions.parse( # parse メソッドを使う\n", | |
| " model=\"gpt-4o-mini\",\n", | |
| " messages=[\n", | |
| " {\"role\": \"system\", \"content\": \"イベント情報を抽出するAIアシスタントです。\"},\n", | |
| " {\"role\": \"user\", \"content\": \"宇宙規模の遠い未来のイベントを企画して、イベント名、日付、参加者(宇宙人5人ぐらい)リストを教えてください。\"},\n", | |
| " ],\n", | |
| " response_format=CalendarEvent, # response_formatにpydanticモデルを指定\n", | |
| " temperature=1,\n", | |
| ")\n", | |
| "\n", | |
| "\n", | |
| "# parsed で確実に上記のpydanticモデル型で結果を取得できる。\n", | |
| "event = completion.choices[0].message.parsed\n", | |
| "\n", | |
| "print('レスポンス:')\n", | |
| "print(completion)\n", | |
| "\n", | |
| "print('\\nイベント情報:')\n", | |
| "print(event)\n", | |
| "\n", | |
| "print('\\neventのデータ型:', type(event))\n", | |
| "\n", | |
| "print('\\n辞書型への変換(必要なら):')\n", | |
| "print(event.model_dump())" | |
| ], | |
| "metadata": { | |
| "id": "THugGjcJJFQY", | |
| "colab": { | |
| "base_uri": "https://localhost:8080/" | |
| }, | |
| "outputId": "7f682dde-979b-4838-f8e6-68ce484775fc" | |
| }, | |
| "execution_count": 11, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "name": "stdout", | |
| "text": [ | |
| "レスポンス:\n", | |
| "ParsedChatCompletion[CalendarEvent](id='chatcmpl-B0D7txEcayp44j0CEIi675VlAv2AM', choices=[ParsedChoice[CalendarEvent](finish_reason='stop', index=0, logprobs=None, message=ParsedChatCompletionMessage[CalendarEvent](content='{\"name\":\"宇宙の運命を決める会議\",\"date\":\"3023-10-20\",\"participants\":[\"ゼルガ星人\",\"フリード星人\",\"タリク族\",\"マノク星人\",\"エイリアン・テクノロジスト\"]}', refusal=None, role='assistant', audio=None, function_call=None, tool_calls=[], parsed=CalendarEvent(name='宇宙の運命を決める会議', date='3023-10-20', participants=['ゼルガ星人', 'フリード星人', 'タリク族', 'マノク星人', 'エイリアン・テクノロジスト'])))], created=1739390157, model='gpt-4o-mini-2024-07-18', object='chat.completion', service_tier='default', system_fingerprint='fp_72ed7ab54c', usage=CompletionUsage(completion_tokens=64, prompt_tokens=225, total_tokens=289, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0)))\n", | |
| "\n", | |
| "イベント情報:\n", | |
| "name='宇宙の運命を決める会議' date='3023-10-20' participants=['ゼルガ星人', 'フリード星人', 'タリク族', 'マノク星人', 'エイリアン・テクノロジスト']\n", | |
| "\n", | |
| "eventのデータ型: <class '__main__.CalendarEvent'>\n", | |
| "\n", | |
| "辞書型への変換:\n", | |
| "{'name': '宇宙の運命を決める会議', 'date': '3023-10-20', 'participants': ['ゼルガ星人', 'フリード星人', 'タリク族', 'マノク星人', 'エイリアン・テクノロジスト']}\n" | |
| ] | |
| } | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "source": [], | |
| "metadata": { | |
| "id": "6Ji5BOpQu4Hb" | |
| }, | |
| "execution_count": null, | |
| "outputs": [] | |
| } | |
| ] | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment