This post is more than a year old. There is a chance the content is outdated.

Querying OpenAI with Laravel

Querying OpenAI with Laravel


Ok, so this isn't technically a Laravel post because you can do this with any framework, but i'll be using Laravel's HTTP library to query OpenAI and then later i'll show you some composer packages to easier work with it.

What is OpenAI

OpenAI is an AI research and deployment company. Their mission is to ensure that artificial general intelligence benefits all of humanity. They are the company that built the very popular ChatGPT.

Creating an OpenAI account and adding credits

In order to utilize the OpenAI API, you will need to create an account and hook up a credit card.

After logging in, click your name in the upper right and click Manage Account.

The click on billing on the left, and click the button to set up a paid account. Your card will be charged a small fee for authorization.

The API itself is very cheap. We will be using GPT-3.5 Turbo which is $0.0015 per 1k tokens.

Don't get confused though, because a single API call does not cost one token.

A helpful rule of thumb is that one token generally corresponds to ~4 characters of text for common English text. This translates to roughly ¾ of a word (so 100 tokens ~= 75 words).

They have a useful Tokenizer Tool so you can visualize how many credits your call will cost.

Adding a new service to Laravel

Open your services.php config file and add the following:

1'open-ai' => [
2 'key' => env('OPENAI_API_KEY'),
3],

Then in your .env file, add a OPENAI_API_KEY= key.

Grab your key from the API Keys area of OpenAI and add it to your .env file.

Querying OpenAI

We are going to use the Laravel Http facade to query the OpenAI endpoint:

1$data = Http::withHeaders([
2 'Content-Type' => 'application/json',
3 'Authorization' => 'Bearer '.config('services.open-ai.key'),
4])
5 ->post("https://api.openai.com/v1/chat/completions", [
6 "model" => "gpt-3.5-turbo",
7 'messages' => [
8 [
9 "role" => "user",
10 "content" => 'what is Laravel?'
11 ]
12 ],
13 ])
14 ->json();
15 
16 return response()->json($data['choices'][0]['message'], 200, array(), JSON_PRETTY_PRINT);

Yields:

Laravel is a popular open-source PHP framework used for web application development. It provides a clean and elegant syntax while offering a wide range of features and tools to make web development tasks easier and more efficient.

Alternative Methods

Instead of using the verbose method above, there are composer packages that help you:

Either of these options will give you a clean API to query with:

1use OpenAI\Laravel\Facades\OpenAI;
2 
3$result = OpenAI::completions()->create([
4 'model' => 'text-davinci-003',
5 'prompt' => 'PHP is',
6]);
7 
8echo $result['choices'][0]['text']; // an open-source, widely-used, server-side scripting language.
Anthony Rappa

By Anthony Rappa

Hello! I'm a full stack developer from Long Island, New York. Working mainly with Laravel, Tailwind, Livewire, and Alpine.js (TALL Stack). I share everything I know about these tools and more, as well as any useful resources I find from the community. You can find me on GitHub and LinkedIn.