ChatGPTのFunction Callingを使う方法

ChatGPT に Function Calling という機能が追加されました。


目次


独自のデータから情報を取得する

ネットに公開されていない名簿から情報を取得する方法です。

下のサンプルでは架空の名簿をJSON形式で与えています。
あらかじめperson_searchという関数を作っておきます。氏名からその人の情報を取得するという機能があります。
ChatGPTには「関連しそうな質問にはこの関数を使う」という指示を組み込んでおきます。

「江戸川利根子の出身地を教えて下さい。」という質問をすると「江戸川利根子の出身地は「千葉」です。」と答えます。

import openai
import json

openai.api_key = ""
query = "江戸川利根子の出身地を教えて下さい。"
person_data = [
  {"漢字氏名": "富士沼太郎", "生年月日": "1950-1-5", "出身地": "東京"},
  {"漢字氏名": "江戸川利根子", "生年月日": "1955-12-15", "出身地": "千葉"},
]

def person_search(arguments):
  person_name = json.loads(arguments)["person_name"]
  person_hit=next((item for item in person_data if item["漢字氏名"] == person_name), None)
  return json.dumps(person_hit)

functions=[
  {
    "name": "person_search",
    "description": "人物の氏名から生年月日、出身地を取得する。",
    "parameters": {
      "type": "object",
      "properties": {
        "person_name": {
          "type": "string",
          "description": "人物の氏名",
        },
      },
      "required": ["person_name"],
    },
  },
]

messages = [{"role": "user", "content": query}]

while True:
  response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo-0613",
    messages=messages,
    functions=functions,
    function_call="auto",
    temperature=0.0,
  )
  message = response.choices[0]["message"]
  if not message.get('function_call'):
    break
  messages.append(message)
  f_call = message["function_call"]
  function_response = globals()[f_call["name"]](f_call["arguments"])
  messages.append({
    "role": "function",
    "name": f_call["name"],
    "content": function_response,
  })

print(message["content"])

計算式を使う

ChatGPTは計算は苦手なようです。Function Callingを使うと正確に計算できます。

下のサンプルでは犬の年齢を人間の年齢に換算しています。
「10歳の犬は人間に換算すると何歳ですか。」と質問すると「10歳の犬は人間に換算すると約67.8歳です。」と答えます。

import openai
import json
import math

openai.api_key = ""
query = "10歳の犬は人間に換算すると何歳ですか。"

def age_dog2human(arguments):
  dog_age = json.loads(arguments)["dog_age"]
  human_age = 16 * math.log(dog_age) + 31
  return json.dumps({"human_age": human_age})

functions=[
  {
    "name": "age_dog2human",
    "description": "犬の年齢が人間の年齢に換算すると何歳になるか。",
    "parameters": {
      "type": "object",
      "properties": {
        "dog_age": {
          "type": "number",
          "description": "犬の年齢。",
        },
      },
      "required": ["dog_age"],
    },
  },
]

messages = [{"role": "user", "content": query}]

while True:
  response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo-0613",
    messages=messages,
    functions=functions,
    function_call="auto",
    temperature=0.0,
  )
  message = response.choices[0]["message"]
  if not message.get('function_call'):
    break
  messages.append(message)
  f_call = message["function_call"]
  function_response = globals()[f_call["name"]](f_call["arguments"])
  messages.append({
    "role": "function",
    "name": f_call["name"],
    "content": function_response,
  })

print(message["content"])

コメント

タイトルとURLをコピーしました