PHPackages                             yannxtrem/ollama-bridge - 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. yannxtrem/ollama-bridge

ActiveLibrary[API Development](/categories/api)

yannxtrem/ollama-bridge
=======================

Laravel Client for Ollama API.

v1.0.0(3mo ago)11MITPHPPHP ^8.2

Since Jan 25Pushed 3mo agoCompare

[ Source](https://github.com/yannXtrem/ollama-bridge)[ Packagist](https://packagist.org/packages/yannxtrem/ollama-bridge)[ RSS](/packages/yannxtrem-ollama-bridge/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

Laravel Ollama Bridge
=====================

[](#laravel-ollama-bridge)

[![Latest Stable Version](https://camo.githubusercontent.com/01718cb47d2126010a3947bc1c23f5d38006f92a64b5b7fbc33ec0346195dfd5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f79616e6e787472656d2f6f6c6c616d612d6272696467653f6c6162656c3d76657273696f6e)](https://camo.githubusercontent.com/01718cb47d2126010a3947bc1c23f5d38006f92a64b5b7fbc33ec0346195dfd5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f79616e6e787472656d2f6f6c6c616d612d6272696467653f6c6162656c3d76657273696f6e)[![License](https://camo.githubusercontent.com/c89febf16880852d424b89bd5a82b6a7b0e94d6eef8918859feb0b2657727a59/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f79616e6e787472656d2f6f6c6c616d612d627269646765)](https://camo.githubusercontent.com/c89febf16880852d424b89bd5a82b6a7b0e94d6eef8918859feb0b2657727a59/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f79616e6e787472656d2f6f6c6c616d612d627269646765)

**Laravel Ollama Bridge** is a robust HTTP client designed to connect your Laravel application to a remote Laravel server hosting LLMs via [Ollama](https://ollama.com/).

It handles authentication via **Laravel Sanctum**, manages timeouts, provides fine-grained error handling, and allows dynamic model switching (Gemma, Mistral, Llama3, etc.) without changing code.

🚀 Features
----------

[](#-features)

- **Secure**: Built-in support for Laravel Sanctum (Bearer Token authentication).
- **Model Agnostic**: Switch between models (e.g., from `gemma` to `mistral`) via config or at runtime.
- **Robust Error Handling**: Maps HTTP errors (401, 403, 422, 500) to descriptive PHP Exceptions.
- **Laravel Native**: Includes a Service Provider, Facade, and fully typed config.
- **Resilient**: Configurable timeouts and connection checks.

📋 Requirements
--------------

[](#-requirements)

- PHP 8.2 or higher
- Laravel 11.0 or higher

📦 Installation
--------------

[](#-installation)

Install the package via Composer:

```
composer require yannxtrem/ollama-bridge
```

⚙️ Configuration
----------------

[](#️-configuration)

### 1. Publish Configuration

[](#1-publish-configuration)

Publish the configuration file to `config/ollama-bridge.php`:

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

### 2. Environment Variables

[](#2-environment-variables)

Add the following variables to your `.env` file:

```
# The URL of your remote AI Server
OLLAMA_BRIDGE_URL=https://api.your-ai-server.com

# The Sanctum Token generated on the AI Server
OLLAMA_BRIDGE_TOKEN=your-secret-sanctum-token

# The default model to use (gemma, mistral, llama3, etc.)
OLLAMA_BRIDGE_MODEL=gemma

# Request timeout in seconds (useful for long generations)
OLLAMA_BRIDGE_TIMEOUT=60
```

Voici la section **Usage** révisée et considérablement détaillée. Elle explique chaque paramètre de la méthode `ask()`, montre comment utiliser les arguments nommés (PHP 8+) et fournit des exemples concrets pour différents cas d'utilisation (rôles système, créativité).

Tu peux remplacer l'ancienne section `## 🛠 Usage` par celle-ci :

---

🛠 Usage
-------

[](#-usage)

The main entry point of this package is the `ask()` method. It handles the communication with the remote AI API.

### Method Signature

[](#method-signature)

```
public function ask(
    string $prompt,
    ?string $system = null,
    ?float $temperature = null
): string
```

### Parameters

[](#parameters)

ParameterTypeRequiredDescription`$prompt``string`**Yes**The main input or question you want to send to the AI.`$system``string`NoThe system instructions (persona). Defines how the AI should behave (e.g., *"You are a senior developer"*).`$temperature``float`NoControls randomness/creativity. Range: `0.0` (deterministic/focused) to `1.0` (creative/random).---

### Examples

[](#examples)

#### 1. Basic Request

[](#1-basic-request)

The simplest way to use the client. It uses the default model configuration.

```
use Yannxtrem\OllamaBridge\OllamaBridge;

public function index(OllamaBridge $ai)
{
    // Simple question
    $answer = $ai->ask("What is Laravel?");

    return $answer;
}
```

#### 2. Using a System Persona

[](#2-using-a-system-persona)

Use the `$system` parameter to give context or define a role for the AI. This is crucial for getting specific types of answers.

```
$prompt = "Explain the Singleton pattern.";
$system = "You are a sarcastic senior engineer who explains concepts using cooking metaphors.";

$answer = $ai->ask($prompt, $system);
// Output: "Listen up! A Singleton is like having only ONE master chef in the kitchen..."
```

#### 3. Controlling Creativity (Temperature)

[](#3-controlling-creativity-temperature)

Use the `$temperature` parameter to adjust the output.

- **Low Temperature (0.1 - 0.3)**: Best for code generation, facts, and technical documentation.
- **High Temperature (0.7 - 1.0)**: Best for creative writing, brainstorming, and poetry.

```
// Very precise (Deterministic)
$code = $ai->ask("Write a JSON parser in PHP", null, 0.1);

// Very creative
$poem = $ai->ask("Write a poem about servers", null, 0.9);
```

#### 4. Using Named Arguments (Recommended)

[](#4-using-named-arguments-recommended)

PHP 8 named arguments make the code much more readable, especially when you want to skip the `$system` parameter but set the `$temperature`.

```
$response = $ai->ask(
    prompt: "List 5 unique cat names",
    temperature: 0.8
);
```

### 🔄 Advanced: Dynamic Model Switching

[](#-advanced-dynamic-model-switching)

You can chain the `model()` method before calling `ask()` to switch the LLM for a specific request. This overrides the `default_model` in your config.

```
// Use 'mistral' for a quick chat
$chat = $ai->model('mistral')->ask("Hello!");

// Use 'llama3' for complex reasoning
$analysis = $ai->model('llama3')->ask(
    prompt: "Analyze this large dataset...",
    system: "You are a data analyst.",
    temperature: 0.2
);
```

### ⚡ Checking Service Status

[](#-checking-service-status)

Before sending a request, you might want to check if the remote inference server is reachable.

```
if (! $ai->isOnline()) {
    return "The AI service is currently down for maintenance.";
}

return $ai->ask("Hello");
```

🔌 Server Requirements
---------------------

[](#-server-requirements)

This package acts as a **Client**. It expects your remote Laravel Server to expose endpoints compatible with the following structure.

The URLs are constructed as: `{base_url}/api/{model}/{action}`.

MethodEndpointDescription`POST``/api/{model}/ask`Sends the prompt to the LLM.`GET``/api/{model}/status`Checks if the service is up.### Expected Server Response (Success)

[](#expected-server-response-success)

The server must return a JSON object with a `data.response` key.

```
{
    "data": {
        "response": "Here is the answer generated by the AI..."
    }
}
```

### Expected Server Response (Error)

[](#expected-server-response-error)

Standard Laravel validation or error structure.

```
{
    "message": "Validation Error",
    "errors": {
        "prompt": ["The prompt field is required."]
    }
}
```

⚠️ Error Handling
-----------------

[](#️-error-handling)

The `ask()` method throws standard `\Exception` with translated messages based on the HTTP status code:

- **401**: Invalid AI Configuration (Token rejected).
- **403**: Access Denied (Unauthorized IP or Scope).
- **422**: Malformed Request (Validation error on server).
- **500**: AI Server Error.
- **ConnectionException**: Network timeout or DNS issue.

🤝 Contribution
--------------

[](#-contribution)

Contributions are welcome!

1. Fork the repository.
2. Create a feature branch.
3. Commit your changes.
4. Push to the branch.
5. Open a Pull Request.

📄 License
---------

[](#-license)

This package is open-sourced software licensed under the [MIT license](LICENSE.md).

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance80

Actively maintained with recent releases

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 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

Unknown

Total

1

Last Release

108d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/79eb01e9a298505a276eab8644700fe92c5e6e02a626ded3bdb0c281c10aaed7?d=identicon)[yannXtrem](/maintainers/yannXtrem)

---

Top Contributors

[![yannXtrem](https://avatars.githubusercontent.com/u/62825195?v=4)](https://github.com/yannXtrem "yannXtrem (1 commits)")

### Embed Badge

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

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

###  Alternatives

[spatie/laravel-query-builder

Easily build Eloquent queries from API requests

4.4k26.9M220](/packages/spatie-laravel-query-builder)[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[esign/laravel-conversions-api

A laravel wrapper package around the Facebook Conversions API

69145.4k](/packages/esign-laravel-conversions-api)[surface/laravel-webfinger

A Laravel package to create an ActivityPub webfinger.

113.8k](/packages/surface-laravel-webfinger)

PHPackages © 2026

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