PHPackages                             ai-agent/ai-agent - 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. ai-agent/ai-agent

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

ai-agent/ai-agent
=================

A powerful Laravel package for AI integration with multiple providers

1.0.0(1y ago)13[1 issues](https://github.com/Arseno25/AiAgent-provider/issues)MITPHPPHP ^8.1

Since May 18Pushed 12mo ago1 watchersCompare

[ Source](https://github.com/Arseno25/AiAgent-provider)[ Packagist](https://packagist.org/packages/ai-agent/ai-agent)[ RSS](/packages/ai-agent-ai-agent/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (6)Versions (4)Used By (0)

AI Agent Provider
=================

[](#ai-agent-provider)

A Laravel package for integrating with various AI providers including OpenAI, Anthropic and Google's Gemini.

 [![Laravel](https://camo.githubusercontent.com/540748966581100bddf2fb60b744c38e16e00ec667c5f22dd6ae6554a3a41693/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302e782d7265642e737667)](https://camo.githubusercontent.com/540748966581100bddf2fb60b744c38e16e00ec667c5f22dd6ae6554a3a41693/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302e782d7265642e737667) [![License](https://camo.githubusercontent.com/08cef40a9105b6526ca22088bc514fbfdbc9aac1ddbf8d4e6c750e3a88a44dca/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d626c75652e737667)](https://camo.githubusercontent.com/08cef40a9105b6526ca22088bc514fbfdbc9aac1ddbf8d4e6c750e3a88a44dca/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d626c75652e737667) [![PHP](https://camo.githubusercontent.com/638e69a9ab1080dccb01716be78e182016bdeb34580c2e7070b120086d40df0e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312b2d707572706c652e737667)](https://camo.githubusercontent.com/638e69a9ab1080dccb01716be78e182016bdeb34580c2e7070b120086d40df0e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312b2d707572706c652e737667)

Features
--------

[](#features)

- 🤖 Simple, unified API for different AI providers
- 🔄 Support for text generation, chat completions, and embeddings
- 📊 Built-in logging of AI interactions
- 🚦 Rate limiting for API requests
- 🔌 Easy to extend with new AI providers
- 🔧 Blade directives for simple template integration
- 🚀 HTTP API endpoints for integration with frontend frameworks
- 🧠 Memory caching with configurable TTL
- 📝 Comprehensive logging for auditing and debugging

Table of Contents
-----------------

[](#table-of-contents)

- [AI Agent Provider](#ai-agent-provider)
    - [Features](#features)
    - [Table of Contents](#table-of-contents)
    - [Installation](#installation)
    - [Configuration](#configuration)
    - [Basic Usage](#basic-usage)
        - [Text Generation](#text-generation)
        - [Chat Completions](#chat-completions)
        - [Embeddings](#embeddings)
        - [Blade Directives](#blade-directives)
    - [Advanced Usage](#advanced-usage)
        - [Custom Options](#custom-options)
        - [Error Handling](#error-handling)
        - [Logging](#logging)
        - [Rate Limiting](#rate-limiting)
        - [Caching Responses](#caching-responses)
    - [HTTP API Endpoints](#http-api-endpoints)
        - [Get all providers](#get-all-providers)
        - [Generate text](#generate-text)
        - [Chat completion](#chat-completion)
        - [Generate embeddings](#generate-embeddings)
    - [Extending with Custom Providers](#extending-with-custom-providers)
    - [Artisan Commands](#artisan-commands)
    - [Troubleshooting](#troubleshooting)
        - [Common Issues](#common-issues)
        - [Debugging](#debugging)
    - [API Reference](#api-reference)
        - [AiAgent Facade](#aiagent-facade)
        - [AiLoggerService](#ailoggerservice)
    - [Testing](#testing)
    - [License](#license)
    - [Issues](#issues)
    - [Author](#author)

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

[](#installation)

You can install the package via composer:

```
composer require ai-agent/ai-agent
```

Publish the configuration file:

```
php artisan vendor:publish --provider="AiAgent\Providers\AiAgentServiceProvider" --tag="ai-agent-config"
```

Publish migrations (optional):

```
php artisan vendor:publish --provider="AiAgent\Providers\AiAgentServiceProvider" --tag="ai-agent-migrations"
```

Run migrations to create the AI interactions table:

```
php artisan migrate
```

Configuration
-------------

[](#configuration)

Configure your AI providers in the `config/ai-agent.php` file:

```
return [
    'default_provider' => env('AI_DEFAULT_PROVIDER', 'openai'),

    'providers' => [
        'openai' => [
            'enabled' => true,
            'adapter' => \AiAgent\Adapters\OpenAiAdapter::class,
            'api_key' => env('OPENAI_API_KEY'),
            'model' => env('OPENAI_MODEL', 'gpt-4-turbo-preview'),
            'embedding_model' => env('OPENAI_EMBEDDING_MODEL', 'text-embedding-3-small'),
        ],
        'anthropic' => [
            'enabled' => true,
            'adapter' => \AiAgent\Adapters\AnthropicAdapter::class,
            'api_key' => env('ANTHROPIC_API_KEY'),
            'model' => env('ANTHROPIC_MODEL', 'claude-3-opus-20240229'),
        ],
        'gemini' => [
            'enabled' => true,
            'adapter' => \AiAgent\Adapters\GeminiAdapter::class,
            'api_key' => env('GEMINI_API_KEY'),
            'model' => env('GEMINI_MODEL', 'gemini-pro'),
            'embedding_model' => env('GEMINI_EMBEDDING_MODEL', 'embedding-001'),
        ],
    ],

    'logging' => [
        'enabled' => env('AI_LOGGING_ENABLED', true),
        'channel' => env('AI_LOGGING_CHANNEL', 'stack'),
    ],

    'rate_limiting' => [
        'enabled' => env('AI_RATE_LIMITING_ENABLED', true),
        'max_requests' => env('AI_RATE_LIMITING_MAX_REQUESTS', 60),
        'decay_minutes' => env('AI_RATE_LIMITING_DECAY_MINUTES', 1),
    ],

    'cache' => [
        'enabled' => env('AI_CACHE_ENABLED', true),
        'ttl' => env('AI_CACHE_TTL', 3600), // seconds
        'prefix' => env('AI_CACHE_PREFIX', 'ai_agent_'),
    ],

    'routes' => [
        'enabled' => env('AI_ROUTES_ENABLED', true),
        'prefix' => env('AI_ROUTES_PREFIX', 'api/ai'),
        'middleware' => ['api', 'throttle:60,1'],
    ],
];
```

Basic Usage
-----------

[](#basic-usage)

### Text Generation

[](#text-generation)

```
use AiAgent\Facades\AiAgent;

// Using the default provider
$response = AiAgent::generate('Write a haiku about programming');

// Using a specific provider
$response = AiAgent::provider('anthropic')->generate('Write a haiku about programming');

// Using with options
$response = AiAgent::generate('Explain quantum computing', [
    'temperature' => 0.7,
    'max_tokens' => 500
]);
```

### Chat Completions

[](#chat-completions)

```
$messages = [
    ['role' => 'user', 'content' => 'Hello, who are you?'],
    ['role' => 'assistant', 'content' => 'I am an AI assistant. How can I help you today?'],
    ['role' => 'user', 'content' => 'Tell me a joke about programming.'],
];

$response = AiAgent::chat($messages);

// Using a specific provider with options
$response = AiAgent::provider('gemini')->chat($messages, [
    'temperature' => 0.9,
]);
```

### Embeddings

[](#embeddings)

```
// Single text embedding
$embedding = AiAgent::embeddings('Convert this text to a vector representation');

// Multiple text embeddings
$embeddings = AiAgent::embeddings([
    'This is the first text to embed',
    'This is the second text to embed'
]);
```

### Blade Directives

[](#blade-directives)

The package provides several Blade directives for easy template integration:

```
// First, add the styles for loading indicators in your layout
@aiStyles()

// Text generation with loading indicator
@ai('Generate a tagline for a tech company')

// Chat completion with loading indicator
@aichat([
    ['role' => 'user', 'content' => 'Write a short bio for a software developer']
])

// With specific provider and refresh option
@ai('Generate a tagline for a tech company', 'anthropic', true)
```

The directives now include a loading indicator that shows while the AI is processing your request, providing better UX for users.

Advanced Usage
--------------

[](#advanced-usage)

### Custom Options

[](#custom-options)

Each AI provider supports different options that can be passed to customize the request:

```
// OpenAI options
$options = [
    'temperature' => 0.7,           // Controls randomness (0.0 to 1.0)
    'max_tokens' => 500,            // Maximum length of the response
    'top_p' => 0.9,                 // Controls diversity via nucleus sampling
    'frequency_penalty' => 0.5,     // Reduces repetition of token sequences
    'presence_penalty' => 0.5,      // Encourages discussing new topics
];

$response = AiAgent::provider('openai')->generate('Write a story', $options);
```

### Error Handling

[](#error-handling)

Handle potential errors when working with AI providers:

```
use AiAgent\Exceptions\ProviderNotFoundException;
use AiAgent\Exceptions\AdapterNotFoundException;

try {
    $response = AiAgent::provider('unknown')->generate('Test prompt');
} catch (ProviderNotFoundException $e) {
    // Handle provider not found error
    report($e);
    $response = 'Sorry, the AI provider is not available.';
} catch (\Exception $e) {
    // Handle general errors
    report($e);
    $response = 'Sorry, there was an error processing your request.';
}
```

### Logging

[](#logging)

Enable or disable logging at runtime:

```
use AiAgent\Facades\AiAgent;

// Get the logger service
$logger = app(\AiAgent\Services\AiLoggerService::class);

// Disable logging for a specific operation
$logger->setEnabled(false);
$response = AiAgent::generate('This won\'t be logged');
$logger->setEnabled(true);

// Check if logging is enabled
if ($logger->isEnabled()) {
    // Do something
}
```

### Rate Limiting

[](#rate-limiting)

The package includes built-in rate limiting to prevent excessive API usage. You can configure this in the `config/ai-agent.php` file:

```
'rate_limiting' => [
    'enabled' => true,
    'max_requests' => 60,    // Maximum number of requests
    'decay_minutes' => 1,    // Time window in minutes
],
```

### Caching Responses

[](#caching-responses)

Cache AI responses to reduce API costs and improve performance:

```
use Illuminate\Support\Facades\Cache;

// With custom caching
$cacheKey = 'ai_response_' . md5('My prompt');

if (Cache::has($cacheKey)) {
    $response = Cache::get($cacheKey);
} else {
    $response = AiAgent::generate('My prompt');
    Cache::put($cacheKey, $response, now()->addHours(24));
}

// Using built-in caching with Blade directives
// The third parameter (true) forces a refresh, bypassing the cache
@ai('Generate a quote', 'openai', false)  // Uses cache if available
```

HTTP API Endpoints
------------------

[](#http-api-endpoints)

The package provides API endpoints for integration with frontend frameworks:

### Get all providers

[](#get-all-providers)

```
GET /api/ai/providers

```

Response:

```
{
    "providers": ["openai", "anthropic", "gemini"],
    "default": "openai"
}
```

### Generate text

[](#generate-text)

```
POST /api/ai/generate

```

Request:

```
{
    "prompt": "Explain artificial intelligence",
    "provider": "openai",  // optional
    "options": {
        "temperature": 0.7,
        "max_tokens": 500
    }
}
```

Response:

```
{
    "result": "Artificial intelligence (AI) refers to..."
}
```

### Chat completion

[](#chat-completion)

```
POST /api/ai/chat

```

Request:

```
{
    "messages": [
        {"role": "user", "content": "What is Laravel?"}
    ],
    "provider": "anthropic",  // optional
    "options": {
        "temperature": 0.7
    }
}
```

### Generate embeddings

[](#generate-embeddings)

```
POST /api/ai/embeddings

```

Request:

```
{
    "input": "Convert this text to a vector",
    "provider": "openai",  // optional
    "options": {
        "model": "text-embedding-3-small"  // optional
    }
}
```

Extending with Custom Providers
-------------------------------

[](#extending-with-custom-providers)

You can create your own adapters to integrate additional AI providers:

1. Create a new adapter class that extends the BaseAdapter:

```
namespace App\Adapters;

use AiAgent\Adapters\BaseAdapter;

class CustomAdapter extends BaseAdapter
{
    public function generate(string $prompt, array $options = []): string
    {
        // Implement your custom logic to generate text
        // Example:
        $api_key = $this->getConfig('api_key');
        $model = $this->getConfig('model', 'default-model');

        // Make API request...

        return $response;
    }

    public function chat(array $messages, array $options = []): array
    {
        // Implement chat functionality
    }

    public function embeddings($input, array $options = []): array
    {
        // Implement embeddings functionality
    }
}
```

2. Register your custom adapter in the config file:

```
'providers' => [
    // Other providers...

    'custom' => [
        'enabled' => true,
        'adapter' => \App\Adapters\CustomAdapter::class,
        'api_key' => env('CUSTOM_API_KEY'),
        'model' => env('CUSTOM_MODEL', 'default-model'),
        // Add any other configuration your adapter needs
    ],
],
```

3. Use your custom provider:

```
$response = AiAgent::provider('custom')->generate('Hello, custom AI!');
```

Artisan Commands
----------------

[](#artisan-commands)

The package provides helpful Artisan commands:

```
# List all available AI providers with their features
php artisan ai:providers
```

Troubleshooting
---------------

[](#troubleshooting)

### Common Issues

[](#common-issues)

1. **API Key Not Found**

    Make sure you've set the appropriate API keys in your `.env` file:

    ```
    OPENAI_API_KEY=your-openai-key
    ANTHROPIC_API_KEY=your-anthropic-key
    GEMINI_API_KEY=your-gemini-key

    ```
2. **Rate Limiting Errors**

    If you're hitting rate limits, consider:

    - Increasing the rate limit in the configuration
    - Implementing better caching strategies
    - Optimizing your prompt to reduce token usage
3. **Provider Not Found Error**

    Ensure the provider is correctly configured in `config/ai-agent.php` and that the `enabled` flag is set to `true`.

### Debugging

[](#debugging)

Enable more detailed logging to troubleshoot issues:

```
// In your .env file
AI_LOGGING_ENABLED=true
AI_LOGGING_CHANNEL=stack
```

API Reference
-------------

[](#api-reference)

The package provides the following core API:

### AiAgent Facade

[](#aiagent-facade)

- `AiAgent::provider(string $name)`: Get a specific AI provider
- `AiAgent::generate(string $prompt, array $options = [], string $provider = null)`: Generate text
- `AiAgent::chat(array $messages, array $options = [], string $provider = null)`: Get chat completion
- `AiAgent::embeddings(string|array $input, array $options = [], string $provider = null)`: Generate embeddings
- `AiAgent::getProviderNames()`: Get all available provider names

### AiLoggerService

[](#ailoggerservice)

- `log(string $provider, string $type, $input, $output, array $options = [], int $tokensUsed = 0, float $duration = 0, bool $success = true, string $error = null, ?int $userId = null)`: Log an AI interaction
- `isEnabled()`: Check if logging is enabled
- `setEnabled(bool $enabled)`: Enable or disable logging

Testing
-------

[](#testing)

```
composer test
```

License
-------

[](#license)

This package is open-sourced software licensed under the MIT license.

Issues
------

[](#issues)

If you encounter any issues or have suggestions, please submit them through our [GitHub Issues page](https://github.com/Arseno25/AiAgent-provider/issues).

Author
------

[](#author)

Created by [Arseno25](https://github.com/Arseno25)

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance30

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 85.7% 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

Unknown

Total

1

Last Release

365d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/85e02cfc526f93493a12b87cc4f5f22861e7eb2a88cff97137d284d789ae700a?d=identicon)[Arseno25](/maintainers/Arseno25)

---

Top Contributors

[![Arseno25](https://avatars.githubusercontent.com/u/77256511?v=4)](https://github.com/Arseno25 "Arseno25 (6 commits)")[![google-labs-jules[bot]](https://avatars.githubusercontent.com/in/842251?v=4)](https://github.com/google-labs-jules[bot] "google-labs-jules[bot] (1 commits)")

---

Tags

laravelaiopenaiazureGeminillmanthropicai-integration

###  Code Quality

TestsPest

### Embed Badge

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

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

###  Alternatives

[sbsaga/toon

🧠 TOON for Laravel — a compact, human-readable, and token-efficient data format for AI prompts &amp; LLM contexts. Perfect for ChatGPT, Gemini, Claude, Mistral, and OpenAI integrations (JSON ⇄ TOON).

6115.6k](/packages/sbsaga-toon)[cognesy/instructor-php

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

310107.9k1](/packages/cognesy-instructor-php)[symfony/ai-platform

PHP library for interacting with AI platform provider.

51927.7k136](/packages/symfony-ai-platform)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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