PHPackages                             phpllm/phpllm - 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. [API Development](/categories/api)
4. /
5. phpllm/phpllm

ActiveLibrary[API Development](/categories/api)

phpllm/phpllm
=============

One beautiful PHP API for OpenAI, Anthropic, Gemini, and more. Chat, Vision, Audio, Tools, Streaming.

v0.4.0(5mo ago)24MITPHPPHP ^8.1CI failing

Since Jan 20Pushed 5mo agoCompare

[ Source](https://github.com/khasinski/phpllm)[ Packagist](https://packagist.org/packages/phpllm/phpllm)[ RSS](/packages/phpllm-phpllm/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (6)Versions (5)Used By (0)

PHPLLM
======

[](#phpllm)

One beautiful PHP API for OpenAI, Anthropic, Gemini, and more.

[![PHPStan](https://camo.githubusercontent.com/0729e562e10fac943b16dbb271b4af26488f779a33fc82cc3eef1e37a432c0b4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230352d627269676874677265656e2e737667)](https://phpstan.org/)[![PHP Version](https://camo.githubusercontent.com/acffb6ae1962992d26e4466782832787e79504a6250f80d732c4283458b9f497/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e312d626c75652e737667)](https://php.net/)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE)

Inspired by [RubyLLM](https://rubyllm.com/), PHPLLM provides a unified, elegant interface for working with Large Language Models in PHP.

Features
--------

[](#features)

- 🔄 **Unified API** - Same interface for OpenAI, Anthropic, and more
- 💬 **Chat** - Multi-turn conversations with any model
- 👁️ **Vision** - Analyze images and documents
- 🔧 **Tools** - Function calling with automatic execution
- 📡 **Streaming** - Real-time response streaming
- 🧮 **Embeddings** - Generate and compare text embeddings
- 🎨 **Image Generation** - Create images with GPT Image 1.5
- ⚡ **Framework Ready** - Laravel &amp; Symfony integration

Installation
------------

[](#installation)

```
composer require phpllm/phpllm
```

Quick Start
-----------

[](#quick-start)

```
use PHPLLM\PHPLLM;

// Configure with your API keys
PHPLLM::configure([
    'openai_api_key' => getenv('OPENAI_API_KEY'),
    'anthropic_api_key' => getenv('ANTHROPIC_API_KEY'),
]);

// Start chatting
$chat = PHPLLM::chat();
$response = $chat->ask('What is PHP?');
echo $response->getText();
```

Usage
-----

[](#usage)

### Chat

[](#chat)

```
// Default model (gpt-4o-mini)
$chat = PHPLLM::chat();

// Specific model
$chat = PHPLLM::chat('gpt-5.2');           // OpenAI GPT-5.2 (latest)
$chat = PHPLLM::chat('gpt-5.2-codex');     // Optimized for coding
$chat = PHPLLM::chat('claude-sonnet-4-5-20250929'); // Latest Claude

// With configuration
$chat = PHPLLM::chat('gpt-4o')
    ->withInstructions('You are a helpful PHP expert.')
    ->withTemperature(0.7)
    ->withMaxTokens(1000);

$response = $chat->ask('Explain traits in PHP');
echo $response->getText();
```

### Multi-turn Conversations

[](#multi-turn-conversations)

```
$chat = PHPLLM::chat();

$chat->ask('My name is Alice.');
$response = $chat->ask('What is my name?');
// "Your name is Alice."
```

### Vision (Images &amp; PDFs)

[](#vision-images--pdfs)

```
$chat = PHPLLM::chat('gpt-4o');

// Use explicit named arguments for clarity
$chat->ask('What is in this image?', image: 'photo.jpg');
$chat->ask('Describe this', image: 'https://example.com/image.png');
$chat->ask('Compare these', image: ['image1.jpg', 'image2.jpg']);

// PDF documents
$chat = PHPLLM::chat('claude-sonnet-4-5-20250929');
$chat->ask('Summarize this document', pdf: 'report.pdf');

// Audio files
$chat->ask('Transcribe this', audio: 'recording.mp3');

// Generic file (auto-detected type)
$chat->ask('Process this', file: 'document.pdf');

// Using Attachment objects for more control
use PHPLLM\Core\Attachment;

$chat->ask('Analyze', image: Attachment::image('/path/to/photo.jpg'));
$chat->ask('From URL', image: Attachment::imageUrl('https://example.com/img.png'));
$chat->ask('Read PDF', pdf: Attachment::pdf('/path/to/doc.pdf'));
```

### Streaming

[](#streaming)

```
$chat = PHPLLM::chat();

$response = $chat->ask('Tell me a story', stream: function ($chunk) {
    echo $chunk->content;
    flush();
});
```

### Tool Calling

[](#tool-calling)

```
use PHPLLM\Core\Tool;

class GetWeather extends Tool
{
    protected string $name = 'get_weather';
    protected string $description = 'Get weather for a location';

    protected function parameters(): array
    {
        return [
            'location' => [
                'type' => 'string',
                'description' => 'City name',
                'required' => true,
            ],
        ];
    }

    public function execute(array $arguments): mixed
    {
        // Call your weather API
        return ['temperature' => 22, 'condition' => 'sunny'];
    }
}

$chat = PHPLLM::chat('gpt-4o')
    ->withTool(GetWeather::class)
    ->onToolCall(function ($call, $result) {
        echo "Called {$call->name}\n";
    });

$response = $chat->ask('What is the weather in Tokyo?');
```

### Embeddings

[](#embeddings)

```
// Single text
$embedding = PHPLLM::embed('Hello, world!');
echo $embedding->dimensions; // 1536

// Multiple texts
$embeddings = PHPLLM::embed(['Hello', 'World', 'Test']);

// Compare similarity
$sim = $embeddings[0]->similarity($embeddings[1]);
echo "Similarity: {$sim}"; // 0.0 to 1.0

// Custom model
$embedding = PHPLLM::embed('Hello', model: 'text-embedding-3-large');
```

### Image Generation

[](#image-generation)

```
// Generate an image (uses gpt-image-1.5 by default)
$image = PHPLLM::paint('A sunset over mountains');
echo $image->url;

// Save to file
$image->save('sunset.png');

// Options
$image = PHPLLM::paint('A cat', options: [
    'size' => '1024x1024',
    'quality' => 'hd',
    'style' => 'vivid',
]);

// Multiple images
$images = PHPLLM::paintMany('A dog', count: 3);

// Use legacy DALL-E 3 if needed (deprecated)
$image = PHPLLM::paint('A cat', model: 'dall-e-3');
```

Framework Integration
---------------------

[](#framework-integration)

### Laravel

[](#laravel)

See detailed Laravel examples below. For **Symfony**, see [SYMFONY.md](SYMFONY.md).

### Laravel Installation

[](#laravel-installation)

```
composer require phpllm/phpllm
```

Add the service provider (auto-discovered in Laravel 5.5+):

```
// config/app.php
'providers' => [
    PHPLLM\Integration\Laravel\PHPLLMServiceProvider::class,
],

'aliases' => [
    'AI' => PHPLLM\Integration\Laravel\Facades\AI::class,
],
```

Publish the config:

```
php artisan vendor:publish --tag=phpllm-config
```

### Configuration

[](#configuration)

```
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
PHPLLM_DEFAULT_MODEL=gpt-4o-mini
```

### Using the Facade

[](#using-the-facade)

```
use AI;

$chat = AI::chat();
$response = $chat->ask('Hello!');

$embedding = AI::embed('Hello');
$image = AI::paint('A sunset');
```

### Eloquent Integration

[](#eloquent-integration)

```
use PHPLLM\Integration\Laravel\Eloquent\ActsAsChat;

class Conversation extends Model
{
    use ActsAsChat;

    protected string $messagesRelation = 'messages';
    protected string $modelColumn = 'ai_model';

    public function messages()
    {
        return $this->hasMany(Message::class);
    }
}

// Usage
$conversation = Conversation::create(['ai_model' => 'gpt-4o']);
$response = $conversation->ask('Hello!');
// Messages are automatically persisted
```

Supported Providers
-------------------

[](#supported-providers)

ProviderChatVisionToolsStreamingEmbeddingsImagesOpenAI✅✅✅✅✅✅Anthropic✅✅✅✅❌❌Gemini🚧🚧🚧🚧🚧🚧Configuration Options
---------------------

[](#configuration-options)

```
PHPLLM::configure([
    // API Keys
    'openai_api_key' => 'sk-...',
    'anthropic_api_key' => 'sk-ant-...',
    'gemini_api_key' => '...',

    // Custom endpoints
    'openai_api_base' => 'https://api.openai.com/v1',
    'ollama_api_base' => 'http://localhost:11434',

    // Defaults
    'default_model' => 'gpt-4o-mini',
    'default_provider' => 'openai',  // Used for unknown models

    // Request settings
    'request_timeout' => 120,
    'max_retries' => 3,

    // Logging (PSR-3 compatible)
    'logging_enabled' => true,
    'logger' => $psrLogger,  // Auto-wired when both are set

    // Model aliases
    'model_aliases' => [
        'fast' => 'gpt-4o-mini',
        'smart' => 'claude-opus-4-5-20251101',
    ],
]);
```

### Dependency Injection

[](#dependency-injection)

For DI containers, instantiate classes directly instead of using the facade:

```
use PHPLLM\Core\Configuration;
use PHPLLM\Core\Chat;
use PHPLLM\Providers\OpenAI\OpenAIProvider;

// Create configuration for DI
$config = new Configuration([
    'openai_api_key' => $apiKey,
    'default_model' => 'gpt-4o',
]);

// Inject provider and create chat
$provider = new OpenAIProvider($config);
$chat = new Chat($provider, 'gpt-4o');

$response = $chat->ask('Hello!');
```

Error Handling
--------------

[](#error-handling)

```
use PHPLLM\Exceptions\RateLimitException;
use PHPLLM\Exceptions\AuthenticationException;
use PHPLLM\Exceptions\ApiException;
use PHPLLM\Exceptions\ConfigurationException;
use PHPLLM\Exceptions\ToolExecutionException;

try {
    $response = $chat->ask('Hello');
} catch (RateLimitException $e) {
    // Wait and retry
    sleep($e->getRetryAfter() ?? 60);
} catch (AuthenticationException $e) {
    // Invalid API key
} catch (ApiException $e) {
    // Other API error
    echo $e->getStatusCode();
    echo $e->getMessage();
}

// Configuration errors (invalid keys, unknown models)
try {
    PHPLLM::configure(['invalid_key' => 'value']);
} catch (ConfigurationException $e) {
    // Unknown configuration keys: invalid_key
}

try {
    PHPLLM::chat('unknown-model-xyz');
} catch (ConfigurationException $e) {
    // Cannot detect provider for model 'unknown-model-xyz'
}

// Tool execution errors
try {
    $chat->withTool(MyTool::class)->ask('Use the tool');
} catch (ToolExecutionException $e) {
    echo "Tool '{$e->toolName}' failed: {$e->getMessage()}";
    echo "Arguments: " . json_encode($e->arguments);
}
```

Testing
-------

[](#testing)

PHPLLM uses [PHP-VCR](https://php-vcr.github.io/) for integration tests:

```
# Run all tests
composer test

# Run unit tests only
vendor/bin/phpunit tests/Unit

# Run with coverage
vendor/bin/phpunit --coverage-html coverage
```

To record new cassettes:

1. Set your API keys in `.env`
2. Delete the cassette file in `tests/fixtures/vcr/`
3. Run the test

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

Credits
-------

[](#credits)

- Inspired by [RubyLLM](https://rubyllm.com/) by Carmine Paolino
- Built with ❤️ for the PHP community

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance71

Regular maintenance activity

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

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

Every ~0 days

Total

4

Last Release

163d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4cc26dfbb6f8738c22829c00cc879449528634450d96bb6504d05e82d1099631?d=identicon)[khasinski](/maintainers/khasinski)

---

Top Contributors

[![khasinski](https://avatars.githubusercontent.com/u/702380?v=4)](https://github.com/khasinski "khasinski (14 commits)")

---

Tags

phpaiopenaimachine learningGeminiclaudellmanthropicgptChatGpt

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/phpllm-phpllm/health.svg)

```
[![Health](https://phpackages.com/badges/phpllm-phpllm/health.svg)](https://phpackages.com/packages/phpllm-phpllm)
```

###  Alternatives

[theodo-group/llphant

LLPhant is a library to help you build Generative AI applications.

1.7k409.0k6](/packages/theodo-group-llphant)[mozex/anthropic-laravel

Laravel integration for the Anthropic API: facade, config publishing, install command, testing fakes, messages, streaming, tool use, thinking, and batches.

74331.3k1](/packages/mozex-anthropic-laravel)[vizra/vizra-adk

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

29434.2k](/packages/vizra-vizra-adk)[claude-php/claude-php-sdk-laravel

Laravel integration for the Claude PHP SDK - Anthropic Claude API

5223.2k](/packages/claude-php-claude-php-sdk-laravel)

PHPackages © 2026

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