laitimes

4 Ways to Use ChatGPT API in Python

author:Not bald programmer
4 Ways to Use ChatGPT API in Python

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

访问 ChatGPT API 的步骤

Follow the steps below to access the ChatGPT API.

  1. 访问OpenAI Platform。
  2. Sign up with your Google, Microsoft, or Apple account. The address is:
  3. https://platform.openai.com/
  4. Once you've created your account, the next step is to generate a secret API key to access the API.
  5. API 密钥如右所示 -sk-xxxxxxxxxxxxxxxxxxxx
  6. If your phone number hasn't been previously associated with any other OpenAI account, you may receive a free credit to test the API.
  7. Otherwise, you'll need to add at least $5 to your account, and the cost will be based on the usage and model type used.
  8. You can also check out the pricing details on the OpenAI website.
  9. Now you can call the API using the code below.

访问 Chatgopot API 的 Python 代码

步骤 1:要安装 OpenAI Python 库,请运行以下命令:pip install openai

Step 2: Enter your API key and enter the question you want to ask in the arguments of the code below os.environ["OPENAI_API_KEY"] =.

prompt

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 parameters, you can enter GPT-3.5-Turbo, GPT-4-Turbo, or GPT-4 to point to the latest model version.

4 Ways to Use ChatGPT API in Python

ChatGPT 自定义指令

If you want ChatGPT to use some advanced instructions when providing a response.

That is, what information about you is expected to be understood by ChatGPT to provide a response. For example, you want the model to "act like a linguist and provide responses in layman's terms." You can system_instruction enter the directive in the argument in the code below.

# 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']

# Run Function    
print(chatGPT(prompt = "who are you and what do you do?",
              system_instruction = "You are Janie Jones, the CEO of Jones Auto."))           
4 Ways to Use ChatGPT API in Python

How to talk like ChatGPT's official website

The ChatGPT website remembers previous conversations while providing responses to current questions. For example, if you ask "2+2", it answers "4". Then you ask follow-up questions like "how is it squared" and it returns "16". So it remembers the previous "2+2" response.

By default, the ChatGPT API does not remember previous conversations. However, we can get the ChatGPT API to remember the previous conversation by providing the ChatGPT API with previous questions and responses in each API 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

chatGPT_chat("2*3")
# 6

chatGPT_chat("square of it")
# The square of 6 is 36.

chatGPT_chat("add 3 to it")
# Adding 3 to 36, we get 39.           

Build a chatbot using the ChatGPT API

In the following code, we build an application tkinter using a Python library that creates a graphical user interface (GUI). It includes multiple widgets such as text boxes, buttons, drop-down menus, and more.

To install the tkinter library, run the following command:

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']

# tikinter 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')

# Define the function to get the selected option
def on_select(value):
    print("Selected model:", value)

# Create the main window
root = tk.Tk()
root.title("ChatGPT")
root.geometry("600x700")

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

# Create a label
label = tk.Label(root, text="Select Model:", font=("Arial", 12, "italic"))
label.pack()

# Create dropdown menu
dropdown_var = tk.StringVar(root)
dropdown_var.set(options[0])
dropdown_font = ('Arial', 12)
dropdown = tk.OptionMenu(root, dropdown_var, *options, command=on_select)
dropdown.config(font=dropdown_font)
dropdown.pack()

# Create a label for the input field
input_label = tk.Label(root, text="Enter Your Prompt:", font=("Arial", 14, "italic"))
input_label.pack(pady=5)

# Create input field
input_field = tk.Entry(root, font=("Arial", 14), width=50, bd=2, relief="groove", justify="left")
input_field.pack(pady=5, ipady=15)

# Create submit button
submit_button = tk.Button(root, text="Submit", font=("Arial", 14), command=chatgpt_output)
submit_button.pack(pady=10)

# Create output box
output_field = tk.Text(root, font=("Arial", 14), state='disabled')
output_field.pack(pady=10)

# Start
root.mainloop()           
4 Ways to Use ChatGPT API in Python

How can I improve the appearance of my chatbot?

GUIs that can be developed using the tkinter library lack beautiful visuals. To build a more modern and sleek interface, you can use the Gradio package.

Read on