Posted on Leave a comment

Creating A Laravel ChatGPT API

laravel + chatgpt

What Is ChatGPT?

ChatGPT is a generative AI software created by OpenAI from the official Wikipedia page

ChatGPT (Chat Generative Pre-trained Transformer[2]) is a chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI’s GPT-3 family of large language models and has been fine-tuned (an approach to transfer learning) using both supervised and reinforcement learning techniques.

https://en.wikipedia.org/wiki/ChatGPT

Since its launch, it has taken the world by storm. People are losing their minds over the impending AI overlords destroying society and making humanity its slave 😂

Seriously though we are talking BILLIONS of weights across MILLIONS of neurons I geek out every time I think about it. I keep getting asked what my thoughts are on ChatGPT and instead of repeating myself for the 99934394398th time, I decided to write a blog and do a Laravel code tutorial to show developers just HOW EASY it is to use this OpenAI software.

Use Cases For ChatGPT

Asset Generation

With ChatGPT you can generate images This was first made popular with the DALL-E project. AI-generated art is on the rise and there are many opportunities to be had. Images aren’t the end though, with ChatGPT you can generate any asset. Think about how this will affect gaming! You can generate 3D assets, audio assets, texture assets, and more.

Code Generation

In my opinion, this is where ChatGPT shines. The Codex project allows you to use ChatGPT to generate code, and the results are scarily amazing. If you are a solo developer you can leverage the power of artificial intelligence to speed run through proof of concepts. I have seen videos of people programming whole apps with ChatGPT

Text Generation

Using ChatGPT you can generate text. Many companies are integrating ChatGPT to create contextual accurate text responses. One of my favorite integrations of this is the Twitter bot ChatGPTBot. However, some people are scared of this technology such as the Rabbi who used AI to create a sermon. I personally think e-commerce will be dominated by AI-driven product descriptions.

The Sky Is The Limit

Microsoft has already integrated ChatGPT into Bing and Google is working on a rival application called Bard. The beautiful thing about this technology is that it is only limited to our imagination. We don’t even know the full scope of what ChatGPT is capable of. This is a perfect storm for people to get first movers advantage on this gold rush that is coming over the next decade.

How I Plan On Using ChatGPT

Mobisnacks

Download Mobisnacks!

I have integrated ChatGPT into MobiSnacks to create product descriptions for chefs. The chefs can put in keywords and ChatGPT spits out 3 descriptions for the chefs to use as a starting point. The next step is to use ChatGPT to generate contextual ads for the platform and for the chefs as an additional service.

GPT Audiobook

GPT Audiobook logo

I created a proof of concept called GPT Audiobook. It uses ChatGPT to create audiobooks and spits them out as SSML documents for text-to-speech software to read. I’m currently creating an Android and iOS app to go with the web app. In the future, I plan on adding rich structured data snippets to display the books on Google and other search engines. Even the logo for GPT Audiobook was MADE WITH CHATGPT!

The Laravel ChatGPT API

Overview

The Laravel API will be very simple: one route, one model, and one controller. The model will be called Prompt a prompt will have two fields, prompt_text and data. The controller will have one method called generateResult that will use the OpenAI SDK to communicate with ChatGPT and generate the result. Finally, there will be a POST route called /generate-result which saves the model and returns the JSON.

Listen To Some Hacker Music While You Code

Follow me on Spotify I make Tech Trap music

Creating The Application

For this tutorial, I am using a Mac with docker. To start open up the tutorial and create a new Laravel application

curl -s "https://laravel.build/laravel-chat-gpt-api" | bash

Afterward cd into the application and add the OpenAI Laravel package, which will power our ChatGPT logic.

composer require openai-php/laravel

This is the only composer requirement we will need for this tutorial. Now we need to do our configuration for OpenAI.

Configuring The OpenAI SDK

The OpenAI Laravel package comes with some config files that need to be published before we get started coding. In your terminal paste the following command

php artisan vendor:publish --provider="OpenAI\Laravel\ServiceProvider"

This will create a config/openai.php configuration file in your project, which you can modify to your needs using environment variables: You need to retrieve your OpenAI developer key from here and paste it in your .env file.

OPENAI_API_KEY=sk-...

Ok, that’s it for the SDK configuration.

Database & Model

The Prompt model will have a prompt_text field that will hold the text entered by the user. It will also have a data json field that holds the result from OpenAI. Let’s create the model and the migration all in one:

./vendor/bin/sail artisan make:model -m Prompt

Open up the created migration and paste in the following:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('prompts', function (Blueprint $table) {
            $table->id();
            $table->string('prompt_text');
            $table->json('data');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('prompts');
    }
};
 

Next open up the Prompt model and paste the following:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Prompt extends Model
{
    use HasFactory;

    protected $guarded = [];
    protected $casts = [
      'data' => 'array'
    ];
}

Next, let’s move on to creating the controller.

Creating The Controller

Generate the PromptController in the terminal:

 ./vendor/bin/sail artisan make:controller PromptController 

Open it up and let’s create our generateResult function:

<?php

namespace App\Http\Controllers;
use OpenAI\Laravel\Facades\OpenAI;
use App\Models\Prompt;
use Illuminate\Http\Request;

class PromptController extends Controller
{
    //
    function generateResult(Request $request) {

      $result = OpenAI::completions()->create($request->all());
      $prompt = new Prompt([
        'prompt_text' => $request->prompt,
        'data' => $result
      ]);
      return response()->json($prompt);
    }
}

So what’s going on here? We import the OpenAI SDK and we simply pass the $request to the completions API. If you need a reference you can check the OpenAI API reference. We then create a new prompt model pass in the text and pass in the resulting data. The last thing to do is create the route and we are done!

Creating The API Route

Open up the routes/api.php routes file and update it to call the PromptController@generateResult function

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('/generate-result','App\Http\Controllers\PromptController@generateResult');

Now we are done, make sure you plug in your API key and make a test request! Here is how we can test with cURL:


curl -X POST http://localhost/api/generate-result -H "Content-Type: application/json" --data-binary @- <<DATA
{
  "model": "text-davinci-003",
   "prompt" : "PHP is"
}
DATA

Next Steps

The next step that I want to do with this project is to create it as a Laravel package so developers can put an OpenAI ChatGPT API in their backends easily. Afterward, I would like to add functionality for issuing tokens and possibly even a monetization module powered by Stripe and Laravel Cashier. Please leave comments on this article and let me know what you would like to see and I will build it! You can see the GitHub repository here.

**UPDATE** I Created The Laravel Composer Package

Shortly after writing this tutorial, I went ahead and created a Composer package for the Laravel OpenAI ChatGPT API. If you want to implement this functionality from the tutorial and more then please check it out! I’m actively looking for PRs from fellow developers! I can’t wait to see how you all use and integrate this package into your web applications and business services!

You can install the package using the following command:

composer require mastashake08/laravel-openai-api 

Afterward you can publish the migrations and config files with the following commands:

php artisan vendor:publish --tag="openai-api-migrations"
php artisan migrate
php artisan vendor:publish --tag="openai-api-config"

Finally, start to use it in your code! You can access the object directly, via the included API routes, or with the interactive Artisan CLI command.

Via Code

$laravelOpenaiApi = new Mastashake\LaravelOpenaiApi();
echo $laravelOpenaiApi->generateResult($type, $data);

Via Artisan

php artisan laravel-openai-api:generate-result

Via API

You set the OPENAI_API_URL in the .env file if a value is not set then it defaults to /api/generate-result

/api/generate-result POST {openai_data}

The data object requires a type property that is either set to text or image. Depending on which type then provide the JSON referenced in the OpenAI API Reference

Text Example

{
  "type": "text",
  "prompt": "Rust is",
  "n": 1,
  "model": "text-davinci-003",
  "max_tokens": 16
}

Image Example

{
  "type": "image",
  "prompt": "A cute baby sea otter",
  "n": 1,
  "size": "1024x1024"
}

I’m going to continue to work on both this package and the demo tutorial and will update you all on the progress for sure. Thank you for taking time to read this tutorial, if you found it helpful please leave a comment and a like!

Follow Me On Social Media

Follow Me On Youtube!

Follow my YouTube account

Get Your Next Domain Cheap & Support The Channel

I use Namecheap for all of my domains! Whenever I need a cheap solution for a proof-of-concept project I grab a domain name for as little as $1! When you sign up and buy your first domain with Namecheap I get a commission, it’s a great way to get a quality service and support this platform!

Get Your Next Domain Cheap
CLICK HERE

Become A Sponsor

Open-source work is free to use but it is not free to develop. If you enjoy my content and would like to see more please consider becoming a sponsor on Github or Patreon! Not only do you support me but you are funding tech programs for at risk youth in Louisville, Kentucky.

Join The Newsletter

By joining the newsletter, you get first access to all of my blogs, events, and other brand-related content delivered directly to your inbox. It’s 100% free and you can opt out at any time!

Check The Shop

You can also consider visiting the official #CodeLife shop! I have my own clothing/accessory line for techies as well as courses designed by me covering a range of software engineering topics.

Leave a Reply