開始使用免費開始

每次都產生一致的輸出!

你正在為一個串流平台開發個人化的電影推薦系統。為了讓推薦結果可以正確顯示在應用程式的 UI 中,你需要搭配 pydanticOpenAI 用結構化輸出。你會定義一個電影推薦的結構(schema),並擷取結構化的結果。

本練習屬於課程

使用 OpenAI Responses API

檢視課程

練習說明

  • 定義一個名為 MovieRecommendationpydantic 類別,包含 titlegenrevibewhy 欄位。
  • 使用 MovieRecommendation 類別與提供的提示詞產生結構化的推薦結果。
  • 從回應中擷取解析後的推薦結果,然後讀取其中的 titlewhy 資訊。

動手互動練習

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

# Define the book recommendation schema
class ____(BaseModel):
    ____: str = Field(description="The book title")
    ____: str = Field(description="Primary genre")
    ____: str = Field(description="One-word vibe: cozy, thrilling, emotional, or fun")
    ____: str = Field(description="One sentence explaining why this matches")

# Generate structured recommendation
response = client.responses.____(
    model="gpt-5.4-mini",
    instructions="You are a knowledgeable movie recommender.",
    input="Recommend a movie for someone who loved Inception and wants something mind-bending",
    text_format=____,
)

# Extract the parsed output and results
recommendation = response.____
print(f"Title: {recommendation.____}")
print(f"Reason: {recommendation.____}")
編輯並執行程式碼