PHP Luminova: Ollama AI Agent Integration
Use the Ollama agent for chat, embeddings, vision, and local model management.
The Luminova Ollama agent (Luminova\AI\Agents\Ollama) provides a clean interface to the Ollama API, enabling local or self-hosted open-source model inference including chat, embeddings, vision, model management, custom model creation, and fine-tuning via Modelfiles.
Ollama works by building and running models locally (or via a remote server).There is no background training system—models are created instantly from a Modelfile.
This guide covers Ollama-specific methods and usage within Luminova.
For shared AI features and agent implementation, see: Base AI Agent (Luminova\Base\AbstractAiAgent)
To get started, install and run Ollama:https://ollama.com
Usages
Local Instance (Default)
use Luminova\AI\Agents\Ollama;
$agent = new Ollama(); // Connects to http://localhost:11434/api/Custom Host
$agent = new Ollama('http://192.168.1.50:11434/api/');Authenticated Remote Deployment
$agent = new Ollama(
baseurl: 'https://ollama.example.com/api/',
apiKey: env('OLLAMA_KEY')
);Via Application Config
Set handler = 'Ollama' and baseUrl = 'http://...' in App\Config\AI, then use the Agent proxy:
use Luminova\AI\Agent;
$reply = Agent::message('Hello from Ollama!');Text Generation
Raw Completion (generate)
Sends a plain prompt to the /generate endpoint without conversation context.
$response = $agent->setModel('llama3')->generate('Explain recursion in plain English.');
print_r($response);Single Message
$reply = $agent->message('What are the main features of PHP 8.3?');
echo $reply['content'] ?? '';Multi-Turn Chat
$reply = $agent->chat([
['role' => 'system', 'content' => 'You are a helpful Linux assistant.'],
['role' => 'user', 'content' => 'How do I list all running processes?'],
['role' => 'assistant', 'content' => 'You can use the `ps aux` command.'],
['role' => 'user', 'content' => 'How do I filter by process name?'],
]);
echo $reply['content'] ?? '';With Options
$reply = $agent->chat('Write a short poem about databases.', [
'model' => 'mistral',
'temperature' => 0.9,
]);Web Search
Note:Ollama's web search support requires a compatible server configuration.
$results = $agent->webSearch('Current PHP release notes', ['limit' => 5]);
print_r($results);Embeddings
Generate vector embeddings for semantic search, clustering, or RAG pipelines.
Single Embedding
$vector = $agent->embed('The quick brown fox');
// Returns a flat float array: [0.012, -0.034, ...]Batch Embeddings
$vectors = $agent->embed(['cat', 'feline', 'automobile']);
use Luminova\AI\Agent;
$score = Agent::compareCosineVector($vectors[0], $vectors[1]);
echo $score; // ~0.92 (cat vs feline are similar)With a Specific Embedding Model
$vector = $agent->embed('Some text to embed', [
'model' => 'nomic-embed-text',
]);Vision (Image Understanding)
Ollama supports multimodal models like llava that can process images alongside text.
Analyze an Image by URL
$content = $agent->vision(
'What is shown in this image?',
'https://example.com/photo.jpg',
['model' => 'llava']
);
echo $content['content'] ?? '';Analyze a Local File
$content = $agent->vision(
'Is there any text visible in this screenshot?',
'/tmp/screenshot.png'
);
echo $content['content'] ?? '';Compare Multiple Images
$content = $agent->vision(
'Describe the differences between these two images.',
['/tmp/before.png', '/tmp/after.png'],
['model' => 'llava']
);Model Management
List All Local Models
$models = $agent->models();
foreach ($models as $model) {
echo $model['name'] . PHP_EOL;
}Get Model Details
$info = $agent->model('llama3');
echo $info['modified_at'];Pull a Model from the Registry
$agent->pull('mistral');
$agent->pull('llama3:8b');Push a Model to the Registry
$agent->push('my-org/my-assistant');Delete a Local Model
$agent->delete('llama3');Creating Custom Models
create() builds a custom Ollama model from a Modelfile path or its text. Convert a structured array to Modelfile text before passing it to create().
From a Modelfile Path
$result = $agent->create('my-assistant', '/path/to/dataset.modelfile', [
'from' => 'llama3',
'system' => 'You are a helpful PHP assistant.',
]);From an Array Serialized as Modelfile Text
$model = $agent->create(
'php-assistant',
modelfile: Ollama::toModelFile([
'parameters' => [
'temperature' => 0.2,
'top_p' => 0.9,
],
]),
options: [
'from' => 'llama3',
'system' => 'You are a helpful assistant specialized in PHP.',
]
);From a Raw Modelfile String
$modelfile = "PARAMETER temperature 0.5\nPARAMETER top_p 0.95";
$result = $agent->create('custom-model', $modelfile, ['from' => 'mistral']);Fine-Tuning
fineTune() is a direct alias of create().
Note:
This is not traditional fine-tuning, the
fineTunemethod wrapscreatefor consistency.Ollama builds a new model by combining a base model with instructions and examples.
From a Modelfile
$result = $agent->fineTune('my-llama', '/path/to/dataset.modelfile', [
'system' => 'You are a helpful PHP assistant.',
]);From a Structured Dataset Array
fineTuneDataset() converts a PHP array to Modelfile format, writes a temp file, and calls create() automatically. The temp file is deleted after processing.
$result = $agent->fineTuneDataset([
'parameters' => ['temperature' => 0.7, 'max_tokens' => 256],
'messages' => [
['prompt' => 'What is PHP?', 'completion' => 'A server-side scripting language.'],
['prompt' => 'What is MySQL?', 'completion' => 'An open-source relational database.'],
],
], [
'suffix' => 'php-assistant',
'system' => 'You are a PHP expert.',
]);Checking Fine-Tune Status
$status = $agent->fineTuneStatus('php-assistant');
print_r($status);Error Handling
use Luminova\Exceptions\AIAgentException;
try {
$reply = $agent->message('Hello!');
} catch (AIAgentException $e) {
echo 'Ollama Error: ' . $e->getMessage();
}Class Definition
- Full namespace:
Luminova\AI\Agents\Ollama - This class extends Luminova\Base\AbstractAiAgent
- Inherited interfaces include AIAgentInterface and LazyObjectInterface.
Properties
endpoints
Ollama API endpoints.
/**
* @var array<string, string>
*/
protected array $endpoints = [
'generate' => 'generate',
'responses' => 'chat',
'embeddings' => 'embed',
'models' => 'tags',
'show' => 'show',
'pull' => 'pull',
'push' => 'push',
'delete' => 'delete',
'create' => 'create',
'search' => 'web_search',
];Methods
The Base AI Agent reference documents the shared constructor hook, request options, and provider method contracts. The sections below describe the behavior specific to this agent.
__construct
Create a new Ollama agent instance.
public function __construct(?string $baseUrl = null, ?string $apiKey = null)Parameters:
| Parameter | Type | Description |
|---|---|---|
$baseurl | string|null | Base URL of the Ollama server (default: http://localhost:11434/api/). |
$apiKey | string|null | Optional Bearer token for authenticated Ollama deployments. |
Example:
Local default:
$agent = new Ollama('http://localhost:11434/api/');
$reply = $agent->message('Explain recursion in plain English.');Remote / authenticated deployment:
$agent = new Ollama('https://ollama.example.com/api/', env('OLLAMA_KEY'));
App\Config\AI- For default application AI configuration.
create
Creates a custom model.
- An absolute path to a
.modelfiletext file - An absolute path to a JSON file (auto-converted via
toModelFile()) - A raw Modelfile string
public function create(string $model, array|string $modelfile, array $options = []): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$model | string | Suffix or display name for the resulting fine-tuned model (e.g. my-model). |
$modelfile | array<array-key, mixed>|string | Modelfile path or Modelfile text. Use Ollama::toModelFile() to serialize structured data before passing it here. |
$options | array<string, mixed> | Optional training parameters. @type string from Base model to fine-tune (e.g. llama3).@type string system System prompt to embed in the modelfile (Ollama only). |
Return:
array<array-key, mixed> - Return model creation result.
Throws:
- Luminova\Exceptions\AIAgentException - On network, provider request errors or malformed JSON in the response.
Note:
- Model creation uses a non-streaming request by default.
- Always ensure the base model exists (
pull('llama3')) before creating derived models.
Example:
Create Model:
$model = $agent->create('php-assistant',
modelfile: [
'parameters' => [
'temperature' => 0.2,
'top_p' => 0.9,
]
],
options: [
'from' => 'llama3',
'system' => 'You are a helpful assistant specialized in PHP.',
]
);delete
Delete a locally-stored model.
public function delete(string $model): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$model | string | Model name to delete (e.g. llama3). |
Return:
array<array-key, mixed> - Ollama API response.
Example:
$agent->delete('llama3');pull
Pull (download) a model from the Ollama model registry.
public function pull(string $model): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$model | string | Model name to pull (e.g. mistral, llama3:8b). |
Return:
array<array-key, mixed> - Ollama API response containing pull progress details.
Example:
$agent->pull('mistral');push
Push a locally-created model to the Ollama model registry.
public function push(string $model): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$model | string | Model name to push (must exist locally). |
Return:
array<array-key, mixed> - Ollama API response.
Example:
$agent->push('my-org/my-assistant');chat
Send a chat request through the agent’s configured endpoint. A string becomes a user message and streaming defaults to false.
public function chat(array|string $messages, array $options = []): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$messages | string\|array<string,mixed>\|array<int,array<string,mixed>> | Prompt, single message, or conversation history. |
$options | array<string,mixed> | Provider request options. |
Return:
array<array-key,mixed> - Returns the message field when present, or the full decoded response.
webSearch
Send the search prompt through the agent’s configured search endpoint.
public function webSearch(string $query, array $options = []): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$query | string | Search prompt. |
$options | array<string,mixed> | Provider request options. |
Return:
array<array-key,mixed> - Returns the provider’s search response data.
resolveConstructorArgs
Read the base URL and API key from the application AI configuration.
public static function resolveConstructorArgs(AI $config): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$config | App\Config\AI | Application AI configuration. |
Return:
array<int,mixed> - Returns the values in the order expected by the agent constructor.