<?php
$text = <<<TEXT
Jason is 25 years old, he is an engineer and tech lead. He lives in
San Francisco. He likes to play soccer and climb mountains.
TEXT;
$system = 'You are a precise structured data extraction assistant for JSON output. '
. 'Copy values exactly from the source text. '
. 'Do not omit explicitly stated person names.';
$prompt = 'Extract one user profile from the text as JSON. '
. 'Always fill name, age, location, roles, and hobbies when the source text provides them. '
. 'Use the exact person name from the text.';
$stream = (new StructuredOutput(
StructuredOutputRuntime::fromProvider(LLMProvider::using('openai'))
->withConfig(new StructuredOutputConfig(
responseCachePolicy: ResponseCachePolicy::None, // use Memory if you need replay
))
->withOutputMode(OutputMode::Json)
))->with(
messages: $text,
responseModel: UserDetail::class,
system: $system,
prompt: $prompt,
)
->withStreaming()
->stream();
$partials = [];
foreach ($stream->partials() as $partial) {
// Streams are one-shot by default. Keep updates if you need to inspect them later.
$partials[] = $partial;
partialUpdate($partial);
}
$user = $stream->finalValue();
exitPartialScreen();
echo "All tokens received, fully completed object available in `\$user` variable.\n";
echo '$user = '."\n";
dump($user);
assert(!empty($user->roles));
assert(!empty($user->hobbies));
assert($user->location === 'San Francisco');
assert($user->age == 25);
assert($user->name === 'Jason');
?>