I don’t know about you, but 3 out of 4 tweets on my Twitter feed are about ChatGPT. So I had to write a quick article on how to use the ChatGPT API in Symfony, especially since it’s relatively simple.
We’ll develop a script that sorts customer comments from a restaurant, from the nicest to the meanest!
Creating a New Project
To start, create a new Symfony project:
symfony new sf6-chatGPTAdd the Maker Bundle to simplify the creation of commands:
composer req symfony/maker-bundle --devNext, install the openai-php bundle to access the ChatGPT API:
composer req openai-php/symfonyAdd your OpenAI API key to the .env file:
###> openai-php/symfony ###
# Generate your own API credentials via the OpenAI portal:
# https://platform.openai.com/account/api-keys
OPENAI_API_KEY=sk-...
OPENAI_ORGANIZATION=
###< openai-php/symfony ###Creating the Command
Create a new Symfony command:
bin/console make:commandHere’s an example test dataset for customer comments:
$customerComments = [
"I ordered a waffle and found a nail and a hair in it. I was told to wait an hour for a replacement. I was never refunded. I wouldn’t even send my worst enemy to this restaurant.",
"Acceptable service. But the food wasn’t good (the lobster). We had a 7 PM reservation, arrived 10 minutes late, and our table was given away... even though there were plenty of empty tables.",
"Excellent restaurant with quality products and very good dishes. The servers are lovely. We had a great time. We can’t wait to return.",
"The setting is beautiful, from this very nicely restored building. Promising but disappointing. On the terrace, coffee served cold... despite the price. Meal with appetizers for small appetites, undercooked fish, minimal service. It's a shame; it could be much better.",
"Flawless, a magical place at night, excellent meal, and an attentive and very knowledgeable team. We had a very pleasant time! We will certainly return.",
"Very good restaurant, impeccable service, pleasant setting, quality cuisine. We had a very good time. We highly recommend this restaurant."
];Calling the ChatGPT API
To ask ChatGPT to sort the comments:
$result = $this->openai->completions()->create([
'model' => 'text-davinci-003',
'prompt' => 'Sort these restaurant customer comments from nicest to meanest:
' . implode("\n", $customerComments),
'max_tokens' => 1000,
]);The response is retrieved and transformed into a list:
$sortedCustomerComments = explode("\n", trim($result['choices'][0]['text']));Complete Command Example
Here’s the final command code:
<?php
namespace App\Command;
use OpenAI\Client;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'sort:comments',
description: 'Sort customer comments by satisfaction level',
)]
class SortCommentsCommand extends Command
{
public function __construct(private readonly Client $openai)
{
parent::__construct();
}
protected function configure(): void
{
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$customerComments = [
"I ordered a waffle and found a nail and a hair in it. I was told to wait an hour for a replacement. I was never refunded. I wouldn’t even send my worst enemy to this restaurant.",
"Acceptable service. But the food wasn’t good (the lobster). We had a 7 PM reservation, arrived 10 minutes late, and our table was given away... even though there were plenty of empty tables.",
"Excellent restaurant with quality products and very good dishes. The servers are lovely. We had a great time. We can’t wait to return.",
"The setting is beautiful, from this very nicely restored building. Promising but disappointing. On the terrace, coffee served cold... despite the price. Meal with appetizers for small appetites, undercooked fish, minimal service. It's a shame; it could be much better.",
"Flawless, a magical place at night, excellent meal, and an attentive and very knowledgeable team. We had a very pleasant time! We will certainly return.",
"Very good restaurant, impeccable service, pleasant setting, quality cuisine. We had a very good time. We highly recommend this restaurant.",
];
$result = $this->openai->completions()->create([
'model' => 'text-davinci-003',
'prompt' => 'Sort these restaurant customer comments from nicest to meanest:
' . implode("\n", $customerComments),
'max_tokens' => 1000,
]);
$sortedCustomerComments = explode("\n", trim($result['choices'][0]['text']));
foreach ($sortedCustomerComments as $comment) {
$output->writeln($comment);
}
$io->success('Processing complete');
return Command::SUCCESS;
}
}Conclusion
That’s it for today! You can find the complete code on GitHub: https://github.com/gponty/sf6-chatGPT
