{"id":71735,"date":"2024-04-24T21:00:50","date_gmt":"2024-04-24T13:00:50","guid":{"rendered":"https:\/\/www.hongkiat.com\/blog\/?p=71735"},"modified":"2024-04-28T00:27:54","modified_gmt":"2024-04-27T16:27:54","slug":"create-chatbot-with-openai","status":"publish","type":"post","link":"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/","title":{"rendered":"How to Create a Personalized AI Assistant with OpenAI"},"content":{"rendered":"<p>Imagine having your own virtual assistant, kind of like J.A.R.V.I.S from the Iron Man movie, but personalized for your needs. This AI assistant is designed to help you tackle routine tasks or anything else you teach it to handle.<\/p>\n<p>In this article, we\u2019ll show you <a href=\"#demo\">an example<\/a> of what our trained AI assistant can achieve. We\u2019re going to create an AI that can provide basic insights into our site\u2019s content, assisting us in managing both the site and its content more effectively.<\/p>\n<p>To build this, we\u2019ll use three main stacks: <a rel=\"noopener nofollow\" target=\"_blank\" href=\"https:\/\/openai.com\/\">OpenAI<\/a>, <a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/langchain.com\">LangChain<\/a>, and <a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/nextjs.org\/\">Next.js<\/a>.<\/p>\n<h2>OpenAI<\/h2>\n<p>OpenAI, if you don\u2019t already know, is an AI research organization known for their <a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/chat.openai.com\/\">ChatGPT<\/a>, which can generate human-like responses. They also provide an API that allows developers to access these AI capabilities to build their own applications.<\/p>\n<p>To get your API key, you can sign up on the <a rel=\"noopener nofollow\" target=\"_blank\" href=\"https:\/\/platform.openai.com\/\">OpenAI Platform<\/a>. After signing up, you can create a key from the <strong>API keys<\/strong> section of your dashboard.<\/p>\n<figure><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/assets.hongkiat.com\/uploads\/create-chatbot-with-openai\/openai-apikey.jpg\" alt=\"A white dashboard showing the list of menu and a button to generate the API key\" width=\"720\" height=\"220\"><\/figure>\n<div class=\"sue-icon-text su-image-caption\" data-url=\"\" data-target=\"self\" style=\"min-height:34px;padding-left:36px;color:#333333\">\n<div class=\"sue-icon-text-icon\" style=\"color:#333333;font-size:24px;width:24px;height:24px\"><i class=\"sui sui-photo\" style=\"font-size:24px;color:#333333\"><\/i><\/div>\n<div class=\"sue-icon-text-content su-u-trim\" style=\"color:#333333\">API keys section on the OpenAI platform dashboard.<\/div>\n<div style=\"clear:both;height:0\"><\/div>\n<\/div>\n<p>Once you\u2019ve generated an API key, you have to put it in your computer as an environment variable and name it <code>OPENAI_API_KEY<\/code>. This is a standard name that libraries like <strong>OpenAI<\/strong> and <strong>LangChain<\/strong> look for, so you don\u2019t need to pass it manually later on.<\/p>\n<p>Do note that Windows, macOS, and Linux each have their own way to set an environment variable.<\/p>\n<h3>Windows<\/h3>\n<ol>\n<li>Right-click on \u201c<strong>This PC<\/strong>\u201d or \u201c<strong>My Computer<\/strong>\u201d and select \u201c<strong>Properties<\/strong>\u201c.<\/li>\n<li>Click on \u201c<strong>Advanced system settings<\/strong>\u201d on the left sidebar.<\/li>\n<li>In the System Properties window, click on the \u201c<strong>Environment Variables<\/strong>\u201d button.<\/li>\n<li>Under \u201c<strong>System variables<\/strong>\u201d or \u201c<strong>User variables<\/strong>\u201c, click \u201c<strong>New<\/strong>\u201d and enter the name, <code>OPENAI_API_KEY<\/code>, and value of the environment variable.<\/li>\n<\/ol>\n<h3>macOS and Linux<\/h3>\n<p>To set a permanent variable, add the following to your shell configuration file such as <code>~\/.bash_profile<\/code>, <code>~\/.bashrc<\/code>, <code>~\/.zshrc<\/code>.<\/p>\n<pre>\r\nexport OPENAI_API_KEY=value\r\n<\/pre>\n<h2>LangChain<\/h2>\n<p><strong>LangChain<\/strong> is a system that helps computers understand and work with human language. In our case, it provides tools that will help us convert text documents into numbers.<\/p>\n<p>You might wonder, <em>why do we need to do this?<\/em><\/p>\n<p>Basically, AI, machines, or computers are good at working with numbers but not with words, sentences, and their meanings. So we need to convert words into numbers.<\/p>\n<p>This process is called <strong>embedding<\/strong>.<\/p>\n<p>It makes it easier for computers to analyze and find patterns in language data, as well as helps to understand the semantics of the information they are given from a human language.<\/p>\n<figure><img decoding=\"async\" src=\"https:\/\/assets.hongkiat.com\/uploads\/create-chatbot-with-openai\/embedding-vectors-process.jpg\" alt=\"A diagram showing the process of embedding words 'fancy cars' into numbers from left to right\"><\/figure>\n<p>For example, let\u2019s say a user sends a query about \u201c<em>fancy cars<\/em>\u201c. Rather than trying to find the exact words from the information source, it would probably understand that you are trying to search for Ferrari, Maserati, Aston Martin, Mercedes Benz, etc.<\/p>\n<h2>Next.js<\/h2>\n<p>We need a framework to create a user interface so users can interact with our chatbot.<\/p>\n<p>In our case, Next.js has everything we need to get our chatbot up and running for the end-users. We will build the interface using a React.js UI library, <a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/ui.shadcn.com\/\">shadcn\/ui<\/a>. It has a route system for creating an API endpoint.<\/p>\n<p>It also provides <a rel=\"noopener nofollow\" target=\"_blank\" href=\"https:\/\/www.npmjs.com\/package\/ai\">an SDK<\/a> that will make it easier and quicker to build chat user interfaces.<\/p>\n<figure><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/assets.hongkiat.com\/uploads\/create-chatbot-with-openai\/shadcn.jpg\" alt=\"\" width=\"721\" height=\"480\"><\/figure>\n<h2>Data and Other Prerequisites<\/h2>\n<p>Ideally, we\u2019ll also need to prepare some data ready. These will be processed, stored in a Vector storage and sent to OpenAI to give more info for the prompt.<\/p>\n<p>In this example, to make it simpler, I\u2019ve made a JSON file with a list of title of a blog post. You can find them <a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/github.com\/hongkiat\/ai-assistant\/blob\/main\/data\">in the repository<\/a>. Ideally, you\u2019d want to retrieve this information directly from the database.<\/p>\n<p>I assume you have a fair understanding of working with JavaScript, React.js, and NPM because we\u2019ll use them to build our chatbot.<\/p>\n<p>Also, make sure you have Node.js installed on your computer. You can check if it\u2019s installed by typing:<\/p>\n<pre>node -v<\/pre>\n<p>If you don\u2019t have Node.js installed, you can follow the instructions on the <a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/nodejs.org\/en\/download\/\">official website<\/a>.<\/p>\n<h2>How\u2019s Everything Going to Work?<\/h2>\n<p>To make it easy to understand, here\u2019s a high-level overview of how everything is going to work:<\/p>\n<ol>\n<li>The user will input a question or query into the chatbot.<\/li>\n<li>LangChain will retrieve related documents of the user\u2019s query.<\/li>\n<li>Send the prompt, the query, and the related documents to the OpenAI API to get a response.<\/li>\n<li>Display the response to the user.<\/li>\n<\/ol>\n<p>Now that we have a high-level overview of how everything is going to work, let\u2019s get started!<\/p>\n<h2>Installing Dependencies<\/h2>\n<p>Let\u2019s start by installing the necessary packages to build the user interface for our chatbot. Type the following command:<\/p>\n<pre>\r\nnpx create-next-app@latest ai-assistant --typescript --tailwind --eslint\r\n<\/pre>\n<p>This command will install and set up Next.js with <strong>shadcn\/ui<\/strong>, TypeScript, <a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/tailwindcss.com\/\">Tailwind CSS<\/a>, and ESLint. It may ask you a few questions; in this case, it\u2019s best to select the default options.<\/p>\n<p>Once the installation is complete, navigate to the project directory:<\/p>\n<pre>\r\ncd ai-assistant\r\n<\/pre>\n<p>Next, we need to install a few additional dependencies, such as <a rel=\"noopener nofollow\" target=\"_blank\" href=\"https:\/\/www.npmjs.com\/package\/ai\">ai<\/a>, <a rel=\"noopener nofollow\" target=\"_blank\" href=\"https:\/\/www.npmjs.com\/package\/openai\">openai<\/a>, and <a rel=\"noopener nofollow\" target=\"_blank\" href=\"https:\/\/www.npmjs.com\/package\/langchain\">langchain<\/a>, which were not included in the previous command.<\/p>\n<pre>\r\nnpm i ai openai langchain @langchain\/openai remark-gfm\r\n<\/pre>\n<h2>Building the Chat Interface<\/h2>\n<p>To create the chat interface, we\u2019ll use some pre-built components from <strong>shadcn\/ui<\/strong> like the <a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/ui.shadcn.com\/docs\/components\/button\">button<\/a>, <a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/ui.shadcn.com\/docs\/components\/avatar\">avatar<\/a>, and <a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/ui.shadcn.com\/docs\/components\/input\">input<\/a>. Fortunately, adding these components is easy with <strong>shadcn\/ui<\/strong>. Just type:<\/p>\n<pre>\r\nnpx shadcn-ui@latest add scroll-area button avatar card input\r\n<\/pre>\n<p>This command will automatically pull and add the components to the <code>ui<\/code> directory.<\/p>\n<p>Next, let\u2019s make a new file named Chat.tsx in the src\/components directory. This file will hold our chat interface.<\/p>\n<p>We\u2019ll use the ai package to manage tasks such as capturing user input, sending queries to the API, and receiving responses from the AI.<\/p>\n<p>The OpenAI\u2019s response can be plain text, HTML, or Markdown. To format it into proper HTML, we\u2019ll use the <a rel=\"noopener nofollow\" target=\"_blank\" href=\"https:\/\/www.npmjs.com\/package\/remark-gfm\">remark-gfm<\/a> package.<\/p>\n<p>We\u2019ll also need to display avatars within the Chat interface. For this tutorial, I\u2019m using <a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/www.avatartion.com\/\">Avatartion<\/a> to generate avatars for both the AI and the user. These avatars are stored in the <code>public<\/code> directory.<\/p>\n<p>Below is the code we\u2019ll add to this file.<\/p>\n<pre>\r\n'use client';\r\n\r\nimport { Avatar, AvatarFallback, AvatarImage } from '@\/ui\/avatar';\r\nimport { Button } from '@\/ui\/button';\r\nimport {\r\n    Card,\r\n    CardContent,\r\n    CardFooter,\r\n    CardHeader,\r\n    CardTitle,\r\n} from '@\/ui\/card';\r\nimport { Input } from '@\/ui\/input';\r\nimport { ScrollArea } from '@\/ui\/scroll-area';\r\nimport { useChat } from 'ai\/react';\r\nimport { Send } from 'lucide-react';\r\nimport { FunctionComponent, memo } from 'react';\r\nimport { ErrorBoundary } from 'react-error-boundary';\r\nimport ReactMarkdown, { Options } from 'react-markdown';\r\nimport remarkGfm from 'remark-gfm';\r\n\r\n\/**\r\n * Memoized ReactMarkdown component.\r\n * The component is memoized to prevent unnecessary re-renders.\r\n *\/\r\nconst MemoizedReactMarkdown: FunctionComponent&lt;Options&gt; = memo(\r\n    ReactMarkdown,\r\n    (prevProps, nextProps) =>\r\n        prevProps.children === nextProps.children &&\r\n        prevProps.className === nextProps.className\r\n);\r\n\r\n\/**\r\n * Represents a chat component that allows users to interact with a chatbot.\r\n * The component displays a chat interface with messages exchanged between the user and the chatbot.\r\n * Users can input their questions and receive responses from the chatbot.\r\n *\/\r\nexport const Chat = () =&gt; {\r\n    const { handleInputChange, handleSubmit, input, messages } = useChat({\r\n        api: '\/api\/chat',\r\n    });\r\n\r\n    return (\r\n        &lt;Card className=\"w-full max-w-3xl min-h-[640px] grid gap-3 grid-rows-[max-content,1fr,max-content]\"&gt;\r\n            &lt;CardHeader className=\"row-span-1\"&gt;\r\n                &lt;CardTitle&gt;AI Assistant&lt;\/CardTitle&gt;\r\n            &lt;\/CardHeader&gt;\r\n            &lt;CardContent className=\"h-full row-span-2\"&gt;\r\n                &lt;ScrollArea className=\"h-full w-full\"&gt;\r\n                    {messages.map((message) =&gt; {\r\n                        return (\r\n                            &lt;div\r\n                                className=\"flex gap-3 text-slate-600 text-sm mb-4\"\r\n                                key={message.id}\r\n                            &gt;\r\n                                {message.role === 'user' && (\r\n                                    &lt;Avatar&gt;\r\n                                        &lt;AvatarFallback&gt;U&lt;\/AvatarFallback&gt;\r\n                                        &lt;AvatarImage src=\"\/user.png\" \/&gt;\r\n                                    &lt;\/Avatar&gt;\r\n                                )}\r\n                                {message.role === 'assistant' && (\r\n                                    &lt;Avatar&gt;\r\n                                        &lt;AvatarImage src=\"\/kovi.png\" \/&gt;\r\n                                    &lt;\/Avatar&gt;\r\n                                )}\r\n                                &lt;p className=\"leading-relaxed\"&gt;\r\n                                    &lt;span className=\"block font-bold text-slate-700\"&gt;\r\n                                        {message.role === 'user' ? 'User' : 'AI'}\r\n                                    &lt;\/span&gt;\r\n                                    &lt;ErrorBoundary\r\n                                        fallback={\r\n                                            &lt;div className=\"prose prose-neutral\"&gt;\r\n                                                {message.content}\r\n                                            &lt;\/div&gt;\r\n                                        }\r\n                                    &gt;\r\n                                        &lt;MemoizedReactMarkdown\r\n                                            className=\"prose prose-neutral prose-sm\"\r\n                                            remarkPlugins={[remarkGfm]}\r\n                                        &gt;\r\n                                            {message.content}\r\n                                        &lt;\/MemoizedReactMarkdown&gt;\r\n                                    &lt;\/ErrorBoundary&gt;\r\n                                &lt;\/p&gt;\r\n                            &lt;\/div&gt;\r\n                        );\r\n                    })}\r\n                &lt;\/ScrollArea&gt;\r\n            &lt;\/CardContent&gt;\r\n            &lt;CardFooter className=\"h-max row-span-3\"&gt;\r\n                &lt;form className=\"w-full flex gap-2\" onSubmit={handleSubmit}&gt;\r\n                    &lt;Input\r\n                        maxLength={1000}\r\n                        onChange={handleInputChange}\r\n                        placeholder=\"Your question...\"\r\n                        value={input}\r\n                    \/&gt;\r\n                    &lt;Button aria-label=\"Send\" type=\"submit\"&gt;\r\n                        &lt;Send size={16} \/&gt;\r\n                    &lt;\/Button&gt;\r\n                &lt;\/form&gt;\r\n            &lt;\/CardFooter&gt;\r\n        &lt;\/Card&gt;\r\n    );\r\n};\r\n<\/pre>\n<p>Let\u2019s check out the UI. First, we need to enter the following command to start the Next.js localhost environment:<\/p>\n<pre>npm run dev<\/pre>\n<p>By default, the Next.js localhost environment runs at <code>localhost:3000<\/code>. Here\u2019s how our chatbot interface will appear in the browser:<\/p>\n<figure> <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/assets.hongkiat.com\/uploads\/create-chatbot-with-openai\/ui-interface.jpg\" alt=\"\" width=\"720\" height=\"480\"><\/figure>\n<h2>Setting up the API endpoint<\/h2>\n<p>Next, we need to set up the API endpoint that the UI will use when the user submits their query. To do this, we create a new file named <code>route.ts<\/code> in the <code>src\/app\/api\/chat<\/code> directory. Below is the code that goes into the file.<\/p>\n<pre>\r\nimport { readData } from '@\/lib\/data';\r\nimport { OpenAIEmbeddings } from '@langchain\/openai';\r\nimport { OpenAIStream, StreamingTextResponse } from 'ai';\r\nimport { Document } from 'langchain\/document';\r\nimport { MemoryVectorStore } from 'langchain\/vectorstores\/memory';\r\nimport OpenAI from 'openai';\r\n\r\n\/**\r\n    * Create a vector store from a list of documents using OpenAI embedding.\r\n    *\/\r\nconst createStore = () => {\r\n    const data = readData();\r\n\r\n    return MemoryVectorStore.fromDocuments(\r\n        data.map((title) => {\r\n            return new Document({\r\n                pageContent: `Title: ${title}`,\r\n            });\r\n        }),\r\n        new OpenAIEmbeddings()\r\n    );\r\n};\r\nconst openai = new OpenAI();\r\n\r\nexport async function POST(req: Request) {\r\n    const { messages } = (await req.json()) as {\r\n        messages: { content: string; role: 'assistant' | 'user' }[];\r\n    };\r\n    const store = await createStore();\r\n    const results = await store.similaritySearch(messages[0].content, 100);\r\n    const questions = messages\r\n        .filter((m) => m.role === 'user')\r\n        .map((m) => m.content);\r\n    const latestQuestion = questions[questions.length - 1] || '';\r\n    const response = await openai.chat.completions.create({\r\n        messages: [\r\n            {\r\n                content: `You're a helpful assistant. You're here to help me with my questions.`,\r\n                role: 'assistant',\r\n            },\r\n            {\r\n                content: `\r\n                Please answer the following question using the provided context.\r\n                If the context is not provided, please simply say that you're not able to answer\r\n                the question.\r\n\r\n            Question:\r\n                ${latestQuestion}\r\n\r\n            Context:\r\n                ${results.map((r) => r.pageContent).join('\\n')}\r\n                `,\r\n                role: 'user',\r\n            },\r\n        ],\r\n        model: 'gpt-4',\r\n        stream: true,\r\n        temperature: 0,\r\n    });\r\n    const stream = OpenAIStream(response);\r\n\r\n    return new StreamingTextResponse(stream);\r\n}\r\n<\/pre>\n<p>Let\u2019s break down some important parts of the code to understand what\u2019s happening, as this code is crucial for making our chatbot work.<\/p>\n<p>First, the following code enables the endpoint to receive a POST request. It takes the <code>messages<\/code> argument, which is automatically constructed by the <code>ai<\/code> package running on the front-end.<\/p>\n<pre>\r\nexport async function POST(req: Request) {\r\n    const { messages } = (await req.json()) as {\r\n        messages: { content: string; role: 'assistant' | 'user' }[];\r\n    };\r\n}\r\n<\/pre>\n<p>In this section of the code, we process the JSON file, and store them in a vector store.<\/p>\n<pre>\r\nconst createStore = () => {\r\n    const data = readData();\r\n\r\n    return MemoryVectorStore.fromDocuments(\r\n        data.map((title) => {\r\n            return new Document({\r\n                pageContent: `Title: ${title}`,\r\n            });\r\n        }),\r\n        new OpenAIEmbeddings()\r\n    );\r\n};\r\n<\/pre>\n<p>For the sake of simplicity in this tutorial, we store the vector in memory. Ideally, you would need to store it in a Vector database. There are several options to choose from, such as:<\/p>\n<ul>\n<li><a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/cassandra.apache.org\/_\/index.html\">Apache Cassandra<\/a><\/li>\n<li><a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/www.elastic.co\/elasticsearch\">ElasticSearch<\/a><\/li>\n<li><a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/www.mongodb.com\/atlas\/database\">MongoDB Atlas<\/a><\/li>\n<li><a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/opensearch.org\">OpenSearch<\/a><\/li>\n<li><a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/redis.io\">Redis<\/a><\/li>\n<\/ul>\n<p>Then we retrieve of the relevant piece from the document based on the user query from it.<\/p>\n<pre>\r\nconst store = await createStore();\r\nconst results = await store.similaritySearch(messages[0].content, 100);\r\n<\/pre>\n<p>Finally, we send the user\u2019s query and the related documents to the OpenAI API to get a response, and then return the response to the user. In this tutorial, we use the GPT-4 model, which is currently the latest and most powerful model in OpenAI.<\/p>\n<pre>\r\nconst latestQuestion = questions[questions.length - 1] || '';\r\nconst response = await openai.chat.completions.create({\r\n    messages: [\r\n        {\r\n            content: `You're a helpful assistant. You're here to help me with my questions.`,\r\n            role: 'assistant',\r\n        },\r\n        {\r\n            content: `\r\n            Please answer the following question using the provided context.\r\n            If the context is not provided, please simply say that you're not able to answer\r\n            the question.\r\n\r\n        Question:\r\n            ${latestQuestion}\r\n\r\n        Context:\r\n            ${results.map((r) => r.pageContent).join('\\n')}\r\n            `,\r\n            role: 'user',\r\n        },\r\n    ],\r\n    model: 'gpt-4',\r\n    stream: true,\r\n    temperature: 0,\r\n});\r\n<\/pre>\n<p>We use a simple very prompt. We first tell OpenAI to evaluate the user\u2019s query and respond to user with the provided context. We also set the latest model available in OpenAI, <code>gpt-4<\/code> and set the <code>temperature<\/code> to <code>0<\/code>. Our goal is to ensure that the AI only responds within the scope of the context, instead of being creative which can often lead to <strong><a rel=\"noopener\" target=\"_blank\" href=\"https:\/\/cloud.google.com\/discover\/what-are-ai-hallucinations\">hallucination<\/a><\/strong>.<\/p>\n<p id=\"demo\">And that\u2019s it. Now, we can try to chat with the chatbot; our virtual personal assistant.<\/p>\n<p><video playsinline muted src=\"https:\/\/assets.hongkiat.com\/uploads\/create-chatbot-with-openai\/ai-demo.mov\" autoplay loop controls style=\"width: 100%; height: auto;\">\n<\/video><\/p>\n<h2>Wrapping Up<\/h2>\n<p>We\u2019ve just built a simple chatbot! There\u2019s room to make it more advanced, certainly. As mentioned in this tutorial, if you plan to use it in production, you should store your vector data in a proper database instead of in memory. You might also want to add more data to provide better context for answering user queries. You may also try tweaking the prompt to improve the AI\u2019s response.<\/p>\n<p>Overall, I hope this helps you get started with building your next AI-powered application.<\/p>","protected":false},"excerpt":{"rendered":"<p>We&#8217;ve created an AI assistant to help answer basic queries about our blog posts. Here&#8217;s how we did it.<\/p>\n","protected":false},"author":113,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[3392],"tags":[3545],"topic":[],"class_list":["entry-content","is-maxi"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v22.8 (Yoast SEO v27.6) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>How to Create a Personalized AI Assistant with OpenAI - Hongkiat<\/title>\n<meta name=\"description\" content=\"We&#039;ve created an AI assistant to help answer basic queries about our blog posts. Here&#039;s how we did it.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Create a Personalized AI Assistant with OpenAI\" \/>\n<meta property=\"og:description\" content=\"We&#039;ve created an AI assistant to help answer basic queries about our blog posts. Here&#039;s how we did it.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/\" \/>\n<meta property=\"og:site_name\" content=\"Hongkiat\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/hongkiatcom\" \/>\n<meta property=\"article:published_time\" content=\"2024-04-24T13:00:50+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-27T16:27:54+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/assets.hongkiat.com\/uploads\/create-chatbot-with-openai\/openai-apikey.jpg\" \/>\n<meta name=\"author\" content=\"Thoriq Firdaus\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@tfirdaus\" \/>\n<meta name=\"twitter:site\" content=\"@hongkiat\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Thoriq Firdaus\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/create-chatbot-with-openai\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/create-chatbot-with-openai\\\/\"},\"author\":{\"name\":\"Thoriq Firdaus\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#\\\/schema\\\/person\\\/e7948c7a175d211496331e4b6ce55807\"},\"headline\":\"How to Create a Personalized AI Assistant with OpenAI\",\"datePublished\":\"2024-04-24T13:00:50+00:00\",\"dateModified\":\"2024-04-27T16:27:54+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/create-chatbot-with-openai\\\/\"},\"wordCount\":1457,\"publisher\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/create-chatbot-with-openai\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/assets.hongkiat.com\\\/uploads\\\/create-chatbot-with-openai\\\/openai-apikey.jpg\",\"keywords\":[\"Artificial Intelligence\"],\"articleSection\":[\"Coding\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/create-chatbot-with-openai\\\/\",\"url\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/create-chatbot-with-openai\\\/\",\"name\":\"How to Create a Personalized AI Assistant with OpenAI - Hongkiat\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/create-chatbot-with-openai\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/create-chatbot-with-openai\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/assets.hongkiat.com\\\/uploads\\\/create-chatbot-with-openai\\\/openai-apikey.jpg\",\"datePublished\":\"2024-04-24T13:00:50+00:00\",\"dateModified\":\"2024-04-27T16:27:54+00:00\",\"description\":\"We've created an AI assistant to help answer basic queries about our blog posts. Here's how we did it.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/create-chatbot-with-openai\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/create-chatbot-with-openai\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/create-chatbot-with-openai\\\/#primaryimage\",\"url\":\"https:\\\/\\\/assets.hongkiat.com\\\/uploads\\\/create-chatbot-with-openai\\\/openai-apikey.jpg\",\"contentUrl\":\"https:\\\/\\\/assets.hongkiat.com\\\/uploads\\\/create-chatbot-with-openai\\\/openai-apikey.jpg\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/create-chatbot-with-openai\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to Create a Personalized AI Assistant with OpenAI\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/\",\"name\":\"Hongkiat\",\"description\":\"Tech and Design Tips\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#organization\",\"name\":\"Hongkiat.com\",\"url\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/wp-content\\\/uploads\\\/hkdc-logo-rect-yoast.jpg\",\"contentUrl\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/wp-content\\\/uploads\\\/hkdc-logo-rect-yoast.jpg\",\"width\":1200,\"height\":799,\"caption\":\"Hongkiat.com\"},\"image\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/hongkiatcom\",\"https:\\\/\\\/x.com\\\/hongkiat\",\"https:\\\/\\\/www.pinterest.com\\\/hongkiat\\\/\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#\\\/schema\\\/person\\\/e7948c7a175d211496331e4b6ce55807\",\"name\":\"Thoriq Firdaus\",\"description\":\"Thoriq is a writer for Hongkiat.com with a passion for web design and development. He is the author of Responsive Web Design by Examples, where he covered his best approaches in developing responsive websites quickly with a framework.\",\"sameAs\":[\"https:\\\/\\\/thoriq.com\",\"https:\\\/\\\/x.com\\\/tfirdaus\"],\"jobTitle\":\"Web Developer\",\"url\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/author\\\/thoriq\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"How to Create a Personalized AI Assistant with OpenAI - Hongkiat","description":"We've created an AI assistant to help answer basic queries about our blog posts. Here's how we did it.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/","og_locale":"en_US","og_type":"article","og_title":"How to Create a Personalized AI Assistant with OpenAI","og_description":"We've created an AI assistant to help answer basic queries about our blog posts. Here's how we did it.","og_url":"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/","og_site_name":"Hongkiat","article_publisher":"https:\/\/www.facebook.com\/hongkiatcom","article_published_time":"2024-04-24T13:00:50+00:00","article_modified_time":"2024-04-27T16:27:54+00:00","og_image":[{"url":"https:\/\/assets.hongkiat.com\/uploads\/create-chatbot-with-openai\/openai-apikey.jpg","type":"","width":"","height":""}],"author":"Thoriq Firdaus","twitter_card":"summary_large_image","twitter_creator":"@tfirdaus","twitter_site":"@hongkiat","twitter_misc":{"Written by":"Thoriq Firdaus","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/#article","isPartOf":{"@id":"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/"},"author":{"name":"Thoriq Firdaus","@id":"https:\/\/www.hongkiat.com\/blog\/#\/schema\/person\/e7948c7a175d211496331e4b6ce55807"},"headline":"How to Create a Personalized AI Assistant with OpenAI","datePublished":"2024-04-24T13:00:50+00:00","dateModified":"2024-04-27T16:27:54+00:00","mainEntityOfPage":{"@id":"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/"},"wordCount":1457,"publisher":{"@id":"https:\/\/www.hongkiat.com\/blog\/#organization"},"image":{"@id":"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/#primaryimage"},"thumbnailUrl":"https:\/\/assets.hongkiat.com\/uploads\/create-chatbot-with-openai\/openai-apikey.jpg","keywords":["Artificial Intelligence"],"articleSection":["Coding"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/","url":"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/","name":"How to Create a Personalized AI Assistant with OpenAI - Hongkiat","isPartOf":{"@id":"https:\/\/www.hongkiat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/#primaryimage"},"image":{"@id":"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/#primaryimage"},"thumbnailUrl":"https:\/\/assets.hongkiat.com\/uploads\/create-chatbot-with-openai\/openai-apikey.jpg","datePublished":"2024-04-24T13:00:50+00:00","dateModified":"2024-04-27T16:27:54+00:00","description":"We've created an AI assistant to help answer basic queries about our blog posts. Here's how we did it.","breadcrumb":{"@id":"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/#primaryimage","url":"https:\/\/assets.hongkiat.com\/uploads\/create-chatbot-with-openai\/openai-apikey.jpg","contentUrl":"https:\/\/assets.hongkiat.com\/uploads\/create-chatbot-with-openai\/openai-apikey.jpg"},{"@type":"BreadcrumbList","@id":"https:\/\/www.hongkiat.com\/blog\/create-chatbot-with-openai\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.hongkiat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"How to Create a Personalized AI Assistant with OpenAI"}]},{"@type":"WebSite","@id":"https:\/\/www.hongkiat.com\/blog\/#website","url":"https:\/\/www.hongkiat.com\/blog\/","name":"Hongkiat","description":"Tech and Design Tips","publisher":{"@id":"https:\/\/www.hongkiat.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.hongkiat.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.hongkiat.com\/blog\/#organization","name":"Hongkiat.com","url":"https:\/\/www.hongkiat.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.hongkiat.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/www.hongkiat.com\/blog\/wp-content\/uploads\/hkdc-logo-rect-yoast.jpg","contentUrl":"https:\/\/www.hongkiat.com\/blog\/wp-content\/uploads\/hkdc-logo-rect-yoast.jpg","width":1200,"height":799,"caption":"Hongkiat.com"},"image":{"@id":"https:\/\/www.hongkiat.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/hongkiatcom","https:\/\/x.com\/hongkiat","https:\/\/www.pinterest.com\/hongkiat\/"]},{"@type":"Person","@id":"https:\/\/www.hongkiat.com\/blog\/#\/schema\/person\/e7948c7a175d211496331e4b6ce55807","name":"Thoriq Firdaus","description":"Thoriq is a writer for Hongkiat.com with a passion for web design and development. He is the author of Responsive Web Design by Examples, where he covered his best approaches in developing responsive websites quickly with a framework.","sameAs":["https:\/\/thoriq.com","https:\/\/x.com\/tfirdaus"],"jobTitle":"Web Developer","url":"https:\/\/www.hongkiat.com\/blog\/author\/thoriq\/"}]}},"jetpack_featured_media_url":"https:\/\/","jetpack_shortlink":"https:\/\/wp.me\/p4uxU-iF1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/posts\/71735","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/users\/113"}],"replies":[{"embeddable":true,"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/comments?post=71735"}],"version-history":[{"count":4,"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/posts\/71735\/revisions"}],"predecessor-version":[{"id":71752,"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/posts\/71735\/revisions\/71752"}],"wp:attachment":[{"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/media?parent=71735"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/categories?post=71735"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/tags?post=71735"},{"taxonomy":"topic","embeddable":true,"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/topic?post=71735"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}