將模型回應格式化為 JSON
身為一名為新書建檔的圖書館員,你希望利用 OpenAI API,將同事提供的文字筆記自動轉換為 JSON 檔案。你的工作是擷取書名與作者等相關資訊。為此,你會使用 OpenAI API 把包含書名與作者的文字筆記,轉換成結構化的 JSON 檔案。
在本題以及後續所有練習中,openai 函式庫都已經載入。在本課程中,你不需要輸入自己的 API 金鑰就能建立請求並完成練習;但如果你偏好自行提供也可以。
本練習屬於課程
使用 OpenAI API 開發 AI 系統
練習說明
- 建立一個 OpenAI API 用戶端。
- 建立一個傳送至 Chat Completions 端點的請求。
- 指定此請求應使用
json_object回應格式。 - 擷取並列印模型回應。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create the OpenAI client
client = ____(api_key="")
# Create the request
response = ____(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "I have these notes with book titles and authors: New releases this week! The Beholders by Hester Musson, The Mystery Guest by Nita Prose. Please organize the titles and authors in a json file."}
],
# Specify the response format
____
)
# Print the response
print(____)