Benjamin Crozat The web developer life

OpenAI PHP & Laravel: artificial intelligence in your project

Benjamin Crozat Benjamin Crozat5 minutes read

Before you start reading this article, did you know 76 persons subscribed to my newsletter?

Join them and enjoy free content about the art of crafting websites!

OpenAI PHP & Laravel: artificial intelligence in your project

To use OpenAI’s web API, you can:

  1. Directly make HTTP requests;
  2. Use a client written in PHP that will significantly simplify your journey.

Option #2 is precisely what we’re going to do thanks to the Open AI PHP client written by Mantas Smilinskas, Nuno Maduro, and Sandro Gehri.

You can apply what you’ll learn in projects using vanilla PHP, Laravel, Symfony, CodeIgniter or whatever else it is you prefer, it doesn’t matter.

The goal will be to extract unstructured data from a job offer, which is something only AI can do (besides humans). With courage and perseverance, it could lead to an entirely automated jobs board for instance!

Table of contents

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 tiny human child growing up into a smarter adult, AI systems “learn” by increasing their experience and processing more information.

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-3 models in our projects. I will show you how.

The OpenAI API

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

I must tell you first, though: the OpenAI API isn’t free! Here are their pricings depending on the model.

But who cares? They recently lowered their prices, and you can start with $18 of free credit for three months. After that, it’s incredibly cheap as long as you use it for testing purposes.

I recommend you to get up to speed by playing with GPT-3 using OpenAI’s playground. Create an account, mess in the playground, and join me for the next step!

Be inspired by services already using the OpenAI GPT-3 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. 👍

What The Diff

What The Diff

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

As you may know, GPT-3 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.

Start for free, no credit card required

Copy.ai

Copy.ai

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

Some people like to create websites only with AI generated content (which can be a lucrative business if Google doesn’t catch you) and some people like me use them to help with the blank page syndrome.

Honestly, I can’t live without one of these tools anymore.

Get a free account with 2,000 words per month, no credit card required

Jasper (formerly Jarvis)

Jasper

Jasper is basically the same thing as Copy.ai, in a different form. In my opinion, Copy.ai is the best. But if you’re seriously looking to use an AI, I’d recommend you to test both and make your own opinion.

Get started for free with 10,000 credits + 10,000 bonus credits

Tweet Hunter

Tweet Hunter

Tweet Hunter is a crazy good idea that will make you a rock star on Twitter.

It allows you to browse successful tweets and rewrite them thanks to the power of GPT-3 to maximize your chances of generating engagement.

But there’s more and it’s free to try!

Try it for free, cancel any time

How to use the OpenAI API 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:

mkdir openai-test
cd openai-test
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 GPT-3 model: “Extract the requirements for this job offer as a list.”;
  3. Then, we call the API using PHP, which is way more convenient than manually making HTTP requests.
$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,
'max_tokens' => 50, // A token is a basically a word.
]);

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. Store what the AI gives you into a database, aggregate the job offers on a website and help thousands of developers!

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

The OpenAI Laravel wrapper is a simple project I made to help Laravel developers get started even more easily with GPT-3.

Installation of OpenAI Laravel

Install the package via Composer:

composer require benjamincrozat/openai-laravel

Usage of OpenAI Laravel

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

Then, add it in your .env file:

OPENAI_API_KEY=your-api-key

The Facade makes it super convenient to get started:

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

Conclusion

GPT-3 is the basis for a variety of great products such as Copy.ai, Jasper, 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 API and the OpenAI PHP client on GitHub.

Other posts to read

You heard about Laravel but don't know where to start? Don't worry, you found the best starting point for your journey.

Whether PHP is dead or not is a matter of numbers, not opinions. I will provide you with essential statistics that will lead you to make better decisions.

There are multiple ways to check if an array is empty. Let me tell you about each of them and why and when you should use them.

Learning a framework can be overwhelming. Time and practice will make you a master. Here are some best practices to help you toward your goal.

To keep getting better with PHP, you should subscribe to as many quality blogs as possible. In this article, I share the ones I often read myself.

Redirects in PHP are simple. I will guide you step by step and show you how to dodge some traps. Finally, we'll learn the nuance between 301 and 302 redirects.

Learn why the "Using $this when not in object context" error happens, and let me show you the only way to fix.

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.

A soft delete in Laravel allows you to prevent mistakes by not removing sensitive data from your database right away.

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.