Streaming
Presenting AI response to your user in real-time.
Last updated
use App\Neuron\MyAgent;
use NeuronAI\Chat\Messages\UserMessage;
$stream = MyAgent::make()->stream(
new UserMessage('How are you?')
);
// Print the response chunk-by-chunk in real-time
foreach ($stream as $text) {
echo $text;
}
// I'm fine, thank you! How can I assist you today?use App\Neuron\MyAgent;
use NeuronAI\Chat\Messages\UserMessage;
use NeuronAI\Tools\Tool;
$stream = MyAgent::make()
->addTool(
Tool::make(
'get_server_configuration',
'retrieve the server network configuration'
)->addProperty(...)->setCallable(...)
)
->stream(
new UserMessage("What's the IP address of the server?")
);
// Iterate chunks
foreach ($stream as $chunk) {
if ($chunk instanceof ToolCallMessage) {
// Output the ongoing tool call
echo PHP_EOL.\array_reduce(
$chunk->getTools(),
fn(string $carry, ToolInterface $tool)
=> $carry .= '- Calling tool: '.$tool->getName().PHP_EOL,
'');
} else {
echo $chunk;
}
}
// Let me retrieve the server configuration.
// - Calling tool: get_server_configuration
// The IP address of the server is: 192.168.0.10INSPECTOR_INGESTION_KEY=nwse877auxxxxxxxxxxxxxxxxxxxxxxxxxxxx