You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classSpeedingTicket(BaseModel):
""" You are processing speeding tickets at the service center and expected to extract the data for the defined fields """license_plate: str|None=Field(
description="The license plate number of the speeding vehicle."
)
location: str|None=Field(
description="The address/location where the speeding took place"
)
speed: int|None=Field(description="The recorded speed of the vehicle.")
In addition, I have the following speeding ticket:
And I get the expected result, namely: license_plate='B-1234XYZ' location='A100, Berlin, Germany' speed=110
However, if I modify the model to (note the added date field):
classSpeedingTicket(BaseModel):
""" You are processing speeding tickets at the service center and expected to extract the data for the defined fields """license_plate: str|None=Field(
description="The license plate number of the speeding vehicle."
)
location: str|None=Field(
description="The address/location where the speeding took place"
)
ticket_date: date|None=Field(description="The date of the ticket issuing.")
speed: int|None=Field(description="The recorded speed of the vehicle.")
and execute the same call, I get the following error:
InstructorRetryException: Error code: 400 - {'error': {'message': "Invalid schema for function 'SpeedingTicket': In context=('properties', 'ticket_date', 'anyOf', '0'), 'format' is not permitted.", 'type': 'invalid_request_error', 'param': 'tools[0].function.parameters', 'code': 'invalid_function_parameters'}}
How this small and rather reasonable change break the call? Thanks in advance!
The text was updated successfully, but these errors were encountered:
The issue occurs because OpenAI's API schema validation doesn't directly support Python's date or datetime types. Here's the explanation and solution:
Root Cause
OpenAI's API schema validation only supports a limited set of JSON Schema types
The date type in Pydantic includes a format validator that's not supported by OpenAI
The API expects ISO format strings for dates
Solution
Use string type for the API communication while maintaining proper date validation internally. Here's the fixed implementation:
fromdatetimeimportdatefrompydanticimportBaseModel, Field, validatorfromtypingimportOptionalclassSpeedingTicket(BaseModel):
""" You are processing speeding tickets at the service center and expected to extract the data for the defined fields """license_plate: Optional[str] =Field(
description="The license plate number of the speeding vehicle."
)
location: Optional[str] =Field(
description="The address/location where the speeding took place"
)
ticket_date: Optional[str] =Field(
description="The date of the ticket issuing in ISO format (YYYY-MM-DD)."
)
speed: Optional[int] =Field(description="The recorded speed of the vehicle.")
@validator('ticket_date', pre=True)defvalidate_date(cls, value):
ifvalueisNone:
returnNoneifisinstance(value, date):
returnvalue.isoformat()
try:
# Validate and ensure ISO formatreturndate.fromisoformat(value).isoformat()
exceptValueError:
raiseValueError("Date must be in ISO format (YYYY-MM-DD)")
defget_date_object(self) ->Optional[date]:
"""Helper method to get the date as a date object"""returndate.fromisoformat(self.ticket_date) ifself.ticket_dateelseNone
Usage Example
result=client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": ticket,
}
],
response_model=SpeedingTicket,
)
# Access the date as a stringprint(result.ticket_date) # Output: "2025-01-20"# Access the date as a date objectprint(result.get_date_object()) # Output: datetime.date(2025, 1, 20)
Key Benefits
Works with OpenAI's API constraints
Maintains type safety and validation
Provides easy conversion to date objects when needed
Ensures consistent ISO format for dates
This solution should resolve the InstructorRetryException while maintaining proper date handling. Hope this helps!
I start with the following model:
In addition, I have the following speeding ticket:
Lastly, I run:
And I get the expected result, namely:
license_plate='B-1234XYZ' location='A100, Berlin, Germany' speed=110
However, if I modify the model to (note the added
date
field):and execute the same call, I get the following error:
How this small and rather reasonable change break the call? Thanks in advance!
The text was updated successfully, but these errors were encountered: