{"id":374,"date":"2023-11-25T06:27:43","date_gmt":"2023-11-25T04:27:43","guid":{"rendered":"https:\/\/celilsemi.erkiner.com\/blog\/?p=374"},"modified":"2023-12-02T04:24:30","modified_gmt":"2023-12-02T02:24:30","slug":"guide-start-your-journey-with-openais-new-assistants-api","status":"publish","type":"post","link":"https:\/\/celilsemi.erkiner.com\/blog\/guide-start-your-journey-with-openais-new-assistants-api\/","title":{"rendered":"Guide: Start Your Journey with OpenAI&#8217;s New Assistants API"},"content":{"rendered":"\n<p>Welcome to the exciting world of OpenAI&#8217;s recently <a href=\"https:\/\/celilsemi.erkiner.com\/blog\/openai-devday-2023-pioneering-the-new-ai-landscape\/\" target=\"_blank\" rel=\"noopener\" title=\"OpenAI DevDay 2023: Pioneering the New AI Landscape\">announced<\/a> Assistants API. This groundbreaking API allows developers to create intelligent and conversational assistants that can understand and respond to human language. Whether you&#8217;re an experienced developer or a curious beginner, this hello world project is perfect for anyone who wants to dive into the capabilities of the Assistants API and it&#8217;s time to explore the possibilities to change how we interact with Open AI API. Let&#8217;s get started!<\/p>\n\n\n\n<p>Essential Resources:<\/p>\n\n\n\n<ul class=\"has-small-font-size wp-block-list\">\n<li>NodeJS<\/li>\n\n\n\n<li>OpenAI npm version 4.16.1 or later (installable via <code>npm install openai<\/code>)<\/li>\n\n\n\n<li>dotenv npm (installable via <code>npm install dotenv<\/code>)<\/li>\n\n\n\n<li>An active OpenAPI key<\/li>\n<\/ul>\n\n\n\n<p>I highly recommend delving into the <a href=\"https:\/\/platform.openai.com\/docs\/assistants\/overview\" target=\"_blank\" rel=\"noopener\" title=\"OpenAI Assistants API documentation\">OpenAI Assistants API documentation<\/a> because this documentation introduces several new and crucial concepts that are fundamental to understanding and effectively utilizing the API.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step-by-Step Coding Guide:<\/h2>\n\n\n\n<h4 class=\"wp-block-heading\">1. Start by creating a \u201c.env\u201d file. <\/h4>\n\n\n\n<p>In this file, you need to include your specific OpenAI API key, which you can obtain from your OpenAI developer account. Format it as follows: <\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}\">OPENAI_API_KEY=&quot;YOUR OPENAI API KEY&quot;<\/pre><\/div>\n\n\n\n<h4 class=\"wp-block-heading\">2. Next, create a script file.<\/h4>\n\n\n\n<p>For instance, create <code>mathAssistant.js<\/code> and insert the following NodeJS code into this file:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Import the required dependencies\nrequire(&quot;dotenv&quot;).config();\nconst OpenAI = require(&quot;openai&quot;);\n\n\/\/ Create an OpenAI connection with the API key from the environment variables \nconst openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n\n\/\/ Define an asynchronous function to prompt the user for input\nasync function askQuestion(question) { \n    process.stdout.write(question);\n    return new Promise((resolve) =&gt; {\n        process.stdin.once('data', data =&gt; resolve(data.toString().trim()));\n    });\n}\n\n\/\/ Define the main asynchronous function\nasync function main() { \n    try { \n        \/\/ Print the first greeting for User\n        process.stdout.write(&quot;\\nAssistant: Hello there, I'm your personal math tutor assistant.\\n&quot;);\n\n        \/\/ Create a new AI assistant instance using the OpenAI API\n        const assistant = await openai.beta.assistants.create({\n            name: &quot;Math Tutor&quot;,\n            instructions: &quot;You are a personal math tutor. Answer math questions.&quot;,\n            model: &quot;gpt-3.5-turbo-1106&quot;,\n        });\n\n        \/\/ Create a new conversation thread for interacting with the assistant\n        const thread = await openai.beta.threads.create(); \n\n        \/\/ Enter a loop to continue asking questions as long as the flag is true\n        let keepAsking = true;\n        while (keepAsking) {\n            \/\/ Prompt the user to input a question\n            const userQuestion = await askQuestion(&quot;\\nAssistant: What is your question?\\n\\nYou: &quot;);\n\n            \/\/ Print the assistant's thinking message\n            process.stdout.write(`\\nAssistant: Thinking...\\n`);\n\n            \/\/ Add the user's question to the conversation thread\n            await openai.beta.threads.messages.create(thread.id, { \n                role: &quot;user&quot;,\n                content: userQuestion,\n            });\n\n            \/\/ Initiate a run to get the assistant's response\n            const run = await openai.beta.threads.runs.create(thread.id, { \n                assistant_id: assistant.id,\n            });\n\n            \/\/ Use a polling mechanism to check if the run is completed\n            let runStatus;\n            do  { \n                await new Promise((resolve) =&gt; setTimeout(resolve, 2000));\n                runStatus = await openai.beta.threads.runs.retrieve(thread.id, run.id);\n            } while (runStatus.status !== &quot;completed&quot;)\n\n            \/\/ Retrieve the list of messages in the conversation thread\n            const messages = await openai.beta.threads.messages.list(thread.id); \n\n            \/\/ Filter and reverse the messages to get the assistant's response from the current run\n            const assistantMessages = messages.data \n                .filter(\n                    (message) =&gt; message.run_id === run.id &amp;&amp; message.role === &quot;assistant&quot;\n                ).reverse();\n\n            \/\/ Remove assistant's thinking message\n            process.stdout.moveCursor(0, -2);\n            process.stdout.clearLine(1);\n\n            \/\/ Loop through the assistant messages and print them\n            assistantMessages.forEach(assistantMessage =&gt; {\n                process.stdout.write(`\\nAssistant: ${assistantMessage.content[0].text.value}\\n`);\n            });\n\n            \/\/ Then ask if the user wants to ask another question\n            const continueAsking = await askQuestion(&quot;\\nAssistant: Do you want to ask another question? (yes\/no)\\n\\nYou: &quot;);\n            keepAsking = continueAsking.toLowerCase() === &quot;yes&quot;;\n\n            \/\/ Display an ending message if the user does not want to ask another question\n            if (!keepAsking) {\n                process.stdout.write(&quot;\\nAssistant: Thanks, I hope you learned something!\\n\\n\\n&quot;);\n            }\n        }\n\n        process.exit();\n    } catch (error) { \n        \/\/ Catch any potential errors thrown within the try block\n        console.error(error);\n    }\n}\n\n\/\/ Call the main function\nmain(); <\/pre><\/div>\n\n\n\n<p>This code, although put together swiftly and explained briefly in the comments, serves as a solid foundation. It has potential for enhancements, particularly in the polling mechanism, which is a crucial aspect of such interactive applications.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">3. Executing Your Code:<\/h4>\n\n\n\n<p>To run your script, open your terminal, navigate to the directory where your files are, and execute the <code>mathAssistant.js<\/code> file using the command:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}\">node mathAssistant.js<\/pre><\/div>\n\n\n\n<h4 class=\"wp-block-heading\">4. Recap<\/h4>\n\n\n\n<p>This is the result:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><a href=\"https:\/\/celilsemi.erkiner.com\/blog\/wp-content\/uploads\/2023\/11\/image-3.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"500\" src=\"https:\/\/celilsemi.erkiner.com\/blog\/wp-content\/uploads\/2023\/11\/image-3-1024x500.png\" alt=\"\" class=\"wp-image-379\" srcset=\"https:\/\/celilsemi.erkiner.com\/blog\/wp-content\/uploads\/2023\/11\/image-3-1024x500.png 1024w, https:\/\/celilsemi.erkiner.com\/blog\/wp-content\/uploads\/2023\/11\/image-3-300x146.png 300w, https:\/\/celilsemi.erkiner.com\/blog\/wp-content\/uploads\/2023\/11\/image-3-768x375.png 768w, https:\/\/celilsemi.erkiner.com\/blog\/wp-content\/uploads\/2023\/11\/image-3-1536x749.png 1536w, https:\/\/celilsemi.erkiner.com\/blog\/wp-content\/uploads\/2023\/11\/image-3-2048x999.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><\/figure>\n\n\n\n<p>To recap, this JavaScript code sets up a communication interface with the OpenAI service to create an AI assistant for answering math questions. Here&#8217;s a breakdown of the code:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Dependencies<\/strong>: The <code>dotenv<\/code> and <code>openai<\/code> packages are imported to manage environment variables and interact with the OpenAI API.<\/li>\n\n\n\n<li><strong>OpenAI Connection<\/strong>: An instance of the OpenAI client is created with the API key retrieved from the environment variables.<\/li>\n\n\n\n<li><strong>Asynchronous User Input<\/strong>: An asynchronous function <code>askQuestion<\/code> is defined to prompt the user for input. It uses <code>process.stdin.once<\/code> to capture the user&#8217;s response.<\/li>\n\n\n\n<li><strong>Main Function<\/strong>: The <code>main<\/code> function is defined as the entry point. It starts by greeting the user and then creates an AI assistant instance using the OpenAI API.<\/li>\n\n\n\n<li><strong>Conversation Thread<\/strong>: A new conversation thread is created for interacting with the AI assistant.<\/li>\n\n\n\n<li><strong>Asking Questions Loop<\/strong>: Inside a loop, the user is prompted to input a question, and the assistant&#8217;s thinking message is displayed. The user&#8217;s question is added to the conversation thread, and a run is initiated to get the assistant&#8217;s response.<\/li>\n\n\n\n<li><strong>Polling Mechanism<\/strong>: The code uses a polling mechanism to check if the run is completed before retrieving the assistant&#8217;s response.<\/li>\n\n\n\n<li><strong>Display Assistant&#8217;s Response<\/strong>: The assistant&#8217;s responses are filtered, reversed, and printed to the console.<\/li>\n\n\n\n<li><strong>User Interaction<\/strong>: After each interaction, the user is asked if they want to ask another question. The loop continues until the user indicates they do not want to ask another question.<\/li>\n\n\n\n<li><strong>Error Handling<\/strong>: Any errors that occur within the <code>try<\/code> block are caught and logged to the console.<\/li>\n\n\n\n<li><strong>Function Invocation<\/strong>: Finally, the <code>main<\/code> function is called to start the interaction with the AI assistant.<\/li>\n<\/ol>\n\n\n\n<p>The code demonstrates an interactive session where the user can ask math-related questions, and the AI assistant provides answers.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Whether you&#8217;re an experienced developer or a curious beginner, this hello world example is perfect for anyone who wants to dive into the capabilities of the Assistants API. <\/p>\n","protected":false},"author":1,"featured_media":379,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"set","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[54,8],"tags":[],"class_list":["post-374","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ai","category-back-end"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/celilsemi.erkiner.com\/blog\/wp-json\/wp\/v2\/posts\/374","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/celilsemi.erkiner.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/celilsemi.erkiner.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/celilsemi.erkiner.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/celilsemi.erkiner.com\/blog\/wp-json\/wp\/v2\/comments?post=374"}],"version-history":[{"count":7,"href":"https:\/\/celilsemi.erkiner.com\/blog\/wp-json\/wp\/v2\/posts\/374\/revisions"}],"predecessor-version":[{"id":387,"href":"https:\/\/celilsemi.erkiner.com\/blog\/wp-json\/wp\/v2\/posts\/374\/revisions\/387"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/celilsemi.erkiner.com\/blog\/wp-json\/wp\/v2\/media\/379"}],"wp:attachment":[{"href":"https:\/\/celilsemi.erkiner.com\/blog\/wp-json\/wp\/v2\/media?parent=374"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/celilsemi.erkiner.com\/blog\/wp-json\/wp\/v2\/categories?post=374"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/celilsemi.erkiner.com\/blog\/wp-json\/wp\/v2\/tags?post=374"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}