PHP code example of camh / laravel-ollama

1. Go to this page and download the library: Download camh/laravel-ollama library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

camh / laravel-ollama example snippets


use Camh\Ollama\Facades\Ollama;

$response = Ollama::generate('Why is the sky blue?');
echo $response;

$response = Ollama::generate('Why is the sky blue?', [
    'model' => 'llama3.1',
    'options' => [
        'temperature' => 0.7,
    ],
]);

$messages = [
    ['role' => 'system', 'content' => 'You are a helpful assistant.'],
    ['role' => 'user', 'content' => 'Why is the sky blue?'],
];

$response = Ollama::chat($messages);
echo $response; // Outputs the assistant's message content

$embedding = Ollama::embed('Hello world');
// Returns an array of floats

$embeddings = Ollama::embed(['Hello', 'world']);
// Returns an array of embedding arrays

Ollama::stream('Tell me a long story.', function ($chunk) {
    echo $chunk;
});

$response = Ollama::json('Create a user profile for John Doe.');
// Returns an array

$schema = [
    'type' => 'object',
    'properties' => [
        'name' => ['type' => 'string'],
        'email' => ['type' => 'string', 'format' => 'email'],
    ],
    '

use Camh\Ollama\Support\Conversation;
use Camh\Ollama\Facades\Ollama;

// Start or load a conversation for a user/session
$conversation = Conversation::load('user123') ?? new Conversation('user123', 'You are a helpful assistant.');

// Add a user message and get the assistant's reply
$reply = Ollama::conversation($conversation, 'Why is the sky blue?');
echo $reply;

// Continue the conversation
$reply2 = Ollama::conversation($conversation, 'What about sunsets?');
echo $reply2;

// Save the conversation (automatically done after each reply)
$conversation->save();

// Retrieve full history
$history = $conversation->getMessages();

// Clear the conversation
$conversation->clear();
$conversation->save();