How to Build a Python ChatGPT App: Step‑by‑Step API Guide

This tutorial walks you through accessing the OpenAI ChatGPT API with Python, covering account setup, API key generation, code examples for basic calls, custom system instructions, conversation memory handling, and building a simple GUI chatbot using tkinter or Gradio.

21CTO
21CTO
21CTO
How to Build a Python ChatGPT App: Step‑by‑Step API Guide

In this tutorial we explain how to use the ChatGPT API in Python with practical examples.

Steps to Access the ChatGPT API

Visit the OpenAI Platform at https://platform.openai.com/ and sign up using a Google, Microsoft, or Apple account.

After creating an account, generate a secret API key (example shown below): sk-xxxxxxxxxxxxxxxxxxxx

If your phone number has not been linked to any other OpenAI account you may receive free credits for testing; otherwise you need to add at least $5, with costs depending on usage and model type.

Now you can call the API using the code provided later.

Python Code to Access the ChatGPT API

Step 1: Install the OpenAI Python library: pip install openai Step 2: Set your API key and provide your prompt in the code parameters.

import os
import openai

# Set API Key
os.environ["OPENAI_API_KEY"] = "sk-xxxxxxxxxxxxxxxxxxxxxx"
openai.api_key = os.getenv("OPENAI_API_KEY")

def chatGPT(prompt, model="gpt-3.5-turbo", temperature=0.7, top_p=1):
    error_message = ""
    try:
        response = openai.ChatCompletion.create(
            model=model,
            messages=[{'role': 'user', 'content': prompt}],
            temperature=temperature,
            top_p=top_p
        )
    except Exception as e:
        error_message = str(e)
    if error_message:
        return "An error occurred: {}".format(error_message)
    else:
        return response['choices'][0]['message']['content']

# Run Function
print(chatGPT("efficient way to remove duplicates in python. Less verbose response."))

In the model parameter you can specify gpt-3.5-turbo, gpt-4-turbo or gpt-4, which point to the latest versions of each model.

ChatGPT Custom Instructions

If you want ChatGPT to follow advanced instructions when responding, you can provide a system_instruction argument.

# System Message
def chatGPT(prompt, system_instruction=None, model="gpt-3.5-turbo", temperature=0.7, top_p=1):
    error_message = ""
    try:
        messages = [{'role': 'user', 'content': prompt}]
        if system_instruction:
            messages.insert(0, {'role': 'system', 'content': system_instruction})
        response = openai.ChatCompletion.create(
            model=model,
            messages=messages,
            temperature=temperature,
            top_p=top_p
        )
    except Exception as e:
        error_message = str(e)
    if error_message:
        return "An error occurred: {}".format(error_message)
    else:
        return response['choices'][0]['message']['content']

print(chatGPT(prompt="who are you and what do you do?", system_instruction="You are Janie Jones, the CEO of Jones Auto."))

How to Chat Like the Official ChatGPT Site

The ChatGPT website remembers previous turns in a conversation. The API does not do this automatically, but you can achieve the same effect by sending the full conversation history with each request.

# ChatGPT Chat
import os
import openai
os.environ['OPENAI_API_KEY'] = "sk-xxxxxxxxxxxxxxxxxxxxxxx"
openai.api_key = os.getenv('OPENAI_API_KEY')

chatHistory = []

def chatGPT_chat(prompt, modelName="gpt-3.5-turbo", temperature=0.7, top_p=1):
    params = {"model": modelName, "temperature": temperature, "top_p": top_p}
    chatHistory.append({"role": "user", "content": prompt})
    response = openai.ChatCompletion.create(**params, messages=chatHistory)
    answer = response["choices"][0]["message"]["content"].strip()
    chatHistory.append({"role": "assistant", "content": answer})
    return answer

print(chatGPT_chat("2*3"))  # 6
print(chatGPT_chat("square of it"))  # The square of 6 is 36.
print(chatGPT_chat("add 3 to it"))  # Adding 3 to 36, we get 39.

Building a Chatbot with the ChatGPT API

The following example uses the tkinter library to create a simple GUI application.

Install tkinter with:

pip install tkinter
import os
import openai
import tkinter as tk

# Set API Key
os.environ["OPENAI_API_KEY"] = "sk-xxxxxxxxxxxxxxxxxxxxxx"
openai.api_key = os.getenv("OPENAI_API_KEY")

def chatGPT(prompt, model="gpt-3.5-turbo", temperature=0.7, top_p=1):
    error_message = ""
    try:
        response = openai.ChatCompletion.create(
            model=model,
            messages=[{'role': 'user', 'content': prompt}],
            temperature=temperature,
            top_p=top_p
        )
    except Exception as e:
        error_message = str(e)
    if error_message:
        return "An error occurred: {}".format(error_message)
    else:
        return response['choices'][0]['message']['content']

# GUI Application

def chatgpt_output():
    input_text = input_field.get()
    model_name = dropdown_var.get()
    response = chatGPT(input_text, model_name)
    output_field.config(state='normal')
    output_field.delete('1.0', tk.END)
    output_field.insert(tk.END, response)
    output_field.config(state='disabled')

root = tk.Tk()
root.title("ChatGPT")
root.geometry("600x700")

options = ["gpt-3.5-turbo", "gpt-4", "gpt-4-turbo"]

dropdown_var = tk.StringVar(root)
dropdown_var.set(options[0])

dropdown = tk.OptionMenu(root, dropdown_var, *options)
dropdown.pack(pady=5)

input_label = tk.Label(root, text="Enter Your Prompt:")
input_label.pack(pady=5)
input_field = tk.Entry(root, width=50)
input_field.pack(pady=5)

submit_button = tk.Button(root, text="Submit", command=chatgpt_output)
submit_button.pack(pady=10)

output_field = tk.Text(root, state='disabled')
output_field.pack(pady=10)

root.mainloop()

How to Improve the Chatbot Appearance?

The default tkinter GUI lacks modern visual appeal. To build a more stylish interface you can use the Gradio library instead.

Author: 万能的大雄
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonAIChatGPTAPIOpenAITutorialTkinter
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.