premieroctet/php-stream-protocol
Composer 安装命令:
composer require premieroctet/php-stream-protocol
包简介
A PHP library for handling AI streaming protocols, particularly the Vercel AI SDK Stream Protocol
关键字:
README 文档
README
A PHP library for handling the Vercel AI SDK Stream Protocol. This package provides an easy-to-use interface for creating streaming AI responses with support for tool calls, attachments, and various AI providers.
Features
- 🚀 Easy Integration: Simple, fluent API for streaming responses
- 🔧 Tool Support: Built-in tool calling and execution
- 📎 Attachments: Handle file and image attachments
- 🔄 Multi-Provider: Support for OpenAI and other providers
- 📊 Protocol Compliant: Follows Vercel AI SDK Stream Protocol specifications
- ⚡ Symfony Integration: Built with Symfony components
Installation
composer require premieroctet/php-stream-protocol
Quick Start
Basic Usage
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); }
Symfony Usage
<?php 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(new WeatherTool()); } #[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'); } }
Advanced Usage with Custom Tools
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"]; } }
Message Conversion
// Convert messages to different AI provider formats $messages = $protocol->parseMessages($jsonData); // For OpenAI $openaiMessages = $protocol->convertToOpenAI($messages);
Simple Text Streaming (for testing)
public function demo(): Response { $protocol = StreamProtocol::create(); return $protocol->streamText( 'This is a demo of streaming text word by word.', 50 // delay in milliseconds ); }
Message Format
The library handles messages in the Vercel AI SDK format, supporting:
- Text messages: Simple text content
- Tool calls: Function calling with arguments and results
- Attachments: File and image attachments
- Message parts: Complex message structures
Example message structure:
{
"messages": [
{
"role": "user",
"content": "What's the weather like?",
"experimental_attachments": [
{
"contentType": "image/jpeg",
"url": "data:image/jpeg;base64,..."
}
]
},
{
"role": "assistant",
"content": "",
"toolInvocations": [
{
"toolCallId": "call_123",
"toolName": "get_weather",
"args": { "location": "New York" },
"result": { "temperature": "25°C", "condition": "sunny" }
}
]
}
]
}
Stream Protocol
The library implements the Vercel AI SDK Stream Protocol with the following message types:
0:- Text content9:- Tool calla:- Tool resultb:- Tool call streaming startc:- Tool call deltad:- Finish messagee:- Finish stepf:- Message start
Tool Integration
Tools must follow this interface:
class WeatherTool implements ToolInterface { public function getName(): string { return 'get_current_weather'; } public function getDescription(): string { return 'Get current weather for a location'; } public function execute(array $parameters): mixed { return [ 'location' => $parameters['location'], 'temperature' => '25°C', 'condition' => 'sunny' ]; } public function getParameters(): array { return [ 'type' => 'object', 'properties' => [ 'location' => [ 'type' => 'string', 'description' => 'The city and state, e.g. San Francisco, CA' ] ], 'required' => ['location'] ]; } public function isStrict(): bool { return true; } }
Requirements
- PHP 8.1 or higher
- Symfony HttpFoundation component
License
MIT License - see LICENSE file for details.
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
premieroctet/php-stream-protocol 适用场景与选型建议
premieroctet/php-stream-protocol 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.62k 次下载、GitHub Stars 达 3, 最近一次更新时间为 2025 年 06 月 25 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「streaming」 「protocol」 「ai」 「openai」 「vercel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 premieroctet/php-stream-protocol 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 premieroctet/php-stream-protocol 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 premieroctet/php-stream-protocol 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A small client implementing the Measurement Protocol for Google Analytics 4.
PHP 8.0+ OpenAI API client with fully typed/documented requests+responses models, guzzle and symfony/http-client support and async/parallel requests.
A laravel bundle for the OpenTok PHP SDK
Yii2 Extension for sending push notification with both Firebase Cloud Messaging (FCM) HTTP Server Protocols (APIs).
Laravel Wrapper for the OpenTok PHP SDK
A robust, configuration-driven ETL and data import framework for Laravel. Handles CSV/Excel streaming, queues, validation, and relationships.
统计信息
- 总下载量: 1.62k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 3
- 点击次数: 25
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-06-25