PHP code example of displace / ai-contracts

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

    

displace / ai-contracts example snippets


use Displace\AI\Contracts\Embedder;
use Displace\AI\Contracts\VectorIndex;

function indexPosts(Embedder $embedder, VectorIndex $index, array $posts): void
{
    // One packed buffer for the whole batch, one add() call.
    $index->add(
        $embedder->embedBatch(array_column($posts, 'content')),
        array_column($posts, 'id'),
    );
}

function searchPosts(Embedder $embedder, VectorIndex $index, string $query, array $visibleIds): array
{
    // The allowlist composes with a SQL pre-filter:
    //   SELECT id FROM posts WHERE status = 'publish'  →  $visibleIds
    return $index->search($embedder->embed($query), k: 10, allowlist: $visibleIds);
}

use Displace\AI\Contracts\Embedder;
use Displace\Infer\Model;

final class InferEmbedder implements Embedder
{
    public function __construct(private readonly Model $model) {}

    public function embed(string $text): string
    {
        // ext-infer ≥ 0.2 emits the packed contract natively; on 0.1,
        // bridge with pack('g*', ...$vector) instead.
        return $this->model->embed($text)->normalize()->packed();
    }

    public function embedBatch(array $texts): string
    {
        return implode('', array_map($this->embed(...), $texts));
    }

    public function dimensions(): int
    {
        return $this->model->embed('')->dimensions();
    }
}