PHP code example of f4php / ollaminator

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

    

f4php / ollaminator example snippets


// somewhere in your F4 config
final class Config
{
    public const string OLLAMINATOR_URL   = 'http://localhost:11434'; // Ollama host
    public const string OLLAMINATOR_MODEL = 'llama3.2';               // default model
    // ...
}

use F4\Ollaminator\Client;

$client = new Client();

// No model here — it comes from Config::OLLAMINATOR_MODEL
$response = $client->chat(
    messages: [
        ['role' => 'system', 'content' => 'You are a helpful assistant.'],
        ['role' => 'user',   'content' => 'Say hello in one sentence.'],
    ],
);

// ChatResponse is Stringable — casting yields the message content
echo $response;                     // "Hello! ..."
echo $response->message['content']; // same thing, explicitly

$response = $client->generate(
    prompt: 'Write a haiku about PHP.',
);

echo $response;           // GenerateResponse is Stringable
echo $response->response; // the generated text

$response = $client->embed(
    model: 'nomic-embed-text', // override the default just for this call
    input: ['The quick brown fox', 'jumps over the lazy dog'],
);

// float[][] — one vector per input
$vectors = $response->embeddings;

foreach ($client->listModels() as $model) {
    echo "{$model->name} ({$model->size} bytes)\n";
}

use F4\Ollaminator\ApiClient;
use F4\Ollaminator\Client;

$client = new Client(
    apiClient: new ApiClient(baseUrl: 'http://ollama.internal:11434', timeout: 120),
);

// or pin both a default model and a custom host:
$client = new Client(
    model: 'llama3.2',
    apiClient: new ApiClient(baseUrl: 'http://ollama.internal:11434'),
);

$response = $client->chat(
    messages: [['role' => 'user', 'content' => 'Give me a person as JSON.']],
    format: [
        'type' => 'object',
        'properties' => [
            'name' => ['type' => 'string'],
            'age'  => ['type' => 'integer'],
        ],
        '

use F4\Ollaminator\Exception\ConnectionException;
use F4\Ollaminator\Exception\ModelNotFoundException;
use F4\Ollaminator\Exception\OllamaException;

try {
    $response = $client->chat(messages: $messages);
} catch (ConnectionException $e) {
    // Ollama unreachable at the configured host
} catch (ModelNotFoundException $e) {
    // model isn't pulled locally (HTTP 404)
} catch (OllamaException $e) {
    // any other Ollama / transport error
}