taecontrol/openrouter-laravel-sdk
Composer 安装命令:
composer require taecontrol/openrouter-laravel-sdk
包简介
An OpenRouter SDK for Laravel
README 文档
README
A lightweight, expressive Laravel wrapper around the OpenRouter API built on top of the excellent Saloon HTTP client. It provides:
- Simple methods for text completions and chat completions (with optional streaming)
- Typed Data Objects for building requests and parsing responses
- Configurable base URI, API token and timeouts
- Support for reasoning & usage reporting parameters
Requirements
- PHP 8.2+
- Laravel 10 or 11
Installation
Install via Composer:
composer require taecontrol/openrouter-laravel-sdk
Publish the config (optional – only if you want to override defaults):
php artisan vendor:publish --tag="openrouter-laravel-sdk-config"
The published config file (config/openrouter-laravel-sdk.php):
return [ 'base_uri' => 'https://openrouter.ai/api/v1', 'token' => env('OPENROUTER_API_KEY', ''), 'connect_timeout' => 10, 'request_timeout' => 120, ];
Add your API key to .env:
OPENROUTER_API_KEY=sk-or-xxxxx
That's it. No migrations or views are shipped.
Quick Start
Use the facade:
use Taecontrol\OpenRouter\Facades\OpenRouter; use Taecontrol\OpenRouter\DataObjects\CompletionsData; $response = OpenRouter::completions( new CompletionsData( model: 'openai/gpt-3.5-turbo-instruct', prompt: 'Write a haiku about Laravel.' ) ); $text = $response->choices[0]->text; // string
Or resolve the class (easier to swap or test):
use Taecontrol\OpenRouter\OpenRouter as OpenRouterClient; use Taecontrol\OpenRouter\DataObjects\CompletionsData; $client = app(OpenRouterClient::class); $response = $client->completions(new CompletionsData( model: 'openai/gpt-3.5-turbo-instruct', prompt: 'Explain SOLID principles briefly.' ));
Chat Completions
use Taecontrol\OpenRouter\Facades\OpenRouter; use Taecontrol\OpenRouter\DataObjects\ChatCompletionsData; use Taecontrol\OpenRouter\DataObjects\ChatCompletionsMessageData; use Taecontrol\OpenRouter\Enums\Role; $data = new ChatCompletionsData( model: 'openai/gpt-4o-mini', messages: [ ChatCompletionsMessageData::from([ 'role' => Role::User, 'content' => 'Give me three Laravel testing tips.' ]), ], temperature: 0.7, ); $response = OpenRouter::chatCompletions($data); foreach ($response->choices as $choice) { $message = $choice->message; // ChatCompletionsMessageData echo $message->content . PHP_EOL; }
Streaming Chat Completions
Streams are returned as a PSR-7 StreamInterface. You can iterate chunks as they arrive (framework/event broadcasting omitted for brevity):
use Taecontrol\OpenRouter\Facades\OpenRouter; use Taecontrol\OpenRouter\DataObjects\ChatCompletionsData; use Taecontrol\OpenRouter\DataObjects\ChatCompletionsMessageData; use Taecontrol\OpenRouter\Enums\Role; $stream = OpenRouter::chatCompletionsStream( new ChatCompletionsData( model: 'openai/gpt-4o-mini', messages: [ ChatCompletionsMessageData::from([ 'role' => Role::User, 'content' => 'Stream a short motivational quote word by word.' ]), ], ) ); while (!$stream->eof()) { $chunk = $stream->read(1024); if ($chunk !== '') { echo $chunk; // Each SSE/data chunk from OpenRouter } }
Embeddings
You can generate embeddings for text using the embeddings method:
use Taecontrol\OpenRouter\Facades\OpenRouter; use Taecontrol\OpenRouter\DataObjects\EmbeddingsData; use Taecontrol\OpenRouter\Enums\EmbeddingEncodingFormat; $data = new EmbeddingsData( input: 'The quick brown fox jumps over the lazy dog', model: 'text-embedding-ada-002', encodingFormat: EmbeddingEncodingFormat::Float, // Optional: Float or Base64 ); $response = OpenRouter::embeddings($data); foreach ($response->data as $embeddingObject) { print_r($embeddingObject->embedding); // array of floats echo $embeddingObject->index; // int } // Usage statistics are also available echo $response->usage->totalTokens;
Request Data Objects
You construct strongly-typed request DTOs:
- CompletionsData(model, prompt, reasoningData?, usageData?, maxTokens?, temperature?, seed?, topP?, topK?, user?)
- ChatCompletionsData(model, messages[], reasoningData?, usageData?, maxTokens?, temperature?, seed?, topP?, topK?, user?)
- ChatCompletionsMessageData(role, content, refusal?, reasoning?, reasoningDetails[]?)
- EmbeddingsData(input, model, encodingFormat?, dimensions?, user?, provider?, inputType?)
- ReasoningData(effort: Effort|null, maxTokens: string|null, exclude: bool|null)
- UsageData(include: bool = false)
Optional Parameters
| Parameter | Purpose |
|---|---|
| temperature | Controls randomness (float) |
| max_tokens | Limit output tokens (int) |
| top_p | Nucleus sampling (float) |
| top_k | Limits token selection to top K (int) |
| seed | Determinism when supported (int) |
| user | End-user identifier string |
| reasoning | Structured reasoning controls (ReasoningData) |
| usage | Ask API to include usage breakdown (UsageData) |
Reasoning Effort Enum
Effort values come from Taecontrol\OpenRouter\Enums\Effort (e.g. Effort::Low, Effort::Medium, Effort::High).
Roles Enum
Use Taecontrol\OpenRouter\Enums\Role (e.g. Role::User, Role::Assistant, Role::System).
Responses
- CompletionsResponse(id, choices[] CompletionsChoicesData)
- ChatCompletionsResponse(id, choices[] ChatCompletionsChoiceData)
- EmbeddingsResponseData(object, data[] EmbeddingObjectData, model, usage?)
Each ChatCompletionsChoiceData wraps a ChatCompletionsMessageData (so you always look at $choice->message->content).
Dependency Injection / Custom Token
You can instantiate with a custom token (overrides config/env):
use Taecontrol\OpenRouter\OpenRouter; use Taecontrol\OpenRouter\DataObjects\CompletionsData; $client = new OpenRouter(token: 'sk-alt-token'); $response = $client->completions(new CompletionsData( model: 'openai/gpt-3.5-turbo-instruct', prompt: 'Custom token example.' ));
Timeouts
Configure in config/openrouter-laravel-sdk.php:
- connect_timeout (default 10s)
- request_timeout (default 120s)
Testing
A basic test suite is included (Pest). Run:
composer test
You can mock the underlying Saloon connector or stub methods on the OpenRouter class when testing your application.
Error Handling
All request methods may throw:
- Saloon\Exceptions\Request\RequestException (HTTP level problems)
- Saloon\Exceptions\Request\FatalRequestException (network/transport issues)
- \Throwable (in edge cases such as JSON decoding)
Wrap calls as needed:
try { $response = OpenRouter::completions(new CompletionsData( model: 'openai/gpt-3.5-turbo-instruct', prompt: 'Give me a tip.' )); } catch (\Throwable $e) { report($e); }
Roadmap / Ideas
- Add image generation endpoints when exposed
- Add tools/function calling support if OpenRouter standardizes schema
- Add automatic pagination helpers if needed
Contributing
Please see CONTRIBUTING for details.
Changelog
See CHANGELOG.
Security Vulnerabilities
Please review our security policy for reporting guidelines.
License
Released under the MIT License. See LICENSE.
taecontrol/openrouter-laravel-sdk 适用场景与选型建议
taecontrol/openrouter-laravel-sdk 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 693 次下载、GitHub Stars 达 2, 最近一次更新时间为 2025 年 09 月 18 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「laravel」 「taecontrol」 「openrouter-laravel-sdk」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 taecontrol/openrouter-laravel-sdk 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 taecontrol/openrouter-laravel-sdk 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 taecontrol/openrouter-laravel-sdk 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Alfabank REST API integration
Laravel package to communicate with Larastats
Build agentic apps
Laravel package for Accurate Online API integration.
Shared RCX Laravel DataTables UI and configuration helpers.
Boot a Laravel project on any machine with one command: app:serve installs missing tools (PHP, Node, Composer, Herd, Docker), creates .env, sets up the database, runs migrations, builds assets, starts a queue worker and serves via Herd, Sail or artisan serve; app:down cleanly stops everything it sta
统计信息
- 总下载量: 693
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 14
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-09-18