PHP code example of timm49 / similar-content-laravel
1. Go to this page and download the library: Download timm49/similar-content-laravel 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/ */
timm49 / similar-content-laravel example snippets
return [
'openai_api_key' => env('SIMILAR_CONTENT_OPENAI_API_KEY'), // OpenAI API Key
'limit_similar_results' => 10, // how many items will be fetched for similar results
'limit_search_results' => 10, // how many items will be fetched for search results
'auto_generate' => false, // auto generate embeddings when a model is created/updated
'cache_enabled' => false, // cache the similar content results
'cache_ttl' => 3600, // default ttl in seconds
];
use Timm49\SimilarContentLaravel\Attributes\HasEmbeddings;
#[HasEmbeddings]
class Article extends Model
{
use HasSimilarContent;
}
SimilarContent::createEmbedding($article);
$results = SimilarContent::getSimilarContent($article);
foreach ($results as $result) {
echo "Found similar content (score: {$result->similarityScore}) with ID {$result->targetId}";
}
readonly class SimilarContentResult
{
public function __construct(
public string $sourceType, // Class name of the original model
public string $sourceId, // ID of the original model
public string $targetType, // Class name of the similar model
public string $targetId, // ID of the similar model
public float $similarityScore, // Value between 0 and 1 (1 = identical)
) {
}
}
SimilarContent::search('Donald Trump');
readonly class SearchResult
{
public function __construct(
public string $id, // ID of the similar model
public string $type, // Class name of the similar model
public float $similarityScore, // Value between 0 and 1 (1 = identical)
) {
}
}
use Timm49\SimilarContentLaravel\Traits\HasSimilarContent;
class Article extends Model
{
use HasSimilarContent;
public function getEmbeddingData(): string
{
return $this->title . "\n" . $this->content;
}
}