PHPackages                             ghdj/laravel-ai-integration - 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. ghdj/laravel-ai-integration

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

ghdj/laravel-ai-integration
===========================

Laravel package for AI provider abstraction with support for OpenAI, Claude, and Gemini

v1.0.0(4mo ago)21MITPHPPHP ^8.1CI passing

Since Dec 14Pushed 4mo agoCompare

[ Source](https://github.com/GhDj/laravel-ai-integration)[ Packagist](https://packagist.org/packages/ghdj/laravel-ai-integration)[ RSS](/packages/ghdj-laravel-ai-integration/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (8)Versions (3)Used By (0)

Laravel AI Integration
======================

[](#laravel-ai-integration)

[![Tests](https://github.com/GhDj/laravel-ai-integration/actions/workflows/tests.yml/badge.svg)](https://github.com/GhDj/laravel-ai-integration/actions/workflows/tests.yml)[![Code Style](https://github.com/GhDj/laravel-ai-integration/actions/workflows/code-style.yml/badge.svg)](https://github.com/GhDj/laravel-ai-integration/actions/workflows/code-style.yml)[![Static Analysis](https://github.com/GhDj/laravel-ai-integration/actions/workflows/static-analysis.yml/badge.svg)](https://github.com/GhDj/laravel-ai-integration/actions/workflows/static-analysis.yml)[![Latest Version](https://camo.githubusercontent.com/d2dc8cb1227858c20be1edae75395cccde54d56086dfcdb07a95c1741d2cf367/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6768646a2f6c61726176656c2d61692d696e746567726174696f6e2e737667)](https://packagist.org/packages/ghdj/laravel-ai-integration)[![License](https://camo.githubusercontent.com/ad10676c10ad944897b37c2fcd7cc26834553d06e6ed7759e6ac8731ecf31fe8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6768646a2f6c61726176656c2d61692d696e746567726174696f6e2e737667)](https://packagist.org/packages/ghdj/laravel-ai-integration)[![PHP Version](https://camo.githubusercontent.com/cd0176dc81dd5eb686759ace10deb02cd0011be83d1afd18819b2f1028785ed4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6768646a2f6c61726176656c2d61692d696e746567726174696f6e2e737667)](https://packagist.org/packages/ghdj/laravel-ai-integration)

A Laravel package for seamless integration with multiple AI providers (OpenAI, Claude, Gemini) featuring rate limiting, cost tracking, and prompt templating.

Requirements
------------

[](#requirements)

- PHP 8.1+
- Laravel 10.0+

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

[](#installation)

```
composer require ghdj/laravel-ai-integration
```

Publish the configuration file:

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

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

[](#configuration)

Add your API keys to `.env`:

```
AI_DEFAULT_PROVIDER=openai

OPENAI_API_KEY=your-openai-key
OPENAI_DEFAULT_MODEL=gpt-4o

CLAUDE_API_KEY=your-claude-key
CLAUDE_DEFAULT_MODEL=claude-sonnet-4-20250514

GEMINI_API_KEY=your-gemini-key
GEMINI_DEFAULT_MODEL=gemini-1.5-pro
```

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

[](#basic-usage)

### Simple Chat

[](#simple-chat)

```
use Ghdj\AIIntegration\Facades\AI;

// Using default provider
$response = AI::provider()->chat([
    ['role' => 'user', 'content' => 'Hello, how are you?']
]);

echo $response->getContent();
```

### Switching Providers

[](#switching-providers)

```
// OpenAI
$response = AI::provider('openai')->chat([
    ['role' => 'user', 'content' => 'Explain quantum computing']
]);

// Claude
$response = AI::provider('claude')->chat([
    ['role' => 'user', 'content' => 'Explain quantum computing']
]);

// Gemini
$response = AI::provider('gemini')->chat([
    ['role' => 'user', 'content' => 'Explain quantum computing']
]);
```

### With System Message

[](#with-system-message)

```
$response = AI::provider('openai')->chat([
    ['role' => 'system', 'content' => 'You are a helpful coding assistant.'],
    ['role' => 'user', 'content' => 'Write a function to reverse a string in PHP']
]);
```

### Using Options

[](#using-options)

```
$response = AI::provider('openai')->chat(
    messages: [
        ['role' => 'user', 'content' => 'Write a haiku about programming']
    ],
    options: [
        'model' => 'gpt-4o',
        'temperature' => 0.7,
        'max_tokens' => 150,
    ]
);
```

### Text Completion

[](#text-completion)

```
$response = AI::provider('openai')->complete(
    'Translate to French: Hello, world!',
    ['temperature' => 0.3]
);

echo $response->getContent();
```

Streaming Responses
-------------------

[](#streaming-responses)

```
$stream = AI::provider('openai')->chatStream([
    ['role' => 'user', 'content' => 'Tell me a story']
]);

foreach ($stream as $chunk) {
    echo $chunk; // Output chunks as they arrive
    flush();
}

// Get final usage stats
echo "Tokens used: " . $stream->getTotalTokens();
```

Embeddings
----------

[](#embeddings)

```
// Single text
$response = AI::provider('openai')->embed('Hello world');
$vector = $response->getFirstEmbedding();

// Multiple texts
$response = AI::provider('openai')->embed([
    'First text to embed',
    'Second text to embed',
]);
$vectors = $response->getEmbeddings();

// Gemini batch embeddings
$response = AI::provider('gemini')->embed([
    'Text one',
    'Text two',
    'Text three',
]);
```

> Note: Claude does not support embeddings. Use OpenAI or Gemini.

Tool/Function Calling
---------------------

[](#toolfunction-calling)

### OpenAI Tools

[](#openai-tools)

```
$tools = [
    [
        'type' => 'function',
        'function' => [
            'name' => 'get_weather',
            'description' => 'Get the current weather for a location',
            'parameters' => [
                'type' => 'object',
                'properties' => [
                    'location' => [
                        'type' => 'string',
                        'description' => 'City name',
                    ],
                ],
                'required' => ['location'],
            ],
        ],
    ],
];

$response = AI::provider('openai')->chatWithTools(
    messages: [
        ['role' => 'user', 'content' => 'What is the weather in Paris?']
    ],
    tools: $tools
);

if ($response->hasToolCalls()) {
    foreach ($response->getToolCalls() as $toolCall) {
        $name = $toolCall['function']['name'];
        $args = json_decode($toolCall['function']['arguments'], true);

        // Execute tool and continue conversation
        $result = executeYourTool($name, $args);

        // Send tool result back
        $response = AI::provider('openai')->chat([
            ['role' => 'user', 'content' => 'What is the weather in Paris?'],
            ['role' => 'assistant', 'content' => null, 'tool_calls' => $response->getToolCalls()],
            ['role' => 'tool', 'tool_call_id' => $toolCall['id'], 'content' => json_encode($result)],
        ]);
    }
}
```

### Claude Tools

[](#claude-tools)

```
$tools = [
    [
        'name' => 'calculator',
        'description' => 'Perform basic math operations',
        'input_schema' => [
            'type' => 'object',
            'properties' => [
                'operation' => ['type' => 'string', 'enum' => ['add', 'subtract', 'multiply', 'divide']],
                'a' => ['type' => 'number'],
                'b' => ['type' => 'number'],
            ],
            'required' => ['operation', 'a', 'b'],
        ],
    ],
];

$response = AI::provider('claude')->chatWithTools(
    messages: [['role' => 'user', 'content' => 'What is 25 * 4?']],
    tools: $tools
);
```

### JSON Mode (OpenAI)

[](#json-mode-openai)

```
$response = AI::provider('openai')->chat(
    messages: [
        ['role' => 'user', 'content' => 'List 3 colors as JSON array']
    ],
    options: [
        'response_format' => ['type' => 'json_object'],
    ]
);

$data = json_decode($response->getContent(), true);
```

Prompt Templating
-----------------

[](#prompt-templating)

### Basic Templates

[](#basic-templates)

```
// Register a template
AI::registerPrompt('greeting', 'Hello {{ name }}, welcome to {{ place }}!');

// Render the template
$text = AI::renderPrompt('greeting', [
    'name' => 'John',
    'place' => 'Laravel'
]);
// Output: Hello John, welcome to Laravel!
```

### Templates with Defaults

[](#templates-with-defaults)

```
AI::registerPrompt('welcome', [
    'template' => 'Welcome {{ name | ucfirst }}, your role is {{ role }}.',
    'defaults' => ['role' => 'user'],
]);

echo AI::renderPrompt('welcome', ['name' => 'john']);
// Output: Welcome John, your role is user.
```

### System Prompts

[](#system-prompts)

```
AI::registerPrompt('assistant', [
    'template' => 'Help me with: {{ task }}',
    'system' => 'You are a helpful {{ specialty }} assistant.',
    'defaults' => ['specialty' => 'general'],
]);

$messages = AI::promptToMessages('assistant', [
    'task' => 'Write a unit test',
    'specialty' => 'PHP',
]);

// Returns:
// [
//     ['role' => 'system', 'content' => 'You are a helpful PHP assistant.'],
//     ['role' => 'user', 'content' => 'Help me with: Write a unit test'],
// ]

$response = AI::provider('openai')->chat($messages);
```

### Available Filters

[](#available-filters)

```
AI::registerPrompt('filters', '
    Upper: {{ text | upper }}
    Lower: {{ text | lower }}
    Capitalize: {{ text | ucfirst }}
');

echo AI::renderPrompt('filters', ['text' => 'hello WORLD']);
// Upper: HELLO WORLD
// Lower: hello world
// Capitalize: Hello WORLD
```

### Loading Templates from Files

[](#loading-templates-from-files)

Create template files in your configured prompts directory:

**prompts/summarize.txt**

```
Summarize the following text in {{ style }} style:

{{ content }}

```

**prompts/code-review.json**

```
{
    "template": "Review this {{ language }} code:\n\n```{{ language }}\n{{ code }}\n```",
    "system": "You are an expert code reviewer.",
    "defaults": {
        "language": "php"
    }
}
```

**prompts/translate.php**

```
