28,99 €
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.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 209
Veröffentlichungsjahr: 2024
OpenAI API Cookbook
Build intelligent applications including chatbots, virtual assistants, and content generators
Henry Habib
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
To Soniya, Faisal, Munira, Maheen, Karan, and Riri.
– Henry
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
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
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.
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).
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.
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.
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.
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.
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.
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!
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.”
Tips or important notes
Appear like this.
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:
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.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
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 [email protected].
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.
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 [email protected] 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.
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.
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:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/9781805121350
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyChatGPT, 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.
Programmers and developers are taking note, integrating GPT’s power into their own applications to make them intelligent. In fact, many well-funded start-ups (Typeface, Jasper AI, Copy.ai) have ChatGPT and other Large Language Models (LLMs) as the basis of their product, whether it’s summarizing text, finding information, or creating a chatbot. This requires a fundamental understanding of the OpenAI API and how to use it to build intelligent applications, which is where we’ll begin.
This starts with the basics, which involves creating an OpenAI account, accessing the API Playground, and making API requests.
In this chapter, we will cover the following recipes:
Setting up your OpenAI Playground environmentRunning a completion request in the OpenAI PlaygroundUsing the System Message in the OpenAI PlaygroundUsing the Chat Log to modify the model’s behaviorMaking OpenAI API requests with PostmanThis chapter requires you to have access to the OpenAI API. You can create an account and register for access at https://platform.openai.com/overview.
The OpenAI Playground is an interactive web-based interface designed to allow users to experiment with OpenAI’s language models, including ChatGPT. It’s a place where you can learn about the capabilities of these models by entering prompts and seeing the responses generated in real time. This platform acts as a sandbox where developers, researchers, and curious individuals alike can experiment, learn, and even prototype their ideas.
In the Playground, you have the freedom to engage in a wide range of activities. You can test out different versions of the AI models, experimenting with various prompts to see how the model responds, and you can play around with different parameters to influence the responses generated. It provides a real-time glimpse into how these powerful AI models think, react, and create based on your input.
Before you start, you need to create an OpenAI Platform account.
Navigate to https://platform.openai.com/ and sign in to your OpenAI account. If you do not have an account, you can sign up for free with an email address. Alternatively, you can log in to OpenAI with a valid Google, Microsoft, or Apple account. Follow the instructions to complete the creation of your account. You may need to verify your identity with a valid phone number.
