Get a dictionary as an structured output with response_format. #2304
-
|
Hi, im trying to create and agent to assign and amount of days to a country. The agent recieved a list of countries and the expected output is something like: {
"country1": days,
"country2": days,
"country3": days,
...
}I made this Pydantic model: class DaysPerCountry(BaseModel): But when i run the agent i got this error: agent_framework.exceptions.ServiceResponseException: <class 'agent_framework.openai._chat_client.OpenAIChatClient'> service failed to complete the prompt: Error code: 400 - {'error': {'message': "Invalid schema for response_format 'DaysPerCountry': In context=(), 'required' is required to be supplied and to be an array including every key in properties. Extra required key 'days_per_country' supplied.", 'type': 'invalid_request_error', 'param': 'response_format', 'code': None}} How can i get this dictionary as a result? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Hi @Antonio-ISA, OpenAI’s structured output format does not support free-form dictionaries because it requires a schema with explicitly defined keys and no unbounded additional properties. You will need to model your data using one or more fixed schema objects tailored to the structure you expect. Here's a working example: # Copyright (c) Microsoft. All rights reserved.
import asyncio
from agent_framework.openai import OpenAIResponsesClient
from pydantic import BaseModel, Field
"""
OpenAI Responses Client with Dictionary-like Structured Output Example
This sample demonstrates how to work around OpenAI's structured output limitations
when you need dictionary-like results. Instead of using Dict[str, int] directly
(which causes validation errors), we use a list of key-value pairs.
"""
class CountryDays(BaseModel):
"""A single country with assigned days."""
country: str = Field(description="The name of the country")
days: int = Field(description="Number of days assigned to this country")
class DaysPerCountry(BaseModel):
"""Assignment of days to multiple countries."""
assignments: list[CountryDays] = Field(description="List of countries with their assigned days")
def to_dict(self) -> dict[str, int]:
"""Convert the list structure to a dictionary for easier access."""
return {assignment.country: assignment.days for assignment in self.assignments}
async def main() -> None:
print("=== OpenAI Responses Agent with Dictionary-like Output ===\n")
# Create an OpenAI Responses agent
# Feel free to use any client based on your needs
agent = OpenAIResponsesClient().create_agent(
name="TravelPlannerAgent",
instructions=(
"You are a travel planning assistant. When given a list of countries, "
"assign a reasonable number of days to visit each country based on "
"the country's size, number of attractions, and typical tourist itineraries."
),
)
# List of countries to assign days to
countries = ["France", "Belgium", "Netherlands", "Germany", "Switzerland"]
query = f"Assign days for visiting these countries: {', '.join(countries)}"
print(f"User: {query}\n")
# Get structured response from the agent
result = await agent.run(query, response_format=DaysPerCountry)
# Different ways to access the response
print("=== Understanding the Response ===\n")
print(f"result.value type: {type(result.value)}")
print(f"result.value is a DaysPerCountry instance: {isinstance(result.value, DaysPerCountry)}")
print(f"\nresult.text (string representation):\n{result.text}\n")
# Access the structured output
if result.value:
structured_data: DaysPerCountry = result.value # type: ignore
print("Structured Output (as list):")
for assignment in structured_data.assignments:
print(f" {assignment.country}: {assignment.days} days")
print("\nConverted to dictionary:")
days_dict = structured_data.to_dict()
print(f" {days_dict}")
print("\nAccess individual values:")
for country in countries:
if country in days_dict:
print(f" {country}: {days_dict[country]} days")
else:
print("Error: No structured data found in result.value")
if __name__ == "__main__":
asyncio.run(main())with the following output: |
Beta Was this translation helpful? Give feedback.
Hi @Antonio-ISA, OpenAI’s structured output format does not support free-form dictionaries because it requires a schema with explicitly defined keys and no unbounded additional properties. You will need to model your data using one or more fixed schema objects tailored to the structure you expect.
Here's a working example: