Làm việc với OpenAI Responses API
James Chapman
AI Curriculum Manager, DataCamp




from pydantic import BaseModelclass QuizResult(BaseModel): score: int passed: bool feedback: str
from pydantic import BaseModel, Field
class QuizResult(BaseModel):
score: int = Field(description="Số câu đúng trên 10")
passed: bool = Field(description="True nếu điểm từ 7 trở lên")
feedback: str = Field(
description="Thông điệp khích lệ kèm mẹo cải thiện cụ thể"
)
response = client.responses.parse(model="gpt-5.4-mini",instructions="Bạn là gia sư từ vựng tiếng Tây Ban Nha. Chấm bài trắc nghiệm của học viên. Mỗi câu đúng được 2 điểm.", input="""1. casa = house 2. perro = dog 3. gato = car 4. libro = book 5. agua = water""",text_format=QuizResult)
result = response.output_parsedprint(f"Score: {result.score}/10") print(f"Passed: {result.passed}") print(f"Feedback: {result.feedback}")
Score: 8/10
Passed: True
Feedback: Làm tốt lắm - bạn đạt 8/10 (đúng 4/5). Lỗi duy nhất là #3: 'gato'
nghĩa là 'cat', không phải 'car' (tiếng Tây Ban Nha cho 'car' là 'coche' hoặc 'carro'). Mẹo: ôn từ vựng về động vật bằng flashcard và các bài kiểm tra ngắn để củng cố ghi nhớ.
class Mistake(BaseModel): word: str = Field(description="Từ tiếng Tây Ban Nha bị sai") student_answer: str = Field(description="Học viên đã viết gì") correct_answer: str = Field(description="Bản dịch đúng")class DetailedQuizResult(BaseModel): score: int = Field(description="Số câu đúng trên 10") passed: bool = Field(description="True nếu điểm từ 7 trở lên") feedback: str = Field(description="Thông điệp khích lệ kèm mẹo cụ thể")mistakes: list[Mistake] = Field(description="Danh sách các câu sai")
response = client.responses.parse( model="gpt-5.4-mini", instructions="Bạn là gia sư từ vựng tiếng Tây Ban Nha. Chấm bài trắc nghiệm của học viên. Mỗi câu đúng được 2 điểm.", input="""1. casa = house 2. perro = dog 3. gato = car 4. libro = library 5. agua = water""",text_format=DetailedQuizResult)
result = response.output_parsed print(f"Score: {result.score}/10") print(f"Passed: {result.passed}")for mistake in result.mistakes: print(f"{mistake.word}: '{mistake.student_answer}' -> '{mistake.correct_answer}'")
Score: 6/10
Passed: False
gato: 'car' -> 'cat'
libro: 'library' -> 'book'
from pydantic import BaseModel, Field
class QuizResult(BaseModel):
score: int = Field(...)
passed: bool = Field(...)
feedback: str = Field(...)
result = response.output_parsed
print(f"Score: {result.score}/10")
print(f"Passed: {result.passed}")
print(f"Feedback: {result.feedback}")
response = client.responses.parse( model="gpt-5.4-mini", instructions="...", input="...",text_format=QuizResult)
Làm việc với OpenAI Responses API