PHP code example of sferra / delta

1. Go to this page and download the library: Download sferra/delta library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sferra / delta example snippets


use Sferra\Delta\Facades\Delta;

$response = Delta::using(
    url: 'http://localhost:8642/v1/chat/completions',
    key: 'my-key',
    model: 'hermes-agent'
)->stream(
    messages: [['role' => 'user', 'content' => 'What is PHP?']],
    onChunk: fn(string $chunk) => echo $chunk  // real-time streaming
);

use Sferra\Delta\DeltaClient;

$client = new DeltaClient(
    url: 'https://api.openai.com/v1/chat/completions',
    key: 'sk-...',
    model: 'gpt-4'
);

$response = $client->stream(
    messages: [['role' => 'user', 'content' => 'Hello!']]
);

echo $response; // complete response

use Sferra\Delta\Facades\Delta;

$shouldCancel = false;

$response = Delta::stream(
    messages: [['role' => 'user', 'content' => 'Tell me a long story.']],
    onChunk: fn(string $chunk) => echo $chunk,
    shouldCancel: fn () => $shouldCancel
);

// Later, from another part of the app (e.g. a Livewire cancel button):
$shouldCancel = true;

// SideChat.php (Livewire component)
public bool $shouldCancel = false;

public function cancelStream(): void
{
    $this->shouldCancel = true;
}

#[On('sendToAI')]
public function streamToAI(): void
{
    $this->shouldCancel = false;

    Delta::stream(
        messages: $this->messages,
        onChunk: fn (string $chunk) => $this->stream('response', $chunk),
        shouldCancel: fn () => $this->shouldCancel
    );
}
bash
php artisan vendor:publish --tag=delta-config