PHP code example of aimatchfun / laravel-ai

1. Go to this page and download the library: Download aimatchfun/laravel-ai 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/ */

    

aimatchfun / laravel-ai example snippets


$messages = [
    ['role' => 'user', 'content' => 'Hello, how are you?'],
    ['role' => 'assistant', 'content' => 'I am doing well, thank you!'],
    ['role' => 'user', 'content' => 'What can you help me with?']
];

use AIMatchFun\LaravelAI\Services\Message;

$messages = [
    Message::user('Hello, how are you?'),
    Message::assistant('I am doing well, thank you!'),
    Message::user('What can you help me with?')
];

return [
    'default' => env('AI_PROVIDER', 'ollama'),

    'providers' => [
        'ollama' => [
            'base_url' => env('OLLAMA_BASE_URL', 'http://localhost:11434'),
            'default_model' => env('OLLAMA_DEFAULT_MODEL', 'llama3'),
            'timeout' => env('OLLAMA_TIMEOUT', 30), // Timeout in seconds
        ],
        
        'openai' => [
            'api_key' => env('OPENAI_API_KEY'),
            'default_model' => env('OPENAI_DEFAULT_MODEL', 'gpt-4o'),
            'timeout' => env('OPENAI_TIMEOUT', 30), // Timeout in seconds
        ],
        
        'anthropic' => [
            'api_key' => env('ANTHROPIC_API_KEY'),
            'default_model' => env('ANTHROPIC_DEFAULT_MODEL', 'claude-3-opus-20240229'),
            'timeout' => env('ANTHROPIC_TIMEOUT', 30), // Timeout in seconds
        ],

        'novita' => [
            'api_key' => env('NOVITA_API_KEY'),
            'default_model' => env('NOVITA_DEFAULT_MODEL', 'deepseek/deepseek-v3-0324'),
            'timeout' => env('NOVITA_TIMEOUT', 30), // Timeout in seconds
        ],
    ],
];

use AIMatchFun\LaravelAI\Facades\AI;
use AIMatchFun\LaravelAI\Enums\AIProvider;

// Basic usage with default provider
$response = AI::prompt('What is Laravel?')
    ->run();

// $response is an object with:

// $response->answer (string)

// Specify a provider using string
$response = AI::provider('ollama')
    ->prompt('What is Laravel?')
    ->run();

// Specify a provider using enum (recommended for type safety)
$response = AI::provider(AIProvider::OLLAMA)
    ->prompt('What is Laravel?')
    ->run();

// Specify a model
$response = AI::provider('ollama')
    ->model('llama3')
    ->prompt('What is Laravel?')
    ->run();

// With system instruction
$response = AI::provider('ollama')
    ->model('llama3')
    ->systemInstruction('You are a helpful AI assistant.')
    ->prompt('What is Laravel?')
    ->run();

// Using preview messages for context
$messages = [
    ['role' => 'user', 'content' => 'Hello, how are you?'],
    ['role' => 'assistant', 'content' => 'I am doing well, thank you!']
];

$response = AI::provider('ollama')
    ->model('llama3')
    ->previewMessages($messages)
    ->prompt('What is Laravel?')
    ->run();

// Adjust creativity level (temperature) - accepts float between 0.1 and 2.0
$response = AI::provider('ollama')
    ->model('llama3')
    ->prompt('Write a poem about Laravel.')
    ->temperature(1.5)  // Higher values = more creative (0.1 to 2.0)
    ->run();

// Using response format for structured outputs (JSON schema)
$response = AI::provider('novita')
    ->model('deepseek/deepseek-v3-0324')
    ->responseFormat([
        'type' => 'json_object',
        'schema' => [
            'type' => 'object',
            'properties' => [
                'name' => ['type' => 'string'],
                'age' => ['type' => 'integer']
            ],
            '

$response = AI::prompt('What is Laravel?')->run();

$answer = $response->answer; // string
$inputTokens = $response->inputTokens; // int|null
$outputTokens = $response->outputTokens; // int|null

// Using array format
$messages = [
    ['role' => 'user', 'content' => 'Hello, who are you?'],
    ['role' => 'assistant', 'content' => 'I am an AI assistant.']
];

$response = AI::previewMessages($messages)
    ->prompt('What can you help me with?')
    ->run();

// Using Message objects
use AIMatchFun\LaravelAI\Services\Message;

$messages = [
    Message::user('Hello, who are you?'),
    Message::assistant('I am an AI assistant.')
];

$response = AI::previewMessages($messages)
    ->prompt('What can you help me with?')
    ->run();

// Request a JSON object response
$response = AI::provider('novita')
    ->model('deepseek/deepseek-v3-0324')
    ->responseFormat([
        'type' => 'json_object'
    ])
    ->prompt('Return a JSON object with name and age.')
    ->run();

// Request structured output with schema
$response = AI::provider('novita')
    ->model('deepseek/deepseek-v3-0324')
    ->responseFormat([
        'type' => 'json_object',
        'schema' => [
            'type' => 'object',
            'properties' => [
                'name' => ['type' => 'string'],
                'age' => ['type' => 'integer'],
                'email' => ['type' => 'string']
            ],
            '

use AIMatchFun\LaravelAI\Enums\AIProvider;

// Use enum instead of string (recommended for type safety)
$response = AI::provider(AIProvider::OLLAMA)
    ->prompt('What is Laravel?')
    ->run();

// Get all available providers
$allProviders = AIProvider::values();
// Returns: ['ollama', 'openai', 'anthropic', 'novita', 'openrouter', 'together']

// Get providers with labels
$options = AIProvider::options();
// Returns: ['ollama' => 'Ollama', 'openai' => 'OpenAI', ...]

// Check if a provider is valid
if (AIProvider::isValid('ollama')) {
    // Provider is valid
}

// Get provider from string value
$provider = AIProvider::fromValue('ollama');
// Returns: AIProvider::OLLAMA or null if not found

// Get provider from string value or throw exception
$provider = AIProvider::fromValueOrFail('ollama');
// Returns: AIProvider::OLLAMA or throws InvalidArgumentException

// Get label for a provider
$label = AIProvider::OLLAMA->label();
// Returns: 'Ollama'

use AIMatchFun\LaravelAI\Services\Providers\NovitaProvider;

$provider = new NovitaProvider(
    config('ai.providers.novita.api_key'),
    config('ai.providers.novita.default_model'),
    config('ai.providers.novita.timeout', 30)
);

$response = $provider
    ->setModel('deepseek/deepseek-v3-0324')
    ->setSystemInstruction('You are a helpful assistant.')
    ->setUserMessages([['role' => 'user', 'content' => 'Write a creative story.']])
    ->temperature(0.7)           // Controls randomness (higher = more creative)
    ->maxTokens(1000)           // Maximum number of tokens to generate
    ->topP(0.9)                 // Nucleus sampling, controls cumulative probability
    ->topK(50)                  // Limits candidate token count
    ->presencePenalty(0.1)       // Controls repeated tokens in the text
    ->frequencyPenalty(0.1)     // Controls token frequency in the text
    ->repetitionPenalty(1.1)     // Penalizes or encourages repetition
    ->generateResponse();

use AIMatchFun\LaravelAI\Enums\AIProvider;

// Use enum instead of string
$response = AI::provider(AIProvider::OLLAMA)
    ->prompt('What is Laravel?')
    ->run();

// Get all available providers
$allProviders = AIProvider::values();
// Returns: ['ollama', 'openai', 'anthropic', 'novita', 'openrouter', 'together']

// Get providers with labels
$options = AIProvider::options();
// Returns: ['ollama' => 'Ollama', 'openai' => 'OpenAI', ...]

// Check if a provider is valid
if (AIProvider::isValid('ollama')) {
    // Provider is valid
}

// Get provider from string value
$provider = AIProvider::fromValue('ollama');
// Returns: AIProvider::OLLAMA or null if not found

// Get provider from string value or throw exception
$provider = AIProvider::fromValueOrFail('ollama');
// Returns: AIProvider::OLLAMA or throws InvalidArgumentException

// Get label for a provider
$label = AIProvider::OLLAMA->label();
// Returns: 'Ollama'

use AIMatchFun\LaravelAI\Enums\NovitaModel;

// Use a specific model
$response = AI::provider('novita')
    ->model(NovitaModel::ERNIE_4_5_0_3B->value)
    ->prompt('What is Laravel?')
    ->run();

// Get all available models
$allModels = NovitaModel::getValues();

// Find a model by value
$model = NovitaModel::fromValue('baidu/ernie-4.5-0.3b');

use AIMatchFun\LaravelAI\Services\AIService;
use App\Services\AI\CustomProvider;

public function boot()
{
    $this->app->extend('ai', function (AIService $service, $app) {
        $service->extend('custom', function () {
            return new CustomProvider(
                config('ai.providers.custom.api_key'),
                config('ai.providers.custom.default_model')
            );
        });
        
        return $service;
    });
}
bash
php artisan vendor:publish --provider="AIMatchFun\LaravelAI\Providers\AIServiceProvider" --tag="config"
bash
php vendor/bin/phpunit tests/Integration
bash
php vendor/bin/phpunit tests/Integration/OpenAIProviderTest.php
bash
php vendor/bin/phpunit tests/Integration/OpenAIProviderTest.php --filter test_can_generate_response
bash
# Test OpenAI
php tests/test-openai.php

# Test Anthropic
php tests/test-anthropic.php

# Test Ollama
php tests/test-ollama.php

# Test Novita
php tests/test-novita.php

# Test OpenRouter
php tests/test-openrouter.php

# Test Together
php tests/test-together.php