How To Build Intelligent Chatbots with Python and ChatGPT
Tags: chatgpt, python
Published: 2022-12-26 15:37:24

<div class="entry-content">
			<div class="row">
				<div class="col-lg-8 col-xl-8 blog-content-col">
					
<h1>Build Intelligent Chatbots with Python and ChatGPT</h1>



<p>ChatGPT is a variant of the popular language model GPT-3 that is specifically designed for chatbot applications. It allows developers to build intelligent chatbots that can generate human-like responses to user inputs in natural language.</p>

<h2>Using the OpenAI API to Access ChatGPT in Python</h2>



<p>One of the great things about ChatGPT is that it can be easily integrated into Python applications using the OpenAI API. In this post, we’ll take a look at how to use ChatGPT in a Python application and provide some code snippets as examples.</p>



<p>To get started, you’ll need to sign up for an <a href="https://beta.openai.com/signup" class="ek-link">OpenAI</a> API key. Once you have created an account, you can obtain an API key from <a href="https://beta.openai.com/account/api-keys" class="ek-link">here</a>. This will give you access to the various language models, including ChatGPT, that are available through the API.</p>



<p>Before we start writing code, we need to install <code>openai</code> with pip:</p>



<p>To install <em>openai </em>with <a href="https://pypi.org/project/openai/" class="ek-link">pip</a>, first ensure that you have pip installed on your system. You can check if you have pip installed by running the following command in your terminal:</p>



<pre class="wp-block-code language-python" tabindex="0"><code lang="python" class="language-python">pip <span class="token operator">-</span><span class="token operator">-</span>version
</code></pre>



<p>If pip is not installed, you can install it by running the following command:</p>



<pre class="wp-block-code language-python" tabindex="0"><code lang="python" class="language-python">python <span class="token operator">-</span>m ensurepip <span class="token operator">-</span><span class="token operator">-</span>upgrade
</code></pre>



<p>Once pip is installed, you can use it to install the <em>openai </em>package by running the following command (as of the writing of this article, note that the <em><a href="https://pypi.org/project/pandas/" class="ek-link">pandas</a> </em>package is required in order to use openai):</p>



<pre class="wp-block-code language-python" tabindex="0"><code lang="python" class="language-python">pip install pandas openai
</code></pre>



<p>This will install the latest version of the <em>openai </em>package and its dependencies. You can then import and use the <em>openai </em>module in your Python code.</p>



<pre class="wp-block-code language-python" tabindex="0"><code lang="python" class="language-python"><span class="token keyword">import</span> openai
</code></pre>



<p>Here’s an example of how to use the <code>openai</code> library to generate a response using ChatGPT:</p>



<pre class="wp-block-code language-python" tabindex="0"><code lang="python" class="language-python"><span class="token keyword">import</span> openai

openai<span class="token punctuation">.</span>api_key <span class="token operator">=</span> <span class="token string">"YOUR_API_KEY"</span>

<span class="token keyword">def</span> <span class="token function">generate_response</span><span class="token punctuation">(</span>prompt<span class="token punctuation">)</span><span class="token punctuation">:</span>
    model_engine <span class="token operator">=</span> <span class="token string">"text-davinci-002"</span>
    prompt <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token string-interpolation"><span class="token string">f"</span><span class="token interpolation"><span class="token punctuation">{</span>prompt<span class="token punctuation">}</span></span><span class="token string">"</span></span><span class="token punctuation">)</span>

    completions <span class="token operator">=</span> openai<span class="token punctuation">.</span>Completion<span class="token punctuation">.</span>create<span class="token punctuation">(</span>
        engine<span class="token operator">=</span>model_engine<span class="token punctuation">,</span>
        prompt<span class="token operator">=</span>prompt<span class="token punctuation">,</span>
        max_tokens<span class="token operator">=</span><span class="token number">1024</span><span class="token punctuation">,</span>
        n<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span>
        stop<span class="token operator">=</span><span class="token boolean">None</span><span class="token punctuation">,</span>
        temperature<span class="token operator">=</span><span class="token number">0.5</span><span class="token punctuation">,</span>
    <span class="token punctuation">)</span>

    message <span class="token operator">=</span> completions<span class="token punctuation">.</span>choices<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">.</span>text
    <span class="token keyword">return</span> message<span class="token punctuation">.</span>strip<span class="token punctuation">(</span><span class="token punctuation">)</span>
</code></pre>



<p>For this demo, we are using the “<em>text-davinci-002</em>” model engine. GPT-3 models can understand and generate natural language. There are four main models with different levels of power suitable for different tasks. <em>Davinci </em>is the most capable model, and <em>Ada </em>is the fastest. You can find more details about the different engines <a href="https://beta.openai.com/docs/models/gpt-3" class="ek-link">here</a>.</p>



<h2>Customizing ChatGPT Responses in Python</h2>



<p>In this example, we’re using the <code>openai.Completion.create()</code> method to generate a response to a given prompt. The <code>prompt</code> parameter is the input that the user has provided to the chatbot, and the <code>max_tokens</code> parameter specifies the maximum number of tokens (i.e. words) that the response should contain.</p>



<p>You can also customize the behavior of the ChatGPT model by adjusting the <code>temperature</code> parameter. A higher temperature will result in more diverse and unpredictable responses, while a lower temperature will produce more conservative and predictable responses.</p>



<p>Here’s an example of how you might use the <code>generate_response()</code> function in a simple chatbot application:</p>



<pre class="wp-block-code language-python" tabindex="0"><code lang="python" class="language-python"><span class="token keyword">while</span> <span class="token boolean">True</span><span class="token punctuation">:</span>
    user_input <span class="token operator">=</span> <span class="token builtin">input</span><span class="token punctuation">(</span><span class="token string">"User: "</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> user_input <span class="token operator">==</span> <span class="token string">"exit"</span><span class="token punctuation">:</span>
        <span class="token keyword">break</span>
    response <span class="token operator">=</span> generate_response<span class="token punctuation">(</span>user_input<span class="token punctuation">)</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Chatbot:"</span><span class="token punctuation">,</span> response<span class="token punctuation">)</span>
</code></pre>



<p>In this example, the chatbot will continue to generate responses as long as the user doesn’t input the word “exit”.</p>



<h2>More Examples</h2>



<p>ChatGPT is not limited to just answering simple questions. Let’s take a look at some advanced examples. For this purpose, we will rewrite our script to accept user import then print the result.</p>



<p>Save your code in a python file, let’s call it <em>app.py</em>. The final code should look like the following:</p>



<pre class="wp-block-code language-python" tabindex="0"><code lang="python" class="language-python"><span class="token keyword">import</span> openai

openai<span class="token punctuation">.</span>api_key <span class="token operator">=</span> <span class="token string">"YOUR_API_KEY"</span>

<span class="token keyword">def</span> <span class="token function">generate_response</span><span class="token punctuation">(</span>prompt<span class="token punctuation">)</span><span class="token punctuation">:</span>
    model_engine <span class="token operator">=</span> <span class="token string">"text-davinci-002"</span>
    prompt <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token string-interpolation"><span class="token string">f"</span><span class="token interpolation"><span class="token punctuation">{</span>prompt<span class="token punctuation">}</span></span><span class="token string">"</span></span><span class="token punctuation">)</span>

    completions <span class="token operator">=</span> openai<span class="token punctuation">.</span>Completion<span class="token punctuation">.</span>create<span class="token punctuation">(</span>
        engine<span class="token operator">=</span>model_engine<span class="token punctuation">,</span>
        prompt<span class="token operator">=</span>prompt<span class="token punctuation">,</span>
        max_tokens<span class="token operator">=</span><span class="token number">1024</span><span class="token punctuation">,</span>
        n<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span>
        stop<span class="token operator">=</span><span class="token boolean">None</span><span class="token punctuation">,</span>
        temperature<span class="token operator">=</span><span class="token number">0.5</span><span class="token punctuation">,</span>
    <span class="token punctuation">)</span>

    message <span class="token operator">=</span> completions<span class="token punctuation">.</span>choices<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">.</span>text
    <span class="token keyword">return</span> message<span class="token punctuation">.</span>strip<span class="token punctuation">(</span><span class="token punctuation">)</span>

prompt <span class="token operator">=</span> <span class="token builtin">input</span><span class="token punctuation">(</span><span class="token string">"Enter your question: "</span><span class="token punctuation">)</span>
response <span class="token operator">=</span> generate_response<span class="token punctuation">(</span>prompt<span class="token punctuation">)</span>

<span class="token keyword">print</span><span class="token punctuation">(</span>response<span class="token punctuation">)</span>

</code></pre>



<p><em>You can find the source code in <a href="https://github.com/NextIdeaTechUS/chatgpt-python-example" class="ek-link">this</a> git repository.</em></p>



<p>Let’s run our script</p>



<pre class="wp-block-code language-python" tabindex="0"><code lang="python" class="language-python">python app<span class="token punctuation">.</span>py
Enter your question<span class="token punctuation">:</span>
</code></pre>



<p>Let’s say we want ChatGPT to create a function to retrieve data from an API endpoint:</p>



<pre class="wp-block-code"><code lang="" class="">Enter your question: write python code to get data from the weather api</code></pre>



<p>Here is the result</p>



<pre class="wp-block-code language-python" tabindex="0"><code lang="python" class="language-python"><span class="token keyword">import</span> requests

api_address<span class="token operator">=</span><span class="token string">'http://api.openweathermap.org/data/2.5/weather?appid=0c42f7f6b53b244cadb97fcb18feb5f6&amp;q=London'</span>

json_data <span class="token operator">=</span> requests<span class="token punctuation">.</span>get<span class="token punctuation">(</span>api_address<span class="token punctuation">)</span><span class="token punctuation">.</span>json<span class="token punctuation">(</span><span class="token punctuation">)</span>

formatted_data <span class="token operator">=</span> json_data<span class="token punctuation">[</span><span class="token string">'weather'</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token string">'main'</span><span class="token punctuation">]</span>

<span class="token keyword">print</span><span class="token punctuation">(</span>formatted_data<span class="token punctuation">)</span></code></pre>



<p>Note how the response uses the <em>actual </em>Weather API endpoint, moreover it knows <em>exactly </em>where the response is in the returned JSON object!</p>



<p>Let’s try another example. Let’s use one of the most asked questions on <a href="https://stackoverflow.com/questions/927358/how-do-i-undo-the-most-recent-local-commits-in-git" class="ek-link">Stackoverflow</a></p>



<pre class="wp-block-code"><code lang="" class="">Enter your question: How do I undo the most recent local commits in Git?

If you have not pushed the commits to a remote repository, you can use the "reset" command.

git reset HEAD~1</code></pre>



<h2><strong>Final Thoughts</strong></h2>



<p>One major advantage of ChatGPT is its ability to generate human-like responses. ChatGPT has been trained on a large dataset of human-human conversation, making it well-suited for generating responses that feel natural and authentic. Additionally, ChatGPT is able to generate responses to a wide range of prompts, making it a versatile choice for chatbot applications, content writing and many more.</p>



<p>However like most <a href="https://mindmajix.com/artificial-intelligence-technologies" class="ek-link">AI related innovations</a>, it has its pros and cons. One potential drawback of ChatGPT is its reliance on a large dataset for training. This means that it may not be well-suited for chatbot applications that require a deep understanding of niche topics or specialized language.</p>



<p></p>
					<!-- <section class="cta-card">
					  <div class="cta-card__container">
					    <div class="cta-card__header">
					      <p class="cta-card__title">Tell us the skills you need and we'll find the best developer for you in days, not weeks.</p>
					      <a href="https://nextideatech.com/contact/">Hire Developers</a>
					    </div>
					  </div>
					</section> -->

					<!-- subscribe form -->
					<div id="mc_embed_signup" class="subscribe-form">
						<form action="https://nextideatech.us7.list-manage.com/subscribe/post?u=ae45185df605e4c3b1371d09f&amp;id=22c96b1894&amp;f_id=0004c5e4f0" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate="novalidate">
							<div id="mc_embed_signup_scroll">
								<h4>Subscribe to our newsletter and get<br> exclusive content</h4>
								<div class="mc-field-group">
									<input type="email" value="" name="EMAIL" class="required email" placeholder="Email Address" id="mce-EMAIL" aria-required="true">
									<span id="mce-EMAIL-HELPERTEXT" class="helper_text"></span>
									<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">
								</div>
								<div id="mce-responses" class="clear foot">
									<div class="response" id="mce-error-response" style="display:none"></div>
									<div class="response" id="mce-success-response" style="display:none"></div>
								</div>
						    <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_ae45185df605e4c3b1371d09f_22c96b1894" tabindex="-1" value=""></div>
						   </div>
						</form>
					</div>
					<script type="text/javascript" src="//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js"></script>
					<script type="text/javascript">(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';fnames[3]='ADDRESS';ftypes[3]='address';fnames[4]='PHONE';ftypes[4]='phone';}(jQuery));var $mcj = jQuery.noConflict(true);</script>

				</div>

				<div class="col-lg-4 col-xl-4 blog-sidebar-col">
						<div id="sidebar">
		<div id="block-17" class="et_pb_widget widget_block">
<h5>Related Posts</h5>
</div><div id="block-18" class="et_pb_widget widget_block widget_recent_entries"><ul class="wp-block-latest-posts__list has-dates wp-block-latest-posts"><li><div class="wp-block-latest-posts__featured-image alignleft"><a href="https://blog.nextideatech.com/chatgpt-threat-freelance-workers/" aria-label="Is ChatGPT a Threat to the Gig Economy?"><img loading="lazy" width="300" height="169" src="https://blog.nextideatech.com/wp-content/uploads/2022/12/img_0120-2-2-300x169.png" class="attachment-medium size-medium wp-post-image" alt="chatgpt freelancers gig workers" style="" srcset="https://blog.nextideatech.com/wp-content/uploads/2022/12/img_0120-2-2-300x169.png 300w, https://blog.nextideatech.com/wp-content/uploads/2022/12/img_0120-2-2-1024x576.png 1024w, https://blog.nextideatech.com/wp-content/uploads/2022/12/img_0120-2-2-768x432.png 768w, https://blog.nextideatech.com/wp-content/uploads/2022/12/img_0120-2-2-1536x864.png 1536w, https://blog.nextideatech.com/wp-content/uploads/2022/12/img_0120-2-2-2048x1152.png 2048w" sizes="(max-width: 300px) 100vw, 300px"></a></div><a class="wp-block-latest-posts__post-title" href="https://blog.nextideatech.com/chatgpt-threat-freelance-workers/">Is ChatGPT a Threat to the Gig Economy?</a><time datetime="2022-12-24T15:04:08+00:00" class="wp-block-latest-posts__post-date">December 24, 2022</time></li>
<li><div class="wp-block-latest-posts__featured-image alignleft"><a href="https://blog.nextideatech.com/how-to-build-intelligent-chatbots-with-python-and-chatgpt/" aria-label="How To Build Intelligent Chatbots with Python and ChatGPT"><img width="240" height="300" src="https://blog.nextideatech.com/wp-content/uploads/2022/12/andrea-de-santis-zwd435-ewb4-unsplash-240x300.jpg" class="attachment-medium size-medium wp-post-image" alt="ChatGPT python" loading="lazy" style=""></a></div><a class="wp-block-latest-posts__post-title" href="https://blog.nextideatech.com/how-to-build-intelligent-chatbots-with-python-and-chatgpt/">How To Build Intelligent Chatbots with Python and ChatGPT</a><time datetime="2022-12-23T17:48:52+00:00" class="wp-block-latest-posts__post-date">December 23, 2022</time></li>
<li><div class="wp-block-latest-posts__featured-image alignleft"><a href="https://blog.nextideatech.com/how-to-set-up-flask-with-mongodb-and-docker-2022-complete-guide/" aria-label="How to Set Up Flask with MongoDB and Docker: 2022 Complete Guide"><img width="300" height="167" src="https://blog.nextideatech.com/wp-content/uploads/2022/12/flask-mongo-docker-300x167.png" class="attachment-medium size-medium wp-post-image" alt="How to Set Up Flask with MongoDB and Docker" loading="lazy" style=""></a></div><a class="wp-block-latest-posts__post-title" href="https://blog.nextideatech.com/how-to-set-up-flask-with-mongodb-and-docker-2022-complete-guide/">How to Set Up Flask with MongoDB and Docker: 2022 Complete Guide</a><time datetime="2022-12-16T16:59:32+00:00" class="wp-block-latest-posts__post-date">December 16, 2022</time></li>
</ul></div><div id="block-19" class="et_pb_widget widget_block">
<div class="sticky-block-wrapper sticky-block-wrapper-0"><div class="sticky-block-placeholder sticky-block-placeholder-0" style="width:0; height:0; margin:0; padding:0; visibility:hidden;"></div><div class="wp-block-senff-sticky-block senff-sticky-block-0 sticky-block-original-0 block-is-not-sticky sticky-block-active-0" data-topspace="100" data-cfa="true" data-minwidth="980" data-maxwidth="99999" data-pushup="#main-footer" data-zindex="1" style="">
<h5>Share</h5>


<p></p><div class="addtoany_shortcode"><div class="a2a_kit a2a_kit_size_32 addtoany_list" data-a2a-url="https://blog.nextideatech.com/how-to-build-intelligent-chatbots-with-python-and-chatgpt/" data-a2a-title="How To Build Intelligent Chatbots with Python and ChatGPT" style="line-height: 32px;"><a class="a2a_button_facebook" href="/#facebook" title="Facebook" rel="nofollow noopener" target="_blank"><span class="a2a_svg a2a_s__default a2a_s_facebook" style="background-color: rgb(10, 107, 216);"><svg focusable="false" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><path fill="#FFF" d="M17.78 27.5V17.008h3.522l.527-4.09h-4.05v-2.61c0-1.182.33-1.99 2.023-1.99h2.166V4.66c-.375-.05-1.66-.16-3.155-.16-3.123 0-5.26 1.905-5.26 5.405v3.016h-3.53v4.09h3.53V27.5h4.223z"></path></svg></span><span class="a2a_label">Facebook</span></a><a class="a2a_button_twitter" href="/#twitter" title="Twitter" rel="nofollow noopener" target="_blank"><span class="a2a_svg a2a_s__default a2a_s_twitter" style="background-color: rgb(10, 107, 216);"><svg focusable="false" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><path fill="#FFF" d="M28 8.557a9.913 9.913 0 0 1-2.828.775 4.93 4.93 0 0 0 2.166-2.725 9.738 9.738 0 0 1-3.13 1.194 4.92 4.92 0 0 0-3.593-1.55 4.924 4.924 0 0 0-4.794 6.049c-4.09-.21-7.72-2.17-10.15-5.15a4.942 4.942 0 0 0-.665 2.477c0 1.71.87 3.214 2.19 4.1a4.968 4.968 0 0 1-2.23-.616v.06c0 2.39 1.7 4.38 3.952 4.83-.414.115-.85.174-1.297.174-.318 0-.626-.03-.928-.086a4.935 4.935 0 0 0 4.6 3.42 9.893 9.893 0 0 1-6.114 2.107c-.398 0-.79-.023-1.175-.068a13.953 13.953 0 0 0 7.55 2.213c9.056 0 14.01-7.507 14.01-14.013 0-.213-.005-.426-.015-.637.96-.695 1.795-1.56 2.455-2.55z"></path></svg></span><span class="a2a_label">Twitter</span></a><a class="a2a_button_pinterest" href="/#pinterest" title="Pinterest" rel="nofollow noopener" target="_blank"><span class="a2a_svg a2a_s__default a2a_s_pinterest" style="background-color: rgb(10, 107, 216);"><svg focusable="false" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><path fill="#FFF" d="M16.539 4.5c-6.277 0-9.442 4.5-9.442 8.253 0 2.272.86 4.293 2.705 5.046.303.125.574.005.662-.33.061-.231.205-.816.27-1.06.088-.331.053-.447-.191-.736-.532-.627-.873-1.439-.873-2.591 0-3.338 2.498-6.327 6.505-6.327 3.548 0 5.497 2.168 5.497 5.062 0 3.81-1.686 7.025-4.188 7.025-1.382 0-2.416-1.142-2.085-2.545.397-1.674 1.166-3.48 1.166-4.689 0-1.081-.581-1.983-1.782-1.983-1.413 0-2.548 1.462-2.548 3.419 0 1.247.421 2.091.421 2.091l-1.699 7.199c-.505 2.137-.076 4.755-.039 5.019.021.158.223.196.314.077.13-.17 1.813-2.247 2.384-4.324.162-.587.929-3.631.929-3.631.46.876 1.801 1.646 3.227 1.646 4.247 0 7.128-3.871 7.128-9.053.003-3.918-3.317-7.568-8.361-7.568z"></path></svg></span><span class="a2a_label">Pinterest</span></a><a class="a2a_button_linkedin" href="/#linkedin" title="LinkedIn" rel="nofollow noopener" target="_blank"><span class="a2a_svg a2a_s__default a2a_s_linkedin" style="background-color: rgb(10, 107, 216);"><svg focusable="false" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><path d="M6.227 12.61h4.19v13.48h-4.19V12.61zm2.095-6.7a2.43 2.43 0 0 1 0 4.86c-1.344 0-2.428-1.09-2.428-2.43s1.084-2.43 2.428-2.43m4.72 6.7h4.02v1.84h.058c.56-1.058 1.927-2.176 3.965-2.176 4.238 0 5.02 2.792 5.02 6.42v7.395h-4.183v-6.56c0-1.564-.03-3.574-2.178-3.574-2.18 0-2.514 1.7-2.514 3.46v6.668h-4.187V12.61z" fill="#FFF"></path></svg></span><span class="a2a_label">LinkedIn</span></a><a class="a2a_button_email" href="/#email" title="Email" rel="nofollow noopener" target="_blank"><span class="a2a_svg a2a_s__default a2a_s_email" style="background-color: rgb(10, 107, 216);"><svg focusable="false" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><path fill="#FFF" d="M26 21.25v-9s-9.1 6.35-9.984 6.68C15.144 18.616 6 12.25 6 12.25v9c0 1.25.266 1.5 1.5 1.5h17c1.266 0 1.5-.22 1.5-1.5zm-.015-10.765c0-.91-.265-1.235-1.485-1.235h-17c-1.255 0-1.5.39-1.5 1.3l.015.14s9.035 6.22 10 6.56c1.02-.395 9.985-6.7 9.985-6.7l-.015-.065z"></path></svg></span><span class="a2a_label">Email</span></a></div></div><p></p>
</div></div>
</div>	</div>
				</div>

			</div>
		</div>