Benjamin Crozat “Heard about Sevalla? They let you deploy PHP apps with ease.” Claim $50 →

openai-php/client: leverage OpenAI's API, effortlessly

10 minutes read

openai-php/client: leverage OpenAI's API, effortlessly

Introduction

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.

The de-facto standard in the community is the unofficial, open-source package openai-php/client maintained by Nuno Maduro, Sandro Gehri, and the open source community. It offers a fluent, framework-agnostic API and keeps pace with every capability the OpenAI platform exposes—chat completions, embeddings, audio, images, and more.

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

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

By the way, for the ones who still don’t know what GPT is, I recommend you to read the next section. I also have a comprehensive yet simple-to-understand article about how Large Language Models such as GPT work.

What GPT is

Picture the smartest autocomplete you’ve ever used—now crank it up to 11. That’s GPT.

  1. It read the internet. During training, the model devoured a near-internet-sized library of text, code, and even images so it could learn how information normally fits together.
  2. It guesses the next bit. When you ask a question, GPT simply guesses the next word (technically a “token”) over and over until a full answer appears. No magic, just really fast pattern-matching.

Because it has seen so many examples, it can:

  • Draft emails and blog posts.
  • Summarise long documents.
  • Translate between languages.
  • Create and edit images.
  • Think through complex problems (reasoning models like o3 shine here).
  • Write and explain code.
  • Call external tools/APIs you design (so it can, for example, fetch docs or run calculations on demand).

But keep these three points in mind:

  • It can be wrong. Sometimes GPT invents facts that sound good—double-check anything important.
  • It’s not up-to-date. The model’s knowledge currently stops in late 2023.
  • It’s not alive. There’s no understanding or feelings—just statistics.

Want the nerdy details? Read my deep dive: How do language-based AIs, such as GPT, work?

Create an OpenAI account

  1. Create an account.

Creating an account on OpenAI

  1. Confirm your email address.
  2. Log in.
  3. Generate your first API key. Be careful, it will only be displayed once. Copy and paste it into a password manager so it’s stored securely.
  4. Start using GPT-4.1’s API!

API key generation on OpenAI

GPT models pricing

The pricing of GPT models is pay for what you use. Don’t worry, invoices will be automatically calculated for you. It’s not like taxes, haha!

Model Input (USD / 1 M tokens) Cached input Output Typical use-case / notes²
GPT-4.1 $2.00 $0.50 $8.00 Flagship “every-day” model, up to 1 M-token context
GPT-4.1 mini $0.40 $0.10 $1.60 5× cheaper, ~90 % of 4.1 quality
GPT-4.1 nano $0.10 $0.025 $0.40 Lowest-latency, budget-friendly tier
o3 $2.00 $0.50 $8.00 High-reasoning model (math, code, multimodal)
o4-mini $1.10 $0.275 $4.40 Cheaper reasoning alternative
GPT-4o (Realtime API) $5.00 $2.50 $20.00 Low-latency streaming, text & vision
GPT-4o mini (Realtime) $0.60 $0.30 $2.40 Fastest realtime choice
GPT-image-1 (Text → Image) $5.00 $1.25 Token cost to create an image prompt
GPT-image-1 (Image I/O) $10.00 (input) $2.50 (cached) $40.00 (output) Image-token cost to edit / return images

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

In this tutorial, we will use the cheap, capable, and speedy GPT-4.1 mini.

How to use the OpenAI API PHP wrapper (openai-php/client)

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

We will focus on the gpt-4.1-mini model. It’s cheaper and fast. That being said, feel free to use gpt-4.1 if you value intelligence over speed.

The openai-php/client package is great because it’ll fit no matter what your favorite framework or CMS is (Symfony, CodeIgniter, CakePHP, WordPress, Magento, etc.).

Install openai-php/client

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 PHP code snippet:

<?php

require 'vendor/autoload.php';

$client = OpenAI::client('YOUR_API_KEY');

$response = $client->chat()->create([
    'model' => 'gpt-4.1-mini',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello!'],
    ],
]);

echo $response->choices[0]->message->content; // "Hello there! How can I assist you today?"

You can generate your own API key here.

Usage of openai-php/client

Once the instance of the OpenAI PHP client has been created, you can start using it by calling the chat() method and have a conversation with GPT:

$data = $client->chat()->create([
    'model' => 'gpt-4.1-mini',
    'messages' => [[
        'role' => 'user',
        'content' => 'Hello!',
     ]],
]);

// Hello there! How can I assist you today?
echo $data['choices'][0]['message']['content'];

As you can see, the API is super easy to use. You just have to pass the model you want to use and the messages you want to send to GPT.

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

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

The package supports:

  • Listing the available models for your account (gpt-4.1, gpt-4o, etc.).
  • Using completions (letting AI complete a piece of text).
  • Chatting with a model, just like in ChatGPT.
  • Transcribing an audio file (useful for podcasts for instance).
  • And so much more! This is an extensive package.

Install openai-php/laravel

Install the package via Composer:

composer require openai-php/laravel

Note that this package will also install openai-php/client, which it depends on to work. The Laravel wrapper simply registers the client in the container and provides a Facade to make it easier to use.

Usage of openai-php/laravel

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 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-4.1-mini',
    'messages' => [[
        'role' => 'user',
        'content' => 'Hello!',
    ]],
]);

echo $response->choices[0]->message->content; // "Hello there! How can I assist you today?"

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.

How to choose your GPT model

Each model (GPT-4.1, GPT-4o, etc.) has different capabilities. “4.1” models such as gpt-4.1 and gpt-4.1-mini are the smartest and most reliable among the non-reasoning models.

Your choice should be dictated by the kind of tasks you want to perform and your budget. OpenAI has pages detailing their GPT models’ capabilities as well as their pricing (which is always up to date unlike in this article).

Build a powerful spam detection tool

Let’s say you have a comments 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. Choose the model you want to use. It can be gpt-4.1, gpt-4.1-mini, gpt-4o, etc.
  2. 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.
  3. Create a user prompt that contains the potentially spammy comment.
$data = OpenAI::chat()->create([
    'model' => 'gpt-4.1-mini',
    'messages' => [[
        'role' => 'system',
        'content' => <<<'PROMPT'
You are a spam detection tool. Every prompt you get is a user-generated input from my comments 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 with JSON?

Here’s how to proceed:

  1. Change your system prompt to include the instructions to reply with JSON and the desired structure:
<<<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,
  1. To make sure GPT always replies with JSON, we will also tell it to use the JSON mode. If you don’t, GPT can be unreliable and reply with text instead:
[
  'model' => 'gpt-4.1-mini',
+  "response_format": {
+      "type": "json_object"
+  }
]

Now, for the same “Get rich with Bitcoins, now!” comment, the gpt-4.1-mini 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, you can experiment and refine this spam detection tool even more.

OpenAI API’s without a wrapper

While openai-php/client is time saving and extremely useful, some people (like me) might prefer to avoid dependencies. This is how easy it is to send requests to OpenAI’s API using Laravel’s HTTP client:

namespace App\Actions;

use Illuminate\Support\Facades\Http;

class DoSomething
{
    public function do() : string
	{
		$response = Http::withToken(config('services.openai.api_key'))
			->post('https://api.openai.com/v1/chat/completions', [
				'model' => 'gpt-4.1-mini',
				'messages' => [
					[
						'role' => 'user',
						'content' => 'I want you to do this thing.'
					],
				],
			])
			->throw()
			->json();

		return $response['choices'][0]['message']['content'];
	}
}

Then, you can test this code using the fake() method of the HTTP client’s Facade. Here’s an example written with Pest:

use App\Actions\DoSomething;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;

it('asks GPT to do a thing', function () {
    Http::fake([
        'api.openai.com/v1/chat/completions' => Http::response([
            'choices' => [['message' => ['content' => 'Lorem ipsum dolor sit amet.']]],
        ]),
    ]);

    $result = (new DoSomething)->do();

    $this->assertEquals('Lorem ipsum dolor sit amet.', $result);
  
    Http::assertSent(function (Request $request) {
	    // You can also test that:
	    // - You are using the right model ("gpt-3.5-turbo" for instance).
	    // - You sent the right prompt. Because it might contain dynamic
	    // values or be different depending on some parameters.
	});
});

Conclusion

GPT is the basis for a variety of great products nowadays and only the imagination is the limit. I hope you will create something unique thanks to the power of AI!

Talking about unique products, did you know OpenAI provides an API endpoint to generate true to life voices?


Did you like this article? Then, keep learning:

Would you mind helping me reach more people by sharing this article on social media?

4 comments

Guest

Markdown is supported.

Hey, you need to sign in with your GitHub account to comment. Get started →

Great deals for developers