PHP code example of tobiebenezer / php-ai

1. Go to this page and download the library: Download tobiebenezer/php-ai library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tobiebenezer / php-ai example snippets


use Tobiebenezer\Ai\AiAssistant;
use Tobiebenezer\Ai\DTO\AiMessage;
use Tobiebenezer\Ai\DTO\AiRequest;

$assistant = app(AiAssistant::class);

$imagePath = storage_path('app/receipts/receipt.jpg');
$base64Image = base64_encode(file_get_contents($imagePath));
$mimeType = mime_content_type($imagePath) ?: 'image/jpeg';

$message = AiMessage::userWithImage(
    'Describe this image and extract any visible text.',
    $base64Image,
    $mimeType
);

$response = $assistant->respond(new AiRequest([
    'messages' => [$message],
]));

echo $response->content;

$request = new AiRequest([
    'messages' => [
        AiMessage::userWithImage(
            'Extract the transaction reference, amount, and date from this receipt.',
            $base64Image,
            'image/jpeg'
        )
    ],
    'options' => [
        'temperature' => 0.1,
    ],
    'response_schema' => [
        'type' => 'object',
        'properties' => [
            'is_valid_receipt' => ['type' => 'boolean'],
            'bank_name'        => ['type' => ['string', 'null']],
            'session_id'       => ['type' => ['string', 'null']],
            'amount'           => ['type' => ['number', 'null']],
            'date'             => ['type' => ['string', 'null']],
        ],
        '

// config/ai.php
'settings_service' => \App\Services\Ai\AiSettingsService::class,



namespace App\Services\Ai;

use App\Models\Config;
use Illuminate\Support\Facades\Cache;

class AiSettingsService
{
    public function apply(): void
    {
        $configs = Cache::remember('app_ai_configs', 3600, function () {
            return Config::where('category', 'ai')->pluck('value', 'tag');
        });

        $activeProvider = $configs['ai_provider'] ?? 'openrouter';

        config([
            'ai.default_profile' => $activeProvider,
            'ai.providers.openrouter.key' => $configs['ai_openrouter_key'] ?? env('OPENROUTER_API_KEY'),
            'ai.profiles.openrouter.model' => $configs['ai_openrouter_model'] ?? 'google/gemini-2.0-flash',
            'ai.providers.gemini.key'     => $configs['ai_gemini_key'] ?? env('GEMINI_API_KEY'),
            'ai.profiles.gemini.model'    => $configs['ai_gemini_model'] ?? 'gemini-2.0-flash',
        ]);
    }
}



namespace App\Ai\Tools;

use Tobiebenezer\Ai\Tools\AnalyticalTool;
use App\Models\Sale;

class QuerySalesTool extends AnalyticalTool
{
    protected function modelClass()
    {
        return Sale::class;
    }

    protected function filterableColumns()
    {
        return ['branch_id', 'staff_id', 'status_id'];
    }

    protected function groupableColumns()
    {
        return ['branch_id', 'staff_id', 'status_id'];
    }

    protected function aggregateableColumns()
    {
        return ['total', 'discount'];
    }

    protected function defaultSelects()
    {
        return [
            'sales.id',
            'sales.total',
            'sales.discount',
            'sales.created_at',
            'branches.name as branch_name',
        ];
    }

    protected function joins()
    {
        return [
            ['branches', 'sales.branch_id', '=', 'branches.id'],
        ];
    }

    public function description()
    {
        return 'Query sales transactions with totals, discounts, and branch associations.';
    }
}



namespace App\Ai\Tools;

use Tobiebenezer\Ai\Contracts\Tool;
use Tobiebenezer\Ai\Guardrails\GuardrailContext;

class ExternalWeatherTool implements Tool
{
    public function name()
    {
        return 'get_weather';
    }

    public function description()
    {
        return 'Retrieve current weather for a city.';
    }

    public function schema()
    {
        return [
            'type' => 'object',
            'properties' => [
                'city' => ['type' => 'string', 'description' => 'The city name']
            ],
            '



namespace App\Ai\Guardrails;

use Tobiebenezer\Ai\Contracts\RuntimeGuardrail;
use Tobiebenezer\Ai\Guardrails\GuardrailContext;
use Tobiebenezer\Ai\Guardrails\GuardrailDecision;
use Tobiebenezer\Ai\Guardrails\GuardrailEvent;

class SensitiveDataBlockGuardrail implements RuntimeGuardrail
{
    public function appliesTo(GuardrailContext $context)
    {
        return true;
    }

    public function check(GuardrailEvent $event, GuardrailContext $context)
    {
        if ($event->phase === GuardrailEvent::BEFORE_PROVIDER_REQUEST) {
            // Inspect input for sensitive keywords
        }

        return GuardrailDecision::allow();
    }
}

// app/Providers/AppServiceProvider.php
use Tobiebenezer\Ai\Guardrails\CapabilitiesGuardrail as BaseCapabilities;
use App\Ai\Guardrails\CustomCapabilitiesGuardrail;

public function boot()
{
    $this->app->bind(BaseCapabilities::class, CustomCapabilitiesGuardrail::class);
}

'budget' => [
    'monthly_token_limit' => 5000000,
],
bash
composer 
bash
# Publish everything
php artisan vendor:publish --provider="Tobiebenezer\Ai\AiServiceProvider"

# Or publish individually
php artisan vendor:publish --tag="ai-config"
php artisan vendor:publish --tag="ai-migrations"
php artisan vendor:publish --tag="ai-stubs"
bash
php artisan migrate