PHP code example of strtob / yii2-ollama

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

    

strtob / yii2-ollama example snippets


use strtob\yii2Ollama\QdrantAdapter;

$qdrantAdapter = new QdrantAdapter($qdrantClient, 'my_collection');

'components' => [
    'ollama' => [
        'class' => 'strtob\yii2Ollama\OllamaComponent',
        'apiUrl' => 'http://localhost:11434/v1/generate',
        'apiKey' => 'MY_SECRET_TOKEN',
        'model' => \strtob\yii2Ollama\OllamaComponent::MODEL_MISTRAL,
        'temperature' => 0.7,
        'maxTokens' => 512,
        'topP' => 0.9,
        'vectorDb' => $qdrantAdapter, // must implement VectorDbInterface
        'vectorDbTopK' => 5,
    ],
];

try {
    $prompt = "Explain RAG with vector DB.";

    $text = \Yii::$app->ollama->generateText($prompt);

    echo $text;

    //or

    print_r(generateTextWithTokens(string $prompt, $options = []))

} catch (\yii\base\InvalidConfigException $e) {
    echo Yii::t('yii2-ollama', 'Configuration error: {message}', ['message' => $e->getMessage()]);
} catch (\strtob\yii2Ollama\OllamaApiException $e) {
    echo Yii::t('yii2-ollama', 'API request failed: {message}', ['message' => $e->getMessage()]);
}

 public function actionIndex()
    {
        $response = Yii::$app->response;
        $response->format = \yii\web\Response::FORMAT_RAW;
        Yii::$app->response->isSent = true;

        // Output-Puffer leeren
        while (ob_get_level())
            ob_end_clean();
        ob_implicit_flush(true);

        Yii::$app->ollama->stream = true;

        try {
            Yii::$app->ollama->generate("Whats up?", [], function ($chunk) {
                echo $chunk;
                flush();
            });
        } catch (\Throwable $e) {
            echo "\n[Error]: " . $e->getMessage();
        }

    }

// Log after generation
\Yii::$app->ollama->on(\strtob\yii2Ollama\OllamaComponent::EVENT_AFTER_GENERATE, function($event) {
    Yii::info("Prompt generated: {$event->data['prompt']}", 'ollama');
    Yii::info("User: " . ($event->data['user']->username ?? 'guest'), 'ollama');
});

// Handle errors
\Yii::$app->ollama->on(\strtob\yii2Ollama\OllamaComponent::EVENT_GENERATE_ERROR, function($event) {
    Yii::error("Generation failed for prompt: {$event->data['prompt']}", 'ollama');
    Yii::error("Exception: " . $event->data['exception']->getMessage(), 'ollama');
});

try {
    $text = "Llamas are members of the camelid family.";
    
    $embeddingResult = \Yii::$app->ollama->embedText($text);
    
    echo "Embedding vector:\n";
    print_r($embeddingResult['embedding']); // Nur die Embeddings anzeigen

} catch (\yii\base\InvalidConfigException $e) {
    echo "Configuration error: " . $e->getMessage();
} catch (\strtob\yii2Ollama\OllamaApiException $e) {
    echo "Embedding request failed: " . $e->getMessage();
}

use app\models\DocumentModel;
use yii\web\UploadedFile;

// 1) Create a new document
$doc = new DocumentModel();
$doc->title = 'Sample PDF';
$doc->user_id = 1;
$doc->uploadedFile = UploadedFile::getInstance($model, 'uploadedFile');
$doc->save(); // extracts text and stores embeddings automatically

// 2) Update document content and embeddings
$doc = DocumentModel::findOne($id);
$doc->title = 'Updated Title';
$doc->uploadedFile = UploadedFile::getInstance($model, 'uploadedFile'); // optional
$doc->save(); // embeddings updated automatically

// 3) Delete document and corresponding vectors
$doc = DocumentModel::findOne($id);
$doc->delete(); // deletes vectors in vector DB automatically

use strtob\yii2Ollama\VectorDbInterface;
use strtob\yii2Ollama\QdrantAdapter;

$qdrantAdapter = new QdrantAdapter($qdrantClient, 'my_collection');