PHP code example of easybdit / laraveleasyai

1. Go to this page and download the library: Download easybdit/laraveleasyai 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/ */

    

easybdit / laraveleasyai example snippets


// Same code. Any provider. Just change the name.
$response = AI::provider('ollama')->chat($messages);    // Self-hosted, free
$response = AI::provider('openai')->chat($messages);    // ChatGPT
$response = AI::provider('anthropic')->chat($messages); // Claude
$response = AI::provider('deepseek')->chat($messages);  // DeepSeek

echo ai('What is Laravel?'); // running against a model on your own machine

use EasyAI\LaravelAI\Facades\AI;

AI::rag()->ingest('Refunds are accepted within 30 days of purchase.', 'policies');
$answer = AI::rag()->ask('What is the refund window?');
// "Refunds are accepted within 30 days of purchase."

use EasyAI\LaravelAI\Facades\AI;

$response = AI::chat([['role' => 'user', 'content' => 'What is Laravel?']]);
echo $response->content;

$answer = ai('What is Laravel?');

// routes/web.php — good enough for trying things out, no view/controller needed
use EasyAI\LaravelAI\Facades\AI;

Route::get('/test-ai', function () {
    $response = AI::chat([['role' => 'user', 'content' => 'What is Laravel?']]);
    return $response->content;
});

$messages = [
    ['role' => 'user', 'content' => 'What is Laravel?'],
];

$results = AI::rag()->source('project_5')->search('your query');
$answer  = AI::rag()->source('project_5')->ask('your question');
AI::rag()->flush('project_5');

// Store
AI::rag()->ingest('Laravel is a PHP framework using MVC.', 'docs');

// Ask
$answer = AI::rag()->ask('What is Laravel?');

// Search
$results = AI::rag()->search('MVC pattern');
// [['content' => '...', 'source' => 'docs', 'score' => 0.91]]

// Scoped
$results = AI::rag()->source('project_5')->search('your query');

// Flush
AI::rag()->flush();
AI::rag()->flush('project_5');

// Full-corpus keyword scan for "how many X" questions — top-K semantic
// search alone under-counts when relevant chunks rank outside K.
AI::rag()->countMatches('invoice', 'project_5');

// config/ai.php
'rag' => [
    'auto_index' => [
        'posts' => [
            'model'  => \App\Models\Post::class,
            'source' => 'site_posts',
            'text'   => fn ($post) => $post->title . "\n\n" . strip_tags($post->body),
            'when'   => fn ($post) => $post->is_published, // optional
        ],
    ],
],

interface VectorStoreInterface
{
    public function upsert(string $content, string $source, array $embedding): void;
    public function search(array $queryEmbedding, ?string $source, int $topK): array;
    public function delete(?string $source): void;
    public function count(?string $source): int;
}

$this->app->bind(
    \EasyAI\LaravelAI\RAG\Contracts\VectorStoreInterface::class,
    \EasyAI\LaravelAI\RAG\VectorStores\PgVectorStore::class
);

\App\Models\User::create([
    'name'     => 'Your Name',
    'email'    => '[email protected]',
    'password' => bcrypt('choose-a-real-password'),
]);

Gate::define('manage-ai-settings', fn ($user) => $user->hasRole('admin'));

'pricing' => [
    'openai' => [
        'image' => ['dall-e-3' => 0.04],              // flat USD per image
    ],
    'together' => [
        'image' => ['black-forest-labs/FLUX.1-schnell' => ['per_mp' => 0.0027]], // USD per megapixel
    ],
    'gemini' => [
        'image' => ['gemini-3.1-flash-image' => 0.04], // flat USD per image, same shape as OpenAI's
    ],
],

// config/ai.php
'bot_profiles' => [
    'support' => [
        'label'         => 'Support Bot',
        'provider'      => 'openai',
        'system_prompt' => 'You are a friendly support agent for Acme Inc.',
    ],
],

POST /ai-chat/api/sessions  { "profile": "support" }

// app/Services/MyProductResolver.php
use EasyAI\LaravelAI\Commerce\Contracts\ProductResolver;

class MyProductResolver implements ProductResolver
{
    public function search(array $criteria): array
    {
        // $criteria: ['keyword' => 'red dress', 'min_price' => 20, 'max_price' => 50, 'limit' => 4]
        return Product::query()
            ->when($criteria['keyword'] ?? null, fn ($q, $kw) => $q->where('name', 'like', "%{$kw}%"))
            ->when($criteria['max_price'] ?? null, fn ($q, $p) => $q->where('price', '<=', $p))
            ->limit($criteria['limit'] ?? 4)
            ->get()
            ->map(fn ($p) => ['id' => $p->id, 'name' => $p->name, 'price' => $p->price, 'currency' => 'USD'])
            ->all();
    }

    public function find(int|string $productId): ?array
    {
        $p = Product::find($productId);
        return $p ? ['id' => $p->id, 'name' => $p->name, 'price' => $p->price] : null;
    }
}

public function register(): void
{
    $this->app->bind(
        \EasyAI\LaravelAI\Commerce\Contracts\ProductResolver::class,
        \App\Services\MyProductResolver::class
    );
}

// app/Providers/AppServiceProvider.php
Gate::define('view-store-assistant', fn ($user) => $user->isAdmin());

// or per-call
AI::provider('ollama')->think(false)->chat($messages);

$url = AI::provider('openai')->generateImage('a red fox in snow');

$text  = AI::provider('openai')->transcribe(storage_path('app/recording.mp3'));
$audio = AI::provider('openai')->textToSpeech('Hello there!'); // raw mp3 bytes

Storage::disk('local')->put('reply.mp3', $audio);

$result = AI::provider('gemini')->generateImage('a red fox in snow');

'custom_providers' => [
    'lmstudio' => [
        'label'   => 'LM Studio (local)',
        'url'     => 'http://127.0.0.1:1234/v1',
        'api_key' => null,
        'model'   => 'local-model',
        'timeout' => 60,
    ],
],

AI::custom('lmstudio')->chat($messages);
// or, in the chat UI provider selector: "custom:lmstudio"

use EasyAI\LaravelAI\Agent\Tool;

$weather = Tool::make(
    name: 'get_weather',
    description: 'Get the current weather for a city.',
    parameters: ['type' => 'object', 'properties' => ['city' => ['type' => 'string']], '

$response = AI::provider('openai')->tools([$weather])->run([
    ['role' => 'user', 'content' => 'What is the weather in Paris?'],
]);

echo $response->content;
// "It's currently 22°C and sunny in Paris."

$calculator = Tool::make(
    name: 'calculate',
    description: 'Evaluate a basic arithmetic expression, e.g. "12 * (4 + 3)".',
    parameters: ['type' => 'object', 'properties' => ['expression' => ['type' => 'string']], '

$response = AI::provider('anthropic')->tools([$weather, $calculator])->run([
    ['role' => 'user', 'content' => 'What is 12 times 7?'],
]);

echo $response->content;                 // the final answer
$response->hasToolCalls();               // false on the final turn (that's how run() knows to stop)

use EasyAI\LaravelAI\Agent\Tools\WebSearchTool;

$response = AI::provider('openai')
    ->tools([WebSearchTool::make()])
    ->run([['role' => 'user', 'content' => 'What happened in the news today about Laravel?']]);

$this->app->bind(
    \EasyAI\LaravelAI\Agent\Contracts\WebSearchProvider::class,
    \App\Services\MySearchProvider::class // implements search(string $query, int $limit): array
);

$response = AI::provider('openai')->tools([$weather])->run(
    $messages,
    maxSteps: 5,
    onToolCall: null,                         // still available — see below
    onChunk: fn (string $chunk) => print($chunk),
);

$totalPromptTokens = $totalCompletionTokens = 0;

$response = AI::provider('openai')->tools([$weather])->run(
    $messages,
    maxSteps: 5,
    onToolCall: null,
    onChunk: null,
    onStep: function ($stepResponse) use (&$totalPromptTokens, &$totalCompletionTokens) {
        $totalPromptTokens += $stepResponse->getPromptTokens();
        $totalCompletionTokens += $stepResponse->getCompletionTokens();
    },
);

$response = AI::provider('ollama')
    ->model('qwen2:1.5b')
    ->temperature(0.9)
    ->maxTokens(500)
    ->systemPrompt('You are a helpful Laravel expert.')
    ->chat([['role' => 'user', 'content' => 'Explain middleware']]);

AI::provider('ollama')->stream(
    [['role' => 'user', 'content' => 'Write a poem']],
    function (string $chunk) { echo $chunk; }
);

use Illuminate\Support\Facades\Log;

foreach (['ollama', 'deepseek', 'openai'] as $provider) {
    try {
        if (!AI::provider($provider)->health()) continue;
        return AI::provider($provider)->chat($messages)->content;
    } catch (\Throwable $e) {
        Log::warning("{$provider} failed: {$e->getMessage()}");
    }
}

// or per-call, same "total attempts" meaning
AI::provider('openai')->retries(3, 500)->chat($messages);

$tokens = AI::estimateTokens('Hello world');
$tokens = AI::estimateTokens($messagesArray);

// config/ai.php
'pricing' => [
    'openai' => [
        'gpt-4o-mini' => ['input' => 0.15, 'output' => 0.60],
    ],
],

$response = AI::provider('openai')->model('gpt-4o-mini')->chat($messages);
$response->getEstimatedCost(); // 0.0007 (float, USD) — or null if that exact provider/model pair has no configured rate

$schema = [
    'type'       => 'object',
    'properties' => ['city' => ['type' => 'string'], 'temp_c' => ['type' => 'number']],
    'pond with city and temp_c.'],
]);

$response->getStructuredData(); // ['city' => 'Paris', 'temp_c' => 22]
$response->hasStructuredData(); // true

$vectors = AI::provider('openai')->model('text-embedding-3-small')->embed('Hello world');
$vectors[0]; // [0.0123, -0.0456, ...] — always an array of vectors, one per input

$vectors = AI::provider('openai')->embed(['first text', 'second text']); // batch

AI::provider('ollama')->keepAlive('10m')->chat($messages);
AI::provider('ollama')->options(['num_ctx' => 2048])->chat($messages);
AI::provider('ollama')->pullModel('llama3.1:8b');
AI::provider('ollama')->runningModels();
AI::provider('ollama')->deleteModel('old-model');

use EasyAI\LaravelAI\Exceptions\ConnectionException;
use EasyAI\LaravelAI\Exceptions\ProviderException;
use Illuminate\Support\Facades\Log;

try {
    $response = AI::provider('openai')->chat($messages);
} catch (ConnectionException $e) {
    Log::error("Connection failed: " . $e->getMessage());
} catch (ProviderException $e) {
    Log::error("Provider [{$e->getProvider()}]: " . $e->getMessage());
}

ai('Your question')
ai('Your question', 'openai')
ai('Your question', 'anthropic', 'claude-haiku-...')

// config/ai.php
return [
    'default' => env('AI_PROVIDER', 'ollama'),
    'providers' => [
        'ollama'    => ['driver' => 'ollama',    'url'     => env('AI_OLLAMA_URL'),    'model' => env('AI_OLLAMA_MODEL', 'qwen2:1.5b'),      'timeout' => env('AI_OLLAMA_TIMEOUT', 120)],
        'openai'    => ['driver' => 'openai',    'api_key' => env('AI_OPENAI_KEY'),    'model' => env('AI_OPENAI_MODEL', 'gpt-4o-mini'),      'timeout' => 60],
        'anthropic' => ['driver' => 'anthropic', 'api_key' => env('AI_ANTHROPIC_KEY'), 'model' => env('AI_ANTHROPIC_MODEL'),                  'timeout' => 60],
        'deepseek'  => ['driver' => 'deepseek',  'api_key' => env('AI_DEEPSEEK_KEY'),  'model' => env('AI_DEEPSEEK_MODEL', 'deepseek-chat'),  'timeout' => 60],
    ],
    'rag' => [
        'embed_provider' => env('AI_RAG_PROVIDER', 'ollama'),
        'embed_model'    => env('AI_RAG_EMBED_MODEL', 'nomic-embed-text'),
        'chat_provider'  => env('AI_RAG_CHAT_PROVIDER', null),
        'chunk_size'     => (int) env('AI_RAG_CHUNK_SIZE', 2000),
        'top_k'          => (int) env('AI_RAG_TOP_K', 3),
        'table'          => env('AI_RAG_TABLE', 'ai_documents'),
        'system_prompt'  => env('AI_RAG_SYSTEM_PROMPT', 'Answer using ONLY the context below. If unsure, say so.'),
    ],
];

// ❌ This shadows every package route, including its JSON APIs
Route::get('/{any}', fn () => view('app'))->where('any', '.*');

// ✅ Use fallback() instead — it only matches when nothing else did
Route::fallback(fn () => view('app'));

// routes/api.php, inside your existing auth:sanctum group
Route::post('/session-bridge', function (Request $request) {
    Auth::guard('web')->login($request->user());
    $request->session()->regenerate();
    return response()->json(['ok' => true]);
});

// config/ai.php
'chat' => [
    'identity_resolver' => fn ($request) => $request->user('sanctum')?->id,
],
bash
php artisan laravelai:install   # publishes /ai-chat, migrates, done
bash
php artisan laravelai:install
bash
php artisan vendor:publish --tag=ai-config
php artisan vendor:publish --tag=ai-chat-assets
php artisan migrate
bash
php artisan vendor:publish --tag=ai-chat-views
# → resources/views/vendor/laravelai/chat.blade.php
bash
ollama pull nomic-embed-text
php artisan migrate
bash
php artisan ai:rag:ingest storage/docs/manual.txt --source=manual
php artisan ai:rag:ingest storage/docs/ --flush
bash
php artisan laravelai:make-admin [email protected]
bash
php artisan tinker