Gradient Generator Tool New Tool

Search Suggest

Laravel AI SDK v1.2 Tutorial: Build Vector Search and RAG with PHP

Learn how to build semantic search and RAG in Laravel using the Laravel AI SDK v1.2, embeddings, PostgreSQL pgvector, Eloquent, and AI agents. Include

Laravel AI SDK makes it easier to add AI capabilities to Laravel applications without writing provider-specific integration code everywhere. In this tutorial, we will build the foundation of an AI-powered knowledge base that stores document embeddings, searches by meaning, and gives an AI agent access to relevant information.

This guide targets Laravel AI SDK 1.x, including v1.2.0. It distinguishes the SDK's actual release changes from the vector-search features documented by Laravel.

Laravel AI SDK v1.2 Tutorial: Build Vector Search and RAG with PHP


Laravel AI SDK v1.0 vs v1.2: What Changed?

Laravel AI SDK v1.0 was released on September 23, 2026. Version 1.2.0 followed on October 7, 2026. The 1.2 release includes improvements to structured output, OpenAI Decisions classification with image attachments, Bedrock structured output, and Anthropic model defaults.

Version Important details
v1.0.0 First stable 1.x release, including updates to conversation storage, agent middleware, usage reporting, and streaming protocols.
v1.1.0 Added agent skills, additional provider support, and improvements to built-in tools and provider handling.
v1.2.0 Improved structured output handling and classification-related functionality.

Important: v1.2.0 does not introduce a new vector-search API. Laravel's documented vector columns, embeddings, similarity queries, and SimilaritySearch tool are the relevant APIs for this tutorial. Check the official changelog before assuming a new SDK release changes your RAG implementation.

1. Install the Laravel AI SDK

Install the package in a compatible Laravel application:

Publish the AI SDK configuration and migration files, then run the migrations:

Configure your AI provider in the application's environment. For example, when using OpenAI:

Use a real secret only in your local environment or managed secrets service. Never commit API keys to Git or expose them in frontend JavaScript.

2. Create a Vector Database Table

For this example, we will use PostgreSQL with the pgvector extension. Laravel also documents vector-query support for MariaDB 11.7 or later, but the database setup and supported operations must match your environment.

Create a migration:

Use the following migration body:

The vector column stores an embedding, while the index helps accelerate similarity queries. The dimension of 1536 is an example, not a universal value. Select an embedding model whose output dimension matches your schema.

3. Create the Document Model

Create an Eloquent model:

Configure the model to cast its vector column:

The AsVector cast lets Eloquent handle the vector value as an array of numbers. Use explicit attribute assignments or an appropriate fillable policy when creating document records.

4. Generate Embeddings and Save a Document

An embedding is a numerical representation of text. Similar documents have embeddings that can be close to one another in vector space.

The Laravel AI SDK provides the Embeddings API for generating embeddings from one or more inputs. Here is a minimal example:

After confirming that your configured embedding model returns 1536 dimensions, you can save the generated embedding with a document:

This is a simple demonstration. For a real document-ingestion service, validate the source, chunk long documents, handle embedding failures, and dispatch processing to a queue instead of generating embeddings during a user-facing HTTP request.

5. Search Documents by Meaning

Laravel provides the whereVectorSimilarTo query method. It can accept either a vector or a string; when you pass a string, Laravel can generate an embedding through the configured AI SDK.

Example: A user searches for "find information by meaning." The database may return a document titled "Semantic Search with Vector Embeddings" even if the title does not contain the exact query words.

The similarity threshold is a starting point for experimentation, not a guarantee of relevance. Evaluate real queries and tune the threshold using your own documents and embedding model.

6. Give an AI Agent Access to Vector Search

The Laravel AI SDK includes a SimilaritySearch tool that lets an agent search records stored in a compatible Eloquent model.

Inside the tools method of your agent class, register the tool:

This is the tools method to add to an agent class, not a complete standalone agent. The agent must also implement the appropriate SDK contracts and define its instructions according to the official agent documentation.

For a multi-tenant application, do not expose every document to every user. Apply authorization and tenant filtering in the search query. Use the custom SimilaritySearch closure form when you need explicit query scoping.

7. Build a Reliable RAG Pipeline

A production RAG application has two main workflows: indexing documents and answering questions.

  1. Ingestion: Validate and extract text from uploaded files.
  2. Chunking: Split long documents into useful sections while preserving context.
  3. Embedding: Generate a vector for each chunk.
  4. Storage: Save chunk content, embeddings, document IDs, and authorization metadata.
  5. Retrieval: Search for relevant chunks when the user asks a question.
  6. Generation: Give the retrieved context to the AI agent and ask it to answer using that evidence.
  7. Evaluation: Measure retrieval relevance, answer quality, latency, and cost.

Vector retrieval alone is not a complete RAG implementation. The generation step must actually receive the retrieved information as context, and the application must enforce document permissions before that information reaches the model.

8. Production Best Practices

  • Use Laravel queues to process large documents and embedding batches asynchronously.
  • Keep embedding dimensions consistent across the model, stored documents, and query embeddings.
  • Use metadata filters to enforce tenant, user, and document-level access control.
  • Combine full-text and vector search when exact technical terms, product IDs, or error codes matter.
  • Consider reranking when a fast initial search needs a more relevant final ordering.
  • Cache reusable embeddings where appropriate, and invalidate caches when content changes.
  • Measure provider usage, database query latency, queue failures, and total cost.
  • Treat retrieved content as untrusted input. Never let a document override system instructions or security rules.

Laravel AI SDK v1.0 to v1.2: Upgrade Checklist

If you are upgrading from an earlier release, review the official upgrade guide and release notes instead of assuming that a minor version requires no migration work.

  • Review v1.0 breaking changes affecting conversation storage, agent middleware, usage reporting, and streaming protocols.
  • Check the v1.1 release notes for additional provider and agent-tool changes.
  • Review v1.2 structured-output changes if you use provider-specific output configuration or Bedrock models.
  • Run your agent, embedding, vector-search, and structured-output tests against the exact installed version.
  • Verify your database extensions, embedding dimensions, and provider configuration before deployment.

To inspect the installed package version, run:

Frequently Asked Questions

Does Laravel AI SDK v1.2 add a new vector-search API?

No. The published v1.2.0 release notes focus on structured-output fixes, classification functionality, and provider-related improvements. Use Laravel's documented vector-search APIs for semantic retrieval.

Can Laravel AI SDK work with PostgreSQL?

Yes. Laravel documents vector queries using PostgreSQL with the pgvector extension. MariaDB 11.7 or later is also documented as supporting vector queries.

What is the difference between vector search and RAG?

Vector search retrieves semantically related content. RAG combines retrieval with an AI model that uses the retrieved content to generate an answer.

Can I use Laravel AI SDK with an existing application?

Yes, if the installed Laravel version, package requirements, database driver, and AI provider configuration are compatible. Introduce indexing and retrieval incrementally and test the complete workflow.

How can I improve semantic search accuracy?

Improve text extraction, chunking, metadata filtering, embedding consistency, and threshold selection. Consider hybrid search or reranking, then evaluate the system with real user queries.

Conclusion

Laravel AI SDK v1.2 provides a stable 1.x foundation for building AI-powered Laravel applications, while Laravel's vector-query APIs and SimilaritySearch tool provide the building blocks for semantic retrieval and RAG.

Start with a small knowledge base, validate the embedding dimensions, implement secure retrieval, and test the quality of the answers. Add queues, hybrid search, reranking, and monitoring as the application grows.


Post a Comment

NextGen Digital Welcome to WhatsApp chat
Howdy! How can we help you today?
Type here...