Creating ChatGPT Apps with JavaScript: A Hands-on Guide for AI Applications with OpenAI APIs / Создание приложений ChatGPT с помощью JavaScript: Практическое руководство по приложениям искусственного интеллекта с открытыми API Год издания: 2025 Автор: Hopkins Bruce Jr., Hopkins Bruce Sr. / Хопкинс Брюс младший, Хопкинс Брюс старший Издательство: Apress Media LLC ISBN: 979-8-8688-1221-7 Язык: Английский Формат: PDF Качество: Издательский макет или текст (eBook) Количество страниц: 230 Описание: Transform your JavaScript expertise through the power of Open AI API models using “Creating ChatGPT Apps with JavaScript.” This book will guide JavaScript developers to build smart applications while providing tangible knowledge of OpenAI’s API for text summarization, creating transcripts from audio files, generating images, and running models locally on your machine. Through hands-on projects and code examples, readers will discover how to build AI-powered apps from scratch, such as using embeddings to train a Discord bot to answer customers’ questions in multiple languages. Readers will also learn to dictate text for writing articles or blogs with a localized integration of Whisper and generate hero images with Dall-E. What’s more, in the final chapter of this book, you’ll be able to maximize productivity by creating a Smart Assistant like Alexa or Siri with JavaScript and the new Raspberry Pi 5. From seasoned developers to newcomers, this book offers something for everyone. Not only will readers learn to build apps with ChatGPT and JavaScript, but they will also learn best practices for prompt engineering. They’ll understand how AI models can enhance workplace efficiency and utilize natural language processing (NLP) to make interactions with applications feel…well, natural. The end result is expert knowledge in leveraging ChatGPT programmatically and incorporating the technology into diverse applications. What You Will Learn: Gain a deeper understanding of ChatGPT and how OpenAI’s models work, and different ways to implement each of their various features. Authenticate with ChatGPT and OpenAI’s API and learn to send prompts with best practices with prompt engineering. Streamline productivity and content creation by leveraging transcription generation for dictation and image generation for creating hero images. Stay ahead of the game by incorporating different new features of OpenAI’s API and understanding more complex concepts like using GPT-4 to train a Discord bot with an FAQ to assist with multilingual tech support. Who This Book is for: This book is written for JavaScript developers and hobbyists that want to use OpenAI and ChatGPT to create intelligent applications and streamline productivity. No prior experience with ChatGPT or OpenAI APIs is required. Расширьте свои знания в области JavaScript с помощью моделей Open AI API, используя раздел “Создание приложений ChatGPT с помощью JavaScript”. Эта книга поможет разработчикам JavaScript создавать интеллектуальные приложения, предоставляя при этом практические знания API OpenAI для обобщения текста, создания расшифровок из аудиофайлов, генерации изображений и запуска моделей локально на вашем компьютере. Благодаря практическим проектам и примерам кода читатели узнают, как создавать приложения на базе искусственного интеллекта с нуля, например, с помощью встраиваний обучить бота Discord отвечать на вопросы клиентов на нескольких языках. Читатели также научатся диктовать текст для написания статей или блогов с помощью локализованной интеграции Whisper и создавать образы героев с помощью Dall-E. Более того, в последней главе этой книги вы сможете повысить производительность, создав интеллектуального помощника, такого как Alexa или Siri, с помощью JavaScript и нового Raspberry Pi 5. В этой книге найдется занятие для всех - от опытных разработчиков до новичков. Читатели не только научатся создавать приложения с помощью ChatGPT и JavaScript, но и познакомятся с лучшими практиками оперативного проектирования. Они поймут, как модели искусственного интеллекта могут повысить эффективность работы на рабочем месте и использовать обработку естественного языка (NLP), чтобы сделать взаимодействие с приложениями более естественным. Конечным результатом являются экспертные знания по программному использованию ChatGPT и внедрению технологии в различные приложения. Что Вы узнаете: Получите более глубокое представление о ChatGPT и о том, как работают модели OpenAI, а также о различных способах реализации каждой из их функций. Пройдите аутентификацию с помощью ChatGPT и API OpenAI и научитесь отправлять запросы с использованием лучших практик с помощью prompt engineering. Оптимизируйте производительность и создание контента, используя генерацию транскрипции для диктовки и генерацию изображений для создания образов героев. Будьте на шаг впереди, внедряя различные новые функции API OpenAI и вникая в более сложные концепции, например, используя GPT-4 для обучения бота Discord, а также раздел часто задаваемых вопросов, помогающий с многоязычной технической поддержкой. Для кого предназначена эта книга: Эта книга написана для разработчиков JavaScript и любителей, которые хотят использовать OpenAI и ChatGPT для создания интеллектуальных приложений и повышения производительности. Предыдущий опыт работы с API-интерфейсами ChatGPT или OpenAI не требуется.
Примеры страниц (скриншоты)
Оглавление
About the Authors ......................................................................................xi About the Technical Reviewer .......................................................................xiii Chapter 1: Introducing ChatGPT for JavaScript Developers ...............................1 Who Is This Book For? .................................................................................1 Chapter Overview .......................................................................................2 Download the Code Now! .............................................................................2 So, What Exactly Is ChatGPT and Why Do I Need to Use the OpenAI APIs? .........3 Regex vs. ChatGPT – Fight! ..........................................................................6 Analysis Question #1: Who Didn’t Get Any Ice Cream and Why? .......................7 Analysis Question #2: Which Kid Was Probably Left Sad? .................................9 Let’s Unlearn Some Words in Order to Learn More About the ChatGPT API ..........10 Models. Models? Models!!! ............................................................................10 When We Talk About Tokens, Don’t Think About Access Tokens ..........................15 Temperature Is All About Creativity ................................................................16 Getting Started with the OpenAI Playground ......................................................17 1. System Message .......................................................................................19 2. User ...........................................................................................................20 3. Assistant (Optional) ....................................................................................20 4. + (Optional) ................................................................................................21 5. Code (Optional) ..........................................................................................21 6. Model (Optional) ........................................................................................21 7. Temperature (Optional) ..............................................................................22 8. Max Tokens (Optional) ...............................................................................22 Try It Now! Experimenting with the “System” Role ............................................22 Conclusion ..........................................................................................................23 Chapter 2: Using ChatGPT As Your JavaScript Pair-Programmer ..........................25 Chapter Overview ................................................................................................25 You Have Node.js Already Installed, Right? .........................................................26 Installing (or Updating) the OpenAI Node.js Library with npm ............................26 Three Ways to Set Your API Key ..........................................................................27 Option #1: Setting a System-Wide Environment Variable ...................................27 Option #2: Creating a .env File ......................................................................30 Option #3: Hard Coding the API Key Directly in Your Application (Take with Caution) ........................................................................................31 Creating Your First JavaScript ChatGPT App: list-models ...................................32 Using openai.models.list( ) to Get a List of Available Models ..............................32 Handling the Response ..................................................................................33 Using Your API Key to Get a List of Available Models with the OpenAI API ..........34 Wait, How Many Tokens Are in My Prompt? ........................................................36 Using ChatGPT As a Pair-Programmer to Build a Weather Application ...............38 Setting Up the Prompt ...................................................................................38 Creating a Weather App with the AccuWeather API .......................................42 Refining Our Prompt with Prompt Engineering .............................................46 Using ChatGPT As a Pair-Programmer to Build an Application That Estimates Distance and Arrival Time ...................................................................51 Creating a Project with Google Maps Platform API ........................................52 Approach #1: Using ChatGPT to Take a cURL Command and Convert It to JavaScript ......................................................................................................59 Approach #2: Using ChatGPT to Avoid Reading a Lot of Documentation ...............65 Conclusion ..........................................................................................................69 Chapter 3: Creating a Basic ChatGPT Client in JavaScript ...................................71 Creating Our ChatGPT Client Application in JavaScript .......................................71 Resist the Urge to Put Your API Key in a Web Application! ..................................73 Using OpenAI.chat.completions.create() to Send Messages to ChatGPT ............74 Examining the Method Parameters ...............................................................74 There Are Four Types of Messages .....................................................................81 System Message (Array) ................................................................................81 User Message (Array) ....................................................................................82 Assistant Message (Array) .............................................................................83 Tool Message (Array) .....................................................................................84 Running Our Basic ChatGPT Client ......................................................................85 Handling the Response (ChatCompletion) .....................................................87 ChatCompletionMessage ...............................................................................89 Conclusion ..........................................................................................................89 Chapter 4: Using AI in the Enterprise! Creating a Text Summarizer for Slack Messages .....................................................................91 So, What Is Prompt Engineering? ........................................................................92 ChatGPT Is Here to Take Away Everyone’s Jobs (Not Really) ..............................92 Examining a Real-World Problem: Customer Support for a Software Company ..............................................................................................93 Prompt Engineering 101: Text Summarization ....................................................97 Prompt #1: “tl;dr” ..........................................................................................98 Prompt #2: “Explain This in 3 Sentences or Less” ........................................99 Prompt #3: “I’m a Manager. Explain to Me What Happened” ........................100 Prompt #4: “Give Me Suggestions on Next Steps” ......................................103 Let’s Talk About Real Prompt Engineering ...................................................105 Registering a Slack Bot App ..............................................................................106 Specifying What Your Bot Can (and Can’t) Do by Setting the Scope ...............109 Confirming Your Settings .............................................................................110 Viewing the OAuth & Permissions Page ......................................................111 Installing Your Slack Bot App to Your Workspace ........................................112 Getting Your Slack Bot (Access) Token ........................................................114 Inviting Your Bot to Your Channel .................................................................114 Finding the Channel ID of Your Channel ............................................................115 Using Your Slack Bot App to Automatically Grab Messages from a Channel ...........116 Programmatically Reading Messages from Slack ...............................................116 Exercises Left for the Reader ............................................................................119 Conclusion ........................................................................................................120 Chapter 5: Multimodal AI: Creating a Podcast Visualizer with Whisper and DALL·E 3 ..........................................................................121 Introducing the Whisper Model by OpenAI ........................................................124 Features and Limitations of the Whisper Model ...............................................126 Using OpenAI.audio.transcriptions.create() to Transcribe Audio .......................130 Examining the Method Parameters .............................................................130 Creating a Utility App to Split Audio Files ..........................................................132 Creating the Audio Transcriber with Whisper ....................................................136 Having a Little Fun and Trying Things Out with a Podcast ................................138 Going Meta: Prompt Engineering gpt-4o-mini to Write a Prompt for DALL·E ....140 Using OpenAI.openai.images.generate() to Create Images ...............................141 Create Image (JSON) ...................................................................................142 Handling the Response ................................................................................144 Image ...........................................................................................................144 Creating the Images with the DALL·E Model .....................................................144 Visualizing the Podcast .....................................................................................146 DALL·E Prompt Engineering and Best Practices ...............................................147 DALL·E Golden Rule #1: Get Familiar with the Types of Images That DALL·E Can Generate ...........................................................................148 DALL·E Golden Rule #2: Be Descriptive with What You Want in the Foreground and Background .......................................................................149 Conclusion ........................................................................................................150 Exercises Left for the Reader ............................................................................151 Chapter 6: Creating an Automated Community Manager Bot with Discord and JavaScript ..........................................................................153 Choosing Discord as Your Community Platform ................................................154 Creating a More Advanced Bot Than Our Slack Bot ..........................................155 Creating a More Advanced Bot Than Any Typical Discord Bot ...........................155 Understanding the Roles for the Bots ...............................................................156 Our Example Bank: Crook’s Bank ......................................................................157 First Things First: Create Your Own Discord Server ..........................................158 Create the Q&A Channel ....................................................................................159 Registering a New Discord Bot App with Discord .............................................161 Specifying General Info for the Bot ...................................................................162 Specifying OAuth2 Parameters for the Bot .......................................................163 Invite Your Bot to Your Server ............................................................................165 Getting the Discord ID Token for Your Bot and Setting the Gateway Intents .....167 Creating a Q&A Bot App in JavaScript to Answer Questions from a Channel .....170 Creating the Discord Client ..........................................................................173 Listening for New Messages in Our Preferred Discord Channel .......................173 Success! Running Your First Discord Bot ....................................................174 Streamlining the Process of Registering Our Next Discord Bot App .................175 Registering a New Discord Bot App with Discord ..........................................175 Specifying General Info for the Bot ..............................................................176 Specifying OAuth2 Parameters for the Bot ..................................................176 Invite Your Bot to Your Server ......................................................................177 Getting the Discord ID Token for Your Bot and Setting the Gateway Intents ...........................................................................................177 Creating the Next Discord Bot, the Content Moderator .....................................177 Handling Messages Sent to the Discord Server ................................................179 Success Again! Running Your Second Discord Bot, the Content Moderator .......................................................................................179 Conclusion ........................................................................................................180 Exercises Left for the Reader ............................................................................181 Chapter 7: Adding Intelligence to Our Discord Bots, Part 1: Improving Our Q&A Bot .....................................................................183 Making Our Tech Support Bot More Intelligent .................................................184 Important Changes to Note from the Previous Version of the Tech Support Bot .......................................................................................................188 Updates to the Newly Named Function, discordClient.on() .................................189 Analyzing Our ChatGPT Client, chatGPTClient.js ...............................................190 Running Our Intelligent Q&A Bot ..................................................................192 We Have a Monumental Achievement… with One Slight Flaw ...........................195 Update the System Message to ChatGPT and Let’s Try Again ...........................196 Conclusion ........................................................................................................198 Chapter 8: Adding Intelligence to Our Discord Bots, Part 2: Improving Our Moderator Bot ..........................................................199 Using OpenAI.moderations.create() to Invoke a Moderation Model ..................201 Create Moderation (JSON) ...........................................................................202 Handling the JSON Response ......................................................................202 Moderation (JSON) ......................................................................................203 Creating Our Client for Content Moderation ......................................................207 Making Our Content Moderator Bot More Intelligent ........................................210 Important Changes to Note from the Previous Version of the Content Moderator Bot ................................................................................................212 Updates to the discordClient.on() Function .........................................................214 Running Our Intelligent Content Moderator Bot ...................................................215 Conclusion .....................................................................................................217 Exercises Left for the Reader ............................................................................217 Index ............................................................................................................219
Hopkins Bruce Jr., Hopkins Bruce Sr. / Хопкинс Брюс младший, Хопкинс Брюс старший - Creating ChatGPT Apps with JavaScript / Создание приложений ChatGPT с помощью JavaScript [2025, PDF, ENG] download torrent for free and without registration
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum