├── .github ├── FUNDING.yml └── workflows │ ├── fix-php-code-style-issues.yml │ └── run-tests.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── assets └── images │ └── grok-laravel.png ├── composer.json ├── config └── grok.php ├── phpunit.xml.dist └── src ├── Commands └── InstallGrokCommand.php ├── Facades └── GrokAI.php ├── Providers └── GrokServiceProvider.php ├── Services ├── GrokAI.php └── GrokVision.php └── Support └── GrokResponse.php /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: thefeqy -------------------------------------------------------------------------------- /.github/workflows/fix-php-code-style-issues.yml: -------------------------------------------------------------------------------- 1 | name: Fix PHP code style issues 2 | 3 | on: 4 | push: 5 | paths: 6 | - '**.php' 7 | 8 | permissions: 9 | contents: write 10 | 11 | jobs: 12 | php-code-styling: 13 | runs-on: ubuntu-latest 14 | timeout-minutes: 5 15 | 16 | steps: 17 | - name: Checkout code 18 | uses: actions/checkout@v4 19 | with: 20 | ref: ${{ github.head_ref }} 21 | 22 | - name: Fix PHP code style issues 23 | uses: aglipanci/laravel-pint-action@2.5 24 | 25 | - name: Commit changes 26 | uses: stefanzweifel/git-auto-commit-action@v5 27 | with: 28 | commit_message: Fix styling 29 | -------------------------------------------------------------------------------- /.github/workflows/run-tests.yml: -------------------------------------------------------------------------------- 1 | name: run-tests 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | push: 8 | paths: 9 | - '**.php' 10 | - '.github/workflows/run-tests.yml' 11 | - 'phpunit.xml.dist' 12 | - 'composer.json' 13 | - 'composer.lock' 14 | 15 | jobs: 16 | test: 17 | runs-on: ${{ matrix.os }} 18 | timeout-minutes: 10 19 | strategy: 20 | fail-fast: false 21 | matrix: 22 | os: [ubuntu-latest] 23 | php: [8.3, 8.4] 24 | stability: [prefer-lowest, prefer-stable] 25 | 26 | name: PHP ${{ matrix.php }} - ${{ matrix.stability }} - Laravel Tests 27 | 28 | steps: 29 | - name: Checkout Code 30 | uses: actions/checkout@v4 31 | 32 | - name: Setup PHP ${{ matrix.php }} 33 | uses: shivammathur/setup-php@v2 34 | with: 35 | php-version: ${{ matrix.php }} 36 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, fileinfo 37 | coverage: none 38 | 39 | - name: Install Dependencies (${{ matrix.stability }}) 40 | run: composer update --${{ matrix.stability }} --prefer-dist --no-interaction 41 | 42 | - name: Configure PHPUnit 43 | run: | 44 | cp phpunit.xml.dist phpunit.xml 45 | sed -i 's|||g' phpunit.xml 46 | 47 | - name: Cache Dependencies 48 | uses: actions/cache@v3 49 | with: 50 | path: vendor 51 | key: composer-${{ matrix.php }}-${{ matrix.stability }}-${{ hashFiles('composer.lock') }} 52 | restore-keys: | 53 | composer-${{ matrix.php }}-${{ matrix.stability }}- 54 | 55 | - name: List Installed Dependencies 56 | run: composer show -D 57 | 58 | - name: Run PHPUnit Tests 59 | run: vendor/bin/phpunit 60 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `GrokPHP/Laravel` will be documented in this file. 4 | This project follows [Semantic Versioning](https://semver.org/). 5 | 6 | --- 7 | 8 | ## [v1.1.0] - 2024-02-25 9 | ### New Features 10 | - **Added Vision API Support**: The package now supports analyzing images using Grok AI Vision models. 11 | - New method: `GrokAI::vision()->analyze($imagePath, $prompt)`. 12 | - Supports models: `grok-2-vision-1212`, `grok-2-vision`, and `grok-2-vision-latest`. 13 | 14 | ### Improvements 15 | - **Switched from Pest to PHPUnit** for better Laravel compatibility. 16 | - **Introduced `GrokResponse`**: A response wrapper for easier result handling. 17 | - **Enhanced Exception Handling**: 18 | - Proper error handling for image inputs when used with non-vision models. 19 | - Improved API key error handling. 20 | - **Refactored Service Provider** for better maintainability. 21 | - **Dropped Support for PHP 8.1**: Now requires **PHP 8.2+**. 22 | - **Added Support for Laravel 12**: Compatible with **Laravel 10, 11, and 12**. 23 | 24 | ### Internal Changes 25 | - Improved test coverage for **chat and vision API features**. 26 | - Refactored code to follow **SOLID principles**. 27 | - Added GitHub Actions CI workflow to support **PHP 8.3, and 8.4**. 28 | 29 | 30 | --- 31 | 32 | ## [v1.0.0] - 2025-02-07 33 | ### Initial Release 34 | - Released `GrokPHP/Laravel` v1.0.0, a Laravel wrapper for **Grok AI Client**. 35 | - Added support for **chat models** with a simple, fluent syntax. 36 | 37 | --- 38 | 39 | ### Notes 40 | - For detailed usage, refer to the [README.md](README.md). 41 | - Found an issue? Report it on [GitHub Issues](https://github.com/grok-php/laravel/issues). 42 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | Copyright (c) 2024 **Grok PHP** 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🧠 **Grok AI Laravel** 2 | 3 | ![GrokAI Laravel](assets/images/grok-laravel.png) 4 | 5 | A **Laravel integration for the [GrokPHP Client](https://github.com/grok-php/client)**, designed to effortlessly incorporate Grok AI into Laravel applications with a clean and intuitive API. 6 | Utilize **advanced AI models** for **chat, automation, and natural language processing**, all while preserving Laravel's simplicity and elegance. 7 | 8 | [![Latest Version](https://img.shields.io/packagist/v/grok-php/laravel)](https://packagist.org/packages/grok-php/laravel) 9 | [![PHP Version](https://img.shields.io/badge/PHP-8.2%2B-blue)](https://php.net) 10 | [![Laravel Version](https://img.shields.io/badge/Laravel-10%2B-red)](https://laravel.com) 11 | [![Total Downloads](https://img.shields.io/packagist/dt/grok-php/laravel)](https://packagist.org/packages/grok-php/laravel) 12 | ![GitHub Workflow Status](https://github.com/grok-php/laravel/actions/workflows/run-tests.yml/badge.svg) 13 | [![License](https://img.shields.io/badge/license-MIT-brightgreen)](LICENSE) 14 | 15 | --- 16 | 17 | ## Table of Contents 18 | 19 | - [Features](#features) 20 | - [Installation](#installation) 21 | - [Quick Start](#quick-start) 22 | - [Chat API](#chat-api) 23 | - [Vision Analysis](#vision-analysis-image-recognition) 24 | - [Error Handling](#error-handling) 25 | - [Available Grok AI Models](#available-grok-ai-models) 26 | - [Streaming Responses](#streaming-responses) 27 | - [Testing](#testing) 28 | - [Security](#security) 29 | - [Contributing](#contributing) 30 | - [License](#license) 31 | 32 | --- 33 | 34 | ## Features 35 | 36 | - **Seamless Laravel Integration** – Works with Laravel 10, 11, and 12 37 | - **Simple API Client** – Access Grok AI models with a clean and intuitive API 38 | - **Supports Chat & Vision** – Send both text and image-based requests 39 | - **Streaming Capable** – Enable real-time AI responses 40 | - **Configurable Defaults** – Set model, temperature, and timeout via config 41 | 42 | --- 43 | 44 | ## Installation 45 | 46 | Install via Composer: 47 | 48 | ```sh 49 | composer require grok-php/laravel 50 | ``` 51 | 52 | After installation, run the setup command: 53 | 54 | ```sh 55 | php artisan grok:install 56 | ``` 57 | 58 | This command will: 59 | 60 | - Publish the configuration file (`config/grok.php`). 61 | - Add necessary environment variables to `.env`. 62 | 63 | Add your API key in `.env`: 64 | 65 | ```sh 66 | GROK_API_KEY=your-api-key 67 | ``` 68 | 69 | --- 70 | 71 | ## Quick Start 72 | 73 | ### Chat API 74 | 75 | ```php 76 | use GrokPHP\Laravel\Facades\GrokAI; 77 | use GrokPHP\Client\Config\ChatOptions; 78 | use GrokPHP\Client\Enums\Model; 79 | 80 | $response = GrokAI::chat( 81 | [['role' => 'user', 'content' => 'Hello Grok!']], 82 | new ChatOptions(model: Model::GROK_2) 83 | ); 84 | 85 | echo $response->content(); 86 | ``` 87 | 88 | ### Vision Analysis (Image Recognition) 89 | 90 | ```php 91 | $response = GrokAI::vision()->analyze( 92 | 'https://example.com/sample.jpg', 93 | 'Describe this image' 94 | ); 95 | 96 | echo $response->content(); 97 | ``` 98 | 99 | ### Error Handling 100 | 101 | All errors are wrapped in the `GrokException` class: 102 | 103 | ```php 104 | use GrokPHP\Client\Exceptions\GrokException; 105 | 106 | try { 107 | $response = GrokAI::chat( 108 | [['role' => 'user', 'content' => 'Hello!']] 109 | ); 110 | echo $response->content(); 111 | } catch (GrokException $e) { 112 | echo "Error: " . $e->getMessage(); 113 | } 114 | ``` 115 | 116 | --- 117 | 118 | ## Available Grok AI Models 119 | 120 | | Model Enum | API Model Name | Description | 121 | |-----------------------------|----------------------|-----------------------------------------------------| 122 | | `Model::GROK_VISION_BETA` | grok-vision-beta | Experimental vision-enabled model | 123 | | `Model::GROK_2_VISION` | grok-2-vision | Advanced multi-modal vision model | 124 | | `Model::GROK_2_VISION_LATEST` | grok-2-vision-latest | Latest iteration of Grok vision models | 125 | | `Model::GROK_2_VISION_1212` | grok-2-vision-1212 | Enhanced vision model with performance improvements | 126 | | `Model::GROK_2_1212` | grok-2-1212 | Optimized chat model | 127 | | `Model::GROK_2` | grok-2 | Default general-purpose Grok model | 128 | | `Model::GROK_2_LATEST` | grok-2-latest | Latest iteration of Grok-2 | 129 | | `Model::GROK_BETA` | grok-beta | Experimental beta model | 130 | 131 | Default model used: `Model::GROK_2` 132 | 133 | --- 134 | 135 | ## Streaming Responses 136 | 137 | Enable real-time AI responses by setting `stream: true`: 138 | 139 | ```php 140 | $response = GrokAI::chat( 141 | [['role' => 'user', 'content' => 'Tell me a story']], 142 | new ChatOptions(model: Model::GROK_2, stream: true) 143 | ); 144 | ``` 145 | 146 | Streaming is useful for chatbots, assistants, and real-time applications. 147 | 148 | --- 149 | 150 | ## Testing 151 | 152 | To run PHPUnit tests, copy the `phpunit.xml.dist` file to `phpunit.xml` and set your API key. 153 | 154 | ```sh 155 | cp phpunit.xml.dist phpunit.xml 156 | ``` 157 | 158 | ```xml 159 | 160 | 161 | 162 | ``` 163 | 164 | Now, run the tests: 165 | 166 | ```sh 167 | composer test 168 | ``` 169 | 170 | --- 171 | 172 | ## Security 173 | 174 | If you discover a security vulnerability, please report it via email: 175 | [thefeqy@gmail.com](mailto:thefeqy@gmail.com) 176 | 177 | --- 178 | 179 | ## Contributing 180 | 181 | Check out [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on how to contribute. 182 | 183 | --- 184 | 185 | ## License 186 | 187 | This package is open-source software licensed under the [MIT License](LICENSE). 188 | -------------------------------------------------------------------------------- /assets/images/grok-laravel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/grok-php/laravel/1828412179b1aa50ffedcd130cb60eb358d41648/assets/images/grok-laravel.png -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "grok-php/laravel", 3 | "description": "Seamlessly integrate Grok AI into Laravel applications with an elegant, developer-friendly package. Leverage powerful AI models for chat, automation, and NLP while maintaining Laravel's expressive simplicity.", 4 | "type": "library", 5 | "license": "MIT", 6 | "homepage": "https://github.com/grok-php/laravel", 7 | "support": { 8 | "issues": "https://github.com/grok-php/laravel/issues", 9 | "source": "https://github.com/grok-php/laravel" 10 | }, 11 | "authors": [ 12 | { 13 | "name": "Grok PHP", 14 | "email": "thefeqy@gmail.com", 15 | "role": "organization" 16 | }, 17 | { 18 | "name": "Muhammed Elfeqy", 19 | "email": "thefeqy@gmail.com", 20 | "homepage": "https://github.com/thefeqy", 21 | "role": "creator" 22 | } 23 | ], 24 | "keywords": [ 25 | "Grok AI", 26 | "AI API", 27 | "PHP AI SDK", 28 | "Generative AI", 29 | "Machine Learning", 30 | "Natural Language Processing", 31 | "Large Language Model", 32 | "NLP", 33 | "AI Integration", 34 | "AI Client", 35 | "AI SDK", 36 | "REST API", 37 | "AI Text Generation", 38 | "Deep Learning", 39 | "Artificial Intelligence", 40 | "API Wrapper", 41 | "Text Processing", 42 | "AI-powered Applications", 43 | "AI Chatbot", 44 | "Language Model", 45 | "AI Research", 46 | "AI Developer Tools" 47 | ], 48 | "require": { 49 | "php": "^8.2 || ^8.3 || ^8.4", 50 | "laravel/framework": "^10.0|^11.0|^12.0", 51 | "grok-php/client": "^1.3" 52 | }, 53 | "autoload": { 54 | "psr-4": { 55 | "GrokPHP\\Laravel\\": "src/", 56 | "Tests\\": "tests/" 57 | } 58 | }, 59 | "extra": { 60 | "laravel": { 61 | "providers": [ 62 | "GrokPHP\\Laravel\\Providers\\GrokServiceProvider" 63 | ], 64 | "aliases": { 65 | "GrokAI": "GrokPHP\\Laravel\\Facades\\GrokAI" 66 | } 67 | } 68 | }, 69 | "require-dev": { 70 | "laravel/pint": "^1.20", 71 | "phpstan/phpstan": "^1.12", 72 | "mockery/mockery": "^1.6", 73 | "orchestra/testbench": "^9.0", 74 | "phpunit/phpunit": "^11" 75 | }, 76 | "minimum-stability": "stable", 77 | "prefer-stable": true, 78 | "scripts": { 79 | "test": "vendor/bin/phpunit", 80 | "test:types": "phpstan analyse src --ansi", 81 | "format": "vendor/bin/pint" 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /config/grok.php: -------------------------------------------------------------------------------- 1 | env('GROK_API_KEY'), 17 | 18 | /* 19 | |-------------------------------------------------------------------------- 20 | | API Base URL 21 | |-------------------------------------------------------------------------- 22 | | 23 | | Define the base URL for the Grok AI API. This usually points to the 24 | | official API endpoint but can be customized for different environments. 25 | | 26 | */ 27 | 'base_uri' => env('GROK_BASE_URI', DefaultConfig::BASE_URI->value), 28 | 29 | /* 30 | |-------------------------------------------------------------------------- 31 | | Default AI Model 32 | |-------------------------------------------------------------------------- 33 | | 34 | | Choose the default AI model to use when making requests. 35 | | Available models are defined in GrokPHP\Client\Enums\Model. 36 | | 37 | | Example: 'grok-2', 'grok-2-latest', 'grok-vision-beta' 38 | | 39 | */ 40 | 'default_model' => env('GROK_DEFAULT_MODEL', DefaultConfig::MODEL->value), 41 | 42 | /* 43 | |-------------------------------------------------------------------------- 44 | | Default Temperature 45 | |-------------------------------------------------------------------------- 46 | | 47 | | Controls the randomness of the AI’s responses. 48 | | Lower values (e.g., 0.1) make responses more deterministic, 49 | | while higher values (e.g., 1.5) make them more creative. 50 | | 51 | */ 52 | 'default_temperature' => env('GROK_DEFAULT_TEMPERATURE', (float) DefaultConfig::TEMPERATURE->value), 53 | 54 | /* 55 | |-------------------------------------------------------------------------- 56 | | Streaming Mode 57 | |-------------------------------------------------------------------------- 58 | | 59 | | Enable or disable streaming responses. When enabled, responses 60 | | will be returned in real-time as they are generated. 61 | | 62 | | Accepted values: true or false 63 | | 64 | */ 65 | 'enable_streaming' => env('GROK_ENABLE_STREAMING', DefaultConfig::STREAMING->value === 'true'), 66 | 67 | /* 68 | |-------------------------------------------------------------------------- 69 | | Default Timeout (in seconds) 70 | |-------------------------------------------------------------------------- 71 | | 72 | | Set the maximum time (in seconds) before the API request times out. 73 | | This helps prevent long waits for responses. 74 | | 75 | */ 76 | 'timeout' => env('GROK_API_TIMEOUT', (int) DefaultConfig::TIMEOUT->value), 77 | ]; 78 | -------------------------------------------------------------------------------- /phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 11 | 12 | 13 | 14 | tests 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/Commands/InstallGrokCommand.php: -------------------------------------------------------------------------------- 1 | isAlreadyInstalled()) { 20 | $this->warn('⚠️ Grok AI is already installed. No changes were made.'); 21 | 22 | return; 23 | } 24 | 25 | $this->info('🚀 Installing Grok AI for Laravel...'); 26 | 27 | $this->copyConfig(); 28 | $this->addEnvKeys('.env'); 29 | $this->addEnvKeys('.env.example'); 30 | 31 | // Mark installation as complete 32 | $this->markAsInstalled(); 33 | 34 | $this->info("\n✅ Installation complete! Don't forget to set your API key in your .env file."); 35 | 36 | // Ask user to star the repository 37 | if ($this->askToStarRepository()) { 38 | $this->openRepositoryInBrowser(); 39 | } 40 | } 41 | 42 | /** 43 | * Checks if Grok AI is already installed. 44 | */ 45 | private function isAlreadyInstalled(): bool 46 | { 47 | return File::exists(storage_path('grok_installed.lock')); 48 | } 49 | 50 | /** 51 | * Marks the package as installed by creating a lock file. 52 | */ 53 | private function markAsInstalled(): void 54 | { 55 | File::put(storage_path('grok_installed.lock'), now()->toDateTimeString()); 56 | } 57 | 58 | /** 59 | * Publishes the config file if it doesn't already exist. 60 | */ 61 | private function copyConfig(): void 62 | { 63 | if (file_exists(config_path('grok.php'))) { 64 | $this->warn('⚠️ Config file already exists: config/grok.php'); 65 | 66 | return; 67 | } 68 | 69 | $this->callSilent('vendor:publish', [ 70 | '--tag' => 'grok-config', 71 | ]); 72 | 73 | $this->info('✅ Config file published: config/grok.php'); 74 | } 75 | 76 | /** 77 | * Adds missing environment variables to the given env file with comments. 78 | */ 79 | private function addEnvKeys(string $envFile): void 80 | { 81 | $filePath = base_path($envFile); 82 | 83 | if (! file_exists($filePath)) { 84 | $this->warn("⚠️ Skipping: {$envFile} not found."); 85 | 86 | return; 87 | } 88 | 89 | $fileContent = file_get_contents($filePath); 90 | 91 | // Grok AI environment variables with comments 92 | $envSection = <<<'EOL' 93 | 94 | # -------------------------------------------------------------------------- 95 | # 🧠 GROK AI CONFIGURATION 96 | # These variables are required for Grok AI to function in Laravel. 97 | # -------------------------------------------------------------------------- 98 | 99 | GROK_API_KEY= 100 | GROK_BASE_URI=https://api.x.ai/v1/ 101 | GROK_DEFAULT_MODEL=grok-2 102 | GROK_DEFAULT_TEMPERATURE=0.7 103 | GROK_ENABLE_STREAMING=false 104 | GROK_API_TIMEOUT=30 105 | 106 | EOL; 107 | 108 | // Check if any of the variables already exist 109 | if (str_contains($fileContent, 'GROK_API_KEY')) { 110 | $this->info("✅ {$envFile} is already up to date."); 111 | 112 | return; 113 | } 114 | 115 | // Append the section to the .env file 116 | file_put_contents($filePath, PHP_EOL.$envSection.PHP_EOL, FILE_APPEND); 117 | 118 | $this->info("✅ Added Grok AI environment variables to {$envFile}"); 119 | } 120 | 121 | /** 122 | * Asks the user if they want to star the GitHub repository. 123 | */ 124 | private function askToStarRepository(): bool 125 | { 126 | if (! $this->input->isInteractive()) { 127 | return false; 128 | } 129 | 130 | return $this->confirm('⭐ Want to show Grok AI some love by starring it on GitHub?', false); 131 | } 132 | 133 | /** 134 | * Opens the repository in the user's default browser. 135 | */ 136 | private function openRepositoryInBrowser(): void 137 | { 138 | $this->info('Opening GitHub repository... 🌍'); 139 | 140 | if (PHP_OS_FAMILY === 'Darwin') { 141 | exec('open '.self::REPO_URL); 142 | } elseif (PHP_OS_FAMILY === 'Windows') { 143 | exec('start '.self::REPO_URL); 144 | } elseif (PHP_OS_FAMILY === 'Linux') { 145 | exec('xdg-open '.self::REPO_URL); 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/Facades/GrokAI.php: -------------------------------------------------------------------------------- 1 | mergeConfigFrom(__DIR__.'/../../config/grok.php', 'grok'); 17 | 18 | $this->app->singleton(GrokConfig::class, function () { 19 | return new GrokConfig( 20 | apiKey: config('grok.api_key'), 21 | baseUri: config('grok.base_uri', DefaultConfig::BASE_URI->value), 22 | timeout: (int) config('grok.timeout', (int) DefaultConfig::TIMEOUT->value), 23 | ); 24 | }); 25 | 26 | $this->app->singleton(GrokClient::class, fn ($app) => new GrokClient($app->make(GrokConfig::class))); 27 | 28 | $this->app->singleton(GrokAI::class, fn ($app) => new GrokAI($app->make(GrokClient::class))); 29 | 30 | $this->app->alias(GrokAI::class, 'grok-ai'); 31 | } 32 | 33 | public function boot(): void 34 | { 35 | if ($this->app->runningInConsole()) { 36 | $this->commands([ 37 | InstallGrokCommand::class, 38 | ]); 39 | 40 | $this->publishes([ 41 | __DIR__.'/../../config/grok.php' => config_path('grok.php'), 42 | ], 'grok-config'); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/Services/GrokAI.php: -------------------------------------------------------------------------------- 1 | client = $client; 18 | } 19 | 20 | /** 21 | * Send a chat completion request to Grok API. 22 | * 23 | * @throws GrokException 24 | */ 25 | public function chat(array $messages, ?ChatOptions $options = null): GrokResponse 26 | { 27 | $options = $options ?? new ChatOptions( 28 | model: Model::GROK_2, 29 | temperature: 0.7, 30 | stream: false 31 | ); 32 | 33 | $response = $this->client->chat($messages, $options); 34 | 35 | return new GrokResponse($response); 36 | } 37 | 38 | /** 39 | * Analyze an image using Grok Vision models. 40 | */ 41 | public function vision(): GrokVision 42 | { 43 | return new GrokVision($this->client); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/Services/GrokVision.php: -------------------------------------------------------------------------------- 1 | client = $client; 17 | } 18 | 19 | /** 20 | * Analyze an image using Grok Vision models. 21 | * 22 | * @throws GrokException 23 | */ 24 | public function analyze(string $imagePath, string $prompt, ?Model $model = null): GrokResponse 25 | { 26 | $response = $this->client->vision()->analyze($imagePath, $prompt, $model); 27 | 28 | return new GrokResponse($response); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Support/GrokResponse.php: -------------------------------------------------------------------------------- 1 | response = $response; 12 | } 13 | 14 | /** 15 | * Get the full API response. 16 | */ 17 | public function full(): array 18 | { 19 | return $this->response; 20 | } 21 | 22 | /** 23 | * Get only the assistant's message content. 24 | */ 25 | public function content(): string 26 | { 27 | return $this->response['choices'][0]['message']['content'] ?? 'No response received.'; 28 | } 29 | 30 | /** 31 | * Get the usage statistics for the API response. 32 | */ 33 | public function usage(): array 34 | { 35 | return $this->response['usage'] ?? []; 36 | } 37 | 38 | /** 39 | * Allow the GrokResponse object to be serialized to JSON. 40 | */ 41 | public function jsonSerialize(): array 42 | { 43 | return $this->response; 44 | } 45 | } 46 | --------------------------------------------------------------------------------