“I created an AI assistant for Laravel developers that handles all the boring work.”
Learn more
Smousss
Benjamin Crozat The art of crafting web applications

OpenAI for PHP: AI in your project with GPT-3.5 (ChatGPT)

Benjamin Crozat — Updated on

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: AI in your project with GPT-3.5 (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.

https://twitter.com/sama/status/1610666441027772416

What is GPT?

GPT, which stands for Generative Pre-trained Transformer, is an advanced type of artificial intelligence model that belongs to a family called (Large) Language Models (LLMs).

So, what does GPT do?

Well, it’s designed to understand and generate human-like text based on the input it receives.

It can read and analyze large amounts of text data and then use that knowledge to generate coherent and contextually appropriate responses or completions.

Imagine having a really smart assistant that can understand what you’re saying or writing and then provide helpful and accurate information in response.

That’s what GPT does, but on a much larger and more sophisticated scale.

GPT has been trained on vast amounts of data from the internet, books, articles, and other sources to develop a deep understanding of language patterns and context.

This training helps GPT generate text that sounds remarkably human-like.

It can be used for a wide range of applications, such as answering questions, writing essays, providing recommendations, and even creating code.

That being said, remember that GPT is just one example of AI technologies.

The OpenAI REST API

The OpenAI REST API can be used to work with their GPT 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 specificities and cost.

Yep, OpenAI isn’t free!

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!

I made an AI-powered service called Smousss

Smousss

Smousss is a GPT-4-based assistant that makes Laravel developers’ life easier by handling repetitive tasks in a heartbeat.

Here are the available features:

Once you get the hang of how AI works, you will be able to unleash your creativity and create such tools.

Try Smousss

This shameless plug being done, I think I’m the ideal person to teach you about GPT. 😎

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

The best way to learn is to build. Let’s get started by setting up the package and by performing a basic request.

We will focus on the gpt-3.5-turbo model. It’s cheap, fast and this is the same model that powers ChatGPT.

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

$data = $client->chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => [[
'role' => 'user',
'content' => 'Hello!',
]],
]);
 
// Hello there! How can I assist you today?
echo $data['choices'][0]['message']['content'];

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

The OpenAI Laravel wrapper is a package made to help 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:

$data = OpenAI::chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => [[
'role' => 'user',
'content' => 'Hello!',
]],
])
 
// Hello there! How can I assist you today?
echo $data['choices'][0]['message']['content'];

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

  1. We skip creating an OpenAI client instance, since the package already did it and stored the instance in the container.
  2. We call the Facade instead of a newly created object.

Build a powerful spam detection tool in 5 minutes

Let’s say you have a comment system.

You want to make sure the user isn’t spamming you.

This was a hard problem to solve. Luckily, AI can help like it’s nothing.

  1. Create a system prompt that defines the purpose of the model. We tell it it’s a spam detection tool and give it some rules to follow.
  2. Create a user prompt that contains the potentially spammy comment.
$data = OpenAI::chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => [[
'role' => 'system',
'content' => <<<'PROMPT'
You are a spam detection tool. Every prompt you get is a user-generated input from my commenting system. Tell me if it should pass validation or not.
 
The only rules to follow are:
- No self-promotion
- No offensive statements
PROMPT,
], [
'role' => 'user',
'content' => 'Get rich with Bitcoins, now!',
]],
]);
 
// Not valid. This is self-promotion and potentially a scam.
echo $data['choices'][0]['message']['content'];

How incredible is that? Building this spam detection tool required almost zero effort.

But what if we change the system prompt to generate a more exploitable reply woth JSON? Here it is:

<<<PROMPT
You are a spam detection tool. Every prompt you get is a user-generated input from my commenting system. Tell me if it should pass validation or not.
 
The only rules to follow are:
- No self-promotion
- No offensive statements
 
Reply with the following JSON:
 
{
"pass": true,
"reason": "foo"
}
 
The "reason" key should thoroughly describe why the input passes validation or not.
PROMPT,

Now, for the same “Get rich with Bitcoins, now!” comment, the gpt-3.5-model replies with:

// {
// "pass": false,
// "reason": "This input should not pass validation because it is promoting a get-rich-quick scheme related to cryptocurrencies, which is often associated with fraudulent activities."
// }
echo $data['choices'][0]['message']['content'];

From there, I let you experiment further to refine this spam detection tool even more. 💪

Conclusion

GPT is the basis for a variety of great products such as Smousss, and many more.

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

Recommended

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.

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

switch, case, and break. What are all these? When should you use it instead of if? What are its pros and cons?

Debugging requires dissecting everything. Here's a list of all the one-line of code built-in ways to print arrays in PHP (and even Laravel-specific helpers).

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.

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

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

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

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

Offer new ways to interact with your app to your users. Learn how to build a ChatGPT plugin with Laravel.

Powered by