Maximize your Laravel blog's potential with SEO best practices and reach 10K monthly clicks on Google.
Preview the course for free
Benjamin Crozat New!
Benjamin Crozat The art of crafting web applications

OpenAI for PHP: add AI in your project with GPT-3 & ChatGPT

Benjamin Crozat — Updated on
Artboard

Hundreds of developers subscribed to my newsletter.
Join them and enjoy free content about the art of crafting websites!

Powered by

To use OpenAI’s REST API, you can either:

  1. Use the API directly;
  2. Or use a client written in PHP that will significantly simplify your journey.

Option #2 is precisely what we’re aiming for, thanks to the OpenAI PHP client written by Mantas Smilinskas, Nuno Maduro, and Sandro Gehri.

This PHP client is usable in any kind of PHP project. No matter what your favorite framework or CMS is (Symfony, CodeIgniter, CakePHP, WordPress, Magento, etc.), there’s something here for you.

And a Laravel adapter (openai-php/laravel) is available, which adds a handy facade and mocking abilities for everyone’s convenience.

Table of contents

OpenAI for PHP: add AI in your project with GPT-3 & ChatGPT

What is AI (Artificial Intelligence)?

Artificial intelligence (or AI for short) involves using computers to do things that would generally need human intelligence to get done.

This means creating algorithms (or sets of rules) to sort, study, and draw predictions from data.

Just like a child becoming a smarter adult, AI systems “learn” thanks to experience.

What is OpenAI?

OpenAI is a research company that is focused on AI and machine learning.

The company was founded by several people, including Jack Hughes (one of the co-founders of Akamai Technologies) and Elon Musk (the founder of Tesla, SpaceX, and several other startups).

OpenAI’s goal is to “advance digital intelligence in the way that is most likely to benefit humanity as a whole.”

And the best of all? They make it easy for us to use their GPT models in our projects. I will show you how.

The OpenAI REST API

The OpenAI REST API can be used to work with their GPT-3 models (and soon, GPT-4) for tasks involving natural language processing and generation (in over 26 different languages!), as well as code understanding and generation.

Each model have their specificities and cost.

Yep, OpenAI isn’t free!

OpenAI GPT models pricing

First, you should know it’s free to start (with $18 of credit) and quite cheap after that.

Model Training Usage Prompt Completion
GPT-4 (32K context) - - $0.06 $0.12
GPT-4 (8K context) - - $0.03 $0.06
ChatGPT (gpt-3.5-turbo) - $0.002 / 1K tokens - -
Ada $0.0004 / 1K tokens $0.0016 / 1K tokens - -
Babbage $0.0006 / 1K tokens $0.0024 / 1K tokens - -
Curie $0.0020 / 1K tokens $0.0120 / 1K tokens - -
Davinci $0.0200 / 1K tokens $0.1200 / 1K tokens - -

1K tokens = ~750 words (learn more about tokens)

I recommend you to get up to speed by playing with GPT using OpenAI’s playground.

Create an account, mess in the playground, see how the different models perform and join me for the next step!

Be inspired by projects using GPT through OpenAI’s REST API

The services below make millions of dollars using the exact same API demoed in this tutorial. Take inspiration from them, they’ll give you a lot of ideas. 👍

Also, if you subscribe to any of them, I’ll be compensated at no cost to you. This allows me to spend more time creating educational content for free.

What The Diff

What The Diff

What The Diff is an insanely creative use of the model that will save time to thousands of developers.

As you may know, GPT understands code in addition to human language. What The Diff integrates to GitHub and creates a summary of pull requests to help the reviewing developer get a big head start.

Try What The Diff

Copy.ai

Copy.ai

Copy.ai is a GPT-3 based service made to help content creators (like bloggers) write faster.

Some people make money by creating websites filled only with AI-generated content.

Others (like me) use AI to help with the blank page syndrome.

Honestly, I can’t imagine my life without AI anymore.

By the way, Copy.ai gives my readers 40% off their first year if they upgrade to a paid plan within 4 days of creating their free account.

Get a free for life account with 2,000 words each month.

Try Copy.ai

Jasper (formerly Jarvis)

Jasper

Jasper is similar to Copy.ai.

In my opinion, Copy.ai is the best.

But if you’re seriously looking to use AI for your benefit, I’d recommend you to test both and make your own opinion.

10,000 credits + 10,000 bonus using the link below.

Try Jasper

Originality.AI

Originality.AI

Originality.AI is a plagiarism and AI content detection tool.

Tools like Copy.AI and Jasper are great, but you want to make sure they didn’t inadvertently plagiarized any of your competitors, which could make you look really bad.

The cost is only $0.01 per credit, with 1 credit scanning 100 words.

Try Originality.AI

Tweet Hunter

Tweet Hunter

Tweet Hunter is a tool that will make you a rock star on Twitter.

It analyzes the tweets that generated the most engagement and lets you repurpose them for your own growth, thanks to the power of GPT-3.

Try Tweet Hunter

How to use the OpenAI’s API with a PHP client (openai-php/client)

The best way to learn is to build.

When I started playing with OpenAI, I tried to make an automated job offers aggregator powered by AI.

For this tutorial, we’ll make a basic version of it where we extract unstructured data from a given job offer.

Installation

First, create a bare-minimum PHP project:

# Create a directory.
mkdir openai-test
 
# Go into the directory.
cd openai-test
 
# Create an empty file.
touch index.php

Next, install the OpenAI client:

composer require openai-php/client

Then, open the project in your favorite code editor and copy and paste this snippet:

<?php
 
require 'vendor/autoload.php';
 
$client = OpenAI::client('YOUR_API_KEY');

You can generate your own API key here..

Usage

  1. We need to copy and paste text from a job offer. It doesn’t matter which one. (In the initial project, the crawler did it for me, but we need to keep this tutorial as simple as possible.)
  2. We give instructions to the model: “Extract the requirements for this job offer as a list.”;
  3. Then, we display the result.
$prompt = <<<TEXT
Extract the requirements for this job offer as a list.
 
"We are seeking a PHP web developer to join our team.
The ideal candidate will have experience with
PHP, MySQL, HTML, CSS, and JavaScript.
They will be responsible for developing
and managing web applications and working
with a team of developers to create
high-quality and innovative software.
The salary for this position is negotiable
and will be based on experience."
TEXT;
 
$result = $client->completions()->create([
'model' => 'text-davinci-002', // The most expensive one, but the best.
'prompt' => $prompt,
]);
 
echo $result['choices'][0]['text'];

Run this code, and it will output:

- PHP
- MySQL
- HTML
- CSS
- JavaScript

But you can ask all kind of questions as well. Here’s another example:

$prompt = <<<TEXT
Extract the salary from this job offer.
 
"We are seeking a PHP web developer to join our team.
The ideal candidate will have experience with
PHP, MySQL, HTML, CSS, and JavaScript.
They will be responsible for developing
and managing web applications and working
with a team of developers to create
high-quality and innovative software.
The salary for this position is negotiable
and will be based on experience."
TEXT;
 
$result = $client->completions()->create([
'model' => 'text-davinci-002',
'prompt' => $prompt,
]);

The AI will give you this:

The salary for this position is negotiable and will be based on experience.

Now, imagine what you could do.

You could have an entirely automated project.

And lazy people like me know these are the best kind of projects!

How to use the OpenAI Laravel wrapper (openai-php/laravel)

The OpenAI Laravel wrapper is a package made to help Laravel developers get started even more easily with GPT.

Installation

Install the package via Composer:

composer require openai-php/laravel

Usage

First, make sure you have generated your own API key.

Then, publish the configuration file:

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

Finally, add your API key it in your .env file:

OPENAI_API_KEY=your-api-key

The Facade makes it super convenient to get started:

OpenAI::completions()->create([
'model' => 'text-davinci-002',
'prompt' => 'What is the meaning of life?',
])

As you can see, there are differences with the vanilla PHP client:

  1. We skip creating an OpenAI client instance.
  2. We call the Facade instead of the newly created object.

Conclusion

GPT is the basis for a variety of great products such as Copy.ai, Jasper, Originality.AI, Tweet Hunter, What The Diff, and many more.

Your imagination is the limit. I hope you will create something unique thanks to the power of AI!

Learn more about the OpenAI’s REST API.

Recommended

Nailing a Laravel job interview can be a daunting task, but with the right preparation and mindset, you can set yourself up for success.

Learning a framework can be overwhelming, but time and execution will make you a master. Here are some best practices to help you toward your goal.

Here's a case study for my blog in the programming niche, where I share everything I did to increase clicks by a huge amount since the beginning.

I show you how to upgrade your Laravel 9 project to version 10 and help you decide whether the return on investment is worth it.

Laravel 10 has been released on February 14, 2023. Let's dive into every relevant new feature and change.

I show you how to upgrade your Laravel 8 project to version 9 and help you decide whether the return on investment is worth it.

This is the most comprehensive tutorial about Tailwind CSS. Learn how to make front-end development great again.

Migrations are essential in any Laravel app using a database. I will tell you what they are, why you should use them and how you can generate them.

Take your code to the next level, thanks to exceptions. Handle errors in a more graceful way within try and catch blocks.

Store and manage files on Dropbox and use it to back up your Laravel app automatically. Compatible with PHP 8.1+ and Laravel 9+.

Powered by