Polyscope - The agent-first dev environment for Laravel

LLPhant: A PHP Generative AI Framework Inspired by LangChain

Last updated on by

LLPhant: A PHP Generative AI Framework Inspired by LangChain image

LLPhant is a PHP library for building Generative AI applications in PHP. Created by Maxime Thoonsen, it provides a unified interface for working with multiple LLM providers including OpenAI, Anthropic, Mistral, LM Studio, and Ollama. The library is inspired by LangChain and LLamaIndex, bringing similar patterns to PHP developers.

Multi-Provider LLM Support

LLPhant abstracts away provider differences so you can switch between AI services with minimal code changes. Whether you are using OpenAI's GPT models, Anthropic's Claude, Mistral, LM Studio, or running local models through Ollama, the interface remains consistent:

// OpenAI
$chat = new OpenAIChat();
$response = $chat->generateText('What is the capital of France?');
 
// Anthropic Claude
$chat = new AnthropicChat(new AnthropicConfig(AnthropicConfig::CLAUDE_3_5_SONNET));
$response = $chat->generateText('What is the capital of France?');
 
// Local models via Ollama
$config = new OllamaConfig();
$config->model = 'llama2';
$chat = new OllamaChat($config);

The library also supports streaming responses for real-time chat interfaces, token usage tracking for cost monitoring, and vision capabilities for image analysis.

Embeddings and Vector Storage

LLPhant includes a complete pipeline for building Retrieval-Augmented Generation (RAG) applications. You can read documents from various sources (PDF, Word, text files), split them into chunks, generate embeddings, and store them in your preferred vector database:

// Read and process documents
$reader = new FileDataReader(__DIR__.'/documents');
$documents = $reader->getDocuments();
 
// Split into chunks for embedding
$splitDocuments = DocumentSplitter::splitDocuments($documents, 800);
 
// Generate embeddings
$embeddingGenerator = new OpenAI3SmallEmbeddingGenerator();
$embeddedDocuments = $embeddingGenerator->embedDocuments($splitDocuments);
 
// Store in PostgreSQL with pgvector
$vectorStore = new DoctrineVectorStore($entityManager, Document::class);
$vectorStore->addDocuments($embeddedDocuments);
 
// Search for similar content
$embedding = $embeddingGenerator->embedText('search query');
$results = $vectorStore->similaritySearch($embedding, 5);

Vector store support includes Doctrine (PostgreSQL with pgvector), Redis, Elasticsearch, MongoDB, ChromaDB, Qdrant, Milvus, AstraDB, OpenSearch, Pinecone, and Typesense.

Question Answering with RAG

The QuestionAnswering class handles the entire RAG workflow: retrieving relevant documents from your vector store and generating contextualized responses:

use LLPhant\Query\SemanticSearch\QuestionAnswering;
 
$qa = new QuestionAnswering($vectorStore, $embeddingGenerator, $chat);
 
$response = $qa->answerQuestion('What are the main topics covered in the documentation?');

You can customize the system message template to control how the AI uses retrieved context, add guardrails for safety, and implement multi-query transformations to improve retrieval quality.

Function Calling and Tools

LLPhant supports function calling (tools), allowing your LLM to interact with external APIs and services. Define your tools as PHP classes and the LLM can decide when to invoke them based on the conversation context.

You can learn more about LLPhant and find detailed documentation at llphant.readthedocs.org and the GitHub repository.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
SerpApi logo

SerpApi

Access real-time search engine results through a simple API—no more scraping headaches! Use it for AI applications, SEO tools, product research, travel information, and more

SerpApi
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech

The latest

View all →
Laravel Installer Now Returns JSON When Running Inside an AI Agent image

Laravel Installer Now Returns JSON When Running Inside an AI Agent

Read article
Queue-Wide Inspection Methods in Laravel 13.8.0 image

Queue-Wide Inspection Methods in Laravel 13.8.0

Read article
Verifiable Audit Logging with Laravel Chronicle image

Verifiable Audit Logging with Laravel Chronicle

Read article
Ship AI with Laravel: Search Entire PDFs with Zero Search Logic image

Ship AI with Laravel: Search Entire PDFs with Zero Search Logic

Read article
Personalized Content Delivery System: Building an AI-powered recommendation engine with Laravel and MongoDB image

Personalized Content Delivery System: Building an AI-powered recommendation engine with Laravel and MongoDB

Read article
Laravel Brain: Visualize Your Application's Request Lifecycle image

Laravel Brain: Visualize Your Application's Request Lifecycle

Read article