Function Callingを実装を用いて概要とメリットを解説

初めまして、みずぺーといいます。
このnoteを機に初めて私を知った方のために、箇条書きで自己紹介を記述します。

  • 年齢:28歳

  • 出身:長崎

  • 大学:中堅国立大学

  • 専門:河川、河川計画、河道計画、河川環境

  • IT系の資格:R5.4基本情報技術者試験合格💮、R5.5G資格

本日はFunction callingの概要と実装例を元に解説。

Function Callingの機能とメリットについて解説するにあたり、結論から!

機能は以下の通りです。

  • APIに渡す関数をGPTが判断して抽出してくれる機能

メリットは以下の通りです。

  • 抽出して処理した結果を新たな関数に渡すことで、特定の処理において特化且つ、制御可能なモデルの構築が可能

これを中学生にもわかるように簡単な言葉で置き換えると

Function Callingは、コンピューターが自分で考えて、プログラムに必要な部分を選んでくれる機能です。これにより、プログラムがよりスマートになり、特定のタスクをよりうまくこなせるようになります。

それでは続いてはFunction callingを実装例を元に解説したいと思います。

ここでは、にゃんたさんのコードを用いて解説させていただきます!

Function callingの一連の処理の流れ

まずは先に実装の全体像からお伝えします!

画像
Function callingの全体像
  1. APIに渡す関数の定義(Function Callingが呼び出すかどうかを決定)

  2. APIから得られる出力を関数に与える

  3. 処理する関数を定義しAPIに渡す関数により得られる文字を入力とする

  4. 関数により得られた出力をGPTに与えて会話文を生成

なので、 GPTの機能の一つであるFunction callingがAPIを叩くかどうかを自分で考えて決めて、叩く場合には処理が実行されて結果が返ります。その結果を別の関数に渡して処理を実行したうえで再度GPTに渡して会話文が生成されます。

では以下の実装例を用いて解説します。

OpenAIのライブラリをインストール

%%capture
!pip install openai

OpenAIのAPIキーの入力

import openai
import getpass
import json
apikey = getpass.getpass(prompt="OpenAIのAPIキーを入力してください")
openai.api_key = apikey

OpenAIが何ぞや??という方はこちらの記事を参考にしていただければと思います!

定義ゾーン

ここから関数等々を定義していきます。

関数を定義

画像

ここではfunction callingによる返ってきて

def get_current_weather(location, unit):
    """Get the current weather in a given location"""
    weather_info = {
        "location": location,
        "temperature": "72",
        "unit": unit,
        "forecast": ["sunny", "windy"],
    }
    return json.dumps(weather_info)

Function Callingにより呼び出される関数の定義

画像
my_functions = [
    {
        "name": "get_current_weather",
        "description": "Get the current weather",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g. San Francisco, CA",
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "The temperature unit to use. Infer this from the users location.",
                },
            },
            "required": ["location", "unit"],
        },
    }
]

GPTのFunction callingの定義

画像
response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo-0613",
    messages=[{"role": "user", "content": "What's the weather like in Boston?"}],
    functions=my_functions,
    function_call="auto",
)

処理の実施

ここからは処理の実施の確認になります。

responseを実行した結果function callingを使用したかどうか確認

function_name = response["choices"][0]["message"]["function_call"]["name"]
function_name
>get_current_weather

responseを実行した結果どのような処理が返ってきているのかを確認

arguments = response["choices"][0]["message"]["function_call"]["arguments"]
arguments
>{\n  "location": "Boston, MA",\n  "unit": "celsius"\n}

辞書型に変換し関数に渡しやすい変数へと変換

eval(arguments)
{'location': 'Boston, MA', 'unit': 'celsius'}

関数へとfunction callingによって得られた出力を渡す

function_response = get_current_weather(
    location=eval(arguments)["location"], unit=eval(arguments)["unit"]
)
function_response
>{"location": "Boston, MA", "temperature": "72", "unit": "celsius", "forecast": ["sunny", "windy"]}

最終処理の実施

最後にGPTに関数の返り値②を渡して会話文の完了になります。

画像

得られた出力をさらにGPTに渡し会話文を生成

message = response["choices"][0]["message"]
second_response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo-0613",
    messages=[
        {"role": "user", "content": "What's the weather like in Boston?"},
        message,
        {
            "role": "function",
            "name": function_name,
            "content": function_response,
        },
    ],
)
second_response["choices"][0]["message"]["content"]
>The weather in Boston is currently sunny and windy with a temperature of 72 degrees Celsius.

最後に

私自身このFunction callingを聞いた時に「??」を浮かんだ記憶があります。

今では

Function Callingは、コンピューターが自分で考えて、プログラムに必要な部分を選んでくれる機能です。これにより、プログラムがよりスマートになり、特定のタスクをよりうまくこなせるようになります。

と理解しています。

入力をFanctioncallingを呼び出して考えさせ、処理を実行。
理想の結果を誘導して処理を行わせることが可能なものだと思います。

是非、

  • エクセルに特定の処理のみ行って出力したい

  • ○○な情報のみを抽出してワードに張り付けてほしい

等々個別具体な要望はfunction callingによって実現できる可能性がありますので、皆さんも是非活用機会を検討してみて下さい!!

この記事が気に入ったらサポートをしてみませんか?

コメント

コメントを投稿するには、 ログイン または 会員登録 をする必要があります。
Function Callingを実装を用いて概要とメリットを解説|みずぺー | コンサル×AI×公共事業(河川、道路)
word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word

mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1