Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Aip Sdk Laravel Package

baidu/aip-sdk

PHP SDK for integrating Baidu AI Cloud services into Laravel or PHP apps. It provides simple client classes for OCR, NLP, image and face recognition, speech, and other AIP APIs, with Composer installation and straightforward configuration for adding Baidu AI capabilities to your project.

View on GitHub
Deep Wiki
Context7

Getting Started

Install via Composer (the package ships a composer.json with a classmap autoload, no PSR-4 namespaces):

composer require baidu/aip-sdk

Then instantiate the client for the specific product you need. The SDK exposes one class per Baidu AI product (AipOcr, AipNlp, AipFace, AipSpeech, AipImageClassify, AipImageSearch, AipKg, AipNlp, etc.):

require 'vendor/autoload.php';

$ocr = new AipOcr(
    getenv('BAIDU_APP_ID'),
    getenv('BAIDU_API_KEY'),
    getenv('BAIDU_SECRET_KEY')
);

$result = $ocr->basicGeneral(file_get_contents('receipt.jpg'));

if (isset($result['error_code'])) {
    // handle failure
}

Where to look first:

  1. README.md — contains copy-paste examples per product; the constructor signatures are uniform.
  2. src/AipBase.php (or AipBase.php in the root depending on version) — the single transport layer (run(), request(), curl setup, token endpoint, error normalization). Read this before anything else; it dictates every gotcha below.
  3. The product class you care about (e.g. AipOcr.php) — each public method is a thin wrapper that builds $data and calls $this->request(...). Signatures and accepted option keys are documented here, not in the README.

First use case: OCR is the most common entry point — basicGeneral() for Chinese/English text extraction from an image (base64 or public URL). It needs no training or model setup, so it validates credentials, network, and response parsing in one call.

Implementation Patterns

Wrap clients behind your own service class. Never call new AipOcr(...) from controllers. Inject credentials from config and expose intent-named methods:

class ReceiptOcr
{
    public function __construct(private AipOcr $client) {}

    public function extract(string $path): array
    {
        $raw = $this->client->basicGeneral(base64_encode(file_get_contents($path)), [
            'detect_direction' => 'true',
            'probability'      => 'true',
        ]);
        return $this->normalize($raw);
    }

    private function normalize(array $raw): array
    {
        if (isset($raw['error_code'])) {
            throw new BaiduApiException($raw['error_msg'], $raw['error_code']);
        }
        return array_map(fn ($line) => $line['words'], $raw['words_result'] ?? []);
    }
}

Convert the array-shaped error contract into exceptions at the boundary so the rest of your app doesn't need to know about Baidu's quirks.

Bind each product class in the container. The SDK has no shared state across clients, so register singletons per product:

$this->app->singleton(AipOcr::class, fn () => new AipOcr(
    config('services.baidu.app_id'),
    config('services.baidu.api_key'),
    config('services.baidu.secret_key')
));

Keep credentials in config/services.php and .env, never in code.

Treat the image argument carefully. Most OCR/vision methods accept either a local binary (file_get_contents, or base64) or a fully-qualified public URL. Prefer base64 for user uploads (no public exposure, no URL-expiry problems) and URLs for already-hosted assets. Baidu enforces per-request size limits (~4 MB base64, ~2 MB for some APIs), so resize before sending — do not rely on the SDK to validate.

Build a thin retry/backoff layer. The SDK does a blocking cURL per call and will happily return transient network failures as error_code entries. Wrap calls in a small retrier keyed on error codes that indicate throttling or quota (e.g. 18, 19, 17), not on input errors.

Use options to set timeouts, not cURL globals. Every client accepts an $options array in its constructor:

new AipOcr($id, $key, $secret, [
    'timeout' => 10,
    'connectionTimeoutInMillis' => 3000,
]);

Batch and queue long jobs. Some APIs (async OCR, image search ingestion) are slow or rate-limited. Dispatch a queued job per document and let the worker call the client; the SDK has no async support of its own.

Store the raw log_id from every response. Baidu support asks for it and it's the only way to correlate a bad result with their side.

Gotchas and Tips

Errors are arrays, not exceptions. Every method returns the decoded JSON body. error_code / error_msg indicate failure; there is no HTTP status check surfaced to you. Missing keys on success also happen (e.g. words_result_num without words_result for empty images), so guard with ??.

The access token is refreshed on every process, per request. AipBase fetches a token lazily and caches it in memory only. Under PHP-FPM this means an extra HTTP round-trip to Baidu on every request unless you subclass AipBase and persist the token (Baidu tokens are valid ~30 days). This is the single biggest latency/ quota win:

protected function getAuthToken(): string
{
    return Cache::remember('baidu_token', now()->addDays(25), fn () => parent::getAuthToken());
}

No namespaces. All classes live in the global namespace (AipOcr, AipBase, AipHttpClient). If you also load an older copy of the SDK (some products shipped separate zips), you'll get fatal "cannot redeclare class" errors. Ensure only one copy is autoloaded.

Autoloading can be flaky. Older releases only provide require_once 'AipPhpSdk.php'; newer ones use a classmap. If class_exists('AipOcr') is false after composer require, check whether you need a manual require or to dump the autoloader.

Parameter encoding matters. String options like 'detect_direction' => 'true' are expected as strings, not booleans; some endpoints silently ignore booleans or send 1. Match the README examples verbatim.

Image base64 vs. URL. Passing a local path string directly will fail — the SDK sends it as-is and Baidu rejects it as an invalid image. Always file_get_contents or base64_encode first, or pass a URL starting with http.

TLS / cURL issues. AipBase::run() sets its own cURL options. If you're behind a proxy or a corporate MITM, configure CURLOPT_PROXY / a CA bundle via the $options array or by subclassing, rather than editing vendor files.

Chinese error messages. error_msg is often in Chinese; log it verbatim, but map error_code to your own user-facing messages. Codes to know: 110 (token invalid), 17 (daily quota), 18 (QPS limit), 216100 (image size/format).

Result shapes differ per product. OCR returns words_result (array of {words, probability}); NLP returns items; face returns result.face_list. Don't assume a uniform envelope beyond error_code / log_id.

Extension point is subclassing. There's no plugin system. To add a new endpoint Baidu ships before the SDK updates, subclass the product client and call $this->request($url, $data) from a public method — request() is protected and stable.

Version pinning. The package moves slowly (110 stars, low activity). Pin a specific tag and add an integration test that hits one cheap endpoint, so an accidental Composer update doesn't silently break payload shapes.

Logging. Enable 'log' => true in options during development (some builds support it) or wrap the client with a decorator that logs request method names, latency, log_id, and error_code — never log the raw image bytes or tokens.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin