如何搭建laravel ai+ 向量搜索(RAG)
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
docker exec -it pgvector_postgres psql -U root -d pg
CREATE EXTENSION IF NOT EXISTS vector;
\q
'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'),
],
<?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');
}
};
php artisan migrate --database=pgsql --path=database/migrations/vector
<?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);
});