結構化 API 呼叫

使用 OpenAI API 開發 AI 系統

Francesca Donadoni

Curriculum Manager, DataCamp

進度快照

一個黑白標誌,上面寫著「opal library」

使用 OpenAI API 開發 AI 系統

進度快照

一張圖示列出 OpenAI 函式庫與其標誌,以及帶有 API 圖示的 API 呼叫

使用 OpenAI API 開發 AI 系統

進度快照

一張圖示列出 OpenAI 函式庫與標誌、通用 API 呼叫與 API 圖示,以及帶有圖示的回應訊息

使用 OpenAI API 開發 AI 系統

進度快照

from openai import OpenAI
client = OpenAI(api_key="ENTER YOUR KEY HERE")

response = client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "user", "content": "Who developed ChatGPT?"} ] )
print(response.choices[0].message.content)
ChatGPT was developed by OpenAI, an artificial intelligence research lab.
使用 OpenAI API 開發 AI 系統

正式環境的挑戰

  兩人拿著地圖與指南針規劃路線

  一支手機顯示使用 GPS 的地圖應用程式

使用 OpenAI API 開發 AI 系統

正式環境的挑戰

 

  • 錯誤處理
    • 顯示友善的錯誤訊息
    • 服務不可用時的替代方案

 

  • 審核與安全
    • 控制不當輸入
    • 降低資料外洩風險

 

  • 測試與驗證
    • 檢查離題回應
    • 測試行為不一致

 

  • 與外部系統溝通
    • 呼叫外部函式與 API
    • 最佳化回應時間
使用 OpenAI API 開發 AI 系統

OpenAI API 請求的組成

from openai import OpenAI

client = OpenAI(api_key="ENTER YOUR KEY HERE")

response = client.chat.completions.create(
  model="gpt-4o-mini",

messages=[ {"role": "user", "content": "Please write down five trees with their scientific names in json format."} ],
response_format={"type": "json_object"}
)
使用 OpenAI API 開發 AI 系統

OpenAI API 回應的組成

 

print(response.choices[0].message.content)
{
  "trees": [
    {"commonName": "Oak", "scientificName": "Quercus"},
    {"commonName": "Maple", "scientificName": "Acer"},
    {"commonName": "Pine", "scientificName": "Pinus"},
    {"commonName": "Birch", "scientificName": "Betula"},
    {"commonName": "Willow", "scientificName": "Salix"}
  ]
}
使用 OpenAI API 開發 AI 系統

接下來是什麼

 

  • 生產環境整合
  • 呼叫外部函式
  • 最佳實務

一位背包客拿著地圖指向目的地

使用 OpenAI API 開發 AI 系統

一起來練習吧!

使用 OpenAI API 開發 AI 系統

Preparing Video For Download...