Skip to content

Structured Output

The LabsLLM allows you to define structured output schemas for your prompts, ensuring that the model's response follows a specific format.

Defining Output Schema

You can define an output schema using the same parameter types used for function definitions:

php
use LabsLLM\Parameters\ObjectParameter;
use LabsLLM\Parameters\StringParameter;
use LabsLLM\Parameters\NumberParameter;
use LabsLLM\Parameters\ArrayParameter;
use LabsLLM\Parameters\BooleanParameter;

// Define a simple structured output for a product review
$structureObject = new ObjectParameter('review', 'Product review data', [
    new StringParameter('title', 'Title of the review'),
    new NumberParameter('rating', 'Rating from 1 to 5'),
    new StringParameter('comment', 'Detailed review comment'),
    new ArrayParameter('tags', 'Review tags', 
        new StringParameter('tag', 'A single tag')
    ),
    new BooleanParameter('recommended', 'Whether the product is recommended')
], ['title', 'rating', 'comment']);

// Use the schema in your prompt
$execute = LabsLLM::text()
    ->using(new OpenAI('your-api-key', 'gpt-4'))
    ->withOutputSchema($structureObject)
    ->executePrompt('Write a review for the latest iPhone model');

$response = $execute->getResponseData();

Response Format

When using structured output, you can get the structured response using getStructureResponse():

php
// Get the structured response object
$reviewData = $response->getStructureResponse();

echo $reviewData->title;     // "Amazing iPhone Experience"
echo $reviewData->rating;    // 5
echo $reviewData->comment;   // "The new iPhone exceeded all my expectations..."

// Accessing array properties
foreach ($reviewData->tags as $tag) {
    echo $tag->tag;         // "battery", "camera", etc.
}

// Accessing boolean properties
if ($reviewData->recommended) {
    echo "This product is recommended!";
}

Best Practices

  1. Keep schemas simple: Start with basic structures and add complexity as needed
  2. Use clear field names: Choose descriptive names that clearly indicate the purpose of each field
  3. Validate responses: Always validate the JSON response matches your expected structure
  4. Handle errors: Be prepared to handle cases where the model might not follow the schema exactly

Important: While the model will try to follow your schema, it's important to validate the response as the model might occasionally deviate from the exact structure you defined.

Released under the MIT License.