RAG na Prática: Construindo um Chatbot que Realmente Sabe o que Fala
RAG (Retrieval-Augmented Generation) é a técnica que transforma LLMs genéricos em especialistas no seu domínio. Em vez de depender só do que o modelo aprendeu no treino, você fornece contexto relevante em cada query.
Como RAG Funciona
O pipeline tem duas fases:
- Ingestion: seus documentos são divididos em chunks, convertidos em embeddings (vetores numéricos) e armazenados em um vector database.
- Query: a pergunta do usuário vira um embedding, os chunks mais similares são recuperados, e enviados junto com a pergunta ao LLM como contexto.
Implementando com Laravel e pgvector
Primeiro, habilite a extensão pgvector no PostgreSQL e instale as dependências:
composer require openai-php/laravel
php artisan vendor:publish --provider="OpenAI\Laravel\ServiceProvider"
Configure sua migration para armazenar embeddings:
Schema::create('document_chunks', function (Blueprint $table) {
$table->id();
$table->foreignId('document_id')->constrained()->cascadeOnDelete();
$table->text('content');
$table->vector('embedding', 1536); // dimensão do text-embedding-3-small
$table->integer('chunk_index');
$table->timestamps();
});
O ingestion pipeline converte documentos em chunks e gera embeddings:
class DocumentIngestionService
{
public function ingest(Document $document): void
{
$chunks = $this->splitIntoChunks($document->content, chunkSize: 500, overlap: 50);
foreach ($chunks as $index => $chunk) {
$embedding = OpenAI::embeddings()->create([
'model' => 'text-embedding-3-small',
'input' => $chunk,
])->embeddings[0]->embedding;
DocumentChunk::create([
'document_id' => $document->id,
'content' => $chunk,
'embedding' => $embedding,
'chunk_index' => $index,
]);
}
}
}
Resultado
Com este pipeline, você tem um chatbot que responde com precisão usando sua base de conhecimento, cita fontes e sabe quando não sabe a resposta — evitando alucinações.
Related posts
The ghost model that "crushed" GPT-5.6 — and the statistics lesson that came with it
An ownerless model appeared on OpenRouter, scored 80% on a coding benchmark, and made head...
2.4 trillion parameters in open weights: the frontier model left the data center
August 2026 stacked the largest open-weight release ever and a multimodal model built to r...
Laravel 13 and PHP 8.5: AI and vector search in the framework, without breaking what exists
Laravel 13 arrived in March 2026 with a first-party AI SDK, vector search in the query bui...