{"id":31928178,"url":"https://github.com/tigusigalpa/gigachat-php","last_synced_at":"2026-04-13T07:18:59.278Z","repository":{"id":318705543,"uuid":"1071462734","full_name":"tigusigalpa/gigachat-php","owner":"tigusigalpa","description":"🚀 GigaChat PHP SDK - полнофункциональная библиотека для интеграции с Сбер GigaChat AI API. Поддержка Laravel, streaming, OAuth авторизация, чат-боты, генерация текста, диалоги. Простое подключение к AI моделям Сбера через удобный PHP SDK с примерами и документацией.","archived":false,"fork":false,"pushed_at":"2026-04-13T05:18:33.000Z","size":115,"stargazers_count":18,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-13T07:15:43.167Z","etag":null,"topics":["ai","api","gigachat","gigachat-api","laravel","laravel-framework","php","sber","sdk","sdk-php"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tigusigalpa.png","metadata":{"files":{"readme":"README-en.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-07T11:38:22.000Z","updated_at":"2026-04-13T05:17:06.000Z","dependencies_parsed_at":null,"dependency_job_id":"9e74112b-2413-41b6-95d4-20ed5fe0da18","html_url":"https://github.com/tigusigalpa/gigachat-php","commit_stats":null,"previous_names":["tigusigalpa/gigachat-php"],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/tigusigalpa/gigachat-php","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tigusigalpa%2Fgigachat-php","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tigusigalpa%2Fgigachat-php/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tigusigalpa%2Fgigachat-php/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tigusigalpa%2Fgigachat-php/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tigusigalpa","download_url":"https://codeload.github.com/tigusigalpa/gigachat-php/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tigusigalpa%2Fgigachat-php/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31743416,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-13T06:26:45.479Z","status":"ssl_error","status_checked_at":"2026-04-13T06:26:44.645Z","response_time":93,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","api","gigachat","gigachat-api","laravel","laravel-framework","php","sber","sdk","sdk-php"],"created_at":"2025-10-14T03:01:08.335Z","updated_at":"2026-04-13T07:18:59.262Z","avatar_url":"https://github.com/tigusigalpa.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# GigaChat PHP SDK\n\n![GigaChat PHP SDK](https://i.postimg.cc/66jnmS1y/520455254_d44a0f88_f3d6_4c8d_9127_5d858d726cd6.png)\n\nPHP SDK for Sber GigaChat API with Laravel support. Works with streaming and regular requests.\n\n[![Latest Version](https://img.shields.io/packagist/v/tigusigalpa/gigachat-php.svg?style=flat-square)](https://packagist.org/packages/tigusigalpa/gigachat-php)\n[![PHP Version](https://img.shields.io/packagist/php-v/tigusigalpa/gigachat-php.svg?style=flat-square)](https://packagist.org/packages/tigusigalpa/gigachat-php)\n[![License](https://img.shields.io/packagist/l/tigusigalpa/gigachat-php.svg?style=flat-square)](https://packagist.org/packages/tigusigalpa/gigachat-php)\n\n**Language:** English | [Русский](README.md)\n\n**Other versions:** [Golang SDK](https://pkg.go.dev/github.com/tigusigalpa/gigachat-go)\n\n## Features\n\n- GigaChat API integration\n- OAuth token management (automatic refresh)\n- All GigaChat models (GigaChat, GigaChat-Pro, GigaChat-Max)\n- Laravel 8-13 support (Service Provider, Facades)\n- Conversations and single requests\n- Streaming responses\n- Image generation via text2image\n- Image download and processing\n- Style transfer through system prompts\n- Helper methods\n- Rate limiting middleware\n- Artisan commands\n\n## Installation\n\n### From Packagist\n\nInstall via Composer:\n\n```bash\ncomposer require tigusigalpa/gigachat-php\n```\n\n### Laravel\n\nThe package auto-registers in Laravel. Publish the config:\n\n```bash\nphp artisan vendor:publish --tag=gigachat-config\n```\n\n## Configuration\n\n### 1. Get credentials\n\n1. Register at [Sber AI](https://developers.sber.ru/docs/ru/gigachat/quickstart/ind-create-project)\n2. Create a project, get **Client ID** and **Client Secret**\n3. Generate **Authorization Key** (Base64 of \"Client ID:Client Secret\")\n\nSee: [Creating a project and getting keys](https://developers.sber.ru/docs/ru/gigachat/quickstart/ind-create-project)\n\n### 2. Environment\n\nAdd to `.env`:\n\n```env\n# Option 1: Ready Authorization Key\nGIGACHAT_AUTH_KEY=your_base64_encoded_auth_key\n\n# Option 2: Client ID + Secret (auth_key generated automatically)\nGIGACHAT_CLIENT_ID=your_client_id\nGIGACHAT_CLIENT_SECRET=your_client_secret\n\n# Settings\nGIGACHAT_SCOPE=GIGACHAT_API_PERS\nGIGACHAT_DEFAULT_MODEL=GigaChat\nGIGACHAT_TEMPERATURE=0.7\nGIGACHAT_MAX_TOKENS=1000\n\n# Disable SSL verification (for certificate issues)\nGIGACHAT_CERT_PATH=false\n```\n\n## Usage\n\n### Without Laravel\n\n```php\n\u003c?php\n\nuse Tigusigalpa\\GigaChat\\Auth\\TokenManager;\nuse Tigusigalpa\\GigaChat\\GigaChatClient;\n\n// Token manager\n$authKey = base64_encode('your_client_id:your_client_secret');\n$tokenManager = new TokenManager($authKey);\n\n// Client\n$client = new GigaChatClient($tokenManager);\n\n// Available models\n$models = $client-\u003emodels();\nprint_r($models);\n\n// Send message\n$messages = [\n    ['role' =\u003e 'user', 'content' =\u003e 'Hello! How are you?']\n];\n\n$response = $client-\u003echat($messages);\necho $response['choices'][0]['message']['content'];\n```\n\n### With Laravel\n\nUse the Facade:\n\n```php\n\u003c?php\n\nuse Tigusigalpa\\GigaChat\\Laravel\\GigaChat;\nuse Tigusigalpa\\GigaChat\\Models\\GigaChatModels;\n\n// Simple Q\u0026A\n$answer = GigaChat::ask('Tell me a joke');\necho $answer;\n\n// List models\n$models = GigaChat::models();\n\n// With parameters\n$response = GigaChat::chat([\n    ['role' =\u003e 'user', 'content' =\u003e 'Explain quantum physics']\n], [\n    'temperature' =\u003e 0.7,\n    'max_tokens' =\u003e 1000,\n    'model' =\u003e GigaChatModels::GIGACHAT_2_PRO\n]);\n\necho $response['choices'][0]['message']['content'];\n```\n\n### Conversations\n\n```php\n\u003c?php\n\nuse Tigusigalpa\\GigaChat\\Laravel\\GigaChat;\nuse Tigusigalpa\\GigaChat\\Laravel\\GigaChatHelper;\n\n// With system prompt\n$conversation = GigaChatHelper::conversation(\n    'You are a helpful programming assistant',\n    'How to create REST API in Laravel?'\n);\n\n$response = GigaChat::chat($conversation);\necho GigaChatHelper::extractContent($response);\n\n// Continue conversation\n$conversation = GigaChat::continueChat($conversation, 'How to add authentication?');\n```\n\n### Streaming\n\n```php\n\u003c?php\n\nuse Tigusigalpa\\GigaChat\\Laravel\\GigaChat;\n\n$messages = [\n    ['role' =\u003e 'user', 'content' =\u003e 'Write a long story about space']\n];\n\n// Callback\nGigaChat::chatStream($messages, [], function($event, $error) {\n    if ($error) {\n        echo \"Error: \" . $error;\n        return;\n    }\n    \n    if ($event === '[DONE]') {\n        echo \"\\n✅ Done!\";\n        return;\n    }\n    \n    if (isset($event['choices'][0]['delta']['content'])) {\n        echo $event['choices'][0]['delta']['content'];\n    }\n});\n\n// Generator\n$stream = GigaChat::chatStream($messages);\nforeach ($stream as $event) {\n    if (isset($event['choices'][0]['delta']['content'])) {\n        echo $event['choices'][0]['delta']['content'];\n    }\n}\n```\n\n### Eloquent Trait\n\n```php\n\u003c?php\n\nnamespace App\\Models;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Tigusigalpa\\GigaChat\\Laravel\\Traits\\HasGigaChat;\n\nclass Article extends Model\n{\n    use HasGigaChat;\n\n    protected $fillable = ['title', 'content', 'category'];\n\n    public function generateSummary(): string\n    {\n        return $this-\u003esummarize('content');\n    }\n\n    // Generate tags\n    public function generateTags(): array\n    {\n        return $this-\u003egenerateTags('content', 5);\n    }\n\n    // Personalized content\n    public function generateRelatedContent(): string\n    {\n        return $this-\u003egenerateContent(\n            'Create a similar article based on this one',\n            ['title', 'category']\n        );\n    }\n}\n```\n\n## Models\n\nCurrent models: [official documentation](https://developers.sber.ru/docs/ru/gigachat/models)\n\n### Text generation\n\n| Model              | Description                               | Usage                           |\n|--------------------|-------------------------------------------|---------------------------------|\n| **GigaChat-2**     | Base second-generation model              | General tasks, dialogues        |\n| **GigaChat-2-Pro** | Advanced model with enhanced capabilities | Complex tasks, creative writing |\n| **GigaChat-2-Max** | Maximum model for the most complex tasks  | Professional tasks, analysis    |\n\n### Embeddings\n\n| Model               | Description                            | Usage                             |\n|---------------------|----------------------------------------|-----------------------------------|\n| **Embeddings**      | Base model for vector representation   | Semantic search, clustering       |\n| **EmbeddingsGigaR** | Enhanced model for creating embeddings | Precise search, semantic analysis |\n\n### Model constants\n\n```php\nuse Tigusigalpa\\GigaChat\\Models\\GigaChatModels;\nuse Tigusigalpa\\GigaChat\\Laravel\\GigaChat;\n\n$response = GigaChat::chat($messages, [\n    'model' =\u003e GigaChatModels::GIGACHAT_2_PRO\n]);\n\n$generationModels = GigaChatModels::getGenerationModels();\n$embeddingModels = GigaChatModels::getEmbeddingModels();\n\nif (GigaChatModels::isValidGenerationModel('GigaChat-2')) {\n    // valid\n}\n```\n\n## Generation Parameters\n\n```php\nuse Tigusigalpa\\GigaChat\\Models\\GigaChatModels;\n\n$options = [\n    'model' =\u003e GigaChatModels::GIGACHAT_2_PRO, // Model to use\n    'temperature' =\u003e 0.7,                      // Creativity (0.0 - 2.0)\n    'top_p' =\u003e 0.9,                           // Nucleus sampling (0.0 - 1.0)\n    'max_tokens' =\u003e 1000,                     // Maximum number of tokens\n    'repetition_penalty' =\u003e 1.1,              // Repetition penalty (0.0 - 2.0)\n    'update_interval' =\u003e 0                    // Update interval for streaming\n];\n\n$response = GigaChat::chat($messages, $options);\n```\n\n## Image Generation\n\nGigaChat has built-in text2image. Use \"нарисуй\" (draw) in the prompt with `function_call: auto`.\n\n### Basic\n\n```php\n\u003c?php\n\nuse Tigusigalpa\\GigaChat\\Auth\\TokenManager;\nuse Tigusigalpa\\GigaChat\\GigaChatClient;\n\n$tokenManager = new TokenManager($authKey);\n$client = new GigaChatClient($tokenManager);\n\n$response = $client-\u003egenerateImage(\"Нарисуй красивый закат над морем\");\n\n// Extract image ID\n$content = $response['choices'][0]['message']['content'];\nif (preg_match('/\u003cimg[^\u003e]+src=[\"\\']([^\"\\']+)[\"\\'][^\u003e]*\u003e/i', $content, $matches)) {\n    $fileId = $matches[1];\n    $imageData = $client-\u003edownloadImage($fileId);\n    file_put_contents('sunset.jpg', base64_decode($imageData));\n}\n```\n\n### Stylization\n\n```php\n$response = $client-\u003egenerateImage(\"Нарисуй розового кота\", [\n    'system_message' =\u003e 'You are Wassily Kandinsky'\n]);\n\n$response = $client-\u003egenerateImage(\"Нарисуй космический корабль\", [\n    'system_message' =\u003e 'You are a concept artist for science fiction',\n    'temperature' =\u003e 0.8\n]);\n```\n\n### createImage\n\nGenerates and downloads in one call:\n\n```php\n$result = $client-\u003ecreateImage(\"Нарисуй футуристический город\", [\n    'system_message' =\u003e 'You are an architect of the future'\n]);\n\n// $result: content (base64), file_id, response\nfile_put_contents('city.jpg', base64_decode($result['content']));\n```\n\n### Laravel\n\n```php\nuse Tigusigalpa\\GigaChat\\Laravel\\GigaChat;\n\n// drawImage adds \"Нарисуй\" automatically\n$result = GigaChat::drawImage(\"beautiful landscape\");\n\n// With artist style\n$result = GigaChat::drawImageInStyle(\"portrait of a cat\", \"Leonardo da Vinci\");\n\n// Extract image ID\n$response = GigaChat::generateImage(\"Нарисуй dragon\");\n$imageId = GigaChat::extractImageId($response['choices'][0]['message']['content']);\nif ($imageId) {\n    $imageData = GigaChat::downloadImage($imageId);\n    file_put_contents(\"dragon.jpg\", base64_decode($imageData));\n}\n```\n\n### Image Methods\n\n| Method | Description | Returns |\n|--------|-------------|--------|\n| `generateImage($prompt, $options)` | Generate, return API response | `array` |\n| `downloadImage($fileId)` | Download by ID | `string` (base64) |\n| `createImage($prompt, $options)` | Generate + download | `array` |\n| `drawImage($description, $options)` | Laravel: adds \"Нарисуй\" | `array` |\n| `drawImageInStyle($description, $style, $options)` | Laravel: with artist style | `array` |\n| `extractImageId($content)` | Extract ID from HTML | `string\\|null` |\n\n### Image Errors\n\n```php\nuse Tigusigalpa\\GigaChat\\Exceptions\\GigaChatException;\nuse Tigusigalpa\\GigaChat\\Exceptions\\ValidationException;\n\ntry {\n    $result = $client-\u003ecreateImage(\"Нарисуй дракона\");\n} catch (ValidationException $e) {\n    // Validation errors (empty prompt, etc.)\n    echo \"Validation error: \" . $e-\u003egetMessage();\n} catch (GigaChatException $e) {\n    // API errors or image ID extraction issues\n    echo \"Generation error: \" . $e-\u003egetMessage();\n}\n```\n\n## Testing\n\n### Running Tests\n\n```bash\n# Install development dependencies\ncomposer install --dev\n\n# Run all tests\ncomposer test\n# or\nphp run-tests.php\n\n# Run only unit tests\nphp run-tests.php --unit\n\n# Run with code coverage\ncomposer test-coverage\n# or\nphp run-tests.php --coverage\n```\n\n### Integration Tests\n\nTo run integration tests with real API:\n\n```bash\n# Set environment variables\nexport GIGACHAT_CLIENT_ID=your_client_id\nexport GIGACHAT_CLIENT_SECRET=your_client_secret\nexport GIGACHAT_INTEGRATION_TEST=true\n\n# Run integration tests\nphp run-tests.php --integration\n```\n\n### Coverage\n\n- Text generation (chat, streaming)\n- Image generation\n- Authentication (tokens, refresh, cache)\n- Laravel (facades, helpers, service provider)\n- Validation\n- Integration tests\n\nSee [tests/README.md](tests/README.md)\n\n## Prompt Examples\n\n```php\n// Good prompts (contain \"нарисуй\")\n$client-\u003egenerateImage(\"Нарисуй закат в горах\");\n$client-\u003egenerateImage(\"Нарисуй портрет кота в стиле ренессанса\");\n$client-\u003egenerateImage(\"Нарисуй абстрактную композицию\");\n\n// Stylization through system_message\n$client-\u003egenerateImage(\"Нарисуй цветы\", [\n    'system_message' =\u003e 'You are Claude Monet, painting in impressionist style'\n]);\n\n$client-\u003egenerateImage(\"Нарисуй робота\", [\n    'system_message' =\u003e 'You are a concept artist for science fiction films'\n]);\n```\n\n**Note**: Prompts must contain \"нарисуй\" (draw). The API calls text2image when `function_call: auto` is set.\n\n## Error Handling\n\nExceptions:\n\n```php\n\u003c?php\n\nuse Tigusigalpa\\GigaChat\\Exceptions\\GigaChatException;\nuse Tigusigalpa\\GigaChat\\Exceptions\\AuthenticationException;\nuse Tigusigalpa\\GigaChat\\Exceptions\\ValidationException;\n\ntry {\n    $response = GigaChat::chat($messages);\n} catch (AuthenticationException $e) {\n    // Authentication errors (invalid keys, expired token)\n    echo \"Authentication error: \" . $e-\u003egetMessage();\n} catch (ValidationException $e) {\n    // Validation errors (invalid message format)\n    echo \"Validation error: \" . $e-\u003egetMessage();\n} catch (GigaChatException $e) {\n    // General GigaChat API errors\n    echo \"GigaChat error: \" . $e-\u003egetMessage();\n}\n```\n\n### Error Codes\n\n#### Authentication (400-401)\n\n| Code | HTTP | Description                                       | Solution                                                                      |\n|------|------|---------------------------------------------------|-------------------------------------------------------------------------------|\n| 1    | 400  | `scope data format invalid`                       | Check scope field format                                                      |\n| 4    | 401  | `Can't decode 'Authorization' header`             | Check authorization key correctness                                           |\n| 5    | 400  | `scope is empty`                                  | Specify scope: `GIGACHAT_API_PERS`, `GIGACHAT_API_B2B` or `GIGACHAT_API_CORP` |\n| 6    | 401  | `credentials doesn't match db data`               | Reissue authorization key in personal account                                 |\n| 7    | 401  | `scope from db not fully includes consumed scope` | Specify correct API version in scope                                          |\n\n```php\n// Example of handling authentication errors\ntry {\n    $client = new GigaChatClient($tokenManager);\n    $response = $client-\u003echat($messages);\n} catch (AuthenticationException $e) {\n    $message = $e-\u003egetMessage();\n    \n    if (str_contains($message, 'scope is empty')) {\n        echo \"Scope not specified. Add GIGACHAT_API_PERS to settings.\";\n    } elseif (str_contains($message, 'Authorization')) {\n        echo \"Invalid authorization key. Check CLIENT_ID and CLIENT_SECRET.\";\n    } elseif (str_contains($message, 'credentials doesn\\'t match')) {\n        echo \"Key doesn't match API version. Reissue the key.\";\n    }\n}\n```\n\n#### Limits (402-403)\n\n| HTTP | Description         | Cause                  | Solution                                                             |\n|------|---------------------|------------------------|----------------------------------------------------------------------|\n| 402  | `Payment Required`  | Model tokens exhausted | Check token limit in personal account                                |\n| 403  | `Permission denied` | No access to method    | Check tariff plan (e.g., GET /balance unavailable for pay-as-you-go) |\n\n```php\ntry {\n    $response = $client-\u003echat($messages);\n} catch (GigaChatException $e) {\n    $code = $e-\u003egetCode();\n    \n    switch ($code) {\n        case 402:\n            echo \"Tokens exhausted. Top up balance or check limits.\";\n            break;\n        case 403:\n            echo \"No access to this method. Check tariff plan.\";\n            break;\n    }\n}\n```\n\n#### Payload (413)\n\n| HTTP | Description         | Cause                    | Solution                   |\n|------|---------------------|--------------------------|----------------------------|\n| 413  | `Payload too large` | Input data size exceeded | Reduce prompt or file size |\n\n```php\ntry {\n    $response = $client-\u003egenerateImage($longPrompt);\n} catch (GigaChatException $e) {\n    if ($e-\u003egetCode() === 413) {\n        echo \"Prompt too long. Shorten the text.\";\n        // You can use POST /tokens/count to count tokens\n    }\n}\n```\n\n#### Parameters (422)\n\n| HTTP | Description                                  | Cause                           | Solution                                 |\n|------|----------------------------------------------|---------------------------------|------------------------------------------|\n| 422  | `Requested model does not support functions` | Model doesn't support functions | Use different model or disable functions |\n| 422  | `system message must be the first message`   | Wrong message order             | System message must be first             |\n| 422  | `Unprocessable Entity`                       | File exceeds context size       | Split or shorten the file                |\n\n```php\ntry {\n    $messages = [\n        ['role' =\u003e 'user', 'content' =\u003e 'Hello'],\n        ['role' =\u003e 'system', 'content' =\u003e 'You are assistant'], // Wrong!\n    ];\n    $response = $client-\u003echat($messages);\n} catch (GigaChatException $e) {\n    if (str_contains($e-\u003egetMessage(), 'system message must be the first')) {\n        echo \"System message must be first in the list.\";\n        \n        // Fix the order\n        $fixedMessages = [\n            ['role' =\u003e 'system', 'content' =\u003e 'You are assistant'],\n            ['role' =\u003e 'user', 'content' =\u003e 'Hello'],\n        ];\n    }\n}\n```\n\n#### Rate Limit (429)\n\n| HTTP | Description         | Cause                             | Solution                             |\n|------|---------------------|-----------------------------------|--------------------------------------|\n| 429  | `Too Many Requests` | Concurrent request limit exceeded | Reduce request frequency, add delays |\n\n```php\ntry {\n    $response = $client-\u003echat($messages);\n} catch (GigaChatException $e) {\n    if ($e-\u003egetCode() === 429) {\n        echo \"Too many requests. Wait and retry.\";\n        \n        // Add delay and retry\n        sleep(2);\n        $response = $client-\u003echat($messages);\n    }\n}\n```\n\n#### Server (500)\n\n| HTTP | Description             | Cause                  | Solution        |\n|------|-------------------------|------------------------|-----------------|\n| 500  | `Internal Server Error` | GigaChat service error | Contact support |\n\n```php\ntry {\n    $response = $client-\u003echat($messages);\n} catch (GigaChatException $e) {\n    if ($e-\u003egetCode() === 500) {\n        echo \"GigaChat server error. Try later or contact support.\";\n        \n        // Log for analysis\n        error_log(\"GigaChat 500 error: \" . $e-\u003egetMessage());\n    }\n}\n```\n\n### Retry Handler\n\n```php\n\u003c?php\n\nuse Tigusigalpa\\GigaChat\\Laravel\\GigaChat;\nuse Tigusigalpa\\GigaChat\\Exceptions\\GigaChatException;\nuse Tigusigalpa\\GigaChat\\Exceptions\\AuthenticationException;\nuse Tigusigalpa\\GigaChat\\Exceptions\\ValidationException;\n\nfunction handleGigaChatRequest(callable $request): array\n{\n    $maxRetries = 3;\n    $retryDelay = 1; // seconds\n    \n    for ($attempt = 1; $attempt \u003c= $maxRetries; $attempt++) {\n        try {\n            return $request();\n            \n        } catch (ValidationException $e) {\n            // Don't retry validation errors\n            throw $e;\n            \n        } catch (AuthenticationException $e) {\n            if ($attempt === $maxRetries) {\n                throw $e;\n            }\n            \n            // Try to refresh token\n            sleep($retryDelay);\n            \n        } catch (GigaChatException $e) {\n            $code = $e-\u003egetCode();\n            \n            // Retry only for specific errors\n            if (in_array($code, [429, 500]) \u0026\u0026 $attempt \u003c $maxRetries) {\n                sleep($retryDelay * $attempt); // Exponential backoff\n                continue;\n            }\n            \n            throw $e;\n        }\n    }\n}\n\n// Usage\ntry {\n    $result = handleGigaChatRequest(function() {\n        return GigaChat::createImage(\"Draw a cat\");\n    });\n    \n    echo \"Image created: \" . $result['file_id'];\n    \n} catch (Exception $e) {\n    echo \"Failed to create image: \" . $e-\u003egetMessage();\n}\n```\n\n### Debugging\n\n```php\ntry {\n    $response = $client-\u003echat($messages);\n} catch (GigaChatException $e) {\n    error_log('GigaChat Error: ' . json_encode([\n        'message' =\u003e $e-\u003egetMessage(),\n        'code' =\u003e $e-\u003egetCode(),\n    ], JSON_UNESCAPED_UNICODE));\n}\n```\n\nSee: [GigaChat API errors](https://developers.sber.ru/docs/ru/gigachat/api/errors-description)\n\n## Artisan Commands\n\n```bash\n# Test API connection\nphp artisan gigachat:test\n\n# Send message\nphp artisan gigachat:chat \"Hello, how are you?\"\n\n# Send with parameters\nphp artisan gigachat:chat \"Tell a story\" --model=GigaChat-Pro --temperature=0.8 --max-tokens=500\n\n# Streaming mode\nphp artisan gigachat:chat \"Write a long story\" --stream\n```\n\n## Rate Limiting\n\n```php\n// In routes/api.php\nRoute::middleware(['gigachat.rate_limit:30,1'])-\u003egroup(function () {\n    Route::post('/chat', [ChatController::class, 'chat']);\n});\n\n// Configuration in config/gigachat.php\n'rate_limit' =\u003e [\n    'enabled' =\u003e true,\n    'max_attempts' =\u003e 60,        // Maximum requests\n    'decay_minutes' =\u003e 1,        // Per period in minutes\n],\n```\n\n## Examples\n\n### Chatbot\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse Tigusigalpa\\GigaChat\\Laravel\\GigaChat;\n\nclass ChatController extends Controller\n{\n    public function chat(Request $request)\n    {\n        $request-\u003evalidate([\n            'message' =\u003e 'required|string|max:2000'\n        ]);\n\n        try {\n            $response = GigaChat::askWithContext(\n                'You are a friendly assistant',\n                $request-\u003einput('message'),\n                ['temperature' =\u003e 0.7]\n            );\n\n            return response()-\u003ejson([\n                'success' =\u003e true,\n                'reply' =\u003e $response\n            ]);\n        } catch (\\Exception $e) {\n            return response()-\u003ejson([\n                'success' =\u003e false,\n                'error' =\u003e $e-\u003egetMessage()\n            ], 500);\n        }\n    }\n}\n```\n\n### Content Generator\n\n```php\n\u003c?php\n\nuse Tigusigalpa\\GigaChat\\Laravel\\GigaChat;\n\nclass ContentGenerator\n{\n    public function generateArticle(string $topic, string $style = 'informational'): string\n    {\n        return GigaChat::askWithContext(\n            \"You are a professional copywriter. Write in {$style} style.\",\n            \"Write an article on the topic: {$topic}\",\n            ['temperature' =\u003e 0.8, 'max_tokens' =\u003e 1500]\n        );\n    }\n\n    public function translateText(string $text, string $targetLang = 'English'): string\n    {\n        return GigaChat::ask(\n            \"Translate the following text to {$targetLang}:\\n\\n{$text}\",\n            ['temperature' =\u003e 0.2]\n        );\n    }\n\n    public function summarizeText(string $text, int $maxWords = 100): string\n    {\n        return GigaChat::ask(\n            \"Create a brief summary (no more than {$maxWords} words):\\n\\n{$text}\",\n            ['temperature' =\u003e 0.3, 'max_tokens' =\u003e $maxWords * 2]\n        );\n    }\n}\n```\n\n### Laravel Tests\n\n```php\n\u003c?php\n\nnamespace Tests\\Feature;\n\nuse Tests\\TestCase;\nuse Tigusigalpa\\GigaChat\\Laravel\\GigaChat;\n\nclass GigaChatTest extends TestCase\n{\n    public function test_gigachat_basic_functionality()\n    {\n        $response = GigaChat::ask('Hello!');\n        \n        $this-\u003eassertNotEmpty($response);\n        $this-\u003eassertIsString($response);\n    }\n\n    public function test_gigachat_with_context()\n    {\n        $response = GigaChat::askWithContext(\n            'You are a mathematician',\n            'What is 2+2?'\n        );\n        \n        $this-\u003eassertStringContainsString('4', $response);\n    }\n}\n```\n\n## FAQ\n\n**How to get Client ID and Client Secret?**  \nRegister at [Sber AI](https://developers.sber.ru/docs/ru/gigachat/quickstart/ind-create-project) and create a project.\n\n**\"Invalid token response\" error?**  \nCheck Client ID/Secret and authorization service availability.\n\n**Custom SSL certificates?**  \nSet `GIGACHAT_CERT_PATH` to certificate path or `false` to disable.\n\n**Production ready?**  \nYes. Configure SSL and rate limiting properly.\n\n**Pricing?**  \n[Official documentation](https://developers.sber.ru/docs/ru/gigachat/api/tariffs)\n\n### SSL Errors\n\n```\ncURL error 60: SSL certificate problem\n```\n\n```bash\n# Development\nGIGACHAT_CERT_PATH=false\n\n# Production\nGIGACHAT_CERT_PATH=/path/to/certificate.pem\n```\n\nClear cache after changes:\n\n```bash\nphp artisan config:clear\nphp artisan config:cache\n```\n\n## Full Configuration\n\n`config/gigachat.php`:\n\n```php\n\u003c?php\n\nreturn [\n    // Authorization key (Base64(Client ID:Client Secret))\n    'auth_key' =\u003e env('GIGACHAT_AUTH_KEY', null),\n\n    // Alternatively, specify Client ID and Client Secret\n    'client_id' =\u003e env('GIGACHAT_CLIENT_ID', null),\n    'client_secret' =\u003e env('GIGACHAT_CLIENT_SECRET', null),\n\n    // API access scope: GIGACHAT_API_PERS | GIGACHAT_API_B2B | GIGACHAT_API_CORP\n    'scope' =\u003e env('GIGACHAT_SCOPE', 'GIGACHAT_API_PERS'),\n\n    // TLS certificate verification\n    'verify' =\u003e env('GIGACHAT_CERT_PATH', true),\n\n    // Base URIs\n    'base_uri' =\u003e env('GIGACHAT_BASE_URI', 'https://gigachat.devices.sberbank.ru'),\n    'oauth_uri' =\u003e env('GIGACHAT_OAUTH_URI', 'https://ngw.devices.sberbank.ru:9443'),\n\n    // Default model\n    'default_model' =\u003e env('GIGACHAT_DEFAULT_MODEL', 'GigaChat'),\n\n    // Default generation parameters\n    'default_options' =\u003e [\n        'temperature' =\u003e (float) env('GIGACHAT_TEMPERATURE', 0.7),\n        'max_tokens' =\u003e (int) env('GIGACHAT_MAX_TOKENS', 1000),\n        'top_p' =\u003e (float) env('GIGACHAT_TOP_P', 0.9),\n        'repetition_penalty' =\u003e (float) env('GIGACHAT_REPETITION_PENALTY', 1.1),\n    ],\n\n    // Rate limiting settings\n    'rate_limit' =\u003e [\n        'enabled' =\u003e env('GIGACHAT_RATE_LIMIT_ENABLED', true),\n        'max_attempts' =\u003e (int) env('GIGACHAT_RATE_LIMIT_MAX_ATTEMPTS', 60),\n        'decay_minutes' =\u003e (int) env('GIGACHAT_RATE_LIMIT_DECAY_MINUTES', 1),\n    ],\n\n    // Logging settings\n    'logging' =\u003e [\n        'enabled' =\u003e env('GIGACHAT_LOGGING_ENABLED', false),\n        'channel' =\u003e env('GIGACHAT_LOG_CHANNEL', 'default'),\n        'level' =\u003e env('GIGACHAT_LOG_LEVEL', 'info'),\n    ],\n];\n```\n\n## Requirements\n\n- PHP 8.2+\n- Laravel 8+ (including 11, 12)\n- Guzzle HTTP 7.8.2+\n- GigaChat API credentials\n\n## License\n\nMIT. See [LICENSE](LICENSE).\n\n## Links\n\n- [Create Project](https://developers.sber.ru/docs/ru/gigachat/quickstart/ind-create-project)\n- [Quick Start](https://developers.sber.ru/docs/ru/gigachat/quickstart/ind-using-api)\n- [API Reference](https://developers.sber.ru/docs/ru/gigachat/api/reference/rest/gigachat-api)\n- [Models](https://developers.sber.ru/docs/ru/gigachat/models)\n- [Pricing](https://developers.sber.ru/docs/ru/gigachat/api/tariffs)\n\n## Support\n\n- [GitHub Issues](https://github.com/tigusigalpa/gigachat-php/issues)\n- [GitHub Discussions](https://github.com/tigusigalpa/gigachat-php/discussions)\n- [API Documentation](https://developers.sber.ru/docs/ru/gigachat/api/overview)\n\n## Contributing\n\n1. Fork the repository\n2. Create feature branch (`git checkout -b feature/name`)\n3. Commit changes (`git commit -m 'Add feature'`)\n4. Push (`git push origin feature/name`)\n5. Open Pull Request\n\nFollow PSR-12, add tests, update docs.\n\n## Security\n\nReport vulnerabilities to sovletig@gmail.com (not public issues).\n\n## Laravel 12\n\nFully compatible:\n- Service Provider auto-registers\n- `GigaChat` Facade\n- Artisan commands\n- Rate limit middleware\n- `HasGigaChat` trait\n\n## Roadmap\n\n- [ ] Response caching\n- [ ] Metrics\n- [ ] WebSocket\n- [ ] Other PHP frameworks\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftigusigalpa%2Fgigachat-php","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftigusigalpa%2Fgigachat-php","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftigusigalpa%2Fgigachat-php/lists"}