Prism is an innovative AI package designed for Laravel that allows developers to seamlessly integrate artificial intelligence into their web applications. Whether you're looking to perform tasks like text generation, image recognition, or data classification, Prism simplifies the process by providing an easy-to-use interface within Laravel's ecosystem. The package includes tools for natural language processing, AI agents, custom providers, and more, making it highly flexible and powerful.

In this article, we will walk you through Prism step by step, from installation and setup to advanced usage, such as using AI agents and custom providers. We’ll cover practical examples for text generation, prompt handling, using built-in tools, and more.


Table of Contents

  1. What is Prism?

  2. Prerequisites

  3. Installing Prism

  4. Basic Configuration

  5. Text Generation with Prism

    1. Using withPrompt()

    2. Using withMessages()

  6. Using Tools in Prism

  7. AI Agents in Prism

  8. Prism Server

  9. Custom Providers

  10. Conclusion


What is Prism?

Prism is a Laravel package that integrates advanced AI functionalities into web applications. It acts as a bridge between Laravel and popular AI services such as OpenAI, Google Vision, and more. Prism simplifies tasks like generating text, analyzing sentiment, recognizing images, and interacting with AI agents. The package provides an extensible framework where developers can even create custom AI providers and define their own models.


Prerequisites

Before you get started with Prism, ensure that you meet the following requirements:

  • Laravel: Version 8 or higher.

  • PHP: Version 7.4 or higher.

  • Composer: For package management.

  • API keys: For the AI services you intend to use (OpenAI, Google Vision, etc.).


Installing Prism

You can install Prism into your existing Laravel application via Composer.

  1. Install Prism:

    composer require prism-ai/prism

  2. Publish Prism's Configuration:
    After installation, publish Prism's configuration file:

    php artisan vendor:publish --provider="Prism\PrismServiceProvider"

  3. Set API keys:
    Open the .env file and add API keys for any AI services you plan to use. For example:

    PRISM_OPENAI_KEY=your-openai-key-here
    PRISM_GOOGLE_VISION_KEY=your-google-vision-key-here
    


Basic Configuration

After publishing the configuration file, you can find the settings in config/prism.php. This is where you'll manage service API keys and other settings.

Here’s an example of what the configuration might look like:

return [

    'services' => [

        'openai' => [

            'api_key' => env('PRISM_OPENAI_KEY'),

        ],

        'google_vision' => [

            'api_key' => env('PRISM_GOOGLE_VISION_KEY'),

        ],

    ],

];

Add or remove services based on your project’s needs.


Text Generation with Prism

One of the most exciting features of Prism is its ability to generate human-like text using models like GPT from OpenAI. Let’s explore the two primary ways to generate text in Prism.

Using withPrompt()

The withPrompt() method allows you to generate text by passing a simple string as a prompt. This is the most straightforward method for creating text using AI.

Example:

use Prism\Facades\Prism;


$prompt = "Write a short story about a heroic dog.";


// Generate text based on the prompt

$result = Prism::openai()->withPrompt($prompt)->generate();


dd($result);

In this example, the withPrompt() method sends the given prompt to the OpenAI model, which then returns generated text based on the input.

Using withMessages()

For more complex interactions, such as simulating a conversation or providing context over multiple exchanges, you can use withMessages(). This method allows you to maintain a history of messages between the user and the AI.

Example:

use Prism\Facades\Prism;


$messages = [

    ['role' => 'system', 'content' => 'You are an AI assistant.'],

    ['role' => 'user', 'content' => 'What is the weather like today?']

];


// Generate a response based on previous messages

$result = Prism::openai()->withMessages($messages)->generate();


dd($result);

This approach is more suitable for applications like chatbots, where context needs to be maintained across multiple exchanges.


Using Tools in Prism

Prism also provides a collection of built-in tools to perform various AI-driven tasks beyond just text generation. These tools allow developers to easily integrate features like text classification, sentiment analysis, and image recognition.

Example: Sentiment Analysis

You can perform sentiment analysis using a simple API call to OpenAI:

use Prism\Facades\Prism;


$text = "I'm so happy with the new features in this product!";


// Perform sentiment analysis on the given text

$result = Prism::openai()->analyzeSentiment($text);


dd($result);

This method returns whether the sentiment in the input text is positive, negative, or neutral.

Example: Image Recognition

For recognizing objects in an image using Google Vision:

use Prism\Facades\Prism;


$imagePath = storage_path('app/public/images/sample-image.jpg');


// Recognize objects in the image

$result = Prism::googleVision()->recognize($imagePath);


dd($result);

Prism’s tools abstract complex AI tasks into simple methods, allowing you to integrate them into your Laravel application effortlessly.


AI Agents in Prism

AI agents in Prism can be thought of as autonomous entities that perform tasks by interacting with the environment or other AI models. Agents are more advanced than simple models as they can manage complex workflows, make decisions, and carry out a series of tasks based on logic and AI-powered decisions.

Example: Creating an AI Agent

Prism allows you to create AI agents that can perform a sequence of tasks.

use Prism\Facades\Prism;


// Define agent behavior

$agent = Prism::agent()

    ->task('gather_information', function() {

        return "I found some data on the topic.";

    })

    ->task('summarize', function($data) {

        return "Here is a summary of the data: " . $data;

    });


// Run the agent

$result = $agent->run();


dd($result);

Agents allow developers to define a sequence of tasks, each dependent on the result of the previous task, making them perfect for more complex AI-driven workflows.


Prism Server

Prism can also act as a server that processes AI requests from multiple clients. This feature is particularly useful if you are building a SaaS application that provides AI services to users.

Example: Setting Up Prism Server

You can set up a dedicated Prism server by running the following Artisan command:

php artisan prism:serve

Once the server is running, it will handle requests from multiple clients, process them using the AI models you've integrated, and return results. This architecture is ideal for handling high volumes of AI requests efficiently.


Custom Providers

Prism is extensible, allowing developers to create custom AI providers that integrate other AI services or custom models.

Example: Adding a Custom Provider

To add a custom provider, you’ll need to create a new service provider and define how it should interact with Prism.

  1. Create Custom Provider:

namespace App\Providers;

use Prism\Contracts\AIProvider;


class CustomAIProvider implements AIProvider

{

    public function generate($input)

    {

        // Implement logic to interact with a custom AI API

        $response = $this->callCustomAPI($input);

        return $response;

    }


    protected function callCustomAPI($input)

    {

        // Custom API call logic

        return "Generated text from custom provider.";

    }

}
  1. Register Custom Provider:
    Once you've defined your custom provider, register it in the config/prism.php file:

'custom' => [
    'provider' => App\Providers\CustomAIProvider::class,

],
  1. Use Custom Provider:
    You can now use the custom provider like any other built-in service:

$result = Prism::custom()->generate('Hello World');

dd($result);

Custom providers make Prism highly adaptable to any AI service, whether it's a public API or a private model.


Conclusion

Prism is a robust and flexible AI package for Laravel that simplifies the integration of artificial intelligence into web applications. From basic text generation to advanced AI agents and custom providers, Prism offers a wide array of features that make it easier than ever to build AI-powered applications.

By following this comprehensive guide, you should be able to install, configure, and use Prism to integrate powerful AI features into your Laravel applications. Be sure to explore more advanced functionalities like custom providers and agents to take full advantage of what Prism has to offer. Happy coding!