OpenAI PHP/Laravel tutorial: add AI in your project

Benjamin Crozat Benjamin Crozat5 minutes read

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, or the Laravel adapter (openai-php/laravel).

You can apply what you’ll learn in other kind of projects (Symfony, CodeIgniter or whatever else it is you prefer).

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

OpenAI PHP/Laravel tutorial: add AI in your project

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.

Yep, OpenAI isn’t free!

OpenAI models pricing

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

Model Training Usage
Ada $0.0004 / 1K tokens $0.0016 / 1K tokens
Babbage $0.0006 / 1K tokens $0.0024 / 1K tokens
Curie $0.0030 / 1K tokens $0.0120 / 1K tokens
Davinci $0.0300 / 1K tokens $0.1200 / 1K tokens

1K tokens = ~750 words

I recommend you to get up to speed by playing with GPT-3 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 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. 👍

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.

Twalog

Twalog

Twalog is Twitter bookmarks and likes powered by AI & search.

As Twitter power users, we constantly bookmark or like valuable tweets, but never come back to them.

That’s because Twitter does not allow you to efficiently filter them. They remain burried forever.

Twalog fixes all these issues in the most convenient way, using GPT-3 to classify all those tweets.

Join the waiting list

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 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
(No credit card required.)

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.

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

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 it for free, cancel any time

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

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 (openai-php/laravel)

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

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-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.

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.

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

Laravel 10 will be released on February 7, 2023. Its development is still ongoing. Let's dive into every relevant new feature we know about already.

Browse my list of the best hosting providers for your next Laravel app. All budgets and needs are covered.

Laravel Collections make arrays more powerful and convenient to work with. This article provides tons of quick tips to instantly make your codebase better.

Choose a web hosting provider for Laravel Forge and deploy your next Laravel project quickly and without any DevOps cost.

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

Looking to learn web development but don't know where to start? Check out our list of the best online paid and free platforms to get started!

Powered by