<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ramzi Bey on Medium]]></title>
        <description><![CDATA[Stories by Ramzi Bey on Medium]]></description>
        <link>https://medium.com/@ramzi_bey?source=rss-40a57dae91c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*d7Ecp0nQF2LZggZqBRP2MQ.jpeg</url>
            <title>Stories by Ramzi Bey on Medium</title>
            <link>https://medium.com/@ramzi_bey?source=rss-40a57dae91c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:57:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ramzi_bey/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to get the token Consummation using the stream mode with openAI]]></title>
            <link>https://medium.com/@ramzi_bey/how-to-get-the-token-consummation-using-the-stream-mode-with-openai-661098c8cede?source=rss-40a57dae91c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/661098c8cede</guid>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Ramzi Bey]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 16:57:32 GMT</pubDate>
            <atom:updated>2024-09-12T16:57:32.067Z</atom:updated>
            <content:encoded><![CDATA[<p>The question looks trivial but before a recent update, you had to deal with external libraries to get this information in stream mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1I8xJu3p55ZG08E19PuMZA.jpeg" /></figure><h3>Introduction</h3><p>A few months ago, I integrated the OpenAi’s streaming mode into one of my AI project. I encountered one problem with this feature, with the stream mode, the amount of token consumed wasn’t provided anymore. Previously, to get the token consumption, you had to rely on an external library to get back this information. In my company, we decided to not spend time on adding a non native and maybe inaccurate solution.</p><p>Recently, I wanted see if this previously mentioned solution could be implemented quickly and its accuracy. Surprise, in a recent update, OpenAI added an option on the API call body to get effortlessly how mush token you used.</p><h3>Setup</h3><p>To get started with a functional OpenAi project, you can utilize the provided repository below:</p><p><a href="https://github.com/RamziBey/OpenAIChatStream">Github Repository</a></p><ul><li>Clone the repository</li><li>Add a env file with your OpenAi API key with the name “OPENAI_KEY”</li></ul><p>It comes from previous posts I did. The code is straightforward but you can read my posts to understand deeply how it works and get all explanations.</p><p>You have a file called action.tsx. In this file we will pay attention to <strong>callToOpenAI</strong> and <strong>streamReader</strong> function</p><pre>async function callToOpenAi(request: RequestDataForAI) {<br>    const messages = [prompt]<br><br>    const response = await fetch(&quot;https://api.openai.com/v1/chat/completions&quot;, {<br>        cache: &#39;no-cache&#39;,<br>        method: &quot;POST&quot;,<br>        headers: {<br>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br>          &quot;Authorization&quot;: `Bearer ${process.env.OPENAI_KEY}`<br>        },<br>        body: JSON.stringify({<br>            model: request.model,<br>            messages: messages.concat(request.messages),<br>            stream: true,<br>        }),<br>    });<br>    if (response.body != null) {<br>        let reader = response.body.getReader();<br>        return streamReader(reader);<br>    }<br>}<br><br>function streamReader(reader: ReadableStreamDefaultReader&lt;Uint8Array&gt;) {<br>    const textDecoder = new TextDecoder();<br>    let buffer = &#39;&#39;;<br><br>    return (new ReadableStream({<br>        start(controller) {<br>            function push() {<br>                reader.read().then(({ done, value }) =&gt; {<br>                    if (done) {<br>                        controller.close();<br>                        return;<br>                    }<br>                    const decodedChunk = textDecoder.decode(value);<br>                    <br>                    buffer += decodedChunk;<br>                    const encoder = new TextEncoder();<br><br>                    try {<br>                        const cleaneddata = parse(buffer)<br>                        for (let line of cleaneddata) {<br>                            const { content } = line.choices[0].delta;<br>                            <br>                            if (content) {<br>                                const bufferEncoded = encoder.encode(content);<br>                                controller.enqueue(bufferEncoded);<br>                                buffer = &#39;&#39;<br>                            }<br>                        }<br>                    } catch {<br>                        push()<br>                        return<br>                    }<br>                    push();<br>                });<br>            }<br>            push()<br>        },<br>    }))<br>}</pre><p>To better understand the data you receive from OpenAI, place a <em>console.log(decodedChunk)</em> within the <strong>streamReader</strong> function. This will display a JSON object containing a chunk of data you received from OpenAI.</p><p>Now, you need to update the request body of the fetch function in <strong>callToOpenAi </strong>and<strong> </strong>include the field <em>stream_options. </em>This is an object with a boolean <em>include_usage</em> that you must set to true to notify OpenAI that we want the number of tokens used.</p><pre>body: JSON.stringify({<br>    model: request.model,<br>    messages: messages.concat(request.messages),<br>    stream: true,<br>    stream_options: {<br>        include_usage: true,<br>    }<br>}),</pre><p>Make a test and you will have as the last chunk of data, a field “usage built as follow:</p><pre>&quot;usage&quot;:{&quot;prompt_tokens&quot;:313,&quot;completion_tokens&quot;:54,&quot;total_tokens&quot;:367}</pre><h3><strong>Conclusion</strong></h3><p>By adding a simple <em>stream_options</em> to your request, you can now obtain natively real-time token consumption without relying on external libraries or complex workarounds. This will helps you manage costs more effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=661098c8cede" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is GPT-4o that is useful ? Efficiency comparaison between OpenAI models]]></title>
            <link>https://medium.com/@ramzi_bey/is-gpt-4o-that-is-useful-efficiency-comparaison-between-openai-models-67b65bca1888?source=rss-40a57dae91c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/67b65bca1888</guid>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Ramzi Bey]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 21:18:16 GMT</pubDate>
            <atom:updated>2024-06-18T21:18:16.956Z</atom:updated>
            <content:encoded><![CDATA[<h3>Is GPT-4o that is useful ? Efficiency comparaison between OpenAI models</h3><p>We all saw astonishing presentation of the last model GPT-4o. Does it have a real value or is it just another new model.</p><h3>Introduction</h3><p>As a frequent user of the OpenAI API, I often rely on various models for various tasks. The recently launched GPT-4o has garnered attention, but does it truly add value? In this analysis, we will dive into the pros and cons of GPT-4o compared to other models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yl0lCdwkblVreb7YWhX0IQ.jpeg" /></figure><h3>Presentation of the models</h3><p>We will compare the following four models:</p><p><strong>gpt-3.5-turbo</strong>:</p><ul><li>Context limit: 16k tokens</li><li>Cost: $0.50 per 1M tokens (input), $1.50 per 1M tokens (output)</li><li>Characteristics: Light, fast, and cost-effective. Suitable for simple tasks.</li></ul><p><strong>gpt-4-turbo-2024-04-09</strong>:</p><ul><li>Context limit: 128k tokens</li><li>Cost: $10.00 per 1M tokens (input), $30.00 per 1M tokens (output)</li><li>Characteristics: Intelligent but slow and expensive. Ideal for complex tasks requiring deeper understanding.</li></ul><p><strong>gpt-4o:</strong></p><ul><li>Context limit: 128k tokens</li><li>Cost: $5.00 per 1M tokens (input), $10.00 per 1M tokens (output)</li><li>Characteristics: Balanced in terms of speed, efficiency, and cost.</li></ul><h3>Comparaisons</h3><p>I split the comparaison in three categories. Suggestion, Information, Reflexion.</p><ul><li>Suggestion: Each model will be asked to provide suggestions based on a given need.</li><li>Information: each model will be asked to provide factual information.</li><li>Reflection: Each model will be given a mathematical problem to solve..</li></ul><h4>The first question — Suggestion:</h4><blockquote>I recently read a French book, Bel-Ami. Do you have any suggestions for books of a similar style?</blockquote><p><strong>GPT-3.5-turbo</strong> took 1.7 second but did a shorter answer, gives brief details about the books and don’t speak like a human wishing me a nice reading etc.</p><blockquote>1. Madame Bovary by Gustave Flaubert — This classic French novel explores themes of love, adultery, and societal norms in 19th century France, similar to the themes of ambition and manipulation in Bel-Ami.</blockquote><blockquote>2. Therese Raquin by Émile Zola — Another French novel that delves into themes of passion, betrayal, and psychological torment. Like Bel-Ami, the protagonist’s actions have far-reaching consequences on their relationships and lives.</blockquote><p><strong>GPT-4–2024–04–09</strong> is way slower with 9.3 seconds but go deeper in the presentation it provides about the books.</p><blockquote>Certainly! If you enjoyed ”Bel-Ami” by Guy de Maupassant, which is a classic French novel characterized by its critique of society, its rich character development, and Maupassant’s distinctive style, you might also enjoy the following books that offer similar themes and elements:1. ”The Red and the Black” (Le Rouge et le Noir) by Stendhal* — This novel, published in 1830, explores themes of ambition and social climbing in French society, much like ”Bel-Ami.” It tells the story of Julien Sorel, a young man of modest origin who aspires to rise above his humble beginnings through manipulation and seduction. Stendhal captures the complexity of his characters and their moral dilemmas, set against the backdrop of the Restoration period in France.2. ”Thérèse Raquin” by Émile Zola — First published in 1867, this novel is a bit darker but similarly engages with the depths of character and moral ambiguities. The story revolves around Thérèse Raquin, who is trapped in a loveless marriage and embarks on a turbulent and ill-fated affair with her husband’s friend. Zola’s naturalistic style and his focus on the darker sides of human nature and society might appeal to you if you appreciated the realistic and sometimes cynical portrayal found in ”Bel-Ami.”Both these novels offer a profound social commentary much like ”Bel-Ami,” and delve into the complexities of human desires and societal expectations in a narrative style rich with psychological insight and critical observation.</blockquote><p><strong>GPT-4o</strong> answer took 4.21 seconds, the output is accurate with good suggestions. It also provide layout settings like bold, new lines etc. but I removed them to facilitate reading.</p><blockquote>Absolutely! If you enjoyed ”Bel-Ami” by Guy de Maupassant, you might appreciate these two books that share similarities in style, themes, and their exploration of society:</blockquote><blockquote>1. ”The Red and the Black” (Le Rouge et le Noir) by Stendhal (Henri Beyle): This novel provides a keen social critique and portrays the ambitious rise of its protagonist, Julien Sorel, in 19th-century French society. It’s similar to ”Bel-Ami” in its exploration of social climbing, personal ambition, and the often cynical nature of the protagonist’s actions. The depiction of provincial life and the complex entanglements of romantic and political ambitions resonate with the themes in ”Bel-Ami.”</blockquote><blockquote>2. ”Lost Illusions” (Illusions perdues) by Honoré de Balzac: Another great work of French literature, this novel follows the young poet Lucien Chardon as he attempts to make a name for himself in Paris. Like Duroy in ”Bel-Ami,” Lucien faces the harsh realities of ambition, betrayal, and the corrupting influence of high society. Balzac’s intricate detail and realistic portrayal of social dynamics and personal aspirations make it a compelling read for fans of ”Bel-Ami.”Both novels provide a deep dive into the complexities of ambition and social maneuvering, much like ”Bel-Ami.” Happy reading!</blockquote><h4>The second question — Information:</h4><blockquote>I’m looking for a sunny destination for this summer. Give me 4 ideas</blockquote><p><strong>GPT-3.5-turbo</strong> took 4.5 seconds, still the fastest and I consider that in this case where I ask for suggestions, I have a good answers. Description are a bit shorter but the ratio between time and the result is the most interesting.</p><blockquote>Sure! Here are some popular sunny destinations for the summer:</blockquote><blockquote>1. Bali, Indonesia — Known for its beautiful beaches, vibrant culture, and stunning scenery.</blockquote><blockquote>2. Mykonos, Greece — A popular destination for its picturesque beaches, charming villages, and lively nightlife.</blockquote><blockquote>3. Cancun, Mexico — Famous for its crystal-clear waters, white sandy beaches, and vibrant atmosphere.</blockquote><blockquote>4. Santorini, Greece — Renowned for its stunning sunsets, picturesque villages, and beautiful beaches.</blockquote><blockquote>I hope these suggestions help you find the perfect sunny destination for your summer vacation!</blockquote><p><strong>GPT-4-turbo-2024–04–09</strong> took 15 seconds, it’s a lot. longer introduction but is it needed ? and descriptions are a bit longer.</p><blockquote>Certainly! When choosing a sunny destination for the summer, it’s great to consider both the weather and the variety of activities available. Here are a few sunny destinations across different continents that you might enjoy:</blockquote><blockquote>1. Maui, Hawaii, USA — Known for its stunning beaches, scenic drives (like the Road to Hana), and volcanic landscapes. Maui offers a blend of relaxation and adventure with opportunities for snorkeling, hiking, and exploring local culture.</blockquote><blockquote>2. Santorini, Greece — Famous for its dramatic cliffs, white buildings with blue domes, and spectacular sunsets. Santorini is perfect for a romantic getaway with excellent vineyards, delicious cuisine, and beautiful beaches.</blockquote><blockquote>3. Barcelona, Spain — A vibrant city that combines history, art, and culture with a lively beach scene. Explore famous landmarks like the Sagrada Familia and Park Güell, or simply relax on the beach and enjoy the local tapas.</blockquote><blockquote>4. Bali, Indonesia — Offers a peaceful and scenic escape with lush landscapes, ancient temples, and vibrant cultural experiences. Enjoy surfing, yoga retreats, and exploring the rice terraces.</blockquote><blockquote>Each of these destinations offers a unique blend of sun, culture, and nature. Depending on your interests, any of these could be a great choice for a summer vacation.</blockquote><p><strong>GPT-4o</strong> took 11.5 seconds, is effective and provide a description for each destinations.</p><blockquote>Absolutely! Here are a few sunny destinations you might consider for your summer vacation:</blockquote><blockquote>1. Santorini, Greece: Known for its stunning sunsets, beautiful blue-domed buildings, and crystal-clear waters, Santorini is a fantastic summer destination.</blockquote><blockquote>2. Barcelona, Spain: With beautiful beaches, incredible architecture by Gaudí, and a vibrant city atmosphere, Barcelona offers a mix of relaxation and culture.</blockquote><blockquote>3. Amalfi Coast, Italy: Famous for its dramatic cliffs, colorful villages, and beautiful Mediterranean Sea views, the Amalfi Coast is perfect for a scenic and sunny getaway.</blockquote><blockquote>4. Maui, Hawaii, USA: Maui offers pristine beaches, lush rainforests, and plenty of opportunities for outdoor activities like snorkeling and hiking.</blockquote><blockquote>Remember to check travel advisories and local guidelines when planning your trip, as conditions can change. Enjoy your sunny summer getaway!</blockquote><h4>The last question — Mathematics problem</h4><blockquote>In my piggy bank, I have 50-cent coins and 20-cent coins. Altogether, I have 5 dollars. How many 50-cent coins do I have, knowing that I have 16 coins in total?</blockquote><p><strong>GPT-3.5-turbo</strong> took 4 seconds but failed. The results is not even close. In this simple</p><blockquote>Let x be the number of 50-cent coins and y be the number of 20-cent coins.</blockquote><blockquote>From the information given, we can set up two equations:</blockquote><blockquote>1) x + y = 16 (total number of coins)</blockquote><blockquote>2) 0.50x + 0.20y = 5 (total value of coins in dollars)</blockquote><blockquote>To solve these equations, we can multiply the first equation by 0.50 to get:</blockquote><blockquote>0.50x + 0.20x = 8</blockquote><blockquote>0.70x = 8</blockquote><blockquote>x = 11.43 (approx.)</blockquote><blockquote>Since the number of coins must be a whole number, we can see that x = 11 and y = 5.</blockquote><blockquote>Therefore, you have 11 50-cent coins and 5 20-cent coins in your piggy bank.</blockquote><p><strong>GPT-4o</strong> took 11.5 seconds and find the good result. I gives details step by step which is a good point</p><blockquote>To solve the problem, let’s use algebra to represent the number of each type of coin in your piggy bank. Let ( x ) be the number of 50-cent coins and ( y ) be the number of 20-cent coins.Given the following conditions:</blockquote><blockquote>1. The total value of the coins is $5.</blockquote><blockquote>2. The total number of coins is 16.</blockquote><blockquote>We can set up two equations based on these conditions:</blockquote><blockquote>1. The value equation:[ 0.50x + 0.20y = 5 ]</blockquote><blockquote>2. The coin count equation:[ x + y = 16 ]First, let’s simplify the value equation by getting rid of the decimals. Multiply through by 100 to get:[ 50x + 20y = 500 ]</blockquote><blockquote>Now, simplify by dividing everything by 10:</blockquote><blockquote>[ 5x + 2y = 50 ]</blockquote><blockquote>We now have the system of equations:</blockquote><blockquote>1. ( 5x + 2y = 50 )</blockquote><blockquote>2. ( x + y = 16 )</blockquote><blockquote>Let’s solve the second equation for ( y ):</blockquote><blockquote>[ y = 16 — x ]</blockquote><blockquote>Now, substitute this expression for ( y ) into the first equation:</blockquote><blockquote>[ 5x + 2(16 — x) = 50 ]</blockquote><blockquote>Distribute and combine like terms:</blockquote><blockquote>[ 5x + 32–2x = 50 ]</blockquote><blockquote>[ 3x + 32 = 50 ]</blockquote><blockquote>[ 3x = 18 ]</blockquote><blockquote>[ x = 6 ]</blockquote><blockquote>So, you have 6 pieces of 50-cent coins.</blockquote><blockquote>To find the number of 20-cent coins, substitute ( x = 6 ) back into the coin count equation ( x + y = 16):</blockquote><blockquote>[ 6 + y = 16 ]</blockquote><blockquote>[ y = 10 ]</blockquote><blockquote>So, you have 10 pieces of 20-cent coins.</blockquote><blockquote>In summary, you have 6 pieces of 50-cent coins and 10 pieces of 20-cent coins in your piggy bank.</blockquote><p><strong>GPT-4-turbo-2024–04–09</strong> gives a correct result too but took 23 seconds which is two times what 4o needed.</p><blockquote>Let’s designate the number of 50-cent coins as ( x ) and the number of 20-cent coins as ( y ). We know from the problem statement:</blockquote><blockquote>1. The total value of the coins equals 5 dollars.</blockquote><blockquote>2. The total number of coins equals 16.</blockquote><blockquote>We can express these conditions as equations:</blockquote><blockquote>**Equation 1 (Value Equation)**:</blockquote><blockquote>[ 0.50x + 0.20y = 5 ]</blockquote><blockquote>Equation 2 (Number of Coins Equation):</blockquote><blockquote>[ x + y = 16 ]</blockquote><blockquote>We can first solve Equation 2 for one of the variables. Let’s solve for ( y ):</blockquote><blockquote>[ y = 16 — x ]</blockquote><blockquote>Now we substitute this expression for ( y ) in Equation 1:</blockquote><blockquote>[ 0.50x + 0.20(16 — x) = 5 ]</blockquote><blockquote>[ 0.50x + 3.20–0.20x = 5 ]</blockquote><blockquote>[ 0.30x + 3.20 = 5 ]</blockquote><blockquote>Now, isolate ( x ):[ 0.30x = 5–3.20 ]</blockquote><blockquote>[ 0.30x = 1.80 ]</blockquote><blockquote>[ x = frac{1.80}{0.30} ][ x = 6 ]</blockquote><blockquote>Therefore, you have ( 6 ) 50-cent coins.</blockquote><blockquote>To double-check, find ( y ):</blockquote><blockquote>[ y = 16–6 = 10 ]</blockquote><blockquote>Verify the total amount:</blockquote><blockquote>[ 0.50 times 6 + 0.20 times 10 = 3 + 2 = 5 ]</blockquote><blockquote>The total value is indeed 5 dollars, confirming that there are 6 fifty-cent coins and 10 twenty-cent coins.</blockquote><h3>Conclusion</h3><p>GPT-3.5-turbo is fast but when it comes in solving purpose, it’s not that efficient. Use it for simple needs.</p><p>GPT-4-turbo-2024–04–09 is accurate, descriptive and provide more information but as a result, the execution time is quite long.</p><p>GPT-4o is balanced. Answers are corrects, a bit less descriptive than 4-turbo-2024–04–09 but the execution time is 2 times faster.</p><p>Depending on you needs, each one can fit. In my personal experience, when clients need a simple bot, 3.5 is enough and cheap. When the client expect a human and rich answers with no speed expectation, gpt-4-turbo-2024–04–09 is good. Otherwise, most of the time I consider gpt-4o is the most efficient due to the balance it provides : quality, speed and cost.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67b65bca1888" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement the ChatGPT stream effect in your NextJS14 app with server actions]]></title>
            <link>https://medium.com/@ramzi_bey/implement-the-chatgpt-stream-effect-in-your-nextjs14-app-with-server-actions-b1df5712cea0?source=rss-40a57dae91c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1df5712cea0</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Ramzi Bey]]></dc:creator>
            <pubDate>Wed, 05 Jun 2024 20:28:35 GMT</pubDate>
            <atom:updated>2024-06-05T20:28:35.632Z</atom:updated>
            <content:encoded><![CDATA[<p>Enhance user experience by incorporating a stream effect similar to ChatGPT in your NextJS14 application using Server Actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jrYuTDcrKjagV1QHKbG1dw.jpeg" /></figure><h3>Introduction</h3><p>This post is a continuation from my previous articles on creating an assistant bot utilizing the OpenAI API:</p><p><a href="https://medium.com/@ramzi_bey/build-your-own-ai-powered-chatbot-in-5-minutes-using-openais-api-and-next-js-e777291fff32">Build a chatbot in five minutes</a></p><p><a href="https://medium.com/@ramzi_bey/create-a-recommandation-assistant-with-openai-0284cee5f86b">Turn your bot into a recommandation assistant</a></p><p>If you haven’t had a chance to go through them, You can clone <a href="https://github.com/RamziBey/OpenAiSuggestionBot">this repository</a> and start with this article. We developed a sales assistant for mobile phones, providing users with advices.</p><p>What we will add hold particular significance for two key reasons:</p><ul><li>The stream effect adds a sense of dynamism to your software, delivering responses progressively to users, enhancing the perception of speed.</li><li>This implementation also heightens security measures. With the server action, API calls are made from a server-side component, ensuring that sensitive API keys remain hidden from the browser console.</li></ul><h3>Setup the project</h3><p>If you’ve been following along with my previous posts, you should already have the core foundation we’ll be building upon. Otherwise, you can clone <a href="https://github.com/RamziBey/OpenAiSuggestionBot">this repository</a> to get started.</p><p>Then we will add one package that will be mandatory for the stream</p><pre>npm install ai</pre><p>The documentation for that package: <a href="https://sdk.vercel.ai/docs">https://sdk.vercel.ai/docs</a></p><h3>Code our action function</h3><p>We first need to create a file “action.tsx” next to our page.tsx. We will add the imports and necessary interfaces and move the prompt from page.tsx here</p><pre>&#39;use server&#39;;<br> <br>import { experimental_StreamingReactResponse, Message } from &#39;ai&#39;;<br><br>interface RequestDataForAI {<br>    messages: Message[],<br>    model: string,<br>}<br><br>interface AIMessage {<br>    role: string,<br>    content: string<br>}<br><br>// The prompt that will manage the behavior of our bot<br>const prompt: AIMessage = {<br>    role: &quot;system&quot;,<br>    content: `You are a customer assistant and you try to suggest the best phone depending on your customer needs (price, battery, photo, operating system....). Here are your sources:<br>      - &lt;https://www.theverge.com/23879726/apple-iphone-15-plus-review&gt;<br>      - &lt;https://www.theverge.com/23879726/apple-iphone-15-plus-review&gt;<br>      - &lt;https://www.theverge.com/23352282/iphone-14-review-apple&gt;<br>      - &lt;https://www.theverge.com/24058916/samsung-galaxy-s24-plus-review-screen-battery-camera&gt;<br>      - &lt;https://www.theverge.com/24053907/samsung-galaxy-s24-ultra-review-ai-screen-camera-battery&gt;<br>      - &lt;https://www.theverge.com/24051466/honor-magic-v2-review&gt;<br>      - &lt;https://www.theverge.com/24047368/oneplus-12-review&gt;<br>      - &lt;https://www.theverge.com/23912370/google-pixel-8-pro-review-camera-assistant-magic-editor-best-take-audio-eraser&gt;<br>      - &lt;https://www.theverge.com/23826325/samsung-galaxy-z-fold-5-review-screen-hinge-battery-camera&gt;<br>      <br>      Try to note exceed 1000 characters on your replies<br>      If the customer asks you something about another topics than phones, reply that it&#39;s not your field and you can&#39;t help him`<br>}</pre><ul><li>Message import is an interface to structure messages handled by OpenAI</li><li>The experimental_StreamingReactResponse, to quote the doc : “Allows you to stream React component responses.”</li></ul><p>Now, we place our call to OpenAI in action.tsx. We set in the body “stream” to true to notify OpenAI that we want the streamed response and not the classic one.</p><pre>async function callToOpenAi(request: RequestDataForAI) {<br>    const messages = [prompt]<br>    const response = await fetch(&quot;&lt;https://api.openai.com/v1/chat/completions&gt;&quot;, {<br>        cache: &#39;no-cache&#39;,<br>        method: &quot;POST&quot;,<br>        headers: {<br>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br>          &quot;Authorization&quot;: `Bearer ${process.env.OPENAI_KEY}`<br>        },<br>        body: JSON.stringify({<br>            model: request.model,<br>            messages: messages.concat(request.messages),<br>            stream: true,<br>        }),<br>    });<br>    if (response.body != null) {<br>        let reader = response.body.getReader();<br>        return streamReader(reader); //Will be defined in the next step<br>    }<br>}</pre><p>The streamReader function processes streaming data using a ReadableStreamDefaultReader. It decodes chunks into text and continues reading and processing as data arrives.</p><pre>function parse(decodedChunk: string) {<br>    const lines = decodedChunk.split(&#39;\\n&#39;);<br>    const trimmedData = lines.map(line =&gt; line.replace(/^data: /, &quot;&quot;).trim());<br>    const filteredData = trimmedData.filter(line =&gt; ![&quot;&quot;, &quot;[DONE]&quot;].includes(line));<br>    const parsedData = filteredData.map(line =&gt; JSON.parse(line));<br>    <br>    return parsedData;<br>}<br><br>function streamReader(reader: ReadableStreamDefaultReader&lt;Uint8Array&gt;) {<br>    const textDecoder = new TextDecoder();<br>    let buffer = &#39;&#39;;<br>    return (new ReadableStream({<br>        start(controller) {<br>            function push() {<br>                reader.read().then(({ done, value }) =&gt; {<br>                    if (done) {<br>                        controller.close();<br>                        return;<br>                    }<br>                    const decodedChunk = textDecoder.decode(value);<br>                    buffer += decodedChunk;<br>                    const encoder = new TextEncoder();<br>                    try {<br>                        const cleaneddata = parse(buffer)<br>                        for (let line of cleaneddata) {<br>                            const { content } = line.choices[0].delta;<br>                            <br>                            if (content) {<br>                                const bufferEncoded = encoder.encode(content);<br>                                controller.enqueue(bufferEncoded);<br>                                buffer = &#39;&#39;<br>                            }<br>                        }<br>                    } catch {<br>                        push()<br>                        return<br>                    }<br>                    push();<br>                });<br>            }<br>            push()<br>        },<br>    }))<br>}</pre><p>We create a handler function that call callToOpenAi and read the returned streamReader progressively.</p><pre>export async function handler({ messages }: { messages: Message[] }) {<br>    let request: RequestDataForAI = {messages: [], model: &quot;gpt-4-1106-preview&quot;}<br>    request.messages = messages<br>    const response = await callToOpenAi(request)<br>    if (response != null) {<br>        return new experimental_StreamingReactResponse(response, {<br>            ui({ content }) {<br>            return (<br>                &lt;div className=&quot;p-4 bg-gray-100 text-slate-900 ml-2 rounded-md w-fit break-words&quot;&gt;<br>                    {content}<br>                &lt;/div&gt;<br>            );<br>            },<br>        });<br>    }<br>}</pre><p>We have completed work on the action file:</p><ul><li>It receives our conversation</li><li>It calls OpenAI to get a response</li><li>It then reads and parses the data, returning it chunk by chunk.</li></ul><p>Next step, call our action file. Let’s go to update our page.tsx</p><h3>Plug our client component to our action file</h3><p>We implement stream feature from the lib “ai” and we update our rendered code in a first time:</p><pre>import { useChat } from &quot;ai/react&quot;;<br>import { handler } from &quot;./action&quot;;<br><br>export const maxDuration = 160; //Important in case you deploy your project on Vercel to handle long call<br>export const runtime = &#39;edge&#39;;<br><br>export default function Home() {<br>  const [conversation, setConversation] = useState&lt;Array&lt;string&gt;&gt;([]);<br>  const [openAiLoading, setOpenAiLoading] = useState&lt;boolean&gt;(false);<br>  const [streamResponse, setStreamResponse] = useState(&quot;&quot;);<br>	<br>	const { messages, handleInputChange, handleSubmit } = useChat({<br>	    api: handler as any,<br>	    onError: (e) =&gt; {<br>	        console.error(e);<br>	    },<br>	    onFinish: () =&gt; {<br>	      setOpenAiLoading(false)<br>	    } <br>	});<br><br>  const classnames = [&quot;text-right flex justify-end mt-2&quot;, &quot;flex mt-2&quot;]<br>  const textClassNames = [<br>    &quot;p-4 bg-emerald-300 w-fit text-right text-slate-900 rounded-md break-words max-w-xs	&quot;,<br>    &quot;p-4 bg-rose-300 text-slate-900 rounded-md w-fit break-words max-w-xs	&quot;<br>  ]<br><br>  return (<br>    &lt;div id=&quot;global-container&quot; className=&quot;w-1/2 flex justify-center h-full flex-col m-auto py-4 gap-4&quot;&gt;<br>      &lt;div id=&quot;chat&quot; className=&quot;h-full bg-slate-100 p-4 rounded-sm overflow-scroll&quot;&gt;<br>        {<br>          conversation.map((elem, index) =&gt; {<br>            return (<br>              &lt;div key={index} className={classnames[index % classnames.length]}&gt;<br>                &lt;p className={textClassNames[index % textClassNames.length]}&gt;{elem}&lt;/p&gt;<br>              &lt;/div&gt;<br>            )<br>          })<br>        }<br>      &lt;/div&gt;<br>      &lt;div id=&quot;input&quot; className=&quot;w-full h-fit&quot;&gt;<br>        &lt;form name=&quot;questionForm&quot; onSubmit={(e) =&gt; {<br>          submitData(e)<br>        }}&gt;<br>          &lt;div&gt;<br>            &lt;input type=&quot;text&quot; className=&quot;w-full text-slate-900 bg-slate-100 p-2&quot; name=&quot;user input&quot; id=&quot;user-input&quot; placeholder=&quot;Type your text here&quot; onChange={handleInputChange}/&gt;<br>            &lt;div className=&quot;grid grid-cols-2 gap-2 mt-2&quot;&gt;<br>              { openAiLoading &amp;&amp; &lt;button className=&#39;w-full bg-emerald-800 rounded-sm&#39;&gt;&lt;ChatTypingAnimation /&gt;&lt;/button&gt;}<br>              { !openAiLoading &amp;&amp; &lt;button className=&quot;w-full bg-emerald-800 rounded-sm&quot;&gt;Send&lt;/button&gt;}<br>              &lt;button className=&quot;w-full bg-rose-800 rounded-sm&quot; type=&quot;button&quot; onClick={handleDeleteAction}&gt;Clear&lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/form&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Here lies the core of the component, with the additional functions to be added below. I’d like to highlight the primary feature of the AI library we’re using: the useChat function returns a “UseChatHelpers” object, which includes various functions and variables:</p><ul><li>“messages” is an array of the interface Message mentioned earlier and setMessages its setter. We will send the “messages” to OpenAI. It’s basically the conversation we have.</li><li>handleInputChange is set on the input event onChange. It will store what the user is typing.</li><li>handleSubmit will trigger the handler we created earlier in action.tsx</li></ul><p>Next, let’s add our functions:</p><pre>// The &#39;messages&#39; variable is updated to receive chunks. We use a useEffect hook to observe the arrival of new chunks.<br>  useEffect(() =&gt; {<br>    observeMessage()<br>  }, [messages]);<br><br>// Store the input in our conversation then submit our message<br>  function submitData(e: React.FormEvent&lt;HTMLFormElement&gt;) {<br>    e.preventDefault();<br>    const messageInput = (document.getElementById(&#39;user-input&#39;) as HTMLTextAreaElement).value;<br>    (document.getElementById(&#39;user-input&#39;) as HTMLTextAreaElement).value = &quot;&quot;;<br>    setOpenAiLoading(true)<br>    setConversation(prevConversation =&gt; [...prevConversation, messageInput]);<br>    handleSubmit(e);<br>  }<br><br>  // Clear the conversation to start a new one<br>  function handleDeleteAction() {<br>    setConversation([])<br>    setMessages([])<br>  }<br>  <br>  // reads the chunks and save them. The conversation is updated for each chunk so it will appear progressively on your window<br>  function observeMessage() {<br>    if (openAiLoading) {<br>        if (messages.length % 2 == 0 &amp;&amp; conversation.length % 2 != 0) {<br>            conversation.push(&#39;&#39;)<br>        } else {<br>            if (messages.length % 2 == 0)<br>                if (messages[messages.length - 1].content != streamResponse) {<br>                    conversation[conversation.length - 1] = messages[messages.length - 1].content<br>                    setStreamResponse(messages[messages.length - 1].content)<br>                }<br>        }<br>        <br>        return true<br>    }<br>    return false<br>}</pre><p>Here we go, you now have a powerful and dynamic chat system !</p><p>Our client components read the input dynamically, call the server action and observe the update in the “messages” variable provided by useChat. Although Next.Js14 doesn’t handle stream well, with this guide you can reproduce the dynamic behavior as you have on chatGPT</p><h3>Conclusion</h3><p>This article conclude a triptych with my 2 last articles. If you followed them, you are able to build user friendly services using AI. Chat is just one usage but with the knowledge you have of OpenAI, you can imagine tools integrated in bigger products. Let me know if it has be useful and what usage you made of those articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1df5712cea0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a recommandation assistant with OpenAi]]></title>
            <link>https://medium.com/@ramzi_bey/create-a-recommandation-assistant-with-openai-0284cee5f86b?source=rss-40a57dae91c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0284cee5f86b</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ramzi Bey]]></dc:creator>
            <pubDate>Wed, 22 May 2024 13:32:06 GMT</pubDate>
            <atom:updated>2024-05-22T13:32:06.193Z</atom:updated>
            <content:encoded><![CDATA[<p>Hands-on guide to use OpenAI’s prompt system to build an assistant bot for choosing a mobile phone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dBIIkaYTl3ISMy2oZcKqA.jpeg" /></figure><h3>Introduction</h3><p>This post follows a <a href="https://medium.com/@ramzi_bey/build-your-own-ai-powered-chatbot-in-5-minutes-using-openais-api-and-next-js-e777291fff32">previous one</a> where we introduced the fundamentals of OpenAI and concluded with creating a functional chatbot with general knowledge. Resources are provided below so you can catch up and start here.</p><p>In the previous post, we built a simple chat using OpenAI. While the AI has broad general knowledge, you might want to create bot for dedicated task. For instance, if you’re a student who takes notes online, you may want to generate custom exams to prepare your upcoming exams. In our case, we will give some sources to make our AI able to make suggestions on which mobile you should buy.</p><h3>Quick start</h3><p>If you followed my previous post, you already have the codebase i’ll use for this project. Otherwise, you can clone the <a href="https://github.com/RamziBey/OpenAiChat">repository</a></p><p>You must have you own API key that you will place in your .env file.</p><h3>Prompt system</h3><p>If you manipulated a bit the code, you may have noticed that an OpenAI conversation is built as follow:</p><pre>[<br> {<br>  &quot;role&quot;: &quot;user&quot;,<br>  &quot;content&quot;: &quot;Hello !&quot;<br> },<br> {<br>  &quot;role&quot;: &quot;assistant&quot;,<br>  &quot;content&quot;: &quot;Hello ! How can I help you today ?&quot;<br> }<br>// And so on<br>]</pre><p>Role represent who is talking.</p><p>“user” represents you.</p><p>“assistant” represents OpenAI.</p><p>There is a third role named “system”. It represents the AI’s behavior. The tone of voice or any other rules you want the assistant to respect.</p><p>We will place the prompt at the beginning of the conversation for each request to have an assistant that will follow rules we will define.</p><p>As I said in the introduction, I want my assistant to speak about mobile phone and nothing else. Let’s implement that !</p><h3>Create a simple prompt and feed him with knowledge</h3><p>To make a basic example, we will hardcode the prompt in the page.tsx. In a real project, the data must be saved and get from a database. Let’s add to page.tsx this basic prompt.</p><pre>const prompt: Message = {<br>    role: &quot;system&quot;,<br>    content: `You are a customer assistant and you try to suggest the best phone depending on your customer needs (price, battery, photo, operating system....). Here are your sources:<br>      - https://www.theverge.com/23879726/apple-iphone-15-plus-review<br>      - https://www.theverge.com/23352282/iphone-14-review-apple<br>      - https://www.theverge.com/24058916/samsung-galaxy-s24-plus-review-screen-battery-camera<br>      - https://www.theverge.com/24053907/samsung-galaxy-s24-ultra-review-ai-screen-camera-battery<br>      - https://www.theverge.com/24051466/honor-magic-v2-review<br>      - https://www.theverge.com/24047368/oneplus-12-review<br>      - https://www.theverge.com/23912370/google-pixel-8-pro-review-camera-assistant-magic-editor-best-take-audio-eraser<br>      - https://www.theverge.com/23826325/samsung-galaxy-z-fold-5-review-screen-hinge-battery-camera<br>      <br>      Try to not exceed 1000 characters on your replies<br>      If the customer asks you something about another topic than phones, reply that it&#39;s not your field and you can&#39;t help him`<br>  }</pre><p>Here, our assistant will have in his knowledge a list of 8 smartphones with details on their specification from TheVerge.</p><p>I defined a length limit to avoid long replies from my assistant and I also ask him to avoid speaking about other topics.</p><p>Next step, let’s update the functions callToOpenAI().</p><pre>async function callToOpenAI() {<br>    const request = [prompt] // Store the prompt in a local variable<br>    try {<br>      const response = await fetch(&quot;https://api.openai.com/v1/chat/completions&quot;, {<br>        cache: &#39;no-cache&#39;,<br>        method: &quot;POST&quot;,<br>        headers: {<br>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br>          &quot;Authorization&quot;: `Bearer ${process.env.NEXT_PUBLIC_OPENAI_KEY}`<br>        },<br>        body: JSON.stringify({<br>            model: &#39;gpt-4-1106-preview&#39;,<br>            messages: request.concat(messages) // Concatenate the conversation to the prompt<br>        }),<br>      });<br>      const openAiResponse = await response.json()<br>      setConversation(prevConversation =&gt; [...prevConversation, openAiResponse.choices[0].message.content]);<br>      setMessages(prevConversation =&gt; [...prevConversation, {role: openAiResponse.choices[0].message.role, content: openAiResponse.choices[0].message.content}]);<br>    } catch (error) {<br>      console.log(error);<br>    } finally {<br>      setOpenAiLoading(false)<br>    } <br>  }</pre><p>Updated lines are the ones with comments. We concatenate the conversation to the prompt so it will always be the first message of the conversation. AI will take in consideration sources provided and follow the guidelines defined in the prompt.</p><p>Here the output from a short conversation I had with the bot. You can notice he folows perfectly the guidelines from the prompt and use the sources to build a good answer.</p><blockquote><strong>User:</strong> Tell me the size of New Orleans</blockquote><blockquote><strong>Assistant:</strong> I’m sorry, that’s not within my field of expertise. I specialize in helping customers with phone recommendations. If you have any questions about smartphones, I’d be glad to assist you!</blockquote><blockquote><strong>User: </strong>Is the Iphone 14 a good smartphone compared to the OnePlus 12</blockquote><blockquote><strong>Assistant: </strong>The iPhone 14 and OnePlus 12 are both competitive smartphones, each excelling in different areas. The iPhone 14 benefits from Apple’s ecosystem, offering a harmonious user experience, timely updates, and long-term support. It has a strong camera system and excellent build quality, plus ….</blockquote><h3>Conclusion</h3><p>Now, you know how to define rules and give knowledge to your AI. You can create AI for any use case: A teacher, an assistant, a reviewer…</p><p>Customize the prompt and the sources to make your AI personalized and fitted to your needs. You can build a dynamic sources fetching system with embedding and Pgvector (I’m maybe spoiling a future story here)</p><p>Feel free to clone my <a href="https://github.com/RamziBey/OpenAiSuggestionBot">repository</a> if it’s needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0284cee5f86b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own AI-Powered Chatbot in 5 Minutes Using OpenAI’s API and Next.js]]></title>
            <link>https://medium.com/@ramzi_bey/build-your-own-ai-powered-chatbot-in-5-minutes-using-openais-api-and-next-js-e777291fff32?source=rss-40a57dae91c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e777291fff32</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[openai-api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Ramzi Bey]]></dc:creator>
            <pubDate>Sat, 04 May 2024 22:19:29 GMT</pubDate>
            <atom:updated>2024-05-04T22:19:29.511Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn the fundamentals of the OpenAI API and create an intelligent chatbot in just five minutes.</p><h3>Introduction</h3><p>ChatGPT is a real game changer that you may already be using in your daily life. You may already know, ChatGPT is a showcase product built on top of the OpenAI API. Understanding OpenAI and how to use it can help you incorporate new features into your projects.</p><p>The purpose of this guide is to build a simple chatbot in Next.Js14 to help you understand the basics of OpenAI API. For simplicity reason, I won’t focus on safety, <strong>your API key will be visible in the console</strong> so keep this guide for personal usage for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6BzF4lZksBH7adXF1mmzGw.jpeg" /></figure><h3>Setup a new Next.js Project</h3><p>In our project, we will use Next.js14 with typescript, EsLint, Tailwind and the app router</p><pre>$&gt; npx create-next-app@latest<br>typescript: yes<br>Eslint: yes<br>Tailwind: yes<br>src: no<br>App router: yes<br>customize import: no<br><br>$&gt; npm run dev<br>// Your server will now be running</pre><h3>A simple interface</h3><p>Before going into the core purpose of the project, we need a user interface. First, remove the initial Next.js code in the page.tsx file.</p><p>A basic user interface is provided for this post . You can clone it from the “<a href="https://github.com/RamziBey/OpenAiChat">FrontStructure</a>” branch.</p><p>The interface includes a window to display user inputs and AI responses. Beneath this window, there&#39;s a simple form with a text input field, a submit button, and a clear button to reset the conversation.</p><pre>&#39;use client&#39;<br><br>import { useState } from &quot;react&quot;<br><br>export default function Home() {<br>  const [conversation, setConversation] = useState&lt;Array&lt;string&gt;&gt;([&quot;Message 1&quot;, &quot;Message 2&quot;, &quot;Message 3&quot;, &quot;Message 4&quot;, &quot;Message 5&quot;, &quot;Message 6&quot;, <br>  &quot;Message 7 longer than the others. It&#39;s mong enough to span on multiple lines&quot;, &quot;Message 8&quot;, &quot;Message 9&quot;, &quot;Message 10&quot;, &quot;Message 11&quot;, &quot;Message 12&quot;]);<br><br>  const classnames = [&quot;text-right flex justify-end mt-2&quot;, &quot;flex mt-2&quot;]<br>  const textClassNames = [<br>    &quot;p-4 bg-emerald-300 w-fit text-right text-slate-900 rounded-md break-words max-w-xs &quot;,<br>    &quot;p-4 bg-rose-300 text-slate-900 rounded-md w-fit break-words max-w-xs &quot;<br>]<br>  return (<br>    &lt;div id=&quot;global-container&quot; className=&quot;w-1/2 flex justify-center h-full flex-col m-auto py-4 gap-4&quot;&gt;<br>      &lt;div id=&quot;chat&quot; className=&quot;h-full bg-slate-100 p-4 rounded-sm overflow-scroll&quot;&gt;<br>        {<br>          conversation.map((elem, index) =&gt; {<br>            return (<br>              &lt;div key={index} className={classnames[index % classnames.length]}&gt;<br>                &lt;p className={textClassNames[index % textClassNames.length]}&gt;{elem}&lt;/p&gt;<br>              &lt;/div&gt;<br>            )<br>          })<br>        }<br>      &lt;/div&gt;<br><br>      &lt;div id=&quot;input&quot; className=&quot;w-full h-fit&quot;&gt;<br>        &lt;form action=&quot;&quot;&gt;<br>          &lt;div&gt;<br>            &lt;input type=&quot;text&quot; className=&quot;w-full text-slate-900 bg-slate-100 p-2&quot; name=&quot;user input&quot; id=&quot;user-input&quot; placeholder=&quot;Type your text here&quot; /&gt;<br>            &lt;div className=&quot;grid grid-cols-2 gap-2 mt-2&quot;&gt;<br>              &lt;button className=&quot;w-full bg-emerald-800 rounded-sm&quot;&gt;Send&lt;/button&gt;<br>              &lt;button className=&quot;w-full bg-rose-800 rounded-sm&quot;&gt;Clear&lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/form&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>If everything works well, you must have an interface with hardcoded message. Now let’s go into the most interesting part.</p><h3>Adding the OpenAI features</h3><p>You can remove the hardcoded conversation in the useState <em>Conversation.</em> Now, we will set dynamic data.</p><h4>1. Add new data handling functions</h4><p>We first add two hooks useState and an interface.</p><pre>interface Message {<br>  role: string,<br>  content: string<br>}<br><br>export default function Home() {<br>  const [openAiLoading, setOpenAiLoading] = useState&lt;boolean&gt;(false);<br>  const [messages, setMessages] = useState&lt;Array&lt;Message&gt;&gt;([]);<br><br>  // Rest of the code<br>}</pre><p>The interface Message is how OpenAI api expect to receive messages. An array of object with the variable “<em>content</em>” which represent the message and the “<em>role</em>” to define who is speaking. Keep in mind two roles for now:</p><ul><li>“user”: It will be what the user type in the input.</li><li>“assistant”: The responses you’ll receive from the AI.</li></ul><p>The hook setOpenAiLoading will be used to know when to send the request and when the request is completed.</p><p>Then we implement functions to submit a message and clear the conversation</p><pre>function submitData(e: React.FormEvent&lt;HTMLFormElement&gt;) {<br>    e.preventDefault()<br>    const messageInput = (document.getElementById(&quot;user-input&quot;) as HTMLTextAreaElement).value;<br>    (document.getElementById(&quot;user-input&quot;) as HTMLTextAreaElement).value = &quot;&quot;;<br>    setConversation(prevConversation =&gt; [...prevConversation, messageInput]);<br>    setMessages(prevConversation =&gt; [...prevConversation, {role: &quot;user&quot;, content: messageInput}]);<br>    setOpenAiLoading(true)<br>  }</pre><pre>function handleDeleteAction() {<br>    setConversation([])<br>    setMessages([])<br>  }</pre><ul><li>The function submitData read the value typed by the user and save with the hook setConversation and setMessages. It call also setOpenAiLoading and set its value to true. This will allow us to call OpenAI later.</li><li>The function handleDeleteAction is simple. Set our hooks as empty array to clean and start a new conversation</li></ul><h4>2. Update our form to use those newly added functions</h4><p>Update your form and your buttons as follow:</p><pre>&lt;form name=&quot;questionForm&quot; onSubmit={(e) =&gt; {<br>          submitData(e)<br>        }}&gt;<br><br>  &lt; !-- Keep the rest of HTML from the previous step -- &gt; <br><br>  { openAiLoading &amp;&amp; &lt;button className=&quot;w-full bg-gray-300 rounded-sm cursor-default&quot; type=&quot;button&quot;&gt;Wait...&lt;/button&gt;}<br>  { !openAiLoading &amp;&amp; &lt;button className=&quot;w-full bg-emerald-800 rounded-sm&quot;&gt;Send&lt;/button&gt;}<br>  &lt;button className=&quot;w-full bg-rose-800 rounded-sm&quot; type=&quot;button&quot; onClick={handleDeleteAction}&gt;Clear&lt;/button&gt;<br>&lt;/form&gt;</pre><p>The gray button added here shows the user that the call is made and we are waiting for a response.</p><h4>3. Call to OpenAI</h4><p>OpenAI route for conversation is <a href="https://api.openai.com/v1/chat/completions">https://api.openai.com/v1/chat/completions</a>. It requires your API key, the model you want to use (GPT-3.5, 4 …) and a list of messages which is your conversation.</p><p>Now let’s code this part. Into page.tsx add those:</p><pre>interface Message {<br>  role: string,<br>  content: string<br>}<br><br>export default function Home() {<br>  const [messages, setMessages] = useState&lt;Array&lt;Message&gt;&gt;([]);<br>  const [openAiLoading, setOpenAiLoading] = useState&lt;boolean&gt;(false);<br>  const [conversation, setConversation] = useState&lt;Array&lt;string&gt;&gt;([]);<br>  // code from the previous step with useState, classnames....<br><br>  useEffect(() =&gt; {<br>    if (openAiLoading)<br>      callToOpenAI();<br>  }, [openAiLoading]);<br><br>  async function callToOpenAI() {<br>    try {<br>      const response = await fetch(&quot;https://api.openai.com/v1/chat/completions&quot;, {<br>        cache: &quot;no-cache&quot;,<br>        method: &quot;POST&quot;,<br>        headers: {<br>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br>          &quot;Authorization&quot;: `Bearer ${process.env.NEXT_PUBLIC_OPENAI_KEY}`<br>        },<br>        body: JSON.stringify({<br>            model: &quot;gpt-4-1106-preview&quot;,<br>            messages: messages,<br>        }),<br>      });<br>      const openAiResponse = await response.json()<br>      setConversation(prevConversation =&gt; [...prevConversation, openAiResponse.choices[0].message.content]);<br>      setMessages(prevConversation =&gt; [...prevConversation, {role: openAiResponse.choices[0].message.role, content: openAiResponse.choices[0].message.content}]);<br>    } catch (error) {<br>      console.log(error);<br>    } finally {<br>      setOpenAiLoading(false)<br>    } <br>  }<br><br>  // The HTML rendered from the previous <br>}</pre><p>What are we doing here ?</p><ul><li>The hook <em>useEffect</em> will be trigger when the openAiLoading is updated. We use it to trigger the function <em>callToOpenAI</em>.</li><li><em>callToOpenAI</em> is clear, with the fetch function, we are asking OpenAI an answer to the provided <em>messages</em>.</li></ul><p>When we will read and set the response in the conversation, the component will re-render the conversation and the answer will be displayed !</p><p>And it’s already over ! When the form is submitted, the value will be saved, the hook will call the api function, the response will be save so our page will be re-rendered!</p><h3>Conclusion</h3><p>Now you saw that creating a simple conversation bot is simple. It’s the first step for big project you could start ! You could create a bot for a specific purpose, to make suggestion, to help you in your daily life, to learn language … possibilities are countless.</p><p>In my next posts i’ll explore more what can be done and some additional feature. As I said in the introduction, keep in mind that in this example, you key is visible in the browser console.</p><p>Feel free to use <a href="https://github.com/RamziBey/OpenAiChat">my repository</a> as you desire</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e777291fff32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[About me — Ramzi Bey]]></title>
            <link>https://medium.com/@ramzi_bey/about-me-ramzi-bey-74bf15d8600a?source=rss-40a57dae91c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/74bf15d8600a</guid>
            <category><![CDATA[about-me]]></category>
            <dc:creator><![CDATA[Ramzi Bey]]></dc:creator>
            <pubDate>Sat, 30 Mar 2024 15:03:37 GMT</pubDate>
            <atom:updated>2024-03-30T15:03:37.830Z</atom:updated>
            <content:encoded><![CDATA[<h3>About me — Ramzi Bey</h3><h4>A developer, assisted by Medium, who seeks to return the favor</h4><h3>Quick presentation</h3><p>I’m a software developer based in Andalusia passionate about technologies (Of course), sports, travelling and discovering cultures. I’ve dedicated myself to learning two additional languages besides my native tongue, and I’m currently studying a fourth — Arabic. Thanks to my profession, I have the freedom to live wherever I desire leading me to reside in four different countries across three continents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uyb1JqT7GXwK28Fk-NaqAQ.jpeg" /></figure><h3>Professional background</h3><p>I graduated with a Master degree in IT from a school in France and obtained a Diploma of Technology Challenges in the Financial Industry during an exchange year in United States. I’ve worked for large corporations, startups and I’ve been a teaching assistant (An experience I loved). Currently, I’m the CTO of a company I co-founded with my former employer.</p><p>From my desire to share knowledge, reminiscent of my days as a teaching assistant, to the challenges and innovations I encounter daily as a CTO, I’m constantly surrounded by exciting challenges and cutting-edge technologies. These are the very reasons that have led me to Medium today.</p><h3>How I arrived on Medium</h3><p>I’ve been a long-time reader of Medium as a visitor, particularly for work, as the community provides a lot of useful publications about programming. I’ve always appreciated the platform’s concept, and for months now, I’ve been thinking, ‘Why am I not contributing as well?’.</p><p>Despite working with computers, I remain faithful to my pen and notebook. While i’m working, I jot down observations, challenges, experiments, failures, and successes. This practice keeps my thoughts organized and allows me to share my experiences with my team.</p><p>In January, I was working on a tough feature for my company. After weeks of failures, I stumbled upon THE medium article from <a href="https://medium.com/u/6dd832f46def">Jack Herrington</a> that , after some updates, guided me towards the solution. I thought “Perhaps what I’ve added to that article could benefit other developers, I must share it” and here I am.</p><h3>My personal goals</h3><p>I’m diving into Medium as an experiment for several reasons:</p><ol><li>I aim to connect with a network of individuals who share similar interests.</li><li>It serves as an incentive to read more blog posts across various topics.</li><li>I’m also keen on honing my writing skills.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74bf15d8600a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>