Programmatic interaction with ChatGPT
L(i)VID

Programmatic interaction with ChatGPT

I presented the general framework for using artificial intelligence in the context of Digital Transformations. I explained how to create a ChatGPT account, how to generate an API key, and how to buy credits. I gave a quick example of how to use ChatGPT with CURL, a basic example provided by ChatGPT. Now it's time to get down to business by creating a PHP function that will query ChatGPT and obtain a response. Then it's time to interpret the answer. This function will be a fabulous gateway to ChatGPT in a programmatic mode: you'll be able to use it within your programs, without any human intervention if that's your choice, and you'll become aware of the immensity of its field of application.

In this article, I'll mix French and English, on purpose because it will be part of the demonstration. The aim of this article is to query ChatGPT and display its results. As a prerequisite, you will need your API key.

Creation of the PHP function : sermo()

Here's the PHP code (sorry for the code structure ... that's LinkedIn):

<?php
function sermo( $system,$user,$tokens = 100 )
{
    {   /* Prepare the data to be sent to ChatGPT */

        $data = json_encode( array( 'model' => 'gpt-3.5-turbo' ,
                              'messages' => array( array( 'role' => 'system' ,
                                                                           'content' => $system , // instructions
                                                                         ) ,
                                                                 array( 'role'  => 'user',
                                                                     'content' => $user, // question/prompt
                                                               ) 
                                                            ),
                                    'temperature'  => 1,
                                    'frequency_penalty' => 0 ,
                                    'presence_penalty'  => 0,
                                  ),
                             JSON_UNESCAPED_UNICODE
                           );
    }   /* Prepare the data to be sent to ChatGPT */

    {   /* Setup curl */
        $ch = curl_init();

        curl_setopt( $ch,CURLOPT_URL,'https://api.openai.com/v1/chat/completions' );
        curl_setopt( $ch,CURLOPT_POST,1 );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER,1 );
        curl_setopt( $ch,CURLOPT_POSTFIELDS,$data );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER,1 );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYHOST,2 );
        curl_setopt( $ch,CURLOPT_HTTPHEADER,array( 'Content-Type: application/json',"Authorization: Bearer YOUR_API_KEY" ) );
    }   /* Setup CURL */

    $result = curl_exec( $ch );
    curl_close( $ch );

    if ( ! $result )
    {
        return ( null );
    }
    else
    {
        return ( $result );
    }
}
?>        

Parameters

  • system: instructions given to ChatGPT to generate its response
  • user: the question asked to ChatGPT
  • tokens: the maximum number of "words" ChatGPT must use to formulate its answer.

Many AI solutions based on ChatGPT provide a single area for you to enter your question, known as the "prompt". In fact, ChatGPT can handle both the instructions (system) and the question (user) in a single area. We're going to separate the two, i.e. system and user, so we can be more precise.

tokens is important because it's a parameter that enables us to limit our expenses: the longer ChatGPT answers, the faster our credits go! When you're developing solutions, you're going to be doing a lot of testing and ... you don't want to see your account melt like snow in the sun just for the sake of testing; adjusting the number of tokens to the minimum then makes perfect sense.

Using sermo()

We're going to use our sermo() function on the text of an article. We'll change the instructions supplied to ChatGPT (system) a few times while working on the same text. You'll see that a single function, sermo(), can do a myriad of things.

First example: article summary

So, we're going to create a short article (extracted from Belgian government press releases) which we'll complete with a comparison with French debt. Here's the article, written in French:

à la fin juillet 2024, la dette de l’état fédéral belge s’élevait à 521,868 milliards d’euros. La dette de l’état a ainsi augmenté de 258,31 millions d’euros depuis juin. En termes nets (après déduction des placements et des titres en portefeuille), la dette de l’Etat fédéral a diminué de 5,13 milliards d’euros, pour s’établir à 496,259 milliards d’euros. Le solde net à financer s’est élevé à 5,14 milliards d’euros (au détriment du Trésor). Pour de plus amples renseignements sur les émissions et les remboursements des dettes à court et long termes en juillet 2024, veuillez consulter le site de l’Agence fédérale de la Dette (https://www.debtagency.be/fr). La durée moyenne de la dette de l’état fédéral a progressé de 0,16 année pour passer à 10,80 années, tandis que le taux d’intérêt moyen sur les instruments de la dette a baissé pour s’établir à 1,93 %. Les risques de refinancement à 12 et 60 mois étaient respectivement de 13,87 % et 38,04 %
Si on comparait la Belgique et la France sur base de leurs populations approximatives, 11000000 d'habitants pour la Belgique et 66000000 pour la France, on arrive à un facteur 6. Prenons ce facteur et appliquons-le à la dette : 522 milliards x 6 = 3132 milliards (je prends 522 milliards et non 496 car c'est une métrique commune entre France et Belgique). Or ... c'est à peu près l'équivalent effectivement de la dette de la France, non ??à la fin du premier trimestre 2024, la dette publique de la France s'élevait à 3159,7 milliards d'euros, représentant 110,7 % du PIB. On en déduit quoi ? La situation de la Belgique est quasiment équivalente à celle de la France. Ce n'est pas un constat positif !

This will be the prompt (user parameter, $user = the text I just typed above).

Here are the instructions to require the summary of the article:

Tu es un expert en linguistique. Tes réponses sont courtes et directes. Tu n'exprime aucune opinion personnelle. Résume le texte et fournis ta réponse dans une variable PHP comme dans $summary = "<ici ton résumé>"

This will be the instructions (system parameter, $system = the text I just typed above).

$user = "à la fin juillet 2024, la dette de l’état fédéral belge s’élevait à 521,868 milliards d’euros. La dette de l’état a ainsi augmenté de 258,31 millions d’euros depuis juin. En termes nets..."; // Please copy/paste the article        
$system = "Tu es un expert en linguistique. Tes réponses sont courtes et directes. Tu n'exprime aucune opinion personnelle. Résume le texte et fournis ta réponse dans une variable PHP comme dans \$summary = \"<ici ton résumé>\"";        

Calling sermo() to obtain the summary:

$r = json_decode( sermo( $system,$user,100 ) );
$response   = htmlentities( $r->choices[0]->message->content );

echo "<div style=\"background: white; padding: 4em; width: 80%; margin:4em auto; border: 2px solid silver;\">\n";
    echo $response;
echo "</div>\n";        

Which produces the following output:

$summary = "En juillet 2024, la dette de l'état fédéral belge était de 521,868 milliards d'euros, avec une augmentation de 258,31 millions d'euros par rapport à juin. Cependant, en termes nets, la dette a diminué à 496,259 milliards d'euros. Le solde net à financer s'est élevé à 5,14 milliards d'euros. La durée moyenne de la dette a augmenté tandis que le taux d'intérêt moyen a baissé. Comparée à la France, la situation de la Belgique en termes de dette est quasiment équivalente à celle de la France.";        

Amazing, isn't it? You've just created a summary of the article in 2 lines of code. Let's move on by extracting the keywords of the article so that we can later on display them as hashtags attached to the article.

The only thing we will have to change is the $system parameter : we'll formulate other instructions!

Second example: keyword extractions

OK ... only the instruction will have to change. Here they are:

Tu es un expert en linguistique. Tes réponses sont courtes et directes. Tu n'exprimes aucune opinion personnelle. Extrais un tableau de mots-clefs du texte et mets-les dans un tableau PHP que tu nommeras \$keywords. Les mots-clés doivent être capitalisés (1ère lettre en majuscule). Quand tu rencontres des mots-clefs composés comme avec "état belge", élimine les espaces et capitalise chaque mot qui compose le mot-clef (1ère lettre en majuscule). Par exemple "état belge" doit devenir "étatBelge". Quand tu as des mots-clefs qui contiennent des guillemets (quotes), simples ou doubles, élimine les guillemets des mots-clefs. Trasnforme aussi tous les caractères accentués en leur équivalent sans accent. Par exemple "é" devient "e"
$system = "Tu es un expert en linguistique. Tes réponses sont courtes et directes. Tu n'exprimes aucune opinion personnelle. Extrais un tableau de mots-clefs..."; // copy/paste the instructions set above        

Calling sermo() to obtain the keywords:

It's EXACTLY the same code as above and this is precisely why we can say that the same door, our sermo() function, is the entry gate to a myriad of different services...

$r = json_decode( sermo( $system,$user,100 ) );
$response   = htmlentities( $r->choices[0]->message->content );

echo "<div style=\"background: white; padding: 4em; width: 80%; margin:4em auto; border: 2px solid silver;\">\n";
    echo $response;
echo "</div>\n";        

Which produces the following output:

```php <?php $keywords = [ "Dette", "étatBelge", "Milliards", "Euros", "Placements", "TitresEnPortefeuille", "SoldeNet", "Trésor", "AgenceFédéraleDeLaDette", "DuréeMoyenne", "TauxDIntérêtMoyen", "RisquesDeRefinancement", "Population", "France", "Facteur", "PIB", "PremierTrimestre" ]; ?> ```        

Surprising again! There's a small glitch, however, in that the accented characters have not been transformed into non-accented characters. This means that the wording (my instructions, $sytem) is probably not optimal for ChatGPT. We'll have to try again later.

Third example: translation

Once again, all we have to do is modify the instructions! The code to query ChatGPT is identical!

Tu es un traducteur certifié fran?ais-anglais et anglais-fran?ais. Détermine la langue dans laquelle l'article est écrit et traduis l'article dans l'autre langue dont tu es un spécialiste. Ta réponse ne doit contenir QUE la traduction.
$system = "Tu es un traducteur certifié fran?ais-anglais et anglais-fran?ais. Détermine la langue dans laquelle..."; // copy/paste the instructions set above        

Which produces the following output:

At the end of July 2024, the debt of the Belgian federal state stood at 521.868 billion euros. The state's debt has thus increased by 258.31 million euros since June. Net terms (after deducting placements and portfolio securities), the federal state's debt decreased by 5.13 billion euros, to stand at 496.259 billion euros. The net financing balance amounted to 5.14 billion euros (at the expense of the Treasury). For more information on debt issuances and repayments in July 2024, please visit the Federal Debt Agency website (https://www.debtagency.be/fr). The average maturity of the federal state's debt increased by 0.16 years to 10.80 years, while the average interest rate on debt instruments decreased to 1.93%. Refinancing risks at 12 and 60 months were 13.87% and 38.04% respectively. If we were to compare Belgium and France based on their approximate populations, 11,000,000 inhabitants for Belgium and 66,000,000 for France, we arrive at a factor of 6. Let's take this factor and apply it to the debt: 522 billion x 6 = 3132 billion (I take 522 billion and not 496 because it's a common metric between France and Belgium). However... this is roughly equivalent to France's debt, right? At the end of the first quarter of 2024, France's public debt stood at 3159.7 billion euros, representing 110.7% of GDP. What does that tell us? Belgium's situation is almost equivalent to that of France. This is not a positive finding!        

Conclusion

A single function, sermo(), serves as the gateway to a series of functions, all driven by the instructions supplied to ChatGPT. We've summarized an article, extracted its keywords and translated it from French into English, all programmatically.

We can add many features that may prove invaluable in our programs. For my own purposes, I've designed complete instructions ($system) for text analysis, such as: adding automatic hashtags, providing links with speech bubbles, determining main topics (science, economics, politics, sports, etc.). It's a real time-saver.

I hope you enjoyed this mini-series on ChatGPT in "programming" mode. Above all ... keep it always simple like the sermo() function. No fuss !

Previous article - Next article

Woodley B. Preucil, CFA

Senior Managing Director

1 个月

Patrick Boens Fascinating read. Thank you for sharing

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了