Download (Ebook) OpenAI API Cookbook: Build intelligent applications including chatbots, virtual assistants, and content generators by Henry Habib ISBN 9781805121350, 1805121359 ebook All Chapters PDF
Download (Ebook) OpenAI API Cookbook: Build intelligent applications including chatbots, virtual assistants, and content generators by Henry Habib ISBN 9781805121350, 1805121359 ebook All Chapters PDF
com
DOWLOAD EBOOK
ebooknice.com
ebooknice.com
ebooknice.com
(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena
Alfredsson, Hans Heikne, Sanna Bodemyr ISBN 9789127456600,
9127456609
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312
ebooknice.com
https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018
ebooknice.com
ebooknice.com
ebooknice.com
https://ebooknice.com/product/web-api-cookbook-level-up-your-
javascript-applications-56376958
ebooknice.com
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.
Published by
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
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
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
Contributors
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 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.
Preface
Technical requirements
Getting ready
How to do it…
How it works…
Getting ready
How to do it…
How it works…
There’s more…
Using the System Message in the OpenAI
Playground
How to do it…
How it works…
There’s more…
How to do it…
How it works…
Getting ready
How to do it…
How it works…
Technical requirements
Generating customized responses using the Chat
Completions endpoint
Getting ready
How to do it…
How it works…
There’s more…
How to do it…
How it works…
Getting ready
How to do it…
How it works…
Technical requirements
Changing the model parameter and
understanding its impact on generated
responses
Getting ready
How to do it…
How it works…
How to do it…
How it works…
How to do it…
How it works…
Technical requirements
Using the Python library to call the OpenAI API
Getting ready
How to do it…
How it works…
How to do it…
How it works…
How to do it…
How it works…
Technical requirements
Creating a public endpoint server that calls the
OpenAI API
Getting ready
How to do it…
How it works…
How to do it…
How it works…
Getting ready
How to do it…
How it works…
Technical requirements
Creating a wrapper application that generates
replies to your emails
How to do it…
How it works…
How to do it…
How it works…
Technical requirements
Getting ready
How to do it…
How it works…
How it works…
Index
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 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.
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.
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.
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.”
{
"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. 😊🍦"
},
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.”
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).
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
[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.
Your review is important to us and the tech community and will help us make sure
we’re delivering excellent quality content.
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
https://packt.link/free-ebook/9781805121350
3. That’s it! We’ll send your free PDF and other benefits to your email directly
1
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.
Technical requirements
This 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.
Getting ready
Before you start, you need to create an OpenAI Platform account.
How to do it…
1. After you have successfully logged in, navigate to Profile in the top right-hand menu, select
Personal, and then select Usage from the left-hand side menu. Alternatively, you can
navigate to https://platform.openai.com/account/usage after logging in. This page shows the
usage of your API, but more importantly, it shows you how many credits you have available.
2. Normally, OpenAI provides you a $5 credit with a new account, which you should be able to
see under the Free Trial Usage section of the page. If you do have credits, proceed to step
4. If, however, you do not have any credits, you will need to upgrade and set up a paid
account.
3. You need not set up a paid account if you have received free credits. If you run out of free
credits, however, here is how you can set up a paid account: select Billing from the left-hand
side menu and then select Overview. Then, select the Set up paid account button. You will
be prompted to enter your payment details and set a dollar threshold, which can be set to any
level of spend that you are comfortable with. Note that the amount of credits required to
collectively execute every single recipe contained in this book is not likely to exceed $5.
4. After you have created an OpenAI Platform account, you should be able to access the
Playground by selecting Playground from the top menu bar, or by navigating to
https://platform.openai.com/playground.
How it works…
The OpenAI Playground interface is, in my experience, clean, intuitive, and
designed to provide users easy access to OpenAI’s powerful language models. The
Playground is an excellent place to learn how the models perform under different
settings, allowing you to experiment with parameters such as temperature and
max tokens, which influence the randomness and length of the outputs
respectively. The changes you make are instantly reflected in the model’s
responses, offering immediate feedback.
As shown in Figure 1.1, the Playground consists of three sections: the System
Message, the Chat Log, and the Parameters. You will learn more about these three
features in the Running a completion request in the OpenAI Playground recipe.
Now, your Playground is set up and ready to be used. You can use it to run
completion requests and see how varying your prompts and parameters affect the
response from OpenAI.
Getting ready
Ensure you have an OpenAI Platform account with available usage credits. If you
don’t, please follow the Setting up your OpenAI Playground environment recipe.
All the recipes in this chapter will have this same requirement.
How to do it…
Let’s go ahead and start testing the model with the Playground. Let’s create an
assistant that writes marketing slogans:
1. Navigate to the OpenAI Playground.
2. In the System Message, type in the following: You are an assistant that creates
marketing slogans based on descriptions of companies. Here, we are clearly
instructing the model of its role and context.
3. In the Chat Log, populate the USER message with the following: A company that writes
engaging mystery novels.
5. You should now see a completion response from OpenAI. In my case (Figure 1.2), the
response is as follows:
Mies alkoi soittaa keskellä pihaa, mutta äiti työnsi hänet syrjään
sanoen:
— Saanko minä.
— Jens, Jens.
— Entä sitten, posetiivin soittaja, entä sitten, sanoi äiti ja siirtyi yhä
lähemmäksi ukkoa penkillä.
— Niin on.
*****
Ensi työkseen hän lukitsi äidin huoneen oven. Hän kiersi avainta
kaksi kertaa molemmissa ovissa — vaatekammionkin ovessa.
Mutta äiti oli nähnyt kaikki lahjansa, ennenkuin pöytä oli valmis.
— He tahtoivat nousta.
— Tine, Tine.
Ja hän hymyili.
*****
— Niinpä melkein.
— Viimeinen.
— Viimeinen.
— Viimeinen.
He juoksivat lammikon ympäri.
Stinan hajuvesipullo löi äidin sääriä vastaan, kunnes hän sai sen
taskustaan ja asetti sen nurmikolle lammikon viereen.
Äiti nauroi niin, että hänen oli pakko nojautua puun runkoa
vastaan.
Äiti käänsi kirjan lehteä, ja, kuin itsekseen lukien lausui hän runon
uudelleen:
— Tine, sanoi hän äkkiä, ja Tine vavahti, sillä äiti oli sanonut
hänen nimensä melkein kuin apua anova.
Ei yksikään itke
mun syäntäni kylmää:
sitä ainoastaan
näet yksi vain lempi.
*****
Oli kuin olisi tehty sellainen sopimus, että Tine katoasi talosta
tätikautena. Äiti ja hän tapasivat toisensa melkein kuin kaksi
salakuljettajaa. Mutta aamulla täytyi Tinen tulla äitiä ajamaan
vuoteesta.
— Niin — — —
Vihdoin hän pääsi vuoteesta.
Äiti sanoi:
Sitäpaitsi oli tie vihannestarhan läpi, kun sen oli kulkenut kuusi
kertaa edes-takaisin, juuri heidän määränsä. Kävellessään he eivät
puhuneet.
— Geneven lääkäri on oikeassa, sanoi Bothilde täti, ei pidä puhua.
Pitää kävellä ja antaa hermojensa levätä.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com