定制 blackman-ai/client 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

blackman-ai/client

Composer 安装命令:

composer require blackman-ai/client

包简介

Official PHP client for Blackman AI - The AI API proxy that optimizes token usage

README 文档

README

Official PHP client for Blackman AI - The AI API proxy that optimizes token usage to reduce costs.

Features

  • 🚀 Drop-in replacement for OpenAI, Anthropic, and other LLM APIs
  • 💰 Automatic token optimization (save 20-40% on costs)
  • 📊 Built-in analytics and cost tracking
  • 🔒 Enterprise-grade security with SSO support
  • ⚡ Low latency overhead (<50ms)
  • 🎯 Semantic caching for repeated queries

Installation

Install via Composer:

composer require blackman-ai/client

Quick Start

<?php
require_once(__DIR__ . '/vendor/autoload.php');

use Blackman\Client\Api\CompletionsApi;
use Blackman\Client\Configuration;
use Blackman\Client\Model\CompletionRequest;
use Blackman\Client\Model\Message;

// Configure client
$config = Configuration::getDefaultConfiguration()
    ->setHost('https://app.useblackman.ai')
    ->setAccessToken('sk_your_blackman_api_key');

$api = new CompletionsApi(null, $config);

// Create completion request
$message = new Message([
    'role' => 'user',
    'content' => 'Explain quantum computing in simple terms'
]);

$request = new CompletionRequest([
    'provider' => 'OpenAI',
    'model' => 'gpt-4o',
    'messages' => [$message]
]);

try {
    // Send request
    $response = $api->completions($request);
    echo $response->getChoices()[0]->getMessage()->getContent() . "\n";
    echo "Tokens used: " . $response->getUsage()->getTotalTokens() . "\n";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

Authentication

Get your API key from the Blackman AI Dashboard.

$config = Configuration::getDefaultConfiguration()
    ->setHost('https://app.useblackman.ai')
    ->setAccessToken('sk_your_blackman_api_key');

Framework Integration

Laravel

Create a service provider app/Providers/BlackmanServiceProvider.php:

<?php

namespace App\Providers;

use Blackman\Client\Api\CompletionsApi;
use Blackman\Client\Configuration;
use Illuminate\Support\ServiceProvider;

class BlackmanServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(CompletionsApi::class, function ($app) {
            $config = Configuration::getDefaultConfiguration()
                ->setHost(config('services.blackman.host'))
                ->setAccessToken(config('services.blackman.api_key'));

            return new CompletionsApi(null, $config);
        });
    }

    public function boot()
    {
        //
    }
}

Register the provider in config/app.php:

'providers' => [
    // ...
    App\Providers\BlackmanServiceProvider::class,
],

Add configuration to config/services.php:

'blackman' => [
    'host' => env('BLACKMAN_HOST', 'https://app.useblackman.ai'),
    'api_key' => env('BLACKMAN_API_KEY'),
],

Add to .env:

BLACKMAN_API_KEY=sk_your_blackman_api_key

Use in a controller:

<?php

namespace App\Http\Controllers;

use Blackman\Client\Api\CompletionsApi;
use Blackman\Client\Model\CompletionRequest;
use Blackman\Client\Model\Message;
use Illuminate\Http\Request;

class ChatController extends Controller
{
    protected $completionsApi;

    public function __construct(CompletionsApi $completionsApi)
    {
        $this->completionsApi = $completionsApi;
    }

    public function chat(Request $request)
    {
        $message = new Message([
            'role' => 'user',
            'content' => $request->input('message')
        ]);

        $completionRequest = new CompletionRequest([
            'provider' => 'OpenAI',
            'model' => 'gpt-4o',
            'messages' => [$message]
        ]);

        try {
            $response = $this->completionsApi->completions($completionRequest);
            return response()->json([
                'response' => $response->getChoices()[0]->getMessage()->getContent(),
                'tokens' => $response->getUsage()->getTotalTokens()
            ]);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}

Symfony

Create a service in config/services.yaml:

services:
    Blackman\Client\Api\CompletionsApi:
        factory: ['App\Service\BlackmanFactory', 'createCompletionsApi']

    App\Service\BlackmanFactory:
        arguments:
            $host: '%env(BLACKMAN_HOST)%'
            $apiKey: '%env(BLACKMAN_API_KEY)%'

Create factory class src/Service/BlackmanFactory.php:

<?php

namespace App\Service;

use Blackman\Client\Api\CompletionsApi;
use Blackman\Client\Configuration;

class BlackmanFactory
{
    private string $host;
    private string $apiKey;

    public function __construct(string $host, string $apiKey)
    {
        $this->host = $host;
        $this->apiKey = $apiKey;
    }

    public function createCompletionsApi(): CompletionsApi
    {
        $config = Configuration::getDefaultConfiguration()
            ->setHost($this->host)
            ->setAccessToken($this->apiKey);

        return new CompletionsApi(null, $config);
    }
}

Use in a controller:

<?php

namespace App\Controller;

use Blackman\Client\Api\CompletionsApi;
use Blackman\Client\Model\CompletionRequest;
use Blackman\Client\Model\Message;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class ChatController extends AbstractController
{
    #[Route('/chat', name: 'chat', methods: ['POST'])]
    public function chat(Request $request, CompletionsApi $completionsApi): JsonResponse
    {
        $data = json_decode($request->getContent(), true);

        $message = new Message([
            'role' => 'user',
            'content' => $data['message']
        ]);

        $completionRequest = new CompletionRequest([
            'provider' => 'OpenAI',
            'model' => 'gpt-4o',
            'messages' => [$message]
        ]);

        try {
            $response = $completionsApi->completions($completionRequest);
            return $this->json([
                'response' => $response->getChoices()[0]->getMessage()->getContent()
            ]);
        } catch (\Exception $e) {
            return $this->json(['error' => $e->getMessage()], 500);
        }
    }
}

Advanced Usage

Custom Timeouts

use GuzzleHttp\Client;

$httpClient = new Client([
    'timeout' => 60,
    'connect_timeout' => 10
]);

$api = new CompletionsApi($httpClient, $config);

Error Handling

use Blackman\Client\ApiException;

try {
    $response = $api->completions($request);
    echo $response->getChoices()[0]->getMessage()->getContent();
} catch (ApiException $e) {
    echo "HTTP Status Code: " . $e->getCode() . "\n";
    echo "Response Body: " . $e->getResponseBody() . "\n";
    echo "Response Headers: " . print_r($e->getResponseHeaders(), true) . "\n";
} catch (Exception $e) {
    echo "Unexpected error: " . $e->getMessage() . "\n";
}

Retry Logic

function completionsWithRetry($api, $request, $maxRetries = 3) {
    $retries = 0;
    $delay = 100; // milliseconds

    while ($retries < $maxRetries) {
        try {
            return $api->completions($request);
        } catch (Exception $e) {
            $retries++;
            if ($retries >= $maxRetries) {
                throw $e;
            }
            usleep($delay * 1000);
            $delay *= 2; // Exponential backoff
        }
    }
}

$response = completionsWithRetry($api, $request);

Async Requests (with ReactPHP)

use React\EventLoop\Factory;
use GuzzleHttp\Client;
use GuzzleHttp\Promise;

$loop = Factory::create();
$client = new Client();

$promises = [];
foreach ($messages as $msg) {
    $promises[] = $client->postAsync('https://app.useblackman.ai/v1/completions', [
        'headers' => [
            'Authorization' => 'Bearer sk_your_blackman_api_key',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'provider' => 'OpenAI',
            'model' => 'gpt-4o',
            'messages' => [['role' => 'user', 'content' => $msg]]
        ]
    ]);
}

$results = Promise\Utils::unwrap($promises);

Documentation

Requirements

  • PHP 7.4 or higher
  • Composer
  • ext-curl
  • ext-json
  • ext-mbstring

Support

License

MIT © Blackman AI

blackman-ai/client 适用场景与选型建议

blackman-ai/client 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 10 月 18 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「api」 「sdk」 「ai」 「openai」 「llm」 「blackman」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 blackman-ai/client 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 blackman-ai/client 我们能提供哪些服务?
定制开发 / 二次开发

基于 blackman-ai/client 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 8
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-10-18