Build With Abdallah logo Build With Abdallah Software · AI · Automation
Tutorial 2 min read Jun 05, 2026

Building AI Agents with Laravel: No Python Required

A
Abdallah Mohamed
Senior Full-Stack Engineer
Building AI Agents with Laravel: No Python Required

Building AI Agents with Laravel: No Python Required

Artificial Intelligence (AI) is becoming increasingly important in modern applications. Traditionally, AI development has been associated with Python, but in this tutorial, we will explore how to build AI agents using Laravel, a PHP framework. This approach allows developers who are more comfortable with PHP to integrate AI functionalities into their applications without switching languages.

Prerequisites

Before we begin, ensure you have the following installed on your machine:

  1. PHP (version 8.0 or higher)

    sudo apt update
    sudo apt install php
    
  2. Composer (Dependency Manager for PHP)

    php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
    php composer-setup.php
    sudo mv composer.phar /usr/local/bin/composer
    
  3. Laravel Installer

    composer global require laravel/installer
    
  4. Node.js (for Laravel Mix)

    sudo apt install nodejs
    sudo apt install npm
    
  5. MySQL (or any other database of your choice)

    sudo apt install mysql-server
    

Ensure that you have set up a MySQL user and database for your Laravel application.

Project Structure

We will create a Laravel project with the following structure:

laravel-ai-agent/
├── app/
│   ├── Console/
│   ├── Exceptions/
│   ├── Http/
│   │   ├── Controllers/
│   │   └── Middleware/
│   ├── Models/
│   ├── Providers/
│   └── Services/
├── bootstrap/
├── config/
├── database/
│   ├── factories/
│   ├── migrations/
│   └── seeders/
├── public/
├── resources/
├── routes/
├── storage/
├── tests/
├── artisan
├── composer.json
└── webpack.mix.js

Step 1: Setting Up Your Laravel Project

First, let's create a new Laravel project. Open your terminal and run:

laravel new laravel-ai-agent
cd laravel-ai-agent

This command will create a new directory named laravel-ai-agent with a fresh Laravel installation.

Step 2: Installing OpenAI PHP Client

We will use the OpenAI API to incorporate AI functionalities into our Laravel application. Install the OpenAI PHP client using Composer:

composer require openai-php/client

This package allows us to interact with the OpenAI API directly from PHP, making it easy to send requests and receive responses from the AI models.

Step 3: Configuring Environment Variables

To interact with the OpenAI API, you'll need an API key. You can obtain one by signing up on the OpenAI website. Once you have the key, add it to your .env file:

OPENAI_API_KEY=your_openai_api_key_here

Replace your_openai_api_key_here with your actual OpenAI API key. This key will be used to authenticate your requests to the OpenAI API.

Next, let's create a configuration file for the OpenAI client. In the config directory, create a new file named openai.php:

<?php

return [
    'api_key' => env('OPENAI_API_KEY'),
];

This configuration file will load the API key from the environment variables, ensuring that your API key is kept secure.

Step 4: Creating an AI Service

Now, let's create a service to handle interactions with the OpenAI API. In the app/Services directory, create a new file named OpenAIService.php:

<?php

namespace App\Services;

use OpenAI\Client;

class OpenAIService
{
    protected $client;

    public function __construct()
    {
        $this->client = new Client(config('openai.api_key'));
    }

    public function getResponse($prompt)
    {
        $response = $this->client->completions()->create([
            'engine' => 'text-davinci-003',
            'prompt' => $prompt,
            'max_tokens' => 150,
        ]);

        return $response['choices'][0]['text'] ?? 'No response';
    }
}

Explanation

  • Constructor: Initializes the OpenAI client using the API key from the configuration.
  • getResponse Method: Takes a prompt as input, sends it to the OpenAI API, and returns the AI-generated response.

This service will be used by our controllers to interact with the OpenAI API and retrieve responses based on user input.

In the next steps, we will create controllers and views to build a simple web interface for our AI agent.


```markdown
## Step 5: Creating a Controller

Let's create a controller to handle user input and display AI responses. In the `app/Http/Controllers` directory, create a new file named `AIController.php`:

```php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\OpenAIService;

class AIController extends Controller
{
    protected $openAIService;

    public function __construct(OpenAIService $openAIService)
    {
        $this->openAIService = $openAIService;
    }

    public function index()
    {
        return view('ai.index');
    }

    public function getResponse(Request $request)
    {
        $request->validate([
            'prompt' => 'required|string|max:255',
        ]);

        $response = $this->openAIService->getResponse($request->input('prompt'));

        return view('ai.index', compact('response'));
    }
}

Explanation

  • Constructor: Injects the OpenAIService to be used in the controller.
  • index Method: Returns the initial view for user input.
  • getResponse Method: Validates the user input, gets the response from the OpenAI service, and passes it to the view.

Step 6: Defining Routes

Define routes for the AI controller in the routes/web.php file:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AIController;

Route::get('/', [AIController::class, 'index']);
Route::post('/response', [AIController::class, 'getResponse']);

Step 7: Creating Views

Now, let's create a simple view to interact with our AI agent. Create a new directory named ai inside the resources/views directory, and add a file named index.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Agent</title>
</head>
<body>
    <h1>AI Agent</h1>
    <form action="/response" method="POST">
        @csrf
        <label for="prompt">Enter your prompt:</label>
        <input type="text" id="prompt" name="prompt" required>
        <button type="submit">Get Response</button>
    </form>

    @if(isset($response))
        <h2>Response:</h2>
        <p>{{ $response }}</p>
    @endif
</body>
</html>

Explanation

  • Form: Takes user input and submits it to the /response route.
  • Response Display: Shows the AI-generated response if available.

Complete Working Example

Here is a summary of the essential files:

app/Services/OpenAIService.php

<?php

namespace App\Services;

use OpenAI\Client;

class OpenAIService
{
    protected $client;

    public function __construct()
    {
        $this->client = new Client(config('openai.api_key'));
    }

    public function getResponse($prompt)
    {
        $response = $this->client->completions()->create([
            'engine' => 'text-davinci-003',
            'prompt' => $prompt,
            'max_tokens' => 150,
        ]);

        return $response['choices'][0]['text'] ?? 'No response';
    }
}

app/Http/Controllers/AIController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\OpenAIService;

class AIController extends Controller
{
    protected $openAIService;

    public function __construct(OpenAIService $openAIService)
    {
        $this->openAIService = $openAIService;
    }

    public function index()
    {
        return view('ai.index');
    }

    public function getResponse(Request $request)
    {
        $request->validate([
            'prompt' => 'required|string|max:255',
        ]);

        $response = $this->openAIService->getResponse($request->input('prompt'));

        return view('ai.index', compact('response'));
    }
}

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AIController;

Route::get('/', [AIController::class, 'index']);
Route::post('/response', [AIController::class, 'getResponse']);

resources/views/ai/index.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Agent</title>
</head>
<body>
    <h1>AI Agent</h1>
    <form action="/response" method="POST">
        @csrf
        <label for="prompt">Enter your prompt:</label>
        <input type="text" id="prompt" name="prompt" required>
        <button type="submit">Get Response</button>
    </form>

    @if(isset($response))
        <h2>Response:</h2>
        <p>{{ $response }}</p>
    @endif
</body>
</html>

Common Errors and Fixes

  1. Error: Class 'OpenAI\Client' not found

    • Fix: Ensure you have installed the OpenAI PHP client using Composer. Run composer require openai-php/client.
  2. Error: Undefined variable: response

    • Fix: This occurs if the view is loaded without a response. Ensure the getResponse method is called correctly and returns the view with the $response variable.
  3. Error: Invalid API Key

    • Fix: Double-check your OpenAI API key in the .env file. Ensure there are no spaces or typos.

Conclusion

In this tutorial, we demonstrated how to create a simple AI agent using Laravel without needing Python. By leveraging the OpenAI API, we can integrate AI capabilities into PHP applications efficiently.

Sources