天天看點

在 Python 中使用 ChatGPT API 的 4 種方法

作者:不秃頭程式員
在 Python 中使用 ChatGPT API 的 4 種方法

在本教程中,我們将通過示例解釋如何在 Python 中使用 ChatGPT API。

通路 ChatGPT API 的步驟

請按照以下步驟通路 ChatGPT API。

  1. 通路OpenAI Platform。
  2. 使用您的 Google、Microsoft 或 Apple 帳戶進行注冊。位址為:
  3. https://platform.openai.com/
  4. 建立帳戶後,下一步是生成秘密 API 密鑰以通路 API。
  5. API 密鑰如右所示 -sk-xxxxxxxxxxxxxxxxxxxx
  6. 如果你的電話号碼之前未與任何其他 OpenAI 帳戶關聯,可能會獲得免費積分來測試 API。
  7. 否則需要在你的帳戶中添加至少 5 美元,費用将根據使用的使用情況和型号類型而定。
  8. 具體還可以檢視OpenAI 網站上的定價詳細資訊。
  9. 現在,就可以使用下面的代碼調用 API。

通路 ChatGPT API 的 Python 代碼

步驟 1:要安裝 OpenAI Python 庫,請運作以下指令:pip install openai

第 2 步:輸入你的 API 密鑰,并在下面代碼的參數中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."))           

在模型參數中,可以輸入gpt-3.5-turbo、gpt-4-turbo或gpt-4,指向各自的最新模型版本。

在 Python 中使用 ChatGPT API 的 4 種方法

ChatGPT 自定義指令

如果希望 ChatGPT 在提供響應時使用一些進階指令。

也就是說,希望 ChatGPT 了解你的哪些資訊以提供響應。例如,你希望模型“像語言專家一樣行事,并用外行人的術語提供響應”。可以system_instruction在下面的代碼中的參數中輸入指令。

# 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."))           
在 Python 中使用 ChatGPT API 的 4 種方法

如何像 ChatGPT 官網一樣交談

ChatGPT 網站會記住之前的對話,同時提供目前問題的答複。例如:你問“2+2”,它回答“4”。然後你問諸如“它的平方是多少”之類的後續問題,它會傳回“16”。是以它會記住之前的“2+2”響應。

預設情況下,ChatGPT API 不會記住之前的對話。但是,我們可以通過在每個 API 請求中向 ChatGPT API 提供之前的問題和響應,讓 ChatGPT API 記住之前的對話。

# 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.           

使用 ChatGPT API 建構聊天機器人

在下面的代碼中,我們使用 Python 庫建構一個應用程式tkinter,該庫建立圖形使用者界面 (GUI)。它包括多個小部件,例如文本框、按鈕、下拉菜單等。

要安裝 tkinter 庫,請運作以下指令:

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()           
在 Python 中使用 ChatGPT API 的 4 種方法

如何改善聊天機器人的外觀?

可使用 tkinter 庫開發的 GUI 缺乏精美的視覺效果。要建構更現代、更時尚的界面,可以使用Gradio包。

繼續閱讀