PHPackages                             cloudstudio/ollama-laravel - 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. [Framework](/categories/framework)
4. /
5. cloudstudio/ollama-laravel

ActiveLibrary[Framework](/categories/framework)

cloudstudio/ollama-laravel
==========================

This is my package ollama-laravel

v1.3.0(3mo ago)474118.1k↑39.7%46MITPHPPHP ^8.2

Since Nov 19Pushed 3mo ago7 watchersCompare

[ Source](https://github.com/cloudstudio/ollama-laravel)[ Packagist](https://packagist.org/packages/cloudstudio/ollama-laravel)[ Docs](https://github.com/cloudstudio/ollama-laravel)[ RSS](/packages/cloudstudio-ollama-laravel/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (10)Dependencies (18)Versions (31)Used By (0)

[![Latest Version on Packagist](https://camo.githubusercontent.com/3761413f07569684d57d2ec02b631f4009cb07e32767b9754d65355af20701f9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636c6f756473747564696f2f6f6c6c616d612d6c61726176656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/cloudstudio/ollama-laravel)[![Total Downloads](https://camo.githubusercontent.com/b4612b962eb2937fc5ee4c67320e75c584c7c367f6103199c2dc7bef1bbbd088/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636c6f756473747564696f2f6f6c6c616d612d6c61726176656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/cloudstudio/ollama-laravel)

[![Need production AI systems? We build AI agents, RAG pipelines & Claude integrations for teams.](art/banner-cloudstudio.svg)](https://cloudstudio.es/for-developers)

Ollama-Laravel Package
======================

[](#ollama-laravel-package)

Ollama-Laravel is a Laravel package that provides seamless integration with the [Ollama API](https://github.com/jmorganca/ollama). It enables you to harness the power of local AI models for various tasks including text generation, vision analysis, chat completion, embeddings, and more. This package is perfect for developers looking to integrate AI capabilities into their Laravel applications without relying on external API services.

🌟 Features
----------

[](#-features)

- **Text Generation**: Generate content with customizable prompts and models
- **Vision Analysis**: Analyze images using multimodal models
- **Chat Completion**: Build conversational AI with message history
- **Thinking/Reasoning**: Access model reasoning with thinking models (Qwen 3, DeepSeek R1, etc.)
- **Function Calling**: Execute tools and functions through AI
- **Streaming Responses**: Real-time response streaming
- **Model Management**: List, copy, delete, and pull models
- **Embeddings**: Generate vector embeddings for semantic search
- **Flexible Configuration**: Customizable timeouts, temperature, and more

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

[](#-requirements)

- PHP ^8.2
- Laravel ^11.0
- Ollama server running locally or remotely

If you use Laravel 10.x, please use version V1.0.9
--------------------------------------------------

[](#if-you-use-laravel-10x-please-use-version-v109)

```
https://github.com/cloudstudio/ollama-laravel/releases/tag/v1.0.9
```

🚀 Installation
--------------

[](#-installation)

```
composer require cloudstudio/ollama-laravel
```

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

[](#️-configuration)

Publish the configuration file:

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

Update your `.env` file:

```
OLLAMA_MODEL=llama3.1
OLLAMA_URL=http://127.0.0.1:11434
OLLAMA_DEFAULT_PROMPT="Hello, how can I assist you today?"
OLLAMA_CONNECTION_TIMEOUT=300
```

Published config file:

```
return [
    'model' => env('OLLAMA_MODEL', 'llama3.1'),
    'url' => env('OLLAMA_URL', 'http://127.0.0.1:11434'),
    'default_prompt' => env('OLLAMA_DEFAULT_PROMPT', 'Hello, how can I assist you today?'),
    'connection' => [
        'timeout' => env('OLLAMA_CONNECTION_TIMEOUT', 300),
    ],
];
```

📖 Usage Examples
----------------

[](#-usage-examples)

### 🔧 Basic Text Generation

[](#-basic-text-generation)

#### Simple Question Answering

[](#simple-question-answering)

```
use Cloudstudio\Ollama\Facades\Ollama;

$response = Ollama::agent('You are a helpful assistant.')
    ->prompt('Explain quantum computing in simple terms')
    ->model('llama3.1')
    ->ask();

echo $response['response'];
```

#### Content Creation with Custom Options

[](#content-creation-with-custom-options)

```
$response = Ollama::agent('You are a creative writing assistant.')
    ->prompt('Write a short story about a robot learning to paint')
    ->model('llama3.1')
    ->options([
        'temperature' => 0.8,  // More creative
        'top_p' => 0.9,
        'max_tokens' => 500
    ])
    ->ask();
```

#### Code Generation

[](#code-generation)

```
$response = Ollama::agent('You are an expert PHP developer.')
    ->prompt('Create a Laravel middleware that logs API requests with rate limiting')
    ->model('codellama')
    ->options(['temperature' => 0.2]) // Less creative for code
    ->ask();
```

### 🖼️ Vision Analysis

[](#️-vision-analysis)

#### Basic Image Analysis

[](#basic-image-analysis)

```
$response = Ollama::model('llava:13b')
    ->prompt('Describe what you see in this image in detail')
    ->image(public_path('images/product-photo.jpg'))
    ->ask();

echo $response['response'];
// "This image shows a modern smartphone with a sleek black design..."
```

#### Product Catalog Analysis

[](#product-catalog-analysis)

```
$response = Ollama::model('llava:13b')
    ->prompt('Extract product information from this image including brand, model, features, and estimated price range')
    ->image(storage_path('app/uploads/product.jpg'))
    ->ask();
```

#### Multiple Image Comparison

[](#multiple-image-comparison)

```
$response = Ollama::model('llava:13b')
    ->prompt('Compare these images and identify the differences')
    ->images([
        public_path('images/before.jpg'),
        public_path('images/after.jpg')
    ])
    ->ask();
```

#### Document OCR and Analysis

[](#document-ocr-and-analysis)

```
$response = Ollama::model('llava:13b')
    ->prompt('Extract all text from this document and summarize the key points')
    ->image(storage_path('app/documents/invoice.pdf'))
    ->ask();
```

### 💬 Chat Completion

[](#-chat-completion)

#### Customer Support Bot

[](#customer-support-bot)

```
$messages = [
    ['role' => 'system', 'content' => 'You are a helpful customer support agent for an e-commerce website.'],
    ['role' => 'user', 'content' => 'I ordered a laptop 3 days ago but haven\'t received tracking information'],
    ['role' => 'assistant', 'content' => 'I understand your concern. Let me help you track your laptop order. Could you please provide your order number?'],
    ['role' => 'user', 'content' => 'My order number is ORD-12345']
];

$response = Ollama::model('llama3.1')
    ->chat($messages);
```

#### Educational Tutor

[](#educational-tutor)

```
$messages = [
    ['role' => 'system', 'content' => 'You are a patient math tutor helping a student learn calculus.'],
    ['role' => 'user', 'content' => 'I don\'t understand how to find the derivative of x^2 + 3x + 2'],
    ['role' => 'assistant', 'content' => 'I\'d be happy to help! Let\'s break this down step by step...'],
    ['role' => 'user', 'content' => 'Can you show me the power rule?']
];

$response = Ollama::model('llama3.1')
    ->options(['temperature' => 0.3]) // Lower temperature for educational content
    ->chat($messages);
```

#### Code Review Assistant

[](#code-review-assistant)

```
$messages = [
    ['role' => 'system', 'content' => 'You are a senior software engineer providing code reviews.'],
    ['role' => 'user', 'content' => 'Please review this PHP function for potential improvements:'],
    ['role' => 'user', 'content' => '```php
function calculateTotal($items) {
    $total = 0;
    foreach($items as $item) {
        $total += $item["price"] * $item["quantity"];
    }
    return $total;
}
```']
];

$response = Ollama::model('codellama')
    ->chat($messages);
```

### 🧠 Thinking/Reasoning Models

[](#-thinkingreasoning-models)

Ollama supports thinking models like Qwen 3, DeepSeek R1, and others that can show their reasoning process.

#### Enable Thinking Output

[](#enable-thinking-output)

```
$response = Ollama::model('qwen3')
    ->prompt('What is the square root of 144 and why?')
    ->think()
    ->ask();

// Access the reasoning process
echo $response['thinking'];  // Model's step-by-step reasoning
echo $response['response'];  // Final answer
```

#### Thinking with Chat

[](#thinking-with-chat)

```
$messages = [
    ['role' => 'user', 'content' => 'Solve this step by step: If x + 5 = 12, what is x?']
];

$response = Ollama::model('deepseek-r1')
    ->think()
    ->chat($messages);

// Access thinking from chat response
echo $response['message']['thinking'];  // Reasoning steps
echo $response['message']['content'];   // Final answer
```

#### Thinking Levels (for supported models like GPT-OSS)

[](#thinking-levels-for-supported-models-like-gpt-oss)

```
// Some models support thinking levels: "low", "medium", "high"
$response = Ollama::model('gpt-oss')
    ->prompt('Explain quantum entanglement')
    ->think('high')  // Maximum reasoning depth
    ->ask();
```

#### Disable Thinking

[](#disable-thinking)

```
// Explicitly disable thinking output
$response = Ollama::model('qwen3')
    ->prompt('Quick answer: What is 2+2?')
    ->think(false)
    ->ask();
```

### 🔧 Function Calling / Tools

[](#-function-calling--tools)

#### Weather Information System

[](#weather-information-system)

```
$messages = [
    ['role' => 'user', 'content' => 'What\'s the current weather in Tokyo and London?']
];

$response = Ollama::model('llama3.1')
    ->tools([
        [
            "type" => "function",
            "function" => [
                "name" => "get_current_weather",
                "description" => "Get the current weather for a specific location",
                "parameters" => [
                    "type" => "object",
                    "properties" => [
                        "location" => [
                            "type" => "string",
                            "description" => "The city and country, e.g. Tokyo, Japan",
                        ],
                        "unit" => [
                            "type" => "string",
                            "description" => "Temperature unit",
                            "enum" => ["celsius", "fahrenheit"],
                        ],
                    ],
                    "required" => ["location"],
                ],
            ],
        ]
    ])
    ->chat($messages);
```

#### Database Query Assistant

[](#database-query-assistant)

```
$tools = [
    [
        "type" => "function",
        "function" => [
            "name" => "execute_sql_query",
            "description" => "Execute a read-only SQL query on the database",
            "parameters" => [
                "type" => "object",
                "properties" => [
                    "query" => [
                        "type" => "string",
                        "description" => "The SQL SELECT query to execute",
                    ],
                    "table" => [
                        "type" => "string",
                        "description" => "The primary table being queried",
                    ]
                ],
                "required" => ["query", "table"],
            ],
        ],
    ]
];

$messages = [
    ['role' => 'user', 'content' => 'Show me the top 5 customers by total orders']
];

$response = Ollama::model('llama3.1')
    ->tools($tools)
    ->chat($messages);
```

### 🌊 Streaming Responses

[](#-streaming-responses)

#### Real-time Content Generation

[](#real-time-content-generation)

```
use Illuminate\Console\BufferedConsoleOutput;

$response = Ollama::agent('You are a creative storyteller.')
    ->prompt('Write an engaging short story about time travel')
    ->model('llama3.1')
    ->options(['temperature' => 0.8])
    ->stream(true)
    ->ask();

$output = new BufferedConsoleOutput();
$responses = Ollama::processStream($response->getBody(), function($data) use ($output) {
    echo $data['response']; // Output in real-time
    flush();
});

$complete = implode('', array_column($responses, 'response'));
```

#### Live Chat Implementation

[](#live-chat-implementation)

```
// In your controller
public function streamChat(Request $request)
{
    $response = Ollama::agent('You are a helpful assistant.')
        ->prompt($request->input('message'))
        ->model('llama3.1')
        ->stream(true)
        ->ask();

    return response()->stream(function() use ($response) {
        Ollama::processStream($response->getBody(), function($data) {
            echo "data: " . json_encode($data) . "\n\n";
            flush();
        });
    }, 200, [
        'Content-Type' => 'text/plain',
        'Cache-Control' => 'no-cache',
        'X-Accel-Buffering' => 'no'
    ]);
}
```

### 📊 Embeddings for Semantic Search

[](#-embeddings-for-semantic-search)

#### Document Similarity Search

[](#document-similarity-search)

```
// Generate embeddings for documents
$documents = [
    'Laravel is a PHP web framework',
    'Python is a programming language',
    'React is a JavaScript library'
];

$embeddings = [];
foreach ($documents as $doc) {
    $embeddings[] = Ollama::model('nomic-embed-text')
        ->embeddings($doc);
}

// Search for similar content
$query = 'Web development framework';
$queryEmbedding = Ollama::model('nomic-embed-text')
    ->embeddings($query);

// Calculate cosine similarity (implement your similarity function)
$similarities = calculateCosineSimilarity($queryEmbedding, $embeddings);
```

#### Product Recommendation System

[](#product-recommendation-system)

```
// Generate product embeddings
$productDescription = 'Wireless noise-canceling headphones with 30-hour battery life';
$productEmbedding = Ollama::model('nomic-embed-text')
    ->embeddings($productDescription);

// Store embedding in database for later similarity searches
DB::table('products')->where('id', $productId)->update([
    'embedding' => json_encode($productEmbedding['embedding'])
]);
```

🛠️ Model Management
-------------------

[](#️-model-management)

### List Available Models

[](#list-available-models)

```
$models = Ollama::models();
foreach ($models['models'] as $model) {
    echo "Model: " . $model['name'] . " (Size: " . $model['size'] . ")\n";
}
```

### Get Model Information

[](#get-model-information)

```
$info = Ollama::model('llama3.1')->show();
echo "Model: " . $info['details']['family'] . "\n";
echo "Parameters: " . $info['details']['parameter_size'] . "\n";
```

### Copy and Manage Models

[](#copy-and-manage-models)

```
// Copy a model
Ollama::model('llama3.1')->copy('my-custom-llama');

// Pull a new model
Ollama::model('codellama:7b')->pull();

// Delete a model
Ollama::model('old-model')->delete();
```

🏗️ Advanced Use Cases
---------------------

[](#️-advanced-use-cases)

### Content Moderation System

[](#content-moderation-system)

```
class ContentModerationService
{
    public function moderateContent(string $content): array
    {
        $response = Ollama::agent(
            'You are a content moderator. Analyze content for inappropriate material, spam, or policy violations. Respond with JSON containing "safe" (boolean), "categories" (array), and "confidence" (0-1).'
        )
        ->prompt("Analyze this content: {$content}")
        ->model('llama3.1')
        ->format('json')
        ->options(['temperature' => 0.1])
        ->ask();

        return json_decode($response['response'], true);
    }
}
```

### Automated Code Documentation

[](#automated-code-documentation)

```
class CodeDocumentationService
{
    public function generateDocumentation(string $code): string
    {
        return Ollama::agent(
            'You are a technical writer. Generate comprehensive PHPDoc comments for the given code.'
        )
        ->prompt("Generate documentation for this code:\n\n{$code}")
        ->model('codellama')
        ->options(['temperature' => 0.2])
        ->ask()['response'];
    }
}
```

### Multi-language Translation Service

[](#multi-language-translation-service)

```
class TranslationService
{
    public function translate(string $text, string $fromLang, string $toLang): string
    {
        return Ollama::agent(
            "You are a professional translator. Translate the given text accurately while preserving tone and context."
        )
        ->prompt("Translate from {$fromLang} to {$toLang}: {$text}")
        ->model('llama3.1')
        ->options(['temperature' => 0.3])
        ->ask()['response'];
    }
}
```

### Data Analysis Assistant

[](#data-analysis-assistant)

```
class DataAnalysisService
{
    public function analyzeCSV(string $csvPath): array
    {
        $csvContent = file_get_contents($csvPath);

        $response = Ollama::agent(
            'You are a data analyst. Analyze the CSV data and provide insights, trends, and recommendations in JSON format.'
        )
        ->prompt("Analyze this CSV data:\n\n{$csvContent}")
        ->model('llama3.1')
        ->format('json')
        ->ask();

        return json_decode($response['response'], true);
    }
}
```

🎯 Best Practices
----------------

[](#-best-practices)

### 1. Model Selection

[](#1-model-selection)

- Use `llama3.1` for general tasks and reasoning
- Use `codellama` for code-related tasks
- Use `llava` models for vision tasks
- Use `nomic-embed-text` for embeddings

### 2. Temperature Settings

[](#2-temperature-settings)

- **0.1-0.3**: Factual, deterministic outputs (code, analysis)
- **0.4-0.7**: Balanced creativity and accuracy
- **0.8-1.0**: Creative writing, brainstorming

### 3. Prompt Engineering

[](#3-prompt-engineering)

```
// Good: Specific and detailed
$response = Ollama::agent('You are a senior Laravel developer with 10 years of experience.')
    ->prompt('Create a secure user authentication system using Laravel Sanctum with rate limiting and email verification')
    ->ask();

// Better: Include context and constraints
$response = Ollama::agent('You are a senior Laravel developer. Follow PSR-12 coding standards and include comprehensive error handling.')
    ->prompt('Create a user authentication system with these requirements: Laravel Sanctum, rate limiting (5 attempts per minute), email verification, and password reset functionality. Include middleware and proper validation.')
    ->ask();
```

### 4. Error Handling

[](#4-error-handling)

```
try {
    $response = Ollama::model('llama3.1')
        ->prompt('Your prompt here')
        ->ask();
} catch (\Exception $e) {
    Log::error('Ollama request failed: ' . $e->getMessage());
    // Handle gracefully
}
```

### 5. Performance Optimization

[](#5-performance-optimization)

```
// Use keepAlive for multiple requests
$ollama = Ollama::model('llama3.1')->keepAlive('10m');

// Process multiple prompts
foreach ($prompts as $prompt) {
    $response = $ollama->prompt($prompt)->ask();
    // Process response
}
```

🧪 Testing
---------

[](#-testing)

Run the test suite:

```
pest
```

Example test for your AI service:

```
it('can generate content with Ollama', function () {
    $response = Ollama::agent('You are a test assistant.')
        ->prompt('Say hello')
        ->model('llama3.1')
        ->ask();

    expect($response)->toHaveKey('response');
    expect($response['response'])->toBeString();
});
```

📝 Changelog, Contributing, and Security
---------------------------------------

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

- [Changelog](CHANGELOG.md)
- [Contributing](CONTRIBUTING.md)

🎖️ Credits
----------

[](#️-credits)

- [Toni Soriano](https://github.com/cloudstudio)

📄 License
---------

[](#-license)

[MIT License](LICENSE.md)

###  Health Score

60

—

FairBetter than 98% of packages

Maintenance82

Actively maintained with recent releases

Popularity55

Moderate usage in the ecosystem

Community24

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 51.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 ~43 days

Recently: every ~62 days

Total

21

Last Release

96d ago

PHP version history (2 changes)1.0.0PHP ^8.1

v1.0.6PHP ^8.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3589377?v=4)[Toni Soriano](/maintainers/cloudstudio)[@cloudstudio](https://github.com/cloudstudio)

---

Top Contributors

[![cloudstudio](https://avatars.githubusercontent.com/u/3589377?v=4)](https://github.com/cloudstudio "cloudstudio (22 commits)")[![pepijnolivier](https://avatars.githubusercontent.com/u/2015108?v=4)](https://github.com/pepijnolivier "pepijnolivier (7 commits)")[![G4Zz0L1](https://avatars.githubusercontent.com/u/13220636?v=4)](https://github.com/G4Zz0L1 "G4Zz0L1 (3 commits)")[![medjai](https://avatars.githubusercontent.com/u/16169426?v=4)](https://github.com/medjai "medjai (2 commits)")[![neoteknic](https://avatars.githubusercontent.com/u/1809652?v=4)](https://github.com/neoteknic "neoteknic (2 commits)")[![rjsamra](https://avatars.githubusercontent.com/u/31566509?v=4)](https://github.com/rjsamra "rjsamra (2 commits)")[![steef-paqt](https://avatars.githubusercontent.com/u/59729886?v=4)](https://github.com/steef-paqt "steef-paqt (1 commits)")[![cursoragent](https://avatars.githubusercontent.com/u/199161495?v=4)](https://github.com/cursoragent "cursoragent (1 commits)")[![Jamonek](https://avatars.githubusercontent.com/u/209572?v=4)](https://github.com/Jamonek "Jamonek (1 commits)")[![marianoarga](https://avatars.githubusercontent.com/u/1138627?v=4)](https://github.com/marianoarga "marianoarga (1 commits)")[![antonrom-appflame](https://avatars.githubusercontent.com/u/192878789?v=4)](https://github.com/antonrom-appflame "antonrom-appflame (1 commits)")

---

Tags

laravelcloudstudioollama-laravel

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[laravel/socialite

Laravel wrapper around OAuth 1 &amp; OAuth 2 libraries.

5.7k108.5M885](/packages/laravel-socialite)[laravel/boost

Laravel Boost accelerates AI-assisted development by providing the essential context and structure that AI needs to generate high-quality, Laravel-specific code.

3.5k21.5M588](/packages/laravel-boost)[spatie/laravel-health

Monitor the health of a Laravel application

87512.0M165](/packages/spatie-laravel-health)[spatie/laravel-pdf

Create PDFs in Laravel apps

1.0k4.8M47](/packages/spatie-laravel-pdf)[nativephp/mobile

NativePHP for Mobile

1.1k75.1k91](/packages/nativephp-mobile)[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.

5021.9k](/packages/simplestats-io-laravel-client)

PHPackages © 2026

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