Đầu ra nhất quán, mọi lúc!
Bạn đang phát triển hệ thống gợi ý phim cá nhân hóa cho một nền tảng streaming. Để đảm bảo đề xuất được hiển thị đúng trong UI của ứng dụng, bạn cần dùng đầu ra có cấu trúc với pydantic và client OpenAI. Bạn sẽ định nghĩa một schema cho đề xuất phim và trích xuất kết quả đã được cấu trúc.
Bài tập này là một phần của khóa học
Làm việc với OpenAI Responses API
Hướng dẫn bài tập
- Định nghĩa một lớp
pydantictênMovieRecommendationvới các trườngtitle,genre,vibe, vàwhy. - Tạo một đề xuất có cấu trúc bằng cách dùng lớp
MovieRecommendationvà các prompt đã cung cấp. - Trích xuất đề xuất đã được parse từ phản hồi, rồi truy cập thông tin
titlevàwhycủa nó.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# 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-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.____}")