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
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']}");
});
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']);