benbjurstrom/pgvector-scout 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

benbjurstrom/pgvector-scout

Composer 安装命令:

composer require benbjurstrom/pgvector-scout

包简介

Pgvector driver for Laravel Scout

README 文档

README

Logo

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status

Pgvector driver for Laravel Scout

Use the pgvector extension with Laravel Scout for vector similarity search.

To see a full example showing how to use this package check out benbjurstrom/pgvector-scout-demo.

🚀 Quick Start

1. Install the package using composer:

composer require benbjurstrom/pgvector-scout

2. Publish the scout config and the package config:

php artisan vendor:publish --tag="scout-config"
php artisan vendor:publish --tag="pgvector-scout-config"

This is the contents of the published pgvector-scout.php config file. By default it contains 3 different indexes, one for OpenAI, one for Google Gemini, and one for testing. The rest of this guide will use the OpenAI index as an example.

return [
    /*
    |--------------------------------------------------------------------------
    | Embedding Index Configurations
    |--------------------------------------------------------------------------
    |
    | Here you can define the configuration for different embedding indexes.
    | Each index can have its own specific configuration options.
    |
    */
    'indexes' => [
        'openai' => [
            'handler' => Handlers\OpenAiHandler::class,
            'model' => 'text-embedding-3-small',
            'dimensions' => 256, // See Reducing embedding dimensions https://platform.openai.com/docs/guides/embeddings#use-cases
            'url' => 'https://api.openai.com/v1',
            'api_key' => env('OPENAI_API_KEY'),
            'table' => 'openai_embeddings',
        ],
        'gemini' => [
            'handler' => Handlers\GeminiHandler::class,
            'model' => 'text-embedding-004',
            'dimensions' => 256,
            'url' => 'https://generativelanguage.googleapis.com/v1beta',
            'api_key' => env('GEMINI_API_KEY'),
            'table' => 'gemini_embeddings',
            'task' => 'SEMANTIC_SIMILARITY', // https://ai.google.dev/api/embeddings#tasktype
        ],
        'ollama' => [
            'handler' => Handlers\OllamaHandler::class,
            'model' => 'nomic-embed-text',
            'dimensions' => 768,
            'url' => 'http://localhost:11434/api/embeddings',
            'api_key' => 'none',
            'table' => 'ollama_embeddings',
        ],
        'fake' => [ // Used for testing
            'handler' => Handlers\FakeHandler::class,
            'model' => 'fake',
            'dimensions' => 3,
            'url' => 'https://example.com',
            'api_key' => '123',
            'table' => 'fake_embeddings',
        ],
    ],
];

3. Set the scout driver to pgvector in your .env file and add your OpenAI API key:

SCOUT_DRIVER=pgvector
OPENAI_API_KEY=your-api-key

4. Run the scout index command to create a migration file for your embeddings:

php artisan scout:index openai
php artisan migrate

5. Update the model you wish to make searchable:

Add the HasEmbeddings and Searchable traits to your model. Additionally add a searchableAs() method that returns the name of your index. Finally implement toSearchableArray() with the content from the model you want converted into an embedding.

use BenBjurstrom\PgvectorScout\Models\Concerns\HasEmbeddings;
use Laravel\Scout\Searchable;

class YourModel extends Model
{
    use HasEmbeddings, Searchable;

    /**
     * Get the name of the index associated with the model.
     */
    public function searchableAs(): string
    {
        return 'openai';
    }

    /**
     * Get the indexable content for the model.
     */
    public function toSearchableArray(): array
    {
        return [
            'title' => $this->title,
            'content' => $this->content,
        ];
    }
}

🔍 Usage

Create embeddings for your models:

Laravel Scout uses eloquent model observers to automatically keep your search index in sync anytime your Searchable models change.

This package uses this functionality automatically generate embeddings for your models when they are saved or updated; or remove them when your models are deleted.

If you want to manually generate embeddings for existing models you can use the artisan command below. See the Scout documentation for more information.

artisan scout:import "App\Models\YourModel"

Listen for embedding events:

The package dispatches an EmbeddingSaved event whenever an embedding is created or updated. You can listen for this event to monitor embedding operations:

use BenBjurstrom\PgvectorScout\Events\EmbeddingSaved;

class LogEmbeddingSaved
{
    public function handle(EmbeddingSaved $event): void
    {
        $action = $event->wasRecentlyCreated ? 'created' : 'updated';

        Log::info("Embedding {$action}", [
            'model' => $event->modelName,
            'id' => $event->modelId,
            'handler' => $event->handler,
        ]);
    }
}

Register the listener in your EventServiceProvider:

use BenBjurstrom\PgvectorScout\Events\EmbeddingSaved;

protected $listen = [
    EmbeddingSaved::class => [
        LogEmbeddingSaved::class,
    ],
];

Search using vector similarity:

You can use the typical Scout syntax to search your models. For example:

$results = YourModel::search('your search query')->get();

Note that the text of your query will be converted into a vector embedding using the model index's configured handler. It's important that the same model is used for both indexing and searching.

Search using existing vectors:

You can also pass an existing embedding vector as a search parameter. This can be useful to find related models. For example:

$vector = $someModel->embedding->vector;
$results = YourModel::search($vector)->get();

Evaluate search results:

All search queries will be ordered by similarity to the given input and include the embedding relationship. The value of the nearest neighbor search can be accessed as follows:

$results = YourModel::search('your search query')->get();
$results->first()->embedding->neighbor_distance; // 0.26834 (example value)

The larger the distance the less similar the result is to the input.

Advanced filtering with whereSearchable:

You can use the whereSearchable() macro to apply Eloquent query constraints before the vector similarity search. This improves efficiency by filtering the dataset before computing expensive vector distances.

use App\Models\DocumentChunk;

$results = DocumentChunk::search('payment terms')
    ->whereSearchable(fn ($query) =>
        $query->whereHas('document', fn ($doc) =>
            $doc->where('client_id', $clientId)
                ->where('type', 'contract')
        )
    )
    ->get();

🛠Using custom handlers

By default this package uses OpenAI to generate embeddings. To do this it uses the OpenAiHandler class paired with the openai index found in the packages config file.

You can generate embeddings from other providers by adding a custom Handler. A handler is a simple class defined in the HandlerContract that takes a string, a config object, and returns a Pgvector\Laravel\Vector object.

Whatever api calls or logic is needed to turn a string into a vector should be defined in the handle method of your custom handler.

If you need to pass api keys, embedding dimensions, or any other configuration to your handler you can define them in the config/pgvector-scout.php file.

Installing pgvector when using DBngin

If you're using DBngin for local development you can install the pgvector extention by doing the following:

  1. Add PostgreSQL to your path:
export PATH=/Users/Shared/DBngin/postgresql/14.3/bin:$PATH
  1. Then install pgvector:
git clone https://github.com/pgvector/pgvector.git
cd pgvector
make && make install

👏 Credits

📝 License

The MIT License (MIT). Please see License File for more information.

benbjurstrom/pgvector-scout 适用场景与选型建议

benbjurstrom/pgvector-scout 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 8.17k 次下载、GitHub Stars 达 73, 最近一次更新时间为 2024 年 11 月 16 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「Ben Bjurstrom」 「pgvector-scout」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 benbjurstrom/pgvector-scout 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 benbjurstrom/pgvector-scout 我们能提供哪些服务?
定制开发 / 二次开发

基于 benbjurstrom/pgvector-scout 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 8.17k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 73
  • 点击次数: 24
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 73
  • Watchers: 1
  • Forks: 8
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-11-16