0
2

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 で足し算

Last updated at Posted at 2023-06-14

gpt-3.5-turbo-0613 が発表されて Function Calling なる関数呼び出しができるようになりました。詳しい使い方などはクラスメソッドさんの解説がわかりやすいので参考にしてください。

せっかくなのでオリジナルの関数でも作ってみます。簡単に2つの数の足し算をしてみます。

sample.py
import openai
import os


# OpenAI APIキーの準備
openai.api_key = "XXXXXXXXXXXXXXXXXXXX"


import json

def sum_two_numbers(number1, number2):
    info = {
        "number1": number1,
        "number2": number2,
    }
    return json.dumps(info)


functions=[
    {
        "name": "sum_two_numbers",
        "description": "2つの数の足し算",
        "parameters": {
            "type": "object",
            "properties": {
                "number1": {
                    "type": "string",
                    "description": "1つ目の数",
                },
                "number2": {
                    "type": "string",
                    "description": "2つ目の数",
                },
            },
            "required": ["number1, number2"],
        },
    }
]

model_name = "gpt-3.5-turbo-0613"

question = "1+10は?"

response = openai.ChatCompletion.create(
    model=model_name,
    messages=[
        {"role": "user", "content": question},
    ],
    functions=functions,
    function_call="auto",
)
message = response["choices"][0]["message"]
if message.get("function_call"):

    function_name = message["function_call"]["name"]

    arguments = json.loads(message["function_call"]["arguments"])
    function_response = sum_two_numbers(
        number1=arguments.get("number1"),
        number2=arguments.get("number2"),
    )

    second_response = openai.ChatCompletion.create(
        model=model_name,
        messages=[
            {"role": "user", "content": question},
            message,
            {
                "role": "function",
                "name": function_name,
                "content": function_response,
            },
        ],
    )

    print(second_response.choices[0]["message"]["content"].strip())
else:
    print(response.choices[0]["message"]["content"].strip())

2023-06-14_12h22_30.png

シンプルに関数の説明を「2つの数の足し算」として引数を2つ定義してあげるだけで勝手に答えを出力してくれます。便利です。

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?