見出し画像

GPT APIの新機能function calling体験してみました

こちらの記事でGPTのfanction callを動かすサンプルコードが紹介されていたので

私も動かしてみました

Google Colab用にnotebookを追加して記事に載っていたサンプルコードを入れます。
APIキーを自分のに変えます。「gpt-4-0613」はエラーになったので「gpt-3.5-turbo-0613」に書き換えて実行し
セルを追加して

print(main("東京の現在の天気を教えてください。"))

を実行すると


応答が返ってきました。

Google Colab以外で動かす場合は

pip install openai 

を行って以下のコードで動きました。

import openai 
import json 
import requests 
openai.api_key = "あなたのAPIキー" 
 
def get_weather_info(latitude, longitude): 
    base_url = "https://api.open-meteo.com/v1/forecast" 
    parameters = { 
        "latitude": latitude, 
        "longitude": longitude, 
        "current_weather": "true" 
    } 
    response = requests.get(base_url, params=parameters) 
    if response.status_code == 200: 
        data = response.json() 
        return json.dumps(data["current_weather"]) 
    else: 
        return None 
 
weather_function =  { 
    "name": "get_weather_info", 
      "description": "経度緯度の情報から現在の天気を取得", 
      "parameters": { 
          "type": "object", 
          "properties": { 
              "latitude": { 
                  "type": "string", 
                  "description": "経度の情報", 
              }, 
              "longitude": { 
                  "type": "string", 
                  "description": "緯度の情報", 
              }, 
          }, 
          "required": ["latitude", "longitude"], 
      }, 
} 
 
def main(text): 
    response = openai.ChatCompletion.create( 
        model="gpt-3.5-turbo-0613", 
        messages=[{"role": "user", "content": text}], 
        functions=[weather_function], 
        function_call="auto", 
    ) 
    message = response["choices"][0]["message"] 
    if message.get("function_call"): 
        function_name = message["function_call"]["name"] 
        arguments=json.loads(message["function_call"]["arguments"]) 
        function_response = get_weather_info( 
            latitude=arguments.get("latitude"), 
            longitude=arguments.get("longitude"), 
        ) 
        second_response = openai.ChatCompletion.create( 
            model="gpt-3.5-turbo-0613", 
            messages=[ 
                {"role": "user", "content": text}, 
                message, 
                { 
                    "role": "function", 
                    "name": function_name, 
                    "content": function_response, 
                }, 
            ], 
        ) 
        return second_response.choices[0]["message"]["content"].strip() 
 
print(main("広島の現在の天気を教えてください。")) 

この記事が参加している募集

AIとやってみた

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