PHP code example of jarir-ahmed / php-llm

1. Go to this page and download the library: Download jarir-ahmed/php-llm 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/ */

    

jarir-ahmed / php-llm example snippets


use JarirAhmed\PhpLlm\Client;

$ai = Client::create([
    'defaults' => ['llm' => 'openai'],
    'llm' => ['openai' => ['api_key' => 'sk-...']],
]);

// one-shot
echo $ai->ask('Explain Laravel in one line.');

// fluent — a fresh, isolated request each time
$res = $ai->chat()
    ->provider('openai')->model('gpt-4o')
    ->system('You are terse.')
    ->message('Capital of France?')
    ->chat();

echo $res['content'];                 // "Paris."
echo $res['usage']['total_tokens'];   // 27
echo '$' . $res['cost'];              // estimated USD cost

$ai = Client::create([
    'defaults' => ['llm' => 'groq'],
    'llm' => ['groq' => ['api_key' => getenv('GROQ_API_KEY')]],
]);
echo $ai->ask('Why is the LPU fast?');

use JarirAhmed\PhpLlm\Pricing\Pricing;
use JarirAhmed\PhpLlm\Support\Usage;

Pricing::set('my-finetune', 5.00, 15.00);   // $/1M input, $/1M output
$usd = Pricing::estimate('gpt-4o', new Usage(1_000_000, 1_000_000)); // 12.5
$breakdown = Pricing::breakdown('gpt-4o', new Usage(1000, 500));

use JarirAhmed\PhpLlm\Support\EventDispatcher;
use JarirAhmed\PhpLlm\Events\MessageReceived;

EventDispatcher::listen(MessageReceived::class, function (MessageReceived $e) {
    error_log("{$e->provider} {$e->model} took {$e->latency}s, cost \${$e->response['cost']}");
});

$person = $ai->chat()
    ->message('Extract: "Ada Lovelace, born 1815, mathematician."')
    ->structured([
        'type' => 'object',
        'properties' => [
            'name' => ['type' => 'string'],
            'born' => ['type' => 'integer'],
            'role' => ['type' => 'string'],
        ],
        '

foreach ($ai->chat()->message('Write a haiku')->stream() as $chunk) {
    echo $chunk['content'];
    flush();
}

$chat = $ai->conversation('user-42', 'openai', 'conversation');
echo $chat->say('My name is Sam.');
echo $chat->say('What is my name?');     // remembers "Sam"
echo $chat->totalCost();

use JarirAhmed\PhpLlm\Client;

Client::useDatabase('default', new PDO('sqlite:' . __DIR__ . '/ai.sqlite'));
$ai->memory()->driver('persistent')->add('user-42', ['role' => 'user', 'content' => 'hi']);

$vec = $ai->embed('text to embed');                       // ['embedding'=>[...], 'dimensions'=>1536]

$ai->vector('qdrant')->createCollection('docs', 1536);
$ai->vector('qdrant')->upsert('docs', [
    ['id' => '1', 'vector' => $vec['embedding'], 'payload' => ['text' => '...']],
]);

// RAG
$ai->rag()->ingestion()->ingestFromPath('handbook.md', 'docs');
$answer = $ai->rag()->collection('docs')->question('What is the refund policy?')->answer();
echo $answer['answer'];

$agent = $ai->agent('openai')
    ->tool('get_time', fn () => date('c'), 'Current time')
    ->maxSteps(5);

$result = $agent->run('What time is it?');
echo $result['response'];

$this->app->singleton(\JarirAhmed\PhpLlm\AIClient::class, fn () => \JarirAhmed\PhpLlm\Client::create([
    'llm' => ['openai' => ['api_key' => config('services.openai.key')]],
]));

$ai = Client::create(['llm' => ['openai' => ['api_key' => 'test']]]);
$ai->fake();                              // all providers return deterministic fakes
$this->assertSame('fake response', $ai->ask('anything'));
bash
composer