PHP code example of tenqz / ollama

1. Go to this page and download the library: Download tenqz/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/ */

    

tenqz / ollama example snippets


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();

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));