Crafting Applications With Chatgpt Api Using Python Mike Gold
Crafting Applications With Chatgpt Api Using Python Mike Gold
Crafting Applications With Chatgpt Api Using Python Mike Gold
Crafting Applications With Chatgpt Api Using Python Mike Gold
1. Crafting Applications With Chatgpt Api Using
Python Mike Gold download
https://ebookbell.com/product/crafting-applications-with-chatgpt-
api-using-python-mike-gold-55491176
Explore and download more ebooks at ebookbell.com
2. Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Optimized Computer Programming With C10 And Net 6 Dive Into Advanced
Strategies For Crafting Lightningfast Resilient Applications With C
100 And Net 6 Anderson
https://ebookbell.com/product/optimized-computer-programming-
with-c10-and-net-6-dive-into-advanced-strategies-for-crafting-
lightningfast-resilient-applications-with-c-100-and-
net-6-anderson-89194732
Crafting Testdriven Software With Python Write Test Suites That Scale
With Your Applications Needs And Complexity Using Python And Pytest
1st Edition Alessandro Molina
https://ebookbell.com/product/crafting-testdriven-software-with-
python-write-test-suites-that-scale-with-your-applications-needs-and-
complexity-using-python-and-pytest-1st-edition-alessandro-
molina-23292674
Creating Applications With Mozilla 1st Edition David Boswell
https://ebookbell.com/product/creating-applications-with-mozilla-1st-
edition-david-boswell-1564540
Creating Business Applications With Microsoft 365 Techniques In Power
Apps Power Bi Sharepoint And Power Automate 2nd Edition Jeffrey M
Rhodes
https://ebookbell.com/product/creating-business-applications-with-
microsoft-365-techniques-in-power-apps-power-bi-sharepoint-and-power-
automate-2nd-edition-jeffrey-m-rhodes-48680976
3. Creating Business Applications With Office 365 Techniques In
Sharepoint Powerapps Power Bi And More 1st Edition Jeffrey M Rhodes
https://ebookbell.com/product/creating-business-applications-with-
office-365-techniques-in-sharepoint-powerapps-power-bi-and-more-1st-
edition-jeffrey-m-rhodes-54045500
Creating Gui Applications With Wxpython Michael Driscoll
https://ebookbell.com/product/creating-gui-applications-with-wxpython-
michael-driscoll-34960550
Creating Gui Applications With Wxpython Michael Driscoll
https://ebookbell.com/product/creating-gui-applications-with-wxpython-
michael-driscoll-34960552
Creating Business Applications With Rebol Nick Antonaccio
https://ebookbell.com/product/creating-business-applications-with-
rebol-nick-antonaccio-7427818
Modular Java Creating Flexible Applications With Osgi And Spring P10
Craig Walls
https://ebookbell.com/product/modular-java-creating-flexible-
applications-with-osgi-and-spring-p10-craig-walls-1231304
7. Crafting Applications with ChatGPT API
Using Python
Mike Gold
This book is for sale at
http://leanpub.com/craftingapplicationswithchatgptinnovatingacrossplatfor
ms
This version was published on 2023-10-03
* * * * *
This is a Leanpub book. Leanpub empowers authors and publishers with
the Lean Publishing process. Lean Publishing is the act of publishing an
in-progress ebook using lightweight tools and many iterations to get
reader feedback, pivot until you have the right book and build traction
once you do.
* * * * *
10. Table of Contents
What is ChatGPT and Why Use It?
Introduction
Background of ChatGPT
Benefits and Use Cases
Who is this Book For?
Animal Chat
Where to begin
Setting up Python
Installing the OpenAI library
Designing the UI
Introducing Tkinter for GUI
Creating the UI
Filling in the UI Code
Running the Application
Obtaining an API Key
Integrating OpenAI
Generating an Image
Creating a PDF from our Story
Generating the PDF
Securing API Keys with python-dotenv
Conclusion
Creating your own Babel Fish
Introduction
Library Setup
11. Creating the Babel Fish Shell
Submit (Record) Function
Analyzing the submit Method
Recording Speech
Transcribing Speech
Translating Speech
Vocalizing the Text
Three Ingredient Recipe Creater
Get Ready for an Epic Culinary Adventure!
Kickstarting Our Culinary Code Journey
Activating the Virtual Kitchen
Prepping the Kitchen
The Home Page
Rendering the Template in Flask
Running the App
Styling the Home Page
Harnessing ChatGPT within Flask for Culinary Creativity
generate_recipe function explained
Choosing a Cuisine
Adding Food Restrictions
Conclusion
Puzzle Book
Introduction
Setting up the Virtual Environment
The User Interface
The Puzzle Board Creator Class
Putting the Puzzle into a Graphic File
Creating the PDF
12. Creating an Entire Book
Creating a batch_submit Function
Creating the Book
Adding a button to the UI
Conclusion
Appendix
Request for Review
Source Code
Python Concepts needed for this Book
Message Structure
Example Message
Getting Token Usage
14. Introduction
In the realm of technology, few innovations have sparked as much
excitement and potential as ChatGPT. Imagine a world where machines
not only understand us but also assist us in crafting imaginative stories,
bridging language barriers, and inventing delicious recipes. This book is
your gateway to unlocking the remarkable capabilities of ChatGPT. We
will embark on a journey that transforms familiar territory into a
playground with infinite possiblities using three extraordinary
applications.
Buckle up as we accelerate towards untapped creativity and functionality,
harnessing the synergy of imagination, code, and possibility. In the
chapters that follow, you’ll witness the awesome impact of cutting-edge
artificial intelligence on the practicalities of application development.
We’ll begin by producing colorful conversations between animals in a
desktop application, then discover how to translate language seamlessly,
and finish with instantaneous recipes using the ingredients you have on
hand through a web app. This book is your compass through this
landscape of innovation.
Join us at the intersection of imagination and technology, where the
ChatGPT API transforms bold ideas into tangible realities. Whether
you’re a seasoned developer seeking to push the boundaries of what’s
possible or an enthusiast curious about the future of AI-driven
applications, this thrilling expedition promises to reshape how we interact
with computers and the possibilities that lie ahead. Get ready to witness
15. the dawn of a new era in application development with ChatGPT as your
guide and inspiration.
In this opening chapter, we uncover the essence of ChatGPT and explore
the compelling reasons behind its utilization in various domains.
16. Background of ChatGPT
At the forefront of modern artificial intelligence, the Generative pre-
trained Transformer, or GPT, has emerged as a monumental breakthrough.
Developed by OpenAI, a pioneering research organization, GPT
represents a culmination of years of research and innovation in natural
language processing (NLP). The GPT series of models are designed to
understand and generate human-like text, effectively bridging the gap
between human communication and machine comprehension.
OpenAI, a trailblazing institution founded in 2015, stands as a beacon of
ingenuity in the AI landscape. Committed to advancing artificial
intelligence for the betterment of humanity, OpenAI has consistently
pushed the boundaries of what AI can achieve. GPT, which stands for
“Generative Pre-trained Transformer,” is one of OpenAI’s flagship
innovations, with multiple iterations each building upon the successes of
its predecessors. These models are characterized by their remarkable
ability to generate coherent and contextually relevant text, fundamentally
transforming how machines process and produce language. The
democratization of AI knowledge through research papers, tools, and
APIs, including the much-acclaimed ChatGPT API, showcases OpenAI’s
dedication to enabling developers, researchers, and enthusiasts to harness
the power of AI in ways that were once relegated to the realm of science
fiction.
17. Benefits and Use Cases
The allure of ChatGPT transcends its technical intricacies, as it offers a
plethora of tangible benefits across diverse applications. Below are some
of the ways people are leveraging the power of Natural Language
processing through OpenAI’s brainchild.
Customer Support and Companies are leveraging ChatGPT to
revolutionize their customer support systems. From responding to queries
and troubleshooting to guiding users through complex processes,
ChatGPT is reshaping customer service interactions.
Content Generation and In the realm of content creation and marketing,
ChatGPT proves to be an invaluable tool. It assists in generating
captivating blog posts, social media content, and marketing copy, freeing
up creative resources and accelerating content production.
Programming and Within the landscape of artificial intelligence and
programming, ChatGPT emerges as a valuable tool with the potential to
revolutionize coding practices. By seamlessly blending AI capabilities
with coding tasks, ChatGPT offers developers an array of advantages. It
can assist in tasks ranging from code composition and elucidating intricate
programming concepts to offering resolutions for coding hurdles. In doing
so, ChatGPT caters to both neophyte and proficient programmers,
fostering an environment of enhanced productivity and knowledge
dissemination.
18. Idea ChatGPT’s role in brainstorming lies in its ability to foster creativity
and broaden horizons. By leveraging its language generation capabilities,
the API can inspire unique ideas that might not have emerged through
traditional methods. It can introduce unconventional viewpoints and
challenge established thought patterns, enriching your ideation process.
Furthermore, whether you’re conceptualizing a new storyline, envisioning
a visual masterpiece, devising strategic business moves, or revolutionizing
industries with groundbreaking innovations, ChatGPT’s adaptable insights
can provide valuable inputs across these diverse domains. Integrating
ChatGPT into your brainstorming endeavors empowers you to leverage
AI-driven creativity to its fullest potential.
Language Learning and ChatGPT serves as a versatile language partner,
possessing the capability to enhance vocabulary, correct grammar, and
facilitate interactive language practice. This makes it suitable for learners
of all proficiency levels.
19. Who is this Book For?
This book is crafted for the curious minds eager to harness the
transformative power of AI in everyday applications. Whether you’re a
budding developer aiming to integrate ChatGPT into your projects, a tech
enthusiast wanting to grasp the practicality of artificial intelligence, or
simply someone fascinated by the blend of technology and imagination,
this guide offers insights that cater to all. Dive into a world where stories
come alive, languages intertwine seamlessly, and recipes emerge from
mere ingredients. No prior expertise in AI is required, just an enthusiasm
to explore its boundless potential. With the hundreds of possibilities for
innovation that ChatGPT offers, there’s no need to delay any longer. Let’s
dive right into our first application: a Python-based storytelling platform.
20. Animal Chat
Figure 1. Tea Party
Our initial application is designed with simplicity in mind. We’ll start by
selecting two animals from the two drop down menus. Then we’ll be
prompted to provide a scenario for the dialogue. This can be anything we
envision, such as the two animals engaged in a heated debate over the
responsibility of taking out the garbage.
21. Where to begin
We’ll start by preparing the foundational tools for our project. First, we’ll
walk you through the steps of setting up Python, the programming
language that forms the backbone of our application. Next, we’ll guide
you through the process of installing the OpenAI library, which is
essential for integrating ChatGPT’s capabilities into our application.
22. Setting up Python
Before we dive into our application, ensure that Python is properly set up
on your machine. We’ll provide step-by-step instructions for installing
Python, along with any necessary dependencies, so you can start coding
without any hiccups.
Step 1: Download Python
Open a web browser and navigate to the official Python website:
https://www.python.org/
On the main page, find the “Downloads” tab. Click on it.
Step 2: Choose the Python Version
On the download page, find the latest versions of Python. There might be
two available—Python 2.x and Python 3.x. We recommend Python 3.x, as
Python 2.x is no longer actively maintained.
Step 3: Download Installer
Scroll down to find the version you want to install (e.g., Python 3.8,
Python 3.9). Depending on your operating system (Windows, macOS, or
Linux), click on the appropriate download link.
23. Step 4: Run Installer
Locate the downloaded installer file (it should have a .exe extension on
Windows or .pkg on macOS). Double-click the installer to run it.
Step 5: Configure Installation
In the installation window we have various options. Ensure the “Add
Python x.x to PATH” option is checked. This will make it easier to run
Python from the command line. We can customize the installation
directory if needed, or just leave it as the default.
Click the “Install Now” button to begin the installation process.
Step 6: Installation Complete
Once the installation is complete, we’ll see a screen indicating that Python
was installed successfully.
We will now close the installer.
Step 7: Verify Installation
Open a command prompt (Windows) or terminal (macOS/Linux). Type:
Figure 2
24. 1 python --version
and press Enter. We can see the version number that we installed (e.g.,
Python 3.11.4). Congratulations, Python is now installed! We’re ready to
start coding in Python, utilizing its powerful capabilities.
25. Installing the OpenAI library
To tap into the power of ChatGPT, we’ll need to integrate the OpenAI
library into our project. We’ll guide you through the process of installing
the library and setting up the necessary authentication, enabling seamless
communication with the ChatGPT API. By the end of this section, we’ll
be equipped with the tools needed to leverage ChatGPT’s language
generation capabilities into the storytelling application.
Installing the OpenAI library in Python is a straightforward process.
Here’s how to do it:
Step 1: Open a Terminal or Command Prompt
For Windows: Press the Windows key, search for “Command Prompt,”
and open it. For macOS and Linux: Open the Terminal application.
Step 2: Use pip to Install the OpenAI Library
In the Terminal or Command Prompt, type the following command:
Figure 3
1 pip install openai
26. and press Enter to install the OpenAI library using pip, which is Python’s
package manager. To test if it installed correctly, simply type into the
command prompt:
Figure 4
1 python
and at the python >>> prompt, type:
Figure 5
1 import openai
If you don’t get an error, openai was installed correctly.
Type ctrl-Z to exit python.
27. Designing the UI
First, we’ll focus on the user interface (UI) of our storytelling application.
A user-friendly and visually appealing interface is crucial for a positive
user experience. We’ll explore the Tkinter library, a popular choice for
creating graphical user interfaces in Python.
28. Introducing Tkinter for GUI
Tkinter provides a simple yet powerful way to create interactive GUI
applications. We’ll introduce the basics of Tkinter, setting up a window,
adding widgets, and handling user interactions. By the end of this section,
we’ll have a solid understanding of Tkinter’s capabilities and how to
utilize them for our project.
installing Tkinter
To install TkInter for Python, simply type the following command into the
Command Prompt and hit enter:
Figure 6
1 pip install tk
Now we are ready to create a dialog with user input and a few components
in Tk.
29. Creating the UI
To facilitate user interaction, we’ll implement dropdown menus that allow
users to select their preferred animals. We’ll also guide you through the
process of incorporating input fields where users can define the context of
the animal dialogue. By combining these elements, we’ll be laying the
foundation for a user-friendly interface that enables users to customize
their storytelling experience.
Creating the Main Window
Now we need to import the Tk library to get access to the UI components
of tickle:
Figure 7
1 # import toolkit 2 import tkinter as tk 3 # import the toolkit interface 4
from tkinter import ttk
We are now ready to set up the application. In toolkit, that means
constructing the toolkit app and running an event loop. The event loop is
what keeps the application running and responsive to user interactions,
such as button clicks. It will keep the “Animal Discussion Scenario”
window open until the user decides to close it.
30. Figure 8
1 import tkinter as tk 2 from tkinter import ttk 3 4 app = tk . Tk () 5 app .
title ( "Animal Discussion Scenario" ) 6 app . mainloop () # event loop
This code will bring up a blank window until we fill in its contents:
Figure 9. Blank Tk Window
31. Filling in the UI Code
Having established our main window, it’s time to design the inner
components of our UI. For animal selections, we’re creating two
dropdown lists populated with various animal names. Additionally, we’re
providing a text input field where users can draft a hypothetical dialogue
between the animals. To finalize the user’s choices, a ‘Submit’ button is
included. Clicking submit will display the user’s selections. Later in this
chapter we’ll discuss integration with the OpenAI library. Note that each
component (label, combobox, text, and button) all have a grid method that
helps us to lay out the UI controls.
Figure 10
1 import tkinter as tk 2 from tkinter import ttk 3 4 def submit (): 5
animal1 = combo1 . get () 6 animal2 = combo2 . get () 7 scenario =
entry_box . get () 8 9 result_text . delete ( 1.0 , tk . END ) # Clear any
10 # previous 11 # results 12
result_text . insert ( tk . END , f "Animal 1: 13 { animal1
} n ") 14 result_text . insert ( tk . END , f "Animal 2: 15
{ animal2 } n ") 16 result_text . insert ( tk . END , 17 f
"Discussion scenario: 18 { scenario } n ") 19 20 app = tk .
Tk () 21 app . title ( "Animal Discussion Scenario" ) 22 23 # Label and
ComboBox for the first animal 24 label1 = ttk . Label ( app , text = "Select
Animal 1:" ) 25 label1 . grid ( column = 0 , row = 0 , padx = 10 , pady = 5
) 26 combo1 = ttk . Combobox ( app , values = [ "Lion" , 27 "Elephant" ,
33. Running the Application
Running the code we created will display the storytelling window. Let’s
try it out! First create a new Python file called StoryTelling.py and paste
the code above into it. Then run in the Terminal window.
Figure 11
1 python -m StoryTelling
This will bring up the application and automatically display the default
animals, Lion and Elephant, in the dropdowns:
34. Figure 12. Initial App Screen
Let’s type in a scenario for the Lion and Elephant and click the submit
button:
35. Figure 13. After Submit
Clicking submit displays the choices we made in the result text box we
created. Now we are ready to take the next step and integrate OpenAI.
36. Obtaining an API Key
In order to integrate OpenAI into our application, we are going to need
permission to call the OpenAI API. We get permission by using an API Key
which we generate from the Open AI Go to the Open AI page and click Get
We’ll need to register with them in order to get an API key. Once registered
and logged in, click on the API section:
Figure 14. Logged in to ChatGPT
Once registered, we’ll notice a dropdown in the upper right hand corner of
our browser. Here is where we can generate or view existing keys:
37. Figure 15. View API Keys
When we click on View API keys, we’ll see the following screen which will
allow us to generate an API key:
38. Figure 16. Key Generation
We may also be able to get to the API key screen directly once logged in.
Note: Securely store a backup of the key and keep it confidential. Each API
call incurs a cost. The charge varies based on the language model we use. For
instance, as of this publication, invoking the GPT-3.5 Turbo model costs
$0.002 per call. We can protect ourselves from exploding charges by
providing usage limits on our account.
40. Integrating OpenAI
Now that we’ve got a framework for creating our animal storytelling
application and the authorization to call OpenAI, let’s create a fun
application in which two animals chat about any topic we choose. Because
we are running Python on our desktop, it’s okay to expose the key for the
purpose of this application, at least initially. Then we’ll show you a way to
hide it!
For now, let’s add the import for opening OpenAI and assign it our new
key:
Figure 18
1 import openai 2 3 # assign your api key 4 openai . api_key = 'your key
here>'
Let’s modify the submit function to invoke ChatGPT and retrieve a
response based on a prompt. This is where the real excitement lies. We’ll
ask ChatGPT API to create a dynamic dialogue between two animals—-
an elephant and a lion— at a tea party. The primary task is to craft the
appropriate prompt which we’ll derive from the input parameters of the
two animals and the desired interaction scenario. In the code below, we
utilize the OpenAI library to request a chat completion for our animal
dialogue. We generate the prompt from user input and subsequently add it
to the messages collection for ChatGPT to process.
41. Once we’ve called the ChatCompletion function on OpenAI, it will return
a response when it’s done processing (this could take a few seconds).
Upon receiving the response, we add it to the result_text Tk component.
Figure 19
1 # form the prompt out of the input inside submit 2 def submit (): 3
animal1 = combo1 . get () 4 animal2 = combo2 . get () 5 scenario =
entry_box . get () 6 7 prompt = f "Create a play between a 8 {
animal1 } and a { animal2 } with 9 10 lines of dialog with each animal
10 taking turns to speak . Here is the 11 scenario in which they 12
will engage : { scenario } n " 13 14 messages = [{ 'role' : 'user' ,
'content' : prompt }] 15 16 response = openai . ChatCompletion . create
( 17 model = "gpt-3.5-turbo" , 18 messages = messages , 19
temperature = 0.8 , 20 top_p = 1.0 , 21 frequency_penalty = 0.0
, 22 presence_penalty = 0.6 , 23 ) 24 25 chatGPTAnswer = 26
response [ "choices" ][ 0 ][ "message" ] 27 [
"content" ] 28 print ( chatGPTAnswer ) 29 # make result_text
scrollable 30 31 result_text . config ( state = "normal" ) 32 result_text
. delete ( 1.0 , tk . END ) # Clear any 33 #
previous 34 # results 35 result_text . insert ( tk .
END , chatGPTAnswer ) 36 result_text . config ( state = "disabled" )
A few things worth noting are some of the parameters of the OpenAPI call
and what they mean. Feel free to tweak these parameters to get different
flavors of results.
42. Specifies which model to use. In this case, “gpt-3.5-turbo” indicates that
you’re using the GPT-3.5 Turbo version of the model.
A list of message objects that simulate a conversation. Each message has a
‘role’ (which can be ‘system’, ‘user’, or ‘assistant’) and ‘content’ (the
content of the message). The model reads the messages in order and
generates a continuation. In this instance, the prompt is being formatted as
a user message.
Influences the randomness of the model’s responses. A higher value like
1.0 makes output more random, while a lower value like 0.1 makes it
more deterministic. In this case, 0.8 is a balance, allowing for some
creativity without being too random.
Also known as nucleus sampling, it’s used for controlling randomness. A
value of 1.0 means all tokens are considered when generating the
response. Lower values (e.g., 0.9) make the outputs more focused and less
random by only sampling the most probable tokens.
Adjusts the likelihood of tokens based on their frequency. A positive value
makes the model more likely to use frequent tokens,while a negative value
makes it less likely. At 0.0, there’s no penalty applied based on frequency.
Adjusts the likelihood of tokens based on their presence in the context. A
positive value encourages the model to use new tokens, while a negative
value discourages the model from introducing new concepts. Here, 0.6
encourages the introduction of new tokens to some extent.
43. Let’s run the application using:
Figure 20
1 python -m StoryTelling.py
A dialog will appear like the one we created. Let’s leave the Lion and
Elephant selected and choose a scenario of tea Click submit and wait a
few seconds. You should see the following appear in the bottom text:
44. Figure 21. tea party dialog
Here is the full dialog between the Elephant and the Lion that was
generated.
Dialog between an Elephant and a Lion
Figure 22
45. 1 Lion : Good afternoon , Elephant ! What a splendid tea party 2 this is . 3
4 Elephant : Indeed , Lion ! The flowers and the delicious 5 treats make it
such a delightful affair . 6 7 Lion : I must say , your elegant presence adds
an air of 8 grandeur to our gathering . 9 10 Elephant : Why , thank you ,
Lion ! Your regal mane and 11 graceful stride make you quite the host . 12
13 Lion : Please , do help yourself to some tea and 14 biscuits . They 're fit
for royalty, just like 15 ourselves. 16 17 Elephant: How kind of you, Lion.
I shall savor every 18 sip and bite with pleasure. 19 20 Lion: Tell me,
Elephant, have you ever attended a 21 tea party before? 22 23 Elephant:
Surprisingly, this is my first one, Lion. 24 It' s a charming experience ,
indeed . 25 26 Lion : Well , my dear Elephant , I must say you are a 27
natural at this tea party business . 28 29 Elephant : Thank you , Lion .
Your hospitality and 30 company make it all the more enjoyable . 31 32
Lion : It is my pleasure , Elephant . Let ' s continue 33 to indulge in this
enchanting tea party together .
Of course we can adjust the scenario however we want. Let’s have the
elephant accidently spill some tea on the lions lap.
46. Figure 23. Spilled Tea
Below are ChatGPT’s fully generated lines including the spilling mishap:
Figure 24
1 Lion : Ah , what a delightful tea party this is ! 2 3 Elephant : Indeed , the
ambiance is quite charming . 4 5 Lion : Careful not to spill your tea ,
Elephant . 6 7 Elephant : Fear not , Lion , my trunk ensures a steady grip .
47. 8 9 Lion : I 'm glad to hear it. This tea is exquisite, don' t 10 you think ? 11
12 Elephant : Absolutely , Lion . The blend is simply divine . 13 14 Lion :
Oh no ! My apologies , Elephant , I 've spilled tea 15 on your lap. 16 17
Elephant: No worries, Lion. Accidents happen, it' s 18 just a little tea . 19
20 Lion : Still , I feel terrible . Allow me to clean it up 21 for you . 22 23
Elephant : That won ' t be necessary , Lion . It was an 24 innocent mistake
. 25 26 Lion : Thank you for being so understanding , Elephant . 27 You
truly are a gracious friend .
I thought it was a clever twist that the Lion warned the Elephant not to
spill his tea, but then spilled his own…on the Elephant!
Scrolling
Another thing we need to add to the UI is the ability for the results to
scroll vertically so the user can read the full play. We start by adding a
scrollbar widget to our app:
Figure 25
1 scrollbar = tk . Scrollbar ( app )
Now we need to place our scrollbar in the grid layout we’ve defined
Figure 26
48. 1 scrollbar . grid ( row = 4 , column = 3 , sticky = 'ns' )
The Scrollbar widget is placed in the app widget’s grid layout at row 4 and
column 3. The sticky=‘ns’ argument ensures the scrollbar stretches
vertically to fill its assigned grid cell.
Next, when we construct the result_text, we need to have the vertical
movement of the result_text widget’s content linked to the y-position of
the scrollbar :
Figure 27
1 result_text = tk . Text ( app , width = 40 , height = 10 , 2 wrap = tk .
WORD , yscrollcommand = scrollbar . set )
Finally, we link the scrollbar’s motion back to the updating of the
result_view’s rendered content.
Figure 28
1 scrollbar . config ( command = result_text . yview )
49. You may be wondering why we need to add both dependencies: One for
the scrollbar in the Text widget and one for the Text widget in the
scrollbar? We actually do need both linkages and here is why:
The first linkage yscrollcommand=scrollbar.set adjusts the scrollbar based
on the content inside the Text widget.
The second linkage scrollbar.config(command=result_text.yview) ensures
that the actual movement of the scrollbar scrolls the content in the Text
widget.
Both are essential for a fully synchronized, two-way interaction between
the scrollbar and the Text widget. If we omit one of them, we’ll only have
half of the desired behavior.
Here is the full setup code for the widgets including the scrollbar:
Figure 29
1 app = tk . Tk () 2 app . title ( "Animal Discussion Scenario" ) 3 # Label
and ComboBox for the first animal 4 label1 = ttk . Label ( app , text =
"Select Animal 1:" ) 5 label1 . grid ( column = 0 , row = 0 , padx = 10 ,
pady = 5 ) 6 combo1 = ttk . Combobox ( app , values = [ "Lion" ,
"Elephant" , 7 "Giraffe" , "Kangaroo" , "Panda" ]) 8 combo1 . grid
( column = 1 , row = 0 , padx = 10 , pady = 5 ) 9 combo1 . set ( "Lion" )
10 11 # Label and ComboBox for the second animal 12 label2 = ttk .
Label ( app , text = "Select Animal 2:" ) 13 label2 . grid ( column = 0 ,
50. row = 1 , padx = 10 , pady = 5 ) 14 combo2 = ttk . Combobox ( app ,
values = [ "Lion" , 15 "Elephant" , "Giraffe" , "Kangaroo" , "Panda" ])
16 combo2 . grid ( column = 1 , row = 1 , padx = 10 , pady = 5 ) 17
combo2 . set ( "Elephant" ) 18 19 # Label and Entry for entering the
discussion scenario 20 label3 = ttk . Label ( app , text = 21
"Enter Discussion Scenario:" ) 22 label3 . grid ( column = 0 , row = 2 ,
padx = 10 , pady = 5 ) 23 entry_box = ttk . Entry ( app , width = 30 ) 24
entry_box . grid ( column = 1 , row = 2 , padx = 10 , pady = 5 ) 25 26 #
Button to submit the details 27 submit_btn = ttk . Button ( app , text =
"Submit" , 28 command = submit ) 29 submit_btn . grid ( column = 1 ,
row = 3 , padx = 10 , pady = 20 ) 30 31 # make it scrollable 32 # Create a
Scrollbar widget 33 scrollbar = tk . Scrollbar ( app ) 34 scrollbar . grid (
row = 4 , column = 3 , sticky = 'ns' ) 35 36 # Text widget to display results
37 result_text = tk . Text ( app , width = 40 , height = 10 , 38 wrap = tk .
WORD , yscrollcommand = scrollbar . set ) 39 result_text . grid ( column
= 0 , row = 4 , columnspan = 2 , 40 padx = 10 , pady = 10 ) 41
result_text . config ( state = "disabled" ) 42 #
result_text.pack(expand=True, fill=tk.BOTH) 43 44 scrollbar . config (
command = result_text . yview ) 45 46 app . mainloop ()
It’s exciting to have generated an entire story with the push of a button,
but what if we could also generate illustrations for our story at the push of
a button?
51. Generating an Image
The OpenAI library allows us to leverage DALLE-2 to generate either a
128x128, 256x256, or 1024x1024 image from a prompt. For our example, we
will be generating a 256x256 image for our story using the input from the
user to form the prompt.
Let’s start by installing the necessary Python libraries to display the image.
For our storytelling app, we’ll need libraries that have the ability to retrieve
image data from a URL and display it within our label. We’ll utilize the
requests library to access the URL and obtain our data, and the Pillow library
to render that response into an image
Figure 30
1 pip install Pillow requests
Having installed the required libraries, we can now use them to obtain our
image.
Figure 31
1 import openai 2 import requests 3 from PIL import Image , ImageTk
52. First, Let’s add a new Tk label control to the app to hold our image in the
control set up area:
Figure 32
1 image_holder = tk . Label ( app ) 2 image_holder . grid ( column = 0 , row
= 5 , columnspan = 4 , 3 padx = 10 , pady = 10 )
Next, let’s create a Python function that employs the OpenAI API,
specifically the Image.create function, to produce the image from our prompt.
For this task, we’ll employ the image-alpha-001 model.
Figure 33
1 def generateImage ( animal1 , animal2 , scenario ): 2 response = openai .
Image . create ( 3 model = "image-alpha-001" , 4 prompt = f "cartoon
image of a 5 { animal1 } and a { animal2 } 6 discussing {
scenario } ", 7 n = 1 , # Number of images to generate 8 size =
"256x256" , # Size of the generated 9 # image 10
response_format = "url" # Format in which the 11 # image
will be 12 # received 13 ) 14 15 image_url = response .
data [ 0 ][ "url" ] 16 return image_url
Displaying the Image
53. The response to our generateImage function gives us the image url we need in
order to display our story image. Let’s create a new function that takes the
image url generated by DALLE-2 and the Tk label for holding the image as
parameters. The function will do two things: it will make a request to the url
to get the data, and it will place the returned data from the http response into
an image format displayable by our Tk library.
Figure 34
1 def display_image_from_url ( image_holder , url ): 2 # Fetch the image
from the URL 3 response = requests . get ( url ) 4 image_data = BytesIO
( response . content ) 5 6 # Open and display the image 7 # using PIL
and tkinter 8 image = Image . open ( image_data ) 9 photo = ImageTk .
PhotoImage ( image ) 10 11 # Display the image in the label control 12
update_label_with_new_image ( image_holder , 13 photo
)
Once we have an actual image, we can update our label with the image to
show in our UI:
Figure 35
1 def update_label_with_new_image ( label , photo ): 2 label . config (
image = photo ) 3 label . image = photo # Keep a reference 4
# to avoid 5 # garbage collection
The only remaining task is to modify the submit function to call our image
generating function and image display function:
54. Figure 36
1 def submit (): 2 animal1 = combo1 . get () 3 animal2 = combo2 . get () 4
scenario = entry_box . get () 5 6 prompt = f "Create a play between a 7 {
animal1 } and a { animal2 } 8 with 10 lines of dialog with each animal 9
taking turns to speak . Leave a vertical 10 space between lines after
each animal 11 speaks . 12 Here is the scenario in which 13 they
will engage : { scenario } n " 14 messages = [{ 'role' : 'user' , 15
'content' : prompt }] 16 response = openai . ChatCompletion . create ( 17
model = "gpt-3.5-turbo" , 18 messages = messages , 19 temperature =
0.8 , 20 top_p = 1.0 , 21 frequency_penalty = 0.0 , 22
presence_penalty = 0.6 , 23 ) 24 25 chatGPTAnswer = response [
"choices" ][ 0 ] 26 [ "message" ][ "content" ] 27 print (
chatGPTAnswer ) 28 29 30 result_text . config ( state = "normal" ) 31
result_text . delete ( 1.0 , tk . END ) # Clear any 32 #
previous 33 # results 34 result_text . insert ( tk . END
, chatGPTAnswer ) 35 result_text . config ( state = "disabled" ) 36 37
image_url = generateImage ( animal1 , animal2 , 38
scenario ) 39 display_image_from_url ( image_holder , 40
image_url )
After all is said and done, once we click the submit button with our tea party
parameters, we should see something like the following:
60. This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.
Title: The Scientific Basis of Morals, and Other Essays
Author: William Kingdon Clifford
Release date: October 12, 2015 [eBook #50189]
Most recently updated: October 22, 2024
Language: English
Credits: Produced by Jeroen Hellingman and the Online
Distributed
Proofreading Team at http://www.pgdp.net/ for Project
Gutenberg (This file was produced from images
generously
made available by The Internet Archive/American
Libraries.)
*** START OF THE PROJECT GUTENBERG EBOOK THE SCIENTIFIC
BASIS OF MORALS, AND OTHER ESSAYS ***
63. HUMBOLDT
LIBRARY.
[No.
55.
☞ Supplied to the Trade, Returnable, by the News Companies.
THE SCIENTIFIC BASIS
OF
MORALS,
AND OTHER ESSAYS.
BY
William Kingdon Clifford, F.R.S.
CATALOGUE OF THE LIBRARY.
(Continued from last page of cover.)
Nos. 50,
51.
Money and the Mechanism of Exchange. By W. Stanley
Jevons, F.R.S.
52. The Diseases of the Will. By Th. Ribot. Translated from the
French by J. Fitzgerald, A.M.
64. 53. Animal Automatism, and Other Essays. By Prof. T. H.
Huxley, F.R.S.
54. The Birth and Growth of Myth. By Edward Clodd, F.R.A.S.
Covers for the Library, to hold firmly any number of copies from one to
twelve, Price, 60 cents; to Subscribers, 35 cents.
J. FITZGERALD, PUBLISHER,
20 LAFAYETTE PLACE,
NEW YORK.
HUMBOLDT LIBRARY
OF
Popular Science Literature.
No. 55.] NEW YORK: J. FITZGERALD. [Fifteen
Cents.
April, 1884. Entered at the New York Post-Office as
Second-Class Matter.
$1.50 per
Year.
(12
Numbers.)
65. THE SCIENTIFIC BASIS
OF
MORALS,
AND OTHER ESSAYS;
Viz.: Right and Wrong; The Ethics of Belief; The Ethics of Religion.
By WILLIAM KINGDON CLIFFORD, F.R.S.
66. I. ON THE SCIENTIFIC BASIS OF MORALS.
By Morals or Ethic I mean the doctrine of a special kind of pleasure or
displeasure which is felt by the human mind in contemplating certain
courses of conduct, whereby they are felt to be right or wrong, and of a
special desire to do the right things and avoid the wrong ones. The pleasure
or displeasure is commonly called the moral sense; the corresponding desire
might be called the moral appetite. These are facts, existing in the
consciousness of every man who need be considered in this discussion, and
sufficiently marked out by these names; they need no further definition. In
the same way the sense of taste is a feeling of pleasure or displeasure in
things savory or unsavory, and is associated with a desire for the one and a
repulsion from the other. We must assume that everybody knows what these
words mean; the feelings they describe may be analyzed or accounted for,
but they cannot be more exactly defined as feelings.
The maxims of ethic are recommendations or commands of the form, ‘Do
this particular thing because it is right,’ or ‘Avoid this particular thing
because it is wrong.’ They express the immediate desire to do the right thing
for itself, not for the sake of anything else: on this account the mood of
them is called the categorical imperative. The particular things commanded
or forbidden by such maxims depend upon the character of the individual in
whose mind they arise. There is a certain general agreement in the ethical
code of persons belonging to the same race at a given time, but considerable
variations in different races and times. To the question ‘What is right?’ can
therefore only be answered in the first instance, ‘That which pleases your
moral sense.’ But it may be further asked ‘What is generally thought right?’
and the reply will specify the ethic of a particular race and period. But the
ethical code of an individual, like the standard of taste, may be modified by
habit and education; and accordingly the question may be asked, ‘How shall
I order my moral desires so as to be able to satisfy them most completely
and continuously? What ought I to feel to be right?’ The answer to this
question must be sought in the study of the conditions under which the
67. moral sense was produced and is preserved; in other words, in the study of
its functions as a property of the human organism. The maxims derived
from this study may be called maxims of abstract or absolute right; they are
not absolutely universal, ‘eternal and immutable,’ but they are independent
of the individual, and practically universal for the present condition of the
human species.
I mean by Science the application of experience to new circumstances, by
the aid of an order of nature which has been observed in the past, and on the
assumption that such order will continue in the future. The simplest use of
experience as a guide to action is probably not even conscious; it is the
association by continually-repeated selection of certain actions with certain
circumstances, as in the unconsciously-acquired craft of the maker of flint
implements. I still call this science, although it is only a beginning; because
the physiological process is a type of what takes place in all later stages.
The next step may be expressed in the form of a hypothetical maxim,—‘If
you want to make brass, melt your copper along with this blue stone.’ To a
maxim of this sort it may always be replied, ‘I do not want to make brass,
and so I shall not do as you tell me.’ This reply is anticipated in the final
form of science, when it is expressed as a statement or proposition: brass is
an alloy of copper and zinc, and calamine is zinc carbonate. Belief in a
general statement is an artifice of our mental constitution, whereby
infinitely various sensations and groups of sensations are brought into
connection with infinitely various actions and groups of actions. On the
phenomenal side there corresponds a certain cerebral structure by which
various combinations of disturbances in the sensor tract are made to lead to
the appropriate combinations of disturbances in the motor tract. The
important point is that science, though apparently transformed into pure
knowledge, has yet never lost its character of being a craft; and that it is not
the knowledge itself which can rightly be called science, but a special way
of getting and of using knowledge. Namely, science is the getting of
knowledge from experience on the assumption of uniformity in nature, and
the use of such knowledge to guide the actions of men. And the most
abstract statements or propositions in science are to be regarded as bundles
of hypothetical maxims packed into a portable shape and size. Every
68. scientific fact is a shorthand expression for a vast number of practical
directions: if you want so-and-so, do so-and-so.
If with this meaning of the word ‘Science,’ there is such a thing as a
scientific basis of Morals, it must be true that,—
1. The maxims of Ethic are hypothetical maxims.
2. Derived from experience.
3. On the assumption of uniformity in nature.
These propositions I shall now endeavor to prove; and in conclusion, I shall
indicate the direction in which we may look for those general statements of
fact whose organization will complete the likeness of ethical and physical
science.
The Tribal Self.—In the metaphysical sense, the word ‘self’ is taken to
mean the conscious subject, das Ich, the whole stream of feelings which
make up a consciousness regarded as bound together by association and
memory. But, in the more common and more restricted ethical sense, what
we call self is a selected aggregate of feelings and of objects related to
them, which hangs together as a conception by virtue of long and repeated
association. My self does not include all my feelings, because habitually
separate off some of them, say they do not properly belong to me, and treat
them as my enemies. On the other hand, it does in general include my body
regarded as an object, because of the feelings which occur simultaneously
with events which affect it. My foot is certainly part of myself, because I
get hurt when anybody treads on it. When we desire anything for its
somewhat remote consequences, it is not common for these to be
represented to the mind in the form of the actual feelings of pleasure which
are ultimately to flow from the satisfaction of the desire; instead of this,
they are replaced by a symbolic conception which represents the thing
desired as doing good to the complex abstraction self. This abstraction
serves thus to support and hold together those complex and remote motives
which make up by far the greater part of the life of the intelligent races.
When a thing is desired for no immediate pleasure that it can bring, it is
generally desired on account of a certain symbolic substitute for pleasure,
69. the feeling that this thing is suitable to the self. And, as in many like cases,
this feeling, which at first derived its pleasurable nature from the faintly
represented simple pleasures of which it was a symbol, ceases after a time
to recall them and becomes a simple pleasure itself. In this way the self
becomes a sort of center about which our remoter motives revolve, and to
which they always have regard; in virtue of which, moreover, they become
immediate and simple, from having been complex and remote.
If we consider now the simpler races of mankind, we shall find not only that
immediate desires play a far larger part in their lives, and so that the
conception of self is less used and less developed, but also that it is less
definite and more wide. The savage is not only hurt when anybody treads
on his foot, but when anybody treads on his tribe. He may lose his hut, and
his wife, and his opportunities of getting food. In this way the tribe becomes
naturally included in that conception of self which renders remote desires
possible by making them immediate. The actual pains or pleasures which
come from the woe or weal of the tribe, and which were the source of this
conception, drop out of consciousness and are remembered no more; the
symbol which has replaced them becomes a center and goal of immediate
desires, powerful enough in many cases to override the strongest
suggestions of individual pleasure or pain.
Here a helping cause comes in. The tribe, quâ tribe, has to exist, and it can
only exist by aid of such an organic artifice as the conception of the tribal
self in the minds of its members. Hence the natural selection of those races
in which this conception is the most powerful and most habitually
predominant as a motive over immediate desires. To such an extent has this
proceeded that we may fairly doubt whether the selfhood of the tribe is not
earlier in point of development than that of the individual. In the process of
time it becomes a matter of hereditary transmission, and is thus fixed as a
specific character in the constitution of social man. With the settlement of
countries, and the aggregation of tribes into nations, it takes a wider and
more abstract form; and in the highest natures the tribal self is incarnate in
nothing less than humanity. Short of these heights, it places itself in the
family and in the city. I shall call that quality or disposition of man which
consists in the supremacy of the family or tribal self as a mark of reference
70. for motives by its old name Piety. And I have now to consider certain
feelings and conceptions to which the existence of piety must necessarily
give rise.
Before going further, however, it will be advisable to fix as precisely as
may be the sense of the words just used. Self, then, in the ethical sense, is a
conception in the mind of the individual which serves as a peg on which
remote desires are hung and by which they are rendered immediate. The
individual self is such a peg for the hanging of remote desires which affect
the individual only. The tribal self is a conception in the mind of the
individual which serves as a peg on which those remote desires are hung
which were implanted in him by the need of the tribe as a tribe. We must
carefully distinguish the tribal self from society, or the ‘common
consciousness;’ it is something in the mind of each individual man which
binds together his gregarious instincts.
The word tribe is here used to mean a group of that size which in the
circumstances considered is selected for survival or destruction as a group.
Self-regarding excellences are brought out by the natural selection of
individuals; the tribal self is developed by the natural selection of groups.
The size of the groups must vary at different times; and the extent of the
tribal self must vary accordingly.
Approbation and Conscience.—The tribe has to exist. Such tribes as saw no
necessity for it have ceased to live. To exist, it must encourage piety; and
there is a method which lies ready to hand.
We do not like a man whose character is such that we may reasonably
expect injuries from him. This dislike of a man on account of his character
is a more complex feeling than the mere dislike of separate injuries. A cat
likes your hand and your lap, and the food you give her; but I do not think
she has any conception of you. A dog, however, may like you even when
you thrash him, though he does not like the thrashing. Now such likes and
dislikes may be felt by the tribal self. If a man does anything generally
regarded as good for the tribe, my tribal self may say, in the first place, ‘I
like that thing that you have done.’ By such common approbation of
71. individual acts the influence of piety as a motive becomes defined; and
natural selection will in the long run preserve those tribes which have
approved the right things; namely, those things which at that time gave the
tribe an advantage in the struggle for existence. But in the second place, a
man may as a rule and constantly, being actuated by piety, do good things
for the tribe; and in that case the tribal self will say, I like you. The feeling
expressed by this statement on the part of any individual, ‘In the name of
the tribe, I like you,’ is what I call approbation. It is the feeling produced in
pious individuals by that sort of character which seems to them beneficial to
the community.
Now suppose that a man has done something obviously harmful to the
community. Either some immediate desire, or his individual self, has for
once proved stronger than the tribal self. When the tribal self wakes up, the
man says, ‘In the name of the tribe, I do not like this thing that I, as an
individual, have done.’ This Self-judgment in the name of the tribe is called
Conscience. If the man goes further and draws from this act and others an
inference about his own character, he may say, ‘In the name of the tribe, I
do not like my individual self.’ This is remorse. Mr. Darwin has well
pointed out that immediate desires are in general strong but of short
duration, and cannot be adequately represented to the mind after they have
passed; while the social forces, though less violent, have a steady and
continuous action.
In a mind sufficiently developed to distinguish the individual from the tribal
self, conscience is thus a necessary result of the existence of piety; it is
ready to hand as a means for its increase. But to account for the existence of
piety and conscience in the elemental form which we have hitherto
considered is by no means to account for the present moral nature of man.
We shall be led many steps in that direction if we consider the way in which
society has used these feelings of the individual as a means for its own
preservation.
Right and Responsibility.—A like or a dislike is one thing; the expression of
it is another. It is attached to the feeling by links of association; and when
this association has been selectively modified by experience, whether
72. consciously or unconsciously, the expression serves a purpose of retaining
or repeating the thing liked, and of removing the thing disliked. Such a
purpose is served by the expression of tribal approbation or disapprobation,
however little it may be the conscious end of such expression to any
individual. It is necessary to the tribe that the pious character should be
encouraged and preserved, the impious character discouraged and removed.
The process is of two kinds; direct and reflex. In the direct process the tribal
dislike of the offender is precisely similar to the dislike of a noxious beast;
and it expresses itself in his speedy removal. But in the reflex process we
find the first trace of that singular and wonderful judgment by analogy
which ascribes to other men a consciousness similar to our own. If the
process were a conscious one, it might perhaps be described in this way: the
tribal self says, ‘Put yourself in this man’s place; he also is pious, but he has
offended, and that proves that he is not pious enough. Still, he has some
conscience, and the expression of your tribal dislike to his character,
awakening his conscience, will tend to change him and make him more
pious.’ But the process is not a conscious one: the social craft or art of
living together is learned by the tribe and not by the individual, and the
purpose of improving men’s characters is provided for by complex social
arrangements long before it has been conceived by any conscious mind. The
tribal self learns to approve certain expressions of tribal liking or disliking;
the actions whose open approval is liked by the tribal self are called right
actions, and those whose open disapproval is liked are called wrong actions.
The corresponding characters are called good or bad, virtuous or vicious.
This introduces a further complication into the conscience. Self-judgment in
the name of the tribe becomes associated with very definite and material
judgment by the tribe itself. On the one hand, this undoubtedly strengthens
the motive-power of conscience in an enormous degree. On the other hand,
it tends to guide the decisions of conscience; and since the expression of
public approval or disapproval is made in general by means of some
organized machinery of government, it becomes possible for conscience to
be knowingly directed by the wise or misdirected by the wicked, instead of
being driven along the right path by the slow selective process of
experience. Now right actions are not those which are publicly approved,
but those whose public approbation a well-instructed tribal self would like.
73. Still, it is impossible to avoid the guiding influence of expressed
approbation on the great mass of the people; and in those cases where the
machinery of government is approximately a means of expressing the true
public conscience, that influence becomes a most powerful help to
improvement.
Let us note now the very important difference between the direct and the
reflex process. To clear a man away as a noxious beast, and to punish him
for doing wrong, these are two very different things. The purpose in the first
case is merely to get rid of a nuisance; the purpose in the second case is to
improve the character either of the man himself or of those who will
observe this public expression of disapprobation. The offense of which the
man has been guilty leads to an inference about his character, and it is
supposed that the community may contain other persons whose characters
are similar to his, or tend to become so. It has been found that the
expression of public disapprobation tends to awake the conscience of such
people and to improve their characters. If the improvement of the man
himself is aimed at, it is assumed that he has a conscience which can be
worked upon and made to deter him from similar offenses in future.
The word purpose has here been used in a sense to which it is perhaps
worth while to call attention. Adaptation of means to an end may be
produced in two ways that we at present know of; by processes of natural
selection, and by the agency of an intelligence in which an image or idea of
the end preceded the use of the means. In both cases the existence of the
adaptation is accounted for by the necessity or utility of the end. It seems to
me convenient to use the word purpose as meaning generally the end to
which certain means are adapted, both in these two cases, and in any other
that may hereafter become known, provided only that the adaptation is
accounted for by the necessity or utility of the end. And there seems no
objection to the use of the phrase ‘final cause’ in this wider sense, if it is to
be kept at all. The word ‘design’ might then be kept for the special case of
adaptation by an intelligence. And we may then say that since the process of
natural selection has been understood, purpose has ceased to suggest design
to instructed people, except in cases where the agency of man is
independently probable.
74. When a man can be punished for doing wrong with approval of the tribal
self, he is said to be responsible. Responsibility implies two things:—(1)
The act was a product of the man’s character and of the circumstances, and
his character may to a certain extent be inferred from the act; (2) The man
had a conscience which might have been so worked upon as to prevent his
doing the act. Unless the first condition be fulfilled, we cannot reasonably
take any action at all in regard to the man, but only in regard to the offense.
In the case of crimes of violence, for example, we might carry a six-shooter
to protect ourselves against similar possibilities, but unless the fact of a
man’s having once committed a murder made it probable that he would do
the like again, it would clearly be absurd and unreasonable to lynch the
man. That is to say, we assume an uniformity of connection between
character and actions, infer a man’s character from his past actions, and
endeavor to provide against his future actions either by destroying him or
by changing his character. I think it will be found that in all those cases
where we not only deal with the offense but treat it with moral reprobation,
we imply the existence of a conscience which might have been worked
upon to improve the character. Why, for example, do we not regard a lunatic
as responsible? Because we are in possession of information about his
character derived not only from his one offense but from other facts,
whereby we know that even if he had a conscience left, his mind is so
diseased that it is impossible by moral reprobation alone to change his
character so that it may be subsequently relied upon. With his cure from
disease and the restored validity of this condition, responsibility returns.
There are, of course, cases in which an irresponsible person is punished as
if he were responsible, pour encourager les autres who are responsible. The
question of the right or wrong of this procedure is the question of its
average effect on the character of men at any particular time.
The Categorical Imperative.—May we now say that the maxims of Ethic
are hypothetical maxims? I think we may, and that in showing why we shall
explain the apparent difference between them and other maxims belonging
to an early stage of science. In the first place ethical maxims are learned by
the tribe and not by the individual. Those tribes have on the whole survived
in which conscience approved such actions as tended to the improvement of
men’s characters as citizens and therefore to the survival of the tribe. Hence
75. it is that the moral sense of the individual, though founded on the
experience of the tribe, is purely intuitive; conscience gives no reasons.
Notwithstanding this, the ethical maxims are presented to us as conditional;
if you want to live together in this complicated way, your ways must be
straight and not crooked, you must seek the truth and love no lie. Suppose
we answer, ‘I don’t want to live together with other men in this complicated
way; and so I shall not do as you tell me.’ That is not the end of the matter,
as it might be with other scientific precepts. For obvious reasons it is right
in this case to reply, ‘Then in the name of my people I do not like you,’ and
to express this dislike by appropriate methods. And the offender, being
descended from a social race, is unable to escape his conscience, the voice
of his tribal self which says, ‘In the name of the tribe, I hate myself for this
treason that I have done.’
There are two reasons, then, why ethical maxims appear to be
unconditional. First, they are acquired from experience not directly but by
tribal selection, and therefore in the mind of the individual they do not rest
upon the true reasons for them. Secondly, although they are conditional, the
absence of the condition in one born of a social race is rightly visited by
moral reprobation.
Ethics are based on Uniformity.—I have already observed that to deal with
men as a means of influencing their actions implies that these actions are a
product of character and circumstances; and that moral reprobation and
responsibility cannot exist unless we assume the efficacy of certain special
means of influencing character. It is not necessary to point out that such
considerations involve that uniformity of nature which underlies the
possibility of even unconscious adaptations to experience, of language, and
of general conceptions and statements. It may be asked, ‘Are you quite sure
that these observed uniformities between motive and action, between
character and motive, between social influence and change of character, are
absolutely exact in the form in which you state them, or indeed that they are
exact laws of any form? May there not be very slight divergences from
exact laws, which will allow of the action of an “uncaused will,” or of the
interference of some “extra-mundane force”?’ I am sure I do not know. But
this I do know: that our sense of right and wrong is derived from such order
76. as we can observe, and not from such caprice of disorder as we may
fancifully conjecture; and that to whatever extent a divergence from
exactness became sensible, to that extent it would destroy the most
widespread and worthy of the acquisitions of mankind.
The Final Standard.—By these views we are led to conclusions partly
negative, partly positive; of which, as might be expected, the negative are
the most definite.
First, then, Ethic is a matter of the tribe or community, and therefore there
are no ‘self-regarding virtues.’ The qualities of courage, prudence, etc., can
only be rightly encouraged in so far as they are shown to conduce to the
efficiency of a citizen; that is, in so far as they cease to be self-regarding.
The duty of private judgment, of searching after truth, the sacredness of
belief which ought not to be misused on unproved statements, follow only
on showing of the enormous importance to society of a true knowledge of
things. And any diversion of conscience from its sole allegiance to the
community is condemned à priori in the very nature of right and wrong.
Next, the end of Ethic is not the greatest happiness of the greatest number.
Your happiness is of no use to the community, except in so far as it tends to
make you a more efficient citizen—that is to say, happiness is not to be
desired for its own sake, but for the sake of something else. If any end is
pointed to, it is the end of increased efficiency in each man’s special work,
as well as in the social functions which are common to all. A man must
strive to be a better citizen, a better workman, a better son, husband, or
father.
Again, Piety is not Altruism. It is not the doing good to others as others, but
the service of the community by a member of it, who loses in that service
the consciousness that he is anything different from the community.
The social organism, like the individual, may be healthy or diseased. Health
and disease are very difficult things to define accurately: but for practical
purposes, there are certain states about which no mistake can be made.
When we have even a very imperfect catalogue and description of states
77. that are clearly and certainly diseases, we may form a rough preliminary
definition of health by saying that it means the absence of all these states.
Now the health of society involves among other things, that right is done by
the individuals composing it. And certain social diseases consist in a wrong
direction of the conscience. Hence the determination of abstract right
depends on the study of healthy and diseased states of society. How much
light can be got for this end from the historical records we possess? A very
great deal, if, as I believe, for ethical purposes the nature of man and of
society may be taken as approximately constant during the few thousand
years of which we have distinct records.
The matters of fact on which rational ethic must be founded are the laws of
modification of character, and the evidence of history as to those kinds of
character which have most aided the improvement of the race. For although
the moral sense is intuitive, it must for the future be directed by our
conscious discovery of the tribal purpose which it serves.
79. THE SCIENTIFIC GROUND OF THEIR
DISTINCTION.1
The questions which are here to be considered are especially and peculiarly
everybody’s questions. It is not everybody’s business to be an engineer, or a
doctor, or a carpenter, or a soldier; but it is everybody’s business to be a
citizen. The doctrines and precepts which guide the practice of the good
engineer are of interest to him who uses them and to those whose business
it is to investigate them by mechanical science; the rest of us neither obey
nor disobey them. But the doctrines and precepts of morality, which guide
the practice of the good citizen, are of interest to all; they must be either
obeyed or disobeyed by every human being who is not hopelessly and
forever separated from the rest of mankind. No one can say, therefore, that
in this inquiry we are not minding our own business, that we are meddling
with other men’s affairs. We are in fact studying the principles of our
profession, so far as we are able; a necessary thing for every man who
wishes to do good work in it.
Along with the character of universal interest which belongs to our subject
there goes another. What is everybody’s practical business is also to a large
extent what everybody knows; and it may be reasonably expected that a
discourse about Right and Wrong will be full of platitudes and truisms. The
expectation is a just one. The considerations I have to offer are of the very
oldest and the very simplest commonplace and common sense; and no one
can be more astonished than I am that there should be any reason to speak
of them at all. But there is reason to speak of them, because platitudes are
not all of one kind. Some platitudes have a definite meaning and a practical
application, and are established by the uniform and long-continued
experience of all people. Other platitudes, having no definite meaning and
no practical application, seem not to be worth anybody’s while to test; and
these are quite sufficiently established by mere assertion, if it is audacious
enough to begin with and persistent enough afterward. It is in order to
80. distinguish these two kinds of platitude from one another, and to make sure
that those which we retain form a body of doctrine consistent with itself and
with the rest of our beliefs, that we undertake this examination of obvious
and widespread principles.
First of all, then, what are the facts?
We say that it is wrong to murder, to steal, to tell lies, and that it is right to
take care of our families. When we say in this sense that one action is right
and another wrong, we have a certain feeling toward the action which is
peculiar and not quite like any other feeling. It is clearly a feeling toward
the action and not toward the man who does it; because we speak of hating
the sin and loving the sinner. We might reasonably dislike a man whom we
knew or suspected to be a murderer, because of the natural fear that he
might murder us; and we might like our own parents for taking care of us.
But everybody knows that these feelings are something quite different from
the feeling which condemns murder as a wrong thing, and approves
parental care as a right thing. I say nothing here about the possibility of
analyzing this feeling, or proving that it arises by combination of other
feelings; all I want to notice is that it is as distinct and recognizable as the
feeling of pleasure in a sweet taste or of displeasure at a toothache. In
speaking of right and wrong, we speak of qualities of action which arouse
definite feelings that everybody knows and recognizes. It is not necessary,
then, to give a definition at the outset; we are going to use familiar terms
which have a definite meaning in the same sense in which everybody uses
them. We may ultimately come to something like a definition; but what we
have to do first is to collect the facts and see what can be made of them, just
as if we were going to talk about limestone, or parents and children, or fuel.
It is easy to conceive that murder and theft and neglect of the young might
be considered wrong in a very simple state of society. But we find at present
that the condemnation of these actions does not stand alone; it goes with the
condemnation of a great number of other actions which seem to be included
with the obviously criminal action, in a sort of general rule. The wrongness
of murder, for example, belongs in a less degree to any form of bodily
injury that one man may inflict on another; and it is even extended so as to
81. include injuries to his reputation or his feelings. I make these more refined
precepts follow in the train of the more obvious and rough ones, because
this appears to have been the traditional order of their establishment. ‘He
that makes his neighbor blush in public,’ says the Mishna, ‘is as if he had
shed his blood.’ In the same way the rough condemnation of stealing carries
with it a condemnation of more refined forms of dishonesty: we do not
hesitate to say that it is wrong for a tradesman to adulterate his goods, or for
a laborer to scamp his work. We not only say that it is wrong to tell lies, but
that it is wrong to deceive in other more ingenious ways; wrong to use
words so that they shall have one sense to some people and another sense to
other people; wrong to suppress the truth when that suppression leads to
false belief in others. And again, the duty of parents toward their children is
seen to be a special case of a very large and varied class of duties toward
that great family to which we belong—to the fatherland and them that dwell
therein. The word duty which I have here used, has as definite a sense to the
general mind as the words right and wrong; we say that it is right to do our
duty, and wrong to neglect it. These duties to the community serve in our
minds to explain and define our duties to individuals. It is wrong to kill any
one; unless we are an executioner, when it may be our duty to kill a
criminal; or a soldier, when it may be our duty to kill the enemy of our
country; and in general it is wrong to injure any man in any way in our
private capacity and for our own sakes. Thus if a man injures us, it is only
right to retaliate on behalf of other men. Of two men in a desert island, if
one takes away the other’s cloak, it may or may not be right for the other to
let him have his coat also; but if a man takes away my cloak while we both
live in society, it is my duty to use such means as I can to prevent him from
taking away other people’s cloaks. Observe that I am endeavoring to
describe the facts of the moral feelings of Englishmen, such as they are
now.
The last remark leads us to another platitude of exceedingly ancient date.
We said that it was wrong to injure any man in our private capacity and for
our own sakes. A rule like this differs from all the others that we have
considered, because it not only deals with physical acts, words and deeds
which can be observed and known by others, but also with thoughts which
are known only to the man himself. Who can tell whether a given act of
82. punishment was done from a private or from a public motive? Only the
agent himself. And yet if the punishment was just and within the law, we
should condemn the man in the one case and approve him in the other. This
pursuit of the actions of men to their very sources, in the feelings which
they only can know, is as ancient as any morality we know of, and extends
to the whole range of it. Injury to another man arises from anger, malice,
hatred, revenge; these feelings are condemned as wrong. But feelings are
not immediately under our control, in the same way that overt actions are: I
can shake anybody by the hand if I like, but I cannot always feel friendly to
him. Nevertheless we can pay attention to such aspects of the
circumstances, and we can put ourselves into such conditions, that our
feelings get gradually modified in one way or the other; we form a habit of
checking our anger by calling up certain images and considerations,
whereby in time the offending passion is brought into subjection and
control. Accordingly we say that it is right to acquire and to exercise this
control; and the control is supposed to exist whenever we say that one
feeling or disposition of mind is right and another wrong. Thus, in
connection with the precept against stealing, we condemn envy and
covetousness; we applaud a sensitive honesty which shudders at anything
underhand or dishonorable. In connection with the rough precept against
lying, we have built up and are still building a great fabric of intellectual
morality, whereby a man is forbidden to tell lies to himself, and is
commanded to practice candor and fairness and open-mindedness in his
judgments, and to labor zealously in pursuit of the truth. In connection with
the duty to our families, we say that it is right to cultivate public spirit, a
quick sense of sympathy, and all that belongs to a social disposition.
Two other words are used in this connection which it seems necessary to
mention. When we regard an action as right or wrong for ourselves, this
feeling about the action impels us to do it or not to do it, as the case may be.
We may say that the moral sense acts in this case as a motive; meaning by
moral sense only the feeling in regard to an action which is considered as
right or wrong, and by motive something which impels us to act. Of course
there may be other motives at work at the same time, and it does not at all
follow that we shall do the right action or abstain from the wrong one. This
we all know to our cost. But still our feeling about the rightness or
83. wrongness of an action does operate as a motive when we think of the
action as being done by us; and when so operating it is called conscience. I
have nothing to do at present with the questions about conscience, whether
it is a result of education, whether it can be explained by self-love, and so
forth; I am only concerned in describing well-known facts, and in getting as
clear as I can about the meaning of well-known words. Conscience, then, is
the whole aggregate of our feelings about actions as being right or wrong,
regarded as tending to make us do the right actions and avoid the wrong
ones. We also say sometimes, in answer to the question, ‘How do you know
that this is right or wrong?’ ‘My conscience tells me so.’And this way of
speaking is quite analogous to other expressions of the same form; thus if I
put my hand into water, and you ask me how I know that it is hot, I might
say, ‘My feeling of warmth tells me so.’
When we consider a right or a wrong action as done by another person, we
think of that person as worthy of moral approbation or reprobation. He may
be punished or not; but in any case this feeling toward him is quite different
from the feeling of dislike toward a person injurious to us, or of
disappointment at a machine which will not go.
Whenever we can morally approve or disapprove a man for his action, we
say that he is morally responsible for it, and vice versâ. To say that a man is
not morally responsible for his actions is the same thing as to say that it
would be unreasonable to praise or blame him for them.
The statement that we ourselves are morally responsible is somewhat more
complicated, but the meaning is very easily made out; namely, that another
person may reasonably regard our actions as right or wrong, and may praise
or blame us for them.
We can now, I suppose, understand one another pretty clearly in using the
words right and wrong, conscience, responsibility; and we have made a
rapid survey of the facts of the case in our own country at the present time.
Of course I do not pretend that this survey in any way approaches to
completeness; but it will supply us at least with enough facts to enable us to
deal always with concrete examples instead of remaining in generalities;
84. Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com