◆ はじめに
AIからの回答を、JSONなど定型の構造体に収めてアプリケーション上で活用したい、という場面はよくあると思う。
プロンプトで「このような型で回答してほしい」といった要望を逐一指示することも可能ではあるが、実際にやってみると回答にブレが生じる場合があり、期待した型でパースができないといった問題が生じる。
このようなケースで functions パラメータを用いると、回答の定型化を行うことができる。
◆ Function calling
公式の説明としては「関数呼び出し」となっており、
Give models access to new functionality and data they can use to follow instructions and respond to prompts.
(モデルに、指示に従ったりプロンプトに応答したりするために使用できる新しい機能とデータへのアクセス権を付与します。)
とのことだが、正直分かりづらい。
要は外部連携をし易い形で回答を返すことができます=定型の構造体に収めた回答を返せます、ということなので、冒頭で述べたような用途での利用ができる。
◆ パラメータの指定方法
functions を含むリクエストパラメータ例を以下に記載する。
POST /chat/completions Content-Type: application/json Authorization: Bearer YOUR_API_KEY { "model": "gpt-4.1-mini", "messages": [ { "role": "user", "content": "以下の文章に含まれる商品名と、わかればその価格を抽出して\n(対象のテキスト)" } ], "functions": [ { "name": "extract_products", "description": "文章に含まれる商品情報を抽出する", "parameters": { "type": "object", "properties": { "products": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string", "description": "商品名" }, "price": { "type": "integer", "description": "価格" } }, "required": [ "name" ] } } }, "required": [ "products" ] } } ], "function_call": { "name": "extract_products" } }
| messages[n].content | プロンプトを記述する。 |
|---|---|
| functions | 回答に期待する構造体をJSON Schemaで定義する。 |
| function_call.name | functions[n].nameを設定することで、確実にそのfunctionを用いて回答させる。 |
これでAPIリクエストを行うと、以下のようなレスポンスが返る。
{
...
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": null,
"function_call": {
"name": "extract_products",
"arguments": "{\n \"products\": [\n {\n \"name\": \"商品A\",\n \"price\": 120\n },\n {\n \"name\": \"商品B\",\n \"price\": 150\n }\n ]\n}"
}
},
"finish_reason": "function_call"
}
],
...
}
arguments の内容が functions で定義したJSONとなるので、この値をパースしてアプリケーション上で活用する。