目次
Function callingとは?
もっと簡単に言えば、質問に対して事前に組み込んだ関数を選んで、それを実行することができます。
Function callingを使ってみた
今回はPythonでFunction callingを使って、設定した架空の会社名を出力できるようなプログラムを作ってみました。
your-api-keyのところにOpenAIから取得したAPIを入力してください。
APIの取得方法は以下から
あわせて読みたい


OpenAIのAPIとは?概要からAPIキーを取得する方法まで
今回の記事ではOpenAIのAPIキーの取得方法を解説します。OpenAIのAPIキーを取得することで、OpenAIが提供するChatGPTなどさまざまなAIサービスを自身んのアプリケーショ...
openai.api_key = 'your-api-key'
import openai
openai.api_key = 'your-api-key'
# 外部からの入力を受け取る
user_message = input("Please enter your message: ")
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0613",
messages=[
{"role": "system", "content": "If you are asked a question about the company, please select something appropriate from the function."},
{"role": "user", "content": user_message} # 外部から受け取ったメッセージを利用
],
# Function callingの定義
functions = [
{
"name": "get_company_info",
"description": "会社情報を取得",
"parameters": {
"type": "object",
"properties": {
"company_name": {
"type": "string",
"description": "会社名",
"default": "ブルームオーシャンテクノロジーズ"
},
},
"required": ["company_name"]
}
}
],
function_call="auto"
)
print(response['choices'][0]['message']['content'])
実行すると以下の結果になりました。

コードを少し解説すると次のコードで外部から入力受け取ります。
user_message = input("Please enter your message: ")
Function callingで設定した内容と照らし合わせます。
関連するワードと判断したら、その関数を実行します。
# Function callingの定義
functions = [
{
"name": "get_company_info",
"description": "会社情報を取得",
"parameters": {
"type": "object",
"properties": {
"company_name": {
"type": "string",
"description": "会社名",
"default": "ブルームオーシャンテクノロジーズ"
},
},
"required": ["company_name"]
}
}
],
function_call="auto"
)
結果を出力します。
print(response['choices'][0]['message']['content'])
おわりに
簡単ですが、今回はChatGPT APIで使えるFunction callingについて解説しました。
Function callingを使えば、外部システムや独自データとの連携をスマートに実装できます。