<?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 Ralf Elfving on Medium]]></title>
        <description><![CDATA[Stories by Ralf Elfving on Medium]]></description>
        <link>https://medium.com/@ralfelfving?source=rss-6f93c520c891------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jDs6acbH68MOA1iDbwJvJA.jpeg</url>
            <title>Stories by Ralf Elfving on Medium</title>
            <link>https://medium.com/@ralfelfving?source=rss-6f93c520c891------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:51:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ralfelfving/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[Make Gemini Vision API calls with videos and images (NodeJS tutorial)]]></title>
            <link>https://medium.com/@ralfelfving/make-gemini-vision-api-calls-with-videos-and-images-nodejs-tutorial-b9e8753dbb1a?source=rss-6f93c520c891------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9e8753dbb1a</guid>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ralf Elfving]]></dc:creator>
            <pubDate>Thu, 14 Dec 2023 18:47:06 GMT</pubDate>
            <atom:updated>2023-12-14T18:47:06.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sPJzWbl2-4xBNh8-4wOD5g.jpeg" /></figure><p>Google’s long-awaited OpenAI GPT competitor, the Gemini API, was released yesterday. Gemini and Gemini Vision unlocks multimodality, but unlike OpenAI’s models Gemini supports VIDEOS. Yes, that’s right, you can ask Gemini Vision to analyze a video by simply sending it in the API.</p><p>In my latest tutorial I’ll teach you how to get from zero to your first Gemini Vision API call with videos and images in just a few minutes. You can check it out below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fy2MNU8SCiKQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dy2MNU8SCiKQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fy2MNU8SCiKQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8876a59b2c7eef1284ff6a0799b378d3/href">https://medium.com/media/8876a59b2c7eef1284ff6a0799b378d3/href</a></iframe><p>The tutorial is using a <a href="https://ralfs.gadget.app/gemini-vision-repo">GitHub repo</a> that has all the code and resources to make the learning process easy, and help set you up to take the next steps more quickly.</p><p>Hope you enjoy it. I hope to produce a few more Gemini tutorials in the next few weeks, so make sure to subscribe to my <a href="https://www.youtube.com/@ralfelfving">YouTube channel</a> to know when they drop.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9e8753dbb1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get your own macOS AI copilot — using OpenAI Vision, Whisper and TTS]]></title>
            <link>https://medium.com/@ralfelfving/get-your-own-macos-ai-copilot-using-openai-vision-whisper-and-tts-6674370e76ee?source=rss-6f93c520c891------2</link>
            <guid isPermaLink="false">https://medium.com/p/6674370e76ee</guid>
            <category><![CDATA[ai-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Ralf Elfving]]></dc:creator>
            <pubDate>Mon, 11 Dec 2023 21:44:44 GMT</pubDate>
            <atom:updated>2023-12-12T14:49:10.767Z</atom:updated>
            <content:encoded><![CDATA[<h3>Get your own macOS AI copilot — using OpenAI Vision, Whisper and TTS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pqb8BeDOkEdxNtMie6gmcQ.jpeg" /></figure><p>Ever had a question about the application you’re in, like “How do I do XYZ here?” What do you do? Take a screenshot, copy/paste content, open up ChatGPT and write your question? What if there was an easier way?</p><p>There is. You can just press a keyboard shortcut and speak your question to get the answer within seconds, without leaving the application. That’s what I built with <a href="https://ralfs.gadget.app/macos-copilot">this macOS copilot</a>, powered by OpenAI Vision, Whisper and TTS.</p><p>In the tutorial I’ll show you how it works, how to set it up in a few minutes, and explain the code behind it in case you want to tweak the experience.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1IdCWqTZLyA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1IdCWqTZLyA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1IdCWqTZLyA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/748818e3b6c6a5e6a9c1146199e06fdf/href">https://medium.com/media/748818e3b6c6a5e6a9c1146199e06fdf/href</a></iframe><p>To get started simply head over to the <a href="https://ralfs.gadget.app/macos-copilot">macOS copilot GitHub repo</a> and follow the instructions in the repo, or in the video.</p><p>If you just want to see a quick demo, there’s one at 00:30 in the tutorial or check this example I posted on Twitter.</p><h3>Ralf Elfving on Twitter: &quot;Time to get uncomfortable. I published my first ever public GH repo, open-sourcing the macOS AI assistant I built. It will answer questions about any application, activated with a keyboard shortcut. Here&#39;s a quick demo, link to the repo in the comments. pic.twitter.com/iENe0AFdlg / Twitter&quot;</h3><p>Time to get uncomfortable. I published my first ever public GH repo, open-sourcing the macOS AI assistant I built. It will answer questions about any application, activated with a keyboard shortcut. Here&#39;s a quick demo, link to the repo in the comments. pic.twitter.com/iENe0AFdlg</p><p>I use this application every single day to help me remember commands, navigate the menus of various , or navigating the process of setting something up. I sincerely hope it will be useful for you too, and would love to hear your feedback. Drop me a line in the YouTube video, here, or on <a href="https://twitter.com/ralfelfving">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6674370e76ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenAI JSON response format explained with example: Dynamically render a quiz app]]></title>
            <link>https://medium.com/@ralfelfving/openai-json-response-format-explained-with-example-dynamically-render-a-quiz-app-2050d1e719b0?source=rss-6f93c520c891------2</link>
            <guid isPermaLink="false">https://medium.com/p/2050d1e719b0</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[openai-api]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Ralf Elfving]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 15:52:47 GMT</pubDate>
            <atom:updated>2024-01-07T15:49:33.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zAkAsAjEC5Id7jpxvPEizA.jpeg" /></figure><p>In my most recent YouTube video I’m explaining how the OpenAI JSON response format works, and how you can use it to dynamically render web pages.</p><p>The tutorial video below will break it down in a few simple steps, and show you a practical example. You can fork a AI quiz app and have it up and running in under a minute (seriously). Just add in your OpenAI API key, and you’re done.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FP_ntSPbjuwE&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DP_ntSPbjuwE&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=google" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/84a5e78911d7ac9940a4aa72fb238047/href">https://medium.com/media/84a5e78911d7ac9940a4aa72fb238047/href</a></iframe><p>If you’re just looking for an example of what the JSON response format configuration looks like, here’s the code I use for my quiz.</p><pre>// Taken from getQuiz.js serverless function in my Gadget app backend<br><br>let responseText;<br>const completion = await openai.chat.completions.create({<br>      model: &quot;gpt-3.5-turbo-1106&quot;,<br>      response_format: { type: &quot;json_object&quot; },<br>      messages: [<br>        {<br>          role: &quot;system&quot;,<br>          content:<br>            `You are a helpful assistant that generate quiz questions based on a topic. Respond with one short question and three plausible options/answers, of which only one is correct. Provide your answer in JSON structure like this {&quot;topic&quot;: &quot;&lt;The topic of the quiz&gt;&quot;, &quot;question&quot;: &quot;&lt;The quiz question you generate&gt;&quot;, &quot;options&quot;: {&quot;option1&quot;: {&quot;body&quot;: &quot;&lt;Plausible option 1&gt;&quot;, &quot;isItCorrect&quot;: &lt;true or false&gt;}, &quot;option2&quot;: {&quot;body&quot;: &quot;&lt;Plausible option 2&gt;&quot;, &quot;isItCorrect&quot;: &lt;true or false&gt;}, &quot;option3&quot;: {&quot;body&quot;: &quot;&lt;Plausible option 3&gt;&quot;, &quot;isItCorrect&quot;: &lt;true or false&gt;}}}`,<br>        },<br>        {<br>          role: &quot;user&quot;,<br>          content:<br>            &quot;Provide a questions with three possible answers about: The Premier League&quot;,<br>        },<br>        {<br>          role: &quot;assistant&quot;,<br>          content:<br>            &#39;{&quot;topic&quot;: &quot;Premier League location&quot;, &quot;question&quot;: &quot;Where is the Premier League played?&quot;,  &quot;options&quot;: {&quot;option1&quot;: {&quot;body&quot;: &quot;France&quot;, &quot;isItCorrect&quot;: false}, &quot;option2&quot;: {&quot;body&quot;: &quot;England&quot;, &quot;isItCorrect&quot;: true}, &quot;option3&quot;: {&quot;body&quot;: &quot;Sweden&quot;, &quot;isItCorrect&quot;: false}}}&#39;,<br>        },<br>        {<br>          role: &quot;user&quot;,<br>          content: `Provide a question with three possible answers about: ${userQuestion}`,<br>        },<br>      ],<br>    });<br><br>    responseText = completion.choices[0].message.content;<br><br>    console.log(responseText); // Log the response to the logs</pre><p>Set the response_format to {type: &quot;json_object&quot;} and include the word JSON in the system prompt. If you need a consistent JSON structure, provide the desired schema in the system prompt and consider adding a user/assistant example like I have above.</p><p>For those who are interested, head over to my <a href="https://www.youtube.com/watch?v=P_ntSPbjuwE">YouTube channel to watch the full tutorial</a> or click the video link above.</p><p>See you in the video!</p><p><strong>Find this article useful?</strong> I’ve published many other OpenAI and coding tutorials on my <a href="https://medium.com/@ralfelfving">Medium account</a> and on my <a href="https://www.youtube.com/@ralfelfving">YouTube channel</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2050d1e719b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn function calls in OpenAI Assistants API]]></title>
            <link>https://medium.com/@ralfelfving/learn-function-calls-in-openai-assistants-api-519ecc7596ce?source=rss-6f93c520c891------2</link>
            <guid isPermaLink="false">https://medium.com/p/519ecc7596ce</guid>
            <category><![CDATA[assistants-api]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[ai-development]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Ralf Elfving]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 15:39:38 GMT</pubDate>
            <atom:updated>2023-11-28T15:39:38.089Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*epTVP7oihqObLu3eb2rQxA.jpeg" /></figure><p>OpenAI Assistants come with three tools in their belt; code interpreter, knowledge retrieval, and function calls. And although the former two are so far the most used tools, in part because they’re easy to get started with, function calls is an untapped power we’re likely to see grow in popularity as people learn how to implement. And in this tutorial, you’ll learn how to master them within a few minutes using the video and code below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2pKNOHzEQ4Y&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2pKNOHzEQ4Y&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=google" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7f686127e81759a2cb0343d7254fb1e/href">https://medium.com/media/b7f686127e81759a2cb0343d7254fb1e/href</a></iframe><p>Function calls is essentially Assistant’s calling APIs, allowing it to perform specialized tasks beyond its core capability. It means you can give assistants very specific and powerful capabilities, that return very precise and expected results.</p><p>In this tutorial we’ll build a function that returns information about a specific country, but it can be changed to essentially any functionality you wish. Let’s dive in!</p><h3>Resources</h3><p>Before you start, you need these things set up on your</p><ul><li><a href="https://nodejs.org/en/download/current">NodeJS*</a></li><li>OpenAI npm (yarn add openai)</li><li>Readline npm (yarn add readline)</li><li>fs npm (yarn add fs)</li><li>dotenv npm (yarn add dotenv)</li><li>Axios npm (yarn add axios)</li><li>An OpenAPI key</li></ul><h3>Start coding</h3><p>First, create a folder where you want to store the project. Open up the folder in your terminal, and initialize your project with yarn. The default values will be fine, but change them if you want to.</p><pre>yarn init</pre><p>Next you’ll want to install all of the dependencies</p><pre>yarn add openai readline fs dotenv axios</pre><p>Lastly, let’s create three files that our project will use. One is the main JS file I named index.js, next is the file countryInformation.js that will contain the function we’ll run, and lastly .env which holds our OpenAI API key.</p><p>Let’s walk them through in the reverse order. Create the .env file and add the following line to it. Don’t forget to replace the text with your OpenAI API key which you can get from your <a href="https://platform.openai.com/api-keys">OpenAI developer account</a>.</p><pre>OPENAI_API_KEY=&quot;REPLACE WITH YOUR OPENAI API KEY HERE&quot;</pre><p>Next, create another file and name it countryInformation.js. You can change this later when you build your own functions, it’s just the name I use in this tutorial.</p><pre>// countryInformation.js: Contain the function we&#39;ll run for our assistant.<br>const axios = require(&quot;axios&quot;);<br><br>async function getCountryInformation(params) {<br>  const country = params.country;<br><br>  try {<br>    const url = `https://restcountries.com/v3.1/name/${encodeURIComponent(<br>      country<br>    )}`;<br>    const response = await axios.get(url);<br>    // console.log(response.data); if you want to inspect the output<br>    return JSON.stringify(response.data);<br>  } catch (error) {<br>    console.error(error);<br>    return null;<br>  }<br>}<br><br>module.exports = getCountryInformation;</pre><p>This function uses the free restcountries.com API, and will return a JSON object that contain information about a country. If you prefer, you could just include the async function getCountryInformation() in your main index.js file, which we’ll create next.</p><pre>// import the required dependencies<br>require(&quot;dotenv&quot;).config();<br>const OpenAI = require(&quot;openai&quot;);<br>const fsPromises = require(&quot;fs&quot;).promises;<br>const fs = require(&quot;fs&quot;);<br>const readline = require(&quot;readline&quot;).createInterface({<br>  input: process.stdin,<br>  output: process.stdout,<br>});<br>const getCountryInformation = require(&quot;./countryInformation&quot;);<br>global.getCountryInformation = getCountryInformation;<br>// Create a OpenAI connection<br>const secretKey = process.env.OPENAI_API_KEY;<br>const openai = new OpenAI({<br>  apiKey: secretKey,<br>});<br><br>async function askQuestion(question) {<br>  return new Promise((resolve, reject) =&gt; {<br>    readline.question(question, (answer) =&gt; {<br>      resolve(answer);<br>    });<br>  });<br>}<br><br>async function main() {<br>  try {<br>    let assistantId;<br>    const assistantFilePath = &quot;./assistant.json&quot;;<br><br>    // Check if the assistant.json file exists<br>    try {<br>      const assistantData = await fsPromises.readFile(<br>        assistantFilePath,<br>        &quot;utf8&quot;<br>      );<br>      assistantDetails = JSON.parse(assistantData);<br>      assistantId = assistantDetails.assistantId;<br>      console.log(&quot;\nExisting assistant detected.\n&quot;);<br>    } catch (error) {<br>      // If file does not exist or there is an error in reading it, create a new assistant<br>      console.log(&quot;No existing assistant detected, creating new.\n&quot;);<br>      const assistantConfig = {<br>        name: &quot;Country helper&quot;,<br>        instructions:<br>          &quot;You&#39;re a travelling assistant, helping with information about destination countries.&quot;,<br>        model: &quot;gpt-4-1106-preview&quot;,<br>        tools: [<br>          {<br>            type: &quot;function&quot;,<br>            function: {<br>              name: &quot;getCountryInformation&quot;,<br>              parameters: {<br>                type: &quot;object&quot;,<br>                properties: {<br>                  country: {<br>                    type: &quot;string&quot;,<br>                    description: &quot;Country name, e.g. Sweden&quot;,<br>                  },<br>                },<br>                required: [&quot;country&quot;],<br>              },<br>              description: &quot;Determine information about a country&quot;,<br>            },<br>          },<br>        ],<br>      };<br><br>      const assistant = await openai.beta.assistants.create(assistantConfig);<br>      assistantDetails = { assistantId: assistant.id, ...assistantConfig };<br><br>      // Save the assistant details to assistant.json<br>      await fsPromises.writeFile(<br>        assistantFilePath,<br>        JSON.stringify(assistantDetails, null, 2)<br>      );<br>      assistantId = assistantDetails.assistantId;<br>    }<br><br>    // Log the first greeting<br>    console.log(<br>      `Hello there, I&#39;m your personal assistant. You gave me these instructions:\n${assistantDetails.instructions}\n`<br>    );<br><br>    // Create a thread using the assistantId<br>    const thread = await openai.beta.threads.create();<br>    // Use keepAsking as state for keep asking questions<br>    let keepAsking = true;<br>    while (keepAsking) {<br>      const action = await askQuestion(<br>        &quot;What do you want to do?\n1. Chat with assistant\n2. Upload file to assistant\nEnter your choice (1 or 2): &quot;<br>      );<br><br>      if (action === &quot;2&quot;) {<br>        const fileName = await askQuestion(&quot;Enter the filename to upload: &quot;);<br><br>        // Upload the file<br>        const file = await openai.files.create({<br>          file: fs.createReadStream(fileName),<br>          purpose: &quot;assistants&quot;,<br>        });<br><br>        // Retrieve existing file IDs from assistant.json to not overwrite<br>        let existingFileIds = assistantDetails.file_ids || [];<br><br>        // Update the assistant with the new file ID<br>        await openai.beta.assistants.update(assistantId, {<br>          file_ids: [...existingFileIds, file.id],<br>        });<br><br>        // Update local assistantDetails and save to assistant.json<br>        assistantDetails.file_ids = [...existingFileIds, file.id];<br>        await fsPromises.writeFile(<br>          assistantFilePath,<br>          JSON.stringify(assistantDetails, null, 2)<br>        );<br><br>        console.log(&quot;File uploaded and successfully added to assistant\n&quot;);<br>      }<br><br>      if (action === &quot;1&quot;) {<br>        let continueAskingQuestion = true;<br><br>        while (continueAskingQuestion) {<br>          const userQuestion = await askQuestion(&quot;\nWhat is your question? &quot;);<br><br>          // Pass in the user question into the existing thread<br>          await openai.beta.threads.messages.create(thread.id, {<br>            role: &quot;user&quot;,<br>            content: userQuestion,<br>          });<br><br>          // Create a run<br>          const run = await openai.beta.threads.runs.create(thread.id, {<br>            assistant_id: assistantId,<br>          });<br><br>          // Imediately fetch run-status, which will be &quot;in_progress&quot;<br>          let runStatus = await openai.beta.threads.runs.retrieve(<br>            thread.id,<br>            run.id<br>          );<br><br>          // Polling mechanism to see if runStatus is completed<br>          while (runStatus.status !== &quot;completed&quot;) {<br>            await new Promise((resolve) =&gt; setTimeout(resolve, 1000));<br>            runStatus = await openai.beta.threads.runs.retrieve(<br>              thread.id,<br>              run.id<br>            );<br><br>            if (runStatus.status === &quot;requires_action&quot;) {<br>            //   console.log(<br>            //     runStatus.required_action.submit_tool_outputs.tool_calls<br>            //   );<br>              const toolCalls =<br>                runStatus.required_action.submit_tool_outputs.tool_calls;<br>              const toolOutputs = [];<br><br>              for (const toolCall of toolCalls) {<br>                const functionName = toolCall.function.name;<br><br>                console.log(<br>                  `This question requires us to call a function: ${functionName}`<br>                );<br><br>                const args = JSON.parse(toolCall.function.arguments);<br><br>                const argsArray = Object.keys(args).map((key) =&gt; args[key]);<br><br>                // Dynamically call the function with arguments<br>                const output = await global[functionName].apply(null, [args]);<br><br>                toolOutputs.push({<br>                  tool_call_id: toolCall.id,<br>                  output: output,<br>                });<br>              }<br>              // Submit tool outputs<br>              await openai.beta.threads.runs.submitToolOutputs(<br>                thread.id,<br>                run.id,<br>                { tool_outputs: toolOutputs }<br>              );<br>              continue; // Continue polling for the final response<br>            }<br><br>            // Check for failed, cancelled, or expired status<br>            if ([&quot;failed&quot;, &quot;cancelled&quot;, &quot;expired&quot;].includes(runStatus.status)) {<br>              console.log(<br>                `Run status is &#39;${runStatus.status}&#39;. Unable to complete the request.`<br>              );<br>              break; // Exit the loop if the status indicates a failure or cancellation<br>            }<br>          }<br><br>          // Get the last assistant message from the messages array<br>          const messages = await openai.beta.threads.messages.list(thread.id);<br><br>          // Find the last message for the current run<br>          const lastMessageForRun = messages.data<br>            .filter(<br>              (message) =&gt;<br>                message.run_id === run.id &amp;&amp; message.role === &quot;assistant&quot;<br>            )<br>            .pop();<br><br>          // If an assistant message is found, console.log() it<br>          if (lastMessageForRun) {<br>            console.log(`${lastMessageForRun.content[0].text.value} \n`);<br>          } else if (<br>            ![&quot;failed&quot;, &quot;cancelled&quot;, &quot;expired&quot;].includes(runStatus.status)<br>          ) {<br>            console.log(&quot;No response received from the assistant.&quot;);<br>          }<br><br>          // Ask if the user wants to ask another question<br>          const continueAsking = await askQuestion(<br>            &quot;Do you want to ask another question? (yes/no) &quot;<br>          );<br>          continueAskingQuestion =<br>            continueAsking.toLowerCase() === &quot;yes&quot; ||<br>            continueAsking.toLowerCase() === &quot;y&quot;;<br>        }<br>      }<br><br>      // Outside of action &quot;1&quot;, ask if the user wants to continue with any action<br>      const continueOverall = await askQuestion(<br>        &quot;Do you want to perform another action? (yes/no) &quot;<br>      );<br>      keepAsking =<br>        continueOverall.toLowerCase() === &quot;yes&quot; ||<br>        continueOverall.toLowerCase() === &quot;y&quot;;<br><br>      // If the keepAsking state is falsy show an ending message<br>      if (!keepAsking) {<br>        console.log(&quot;Alrighty then, see you next time!\n&quot;);<br>      }<br>    }<br>    // close the readline<br>    readline.close();<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}<br><br>// Call the main function<br>main();</pre><p>In this tutorial I’ll focus on the Functions part of this code, if you want to understand Assistants work in general I suggest you <a href="https://www.youtube.com/watch?v=Bo9Rcau7gkY">watch this tutorial</a> where I break down the non-Functions part of this code.</p><p>If you don’t want to learn more about how Functions work and just want to run this code, skip forward to further below. Next I’ll explain the three three Functions-related things our code do.</p><ol><li>Creates an assistant that has a function</li><li>Orchestration logic for knowing that the assistant wants to call a function, and executes it.</li><li>The function itself</li></ol><p>You see, when you create a functions in OpenAI it’s not OpenAI that executes them — that’s your responsibility. And I’ll show you how below, but let’s first start with looking at how you create an assistant with functions.</p><h4>Creating an assistant and a function</h4><pre>     const assistantConfig = {<br>        name: &quot;Country helper&quot;,<br>        instructions:<br>          &quot;You&#39;re a travelling assistant, helping with information about destination countries.&quot;,<br>        model: &quot;gpt-4-1106-preview&quot;,<br>        tools: [<br>          {<br>            type: &quot;function&quot;,<br>            function: {<br>              name: &quot;getCountryInformation&quot;,<br>              parameters: {<br>                type: &quot;object&quot;,<br>                properties: {<br>                  country: {<br>                    type: &quot;string&quot;,<br>                    description: &quot;Country name, e.g. Sweden&quot;,<br>                  },<br>                },<br>                required: [&quot;country&quot;],<br>              },<br>              description: &quot;Determine information about a country&quot;,<br>            },<br>          },<br>        ],<br>      };</pre><p>In the tools portion of this code we define that the assistant should have access to a function, and define the function. In this tutorial the function is lookining up information about a country, so I’ve named the function getCountryInformation. It takes on parameter named country which is a string and that is required. You can tack on more properties, but we have only one. It’s important to give your parameters a good description so the assistant understand what they are. Similarly, give your function a good description so the assistant knows what the function is for. These descriptions will be used by the assistant to determine when to call a function, and what input to provide.</p><p>Next, let’s look at the function we created in countryInformation.js.</p><pre>async function getCountryInformation(params) {<br>  const country = params.country;<br>... <br>}</pre><p>Note that the function name (getCountryInformation) and the params (country) are identical to what we defined in the Assistant function? That’s by design, as it allows us to call functions dynamically in our code.</p><pre>while (runStatus.status !== &quot;completed&quot;) {<br><br>            ...<br><br><br>            if (runStatus.status === &quot;requires_action&quot;) {<br>              const toolCalls =<br>                runStatus.required_action.submit_tool_outputs.tool_calls;<br>              const toolOutputs = [];<br><br>              for (const toolCall of toolCalls) {<br>                const functionName = toolCall.function.name;<br><br>                console.log(<br>                  `This question requires us to call a function: ${functionName}`<br>                );<br><br>                const args = JSON.parse(toolCall.function.arguments);<br><br>                const argsArray = Object.keys(args).map((key) =&gt; args[key]);<br><br>                // Dynamically call the function with arguments<br>                const output = await global[functionName].apply(null, [args]);<br><br>                toolOutputs.push({<br>                  tool_call_id: toolCall.id,<br>                  output: output,<br>                });<br>              }<br>              // Submit tool outputs<br>              await openai.beta.threads.runs.submitToolOutputs(<br>                thread.id,<br>                run.id,<br>                { tool_outputs: toolOutputs }<br>              );<br>              continue; // Continue polling for the final response<br>            }<br><br>             ...<br>      }</pre><p>When an assistant identifies that it needs to run a function, the status of the ongoing run is set to requires_action. And once it is, there’a information about what the action is inrunStatus.required_action.submit_tool_outputs.tool_calls. Here’s an example of what that could look like</p><pre>[<br>  {<br>    id: &#39;call_5aYhdXyZgiQi5W3LILGczB9l&#39;,<br>    type: &#39;function&#39;,<br>    function: {<br>      name: &#39;getCountryInformation&#39;,<br>      arguments: &#39;{&quot;country&quot;:&quot;Sweden&quot;}&#39;<br>    }<br>  }<br>]</pre><p>Because an assistant may ask to execute n&gt;1 functions, our code handles the execution of several functions. For each function the assistant want to call, we take the function name and arguments and execute them.</p><p>As mentioned earlier, I’ve set up the code to execute functions dynamically. The lines below take the function name passed to us and execute a local function with the same name by passing in the parameters to it. This is why it’s important that the function in our code is named the same as in the assistant’s function.</p><pre>const functionName = toolCall.function.name;<br>const args = JSON.parse(toolCall.function.arguments);<br>const argsArray = Object.keys(args).map((key) =&gt; args[key]);<br>const output = await global[functionName].apply(null, [args]);</pre><p>For global[functionName] to work, we defined getCountryInformation in the global scope like this in index.js:</p><pre>const getCountryInformation = require(&quot;./countryInformation&quot;);<br>global.getCountryInformation = getCountryInformation;</pre><p>So long as you name your function(s) its input parameters the same in your assistant and your JS file, and define this global scope, the code will dynamically trigger whatever function the assistant wants you to run.</p><h4>Returning the function result to the assistant</h4><p>Once we have the result from our function(s), we need to return it to the assistant. We’ve save the result of each function we’ve run to toolOutputs, and then call openai.beta.threads.runs.submitToolOutputs with them along with the thread and run ids.</p><pre><br>              for (const toolCall of toolCalls) {               <br>              ...<br><br>                const output = await global[functionName].apply(null, [args]);<br><br>                toolOutputs.push({<br>                  tool_call_id: toolCall.id,<br>                  output: output,<br>                });<br>              }<br>              // Submit tool outputs<br>              await openai.beta.threads.runs.submitToolOutputs(<br>                thread.id,<br>                run.id,<br>                { tool_outputs: toolOutputs }<br>              );<br>              continue; // Continue polling for the final response<br>            }<br><br>             ...<br>      }</pre><p>The assistant now has the information it needs to continue processing the original user question. The runStatus.status is changed from requires_action to pending until the assistant decides what’s next. If it wants to return a response, it’ll set the status to completed or if you have complex multi-function runs it may decide that additional functions are needed and set it to requires_action again. The code I’ve provided in this tutorial should handle it all.</p><h3>Run your code</h3><p>When you’re ready, you can run the code simply by typing this in your terminal:</p><pre>node index.js</pre><p>The script is set up to recognize if you haven’t already created an assistant with it, and automatically create one. Once the new assistant is created, it will store information about it to an <em>assistant.json</em> file in your folder. This is how it knows if you already have an assistant. It will look something like this:</p><pre>{<br>  &quot;assistantId&quot;: &quot;asst_IkYQ9mzm1QapDMb1XnyFJH5j&quot;,<br>  &quot;name&quot;: &quot;Country helper&quot;,<br>  &quot;instructions&quot;: &quot;You&#39;re a travelling assistant, helping with information about destination countries.&quot;,<br>  &quot;model&quot;: &quot;gpt-4-1106-preview&quot;,<br>  &quot;tools&quot;: [<br>    {<br>      &quot;type&quot;: &quot;function&quot;,<br>      &quot;function&quot;: {<br>        &quot;name&quot;: &quot;getCountryInformation&quot;,<br>        &quot;parameters&quot;: {<br>          &quot;type&quot;: &quot;object&quot;,<br>          &quot;properties&quot;: {<br>            &quot;country&quot;: {<br>              &quot;type&quot;: &quot;string&quot;,<br>              &quot;description&quot;: &quot;Country name, e.g. Sweden&quot;<br>            }<br>          },<br>          &quot;required&quot;: [<br>            &quot;country&quot;<br>          ]<br>        },<br>        &quot;description&quot;: &quot;Determine information about a country&quot;<br>      }<br>    }<br>  ]<br>}</pre><p>This file allows you to re-use the assistant next time you run the script, and avoid creating a new one every time. If you ever want to create a new assistant, simply delete the file. But remember that you’d have to manually remove it from the <a href="https://platform.openai.com/assistants">OpenAI platform UI</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5YZuaStE057q2DHHTP8kA.png" /></figure><p>To use the function you’ve created simply select 1. Ask a question such as “I’m travelling to country X, what currency should I bring?” that the assistant understand it should use the function for.</p><p>It’s really this simple. You can change the function in the assistant definition and countryInformation.js with your own logic, and go from there.</p><h3>Want to learn something else?</h3><p>I hope this tutorial was useful. If it was, please consider liking it on YouTube, subscribing to <a href="https://youtube.com/@ralfelfving">my channel</a> where I publish OpenAI tutorials, or following me on <a href="https://twitter.com/ralfelfving">Twitter</a> or <a href="https://www.linkedin.com/in/ralf-elfving/">LinkedIn</a>.</p><p>Maybe you’d like to learn how to build a voice assistant with OpenAI Whisper and TTS?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6AiVUcDV5FE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6AiVUcDV5FE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6AiVUcDV5FE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4e7ca68f1a0e5c6ad95d145c433b7e2/href">https://medium.com/media/f4e7ca68f1a0e5c6ad95d145c433b7e2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=519ecc7596ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenAI Vision & TTS tutorial — AI commentary of web pages]]></title>
            <link>https://medium.com/@ralfelfving/openai-vision-tts-tutorial-ai-commentary-of-web-pages-00121510e422?source=rss-6f93c520c891------2</link>
            <guid isPermaLink="false">https://medium.com/p/00121510e422</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Ralf Elfving]]></dc:creator>
            <pubDate>Fri, 24 Nov 2023 23:15:35 GMT</pubDate>
            <atom:updated>2023-11-24T23:15:35.017Z</atom:updated>
            <content:encoded><![CDATA[<h3>OpenAI Vision &amp; TTS tutorial — AI commentary of web pages</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NtBobq1u5RHF_fyO5v4iYw.jpeg" /></figure><p>BFCM is here, and every year Shopify has <a href="https://bfcm.shopify.com/">a beautiful visualization displaying global purchases as they happen live</a>. I thought, “Let’s have AI provide live commentary of it”. So I built a scrappy NodeJS script that does exactly that.</p><p>See it in action in <a href="https://twitter.com/ralfelfving/status/1727835902305513526">this tweet</a>, or dive into the tutorial below that has a demo and explains the steps to make this yourself in less than twenty minutes.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FznN6DBZNyTE&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DznN6DBZNyTE&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=google" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5e5609d4a99dd5fc49c12511a146eeb/href">https://medium.com/media/c5e5609d4a99dd5fc49c12511a146eeb/href</a></iframe><h3>Resources</h3><p>Before you start, you need these things set up on your</p><ul><li><a href="https://nodejs.org/en/download/current">NodeJS</a></li><li>Puppeteer npm (yarn add puppeteer)</li><li>Axios npm (yarn add Axios)</li><li>fs npm (yarn add fs)</li><li>readline npm (yarn add readline)</li><li>dotenv npm (yarn add dotenv)</li><li>queue npm (yarn add queue</li><li>An OpenAPI key</li></ul><p>Note that I’m running OSX/Mac on Apple silicon, with Rosetta turned on for my Terminal. Some things may not work on Windows, or another Apple configuration.</p><p>Lastly, I want to point out that <strong>the OpenAI Vision API is in preview and has DAILY rate limits</strong>. The entry-level limit is 100 calls <em>per day</em>, to see your limits go your <a href="https://platform.openai.com/account/limits">account limits page</a>.</p><h3>Start coding</h3><p>First, create a folder where you want to store all the files you’ll create. The script will also automatically create two subfolders in which it’ll create, store and read screenshots and audio files it plays back.</p><p>In the folder, create a file and name it “.env’, and add the following line to it. Don’t forget to replace the text with your OpenAI API key which you can get from your <a href="https://platform.openai.com/api-keys">OpenAI developer account</a>.</p><pre>OPENAI_API_KEY=&quot;REPLACE WITH YOUR OPENAI API KEY HERE&quot;</pre><p>Next, create another file and name it e.g. <em>runCommentary.js. </em>The name doesn’t really matter, it’s just what you’ll run from your terminal later. Paste the following code into it.</p><pre>// This is confirmed to work on OSX/Apple Silicon, running terminal with Rosetta.<br>// import playSound from &quot;play-sound&quot;;<br>import { exec } from &quot;child_process&quot;;<br>import puppeteer from &quot;puppeteer&quot;;<br>import axios from &quot;axios&quot;;<br>import fs from &quot;fs&quot;;<br>import readline from &quot;readline&quot;;<br>import queue from &quot;queue&quot;;<br>import dotenv from &quot;dotenv&quot;;<br><br>// Change to the website you want to have the AI comment on<br>const websiteToUse = &quot;https://shopify.com/bfcm&quot;;<br><br>// OpenAI chat system instruction, change to what makes sense for your usecase<br>let conversationHistory = [<br>  {<br>    role: &quot;system&quot;,<br>    content:<br>      &quot;You&#39;re an enthusiastic news presenter, providing live commentary of stats and insights from the Shopify 2023 BFCM globe page. You always provide commentary in at most three sentences, and use numbers in the millions, don&#39;t use the exact time, or use the words image or photo.&quot;,<br>  },<br>];<br><br>// Configure dotenv to fetch the OpenAI API key stored in the .env file<br>dotenv.config();<br>const openAiApiKey = process.env.OPENAI_API_KEY;<br><br>// Define folders to store screenshots and audio files, create them if they don&#39;t exist.<br>const screenshotsDir = &quot;./screenshots&quot;;<br>const audioDir = &quot;./audio&quot;;<br>const filePrefix = &quot;screenshot&quot;;<br>const audioOutputPrefix = &quot;audio&quot;;<br><br>if (!fs.existsSync(screenshotsDir)) {<br>  fs.mkdirSync(screenshotsDir, { recursive: true });<br>}<br>if (!fs.existsSync(audioDir)) {<br>  fs.mkdirSync(audioDir, { recursive: true });<br>}<br><br>// Set up a readline interface so the user can trigger the AI actions in the terminal<br>const rl = readline.createInterface({<br>  input: process.stdin,<br>  output: process.stdout,<br>});<br><br>// Function to prompt for keypress<br>function promptForKeyPress(question) {<br>  return new Promise((resolve) =&gt; {<br>    rl.question(question, (input) =&gt; {<br>      resolve(input);<br>    });<br>  });<br>}<br><br>// Function to take an input mp3 and play sounds with afplay<br>// This will afaik only work on Mac/OSX and needs to be replaced for Windows.<br>function playAudio(filePath) {<br>  return new Promise((resolve, reject) =&gt; {<br>    exec(`afplay ${filePath}`, (error) =&gt; {<br>      if (error) {<br>        console.error(&quot;Error playing audio:&quot;, error);<br>        reject(error);<br>      } else {<br>        resolve();<br>      }<br>    });<br>  });<br>}<br><br>// Set up an audio playback queue.<br>let audioPlaybackQueue = new queue({ concurrency: 1, autostart: true });<br><br>// This is the main function of this script<br>async function startTakingScreenshots(url, outputPathPrefix) {<br>  // Launch the website in a puppeteer browser locally<br>  const browser = await puppeteer.launch({ headless: false });<br>  const page = await browser.newPage();<br><br>  // Change the viewport settings your needed for your page<br>  await page.setViewport({ width: 1080, height: 800 });<br>  await page.setJavaScriptEnabled(true);<br>  await page.goto(url, { waitUntil: &quot;networkidle2&quot; });<br><br>  const mode = await promptForKeyPress(<br>    &quot;Choose mode:\n1: Manual mode\n2: Continuous mode\n\nEnter 1 or 2 and press return: &quot;<br>  );<br>  // console.log(mode);<br>  // This while loop will keep running, prompting the user to take a<br>  if (mode === &quot;1&quot;) {<br>    // Manual mode<br>    while (true) {<br>      await promptForKeyPress(&quot;\nPress return to trigger  (Ctrl+C to exit) &quot;);<br>      await processScreenshot(page, outputPathPrefix);<br>    }<br>    // Continuous mode<br>  } else if (mode === &quot;2&quot;) {<br>    console.log(&quot;The script will run continuously (press Ctrl+C to exit)&quot;);<br>    // Automatic mode<br>    while (true) {<br>      await processScreenshot(page, outputPathPrefix);<br>    }<br>  }<br>}<br><br>// Function to handle taking screenshots and processing them<br>async function processScreenshot(page, outputPathPrefix) {<br>  // Take, store and process the current screenshot<br>  const timestamp = new Date().toISOString().replace(/:/g, &quot;-&quot;);<br>  const filename = `${outputPathPrefix}_${timestamp}.png`;<br>  const screenshotPath = `${screenshotsDir}/${filename}`; // Path in the screenshots directory<br>  await page.screenshot({ path: screenshotPath, fullPage: true });<br><br>  // Convert the image to a format OpenAI&#39;s API will take<br>  const base64Image = fs.readFileSync(screenshotPath).toString(&quot;base64&quot;);<br><br>  // Define the user message to send to OpenAI, which is just the image<br>  // Use resize to reduce the size of the image -- using higher res images is more expensive!<br>  // 512, 768 and 1024 seem to be common options.<br>  const userMessage = {<br>    role: &quot;user&quot;,<br>    content: [{ image: base64Image, resize: 1024 }], // change resize value if needed<br>  };<br><br>  // Store the user question in the conversation history<br>  conversationHistory.push(userMessage);<br><br>  // Define the params to pass into the Vision API. Increase tokens if your responses get &quot;cut off&quot; mid-sentence.<br>  const params = {<br>    max_tokens: 250,<br>    model: &quot;gpt-4-vision-preview&quot;,<br>    messages: conversationHistory,<br>  };<br><br>  // Make call to the chat completions endpoint<br>  try {<br>    const result = await axios.post(<br>      &quot;https://api.openai.com/v1/chat/completions&quot;,<br>      params,<br>      {<br>        headers: {<br>          Authorization: `Bearer ${openAiApiKey}`,<br>        },<br>      }<br>    );<br>    const responseContent = result.data.choices[0].message.content;<br><br>    // Store the assistant response in the conversation history<br>    conversationHistory.push({<br>      role: &quot;assistant&quot;,<br>      content: responseContent,<br>    });<br><br>    // Convert the response to audio and queue for playback<br>    await streamedAudio(responseContent, audioOutputPrefix);<br>  } catch (error) {<br>    console.error(&quot;Error in processScreenshot:&quot;, error);<br>  }<br>}<br><br>// Function to convert text to speech and play it using play-sound<br>// Taking the Vision API output<br>async function streamedAudio(inputText, outputPathPrefix) {<br>  // Configure the OpenAI TTS (text to speech) API Calls<br>  const url = &quot;https://api.openai.com/v1/audio/speech&quot;;<br>  const headers = {<br>    Authorization: `Bearer ${openAiApiKey}`,<br>    &quot;Content-Type&quot;: &quot;application/json&quot;,<br>  };<br><br>  // The params to send to the TTS API<br>  const data = {<br>    model: &quot;tts-1&quot;,<br>    input: inputText, // This is what the Vision API responded with<br>    voice: &quot;echo&quot;, // This is the pre-selected voice, can be changed<br>    response_format: &quot;mp3&quot;,<br>  };<br><br>  // Make call to the TTS API<br>  try {<br>    const response = await axios.post(url, data, {<br>      headers: headers,<br>      responseType: &quot;arraybuffer&quot;,<br>    });<br><br>    // Set up an audioBuffer and store the TTS response as a uniquely named MP3 file<br>    const audioBuffer = Buffer.from(response.data, &quot;binary&quot;);<br>    const timestamp = new Date().toISOString().replace(/:/g, &quot;-&quot;);<br>    const audioFilename = `${outputPathPrefix}_${timestamp}.mp3`;<br>    const audioPath = `${audioDir}/${audioFilename}`;<br>    fs.writeFileSync(audioPath, audioBuffer);<br><br>    // Add the newly created mp3 to a queue<br>    audioPlaybackQueue.push(function (cb) {<br>      console.log(`\n${inputText}\n`);<br>      playAudio(audioPath)<br>        .then(() =&gt; cb())<br>        .catch((error) =&gt; {<br>          console.error(&quot;Error in audio playback:&quot;, error);<br>          cb();<br>        });<br>    });<br>  } catch (error) {<br>    console.error(&quot;Error in streamedAudio:&quot;, error.message);<br>  }<br>}<br><br>// This triggers the main script<br>startTakingScreenshots(websiteToUse, filePrefix).catch(console.error);</pre><p>Watch the video above where I explain line by line what the code does. But the TL;DR is that it:</p><ul><li>Automatically creates an assistant in OpenAI, and stores information about it to an assistant.json file to re-use in the future</li><li>Allows the user to chat with the assistant, and to upload files to OpenAI</li><li>If a file is uploaded, it gives the assistant access to it so it can be used for answering questions</li></ul><p>You’ll also likely want to change a few parameters in the script above. The websiteToUse on line 12:</p><pre>const websiteToUse = &quot;https://shopify.com/bfcm&quot;;</pre><p>The system prompt for the OpenAI Vision API on line 15–21:</p><pre>let conversationHistory = [<br>  {<br>    role: &quot;system&quot;,<br>    content:<br>      &quot;You&#39;re an enthusiastic news presenter, providing live commentary of stats and insights from the Shopify 2023 BFCM globe page. You always provide commentary in at most three sentences, and use numbers in the millions, don&#39;t use the exact time, or use the words image or photo.&quot;,<br>  },<br>];</pre><p>The OpenAI Vision API resize paramater on line 121. This will impact the resolution of the image you upload to OpenAI, and impacts the cost the API call. Read more about it <a href="https://platform.openai.com/docs/guides/vision">here</a>.</p><pre>  const userMessage = {<br>    role: &quot;user&quot;,<br>    content: [{ image: base64Image, resize: 512 }], // change resize value if needed<br>  };</pre><p>And finally, the max tokens on line 129. If you find that the response from the Vision API gets cut off mid-sentence, you’ll want to increase this — but mind you that longer responses will cost more money.</p><pre>  const params = {<br>    max_tokens: 250,<br>    model: &quot;gpt-4-vision-preview&quot;,<br>    messages: conversationHistory,<br>  };</pre><h3>Run your code</h3><p>To run the script simply open up your folder in the Terminal and run this</p><pre>node runCommentary.js</pre><p>The script is set up to recognize if the screenshot and audio folders already exist, and if they don’t it creates them.</p><p>Next it will open up a browser with Puppeteer and load the website you defined in your code. If you need to change the viewport, <em>width</em> and <em>height</em> parameters on line 80.</p><p>Next, it will ask you to make a choice between running the script in manual or continuous mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*JpiBN47JU5CtrRcim8sPwg.png" /></figure><h4>Manual mode:</h4><p>This will allow you to trigger the browser screenshot that gets sent to OpenAI manually by pressing a key on your keyboard.</p><h4>Continuous mode:</h4><p>This will take screenshots continuously, and queue up the audio to give a more counties stream of commentary.</p><h3>Want to learn something else?</h3><p>I hope this tutorial was useful. If it was, please consider liking it on YouTube, subscribing to <a href="https://youtube.com/@ralfelfving">my channel</a> where I publish OpenAI tutorials, or following me on <a href="https://twitter.com/ralfelfving">Twitter</a> or <a href="https://www.linkedin.com/in/ralf-elfving/">LinkedIn</a>.</p><p>Maybe you’d like to learn how to build a voice assistant with OpenAI Whisper and TTS?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6AiVUcDV5FE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6AiVUcDV5FE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6AiVUcDV5FE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4e7ca68f1a0e5c6ad95d145c433b7e2/href">https://medium.com/media/f4e7ca68f1a0e5c6ad95d145c433b7e2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00121510e422" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn how to programatically upload files using OpenAI Assistants API]]></title>
            <link>https://medium.com/@ralfelfving/learn-how-to-programatically-upload-files-using-openai-assistants-api-322cb5e6d2fd?source=rss-6f93c520c891------2</link>
            <guid isPermaLink="false">https://medium.com/p/322cb5e6d2fd</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Ralf Elfving]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 22:43:58 GMT</pubDate>
            <atom:updated>2024-01-07T15:51:27.707Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hLptx73NSXxSxkRooffaqg.jpeg" /></figure><p>One of the most frequent questions or requests I’ve heard in the past weeks is how to upload files with the OpenAI Assistants API. So on popular demand, here’s a simple step-by-step guide on how to do just that with a few lines of code in NodeJS.</p><p>Follow the video tutorial, and grab the code below to get started in minutes, it’s real simple!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBo9Rcau7gkY&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBo9Rcau7gkY&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=google" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf363c831b48fa5884242f093fdaba0d/href">https://medium.com/media/cf363c831b48fa5884242f093fdaba0d/href</a></iframe><p><strong>Find this article useful?</strong> I’ve published many other OpenAI and coding tutorials on my <a href="https://medium.com/@ralfelfving">Medium account</a> and on my <a href="https://www.youtube.com/@ralfelfving">YouTube channel</a>.</p><h3>Resources</h3><p>Before you start, you need these things set up on your</p><ul><li><a href="https://nodejs.org/en/download/current">NodeJS*</a></li><li>OpenAI npm (yarn add openai)</li><li>Readline npm (yarn add readline)</li><li>fs npm (yarn add fs)</li><li>dotenv npm (yarn dotenv)</li><li>An OpenAPI key</li></ul><h3>Start coding</h3><p>First, create a folder where you want to store all the files you’ll create. Then create a file and name it “.env’, and add the following line to it. Don’t forget to replace the text with your OpenAI API key which you can get from your <a href="https://platform.openai.com/api-keys">OpenAI developer account</a>.</p><pre>OPENAI_API_KEY=&quot;REPLACE WITH YOUR OPENAI API KEY HERE&quot;</pre><p>Next, create another file and name it e.g. <em>runAssistant.js. </em>The name doesn’t really matter, it’s just what you’ll run from your terminal later. Paste the following code into it.</p><pre>// import the required dependencies<br>require(&quot;dotenv&quot;).config();<br>const OpenAI = require(&quot;openai&quot;);<br>const fsPromises = require(&quot;fs&quot;).promises;<br>const fs = require(&quot;fs&quot;);<br>const readline = require(&quot;readline&quot;).createInterface({<br>  input: process.stdin,<br>  output: process.stdout,<br>});<br><br>// Create a OpenAI connection<br>const secretKey = process.env.OPENAI_API_KEY;<br>const openai = new OpenAI({<br>  apiKey: secretKey,<br>});<br><br>async function askQuestion(question) {<br>  return new Promise((resolve, reject) =&gt; {<br>    readline.question(question, (answer) =&gt; {<br>      resolve(answer);<br>    });<br>  });<br>}<br><br>async function main() {<br>  try {<br>    let assistantId;<br>    const assistantFilePath = &quot;./assistant.json&quot;;<br><br>    // Check if the assistant.json file exists<br>    try {<br>      const assistantData = await fsPromises.readFile(<br>        assistantFilePath,<br>        &quot;utf8&quot;<br>      );<br>      assistantDetails = JSON.parse(assistantData);<br>      assistantId = assistantDetails.assistantId;<br>      console.log(&quot;\nExisting assistant detected.\n&quot;);<br>    } catch (error) {<br>      // If file does not exist or there is an error in reading it, create a new assistant<br>      console.log(&quot;No existing assistant detected, creating new.\n&quot;);<br>      const assistantConfig = {<br>        name: &quot;Murder mystery helper&quot;,<br>        instructions:<br>          &quot;You&#39;re a murder mystery assistant, helping solve murder mysteries.&quot;,<br>        tools: [{ type: &quot;retrieval&quot; }], // configure the retrieval tool to retrieve files in the future<br>        model: &quot;gpt-4-1106-preview&quot;,<br>      };<br><br>      const assistant = await openai.beta.assistants.create(assistantConfig);<br>      assistantDetails = { assistantId: assistant.id, ...assistantConfig };<br><br>      // Save the assistant details to assistant.json<br>      await fsPromises.writeFile(<br>        assistantFilePath,<br>        JSON.stringify(assistantDetails, null, 2)<br>      );<br>      assistantId = assistantDetails.assistantId;<br>    }<br><br>    // Log the first greeting<br>    console.log(<br>      `Hello there, I&#39;m your personal assistant. You gave me these instructions:\n${assistantDetails.instructions}\n`<br>    );<br><br>    // Create a thread using the assistantId<br>    const thread = await openai.beta.threads.create();<br>    // Use keepAsking as state for keep asking questions<br>    let keepAsking = true;<br>    while (keepAsking) {<br>      const action = await askQuestion(<br>        &quot;What do you want to do?\n1. Chat with assistant\n2. Upload file to assistant\nEnter your choice (1 or 2): &quot;<br>      );<br><br>      if (action === &quot;2&quot;) {<br>        const fileName = await askQuestion(&quot;Enter the filename to upload: &quot;);<br><br>        // Upload the file<br>        const file = await openai.files.create({<br>          file: fs.createReadStream(fileName),<br>          purpose: &quot;assistants&quot;,<br>        });<br><br>        // Retrieve existing file IDs from assistant.json to not overwrite<br>        let existingFileIds = assistantDetails.file_ids || [];<br><br>        // Update the assistant with the new file ID<br>        await openai.beta.assistants.update(assistantId, {<br>          file_ids: [...existingFileIds, file.id],<br>        });<br><br>        // Update local assistantDetails and save to assistant.json<br>        assistantDetails.file_ids = [...existingFileIds, file.id];<br>        await fsPromises.writeFile(<br>          assistantFilePath,<br>          JSON.stringify(assistantDetails, null, 2)<br>        );<br><br>        console.log(&quot;File uploaded and successfully added to assistant\n&quot;);<br>      }<br><br>      if (action === &quot;1&quot;) {<br>        let continueAskingQuestion = true;<br><br>        while (continueAskingQuestion) {<br>          const userQuestion = await askQuestion(&quot;\nWhat is your question? &quot;);<br><br>          // Pass in the user question into the existing thread<br>          await openai.beta.threads.messages.create(thread.id, {<br>            role: &quot;user&quot;,<br>            content: userQuestion,<br>          });<br><br>          // Create a run<br>          const run = await openai.beta.threads.runs.create(thread.id, {<br>            assistant_id: assistantId,<br>          });<br><br>          // Imediately fetch run-status, which will be &quot;in_progress&quot;<br>          let runStatus = await openai.beta.threads.runs.retrieve(<br>            thread.id,<br>            run.id<br>          );<br><br>          // Polling mechanism to see if runStatus is completed<br>          while (runStatus.status !== &quot;completed&quot;) {<br>            await new Promise((resolve) =&gt; setTimeout(resolve, 1000));<br>            runStatus = await openai.beta.threads.runs.retrieve(<br>              thread.id,<br>              run.id<br>            );<br><br>            // Check for failed, cancelled, or expired status<br>            if ([&quot;failed&quot;, &quot;cancelled&quot;, &quot;expired&quot;].includes(runStatus.status)) {<br>              console.log(<br>                `Run status is &#39;${runStatus.status}&#39;. Unable to complete the request.`<br>              );<br>              break; // Exit the loop if the status indicates a failure or cancellation<br>            }<br>          }<br><br>          // Get the last assistant message from the messages array<br>          const messages = await openai.beta.threads.messages.list(thread.id);<br><br>          // Find the last message for the current run<br>          const lastMessageForRun = messages.data<br>            .filter(<br>              (message) =&gt;<br>                message.run_id === run.id &amp;&amp; message.role === &quot;assistant&quot;<br>            )<br>            .pop();<br><br>          // If an assistant message is found, console.log() it<br>          if (lastMessageForRun) {<br>            console.log(`${lastMessageForRun.content[0].text.value} \n`);<br>          } else if (<br>            ![&quot;failed&quot;, &quot;cancelled&quot;, &quot;expired&quot;].includes(runStatus.status)<br>          ) {<br>            console.log(&quot;No response received from the assistant.&quot;);<br>          }<br><br>          // Ask if the user wants to ask another question<br>          const continueAsking = await askQuestion(<br>            &quot;Do you want to ask another question? (yes/no) &quot;<br>          );<br>          continueAskingQuestion =<br>            continueAsking.toLowerCase() === &quot;yes&quot; ||<br>            continueAsking.toLowerCase() === &quot;y&quot;;<br>        }<br>      }<br><br>      // Outside of action &quot;1&quot;, ask if the user wants to continue with any action<br>      const continueOverall = await askQuestion(<br>        &quot;Do you want to perform another action? (yes/no) &quot;<br>      );<br>      keepAsking =<br>        continueOverall.toLowerCase() === &quot;yes&quot; ||<br>        continueOverall.toLowerCase() === &quot;y&quot;;<br><br>      // If the keepAsking state is falsy show an ending message<br>      if (!keepAsking) {<br>        console.log(&quot;Alrighty then, see you next time!\n&quot;);<br>      }<br>    }<br>    // close the readline<br>    readline.close();<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}<br><br>// Call the main function<br>main();</pre><p>Watch the video above where I explain line by line what the code does. But the TL;DR is that it:</p><ul><li>Automatically creates an assistant in OpenAI, and stores information about it to an assistant.json file to re-use in the future</li><li>Allows the user to chat with the assistant, and to upload files to OpenAI</li><li>If a file is uploaded, it gives the assistant access to it so it can be used for answering questions</li></ul><h3>Run your code</h3><p>Before you run the code, consider updating <em>assistantConfig</em> on line 42 to do whatever you want your assistant to do. The default is set to be a murder mystery solver. When you’re ready, run the <em>runAssistant.js </em>file in your terminal like this:</p><pre>node runAssistant.js</pre><p>The script is set up to recognize if you haven’t already created an assistant with it, and automatically create one. Once the new assistant is created, it will store information about it to an <em>assistant.json</em> file in your folder. This is how it knows if you already have an assistant. It will look something like this:</p><pre>{<br>  &quot;assistantId&quot;: &quot;asst_Dw0MoqTBEGM26UfikYnPb5AW&quot;,<br>  &quot;name&quot;: &quot;Murder mystery helper&quot;,<br>  &quot;instructions&quot;: &quot;You&#39;re a murder mystery assistant, helping solve murder mysteries.&quot;,<br>  &quot;tools&quot;: [<br>    {<br>      &quot;type&quot;: &quot;retrieval&quot;<br>    }<br>  ],<br>  &quot;model&quot;: &quot;gpt-4-1106-preview&quot;,<br>}</pre><p>This file allows you to re-use the assistant next time you run the script, and avoid creating a new one every time. If you ever want to create a new assistant, simply delete the file. But remember that you’d have to manually remove it from the <a href="https://platform.openai.com/assistants">OpenAI platform UI</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5YZuaStE057q2DHHTP8kA.png" /></figure><p>To upload a file, simply select option 2. Place the file you want to upload in the same folder as your other files, and type in the filename into the prompt in the terminal. In my tutorial the assistant is a murder mystery helper, so I created a <em>clues.txt</em> file that contained the line “The name of the killer is Rick Sanchez”, which the assistant could use.</p><p>When you upload files using the script, OpenAI will store the file in their system and assign a file id.</p><p>The script takes that file id and tells OpenAI that the assistant you’re using should have access to it. To enable you to upload more files in the future, the <em>assistant.js</em> file will also be updated with any file ids you’ve uploaded. It’ll now look something like this:</p><pre>{<br>  &quot;assistantId&quot;: &quot;asst_Dw0MoqTBEGM26UfikYnPb5AW&quot;,<br>  &quot;name&quot;: &quot;Murder mystery helper&quot;,<br>  &quot;instructions&quot;: &quot;You&#39;re a murder mystery assistant, helping solve murder mysteries.&quot;,<br>  &quot;tools&quot;: [<br>    {<br>      &quot;type&quot;: &quot;retrieval&quot;<br>    }<br>  ],<br>  &quot;model&quot;: &quot;gpt-4-1106-preview&quot;,<br>  &quot;file_ids&quot;: [<br>    &quot;file-SYMMOtb4dvaVplNnT4ux46N2&quot;<br>  ]<br>}</pre><p>Now if you ask your assistant about something that exists in the file, they’ll be able to use it to answer. It’s really this simple.</p><p>Again, remember to delete these files and assistants from the <a href="https://platform.openai.com/assistants">OpenAI platform UI</a> if you no longer use them.</p><h3>Want to learn something else?</h3><p>I hope this tutorial was useful. If it was, please consider liking it on YouTube, subscribing to <a href="https://youtube.com/@ralfelfving">my channel</a> where I publish OpenAI tutorials, or following me on <a href="https://twitter.com/ralfelfving">Twitter</a> or <a href="https://www.linkedin.com/in/ralf-elfving/">LinkedIn</a>.</p><p>Maybe you’d like to learn how to build a voice assistant with OpenAI Whisper and TTS?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6AiVUcDV5FE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6AiVUcDV5FE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6AiVUcDV5FE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4e7ca68f1a0e5c6ad95d145c433b7e2/href">https://medium.com/media/f4e7ca68f1a0e5c6ad95d145c433b7e2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=322cb5e6d2fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build your own voice-based chat assistant with OpenAI Whisper and TTS (text to speech)]]></title>
            <link>https://medium.com/@ralfelfving/build-your-own-voice-based-chat-assistant-with-openai-whisper-and-tts-text-to-speech-5c1ed05fa9ea?source=rss-6f93c520c891------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c1ed05fa9ea</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[speech-to-text-api]]></category>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[openai-chatgpt]]></category>
            <category><![CDATA[ai-development]]></category>
            <dc:creator><![CDATA[Ralf Elfving]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 23:47:40 GMT</pubDate>
            <atom:updated>2024-01-07T15:50:07.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-wkS4uJ-O5to3FBZvkvHgA.jpeg" /></figure><p>Creating a voice-based chat assistant may sound like a daunting task. But with NodeJS and a few lines of code, you can have a back-and-forth conversation with your very own assistant within just five minutes. In this tutorial I’ll show how! We’ll</p><p>We’ll use OpenAI’s Whisper API for transcription of your spoken input, and TTS (text-to-speech) for translating the chat assitant’s text response to audio that we play back to you.</p><p>It’ll be a perfect way to get familiar with the new OpenAI speech-to-text and text-to-speech APIs, and something you can extend on.</p><p>Watch the video for a step-by-step description, and use the resources and code below to try it yourself! Let’s go!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6AiVUcDV5FE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6AiVUcDV5FE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6AiVUcDV5FE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4e7ca68f1a0e5c6ad95d145c433b7e2/href">https://medium.com/media/f4e7ca68f1a0e5c6ad95d145c433b7e2/href</a></iframe><p><strong>Find this article useful?</strong> I’ve published many other OpenAI and coding tutorials on my <a href="https://medium.com/@ralfelfving">Medium account</a> and on my <a href="https://www.youtube.com/@ralfelfving">YouTube channel</a>.</p><h3>Getting Started with the Setup</h3><p>Before diving into the code, let’s ensure you have everything you need:</p><ul><li>Node.js installed on your machine.</li><li>An OpenAI API key (you can obtain one by signing up on OpenAI’s platform).</li><li>Basic knowledge of JavaScript and Node.js.</li></ul><p>You’ll also need the following NPM packages installed on your machine:</p><ul><li>node-microphone</li><li>fs</li><li>fluent-ffmpeg</li><li>ffmpeg-static</li><li>readline</li><li>axios</li><li>form-data</li><li>speaker</li><li>openai</li><li>dotenv</li></ul><p>Run yarn or npm to add the npm packages above if you don’t already have them installed, e.g. as:</p><pre>yarn add openai</pre><h3>The Workflow of Our Voice-Based Chat Assistant</h3><p>Our chat assistant will work in a simple yet effective manner:</p><ol><li>It listens to your voice input.</li><li>Transcribes the spoken words into text using Whisper API.</li><li>Processes the text through the OpenAI chat completions endpoint.</li><li>Generates a vocal response using OpenAI’s TTS.</li><li>Speaks the response back to you.</li></ol><p>This creates a seamless speech-based interaction with your assistant, making it feel like a conversation with a real person.</p><h3>All the code</h3><p>First, let’s create an .env file and store your OpenAI API key in it, like below. Otherwise we won’t be able to make OpenAI API calls.</p><pre># .env file<br>OPENAI_API_KEY=&quot;REPLACE WITH YOUR OPENAI API KEY&quot;</pre><p>Next, create a new file to hold our JS code. Name it e.g. <em>ttsChat.js, </em>and paste all the code below into it.</p><pre>// Import required modules<br>const Microphone = require(&quot;node-microphone&quot;);<br>const fs = require(&quot;fs&quot;);<br>const ffmpeg = require(&quot;fluent-ffmpeg&quot;);<br>const ffmpegPath = require(&quot;ffmpeg-static&quot;);<br>const readline = require(&quot;readline&quot;);<br>const axios = require(&quot;axios&quot;);<br>const FormData = require(&quot;form-data&quot;);<br>const Speaker = require(&quot;speaker&quot;);<br>const OpenAI = require(&quot;openai&quot;);<br>require(&quot;dotenv&quot;).config();<br><br>// Set the path for FFmpeg, used for audio processing<br>ffmpeg.setFfmpegPath(ffmpegPath);<br><br>// Initialize OpenAI API client with the provided API key<br>const secretKey = process.env.OPENAI_API_KEY;<br>const openai = new OpenAI({<br>  apiKey: secretKey,<br>});<br><br>// Variables to store chat history and other components<br>let chatHistory = []; // To store the conversation history<br>let mic, outputFile, micStream, rl; // Microphone, output file, microphone stream, and readline interface<br><br>console.log(<br>  `\n# # # # # # # # # # # # # # # # # # # # #\n# Welcome to your AI-powered voice chat #\n# # # # # # # # # # # # # # # # # # # # #\n`<br>);<br><br>// These are the main functions<br>// 1. setupReadlineInterface()<br>// 2. startRecording()<br>// 3. stopRecordingAndProcess()<br>// 4. transcribeAndChat()<br>// 5. streamedAudio()<br><br>// See diagram for overview of how they interact<br>// http://www.plantuml.com/plantuml/png/fPJ1ZjCm48RlVefHJY34Fi0Uq5QbYoeMKUqMxQKNaqnJ2tTisHEWF3sUD6jvJSCY4QbLFVdcZ-Vttzn4re67erMwPHVWIyIWV2gPrdXD34r47lmzwiuQmZKnXhrkyTNh1dI41xbPyI9uZwqBdQ7-YPDYpJcViGLrc-1QZ34tk4gNWwRO1lCL4xmyQ9x8RQxN-W7r4Rl5q1cNLOkQKkFkuUqxEF-uXZKPDjgQNmXvqXtTcSX8i7S1FkB91unHaME4OFe3Wzld_lScUgjFq6m4WfLe0Blp-F3WKNzBmpPAN2wVUsj2P2YQAlsHlvvaicd5_kL60hQfeyTG8d8d8rdZasbtz1WCespF3Um7lZKMdtXfg6VAebTNLurIrZaFkGPtQQaWNTfoKLvJ6ilresSmNTNqvToPcPc_V6Hc2nkSBroGPOPaaPb9QdHXHLrfGCcB3qM-KjiKKXW3bDa2gHgAnOu-867GZ23fJND4xoZYZCgpg2QXfQFl67ARd5krY-ST5oGsSen_xP6cbw8i8OP5hmqrempQYF2e3SjnxwTNoF-VTPNr3B-S-OpMsHVlBgIVyCVb0FpZFq5Wf4x9HqdwLp_FPYoyjwRLR1ofUIyMT9BN2dpc0mRO7ZHbUsQi4Vq_nEjtsKYfyN2M7EoRvVmMCZ0h8wFTfA_XQ7y3<br><br>// Function to set up the readline interface for user input<br>const setupReadlineInterface = () =&gt; {<br>  rl = readline.createInterface({<br>    input: process.stdin,<br>    output: process.stdout,<br>    terminal: true, // Make sure the terminal can capture keypress events<br>  });<br><br>  readline.emitKeypressEvents(process.stdin, rl);<br><br>  if (process.stdin.isTTY) {<br>    process.stdin.setRawMode(true);<br>  }<br><br>  // Handle keypress events<br>  process.stdin.on(&quot;keypress&quot;, (str, key) =&gt; {<br>    if (<br>      key &amp;&amp;<br>      (key.name.toLowerCase() === &quot;return&quot; ||<br>        key.name.toLowerCase() === &quot;enter&quot;)<br>    ) {<br>      if (micStream) {<br>        stopRecordingAndProcess();<br>      } else {<br>        startRecording();<br>      }<br>    } else if (key &amp;&amp; key.ctrl &amp;&amp; key.name === &quot;c&quot;) {<br>      process.exit(); // Handle ctrl+c for exiting<br>    } else if (key) {<br>      console.log(&quot;Exiting application...&quot;);<br>      process.exit(0);<br>    }<br>  });<br><br>  console.log(&quot;Press Enter when you&#39;re ready to start speaking.&quot;);<br>};<br><br>// Function to start recording audio from the microphone<br>const startRecording = () =&gt; {<br>  mic = new Microphone();<br>  outputFile = fs.createWriteStream(&quot;output.wav&quot;);<br>  micStream = mic.startRecording();<br><br>  // Write incoming data to the output file<br>  micStream.on(&quot;data&quot;, (data) =&gt; {<br>    outputFile.write(data);<br>  });<br><br>  // Handle microphone errors<br>  micStream.on(&quot;error&quot;, (error) =&gt; {<br>    console.error(&quot;Error: &quot;, error);<br>  });<br><br>  console.log(&quot;Recording... Press Enter to stop&quot;);<br>};<br><br>// Function to stop recording and process the audio<br>const stopRecordingAndProcess = () =&gt; {<br>  mic.stopRecording();<br>  outputFile.end();<br>  console.log(`Recording stopped, processing audio...`);<br>  transcribeAndChat(); // Transcribe the audio and initiate chat<br>};<br><br>// Default voice setting for text-to-speech<br>const inputVoice = &quot;echo&quot;; // https://platform.openai.com/docs/guides/text-to-speech/voice-options<br>const inputModel = &quot;tts-1&quot;; // https://platform.openai.com/docs/guides/text-to-speech/audio-quality<br><br>// Function to convert text to speech and play it using Speaker<br>async function streamedAudio(<br>  inputText,<br>  model = inputModel,<br>  voice = inputVoice<br>) {<br>  const url = &quot;https://api.openai.com/v1/audio/speech&quot;;<br>  const headers = {<br>    Authorization: `Bearer ${secretKey}`, // API key for authentication<br>  };<br><br>  const data = {<br>    model: model,<br>    input: inputText,<br>    voice: voice,<br>    response_format: &quot;mp3&quot;,<br>  };<br><br>  try {<br>    // Make a POST request to the OpenAI audio API<br>    const response = await axios.post(url, data, {<br>      headers: headers,<br>      responseType: &quot;stream&quot;,<br>    });<br><br>    // Configure speaker settings<br>    const speaker = new Speaker({<br>      channels: 2, // Stereo audio<br>      bitDepth: 16,<br>      sampleRate: 44100,<br>    });<br><br>    // Convert the response to the desired audio format and play it<br>    ffmpeg(response.data)<br>      .toFormat(&quot;s16le&quot;)<br>      .audioChannels(2)<br>      .audioFrequency(44100)<br>      .pipe(speaker);<br>  } catch (error) {<br>    // Handle errors from the API or the audio processing<br>    if (error.response) {<br>      console.error(<br>        `Error with HTTP request: ${error.response.status} - ${error.response.statusText}`<br>      );<br>    } else {<br>      console.error(`Error in streamedAudio: ${error.message}`);<br>    }<br>  }<br>}<br><br>// Function to transcribe audio to text and send it to the chatbot<br>async function transcribeAndChat() {<br>  const filePath = &quot;output.wav&quot;;<br>  // note that the file size limitations are 25MB for Whisper<br><br>  // Prepare form data for the transcription request<br>  const form = new FormData();<br>  form.append(&quot;file&quot;, fs.createReadStream(filePath));<br>  form.append(&quot;model&quot;, &quot;whisper-1&quot;);<br>  form.append(&quot;response_format&quot;, &quot;text&quot;);<br><br>  try {<br>    // Post the audio file to OpenAI for transcription<br>    const transcriptionResponse = await axios.post(<br>      &quot;https://api.openai.com/v1/audio/transcriptions&quot;,<br>      form,<br>      {<br>        headers: {<br>          ...form.getHeaders(),<br>          Authorization: `Bearer ${secretKey}`,<br>        },<br>      }<br>    );<br><br>    // Extract transcribed text from the response<br>    const transcribedText = transcriptionResponse.data;<br>    console.log(`&gt;&gt; You said: ${transcribedText}`);<br><br>    // Prepare messages for the chatbot, including the transcribed text<br>    const messages = [<br>      {<br>        role: &quot;system&quot;,<br>        content:<br>          &quot;You are a helpful assistant providing concise responses in at most two sentences.&quot;,<br>      },<br>      ...chatHistory,<br>      { role: &quot;user&quot;, content: transcribedText },<br>    ];<br><br>    // Send messages to the chatbot and get the response<br>    const chatResponse = await openai.chat.completions.create({<br>      messages: messages,<br>      model: &quot;gpt-3.5-turbo&quot;,<br>    });<br><br>    // Extract the chat response.<br>    const chatResponseText = chatResponse.choices[0].message.content;<br><br>    // Update chat history with the latest interaction<br>    chatHistory.push(<br>      { role: &quot;user&quot;, content: transcribedText },<br>      { role: &quot;assistant&quot;, content: chatResponseText }<br>    );<br><br>    // Convert the chat response to speech and play + log it to the terminal<br>    await streamedAudio(chatResponseText);<br>    console.log(`&gt;&gt; Assistant said: ${chatResponseText}`);<br><br>    // Reset microphone stream and prompt for new recording<br>    micStream = null;<br>    console.log(&quot;Press Enter to speak again, or any other key to quit.\n&quot;);<br>  } catch (error) {<br>    // Handle errors from the transcription or chatbot API<br>    if (error.response) {<br>      console.error(<br>        `Error: ${error.response.status} - ${error.response.statusText}`<br>      );<br>    } else {<br>      console.error(&quot;Error:&quot;, error.message);<br>    }<br>  }<br>}<br><br>// Initialize the readline interface<br>setupReadlineInterface();</pre><p>Feel free to change the TTS voice or the chat assistant system prompt for diferent feel and response.</p><h3>Setting Up the Environment</h3><p>Make sure to install all required Node.js modules and handle any system-specific configurations, such as setting up ffmpeg if it&#39;s not already configured on your machine. You may also need to grant the terminal access to play sound.</p><p><strong>Note:</strong> I’ve only been able to test this on Mac/OSX, so I’m not sure if it’ll work on Windows. Please let me know if it doesn’t work on Windows, and if you have a work-around I can share with everyone (with credits!).</p><h3>Testing Your Chat Assistant</h3><p>Once you’ve set up the code, run the script in your terminal by executing this command from your terminal in the folder your file is saved:</p><pre>node ttsChat.js</pre><p>Follow the prompts to interact with your assistant. You’ll be able to have a conversation, ask questions, and receive spoken answers in real-time.</p><h3>Want more?</h3><p>I hope this tutorial was useful. If it was, please consider <a href="https://www.youtube.com/watch?v=6AiVUcDV5FE">liking it on YouTube</a>, subscribing to <a href="https://youtube.com/@ralfelfving">my channel</a>, or following me on <a href="https://twitter.com/ralfelfving">Twitter</a> or <a href="https://www.linkedin.com/in/ralf-elfving/">LinkedIn</a>.</p><p>I’ll hopefully be putting out a few more OpenAI tutorials in the coming weeks, so make sure to subscribe or check back in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c1ed05fa9ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fork this OpenAI Assistant web chat app in 3 minutes — and learn the APIs]]></title>
            <link>https://medium.com/@ralfelfving/fork-this-openai-assistant-web-chat-app-in-3-minutes-and-learn-the-apis-cd3eb687f274?source=rss-6f93c520c891------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd3eb687f274</guid>
            <category><![CDATA[openai-api]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ralf Elfving]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 22:59:22 GMT</pubDate>
            <atom:updated>2023-11-13T22:59:22.008Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fork this OpenAI Assistant web chat app in 3 minutes — and learn the APIs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hPKnZP9w8I8ShqcFbRoFNA.jpeg" /></figure><p>In my most recent YouTube video I’m taking you on a coding journey to explore the OpenAI Assistants API. If you’ve been curious about integrating AI into your web applications, this is the perfect opportunity to dive in.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FbVIFyh419es%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DbVIFyh419es&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FbVIFyh419es%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/989a6f27c69e412a9f0af1fb1ab4fabe/href">https://medium.com/media/989a6f27c69e412a9f0af1fb1ab4fabe/href</a></iframe><p>In the tutorial, I demonstrate how to create an Assistant wrapper with a chat interface that runs smoothly on the web. The best part? You can fork the project I built and have it up and running in just three minutes! Then you can use that as a reference to learn and extend.</p><p>Here’s a sneak peek of what you’ll discover:</p><ul><li>How to fork an existing simple web-based Assistants chat UI</li><li>The process of creating an assistant with custom instructions and capabilities.</li><li>Interacting with the OpenAI API to send messages and receive responses.</li><li>Keeping track of conversations with state management</li></ul><p>By following along, you’ll not only see the end product but also gain insights into the code behind it. I’ll walk you through the steps to clone the project and have it up and running, which takes just three minutes And we’ll discuss the Node.js code involved in interfacing with the APIs.</p><p>For those who are interested, head over to my <a href="https://www.youtube.com/watch?v=bVIFyh419es">YouTube channel to watch the full tutorial </a>or click the video link above.</p><p>See you in the video!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd3eb687f274" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scrape and upload any site to a GPT in 2 minutes]]></title>
            <link>https://medium.com/@ralfelfving/scrape-and-upload-any-site-to-a-gpt-in-2-minutes-1ec5ec127a81?source=rss-6f93c520c891------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ec5ec127a81</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[openai-chatgpt]]></category>
            <dc:creator><![CDATA[Ralf Elfving]]></dc:creator>
            <pubDate>Fri, 10 Nov 2023 19:44:04 GMT</pubDate>
            <atom:updated>2024-01-07T15:42:23.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fovnu19FXGfW2N0HQJO5cw.jpeg" /></figure><p>In this tutorial you’ll learn how to scrape any website with a sitemap and upload it to a GPT. Once you’re set up it’ll take less than two minutes!</p><p>By the end of this tutorial it you’ll have built three capabilities you can chose from, where your code will automatically:</p><ol><li>Create a zip file that contain a text file for each page in a sitemap, saved to your local machine</li><li>Create a single text file with the contents of all pages in a sitemap, saved to your local machine</li><li>Create an OpenAI Assistant and upload the file to it.</li></ol><p>Follow along in the video that covers how to create a zip file, and use the code and other resources below to complete it and the other two capabilities.</p><p>Let’s get started!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FVfKD5NL4buY&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVfKD5NL4buY&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=google" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/70cce5f41c091181dd58da5e300f907f/href">https://medium.com/media/70cce5f41c091181dd58da5e300f907f/href</a></iframe><p><strong>Find this article useful?</strong> I’ve published many other OpenAI and coding tutorials on my <a href="https://medium.com/@ralfelfving">Medium account</a> and on my <a href="https://www.youtube.com/@ralfelfving">YouTube channel</a>.</p><h3>Resources</h3><p>You’ll need things:</p><ul><li><a href="https://nodejs.org/en/download/current">NodeJS</a> installed on your computer.</li><li>Sitemapper npm</li><li>fs npm</li><li>archiver npm</li><li>cheerio npm</li></ul><p>Run yarn or npm to add the npm packages above if you don’t already have them installed, e.g. as:</p><pre>yarn add cheerio</pre><h4>Create and run the scraper</h4><p>Next navigate to the folder you want to keep your script and files you generate. In it, create a file called sitemapScraper.js, and copy/paste the code below into it.</p><pre>// This is sitemapScraper.js<br>const Sitemapper = require(&quot;sitemapper&quot;);<br>const fs = require(&quot;fs&quot;);<br>const fsPromises = fs.promises;<br>const archiver = require(&quot;archiver&quot;);<br>const cheerio = require(&quot;cheerio&quot;);<br><br>const inputSitemap = &quot;https://yourwebsite.dev/sitemap.xml&quot;;<br><br><br>// Extract text by removing some things, like HTML<br>function extractText(htmlContent) {<br>  const $ = cheerio.load(htmlContent);<br>  $(&quot;style&quot;).remove();<br>  $(&quot;script&quot;).remove();<br>  $(&quot;[style]&quot;).removeAttr(&quot;style&quot;);<br>  return $(&quot;body&quot;).text();<br>}<br><br>// Fetch and return &#39;cleaned&#39; text from a URL<br>async function fetchTextContent(url) {<br>  const response = await fetch(url);<br>  const htmlContent = await response.text();<br>  return extractText(htmlContent);<br>}<br><br>// Main function that orchestrates calling other functions and writing files<br>async function scrapeWebsite(url) {<br>  const sitemap = new Sitemapper({ url });<br>  const { sites } = await sitemap.fetch();<br>  const folderName = &quot;pages&quot;;<br><br>  // Create a new folder<br>  await fsPromises.mkdir(folderName, { recursive: true });<br><br>  // Loop through all pages in sitemap<br>  for (const site of sites) {<br>    console.log(`Scraping: ${site}`);<br>    const textContent = await fetchTextContent(site);<br>    const fileName = new URL(site).pathname.replace(/\//g, &quot;_&quot;) + &quot;.txt&quot;;<br>    const filePath = `${folderName}/${fileName}`;<br>    await fsPromises.writeFile(filePath, textContent, &quot;utf8&quot;);<br>  }<br><br>  // Zip the folder<br>  const fileName = &quot;allfiles.zip&quot;;<br>  const output = fs.createWriteStream(fileName);<br>  const archive = archiver(&quot;zip&quot;, {<br>    zlib: { level: 9 }, // Set the compression level<br>  });<br><br>  // Log info once the archiver has created the file<br>  output.on(&quot;close&quot;, function () {<br>    console.log(archive.pointer() + &quot; total bytes&quot;);<br>    console.log(<br>      &quot;Archiver has been finalized and the output file descriptor has closed.&quot;<br>    );<br>  });<br><br>  archive.on(&quot;error&quot;, function (err) {<br>    throw err;<br>  });<br><br>  archive.pipe(output);<br>  archive.directory(folderName, false);<br>  await archive.finalize();<br><br>}<br><br>scrapeWebsite(inputSitemap);</pre><p>Make sure to replace the ‘yourwebsite.dev/sitemap.xml’ with your page.</p><p>Then run this command in a terminal window for folder that has your file.</p><pre>node sitemapScraper.js</pre><p>Make sure you have permission to scrape the data, or use the scraped data responsibly.</p><h4>Create the GPT</h4><p>Once the script has completed, you can go over to <a href="https://chat.openai.com/gpts/discovery">OpenAI’s GPT directory</a> to create your own GPT and upload the file as a resource.</p><p>To avoid the GPT trying to answer questions without making use of the file I uploaded, I called out the requirement to use the file. This is what I used:</p><blockquote>Use the zipfile uploaded to you and search through these documents for any relevant information about what the user is asking for, then respond with a clear and concise answer. The user can ask for more information if they want. Don’t tell the user about the files you have.</blockquote><h4>Create one single text file with all scraped content</h4><p>If you prefer to have one single text file instead of a zip file containing one text file per page in the sitemap, here’s how you can change the sitemapScraper.js to do that.</p><p>Replace the <em>scrapeWebsite()</em> function in the zip-file example above with this.</p><pre>// This is sitemapScraper.js<br>// Keep all of your existing code but replace scrapeWebsite() with this:<br><br>async function scrapeWebsite(url) {<br>  const sitemap = new Sitemapper({ url });<br>  const { sites } = await sitemap.fetch();<br><br>  let combinedContent = &quot;&quot;;<br>  for (const site of sites) {<br>    console.log(`Scraping: ${site}`);<br>    const textContent = await fetchTextContent(site);<br>    combinedContent += textContent + &quot;\n\n&quot;;<br>  }<br><br>  const filePath = &quot;allSiteDataInOneTextfile.txt&quot;;<br>  fs.writeFile(filePath, combinedContent, &quot;utf8&quot;, function (err) {<br>    if (err) throw err;<br>    console.log(&quot;The file has been saved!&quot;);<br>  });</pre><p>This will create one single text file with the content of all of the pages in the sitemap, instead a zip file with one text file for each page.</p><p>If you want you can remove the archiver and fsPromises dependencies, and the archiver code at the bottom of siteScraper.js</p><h4>Create an OpenAI Assistant</h4><p>If you want to instead upload either the text file or zip to OpenAI and create an Assistant, here’s how to do that:</p><p><strong>Resources</strong></p><ul><li>OpenAI npm (4.16.1 or later)</li><li>dotnv npm</li><li>An OpenAPI key</li></ul><p>Create a .env file in the same folder as your .js file and add the following. Don’t give your file a name like <em>key.env</em>, it should just be named <em>.env</em></p><pre># .env file<br>OPENAI_API_KEY=&quot;REPLACE WITH YOUR OPENAI API KEY&quot;</pre><p>Then we need to make some changes to the sitemapScraper.js. Let’s first add the required dependencies at the top of the file:</p><pre>// Add these two dependencies at the top of the file<br>const OpenAI = require(&quot;openai&quot;);<br>require(&quot;dotenv&quot;).config();</pre><p>Then we add code to establish a connection with OpenAI that is required to create your Assistant. The <em>process.env</em> will fetch the secret key you stored in the <em>.env</em> file.</p><pre>// Add these to setup connection with OpenAI under your dependencies<br>const secretKey = process.env.OPENAI_API_KEY;<br>const openai = new OpenAI({<br>  apiKey: secretKey, <br>});</pre><p>Next let’s add the main function that will upload your file to OpenAI, and then create an Assistant that can use the file. Place this code directly after the <em>scrapeWebsite()</em> function. Don’t forget to change the file name reference to be named the same as your file, and change the Assistant <em>name</em> and <em>instructions</em></p><pre>// Add this code under the scrapeWebsite() function<br>  try {<br>    const uploadedFile = await openai.files.create({<br>      file: fs.createReadStream(&quot;ChangeToYourFileName.zipOrTxt&quot;),<br>      purpose: &quot;assistants&quot;,<br>    });<br><br>    // I know I spelled assistant incorrect, but I&#39;ll just leave it :D <br>    const createdAsstant = await openai.beta.assistants.create({<br>      name: &quot;Gadget.dev expert&quot;,<br>      instructions:<br>        &quot;You&#39;re a helpful assistant helping to answer questions about Gadget.dev&quot;,<br>      model: &quot;gpt-4-1106-preview&quot;,<br>      tools: [{ type: &quot;retrieval&quot; }],<br>      file_ids: [uploadedFile.id],<br>    });<br>  } catch (error) {<br>    console.log(&quot;error&quot;);<br>  }</pre><p>Now, if you run the code it will still generate and save a file locally, but it will also create a new Assistant with the generated file as an uploaded resource. You can access your Assistant, and use them in the OpenAI playground, by going to <a href="https://platform.openai.com/assistants">platform.openai.com/assistants</a>.</p><p><strong>Please Note that using the OpenAI API will incur costs for you!</strong></p><h3>Want more?</h3><p>I hope this tutorial was useful. If it was, please consider liking it on YouTube, subscribing to <a href="https://youtube.com/@ralfelfving">my channel</a>, or following me on <a href="https://twitter.com/ralfelfving">Twitter</a> or <a href="https://www.linkedin.com/in/ralf-elfving/">LinkedIn</a>.</p><p>I’ll hopefully be putting out a few more OpenAI tutorials in the coming weeks, so make sure to subscribe or check back in.</p><p>Also want to shout-out <a href="https://twitter.com/0xSamHogan">@0xSamHogan</a> on Twitter that posted <a href="https://twitter.com/0xSamHogan/status/1721934026624385104">this code</a> that I used as a starting point.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ec5ec127a81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Get started with the new OpenAI Assistants API]]></title>
            <link>https://medium.com/@ralfelfving/tutorial-get-started-with-the-new-openai-assistants-api-7049c2517bfe?source=rss-6f93c520c891------2</link>
            <guid isPermaLink="false">https://medium.com/p/7049c2517bfe</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Ralf Elfving]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 04:06:34 GMT</pubDate>
            <atom:updated>2024-01-07T15:50:39.707Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLOwOG7WXHNguoQ47WM54g.jpeg" /></figure><p>OpenAI released the new Assistants API today, which opens up a lot of new opportunities. I put together this scrappy NodeJS tutorial on the day of the release to hopefully help people get started more quickly. Watch the video and use the resources below to build your first Assistant.</p><h4>UPDATE</h4><p>I’ve released two updated, better and more comprehensive tutorials I suggest you use instead.</p><ul><li><strong>Re-use assistants between runs:</strong> Similar to this tutorial, but with better logic that re-use assistants between runs, more robust error handling. <a href="https://www.youtube.com/watch?v=Bo9Rcau7gkY">Check it out here</a>.</li><li><strong>Web-based chat interface</strong>: Instead of running Node locally, you create a web-based chat interface, with Assistant and thread state creation and state management. You can fork and have it up and running in three minutes by following <a href="https://www.youtube.com/watch?v=bVIFyh419es">this tutorial</a>.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1UhV8XcWWgs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1UhV8XcWWgs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1UhV8XcWWgs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4f8c5b29e598359a364879b90ee120e/href">https://medium.com/media/a4f8c5b29e598359a364879b90ee120e/href</a></iframe><p><strong>Find this article useful?</strong> I’ve published many other OpenAI and coding tutorials on my <a href="https://medium.com/@ralfelfving">Medium account</a> and on my <a href="https://www.youtube.com/@ralfelfving">YouTube channel</a>.</p><h3>Resources</h3><p>Before you start, you need these things set up on your</p><ul><li><a href="https://nodejs.org/en/download/current">NodeJS*</a></li><li>OpenAI npm 4.16.1 or later (yarn add openai)</li><li>Readline npm (yarn add readline)</li><li>dotenv npm (yarn dotenv)</li><li>An OpenAPI key</li></ul><p>* Myself and other <a href="https://github.com/forcedotcom/cli/issues/2535">experienced a dependency issue</a> with OpenAI’s node module and the latest Node version (21) today. I resolved this by downgrading NodeJS to 20.9.0. I did not check if the issue was resolved before recording the tutorial, but if you need to downgrade you can do this by running:</p><pre>n 20.9.0</pre><p>Lastly, I would strongly suggest you review OpenAI’s <a href="https://platform.openai.com/docs/assistants/overview">Assistants API documentation</a>, because several new concepts are introduced.</p><h3>Start coding</h3><p>Create a file and name it “.env’, and add the following line to it. Don’t forget to replace the text with your OpenAI API key which you can get from your <a href="https://platform.openai.com/api-keys">OpenAI developer account</a>.</p><pre>OPENAI_API_KEY=&quot;REPLACE WITH YOUR OPENAI API KEY HERE&quot;</pre><p>Next, create another file and name it e.g. <em>mathTeacher.js. </em>The name doesn’t really matter, it’s just what you’ll run from your terminal later. Paste the following code into it.</p><pre><br>// import the required dependencies<br>require(&quot;dotenv&quot;).config();<br>const OpenAI = require(&quot;openai&quot;);<br>const readline = require(&quot;readline&quot;).createInterface({<br>  input: process.stdin,<br>  output: process.stdout,<br>});<br><br>// Create a OpenAI connection<br>const secretKey = process.env.OPENAI_API_KEY;<br>const openai = new OpenAI({<br>  apiKey: secretKey,<br>});<br><br>async function askQuestion(question) {<br>  return new Promise((resolve, reject) =&gt; {<br>    readline.question(question, (answer) =&gt; {<br>      resolve(answer);<br>    });<br>  });<br>}<br><br>async function main() {<br>  try {<br>    const assistant = await openai.beta.assistants.create({<br>      name: &quot;Math Tutor&quot;,<br>      instructions:<br>        &quot;You are a personal math tutor. Write and run code to answer math questions.&quot;,<br>      tools: [{ type: &quot;code_interpreter&quot; }],<br>      model: &quot;gpt-4-1106-preview&quot;,<br>    });<br><br>    // Log the first greeting<br>    console.log(<br>      &quot;\nHello there, I&#39;m your personal math tutor. Ask some complicated questions.\n&quot;<br>    );<br><br>    // Create a thread<br>    const thread = await openai.beta.threads.create();<br><br>    // Use keepAsking as state for keep asking questions<br>    let keepAsking = true;<br>    while (keepAsking) {<br>      const userQuestion = await askQuestion(&quot;\nWhat is your question? &quot;);<br><br>      // Pass in the user question into the existing thread<br>      await openai.beta.threads.messages.create(thread.id, {<br>        role: &quot;user&quot;,<br>        content: userQuestion,<br>      });<br><br>      // Use runs to wait for the assistant response and then retrieve it<br>      const run = await openai.beta.threads.runs.create(thread.id, {<br>        assistant_id: assistant.id,<br>      });<br><br>      let runStatus = await openai.beta.threads.runs.retrieve(<br>        thread.id,<br>        run.id<br>      );<br><br>      // Polling mechanism to see if runStatus is completed<br>      // This should be made more robust.<br>      while (runStatus.status !== &quot;completed&quot;) {<br>        await new Promise((resolve) =&gt; setTimeout(resolve, 2000));<br>        runStatus = await openai.beta.threads.runs.retrieve(thread.id, run.id);<br>      }<br><br>      // Get the last assistant message from the messages array<br>      const messages = await openai.beta.threads.messages.list(thread.id);<br><br>      // Find the last message for the current run<br>      const lastMessageForRun = messages.data<br>        .filter(<br>          (message) =&gt; message.run_id === run.id &amp;&amp; message.role === &quot;assistant&quot;<br>        )<br>        .pop();<br><br>      // If an assistant message is found, console.log() it<br>      if (lastMessageForRun) {<br>        console.log(`${lastMessageForRun.content[0].text.value} \n`);<br>      }<br><br>      // Then ask if the user wants to ask another question and update keepAsking state<br>      const continueAsking = await askQuestion(<br>        &quot;Do you want to ask another question? (yes/no) &quot;<br>      );<br>      keepAsking = continueAsking.toLowerCase() === &quot;yes&quot;;<br><br>      // If the keepAsking state is falsy show an ending message<br>      if (!keepAsking) {<br>        console.log(&quot;Alrighty then, I hope you learned something!\n&quot;);<br>      }<br>    }<br><br>    // close the readline<br>    readline.close();<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}<br><br>// Call the main function<br>main();</pre><p>This code was scrappily put together in little time and briefly explained in the video above, and there’s plenty of room for improvement. There’s definitely flaws in the polling mechanism, but hopefully it’s a start that you can build on.</p><p>I suggest you read the <a href="https://platform.openai.com/docs/assistants/how-it-works">OpenAI Assistants documentation</a> to understand what the code does. As an example you only need to create an assistant once, and then you can create that assistant by creating new threads as needed. I’ll explain this in more detail in a future video.</p><h3>Run your code</h3><p>To run your code, open up your terminal and navigate to the folder where you saved your files. Run the <em>mathTeacher.js </em>file from it</p><pre>node mathTeacher.js</pre><h3>Want more?</h3><p>I hope this tutorial was useful. If it was, please consider liking it on YouTube, subscribing to <a href="https://youtube.com/@ralfelfving">my channel</a>, or following me on <a href="https://twitter.com/ralfelfving">Twitter</a> or <a href="https://www.linkedin.com/in/ralf-elfving/">LinkedIn</a>.</p><p>I’ll hopefully be putting out a few more OpenAI tutorials in the coming weeks, so make sure to subscribe or check back in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7049c2517bfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>