PHPackages                             droath/prism-transformer - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. droath/prism-transformer

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

droath/prism-transformer
========================

A powerful Laravel package for AI-powered content transformation using multiple LLM providers.

1.0.0(7mo ago)041MITPHPPHP ^8.3CI passing

Since Oct 5Pushed 7mo agoCompare

[ Source](https://github.com/droath/prism-transformer)[ Packagist](https://packagist.org/packages/droath/prism-transformer)[ Docs](https://github.com/droath/prism-transformer)[ GitHub Sponsors](https://github.com/droath)[ RSS](/packages/droath-prism-transformer/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (15)Versions (3)Used By (0)

Prism Transformer
=================

[](#prism-transformer)

[![Latest Version on Packagist](https://camo.githubusercontent.com/bca9db771c691b75bc08c33294e034f769684f5e61cafacedc00f39c9d15743d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f64726f6174682f707269736d2d7472616e73666f726d65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/droath/prism-transformer)[![GitHub Tests Action Status](https://camo.githubusercontent.com/6f57fba83cc981bbb9f8510c2d749e95ebd698c15132455fdb28bc13e6ae7757/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f64726f6174682f707269736d2d7472616e73666f726d65722f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/droath/prism-transformer/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/08720ce7ebc61a65c5be06be5c70376e5a903b3b7bbace1b40b2de80d9cf8c09/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f64726f6174682f707269736d2d7472616e73666f726d65722f7068707374616e2e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/droath/prism-transformer/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/a61fea6cbc00d2b5d2420b7741510dd4dafc2c8399902fec52803df7e8777842/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f64726f6174682f707269736d2d7472616e73666f726d65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/droath/prism-transformer)

A powerful Laravel package for AI-powered content transformation using multiple LLM providers with direct Laravel Eloquent model integration.

Transform text content and web URLs into structured data or Laravel models using providers such as OpenAI, Anthropic, Groq, and more, with intelligent caching, automatic schema generation, and robust error handling.

Features
--------

[](#features)

- **🤖 Multi-Provider Support**: OpenAI, Anthropic, Groq, Ollama, Gemini, Mistral, DeepSeek, xAI, OpenRouter, VoyageAI, ElevenLabs
- **🚀 Fluent Interface**: Chainable methods for intuitive transformation workflows
- **📄 Content Sources**: Transform text, URLs, images, and documents
- **🖼️ Media Input Support**: Native support for image and document transformation with AI vision
- **⚡ Intelligent Caching**: Two-layer caching system for content fetching and transformation results
- **🔄 Async Processing**: Queue transformations for background processing with Laravel queues
- **🛠️ Custom Transformers**: Create reusable transformation classes with dependency injection
- **🎯 Laravel Model Output**: Direct transformation to Laravel Eloquent models with automatic schema generation
- **🔧 Laravel Integration**: Service provider, facades, and configuration
- **✅ Validation Support**: Built-in Laravel validation integration
- **🛡️ Security Features**: Blocked domains protection for content fetching
- **🏗️ Service-Oriented Architecture**: Clean separation of concerns with dedicated services
- **🎯 Error Handling**: Comprehensive Throwable-based exception system with transformation context
- **📊 Performance Optimized**: Efficient algorithms and configurable timeout settings

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require droath/prism-transformer
```

Publish the configuration file:

```
php artisan vendor:publish --tag="prism-transformer-config"
```

Configuration
-------------

[](#configuration)

### Requirements

[](#requirements)

- PHP 8.3+
- Laravel 11.0+ or 12.0+

### Environment Variables

[](#environment-variables)

Set up your AI provider API keys in your `.env` file:

```
# Default provider
PRISM_TRANSFORMER_DEFAULT_PROVIDER=openai

# API Keys
OPENAI_API_KEY=your-openai-api-key
ANTHROPIC_API_KEY=your-anthropic-api-key
GROQ_API_KEY=your-groq-api-key

# Caching (optional)
PRISM_TRANSFORMER_CACHE_CONTENT_ENABLED=true
PRISM_TRANSFORMER_CACHE_RESULTS_ENABLED=true
PRISM_TRANSFORMER_CACHE_TTL_CONTENT=1800
PRISM_TRANSFORMER_CACHE_TTL_RESULTS=3600
PRISM_TRANSFORMER_CACHE_STORE=redis

# Async Queue (optional)
PRISM_TRANSFORMER_ASYNC_QUEUE=default
PRISM_TRANSFORMER_QUEUE_CONNECTION=redis
PRISM_TRANSFORMER_TIMEOUT=60
PRISM_TRANSFORMER_TRIES=3
```

### Provider Configuration

[](#provider-configuration)

The package supports multiple AI providers with customizable models and settings:

```
// config/prism-transformer.php
return [
    'default_provider' => Provider::OPENAI,

    'providers' => [
        'openai' => [
            'default_model' => 'gpt-4o-mini',
            'max_tokens' => 4096,
            'temperature' => 0.7,
        ],
        'anthropic' => [
            'default_model' => 'claude-3-5-haiku-20241022',
            'max_tokens' => 4096,
            'temperature' => 0.7,
        ],
        // ... more providers
    ],
];
```

Quick Start
-----------

[](#quick-start)

### Basic Text Transformation

[](#basic-text-transformation)

```
use Droath\PrismTransformer\PrismTransformer;

// Create a simple transformer using a closure
$transformer = new PrismTransformer();

$result = $transformer
    ->text('Hello world!')
    ->using(function($content) {
        return TransformerResult::successful("Transformed: $content");
    })
    ->transform();

echo $result->getContent(); // "Transformed: Hello world!"
```

### Laravel Model Transformation

[](#laravel-model-transformation)

Transform content directly into Laravel Eloquent models:

```
use Droath\PrismTransformer\PrismTransformer;
use Droath\PrismTransformer\Abstract\BaseTransformer;
use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    protected $fillable = ['name', 'email', 'phone'];
}

class ContactExtractor extends BaseTransformer
{
    public function prompt(): string
    {
        return 'Extract contact information from the text as JSON.';
    }

    protected function outputFormat(): Model
    {
        return new Contact();
    }
}

$result = (new PrismTransformer())
    ->text('John Smith, email: john@example.com, phone: (555) 123-4567')
    ->using(ContactExtractor::class)
    ->transform();

// Convert directly to Laravel model
$contact = $result->toModel(Contact::class);
$contact->save(); // Save to database

echo $contact->name;  // "John Smith"
echo $contact->email; // "john@example.com"
```

### URL Content Transformation

[](#url-content-transformation)

```
$result = $transformer
    ->url('https://example.com/article')
    ->using($customTransformer)
    ->transform();
```

### Media Input Transformation

[](#media-input-transformation)

Transform images and documents with AI vision and document analysis:

```
use Droath\PrismTransformer\PrismTransformer;

// Image transformation
$result = (new PrismTransformer())
    ->image('/path/to/image.jpg')
    ->using($imageAnalyzer)
    ->transform();

// Document transformation
$result = (new PrismTransformer())
    ->document('/path/to/document.pdf')
    ->using($documentExtractor)
    ->transform();

// You can also pass metadata
$result = (new PrismTransformer())
    ->image('/path/to/photo.png', ['title' => 'Product Photo'])
    ->using($productAnalyzer)
    ->transform();
```

The media input methods automatically handle:

- **File reading and encoding**: Converts files to base64 for AI processing
- **Media type detection**: Automatically determines image vs document types
- **Proper serialization**: Works with both sync and async transformations

### Async Transformations

[](#async-transformations)

Queue transformations for background processing using Laravel's queue system:

```
use Droath\PrismTransformer\PrismTransformer;

// Async text transformation
$pendingDispatch = (new PrismTransformer())
    ->text('Long content to process...')
    ->async()
    ->using($summarizer)
    ->transform();

// Async URL transformation
$pendingDispatch = (new PrismTransformer())
    ->url('https://example.com/article')
    ->async()
    ->using($contentAnalyzer)
    ->transform();

// Async image transformation
$pendingDispatch = (new PrismTransformer())
    ->image('/path/to/image.jpg')
    ->async()
    ->using($imageDescriber)
    ->transform();

// The transform() method returns a PendingDispatch instance
// The job will be processed by your queue worker
```

**Async with Context:**

```
$pendingDispatch = (new PrismTransformer())
    ->setContext(['user_id' => auth()->id(), 'tenant_id' => 123])
    ->text('Content to transform')
    ->async()
    ->using($transformer)
    ->transform();
```

**Async with Closures:**

Closures are automatically serialized for queue processing and properly handle Media objects:

```
// Works with both string and Media input
$pendingDispatch = (new PrismTransformer())
    ->image('/path/to/image.jpg')
    ->async()
    ->using(function ($content) {
        // $content will be a Media object (Image instance)
        // Properly handle both types
        $data = is_string($content) ? $content : $content->base64();

        return TransformerResult::successful("Processed: {$data}");
    })
    ->transform();
```

**Queue Configuration:**

```
// config/prism-transformer.php
'transformation' => [
    'async_queue' => env('PRISM_TRANSFORMER_ASYNC_QUEUE', 'default'),
    'queue_connection' => env('PRISM_TRANSFORMER_QUEUE_CONNECTION'),
    'timeout' => env('PRISM_TRANSFORMER_TIMEOUT', 60),
    'tries' => env('PRISM_TRANSFORMER_TRIES', 3),
],
```

### Using the Facade

[](#using-the-facade)

```
use Droath\PrismTransformer\Facades\PrismTransformer;

$result = PrismTransformer::text('Content to transform')
    ->using($transformer)
    ->transform();

// Async with facade
$pendingDispatch = PrismTransformer::text('Content to transform')
    ->async()
    ->using($transformer)
    ->transform();
```

Custom Transformers
-------------------

[](#custom-transformers)

Create powerful, reusable transformers by extending `BaseTransformer`:

### Simple Content Summarizer

[](#simple-content-summarizer)

```
