PHPackages                             0xmergen/zai-laravel-sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. 0xmergen/zai-laravel-sdk

ActiveLibrary

0xmergen/zai-laravel-sdk
========================

ZAI Laravel SDK - Advanced AI integration package for Laravel 12

v1.0.1(2mo ago)023MITPHPPHP ^8.4

Since Feb 7Pushed 2mo agoCompare

[ Source](https://github.com/0xmergen/zai-laravel-sdk)[ Packagist](https://packagist.org/packages/0xmergen/zai-laravel-sdk)[ Docs](https://github.com/0xmergen/zai-laravel-sdk)[ GitHub Sponsors](https://github.com/sponsors/0xmergen)[ RSS](/packages/0xmergen-zai-laravel-sdk/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (5)Versions (3)Used By (0)

ZAI Laravel SDK
===============

[](#zai-laravel-sdk)

[![Latest Version](https://camo.githubusercontent.com/cfbe519c38c91e72d27165ae1e875fc6505af59c221f52bdcede80d1d5947a0a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f30786d657267656e2f7a61692d6c61726176656c2d73646b)](https://packagist.org/packages/0xmergen/zai-laravel-sdk)[![License](https://camo.githubusercontent.com/26a917b84af56e5878f887e7aa28406639ed2afd3dfdcf4b527622ec17e73b63/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f30786d657267656e2f7a61692d6c61726176656c2d73646b)](LICENSE)[![Total Downloads](https://camo.githubusercontent.com/e30e2117ad23b35afe6cc2a2de0cae5b861e64c0c13b5d13fd7a1cbca091db20/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f30786d657267656e2f7a61692d6c61726176656c2d73646b)](https://packagist.org/packages/0xmergen/zai-laravel-sdk)[![PHP](https://camo.githubusercontent.com/da6535a88644c69bdd4d06e57de4b58563db153519bfbf76b4d7a44558dbb4ba/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f30786d657267656e2f7a61692d6c61726176656c2d73646b)](https://packagist.org/packages/0xmergen/zai-laravel-sdk)[![Laravel](https://camo.githubusercontent.com/b72e0aa3b09f6ee9f1cd47f19792a8204408312803c6b277768a5d2c99ffd60c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31322e782d7265642e737667)](https://laravel.com/docs/12.x)

A powerful, elegant Laravel SDK for [Z.AI](https://api.z.ai) (Zhipu AI) API. Integrate advanced AI capabilities including chat completion, image generation, and OCR layout parsing into your Laravel applications with type-safe DTOs, fluent interfaces, and comprehensive error handling.

Features
--------

[](#features)

- **Chat Completion** - Support for GLM-4.7, GLM-4.6, GLM-4.6V, GLM-4.5 series with thinking mode, tools/function calling, and streaming responses
- **Vision (Multimodal)** - Image and video understanding with GLM-4.6V series for document analysis, frontend replication, and visual search
- **Image Generation** - Generate images using `glm-image` and `cogview-4-250304` models with customizable quality and size
- **OCR &amp; Layout Parsing** - Extract text, tables, and formulas from PDFs and images with detailed layout information
- **Type-Safe DTOs** - Request/Response objects with full PHP type hints and fluent builders
- **Smart Validation** - Pre-request validation based on model capabilities
- **Comprehensive Error Handling** - Structured exceptions with retry detection and detailed error codes
- **Laravel Integration** - Facade, Dependency Injection, and Artisan command support

Requirements
------------

[](#requirements)

- **PHP**: 8.4 or higher
- **Laravel**: 12.0 or higher
- **Extensions**: `json`, `curl`

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require 0xmergen/zai-laravel-sdk
```

### Configuration

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --tag=zai-sdk-config
```

Add your API key to your `.env` file:

```
ZAI_API_KEY=your_api_key_here
```

> You can obtain an API key from

### Optional Configuration

[](#optional-configuration)

All configuration options in `config/zai-sdk.php` have sensible defaults:

```
# Override default API endpoints if needed
ZAI_BASE_URL=https://api.z.ai/api/paas/v4/chat/completions
ZAI_IMAGE_BASE_URL=https://api.z.ai/api/paas/v4/images/generations
ZAI_OCR_BASE_URL=https://api.z.ai/api/paas/v4/layout_parsing

# Default model for chat completion
ZAI_DEFAULT_MODEL=glm-4.7

# Request timeout (seconds)
ZAI_TIMEOUT=30

# Retry configuration
ZAI_RETRY_TIMES=2
ZAI_RETRY_SLEEP=100
```

Usage
-----

[](#usage)

### Chat Completion

[](#chat-completion)

#### Basic Chat

[](#basic-chat)

```
use Zai\LaravelSdk\Facades\ZaiSdk;
use Zai\LaravelSdk\DataTransferObjects\ChatCompletionRequest;
use Zai\LaravelSdk\Constants\ChatModel;

$request = ChatCompletionRequest::make(
    model: ChatModel::GLM_4_7,
    messages: [
        ['role' => 'user', 'content' => 'Explain quantum computing in simple terms.']
    ]
);

$response = ZaiSdk::chatCompletion($request);

echo $response->content();
// "Quantum computing is a type of computation that..."
```

#### With Parameters

[](#with-parameters)

```
$request = ChatCompletionRequest::make(ChatModel::GLM_4_7, $messages)
    ->withTemperature(0.7)       // 0.0 - 1.0 (default varies by model)
    ->withTopP(0.9)              // 0.01 - 1.0
    ->withMaxTokens(2000)        // Maximum tokens to generate
    ->withUser('user-123');      // User identifier for tracking
```

#### Streaming Responses

[](#streaming-responses)

```
$request = ChatCompletionRequest::make(ChatModel::GLM_4_7, $messages)
    ->withStreaming();

foreach (ZaiSdk::chatCompletionStream($request) as $chunk) {
    echo $chunk;        // Stream each chunk as it arrives
    ob_flush();
    flush();
}
```

#### Thinking Mode

[](#thinking-mode)

Enable reasoning for complex tasks (supported models only):

```
$request = ChatCompletionRequest::make(ChatModel::GLM_4_7, $messages)
    ->withThinking('enabled');   // or 'disabled'

$response = ZaiSdk::chatCompletion($request);

// Access reasoning content
echo $response->reasoningContent();  // Chain-of-thought reasoning
echo $response->content();           // Final answer
```

#### Function / Tool Calling

[](#function--tool-calling)

```
$request = ChatCompletionRequest::make(ChatModel::GLM_4_7, $messages)
    ->withTools([
        [
            'type' => 'function',
            'function' => [
                'name' => 'get_weather',
                'description' => 'Get the current weather for a location',
                'parameters' => [
                    'type' => 'object',
                    'properties' => [
                        'location' => [
                            'type' => 'string',
                            'description' => 'City name, e.g. San Francisco'
                        ]
                    ],
                    'required' => ['location']
                ]
            ]
        ]
    ])
    ->withToolChoice('auto');

$response = ZaiSdk::chatCompletion($request);

if ($response->hasToolCalls()) {
    foreach ($response->toolCalls() as $toolCall) {
        echo $toolCall->function->name;               // 'get_weather'
        print_r($toolCall->function->argumentsAsArray());  // ['location' => 'Tokyo']
    }
}
```

#### JSON Mode

[](#json-mode)

Force JSON output:

```
$request = ChatCompletionRequest::make(ChatModel::GLM_4_7, $messages)
    ->withResponseFormat('json');

$response = ZaiSdk::chatCompletion($request);
$data = json_decode($response->content(), true);
```

### Image Generation

[](#image-generation)

#### Basic Image Generation

[](#basic-image-generation)

```
use Zai\LaravelSdk\Facades\ZaiSdk;
use Zai\LaravelSdk\DataTransferObjects\ImageGenerationRequest;
use Zai\LaravelSdk\Constants\ImageModel;

$request = ImageGenerationRequest::make(
    model: ImageModel::GLM_IMAGE,
    prompt: 'A serene mountain landscape at sunset, digital art style'
);

$response = ZaiSdk::imageGeneration($request);

echo $response->imageUrl();  // URL to the generated image (expires in 30 days)
```

#### Custom Size and Quality

[](#custom-size-and-quality)

```
$request = ImageGenerationRequest::make(ImageModel::GLM_IMAGE, $prompt)
    ->withQuality(ImageModel::QUALITY_HD)     // 'hd' or 'standard'
    ->withSize('1728x960')                    // Width x Height
    ->withUser('user-123');

// Recommended sizes for glm-image:
// 1280x1280, 1568x1056, 1056x1568, 1472x1088, 1088x1472, 1728x960, 960x1728
```

#### Multiple Images

[](#multiple-images)

```
$urls = $response->imageUrls();  // Array of all generated image URLs
foreach ($urls as $url) {
    echo $url . "\n";
}
```

### OCR / Layout Parsing

[](#ocr--layout-parsing)

Extract structured data from PDFs and images:

```
use Zai\LaravelSdk\Facades\ZaiSdk;
use Zai\LaravelSdk\DataTransferObjects\LayoutParsingRequest;
use Zai\LaravelSdk\Constants\OcrModel;

// From URL or base64
$request = LayoutParsingRequest::make('https://example.com/document.pdf')
    ->withPageRange(1, 5)                 // Pages 1-5 only
    ->withLayoutVisualization()           // Get visual layout images
    ->withRequestId('unique-request-id')
    ->withUserId('user-123');

$response = ZaiSdk::layoutParsing($request);

// Get Markdown format
echo $response->md_results();

// Extract specific elements
$tables = $response->tables();           // All tables across pages
$images = $response->images();           // All detected images
$texts = $response->allTextContent();    // All text elements

// Page-specific access
$elements = $response->pageElements(1);   // Elements on page 1
echo "Page 1 has " . $response->elementCount(1) . " elements";

// Access individual element details
foreach ($elements as $element) {
    if ($element->isTable()) {
        echo "Table at: " . json_encode($element->boundingBox()) . "\n";
        echo "Content: " . $element->content . "\n";
    }
}

// Document info
echo "Total pages: " . $response->data_info->num_pages;
```

### Dependency Injection

[](#dependency-injection)

```
use Zai\LaravelSdk\ZaiSdk;
use Zai\LaravelSdk\DataTransferObjects\ChatCompletionRequest;

class ChatService
{
    public function __construct(
        private readonly ZaiSdk $zai
    ) {}

    public function generateResponse(string $userMessage): string
    {
        $request = ChatCompletionRequest::make('glm-4.7', [
            ['role' => 'user', 'content' => $userMessage]
        ]);

        $response = $this->zai->chatCompletion($request);

        return $response->content();
    }
}
```

### Artisan Command

[](#artisan-command)

Check your SDK configuration:

```
php artisan zai:info
```

Output:

```
ZAI Laravel SDK

+---------+-----------------------------------------+
| Property | Value                                   |
+---------+-----------------------------------------+
| Name     | ZAI Laravel SDK                         |
| Version  | 1.0.0                                   |
| API URL  | https://api.z.ai/api/paas/v4/...        |
| API Key  | sk-abc123...xyz9                        |
+---------+-----------------------------------------+

```

Available Models
----------------

[](#available-models)

### Chat Models

[](#chat-models)

ModelContextMax TokensThinkingToolsVision`glm-4.7`128K131,072✅✅❌`glm-4.7-flash`128K131,072✅✅❌`glm-4.7-flashx`128K131,072✅✅❌`glm-4.6`200K131,072✅✅✅`glm-4.6v-flash`128K131,072✅✅✅`glm-4.5`128K98,304✅✅✅`glm-4.5-air`128K98,304✅✅❌`glm-4.5-x`128K98,304✅✅❌`glm-4.5-airx`128K98,304✅✅❌`glm-4.5-flash`128K98,304✅✅❌`glm-4-32b-0414-128k`128K16,384❌❌❌### Image Models

[](#image-models)

ModelDefault SizeMax SizeHD Quality`glm-image`1280x12802048x2048✅`cogview-4-250304`1024x10242048x2048❌### OCR Models

[](#ocr-models)

ModelSupported FormatsMax Pages`glm-ocr`PDF, JPG, PNG100Error Handling
--------------

[](#error-handling)

The SDK provides structured exceptions for different error scenarios:

```
use Zai\LaravelSdk\Exceptions\{
    ZaiApiException,
    ZaiAuthenticationException,
    ZaiRateLimitException,
    ZaiValidationException
};

try {
    $response = ZaiSdk::chatCompletion($request);
} catch (ZaiAuthenticationException $e) {
    // Invalid API key, expired token, etc.
    logger()->error('ZAI Authentication failed: ' . $e->getMessage());
} catch (ZaiRateLimitException $e) {
    // Rate limit exceeded, high concurrency, etc.
    logger()->warning('ZAI rate limit: ' . $e->getMessage());

    // Check if retryable
    if ($e->isRetryable()) {
        sleep(1);
        // Retry request
    }
} catch (ZaiValidationException $e) {
    // Invalid parameters, unsupported model, etc.
    logger()->error('Validation error: ' . $e->getMessage());
} catch (ZaiApiException $e) {
    // General API error
    logger()->error('ZAI error: ' . $e->getMessage());
    logger()->error('Error code: ' . $e->errorCode);
}
```

Testing
-------

[](#testing)

The package includes Pest tests. Run them with:

```
composer test
```

Or via Pest directly:

```
./vendor/bin/pest
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG.md](CHANGELOG.md) for recent changes.

Contributing
------------

[](#contributing)

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [0xmergen](https://github.com/0xmergen)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [LICENSE](LICENSE) for more information.

Author
------

[](#author)

Made with ❤️ by [0xmergen](https://github.com/0xmergen)

- **Twitter**: [@0xm3rg3n](https://x.com/0xm3rg3n)
- **GitHub**: [0xmergen](https://github.com/0xmergen)

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance83

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~5 days

Total

2

Last Release

89d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/9d024b6f776c6c743283743009462e7b7d4e6d52d44ade38fa4103e792d57ee4?d=identicon)[0xmergen](/maintainers/0xmergen)

---

Top Contributors

[![0xmergen](https://avatars.githubusercontent.com/u/36132897?v=4)](https://github.com/0xmergen "0xmergen (3 commits)")

---

Tags

laravelsdkautomationaiOCRllmChatGptimage-generationzaizhipuglm

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/0xmergen-zai-laravel-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/0xmergen-zai-laravel-sdk/health.svg)](https://phpackages.com/packages/0xmergen-zai-laravel-sdk)
```

###  Alternatives

[claude-php/claude-php-sdk-laravel

Laravel integration for the Claude PHP SDK - Anthropic Claude API

5010.8k](/packages/claude-php-claude-php-sdk-laravel)[neuron-core/neuron-laravel

Official Neuron AI Laravel SDK.

10710.0k](/packages/neuron-core-neuron-laravel)[sbsaga/toon

🧠 TOON for Laravel — a compact, human-readable, and token-efficient data format for AI prompts &amp; LLM contexts. Perfect for ChatGPT, Gemini, Claude, Mistral, and OpenAI integrations (JSON ⇄ TOON).

6115.6k](/packages/sbsaga-toon)[mischasigtermans/laravel-toon

Token-Optimized Object Notation encoder/decoder for Laravel with intelligent nested object handling

13113.1k](/packages/mischasigtermans-laravel-toon)[anilcancakir/laravel-ai-sdk-skills

A skill system for Laravel AI SDK agents. Define reusable AI capabilities with SKILL.md files.

151.1k](/packages/anilcancakir-laravel-ai-sdk-skills)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
