Define JSON schemas to receive structured, predictable responses from your AI agents instead of free-form text.
Structured output allows you to define a specific JSON schema that your AI responses must conform to, making it easier to integrate AI-generated content with your application logic.
You can define the response schema in your agent class using the $responseSchema property or add the structuredOutput method in your agent class for defining more complex schemas.
Pay attention to the required, additionalProperties, and strict properties. It’s recommended by OpenAI to set these when defining schemas to get exactly the structure you need.
For complex schemas, it’s recommended to use the structuredOutput() method instead of the property, as it provides more flexibility and can include dynamic logic.
Using trait with structuredOutput() method is a good practice to avoid code duplication and make your code more maintainable.
The schema can be accessed using the structuredOutput() method:
Copy
// Get current schema$schema = $agent->structuredOutput();// Check if structured output is enabledif ($agent->structuredOutput()) { // Handle structured response}
Do include descriptive property descriptions to guide the AI
Do set additionalProperties to false when you want to restrict the output to only the defined properties
Don’t create overly complex (Deeply Nested) schemas that the AI might struggle to fulfillDon’t forget to set the required property for fields that must be present