如何搭建laravel ai+ 向量搜索(RAG)

2026-08-06 11:15:14 阅读:10 编辑

如何搭建laravel ai+ 向量搜索(RAG)

安装 pgsql -docker

docker run --name pgvector_postgres  -e POSTGRES_USER=root -e POSTGRES_PASSWORD=root123  -e POSTGRES_DB=pg -p 5432:5432  -d kgrozdanovski/pgvector:16-alpine

开启vector(向量功能)

docker exec -it pgvector_postgres psql -U root -d pg
CREATE EXTENSION IF NOT EXISTS vector;
\q

laravel配置

config/database.php


        'pgsql' => [
            'driver' => 'pgsql',
            'url' => '',
            'host' => '192.168.2.116',
            'port' => 5432,
            'database' => 'pg',
            'username' => 'root',
            'password' => 'root123',
            'charset' => env('DB_CHARSET', 'utf8'),
            'prefix' => '',
            'prefix_indexes' => true,
            'search_path' => 'public',
            'sslmode' => env('DB_SSLMODE', 'prefer'),
        ],

创建database/migrations/vector/2026_08_04_093358_create_documents_table.php

<?php use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('documents', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->vector('embedding', dimensions: 1536)->index();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('documents');
    }
};

执行migrate

php artisan migrate --database=pgsql --path=database/migrations/vector

创建Document -Model

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;

use Illuminate\Support\Str;
class Document extends BaseModel
{
    protected $connection = 'pgsql';
    protected $table = 'documents';
    protected $casts = [
        'embedding' => 'array', // Laravel 会自动处理向量数组的转换[citation:5][citation:12]
    ];

    // 这个方法接收问题和答案,生成向量并保存
    public static function generateAndSaveEmbedding(string $title, string $content): void
    {
        // 使用 AI SDK 生成向量
        $embedding = Str::of($content)->toEmbeddings();

        // 保存到模型的 embedding 字段
        $document = new self();
        $document->embedding = $embedding; // 确保存储为数组格式

        // 如果是新增记录,还需要保存其他字段
        $document->title = $title;
        $document->content = $content;
        $document->save();
    }

}

测试


Artisan::command('ai:generate_embedding', function () {

  // $embeddings = Str::of('纳帕谷有很棒的葡萄酒。')->toEmbeddings();
  // dd($embeddings);
  //$documents = Document::all();
  //dd($documents);
  Document::generateAndSaveEmbedding('小林简介', '小林是三明尤溪人');
  $documents = Document::all();
  dd($documents);
});