開始使用免費開始

使用外部 API 定義函式

你正在開發一個貨幣換算應用程式,被要求建立一個能依使用者請求提供匯率資訊的系統。你決定使用 OpenAI API 從使用者訊息中擷取相關的貨幣代碼,然後呼叫 ExchangeRate API 以回傳最新匯率。作為此程式專案的第一步,你會在 Chat Completions 端點中設定要傳入 tools 參數的函式。

在本練習中,get_exchange_rate()get_response() 函式已預先載入。get_exchange_rate() 會使用 ExchangeRate API,輸入為一個貨幣代碼,並回傳所請求的匯率資訊回應。

本練習屬於課程

使用 OpenAI API 開發 AI 系統

檢視課程

練習說明

  • 定義要傳入 tools 的函式:內容需包含函式的 'name'、一段 'description'(說明應回傳符合的貨幣代碼)、以及 'parameters''result' 的詳細資訊。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

client = OpenAI(api_key="")

# Define the function to pass to tools
function_definition = [{"type": ____,
                        ____ : {"name": ____,
                                ____: ____,
                                ____: {"type": ____, ____: {"currency_code": {____}, ____} }, 
                                "result": ____ }}]

response = get_response(function_definition)
print(response)
編輯並執行程式碼