最近ChatGpt挺火的,闲来无事在家使用Python的PyQt6库写了一个调用ChatGpt的GUI程序。记住无论如何调用ChatGpt,一定要先安装openai库。
pip3 install openai
下面直接晒代码吧:
import sys
from PyQt6.QtWidgets import (QWidget, QLabel, QLineEdit, QTextEdit, QGridLayout, QApplication, QPushButton)
import openaiopenai.api_key = "<YOUR-API-KEY>" # 请自行注册OpenAi账号,获取API KEYclass ChatGPT(QWidget):def __init__(self):super().__init__()self.initUI()def initUI(self):self.resize(400, 300)self.setWindowTitle('ChatGPT')self.label = QLabel('输入问题:')self.lineEdit = QLineEdit()self.okButton = QPushButton('确定')self.textEdit = QTextEdit()grid = QGridLayout()grid.setSpacing(10)grid.addWidget(self.label, 0, 0)grid.addWidget(self.okButton, 0, 2)grid.addWidget(self.lineEdit, 0, 1)grid.addWidget(self.textEdit, 1, 0, 1, 3)self.setLayout(grid)self.okButton.pressed.connect(self.getAnswer)def getAnswer(self):question = self.lineEdit.text()completion = openai.Completion.create(engine="text-davinci-002",prompt=question,max_tokens=1024,temperature=0.5)answer = completion.choices[0].text.strip()self.textEdit.setText(answer)if __name__ == '__main__':app = QApplication(sys.argv)ex = ChatGPT()ex.show()sys.exit(app.exec())
运行以后的效果如下:
由于晚上时间有限,程序没有做异常处理,调用失败程序会异常退出。有兴趣的朋友可以自己把异常处理的代码补起来。