Bootstrap

调用open.ai接口实现人工智能对话

1.环境需要魔法

2.需要chatgpt账号

效果如下:

这是无界面的版本:

 

代码如下版本1 :

import openai
import tkinter as tk

def openai_reply(messages, apikey):
    openai.api_key = apikey
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo-0301",
        messages=messages,
        temperature=0.5,
        max_tokens=1000,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0,
    )
    return response.choices[0].message.content

def send_message():
    user_input = user_input_entry.get()
    conversation.append({"role": "user", "content": user_input})
    ans = openai_reply(conversation, '你的密钥')
    conversation.append({"role": "assistant", "content": ans})
    chat_text.config(state=tk.NORMAL)
    chat_text.insert(tk.END, "你: " + user_input + "\n")
    chat_text.insert(tk.END, "助手: " + ans + "\n")
    chat_text.config(state=tk.DISABLED)
    user_input_entry.delete(0, tk.END)

conversation = [
    {"role": "system", "content": "你是一个有帮助的助手。"},
]

# 创建GUI窗口
window = tk.Tk()
window.title("AL聊天")

# 创建聊天历史显示区域
chat_text = tk.Text(window, state=tk.DISABLED)
chat_text.pack()

# 创建用户输入框和发送按钮
user_input_entry = tk.Entry(window)
user_input_entry.pack()
send_button = tk.Button(window, text="发送", command=send_message)
send_button.pack()

window.mainloop()

版本2:

import openai

def openai_reply(messages, apikey):
    openai.api_key = apikey
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo-0301",
        messages=messages,
        temperature=0.5,
        max_tokens=1000,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0,
    )
    return response.choices[0].message.content

if __name__ == '__main__':
    conversation = [
        {"role": "system", "content": "你是一个有帮助的助手。"},
    ]

    while True:
        user_input = input("你: ")
        conversation.append({"role": "user", "content": user_input})

        # 生成助手的回复
        ans = openai_reply(conversation, '你的密钥')
        print("助手:", ans)

        # 将助手的回复添加到对话中
        conversation.append({"role": "机器人", "content": ans})

 

;