簡介
OpenAI 最近推出了一個令人興奮的新功能:函數調用(Function Calling)。這個功能讓開發者能更方便地將 GPT 模型與外部工具和 API 連接。在這篇文章中,我將詳細介紹這個新功能並提供一個實用的 Python 範例。
主要特點
- 智能選擇函數調用:模型可以根據用戶輸入智能地選擇要調用的函數。
- 輸出結構化數據:模型會輸出一個 JSON 物件,其中包含調用函數所需的參數。
- 多用途:這個功能可以用於創建聊天機器人、將自然語言查詢轉換為 API 調用或數據庫查詢,以及從文本中提取結構化數據。
API 參數
functions
: 用於描述函數的 JSON Schema。function_call
: 可選參數,用於指定要調用的特定函數。
實戰範例:查詢波士頓的天氣
首先,確保你已經安裝了 OpenAI 的 Python 庫。
pip install openai
接著,使用以下 Python 代碼:
import openai
openai.api_key = "your-api-key"
# 定義函數
functions = [
{
"name": "get_current_weather",
"type": "object",
"properties": {
"location": {"type": "string"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
}
}
]
# 調用模型
response = openai.ChatCompletion.create(
model="gpt-4-0613",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What’s the weather like in Boston right now?"},
],
functions=functions
)
# 處理模型回應
function_call = response['choices'][0]['function_call']
if function_call['name'] == 'get_current_weather':
location = function_call['args']['location']
unit = function_call['args']['unit']
# 調用你的天氣 API
這樣,模型會返回一個 function_call
物件,你可以用它來調用你的天氣 API。
結論
OpenAI 的這個新功能為開發者提供了一個強大的工具,讓我們能更方便地將自然語言處理能力與實際的應用場景結合。希望這篇文章能幫助你更好地理解和使用這個新功能。
有其他問題或想法,歡迎在下方留言討論!