目次

  1. 呼び出す予定の関数を定義
  2. ツールの定義
  3. 実行してツール要望のレスポンスを得る
  4. ツール使用結果を渡す
  5. 最終結果の取得

呼び出す予定の関数を定義

def some_function(arg1, arg2):
"""ツールとして使う関数"""
# 処理
return 戻り値

ツールの定義

tools = [
{
"type": "function",
"function": {
"name": "some_function",
"description": "何に使う関数であるかを説明する文章",
"parameters":{
"type": "object",
"properties": {
"arg1": {
"type": "string",
"description": "引数1についての説明文",
},
"arg2": {
"type": "string",
"description": "引数2についての説明文",
},
},
"required": ["arg1"],
},
},
}
]

実行してツール要望のレスポンスを得る

tools を加えたときのレスポンスをまず得る.

from openai import OpenAI

client = OpenAI()
model = "gpt-4o-mini"
messages = [{"role": "user", "content": "何らかの質問"}]

first_response = client.chat.completions.create(
model = model,
messages = messages,
tools = tools,
)

ここで,first_response にてツールを使いたいtool_callsというレスポンスが返ってくるものとする.
このレスポンスをメッセージに加えておく.

first_response_message = first_response.choices[0].message
messages.append(first_response_message.to_dict())

ツール使用結果を渡す

次に,callされた関数群のレスポンスをメッセージに加える.

import json

available_functions = {
"some_function": some_function,
}

for tool_call in response_message.tool_calls:
function_name = tool_call.function.name
function_to_call = available_functions[function_name]
function_args = json.loads(tool_call.function.arguments)
function_response = function_to_call(
arg1 = function_args.get("arg1"),
arg2 = function_args.get("arg2"),
)

messages.append(
{
"tool_call_id": tool_call.id,
"role": "tool",
"name": function_name,
"content": function_response,
}
)

最終結果の取得

以上のtool使用後の結果を含んだメッセージを再度処理にかけてレスポンスを

second_response = client.chat.completions.create(
model = model,
messages = messages,
)

として得て,

print(second_response.to_json(indent=2))

などで出力するとよい.