5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ChatGPT Function Calling で enum の配列を扱う

Last updated at Posted at 2023-08-02

複数のタグがあり、ユーザーが入力した文章に関連したタグがあったら全部取得したいときがあります。そんなときに使える Function Calling のプログラムです。

import json
import openai

openai.api_key = "XXXXXXXXXXXXXXX"

functions = [
    {
        "name": "make_tags",
        "description": "ユーザーのコメントからタグを選択する",
        "parameters": {
            "type": "object",
            "properties": {
                "tags": {
                    "type": "array",
                    "items": {
                        "type": "string",
                        "enum": [
                            "",
                            "",
                            "",
                            "",
                            "",
                            "",
                            "",
                            "",
                            "美味い",
                            "不味い",
                            "ラーメン",
                            "カレー",
                            "ピザ",
                        ],
                    }
                },
            },
            "required": ["tags"],
        },
    }
]
user_content ="朱色の小さくてほそい旨くないカレー"
response = openai.ChatCompletion.create(
    model="gpt-4-0613",
    messages=[
        {"role": "user", "content": user_content},
    ],
    functions=functions,
    function_call={"name": "make_tags"},
)
item_params = None
try:
    item_params = json.loads(response.choices[0].message.function_call.arguments)
    print("question:", user_content)
    print("result:", item_params)
except:
    print("error")
    print(response.choices[0].message.function_call.arguments)
question: 朱色の小さくてほそい旨くないカレー
result: {'tags': ['赤', '小', '細', '不味い', 'カレー']}
5
7
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
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?