PHPackages                             halilcosdu/laravel-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. halilcosdu/laravel-ollama

ActiveLibrary[API Development](/categories/api)

halilcosdu/laravel-ollama
=========================

Laravel Ollama API Wrapper - Interact with the Ollama API

v1.2.0(1mo ago)269771MITPHPPHP ^8.2CI passing

Since Apr 23Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/halilcosdu/laravel-ollama)[ Packagist](https://packagist.org/packages/halilcosdu/laravel-ollama)[ Docs](https://github.com/halilcosdu/laravel-ollama)[ Fund](https://www.buymeacoffee.com/halilcosdu5)[ RSS](/packages/halilcosdu-laravel-ollama/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (6)Dependencies (51)Versions (15)Used By (0)

Laravel Ollama
==============

[](#laravel-ollama)

[![Latest Version on Packagist](https://camo.githubusercontent.com/69ae6ec66a90db5d3c69df843818e04841ce6eee429e3600a2890dbe30f50c4c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f68616c696c636f7364752f6c61726176656c2d6f6c6c616d612e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/halilcosdu/laravel-ollama)[![Total Downloads](https://camo.githubusercontent.com/52df3b65bb03186eacf4820470e0c97f7a3216afc556470d843c28251d723395/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f68616c696c636f7364752f6c61726176656c2d6f6c6c616d612e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/halilcosdu/laravel-ollama)

A fluent, Laravel-native client for running AI locally with [Ollama](https://ollama.com). Generate text, build conversations, stream tokens without buffering, enforce JSON schemas, call tools, create embeddings, use vision models, and manage the models on your Ollama server.

```
use HalilCosdu\Ollama\Facades\Ollama;

$answer = Ollama::model('gemma3')
    ->agent('You are a concise Laravel expert.')
    ->prompt('Explain service containers in one sentence.')
    ->stream(false)
    ->ask();
```

Why Laravel Ollama?
-------------------

[](#why-laravel-ollama)

- Fluent facade that feels natural in Laravel applications.
- First-class, memory-efficient NDJSON streaming through PHP generators.
- Structured outputs with JSON Schema for reliable application data.
- Generate, chat, vision, tool calling, embeddings, and model management.
- Hermetic test suite: normal tests never require a running Ollama instance.
- Tested across Laravel 11, 12, and 13, including PHP 8.5.

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

[](#requirements)

PackageSupported versionsPHP8.2–8.5Laravel11.x, 12.x, 13.xOllamaA reachable local or remote Ollama serverLaravel 13 requires PHP 8.3 or newer.

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

[](#installation)

Install the package:

```
composer require halilcosdu/laravel-ollama
```

Laravel discovers the service provider and `Ollama` facade automatically. Optionally publish the configuration:

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

Configure your application in `.env`:

```
OLLAMA_URL=http://127.0.0.1:11434
OLLAMA_MODEL=gemma3
OLLAMA_DEFAULT_PROMPT="Hello, how can I assist you today?"
OLLAMA_CONNECTION_TIMEOUT=30
```

Text generation
---------------

[](#text-generation)

`ask()` returns the decoded Ollama response as an array when streaming is disabled:

```
$response = Ollama::model('gemma3')
    ->agent('Answer as a senior PHP engineer.')
    ->prompt('When should I use a readonly class?')
    ->options(['temperature' => 0.2])
    ->keepAlive('10m')
    ->stream(false)
    ->ask();

$text = $response['response'];
```

Available generation controls include `agent()`, `prompt()`, `model()`, `format()`, `options()`, `raw()`, `stream()`, and `keepAlive()`.

Token streaming
---------------

[](#token-streaming)

`streamAsk()` and `streamChat()` open an Ollama NDJSON stream and lazily yield each decoded chunk. The complete response is never buffered in memory, making this suitable for long answers, console commands, queues, and streamed HTTP responses.

```
foreach (Ollama::model('gemma3')->prompt('Write a short story.')->streamAsk() as $chunk) {
    echo $chunk['response'] ?? '';
}
```

Stream chat content:

```
$messages = [['role' => 'user', 'content' => 'Teach me about Laravel queues.']];

foreach (Ollama::model('gemma3')->streamChat($messages) as $chunk) {
    echo data_get($chunk, 'message.content', '');
}
```

The generator throws `HalilCosdu\Ollama\Exceptions\OllamaStreamException` for malformed chunks and for errors reported in the stream. Because generators are lazy, the HTTP request begins when iteration starts.

### Stream directly from a Laravel route

[](#stream-directly-from-a-laravel-route)

```
use HalilCosdu\Ollama\Facades\Ollama;

Route::get('/explain', function () {
    return response()->stream(function () {
        foreach (Ollama::prompt('Explain dependency injection.')->streamAsk() as $chunk) {
            echo $chunk['response'] ?? '';
            ob_flush();
            flush();
        }
    }, headers: ['Content-Type' => 'text/plain; charset=UTF-8']);
});
```

Chat
----

[](#chat)

```
$response = Ollama::model('gemma3')->stream(false)->chat([
    ['role' => 'system', 'content' => 'You are a helpful Laravel mentor.'],
    ['role' => 'user', 'content' => 'What is route model binding?'],
]);

$text = $response['message']['content'];
```

For vision chat, place base64-encoded image data in the relevant message's `images` array. The `image()` convenience method applies to text generation through `ask()`.

Structured outputs
------------------

[](#structured-outputs)

Pass `json` or an entire JSON Schema to `format()`. Use `stream(false)` for a single, easily validated JSON response and a low temperature for consistency.

```
$schema = [
    'type' => 'object',
    'properties' => [
        'name' => ['type' => 'string'],
        'frameworks' => ['type' => 'array', 'items' => ['type' => 'string']],
    ],
    'required' => ['name', 'frameworks'],
];

$response = Ollama::model('gemma3')
    ->format($schema)
    ->options(['temperature' => 0])
    ->prompt('Describe the PHP ecosystem.')
    ->stream(false)
    ->ask();

$data = json_decode($response['response'], true, flags: JSON_THROW_ON_ERROR);
```

Tool calling
------------

[](#tool-calling)

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

$response = Ollama::model('qwen3')
    ->tools($tools)
    ->stream(false)
    ->chat([['role' => 'user', 'content' => 'What is the weather in Istanbul?']]);

$calls = data_get($response, 'message.tool_calls', []);
```

Your application remains responsible for validating arguments, executing approved tools, and returning tool results to the conversation.

Vision
------

[](#vision)

```
$response = Ollama::model('gemma3')
    ->prompt('Describe this image.')
    ->image(storage_path('app/photo.jpg'))
    ->stream(false)
    ->ask();
```

`image()` validates the path and sends the file as base64 data.

Embeddings
----------

[](#embeddings)

```
$one = Ollama::model('nomic-embed-text')->embed('Laravel is expressive.');
$batch = Ollama::model('nomic-embed-text')->embed(['first document', 'second document']);
```

`embeddings()` targets Ollama's deprecated `/api/embeddings` endpoint and remains available only for backward compatibility. Prefer `embed()`.

Model management and server information
---------------------------------------

[](#model-management-and-server-information)

```
$localModels = Ollama::models();
$runningModels = Ollama::ps();
$serverVersion = Ollama::version();
$details = Ollama::model('gemma3')->show();

Ollama::model('gemma3')->pull();
Ollama::model('gemma3')->copy('gemma3-backup');
Ollama::model('gemma3-backup')->delete();
Ollama::model('my-model')->create("FROM gemma3\nSYSTEM You are concise.");
Ollama::model('myorg/my-model')->push();
```

API reference
-------------

[](#api-reference)

MethodOllama endpointResult`ask()``POST /api/generate`Array, or raw Guzzle response with `stream(true)``streamAsk()``POST /api/generate`Generator yielding decoded chunks`chat($messages)``POST /api/chat`Array, or raw Guzzle response with `stream(true)``streamChat($messages)``POST /api/chat`Generator yielding decoded chunks`embed($input)``POST /api/embed`Embedding response array`models()``GET /api/tags`Local models`ps()``GET /api/ps`Running models`version()``GET /api/version`Server version`show()``POST /api/show`Model details`pull()` / `push()``POST /api/pull`, `/api/push`Fluent instance`create($modelfile)``POST /api/create`Fluent instance`copy($destination)``POST /api/copy`Fluent instance`delete()``DELETE /api/delete`Fluent instanceTesting and quality
-------------------

[](#testing-and-quality)

```
composer test
composer analyse
composer format
```

The default suite uses Laravel HTTP fakes and Guzzle mock streams, so it is deterministic and makes no network calls. To run the optional live smoke tests:

```
OLLAMA_INTEGRATION=1 OLLAMA_MODEL=gemma3 composer test -- --group=integration
```

Changelog, contributing, and security
-------------------------------------

[](#changelog-contributing-and-security)

See [CHANGELOG.md](CHANGELOG.md) for release history. Contributions and focused bug reports are welcome through GitHub. Please report security vulnerabilities privately through the repository's [security advisory page](https://github.com/halilcosdu/laravel-ollama/security/advisories/new).

Credits
-------

[](#credits)

- [Halil Cosdu](https://github.com/halilcosdu)
- Inspired by the original Ollama Laravel work from [Cloud Studio](https://github.com/cloudstudio/ollama-laravel)

License
-------

[](#license)

Laravel Ollama is open-source software licensed under the [MIT license](LICENSE.md).

###  Health Score

51

—

FairBetter than 95% of packages

Maintenance92

Actively maintained with recent releases

Popularity25

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 73.2% 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 ~161 days

Recently: every ~34 days

Total

6

Last Release

38d ago

Major Versions

v0.0.2 → v1.0.02026-04-09

### Community

Maintainers

![](https://www.gravatar.com/avatar/eb33d4d47ce7f6f885331f34e8ed984e57866237d54526a2e3c97bdcbb11ecbb?d=identicon)[halilcosdu](/maintainers/halilcosdu)

---

Top Contributors

[![halilcosdu](https://avatars.githubusercontent.com/u/6373017?v=4)](https://github.com/halilcosdu "halilcosdu (41 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (8 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (6 commits)")[![claude](https://avatars.githubusercontent.com/u/81847?v=4)](https://github.com/claude "claude (1 commits)")

---

Tags

laravelHalilCosdularavel-ollama

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[dedoc/scramble

Automatic generation of API documentation for Laravel applications.

2.2k12.6M140](/packages/dedoc-scramble)[defstudio/telegraph

A laravel facade to interact with Telegram Bots

818355.4k3](/packages/defstudio-telegraph)[rawilk/profile-filament-plugin

Profile &amp; MFA starter kit for filament.

3915.5k](/packages/rawilk-profile-filament-plugin)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5226.7k](/packages/simplestats-io-laravel-client)[lettermint/lettermint-laravel

Official Lettermint driver for Laravel

11124.6k1](/packages/lettermint-lettermint-laravel)

PHPackages © 2026

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