GPT-3 in a Symfony 6 Web Application (My analysis on a tutorial)

The following tutorial was generated with chatgpt. Since both symfony 6 and chatgpt’s api are relatively new, or at least it was at the point in time of the training data used in gpt-3, I wanted to check its capabilities on generating a tutorial to mix both of them. The purpose of this is not to create a functional tutorial, but to analyze the AIs knowledge on the matter. The results are actually quite all right, but there are some things that are not quite consistent or super basic. Can you spot them? I will my comments inline. So here it is:

———–Start of GPT tutorial———-

In this tutorial, we will be using the latest text-davinci-003 model from OpenAI’s GPT-3 completion API to autocomplete data in a Symfony 6 form. We will be using the guzzle package for making HTTP requests to the GPT-3 API.

Guzzle… nice! Guzzle is a great HTTP Client in PHP for making requests to external sources. In my opinion one of the best, just behind Panther (which I think it also uses Guzzle?). But, will it be the best for this use case?

Prerequisites

  • A Symfony 6 web application
  • A form with multiple fields
  • PHP 8
  • Composer

Installation

First, we need to install the OpenAI SDK for PHP using composer. Run the following command in your Symfony project root directory:

composer require openai/openai

Big no no! That package does not exist! At least it doesn’t at the time of this writing. There are other packages tagged as “OpenAI SDK for PHP”, but they are made by third parties. Look at orhanerday/open-ai for example, in my opinion the best or tectalic/openai, which uses Guzzle. There is no (public right now at least) package called openai/openai and if you execute this command you will get an error. Strange that openAi’s own gpt3 is not aware of this.

Creating the Form

We will be using a Symfony form with multiple fields, and adding a textarea to construct the GPT-3 prompt. The prompt will be constructed using the form fields names and their description.

Here’s an example of a form with multiple fields:

<?php

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;

class MyFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('field1', TextType::class, [
                'label' => 'Field 1',
                'required' => true
            ])
            ->add('field2', TextType::class, [
                'label' => 'Field 2',
                'required' => true
            ])
            ->add('gpt3_prompt', TextareaType::class, [
                'label' => 'GPT-3 Prompt',
                'required' => true
            ])
        ;
    }
}

Yes, this simple form would ‘work’ but only that. It is a very basic and generic textbook Symfony form. Since you are running on an existing Symfony 6 app (a requirement in this tutorial), I would have recommended using maker bundle to create a new form.

Using the GPT-3 API

To use the GPT-3 API, we first need to instantiate the OpenAI class and set our API key.

use OpenAI\OpenAI;

$openai = new OpenAI(['api_key' => 'your_api_key']);

Again.. this would not work because is using the wrong library. it would go something like this:

use Orhanerday\OpenAi\OpenAi;
$openai = new OpenAi('OPENAI_API_KEY');

Next, we need to construct the GPT-3 prompt using the form fields names and their description.

$prompt = "Please complete the following information:\n";
$prompt .= "Field 1: " . $form->get('field1')->getConfig()->getOption('label') . "\n";
$prompt .= "Field 2: " . $form->get('field2')->getConfig()->getOption('label') . "\n";

$form->get('gpt3_prompt')->setData($prompt);

Now we can use the completions method to generate completions for our prompt.

$response = $openai->completions(
    [
        'engine' => 'text-davinci-003',
        'prompt' => $form->get('gpt3_prompt')->getData(),
        'max_tokens' => '20',
        'temperature' => 0.5,
   ]
);

These two blocks are OK-ish. The code works, but it misses the very important instruction to use this code in the controller, and to do it on form submit. It may have had a different idea, but that’s at least how I’d have done it.

The `completions` method takes several options, including the `engine` to use (in this case, `text-davinci-003`), the `prompt` we constructed earlier, and the `max_tokens` to generate. You can also adjust the `temperature` parameter to control the level of creativity in the generated completions.

The method returns a JSON object containing the generated completions. You can use this data to update the other form fields.

$completions = json_decode($response, true);
$form->get('field1')->setData($completions['choices'][0]['text']);
$form->get('field2')->setData($completions['choices'][1]['text']);

What I don’t get is the general idea… generate a prompt based on the labels of the first two fields (“Field 1” and “Field 2”) and set it to the text area, then use that data to call for the completions method and set the result as values of the two fields.

This does not make sense, as the prompt would be:
Field 1: Field 1
Field 2: Field 2
It just doesn’t make any sense, but well… lets just continue

Adding the Form to a Twig View

To add the form to a Twig view, we first need to create a new controller that will handle the form submission and rendering.

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use App\Form\MyFormType;

class MyFormController extends AbstractController
{
    /**
     * @Route("/form", name="form")
     */
    public function index(Request $request)
    {
        $form = $this->createForm(MyFormType::class);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // Use the GPT-3 API to autocomplete the form fields
            // ...
        }

        return $this->render('form.html.twig', [
            'form' => $form->createView(),
        ]);
    }
}

This looks good, and it adds comments to specify where to put the methods from above. I would’ve added this part before to make more sense.

Then we can create a new Twig template form.html.twig in our templates directory, and render the form using the form variable passed in the controller.

{{ form(form) }}

This would work, but would make a VERY simple and ugly form.

That’s it! You now have a Symfony form that uses OpenAI’s GPT-3 API to autocomplete data, and it’s rendered in a Twig view.

Keep in mind that this is just a basic example, and you can tweak and adjust the code as needed for your specific use case.

———–End of GPT tutorial ———

So as you can see, many inaccuracies along the way. I did not try to follow the tutorial, because it is not the purpose of this post, but just to evaluate the AI’s knowledge on a relatively new version of Symfony and using its own API. I do have Symfony knowledge, I have been following it since Symfony 2, and I can spot here a few things without testing it inside a real project.

So, in conclusion, be careful on what to ask the AI to help you with. If you don’t know absolutely anything about a specific development language, it might give you a good head start, but you will have to come back and forth solving problems that you may or may not know they even exist.

Thanks for reading through.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *