Skip to content

Using structured data as an input

Overview

Instructor offers a way to use structured data as an input. This is useful when you want to use object data as input and get another object with a result of LLM inference.

The input field of Instructor's create() method can be an object, but also an array or just a string.

Example

<?php
require 'examples/boot.php';

use Cognesy\Instructor\StructuredOutput;

class Email {
    public function __construct(
        public string $address = '',
        public string $subject = '',
        public string $body = '',
    ) {}
}

$email = new Email(
    address: 'joe@gmail.com',
    subject: 'Status update',
    body: 'Your account has been updated.'
);

$translatedEmail = StructuredOutput::using('openai')
    ->withInput($email)
    ->withResponseClass(Email::class)
    ->withPrompt('Return an Email object. Copy the address field exactly as provided. Translate only the subject and body fields to natural Spanish.')
    ->withModel('gpt-4o-mini')
    ->withOptions(['temperature' => 0])
    ->get();

print_r($translatedEmail);

if ($translatedEmail->address !== $email->address) {
    echo "ERROR: Address was modified during translation\n";
    exit(1);
}
if ($translatedEmail->subject === $email->subject) {
    echo "ERROR: Subject was not translated\n";
    exit(1);
}
if ($translatedEmail->body === $email->body) {
    echo "ERROR: Body was not translated\n";
    exit(1);
}
?>