debjit/php-ai-hub
Composer 安装命令:
composer require debjit/php-ai-hub
包简介
AI HTTP Service Installer (no-SDK) for Laravel: copy/paste provider stubs via Composer plugin events with JSON registry.
README 文档
README
A lightweight Laravel package that provides a unified way to call AI providers (like OpenAI and Anthropic) using simple HTTP connectors and provider stubs — no vendor SDKs required.
This package focuses on:
- Simple configuration per provider
- Minimal surface area to call common AI endpoints (e.g., chat/completions)
- Extensibility to add new providers without pulling their full SDKs
Requirements
- PHP 8.2+
- Laravel 10 or 11
- Composer
Installation
composer require debjit/php-ai-hub
Laravel package discovery should auto-register the service provider.
Publish Configuration
php artisan vendor:publish --provider="Debjit\PhpAiHub\Installer" --tag=ai-hub-config
This will publish:
config/ai-hub.php— main hub configconfig/ai-hub/openai.php— OpenAI-specific configconfig/ai-hub/anthropic.php— Anthropic-specific config
If these files already exist, review and merge as needed.
Environment Variables
Set the required keys for the providers you intend to use.
OpenAI:
OPENAI_API_KEY=sk-...
OPENAI_BASE_URL=https://api.openai.com
OPENAI_ORG_ID=org_...(optional)
OPENAI_PROJECT_ID=proj_...(optional)
Anthropic:
ANTHROPIC_API_KEY=sk-ant-...
ANTHROPIC_BASE_URL=https://api.anthropic.com
ANTHROPIC_VERSION=2023-06-01
You can override the base URLs to route through proxies/gateways if needed.
Configuration Overview
Main hub configuration: config/ai-hub.php
- Controls default provider and maps provider identifiers to resolver classes and stub implementations.
Example (high-level):
return [ 'default' => env('AI_HUB_DEFAULT_PROVIDER', 'openai'), 'providers' => [ 'openai' => [ 'config' => base_path('config/ai-hub/openai.php'), 'provider' => \Debjit\PhpAiHub\Stubs\OpenAI\Provider::class, ], 'anthropic' => [ 'config' => base_path('config/ai-hub/anthropic.php'), 'provider' => \Debjit\PhpAiHub\Stubs\Anthropic\Provider::class, ], ], ];
Per-provider configuration:
config/ai-hub/openai.phpcontains base URL, auth header strategy, default model, timeouts, etc.config/ai-hub/anthropic.phpcontains base URL, version header, default model, timeouts, etc.
How config is resolved:
Debjit\PhpAiHub\Support\ConfigResolverreads the main hub config, then loads the targeted provider config file.- Environment variables are read via Laravel
env()in those configs. - Missing or invalid configurations will throw descriptive exceptions early.
Core Concepts
- Registry:
Debjit\PhpAiHub\Registry- Entry point to get a provider instance by key (e.g., "openai", "anthropic") or the default.
- Provider Stub:
Debjit\PhpAiHub\Stubs\{Provider}\Provider- Facade-like API that exposes high-level operations (e.g., chat).
- Client/Connector:
Debjit\PhpAiHub\Stubs\{Provider}\Connectors\HttpConnector- Responsible for HTTP requests to the provider with proper headers, endpoints, and payload shape.
You don’t install SDKs for each provider: we model the minimal HTTP required.
Quick Start
Resolve the default provider (configured via AI_HUB_DEFAULT_PROVIDER or config/ai-hub.php):
use Debjit\PhpAiHub\Registry; $provider = app(Registry::class)->provider(); // default from config
Or explicitly:
$openai = app(Registry::class)->provider('openai'); $anthropic = app(Registry::class)->provider('anthropic');
Example: OpenAI Chat Completion
use Debjit\PhpAiHub\Registry; $openai = app(Registry::class)->provider('openai'); $response = $openai->chat()->create([ 'model' => 'gpt-4o-mini', 'messages' => [ ['role' => 'system', 'content' => 'You are a helpful assistant.'], ['role' => 'user', 'content' => 'Write a haiku about Laravel.'], ], 'temperature' => 0.7, ]); $content = $response['choices'][0]['message']['content'] ?? null;
Notes:
- The stub normalizes the request to OpenAI’s
/v1/chat/completions. - Auth header
Authorization: Bearer {OPENAI_API_KEY}is added by the connector.
Example: Anthropic Messages
use Debjit\PhpAiHub\Registry; $anthropic = app(Registry::class)->provider('anthropic'); $response = $anthropic->chat()->create([ 'model' => 'claude-3-5-sonnet-20240620', 'messages' => [ ['role' => 'user', 'content' => 'Summarize Laravel service providers.'], ], 'max_tokens' => 512, ]); $content = $response['content'][0]['text'] ?? null;
Notes:
- The stub targets Anthropic’s
/v1/messageswith headers:x-api-key: {ANTHROPIC_API_KEY}anthropic-version: {ANTHROPIC_VERSION}
Streaming (if supported)
If a provider supports streaming, the stub may expose a streaming method:
$stream = $openai->chat()->stream([ 'model' => 'gpt-4o-mini', 'messages' => [/*...*/], ]); foreach ($stream as $event) { // handle tokens/chunks }
Refer to the specific provider stub for supported features.
Service Container Usage
You can type-hint the registry wherever needed:
use Debjit\PhpAiHub\Registry; class MyController { public function __construct(private Registry $registry) {} public function __invoke() { $ai = $this->registry->provider(); // default // ... } }
Adding a New Provider
-
Create a provider config:
config/ai-hub/{provider}.php- Base URL, auth headers, defaults, timeouts/retries.
-
Implement a connector:
- Example:
src/Stubs/FooAI/Connectors/HttpConnector.php - Use Laravel HTTP client, apply headers and base URL from config.
- Provide methods like
chatCompletions(array $payload): array.
- Example:
-
Implement a provider stub:
- Example:
src/Stubs/FooAI/Provider.php - Expose simplified methods, like
chat()->create($payload)that internally calls the connector. - Keep the public API consistent with existing providers when possible.
- Example:
-
Register in main config:
- In
config/ai-hub.phpadd the mapping:'providers' => [ // ... 'fooai' => [ 'config' => base_path('config/ai-hub/fooai.php'), 'provider' => \Debjit\PhpAiHub\Stubs\FooAI\Provider::class, ], ],
- In
-
Use it:
$foo = app(\Debjit\PhpAiHub\Registry::class)->provider('fooai'); $foo->chat()->create([...]);
Guidelines:
- Do not use the provider’s official SDK. Prefer HTTP with minimal dependencies.
- Normalize payloads where possible to keep your app code portable between providers.
Error Handling & Troubleshooting
-
Missing API key or base URL
- Ensure
.envvariables are set and the provider config reads them viaenv().
- Ensure
-
Invalid provider key
- Confirm the provider key exists in
config/ai-hub.phpunderproviders.
- Confirm the provider key exists in
-
HTTP errors (4xx/5xx)
- The connector will return the response or throw exceptions based on your implementation. Check your timeouts and retry logic in the provider config.
-
Config resolution issues
Debjit\PhpAiHub\Support\ConfigResolverloadsconfig/ai-hub.php, validates provider entry, and then loads the provider’s own config. If paths or classes are wrong, you’ll get descriptive exceptions.
Testing
- Mock the connector classes and assert payload shapes.
- For integration tests, set fake API keys and use Laravel’s HTTP fake to simulate provider responses.
Security
- Never log raw API keys or entire request/response bodies containing sensitive data.
- Prefer setting keys in
.envand referencing via config files.
Versioning
Follow semantic versioning (SemVer). Breaking changes will bump the major version.
License
MIT License. See LICENSE file.
Credits
Crafted for teams that prefer HTTP-first integrations with AI providers in Laravel without heavyweight SDKs.
debjit/php-ai-hub 适用场景与选型建议
debjit/php-ai-hub 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 20 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 08 月 02 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「sdk」 「laravel」 「composer-plugin」 「ai」 「no-sdk」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 debjit/php-ai-hub 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 debjit/php-ai-hub 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 debjit/php-ai-hub 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Composer plugin for preserving custom paths and supporting nested packages
Composer plugin
Composer plugin that automatically creates directories defined in your composer.json.
Composer plugin that verifies GitHub build-provenance attestations for the packages you install
Alfabank REST API integration
Composer plugin for ThemeFusion
统计信息
- 总下载量: 20
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 27
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-08-02