PHPackages                             jarir-ahmed/php-llm - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. jarir-ahmed/php-llm

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

jarir-ahmed/php-llm
===================

Framework-agnostic unified AI/LLM toolkit for PHP — LLMs, embeddings, vector databases, RAG, agents, memory, cost tracking and structured output. Merges and extends manik/neuro + manik/cortex with zero framework coupling.

v1.0.0(yesterday)00MITPHPPHP ^8.3

Since Jun 8Pushed yesterdayCompare

[ Source](https://github.com/jarir2020/jarir-ahmed-php-llm)[ Packagist](https://packagist.org/packages/jarir-ahmed/php-llm)[ RSS](/packages/jarir-ahmed-php-llm/feed)WikiDiscussions main Synced yesterday

READMEChangelogDependencies (3)Versions (2)Used By (0)

jarir-ahmed/php-llm
===================

[](#jarir-ahmedphp-llm)

A **framework-agnostic** unified AI/LLM toolkit for PHP — one fluent API over many LLM, embedding and vector-database providers, plus RAG, agents, memory, **cost/token tracking** and **structured output**.

> This package merges and extends [`manik/neuro`](https://github.com/dev-manik-mia/neuro) and [`manik/cortex`](https://github.com/dev-manik-mia/cortex) (which are the same Laravel package under two names) into a single library with **zero framework coupling** — no `laravel/framework` dependency. Works in Laravel, Symfony, WordPress, Slim, or plain PHP.

[![PHP](https://camo.githubusercontent.com/c8d8dad6beb757a2b8acba331d16140813699543b88a37af0a81f20bd35f61de/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e332532422d626c7565)](https://php.net) [![License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](LICENSE)

---

What changed vs. neuro/cortex
-----------------------------

[](#what-changed-vs-neurocortex)

Areaneuro / cortexphp-llmFrameworkRequires `laravel/framework`**None** — pure PHP + GuzzleBootstrapServiceProvider + Facade`Client::create()` factoryHTTP`Illuminate\Support\Facades\Http`Guzzle-backed `Support\Http` (same fluent API) + retry + true SSE streamingConfigLaravel `config()``Support\Config` (dot-access, env fallback)DB (memory/pgvector)`Illuminate\...\DB`raw `PDO` with **self-healing** tablesSession memoryLaravel session`SessionStore` ($\_SESSION / in-memory / pluggable)Cost trackingflags only**`Pricing` + `Usage`**: real USD estimates per callStructured output—**JSON-schema `->structured()`** (native or instruct+parse)Providers7 LLMs**+ DeepSeek, Groq, Azure OpenAI, OpenRouter**Fluent clientshared, stateful builder**fresh `Generation` per call** + `ask()`, `conversation()`Install
-------

[](#install)

```
composer require jarir-ahmed/php-llm
```

Requires PHP 8.3+. `ext-pdo` is only needed for the persistent-memory and pgvector drivers.

Quick start
-----------

[](#quick-start)

```
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
```

Any value you don't override falls back to the packaged defaults, which read from environment variables (e.g. `OPENAI_API_KEY`). So in production you can often just do `Client::create()`.

LLM providers
-------------

[](#llm-providers)

ProviderKeyNotesOpenAI`openai`Anthropic`anthropic`Google Gemini`gemini`Ollama`ollama`local, no keyxAI Grok`grok`Mistral`mistral`Cohere`cohere`**DeepSeek**`deepseek`new**Groq**`groq`new**Azure OpenAI**`azure`new — set `base_url` (endpoint) + `deployment`**OpenRouter**`openrouter`new — optional `referer`/`title` headers```
$ai = Client::create([
    'defaults' => ['llm' => 'groq'],
    'llm' => ['groq' => ['api_key' => getenv('GROQ_API_KEY')]],
]);
echo $ai->ask('Why is the LPU fast?');
```

Cost &amp; token tracking
-------------------------

[](#cost--token-tracking)

Every `chat()` result carries normalized `usage` and an estimated `cost` (USD). Prices live in `Pricing` and are overridable:

```
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));
```

Hook every call for logging/metering:

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

Structured output (JSON)
------------------------

[](#structured-output-json)

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

// ['name' => 'Ada Lovelace', 'born' => 1815, 'role' => 'mathematician']
```

Uses native `response_format` JSON-schema on OpenAI-compatible providers, and an instruction + tolerant parser everywhere else.

Streaming
---------

[](#streaming)

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

OpenAI-family drivers stream true Server-Sent Events token-by-token via the Guzzle stream body.

Conversations with memory
-------------------------

[](#conversations-with-memory)

```
$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();
```

Memory drivers: `session` (web), `conversation` (in-process), `persistent` (PDO, self-creating table).

```
use JarirAhmed\PhpLlm\Client;

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

Embeddings, vectors &amp; RAG
-----------------------------

[](#embeddings-vectors--rag)

```
$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'];
```

Vector drivers: `qdrant`, `pinecone`, `pgvector` (PDO), `weaviate`, `milvus`, `chroma`.

Agents &amp; tool calling
-------------------------

[](#agents--tool-calling)

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

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

Using inside a framework
------------------------

[](#using-inside-a-framework)

Nothing framework-specific is required. In Laravel/Symfony just build the client once in a service/container binding:

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

You can also plug your framework's session and DB in: `SessionStore::use($yourStore)` and `Client::useDatabase('default', $pdo)`.

Testing without network
-----------------------

[](#testing-without-network)

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

For driver-level tests, inject a Guzzle mock: `PendingRequest::useClient($guzzleWithMockHandler)`.

Architecture
------------

[](#architecture)

```
Client::create() ── AIClient (hub)
                      ├─ chat()/generate() ─ Generation (fluent, per-request: usage+cost+structured)
                      ├─ conversation()    ─ Conversation (memory-backed multi-turn)
                      └─ managers ─ LLM / Embedding / Vector / Image / Speech / RAG / Memory / Agent
                                       └─ Drivers  (Support\Http → Guzzle)
Support: Config · Http/PendingRequest/Response · Database(PDO) · SessionStore · EventDispatcher · Env · Usage
Pricing: USD cost tables + estimate/breakdown

```

Credits
-------

[](#credits)

Built on the excellent work of **Manik Mia** (`manik/neuro`, `manik/cortex`). This package re-architects that code to be framework-agnostic and adds cost tracking, structured output, extra providers, and a polished fluent client.

License
-------

[](#license)

MIT.

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance100

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

1d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/20700f34ff813055154e843bbdbe04d33320c1e6a81bbb3301cad67cb8350fd3?d=identicon)[jarircse16](/maintainers/jarircse16)

---

Tags

aivectoropenaiagentsGeminillmanthropicdeepseekembeddingsraggroq

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/jarir-ahmed-php-llm/health.svg)

```
[![Health](https://phpackages.com/badges/jarir-ahmed-php-llm/health.svg)](https://phpackages.com/packages/jarir-ahmed-php-llm)
```

###  Alternatives

[aws/aws-sdk-php

AWS SDK for PHP - Use Amazon Web Services in your PHP project

6.3k532.1M2.5k](/packages/aws-aws-sdk-php)[cognesy/instructor-php

The complete AI toolkit for PHP: unified LLM API, structured outputs, agents, and coding agent control

317117.1k1](/packages/cognesy-instructor-php)[neuron-core/neuron-ai

The PHP Agentic Framework.

1.9k496.1k32](/packages/neuron-core-neuron-ai)[vizra/vizra-adk

Vizra Agent Development Kit - A comprehensive Laravel package for building intelligent AI agents.

29431.7k](/packages/vizra-vizra-adk)[soukicz/llm

LLM client with support for cache, tools and async requests

4411.4k](/packages/soukicz-llm)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
