About the Authors .................................................................................................... ix
About the Technical Reviewer ................................................................................. xi
Chapter 1: Introducing ChatGPT for Python Developers ........................................... 1
Who Is This Book For? ................................................................................................................... 1
Overview ....................................................................................................................................... 2
Download the Code Now! .............................................................................................................. 2
So, What Exactly Is ChatGPT and Why Do I Need to Use the OpenAI APIs? ................................... 2
Regex vs. ChatGPT: Fight! ............................................................................................................. 5
Analysis Question #1: Who Didn’t Get Any Ice Cream, and Why? ............................................ 6
Analysis Question #2: Which Kid Was Probably Left Sad? ....................................................... 7
Let’s Unlearn Some Words in Order to Learn More About the ChatGPT API .................................. 8
Models. Models? Models!!! ..................................................................................................... 8
When We Talk About Tokens, Don’t Think About Access Tokens ............................................ 12
Temperature Is All About Creativity ........................................................................................ 13
Getting Started with the OpenAI Playground .............................................................................. 13
1. Model ................................................................................................................................. 16
2. System ............................................................................................................................... 16
3. User/Assistant ................................................................................................................... 17
4. Add (Optional) .................................................................................................................... 17
5. Temperature (Optional) ...................................................................................................... 17
6. Maximum Tokens (Optional) .............................................................................................. 17
7. Code (Optional) .................................................................................................................. 18
Try It Now! Experimenting with the “System” Role .................................................................... 18
Conclusion .................................................................................................................................. 18
Chapter 2: Using ChatGPT As Your Python Pair-Programmer ................................. 21
Overview ..................................................................................................................................... 21
Installing (or Updating) the OpenAI Library with pip ................................................................... 21
Three Ways to Set Your API Key .................................................................................................. 22
Option #1: Setting a System-Wide Environment Variable ...................................................... 22
Option #2: Creating a .env File .............................................................................................. 24
Option #3: Hard-Coding the API Key Directly in Your Application (Take with Caution) ........... 25
Creating Your First Python ChatGPT App: model_lister.py ........................................................... 26
Using OpenAI.models.list() to Get a List of Available Models ...................................................... 26
Handling the Response .......................................................................................................... 27
Using Your API Key to Get a List of Available Models with the OpenAI API .................................. 27
Getting a Prettier List of Models ................................................................................................. 29
Wait, How Many Tokens Are in My Prompt? ................................................................................ 30
Using ChatGPT As a Pair-Programmer to Build a Weather Application ....................................... 31
Setting Up the Prompt ........................................................................................................... 32
Creating accuweather_forecaster.py with the AccuWeather API ........................................... 33
Refining Our Prompt with Prompt Engineering ..................................................................... 36
Using ChatGPT As a Pair-Programmer to Build an Application That Estimates Distance
and Arrival Time .......................................................................................................................... 45
Creating a Project with Google Maps Platform API ................................................................ 45
Using ChatGPT to Take a cURL Command and Make It Useable in Python:
The Flexible Programmer’s Approach .................................................................................... 50
Using ChatGPT to Avoid Reading a Lot of Documentation and Having to Decipher
Through Any cURL Code ........................................................................................................ 54
Conclusion .................................................................................................................................. 56
Chapter 3: Creating a Basic ChatGPT Client in Python ........................................... 57
Creating Our ChatGPT Chat Completion Application, chatgpt_client.py ...................................... 57
Using OpenAI.chat.completions.create() to Send Messages to ChatGPT .................................... 58
Examining the Method Parameters ....................................................................................... 59
There Are Four Types of Messages ............................................................................................. 66
System Message (Dictionary) ................................................................................................ 66
User Message (Dictionary) .................................................................................................... 67
Assistant Message (Dictionary) ............................................................................................. 68
Tool Message (Dictionary) ..................................................................................................... 69
Running chatgpt_client.py .......................................................................................................... 69
Handling the Response (ChatCompletion) ............................................................................. 71
ChatCompletionMessage ....................................................................................................... 72
Conclusion .................................................................................................................................. 73
Chapter 4: Using AI in the Enterprise! Creating a Text Summarizer for
Slack Messages ...................................................................................................... 75
So, What Is Prompt Engineering? ................................................................................................ 76
ChatGPT Is Here to Take Away Everyone’s Jobs (Not Really) ...................................................... 76
Examining a Real-World Problem: Customer Support for a Software Company ......................... 76
Prompt Engineering 101: Text Summarization ............................................................................ 80
Prompt #1: “tl;dr” .................................................................................................................. 80
Prompt #2: “Explain This in Three Sentences or Less” .......................................................... 81
Prompt #3: “I’m a Manager. Explain to Me What Happened” ................................................ 82
Prompt #4: “Give Me Suggestions on Next Steps” ................................................................ 84
Let’s Talk About Real Prompt Engineering ............................................................................. 86
Registering a Slack Bot App ........................................................................................................ 86
Specifying What Your Bot Can (and Can’t) Do by Setting the Scope ...................................... 89
Confirming Your Settings ....................................................................................................... 90
Viewing the OAuth & Permissions Page ................................................................................ 91
Installing Your Slack Bot App to Your Workspace .................................................................. 92
Getting Your Slack Bot (Access) Token .................................................................................. 94
Inviting Your Bot to Your Channel ........................................................................................... 94
Finding the Channel ID of Your Channel ...................................................................................... 95
Using Your Slack Bot App to Automatically Grab Messages from a Channel .............................. 96
Programmatically Reading Messages from Slack with slack_chat_reader_bot.py .............. 96
Exercises Left for the Reader ...................................................................................................... 99
Conclusion .................................................................................................................................. 99
Chapter 5: Multimodal AI: Creating a Podcast Visualizer with Whisper and
DALL·E 3 ................................................................................................................ 101
Introducing the Whisper Model by OpenAI ................................................................................ 103
Features and Limitations of the Whisper Model ....................................................................... 106
Using OpenAI.audio.transcriptions.create() to Transcribe Audio ............................................... 108
Examining the Method Parameters ..................................................................................... 109
Creating a Utility App to Split Audio Files: audio_splitter.py ...................................................... 110
Creating the Audio Transcriber: whisper_transcriber.py ........................................................... 113
Having a Little Fun and Trying Things Out with a Podcast ........................................................ 115
Going Meta: Prompt Engineering GPT-4 to Write a Prompt for DALL·E ..................................... 117
Using OpenAI.images.generate() to Create Images ................................................................... 118
Examining the Method Parameters ..................................................................................... 119
Handling the Response ........................................................................................................ 121
Creating the Image Generator: dalle_client.py .......................................................................... 121
DALL·E Prompt Engineering and Best Practices ....................................................................... 123
DALL·E Golden Rule #1: Get Familiar with the Types of Images That DALL·E
Can Generate ....................................................................................................................... 124
DALL·E Golden Rule #2: Be Descriptive with What You Want in the Foreground and
Background ......................................................................................................................... 125
Let’s Play Around with Prompts to DALL·E ................................................................................ 126
Conclusion ................................................................................................................................ 131
Exercises Left for the Reader .................................................................................................... 132
Chapter 6: Creating an Automated Community Manager Bot with Discord
and Python ........................................................................................................... 133
Choosing Discord as Your Community Platform ........................................................................ 134
Creating a More Advanced Bot Than Our Slack Bot .................................................................. 134
Creating a More Advanced Bot Than Any Typical Discord Bot ................................................... 135
Understanding the Roles for the Bots .................................................................................. 135
Our Example Bank: Crook’s Bank .............................................................................................. 136
First Things First: Create Your Own Discord Server .................................................................. 136
Create the Q&A Channel ............................................................................................................ 138
Registering a New Discord Bot App with Discord ..................................................................... 138
Specifying General Info for the Bot ........................................................................................... 140
Specifying OAuth2 Parameters for the Bot ............................................................................... 141
Invite Your Bot to Your Server .................................................................................................... 144
Getting the Discord ID Token for Your Bot and Setting the Gateway Intents ............................. 145
Creating a Q&A Bot App in Python to Answer Questions from a Channel:
tech_support_bot_dumb.py ...................................................................................................... 148
Handling Messages Sent to the Discord Server .................................................................. 150
Success! Running Your First Discord Bot: tech_support_bot_dumb.py .............................. 150
Streamlining the Process of Registering Our Next Discord Bot App with Discord .................... 151
Registering a New Discord Bot App with Discord ................................................................ 151
Specifying General Info for the Bot ...................................................................................... 152
Specifying OAuth2 Parameters for the Bot .......................................................................... 152
Invite Your Bot to Your Server .............................................................................................. 153
Getting the Discord ID Token for Your Bot and Setting the Gateway Intents ........................ 153
Creating The Next Discord Bot: content_moderator_bot_dumb.py ........................................... 153
Handling Messages Sent to the Discord Server .................................................................. 155
Success Again! Running Your Second Discord Bot: content_moderator_bot_dumb.py ...... 155
Conclusion ................................................................................................................................ 156
Exercises Left for the Reader .................................................................................................... 156
Chapter 7: Adding Intelligence to Our Discord Bots, Part 1: Using
the Chat Model for Q&A ........................................................................................ 157
Making tech_support_bot.py More Intelligent .......................................................................... 158
Important Changes to Note from the Previous Version of the Tech Support Bot ....................... 162
Updates to the on_message(message) Function ................................................................ 163
Analyzing chatgpt_client_for_qa_and_moderation.py ............................................................. 164
Breaking Down the ChatGPTClient Class in Python So Our Bot Can Utilize ChatGPT .......... 165
Running Our Intelligent Q&A Bot: tech_support_bot.py ....................................................... 166
We Have a Monumental Achievement…with One Slight Flaw ................................................. 168
Update the System Message to ChatGPT, and Let’s Try Again .................................................. 169
Conclusion ................................................................................................................................ 171
Chapter 8: Adding Intelligence to Our Discord Bots, Part 2: Using Chat and
Moderations Models for Content Moderation ....................................................... 173
Using OpenAI.moderations.create() to Moderate Content ......................................................... 175
Examining the Method Parameters ..................................................................................... 175
Handling the Response ........................................................................................................ 176
Moderation (Dictionary) ....................................................................................................... 176
Creating Our Client for the Moderations Model: moderation_client.py ..................................... 179
Making content_moderator_bot.py More Intelligent ................................................................ 180
Updates to the on_message(message) Function ................................................................ 184
Running Our Intelligent Content Moderator Bot: content_moderator_bot.py ............................ 185
Conclusion ................................................................................................................................ 186
Exercises Left for the Reader .................................................................................................... 186
Appendix 1: List of OpenAI Models ....................................................................... 189
Index ..................................................................................................................... 191
Unlock the future of software development and empower yourself to elevate your Python applications by harnessing the power of AI as this field continues to grow and evolve. Perfect for beginner to intermediate Python programmers, this book breaks down the essentials of using ChatGPT and OpenAI APIs.
You'll start with the basics, learning to authenticate, send prompts, generate responses, test in the Playground, and handle errors with ease. Each chapter includes hands-on exercises that bring concepts to life, demonstrating different API functionalities and practical applications. You'll master models like GPT-4o, GPT-4, GPT-3.5, Whisper, and DALL-E, enabling you to enhance your applications with cutting-edge AI.
Discover how generative AI tools like ChatGPT can automate tedious tasks rather than replace jobs. Leverage ChatGPT’s powerful Natural Language Processing (NLP) capabilities to handle various formats of unstructured text within your Python apps. Quickly see how easy it is to use ChatGPT as your AI-pair programmer, boosting your productivity and speed.
This step-by-step guide will have you creating intelligent chatbots that can automatically process messages from Slack or Discord. With Beginning ChatGPT for Python, you'll master the ChatGPT and OpenAI APIs, building intelligent applications that offer a personalized and engaging user experience.
Connect with the ChatGPT and OpenAI APIs and send effective prompts.
Harness parameters like temperature and top_p to create unique and engaging responses from ChatGPT.
Create an intelligent assistant bot for Slack that automates tasks and enhances productivity.
Develop a bot that can moderate conversations and manage communities on Discord.
Add context to your prompts to get more accurate and relevant responses.
Python developers and enthusiasts who aspire to employ OpenAI and ChatGPT in the creation of intelligent applications to enhance productivity.