slot deposit pulsa slot mahjong slot gacor slot gacor slot gacor resmi slot gacor 2025 slot gacor terpercaya slot gacor 2025 slot gacor hari ini slot gacor hari ini slot gacor hari ini
在 Python 中使用 ChatGPT API 的 4 种方法
17611538698
webmaster@21cto.com

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

人工智能 0 877 2024-04-24 02:05:18

图片

在本教程中,我们将通过示例解释如何在 Python 中使用 ChatGPT API。

访问 ChatGPT API 的步骤

请按照以下步骤访问 ChatGPT API。

  1. 访问OpenAI Platform。

    使用您的 Google、Microsoft 或 Apple 帐户进行注册。地址为:

    https://platform.openai.com/

  2. 创建帐户后,下一步是生成秘密 API 密钥以访问 API。

    API 密钥如右所示 -sk-xxxxxxxxxxxxxxxxxxxx

  3. 如果你的电话号码之前未与任何其他 OpenAI 帐户关联,可能会获得免费积分来测试 API。

    否则需要在你的帐户中添加至少 5 美元,费用将根据使用的使用情况和型号类型而定。

    具体还可以查看OpenAI 网站上的定价详细信息。

  4. 现在,就可以使用下面的代码调用 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-turbogpt-4-turbogpt-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."))

图片

如何像 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()

图片

如何改善聊天机器人的外观?

可使用 tkinter 库开发的 GUI 缺乏精美的视觉效果。要构建更现代、更时尚的界面,可以使用Gradio包。


评论