PHP code example of premieroctet / php-stream-protocol

1. Go to this page and download the library: Download premieroctet/php-stream-protocol 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/ */

    

premieroctet / php-stream-protocol example snippets


use PremierOctet\PhpStreamProtocol\StreamProtocol;
use OpenAI;

// Create a new StreamProtocol instance
$protocol = StreamProtocol::create()
    ->withSystemPrompt('You are a helpful assistant.');

// Register tools
$protocol->registerTool('get_weather', [WeatherService::class, 'getCurrentWeather']);

// In your controller
public function chat(Request $request): Response
{
    // Parse incoming messages
    $messages = $protocol->parseMessages($request->getContent());

    // Convert to OpenAI format and create request
    $openaiRequest = $protocol->buildOpenAIRequest($messages, 'gpt-4');

    // Create OpenAI stream
    $client = OpenAI::client($apiKey);
    $stream = $client->chat()->createStreamed($openaiRequest);

    // Return streaming response
    return $protocol->stream($stream);
}



namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use PremierOctet\PhpStreamProtocol\StreamProtocol;
use App\Tools\WeatherTool;
use OpenAI;


class ChatController extends AbstractController
{
    private StreamProtocol $streamProtocol;

    public function __construct()
    {
        $this->streamProtocol = StreamProtocol::create()
            ->withSystemPrompt('You are a demo assistant showcasing the integration of Vercel AI SDK with a Symfony controller.')
            ->registerTool('get_current_weather', [WeatherTool::class, 'getCurrentWeather']);
    }

    #[Route('/api/chat', name: 'api_chat', methods: ['POST'])]
    public function chat(Request $request): Response
    {
        return $this->streamProtocol->handleRequest(
            $request->getContent(),
            function(array $openaiMessages) {
                $client = OpenAI::client($_ENV['OPENAI_API_KEY']);
                return $client->chat()->createStreamed([
                    'model' => 'gpt-4',
                    'messages' => $openaiMessages,
                    'stream' => true,
                    'tools' => [WeatherTool::getToolDefinition()],
                ]);
            },
        );
    }

    #[Route('/chat', name: 'chat')]
    public function chatPage(): Response
    {
        return $this->render('chat.html.twig');
    }
}


use PremierOctet\PhpStreamProtocol\StreamProtocol;

class ChatController
{
    public function chat(Request $request): Response
    {
        $protocol = StreamProtocol::create()
            ->withSystemPrompt('You are a helpful assistant with access to various tools.')
            ->registerTool('search_web', [$this, 'searchWeb'])
            ->registerTool('get_weather', [$this, 'getWeather'])
            ->registerTool('send_email', [$this, 'sendEmail']);

        return $protocol->handleRequest(
            $request->getContent(),
            function($messages) use ($request) {
                $client = OpenAI::client(env('OPENAI_API_KEY'));
                return $client->chat()->createStreamed([
                    'model' => 'gpt-4',
                    'messages' => $messages,
                    'stream' => true,
                    'tools' => $protocol->getToolDefinitions(),
                ]);
            }
        );
    }

    private function searchWeb(string $query): array
    {
        // Your web search implementation
        return ['results' => "Search results for: {$query}"];
    }

    private function getWeather(string $location): array
    {
        // Your weather service implementation
        return ['weather' => "Weather in {$location}: Sunny, 25°C"];
    }
}

// Convert messages to different AI provider formats
$messages = $protocol->parseMessages($jsonData);

// For OpenAI
$openaiMessages = $protocol->convertToOpenAI($messages);

// For Anthropic Claude
$anthropicData = $protocol->convertToAnthropic($messages);

public function demo(): Response
{
    $protocol = StreamProtocol::create();

    return $protocol->streamText(
        'This is a demo of streaming text word by word.',
        50 // delay in milliseconds
    );
}

class WeatherTool
{
    public static function getCurrentWeather(string $location): array
    {
        // Your implementation
        return [
            'location' => $location,
            'temperature' => '25°C',
            'condition' => 'sunny'
        ];
    }

    public static function getToolDefinition(): array
    {
        return [
            'type' => 'function',
            'function' => [
                'name' => 'get_current_weather',
                'description' => 'Get current weather for a location',
                'parameters' => [
                    'type' => 'object',
                    'properties' => [
                        'location' => [
                            'type' => 'string',
                            'description' => 'The city and state, e.g. San Francisco, CA'
                        ]
                    ],
                    '