As you explore the realm of Laravel development, you’ve likely encountered limitations when integrating AI-driven functionality into your web applications. One common challenge is creating a seamless and interactive experience that leverages real-time data processing and user input. You may have struggled with implementing AI-powered features within a browser-based interface, only to be stymied by the complexities of communication between client-side components and server-side logic.
You’ll build a cutting-edge browser-based AI agent using Livewire and Prism in this tutorial. By the end of it, you’ll have successfully integrated an AI-powered component into your Laravel application, capable of defining and executing complex tasks with real-time feedback. Specifically, you’ll set up WebSockets for efficient communication between client and server, and implement the AI logic within Livewire components to create a sophisticated user interface that interacts with your application seamlessly.
Installing Livewire and Prism in a Laravel Project
To build our browser-based AI agent, we need to start with the foundation: installing Livewire and Prism, a Laravel package for working with large language models (LLMs) that requires PHP 8.2+ and Laravel 11 or later. Livewire allows us to create real-time, dynamic user interfaces in Laravel, while Prism enables us to define tasks (called tools) that the AI agent can execute through an LLM.
First, let’s install Livewire via Composer:
composer require livewire/livewire
Next, we can publish the Livewire configuration file using Artisan. This step is optional, since Livewire works with its defaults and injects its JavaScript assets automatically, but it lets you customize settings such as the default layout:
php artisan livewire:publish --config
Now that Livewire is installed, let’s move on to installing Prism. To do this, we’ll use Composer again:
composer require prism-php/prism
After the installation completes, we need to publish the Prism configuration using Artisan:
php artisan vendor:publish --tag=prism-config
Finally, let’s add the API key for our LLM provider to the .env file. This tutorial uses OpenAI, and the published config/prism.php file reads the key from this variable:
OPENAI_API_KEY=your-openai-api-key
With Livewire and Prism installed and configured, we’re now ready to start building our AI agent.
Creating an AI Agent Class with Livewire Components
Now that we have set up our project and installed the required packages, let’s create a basic AI agent class using Livewire components.
Create a new file named Agent.php in the app/Livewire directory of your Laravel project, which is where Livewire looks for component classes by default. This will hold our AI agent logic.
// app/Livewire/Agent.php
namespace App\Livewire;
use Illuminate\Support\Facades\Http;
use Livewire\Component;
class Agent extends Component
{
public $tasks = [];
public $actions = [];
public function mount()
{
// Initialize tasks and actions on component mount
$this->fetchTasks();
$this->fetchActions();
}
protected function fetchTasks()
{
$response = Http::get('https://api.example.com/tasks');
if ($response->ok()) {
$tasks = json_decode($response->body(), true);
$this->tasks = array_map(function ($task) {
return ['id' => $task['id'], 'name' => $task['name']];
}, $tasks);
}
}
protected function fetchActions()
{
// Replace with your API endpoint for fetching actions
$response = Http::get('https://api.example.com/actions');
if ($response->ok()) {
$actions = json_decode($response->body(), true);
$this->actions = array_map(function ($action) {
return ['id' => $action['id'], 'name' => $action['name']];
}, $actions);
}
}
public function executeTask($taskId)
{
// Implement logic for executing a task here
}
public function performAction($actionId)
{
// Implement logic for performing an action here
}
public function render()
{
return view('livewire.agent');
}
}
In this example, we’ve created a basic AI agent class that fetches tasks and actions from external APIs. We’re extending the Livewire\Component class and returning a view from the render method to enable our component to be rendered on the frontend. Note how we’re using HTTP requests with Http::get() to fetch data from external sources.
The next step will be to define AI tasks and actions using Prism, which will allow us to create a more robust AI agent.
Defining AI Tasks and Actions using Prism
Now that our AI agent class is set up with Livewire components, we need to define the tasks and actions that it will perform. This is where Prism comes in – a powerful Laravel package that gives you one consistent API for working with LLM providers such as OpenAI, Anthropic, and Ollama, including support for tools the model can call.
First, confirm that Prism was installed correctly by running:
composer show prism-php/prism
Next, create a new file called Greeting.php within the app/Tasks directory. Each task is a Prism tool: a class with a name, a description the model uses to decide when to call it, and an __invoke method that does the work.
// app/Tasks/Greeting.php
namespace App\Tasks;
use Prism\Prism\Tool;
class Greeting extends Tool
{
public function __construct()
{
$this
->as('greeting')
->for('Greet the user and offer assistance')
->using($this);
}
public function __invoke(): string
{
return 'Hello, how can I assist you?';
}
}
In this example, we’ve created a simple Greeting task that returns a friendly greeting message. To register our task with the AI agent, pass it to Prism as a tool in your AI agent component:
// app/Livewire/AiAgent.php
namespace App\Livewire;
use App\Tasks\Greeting;
use Livewire\Component;
use Prism\Prism\Enums\Provider;
use Prism\Prism\Facades\Prism;
class AiAgent extends Component
{
public function render()
{
return view('livewire.ai-agent');
}
protected function tools(): array
{
return [new Greeting()];
}
protected function runAgent(string $prompt): string
{
return Prism::text()
->using(Provider::OpenAI, 'gpt-4o-mini')
->withTools($this->tools())
->withMaxSteps(3)
->withPrompt($prompt)
->asText()
->text;
}
}
This makes our Greeting task available to the model whenever the AI agent is triggered; the model decides when to call it, and withMaxSteps lets it call tools and then continue with their results. You can add more tasks and actions using this same pattern – just remember to add them to the tools method of your AI agent class!
Setting up WebSockets for Real-Time Communication
To enable real-time communication between our AI agent and the browser, we’ll set up a WebSocket connection using Laravel Reverb, Laravel’s first-party WebSocket server. This will allow us to push updates from the server to connected clients as they occur.
First, let’s install broadcasting support. On Laravel 11 and later, this command installs Reverb, publishes the necessary configuration files, and sets up Laravel Echo on the frontend:
php artisan install:broadcasting
Next, check the .env file so that broadcasting uses Reverb. The installer adds these values for you:
BROADCAST_CONNECTION=reverb
REVERB_APP_ID=my-app-id
REVERB_APP_KEY=my-app-key
REVERB_APP_SECRET=my-app-secret
REVERB_HOST="localhost"
REVERB_PORT=8080
REVERB_SCHEME=http
The WebSocket server itself is configured in the config/reverb.php file and listens on 0.0.0.0:8080 by default. Start the server:
php artisan reverb:start
Now, let’s create a broadcast event that sends updates over an ai-agent WebSocket channel for our AI agent:
// app/Events/AiAgentUpdated.php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
class AiAgentUpdated implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets;
public function __construct(public array $data)
{
}
public function broadcastOn(): PrivateChannel
{
return new PrivateChannel('ai-agent');
}
public function broadcastAs(): string
{
return 'update';
}
}
Finally, we’ll use the broadcast helper to push updates from our AI agent component:
// app/Livewire/AiAgent.php
use App\Events\AiAgentUpdated;
public function performAction($action, $value = null)
{
// ...
broadcast(new AiAgentUpdated(['action' => $action, 'value' => $value]));
}
This sets up the WebSocket connection and allows us to push updates from the server to connected clients in real-time.
Implementing the AI Agent Logic within Livewire Components
Now that we have our AI tasks and actions defined using Prism, it’s time to implement the logic for our AI agent within the Livewire components.
Open your App\Livewire\AiAgent component file (or create a new one if you haven’t already) and add the following code. This example assumes a Task Eloquent model backed by a table with name and data columns:
use App\Models\Task;
public $tasks = [];
public $selectedTaskId = null;
public $status = null;
public function mount()
{
// Load the available tasks from the database
$this->tasks = Task::all();
}
public function updatedSelectedTaskId()
{
// Get the selected task
$task = Task::find($this->selectedTaskId);
// If a task is selected, trigger its logic
if ($task) {
$this->dispatch('ai-task-selected', data: $task->data);
// Ask the AI agent to process the task and show the result
$this->status = $this->runAgent($task->name);
}
}
In the above code, we’re using the updated lifecycle hook to react to changes in the $selectedTaskId property. When a task is selected, Livewire sends a request to the server, where we dispatch a browser event and run the AI agent to execute the task’s logic.
Next, let’s update our Blade template (resources/views/livewire/ai-agent.blade.php) with the following code:
<div>
<h2>Select AI Task</h2>
<p>Choose an AI task to execute.</p>
<div>
@foreach ($tasks as $task)
<button wire:click="$set('selectedTaskId', {{ $task->id }})" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
{{ $task->name }}
</button>
@endforeach
</div>
<div>
@if ($selectedTaskId)
Task: {{ $tasks->firstWhere('id', $selectedTaskId)?->name }}
@endif
@if ($status)
<p>{{ $status }}</p>
@endif
</div>
</div>
This code will display a list of available AI tasks, and when one is selected, it will trigger the logic for that task. This is where the magic happens – our AI agent is now executing tasks in real-time!
With this implementation, we’ve successfully integrated Prism with Livewire to create an AI agent that can execute tasks within the browser.
Testing and Debugging the AI Agent in a Browser
Now that we have implemented our AI agent logic within Livewire components, it’s time to test and debug it in the browser.
To do this, navigate to your project’s public folder using your web server or by running php artisan serve in your terminal. Open a new tab in your browser and access your application at the URL specified by php artisan serve. You should see the Livewire component rendering the AI agent interface.
Next, let’s create some test cases for our AI agent. We’ll simulate user input using the JavaScript console. Open the developer tools in your browser (usually F12 or right-click > Inspect) and navigate to the Console tab.
{{-- Render the component in any Blade view --}}
<livewire:ai-agent />
{{-- In resources/views/livewire/ai-agent.blade.php, inside the root element --}}
@script
<script>
// Use this function in your component to send actions to the server
window.sendActionToServer = (action, value) => {
console.log(`Sending action ${action} with value ${value}`);
$wire.performAction(action, value);
};
</script>
@endscript
// In console (type these commands one by one)
let aiAgent = Livewire.first(); // Get the AI agent component's $wire object
aiAgent.$set('selectedTaskId', 1); // Select a task and run the AI agent
sendActionToServer('task1', 'value1'); // Simulate user input
sendActionToServer('task2', 'value2');
// Verify that your server-side logging and debugging mechanisms are working as expected.
Remember to also test the AI agent’s ability to handle multiple concurrent user interactions. This will help you identify any potential issues with synchronization or data consistency.
Once you’ve tested and debugged your AI agent, it’s ready for integration into your larger Laravel application. In our next section, we’ll explore how to integrate this component into a real-world scenario within your existing project.
Integrating the AI Agent with Your Laravel Application
To integrate your AI agent into your existing Laravel application, you’ll need to create a service class that will handle communication between the Livewire components and the AI agent logic.
First, create a new file called AiAgentService.php in the app/Services directory. This file will serve as the entry point for interacting with your AI agent.
// app/Services/AiAgentService.php
namespace App\Services;
use App\Events\AiAgentUpdated;
use App\Tasks\Greeting;
use Prism\Prism\Enums\Provider;
use Prism\Prism\Facades\Prism;
class AiAgentService
{
public function getRecommendation(string $input): string
{
// Interact with the AI agent and retrieve a recommendation
$response = Prism::text()
->using(Provider::OpenAI, 'gpt-4o-mini')
->withSystemPrompt('You are a helpful assistant that recommends the next action for the user.')
->withTools([new Greeting()])
->withMaxSteps(3)
->withPrompt($input)
->asText();
// Push the recommendation to connected clients in real time
broadcast(new AiAgentUpdated(['recommendation' => $response->text]));
return $response->text;
}
}
Next, authorize the private WebSocket channel for the AI agent in routes/channels.php (created by install:broadcasting), and add a route for the agent’s page to your web.php route file.
// routes/channels.php
use Illuminate\Support\Facades\Broadcast;
Broadcast::channel('ai-agent', function ($user) {
return $user !== null;
});
// routes/web.php
use App\Livewire\AiAssistant;
Route::get('/ai-agent', AiAssistant::class)->middleware('auth');
Finally, create a new Livewire component, AiAssistant, to serve as the interface for interacting with your AI agent. This will allow users to send input and receive recommendations from the AI.
// app/Livewire/AiAssistant.php
namespace App\Livewire;
use App\Services\AiAgentService;
use Livewire\Attributes\Layout;
use Livewire\Component;
#[Layout('layouts.app')]
class AiAssistant extends Component
{
public $input = '';
public $recommendation = null;
public function handleInput(AiAgentService $agent)
{
$this->validate(['input' => 'required|string|max:1000']);
$this->recommendation = $agent->getRecommendation($this->input);
}
public function render()
{
return view('livewire.ai-assistant');
}
}
{{-- resources/views/livewire/ai-assistant.blade.php --}}
<div>
<h1>Ai Agent Interface</h1>
<form wire:submit="handleInput">
<input type="text" wire:model="input">
<button type="submit">Get Recommendation</button>
</form>
@if ($recommendation)
<p>Recommended action: {{ $recommendation }}</p>
@endif
</div>
This concludes the development of your browser-based AI agent using Livewire and PHP. By following these steps, you’ve created a robust system for automating tasks and providing real-time recommendations to users within your Laravel application.
Now that your AI agent is integrated with your app, explore ways to further enhance its capabilities and user experience!
Frequently Asked Questions
What is the difference between Livewire and Prism in Laravel?
Livewire is a real-time, dynamic user interface library for Laravel, while Prism is a package for working with LLMs that lets an AI agent execute the tasks (tools) you define.
How do I troubleshoot issues with installing Livewire and Prism?
Check your Composer installation and ensure that you have the correct versions of Livewire and Prism installed for your Laravel and PHP versions. Also, verify that you’ve published the necessary configuration files using Artisan and set your LLM provider’s API key in .env.
Can I use a different AI library instead of Prism in Laravel?
Yes, for example Laravel’s first-party AI SDK (laravel/ai) or the openai-php/laravel client. Keep in mind that Prism gives you a single API across multiple LLM providers and a robust tool-calling mechanism; other libraries may require additional setup or configuration.
Why am I getting an error when trying to execute tasks using the AI agent class?
This could be due to issues with your API endpoint, HTTP requests, or task execution logic within the AI agent class. Ensure that your APIs are correctly configured and responding as expected.
How do I add custom actions to my AI agent in Laravel using Livewire and Prism?
You can define new actions by adding them to the $actions array within the Agent class, then implement the logic for performing these actions in the performAction method.
