PHPackages                             tenqz/ollama - 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. [API Development](/categories/api)
4. /
5. tenqz/ollama

ActiveLibrary[API Development](/categories/api)

tenqz/ollama
============

Php library for working with Ollama server.

v0.6.0(8mo ago)11415↓80%MITPHPPHP ^7.2|^8.0CI passing

Since Jul 20Pushed 8mo agoCompare

[ Source](https://github.com/tenqz/ollama)[ Packagist](https://packagist.org/packages/tenqz/ollama)[ RSS](/packages/tenqz-ollama/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (4)Versions (16)Used By (0)

[![Ollama PHP Client Library](logo.png)](logo.png)

Ollama PHP Client Library
=========================

[](#ollama-php-client-library)

Documentation for version v0.6.0

[![Build Status](https://github.com/tenqz/ollama/workflows/Tests/badge.svg)](https://github.com/tenqz/ollama/actions)[![Total Downloads](https://camo.githubusercontent.com/a7b501495acee975b588af1a32839cc3ccf158e84e5aa56cd5407548ef5f8dbd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f74656e717a2f6f6c6c616d61)](https://packagist.org/packages/tenqz/ollama)[![Latest Stable Version](https://camo.githubusercontent.com/04037492d48c700abb846344f6917c2839267d1bd2df76f595a7032a9719177d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f74656e717a2f6f6c6c616d61)](https://packagist.org/packages/tenqz/ollama)[![License](https://camo.githubusercontent.com/e38faaa45932d836799d9f8d49a79702d75adcb0f801655bb865aafa26665adc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f74656e717a2f6f6c6c616d61)](https://packagist.org/packages/tenqz/ollama)

About
-----

[](#about)

Ollama PHP Client Library is a robust, well-designed PHP client for interacting with the Ollama API. This library allows PHP developers to easily integrate large language models (LLMs) into their applications using the Ollama server.

Features
--------

[](#features)

- **Clean, domain-driven architecture** with clear separation of concerns
- **Comprehensive Ollama API support** including text generation and embeddings
- **Type-safe request and response handling** with full DTO support
- **Text generation** with advanced options (temperature, top-k, top-p, repetition penalty, and more)
- **Text embeddings** for semantic search, similarity, and vector operations
- **Multimodal support** for image inputs with base64-encoded images
- **Streaming support** for real-time text generation
- **Flexible configuration** with customizable timeouts and connection settings
- **PSR standards compliance** with proper interfaces and abstractions
- **Comprehensive test coverage** with 97+ unit tests for embeddings alone

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

[](#installation)

You can install the package via composer:

```
composer require tenqz/ollama
```

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

[](#requirements)

- **PHP 7.2 or higher** (supports PHP 8.0+ features)
- **cURL extension** for HTTP communication
- **JSON extension** for data serialization
- **Ollama server** running locally or remotely

Usage
-----

[](#usage)

### Text Generation

[](#text-generation)

```
use Tenqz\Ollama\Generation\Application\DTO\Request\GenerationRequest;
use Tenqz\Ollama\Generation\Application\DTO\Request\GenerationOptions;
use Tenqz\Ollama\Generation\Infrastructure\Client\OllamaGenerationClient;
use Tenqz\Ollama\Shared\Infrastructure\Config\OllamaServerConfig;
use Tenqz\Ollama\Transport\Infrastructure\Http\Client\CurlTransportClient;

// Configure the server connection
$config = new OllamaServerConfig('localhost', 11434);
$transportClient = new CurlTransportClient($config->getBaseUrl());

// Create the Generation API client
$client = new OllamaGenerationClient($transportClient);

// Create a generation request with options
$request = new GenerationRequest('llama3.2');
$request->setPrompt('Write a creative story about AI');
$request->setSystem('You are a creative writing assistant.');

// Configure generation options
$options = new GenerationOptions();
$options->setTemperature(0.8);      // More creative
$options->setTopK(40);              // Vocabulary diversity
$options->setNumPredict(500);       // Max tokens
$request->setOptions($options);

// Generate text
$response = $client->generate($request);
echo $response->getResponse();
```

### Text Embeddings

[](#text-embeddings)

```
use Tenqz\Ollama\Embedding\Application\DTO\Request\EmbeddingRequest;
use Tenqz\Ollama\Embedding\Infrastructure\Client\OllamaEmbeddingClient;
use Tenqz\Ollama\Shared\Infrastructure\Config\OllamaServerConfig;
use Tenqz\Ollama\Transport\Infrastructure\Http\Client\CurlTransportClient;

// Configure the server connection
$config = new OllamaServerConfig('localhost', 11434);
$transportClient = new CurlTransportClient($config->getBaseUrl());

// Create the Embedding API client
$client = new OllamaEmbeddingClient($transportClient);

// Create an embedding request
$request = new EmbeddingRequest('nomic-embed-text:latest', 'Hello world');

// Generate embedding vector
$response = $client->embed($request);

// Access the embedding vector
$embedding = $response->getEmbedding();        // First embedding (768-dimensional vector)
$dimension = $response->getDimension();        // Vector dimension (e.g., 768)

// Use embeddings for similarity search, clustering, etc.
echo "Embedding dimension: {$dimension}\n";
echo "First 5 values: " . implode(', ', array_slice($embedding, 0, 5));
```

Architecture
------------

[](#architecture)

The library follows Domain-Driven Design principles with a clear separation of concerns across multiple layers:

### Transport Layer

[](#transport-layer)

- **`TransportClientInterface`** - Interface for HTTP clients with GET/POST methods
- **`ResponseInterface`** - Interface for API responses with status and data access
- **`CurlTransportClient`** - cURL implementation with configurable timeouts and headers
- **`JsonResponse`** - JSON response implementation with data parsing

### Generation Layer (Text Generation)

[](#generation-layer-text-generation)

- **`GenerationRequest`** - Request DTO with prompts, options, images, streaming, templates
- **`GenerationOptions`** - Fine-grained control (temperature, top-k, top-p, repetition penalty, etc.)
- **`GenerationResponse`** - Response DTO with generated text and metadata
- **`GenerationClientInterface`** - Client interface for generation operations
- **`OllamaGenerationClient`** - Implementation with error handling and response transformation
- **`GenerationException`** - Domain-specific exception for generation errors

### Embedding Layer (Text Embeddings)

[](#embedding-layer-text-embeddings)

- **`EmbeddingRequest`** - Request DTO with model and input text
- **`EmbeddingResponse`** - Response DTO with embedding vectors (supports batch processing)
- **`EmbeddingClientInterface`** - Client interface for embedding operations
- **`OllamaEmbeddingClient`** - Implementation with error handling and vector processing
- **`EmbeddingException`** - Domain-specific exception for embedding errors

### Shared Layer

[](#shared-layer)

- **`OllamaServerConfig`** - Server configuration with host, port, and URL building
- **`OllamaApiEndpoints`** - API endpoint constants (`/api/generate`, `/api/embed`)
- Cross-cutting concerns and utilities used across domains

Advanced Features
-----------------

[](#advanced-features)

### Generation Options

[](#generation-options)

The library supports comprehensive generation options for fine-tuning model behavior:

**Sampling Parameters:**

- `temperature` (0.0-1.0) - Controls randomness (higher = more creative)
- `top_k` (1-100) - Limits vocabulary diversity
- `top_p` (0.0-1.0) - Nucleus sampling for focused responses
- `seed` (integer) - Deterministic outputs for reproducible results

**Generation Control:**

- `num_predict` (integer) - Maximum tokens to generate
- `repeat_penalty` (float) - Penalty for repetition
- `stop` (array) - Stop sequences to end generation

**Advanced:**

- `stream` (boolean) - Real-time streaming responses
- `format` (string) - Output format (e.g., 'json')
- `system` (string) - System message for role definition
- `images` (array) - Base64-encoded images for multimodal models
- `keep_alive` (string/int) - Model persistence duration

### Embedding Features

[](#embedding-features)

The Embedding layer supports:

**Request Options:**

- `model` (string) - Embedding model name (e.g., `nomic-embed-text:latest`)
- `input` (string) - Text to generate embeddings for
- `options` (array) - Additional model parameters
- `keep_alive` (string/int) - Model persistence duration

**Response Data:**

- `embeddings` (array) - Array of embedding vectors (supports batch processing)
- `dimension` (int) - Vector dimension (e.g., 768)
- `model` (string) - Model name used
- Performance metrics: `total_duration`, `load_duration`, `prompt_eval_count`

**Methods:**

- `getEmbedding()` - Get first embedding vector (single text)
- `getEmbeddings()` - Get all embedding vectors (batch processing)
- `getDimension()` - Get vector dimension
- `getCount()` - Get number of embeddings

Development
-----------

[](#development)

The library includes comprehensive development tools:

```
# Run tests
composer test

# Check code style
composer check-style

# Fix code style issues
composer fix-style

# Run static analysis
composer analyze

# Run all quality checks
composer check
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

33

—

LowBetter than 72% of packages

Maintenance58

Moderate activity, may be stable

Popularity20

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity39

Early-stage or recently created project

 Bus Factor1

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

Every ~5 days

Recently: every ~18 days

Total

15

Last Release

269d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/12949394?v=4)[Oleg Patsay](/maintainers/tenqz)[@tenqz](https://github.com/tenqz)

---

Top Contributors

[![tenqz](https://avatars.githubusercontent.com/u/12949394?v=4)](https://github.com/tenqz "tenqz (120 commits)")

---

Tags

phpapiclientaillmollamalarge-language-models

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tenqz-ollama/health.svg)

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

###  Alternatives

[theodo-group/llphant

LLPhant is a library to help you build Generative AI applications.

1.7k409.0k6](/packages/theodo-group-llphant)[deepseek-php/deepseek-php-client

deepseek PHP client is a robust and community-driven PHP client library for seamless integration with the Deepseek API, offering efficient access to advanced AI and data processing capabilities.

46688.8k5](/packages/deepseek-php-deepseek-php-client)[mozex/anthropic-laravel

Laravel integration for the Anthropic API: facade, config publishing, install command, testing fakes, messages, streaming, tool use, thinking, and batches.

74331.3k1](/packages/mozex-anthropic-laravel)[mozex/anthropic-php

PHP client for the Anthropic API: messages, streaming, tool use, thinking, web search, code execution, batches, and more.

49552.5k18](/packages/mozex-anthropic-php)[gemini-api-php/client

API client for Google's Gemini API

225274.6k5](/packages/gemini-api-php-client)[gemini-api-php/laravel

Gemini API client for Laravel

8917.4k](/packages/gemini-api-php-laravel)

PHPackages © 2026

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