オレとChatGPT

AIとの会話記録

Function Calling

先日、OpenAI から発表された function calling という機能は一部では神アップデートと呼ばれている見ようですが。*1 オレもその通りだと思います。

これは ChatGPT を API 経由で使うときに使える機能なのですが、 こういう関数があるよ、引数はこうしてね ChatGPT に伝えておくと、ChatGPT が必要に応じて、その関数を引数付きで呼び出してね、という応答を返してくるものです。

いままでは ChatGPT の API を使って何かしようとすると、ChatGPT のメッセージ自体を解析するとか、あまり安定的でない方法を取らなくてはいけなかったのですが、これを使うと明示的に関数と引数を JSON で返してくれるので安定した処理をすることが出来ます。

Open AI のガイドによると

In an API call, you can describe functions to gpt-3.5-turbo-0613 and gpt-4-0613, and have the model intelligently choose to output a JSON object containing arguments to call those functions. The Chat Completions API does not call the function; instead, the model generates JSON that you can use to call the function in your code.

The latest models (gpt-3.5-turbo-0613 and gpt-4-0613) have been fine-tuned to both detect when a function should to be called (depending on the input) and to respond with JSON that adheres to the function signature. With this capability also comes potential risks. We strongly recommend building in user confirmation flows before taking actions that impact the world on behalf of users (sending an email, posting something online, making a purchase, etc).

ℹ️ Under the hood, functions are injected into the system message in a syntax the model has been trained on. This means functions count against the model's context limit and are billed as input tokens. If running into context limits, we suggest limiting the number of functions or the length of documentation you provide for function parameters.

Function calling allows you to more reliably get structured data back from the model. For example, you can:

  • Create chatbots that answer questions by calling external APIs (e.g. like ChatGPT Plugins)
    • e.g. define functions like send_email(to: string, body: string), or get_current_weather(location: string, unit: 'celsius' | 'fahrenheit')
  • Convert natural language into API calls
    • e.g. convert "Who are my top customers?" to get_customers(min_revenue: int, created_before: string, limit: int)and call your internal API
  • Extract structured data from text
    • e.g. define a function called extract_data(name: string, birthday: string), or sql_query(query: string)
...and much more!

API呼び出しでは、gpt-3.5-turbo-0613およびgpt-4-0613に関数を記述し、モデルがインテリジェントにそれらの関数を呼び出すための引数を含むJSONオブジェクトを出力するよう選択できます。チャットコンプリーションAPIは関数を呼び出さない代わりに、コードで関数を呼び出すために使用できるJSONをモデルを生成します。

最新のモデル(gpt-3.5-turbo-0613およびgpt-4-0613)は、関数が呼び出されるべき場合(入力に応じて)を検出し、関数シグネチャに準拠したJSONで応答するように微調整されています。この機能には潜在的なリスクが伴います。ユーザーに代わって世界に影響を与える行動を取る前に(メールを送信する、オンラインに投稿する、購入するなど)、ユーザーの確認フローを組み込むことを強くお勧めします。

ℹ️ 内部的には、関数はモデルが学習された構文でシステムメッセージに注入されます。これは、関数がモデルのコンテキスト制限に対してカウントされ、入力トークンとして請求されることを意味します。コンテキスト制限に遭遇した場合は、関数の数や関数のパラメータに対するドキュメントの長さを制限することをお勧めします。

関数の呼び出しにより、モデルからより確実に構造化データを取得できます。例えば、次のことができます。

  • 外部APIを呼び出して質問に答えるチャットボットを作成する(例: ChatGPTプラグインのような)
    • 例: send_email(to: string, body: string)get_current_weather(location: string, unit: 'celsius' | 'fahrenheit')のような関数を定義
  • 自然言語API呼び出しに変換する
    • 例:「トップの顧客は誰ですか?」を get_customers(min_revenue: int, created_before: string, limit: int)に変換して、内部APIを呼び出す
  • テキストから構造化データを抽出する
    • 例:extract_data(name: string, birthday: string)sql_query(query: string)という関数を定義する
...など、さらに多くのことができます!

https://platform.openai.com/docs/guides/gpt/function-calling

との事です。

使い方については OpenAI がサンプルの ipynb を公開してくれていますが、少しわかりにくかったので日本語に翻訳し、コメントを追加し、少し修正したものを作成しました。

なお、この文書の翻訳のほとんどは


Python スクリプトに日本語コメントをつける作業をおねがいします。文字列中の英語にも日本語コメントをつけてください。
最初に例を示します。(コメントは過剰になりすぎないようにしてください)

元のスクリプト
```
def add_and_print(a, b):
    """"""Add the two numbers a and b and print the result.""""""
    t = a + b
    print(f""Adding {a} and {b} gives the total {n}"")
```

日本語コメントを追加したスクリプト
```
def add_and_print(a, b):
    """"""Add the two numbers a and b and print the result.""""""
    # 2つの数字a、bを足して結果を表示する。
    t = a + b
    print(f""Adding {a} and {b} gives the total {n}"")
    # {a}と{b}を足すと、合計{n}になります。
```

それではお願いします。

元のスクリプト
```
【ここに翻訳するPythonスクリプトを挿入】
```

とか


文字列の中身も含めて日本語に翻訳して下さい、ただし MarkDown 記法や記号、URL はそのままにしてください。解説は不要です。

```
【ここに翻訳するMarkDownを挿入】
```

みたいなテンプレートを作って ChatGPT の API で GPT-4 モデルを呼び出して行いました。