Share E-Book

OpenAI API Cookbook Build intelligent applications including chatbots, virtual assistants, and content generators (Henry Habib)(Z-Library)

Author

Rating No ratings yet

Log in to rate

AI
Language English

Explore the vast possibilities of integrating the ChatGPT API across various domains, from creating simple wrappers to developing knowledge-based assistants, multi-model applications, and conversational interfaces Key Features - Understand the different elements, endpoints, and parameters of the OpenAI API - Build tailored intelligent applications and workflows with the OpenAI API - Create versatile assistants with for a multitude of tasks As artificial intelligence continues to reshape industries with OpenAI at the forefront of AI research, knowing how to create innovative applications such as chatbots, virtual assistants, content generators, and productivity enhancers is a game-changer. This book takes a practical, recipe-based approach to unlocking the power of OpenAI API to build high-performance intelligent applications in diverse industries and seamlessly integrate ChatGPT in your workflows to increase productivity. You'll begin with the OpenAI API fundamentals, covering setup, authentication, and key parameters, and quickly progress to the different elements of the OpenAI API. Once you've learned how to use it effectively and tweak parameters for better results, you'll follow advanced recipes for enhancing user experience and refining outputs. The book guides your transition from development to live application deployment, setting up the API for public use and application backend. Further, you'll discover step-by-step recipes for building knowledge-based assistants and multi-model applications tailored to your specific needs. By the end of this book, you'll have worked through recipes involving various OpenAI API endpoints and built a variety of intelligent applications, ready to apply this experience to building AI-powered solutions of your own. Who this book is for This book is perfect for developers, data scientists, AI/tech enthusiasts, citizen developers, and no-code aficionados keen on using and mastering the OpenAI API. …

Format PDF
Size 13.5 MB
12
Views
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
OpenAI API Cookbook Build intelligent applications including chatbots, virtual assistants, and content generators Henry Habib
Page 3
OpenAI API Cookbook Copyright © 2024 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Group Product Manager: Niranjan Naikwadi Publishing Product Manager: Tejashwini R Executive Editor: Mudita S Technical Editor: Yash Bhanushali Copy Editor: Safis Editing Proofreader: Safis Editing Indexer: Hemangini Bari Production Designers: Jyoti Kadam and Gokul Raj S.T DevRel Marketing Coordinator: Vinishka Kalra First published: March 2024 Production reference: 1060324 Published by Packt Publishing Ltd. Grosvenor House 11 St Paul’s Square Birmingham B3 1RB, UK. ISBN 978-1-80512-135-0 www.packtpub.com
Page 4
To Soniya, Faisal, Munira, Maheen, Karan, and Riri. – Henry
Page 5
Foreword I started working with Henry after taking one of his online courses, where he was teaching working professionals how they could save time and work faster by using no-code tools. He was both passionate and practical when delivering his content. Particularly, he focused on tangible use cases rather than abstract concepts that did not drive real-world outcomes. Having been in the field of AI and productivity for more than 10 years, he saw the emerging citizen developer trend where anyone could build tools and solutions quickly without knowing any code. When the OpenAI API was first released to the public, Henry was one the first to teach professionals how they can use it to work faster, and his course quickly reached bestseller status within one week of its release. In this book, Henry takes you on a journey on how to use the OpenAI API to build intelligent applications – tools that you can use to automate processes, improve productivity, save time, or build new businesses. He starts by introducing the OpenAI API and its endpoints, features, and parameters, and then he uses it to build apps and assistants. Throughout the book, he always adds practical and real-life examples so that you can start creating an impact from the first page. This is an essential guide for knowledge workers eager to harness the power of OpenAI and ChatGPT to build intelligent applications and solutions. It enables you to integrate the OpenAI API into various domains, from simple apps to whole assistants. Henry is also the architect behind The Intelligent Worker, one of the largest newsletters focused on teaching everyday workers how they can be productive at work with AI, automation, no-code, and other technologies. He continues his mission to empower individuals and boost their productivity through technologies with his online courses. Sam McKay, CEO and founder of Enterprise DNA, which offers top-notch data and AI skills training to over 220,000 data professionals
Page 6
Today, AI and ChatGPT are much more than household words, being a consistent and animated point of discussion and debate. However, they are also immediately actionable tools that can deliver a mind-bending list of potential applications. Unlike any technology in history, AI (and ChatGPT) has eclipsed traditional milestones in user usage, spurring spectacular growth from application ideas through to development and deployment. For people like you (and me), who are interested in implementing ChatGPT in new and innovative ways, ChatGPT’s meteoric rise to prominence is a testament to the relevance of the problems it solves, and to the importance that information and tools play in today’s digital society. With its unparalleled ability to understand and generate human-like text, ChatGPT represents not just a technological leap but a paradigm shift in human-computer interaction. As you journey through this book, I strongly encourage you to take copious notes and to use it as the working handbook that Henry Habib intended it to be. Use it to create your next successful app or business, or employ it to enrich your thinking about how to innovate your next great thing. In fact, I hope you will do what any successful entrepreneur, innovator, investor, or developer does when they are presented with a lot of information and opportunity – dream on it. That’s right – take the ideas and information you gain in this book and dream on it. Then, return to the book again and again to fashion your dreams into a reality with the tools you will have gained here. I believe Henry has masterfully constructed OpenAI API Cookbook. But I knew he could and would when I first learned of this project. From the day Henry and I first met, I recognized in him an impressive combination of technical expertise and communications skills. As a result, I have engaged him in professional development and educational programs for a global network of enterprises (including HSBC) and online education platforms (including Coursera). His proficiency in tools such as SQL, Python, Spark, Qlik Sense, and TensorFlow, combined with his practical knowledge of big data analysis in financial services, retail, and telecommunications, his underlining passion for AI and machine learning, and his ability to communicate simply make him an ideal author to create this guidebook. I know you will thoroughly enjoy this book, as I did. Use it, as I have, and see your next dream come true. Paul Siegel, serial technology entrepreneur and CEO and founder of Starweaver, a top-tier education platform focused on technology and business
Page 7
Contributors About the author Henry Habib is a manager at one of the world’s top management consulting firms, advising F500 companies on analytics and operations, with a particular focus on building intelligent AI-driven solutions and tools to create impact. He is a passionate online instructor and educator, amassing a network of more than 150,000 paid students and facilitating technical programs at large banks and governmental organizations. A proponent of the no-code and LLM revolution, he believes that anyone can now create powerful and intelligent applications without any deep technical skills. Henry resides in Toronto, Canada, with his wife, and he enjoys reading AI research papers and playing tennis in his free time. I want to thank Mudita, Tejashwini, and the Packt team for helping me expand my passion for education to the written medium.
Page 8
About the reviewers Arindam Ganguly has been working as an experienced data scientist at one of the leading multi- national software service firms for more than eight years, where he is responsible for developing and designing intelligent solutions, leveraging his expertise in AI and data analytics. He also has a vast amount of expertise in developing automation and hyper-automation solutions, leveraging automated workflow engines, and integrating them with AI. Arindam is also a published author, writing the book Build and Deploy Machine Learning Solutions Using IBM Watson, which teaches you how to build AI applications using the popular IBM Watson toolkit. Ashutosh Vishwakarma is the co-founder of Verifast.tech, a pioneering conversational AI firm, and he has over eight years of expertise in developing and architecting high-scale, machine learning-driven systems. He spearheads innovations within the Large Language Model (LLM) ecosystem, focusing on crafting next-generation user experiences. His comprehensive background ensures a deep understanding of both the technical and strategic facets of AI development, from conception to deployment. Eswari Jayakumar is a passionate software developer with over seven years of experience, proficient in multiple programming languages. Her expertise spans a wide array of technologies, with a profound interest in cutting-edge fields such as DevOps, machine learning, computer vision, and LLMs. Originally from India, she moved to Canada to pursue her master’s in computer science at the University of New Brunswick. In addition to her technical acumen, Eswari is an adept content writer, sharing her technical knowledge through engaging blogs. She spends her free time volunteering in coding communities. Follow her journey and connect with her on LinkedIn (www.linkedin.com/in/eswarijayakumar).
Page 9
(This page has no text content)
Page 10
Preface xiii 1 Unlocking OpenAI and Setting Up Your API Playground Environment 1 Technical requirements 2 Setting up your OpenAI Playground environment 2 Getting ready 3 How to do it… 3 How it works… 3 Running a completion request in the OpenAI Playground 4 Getting ready 4 How to do it… 5 How it works… 5 There’s more… 6 Using the System Message in the OpenAI Playground 6 How to do it… 7 How it works… 8 There’s more… 9 Using the Chat Log to modify the model’s behavior 9 How to do it… 9 How it works… 11 Making OpenAI API requests with Postman 13 Getting ready 13 How to do it… 14 How it works… 17 2 OpenAI API Endpoints Explained 23 Technical requirements 23 Generating customized responses using the Chat Completions endpoint 24 Getting ready 24 How to do it… 24 How it works… 27 There’s more… 29 Creating pictures using the Images endpoint 30 How to do it… 30 Table of Contents
Page 11
Table of Contentsx How it works… 32 Generating transcripts using the Audio endpoint 34 Getting ready 34 How to do it… 35 How it works… 36 3 Understanding Key Parameters and Their Impact on Generated Responses 37 Technical requirements 38 Changing the model parameter and understanding its impact on generated responses 38 Getting ready 38 How to do it… 39 How it works… 42 Controlling the number of generated responses using the n parameter 46 How to do it… 46 How it works… 49 Determining the randomness and creativity of generated responses using the temperature parameter 50 How to do it… 51 How it works… 53 4 Incorporating Additional Features from the OpenAI API 55 Technical requirements 56 Using the Python library to call the OpenAI API 56 Getting ready 57 How to do it… 57 How it works… 60 Benefits and drawbacks of using the Python library 62 Using the embedding model for text comparisons and other use cases 62 How to do it… 63 How it works… 65 Fine-tuning a completion model 68 How to do it… 68 How it works… 70
Page 12
Table of Contents xi 5 Staging the OpenAI API for Application Development 75 Technical requirements 76 Creating a public endpoint server that calls the OpenAI API 77 Getting ready 77 How to do it… 78 How it works… 82 Extending the endpoint server to accept parameters and return data 84 How to do it… 84 How it works… 87 Calling the user-created endpoint from no-code applications 88 Getting ready 88 How to do it… 89 How it works… 94 6 Building Intelligent Applications with the OpenAI API 97 Technical requirements 98 Creating a wrapper application that generates replies to your emails 98 How to do it… 99 How it works… 111 Creating a multi-modal application that generates travel itineraries 113 How to do it… 114 How it works… 127 7 Building Assistants with the OpenAI API 133 Technical requirements 134 Creating a knowledge-retrieval assistant application 135 Getting ready 136 How to do it… 136 How it works… 148 Creating a knowledge-retrieval assistant through the Assistants API 151 How to do it… 152 How it works… 161 Index 165 Other Books You May Enjoy 170
Page 13
(This page has no text content)
Page 14
Preface In the rapidly advancing generative AI world, the ability to create innovative applications such as chatbots, virtual assistants, content generation tools, and productivity enhancers can be a game- changer. The OpenAI API is your key to achieving this, enabling you to build high-performance intelligent applications in diverse industries or to increase your productivity by adding ChatGPT into your workflows. You will begin with the fundamentals of the OpenAI API, including setup, authentication, and key parameters, enabling a solid foundation for working with API. Next, you will learn about the different elements of the OpenAI API and how to use it effectively, along with the importance of tweaking certain parameters for better results. You will uncover extra features of the OpenAI API that will improve user experience and enable you to obtain refined outputs. Further, you will be guided on moving from development to a live application; you will learn how to set up the API for public use and application backends. Subsequently, you will be able to build knowledge-based assistants and multi-model applications that are tailored to your specific needs. By the end of this book, you will have a comprehensive and practical mastery of the OpenAI API and will be ready to build intelligent and AI-powered solutions. Who this book is for This book is perfect for working professionals and citizen developers who are keen on using and mastering the OpenAI API. Ideal for quickly creating intelligent applications such as chatbots or content generators, it caters to both beginners and experienced professionals. The OpenAI API in this book is accessed with Python. Familiarity with Python and APIs is desired but absolutely not required. What this book covers Chapter 1, Unlocking OpenAI and Setting Up Your API Playground Environment, covers the steps required to start working with the API and the OpenAI API Playground. Chapter 2, OpenAI API Endpoints Explained, delves into the various endpoints available in the OpenAI API, with practical examples and use cases. Chapter 3, Understanding Key Parameters and Their Impact on Generated Responses, discusses the significance of the key API parameters.
Page 15
Prefacexiv Chapter 4, Incorporating Additional Features from the OpenAI API, explains how to use the hidden gems of the API such as embeddings and fine-tuning. Chapter 5, Staging the OpenAI API for Application Development, transitions from fiddling with the API to using it to build real-life applications. Chapter 6, Building Intelligent Applications with the OpenAI API, covers how to build various different intelligent applications with the API. Chapter 7, Building Assistants with the OpenAI API, provides a tutorial on how to build knowledge- based assistants with the API. This book contains many long screenshots. These have been captured to provide readers with an overview of various features. As a result, the text in these images may appear small at 100% zoom. To get the most out of this book This book uses Python to access the OpenAI API. Familiarity with Python is recommended to get the most out of this book, but not required as all code snippets that are used will be shared. Since the book uses APIs, some knowledge of APIs and how they work is recommended but, again, not required. Some basic understanding of programming concepts such as functions and loops will be needed as they will not be covered in the book. Software/hardware covered in the book OS requirements Python Windows, macOS, and Linux (any) Postman Windows, Mac OS X, and Linux (any) Bubble Windows, Mac OS X, and Linux (any) This book leverages the OpenAI API, which you may have to pay an additional fee for if you are not eligible for the free tier. The API is charged on a per-use basis, and as a result, any misuse or abuse of the API can unintentionally result in a large invoice from OpenAI. You should always set limits on any API accounts that you create. This book also uses Google Cloud Platform to create and deploy cloud functions, which, like the OpenAI API, can be expensive if misused. A Google account is required to access this service. If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
Page 16
Preface xv Download the example code files You can download the example code files for this book from GitHub at https://github.com/ PacktPublishing/OpenAI-API-Cookbook. If there’s an update to the code, it will be updated on the existing GitHub repository. We also have other code bundles from our rich catalog of books and videos available at https:// github.com/PacktPublishing/. Check them out! Conventions used There are a number of text conventions used throughout this book. Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “In the System Message, type in the following: You are an assistant that creates marketing slogans.” A block of code is set as follows: { "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are an assistant that creates marketing slogans based on descriptions of companies" } When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: "role": "assistant", "content": "Thank you for your kind words! Vanilla is always a classic favorite. 😊🍦" Any command-line input or output is written as follows: Donald Trump's presidency showcased divisive politics and tumultuous events. Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: “After you have successfully logged in, navigate to Profile in the top right-hand menu, select Personal.”
Page 17
Prefacexvi Tips or important notes Appear like this. Sections In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There’s more..., and See also). To give clear instructions on how to complete a recipe, use these sections as follows: Getting ready This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe. How to do it… This section contains the steps required to follow the recipe. How it works… This section usually consists of a detailed explanation of what happened in the previous section. There’s more… This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe. See also This section provides helpful links to other useful information for the recipe. Get in touch Feedback from our readers is always welcome. General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at customercare@packtpub.com. Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Page 18
Preface xvii Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packtpub.com with a link to the material. If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com. Share Your Thoughts Once you’ve read OpenAI API Cookbook, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback. Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Page 19
Prefacexviii Download a free PDF copy of this book Thanks for purchasing this book! Do you like to read on the go but are unable to carry your print books everywhere? Is your eBook purchase not compatible with the device of your choice? Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost. Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application. The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily Follow these simple steps to get the benefits: 1. Scan the QR code or visit the link below https://packt.link/free-ebook/9781805121350 2. Submit your proof of purchase 3. That’s it! We’ll send your free PDF and other benefits to your email directly
Page 20
1 Unlocking OpenAI and Setting Up Your API Playground Environment ChatGPT, an advanced artificial intelligence (AI) language model developed by OpenAI, is the fastest- growing original consumer application in history, reaching 100 million users in only 2 months. By comparison, TikTok is in second place, reaching the same number of users in over 9 months (https:// www.forbes.com/sites/cindygordon/2023/02/02/chatgpt-is-the-fastest- growing-ap-in-the-history-of-web-applications/?sh=3551e45d678c). The reason for its popularity can be attributed to its ability to democratize Natural Language Processing (NLP) models for the everyday user. NLP represents a domain in AI that focuses on the interaction between computers and humans through natural language. The ultimate goal of NLP is to enable computers to interpret, understand, and respond to human language in a way that is both meaningful and useful. Traditionally, tasks in this field – from sentiment analysis to language translation – required robust datasets and specialized knowledge in machine learning and data science to be effectively executed. However, the rise of ChatGPT and its associated Application Programming Interface (API) has revolutionized the NLP landscape. Thanks to its ability to democratize NLP models, anyone, including regular users, can now generate human-like text from prompts without having any in-depth knowledge of data science or machine learning. For instance, whereas previously one might have needed to design a complex model to classify text into categories, with ChatGPT, a simple prompt can often achieve the same goal. In essence, the advent of ChatGPT has made previously intricate NLP tasks more accessible and user- friendly, bridging the gap between advanced technology and the general public.
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List