8000 Move the responsibility of setting the api key for each platform to u… · DataSolveProblems/pyqt-openai@2495726 · GitHub
[go: up one dir, main page]

Skip to content

Commit 2495726

Browse files
committed
Move the responsibility of setting the api key for each platform to usingApiPage
1 parent 031c97a commit 2495726

File tree

10 files changed

+66
-106
lines changed

10 files changed

+66
-106
lines changed

pyqt_openai/chat_widget/center/chatHome.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,26 +16,26 @@ def __init__(self, parent=None):
1616

1717
def __initUi(self):
1818
title = QLabel(f"Welcome to {DEFAULT_APP_NAME}!", self)
19-
title.setFont(QFont(LARGE_LABEL_PARAM))
19+
title.setFont(QFont(*LARGE_LABEL_PARAM))
2020
title.setAlignment(Qt.AlignmentFlag.AlignCenter)
2121

2222
description = QLabel(LangClass.TRANSLATIONS['Enjoy convenient chatting, all day long!'])
2323

2424
self.__quickStartManualLbl = LinkLabel()
2525
self.__quickStartManualLbl.setText(LangClass.TRANSLATIONS['Quick Start Manual'])
2626
self.__quickStartManualLbl.setUrl(HOW_TO_GET_OPENAI_API_KEY_URL)
27-
self.__quickStartManualLbl.setFont(QFont(MEDIUM_LABEL_PARAM))
27+
self.__quickStartManualLbl.setFont(QFont(*MEDIUM_LABEL_PARAM))
2828
self.__quickStartManualLbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
2929

3030
self.__openaiApiManualLbl = LinkLabel()
3131
self.__openaiApiManualLbl.setText(LangClass.TRANSLATIONS['How to get OpenAI API Key?'])
3232
self.__openaiApiManualLbl.setUrl(HOW_TO_GET_OPENAI_API_KEY_URL)
33-
self.__openaiApiManualLbl.setFont(QFont(MEDIUM_LABEL_PARAM))
33+
self.__openaiApiManualLbl.setFont(QFont(*MEDIUM_LABEL_PARAM))
3434
self.__openaiApiManualLbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
3535

3636
self.__background_image = QLabel()
3737

38-
description.setFont(QFont(MEDIUM_LABEL_PARAM))
38+
description.setFont(QFont(*MEDIUM_LABEL_PARAM))
3939
description.setAlignment(Qt.AlignmentFlag.AlignCenter)
4040

4141
lay = QVBoxLayout()

pyqt_openai/chat_widget/chatMainWidget.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff lin 9E88 e numberDiff line change
@@ -16,7 +16,6 @@
1616
from pyqt_openai.lang.translations import LangClass
1717
from pyqt_openai.models import ChatThreadContainer, ChatMessageContainer, CustomizeParamsContainer
1818
from pyqt_openai.globals import DB, LLAMAINDEX_WRAPPER
19-
from pyqt_openai.globals import is_openai_enabled
2019
from pyqt_openai.util.script import open_directory, get_generic_ext_out_of_qt_ext, message_list_to_txt, \
2120
conv_unit_to_html, \
2221
add_file_to_zip, getSeparator
@@ -277,4 +276,4 @@ def __showFavorite(self, f):
277276
else:
278277
lst = [ChatMessageContainer(**dict(c)) for c in lst]
279278
self.__browser.replaceThreadForFavorite(lst)
280-
self.__chatWidget.setAIEnabled(not f and is_openai_enabled())
279+
self.__chatWidget.setAIEnabled(not f)

pyqt_openai/apiDialog.py renamed to pyqt_openai/chat_widget/right_sidebar/apiWidget.py

Lines changed: 28 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
from PySide6.QtWidgets import QVBoxLayout, QTableWidget, QHeaderView, QTableWidgetItem, QLabel, QLineEdit, QDialog, \
2-
QDialogButtonBox
31
from PySide6.QtCore import Qt
2+
from PySide6.QtWidgets import QVBoxLayout, QTableWidget, QHeaderView, QTableWidgetItem, QLabel, QLineEdit, \
3+
QDialogButtonBox, QWidget, QPushButton
44

55
from pyqt_openai import HOW_TO_GET_OPENAI_API_KEY_URL, HOW_TO_GET_CLAUDE_API_KEY_URL, HOW_TO_GET_GEMINI_API_KEY_URL, \
6-
HOW_TO_GET_LLAMA_API_KEY_URL
6+
HOW_TO_GET_LLAMA_API_KEY_URL, DEFAULT_API_CONFIGS
7+
from pyqt_openai.config_loader import CONFIG_MANAGER
8+
from pyqt_openai.globals import set_api_key
79
from pyqt_openai.widgets.linkLabel import LinkLabel
810

911

@@ -14,14 +16,22 @@
1416
# print(f)
1517

1618

17-
class ApiDialog(QDialog):
18-
def __init__(self, api_keys: list, parent=None):
19+
class ApiWidget(QWidget):
20+
def __init__(self, parent=None):
1921
super().__init__(parent)
20-
self.__initVal(api_keys)
22+
self.__initVal()
2123
self.__initUi()
2224

23-
def __initVal(self, api_keys):
24-
self.__api_keys = api_keys
25+
def __initVal(self):
26+
self.__api_keys = []
27+
# Get the api keys from the conf file with the env var name
28+
for conf in DEFAULT_API_CONFIGS:
29+
_conf = {
30+
'display_name': conf['display_name'],
31+
'env_var_name': conf['env_var_name'],
32+
'api_key': CONFIG_MANAGER.get_general_property(conf['env_var_name'])
33+
}
34+
self.__api_keys.append(_conf)
2535

2636
# Set "get api key" here
2737
for i, obj in enumerate(self.__api_keys):
@@ -57,23 +67,25 @@ def __initUi(self):
5767
getApiKeyLbl.setUrl(obj['get_api_key'])
5868
self.__tableWidget.setCellWidget(i, 2, getApiKeyLbl)
5969

60-
# Dialog buttons
61-
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
62-
buttonBox.accepted.connect(self.accept)
63-
buttonBox.rejected.connect(self.reject)
70+
saveBtn = QPushButton('Save')
71+
saveBtn.clicked.connect(self.setApiKeys)
6472

6573
lay = QVBoxLayout()
6674
lay.addWidget(QLabel('API Key'))
6775
lay.addWidget(self.__tableWidget)
68-
lay.addWidget(buttonBox)
76+
lay.addWidget(saveBtn)
77+
lay.setContentsMargins(0, 0, 0, 0)
6978

7079
self.setLayout(lay)
7180

72-
self.setMinimumWidth(600)
81+
self.setMinimumHeight(150)
7382

74-
def getApiKeys(self) -> dict:
83+
def setApiKeys(self):
7584
"""
7685
Dynamically get the api keys from the table widget
7786
"""
7887
api_keys = {self.__api_keys[i]['env_var_name']: self.__tableWidget.cellWidget(i, 1).text() for i in range(self.__tableWidget.rowCount())}
79-
return api_keys
88+
# Save the api keys to the conf file
89+
for k, v in api_keys.items():
90+
CONFIG_MANAGER.set_general_property(k, v)
91+
set_api_key(k, v)

pyqt_openai/chat_widget/right_sidebar/llama_widget/llamaPage.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
from pyqt_openai.chat_widget.right_sidebar.llama_widget.listWidget import FileListWidget
99
from pyqt_openai.lang.translations import LangClass
1010

11-
1211
class LlamaPage(QWidget):
1312
onDirectorySelected = Signal(str)
1413

@@ -18,7 +17,7 @@ def __init__(self, parent=None):
1817

1918
def __initUi(self):
2019
self.__apiCheckPreviewLbl = QLabel()
21-
self.__apiCheckPreviewLbl.setFont(QFont(SMALL_LABEL_PARAM))
20+
self.__apiCheckPreviewLbl.setFont(QFont(*SMALL_LABEL_PARAM))
2221

2322
self.__listWidget = FileListWidget()
2423
self.__listWidget.clicked.connect(self.__setTextInBrowser)

pyqt_openai/chat_widget/right_sidebar/usingAPIPage.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from pyqt_openai import DEFAULT_SHORTCUT_JSON_MODE, OPENAI_TEMPERATURE_RANGE, OPENAI_TEMPERATURE_STEP, \
66
MAX_TOKENS_RANGE, TOP_P_RANGE, TOP_P_STEP, FREQUENCY_PENALTY_RANGE, PRESENCE_PENALTY_STEP, PRESENCE_PENALTY_RANGE, \
77
FREQUENCY_PENALTY_STEP, LLAMAINDEX_URL
8+
from pyqt_openai.chat_widget.right_sidebar.apiWidget import ApiWidget
89
from pyqt_openai.config_loader import CONFIG_MANAGER
910
from pyqt_openai.lang.translations import LangClass
1011
from pyqt_openai.globals import get_chat_model, init_llama, get_openai_chat_model
@@ -55,6 +56,8 @@ def __initUi(self):
5556
lay.addWidget(modelCmbBox)
5657
lay.setContentsMargins(0, 0, 0, 0)
5758

59+
apiWidget = ApiWidget()
60+
5861
selectModelWidget = QWidget()
5962
selectModelWidget.setLayout(lay)
6063

@@ -166,19 +169,19 @@ def __initUi(self):
166169
self.__llamaChkBox.toggled.connect(self.__use_llama_indexChecked)
167170
self.__llamaChkBox.setText(LangClass.TRANSLATIONS['Use LlamaIndex'])
168171

169-
sep = getSeparator('horizontal')
170-
171172
lay = QVBoxLayout()
172173
lay.addWidget(systemlbl)
173174
lay.addWidget(self.__systemTextEdit)
174175
lay.addWidget(saveSystemBtn)
176+
lay.addWidget(getSeparator('horizontal'))
177+
lay.addWidget(apiWidget)
175178
lay.addWidget(selectModelWidget)
176179
lay.addWidget(self.__warningLbl)
177180
lay.addWidget(streamChkBox)
178181
lay.addWidget(self.__jsonChkBox)
179182
lay.addWidget(self.__llamaChkBox)
180183
lay.addWidget(llamaManualLbl)
181-
lay.addWidget(sep)
184+
lay.addWidget(getSeparator('horizontal'))
182185
lay.addWidget(advancedSettingsGrpBox)
183186
lay.setAlignment(Qt.AlignmentFlag.AlignTop)
184187

pyqt_openai/dalle_widget/dalleHome.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,12 @@ def __init__(self, parent=None):
1212

1313
def __initUi(self):
1414
title = QLabel('Welcome to DALL-E Page !', self)
15-
title.setFont(QFont(LARGE_LABEL_PARAM))
15+
title.setFont(QFont(*LARGE_LABEL_PARAM))
1616
title.setAlignment(Qt.AlignmentFlag.AlignCenter)
1717

1818
description = QLabel('Generate images with DALL-E.' + CONTEXT_DELIMITER)
1919

20-
description.setFont(QFont(MEDIUM_LABEL_PARAM))
20+
description.setFont(QFont(*MEDIUM_LABEL_PARAM))
2121
description.setAlignment(Qt.AlignmentFlag.AlignCenter)
2222

2323
lay = QVBoxLayout()

pyqt_openai/globals.py

Lines changed: 17 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,6 @@
2525
from pyqt_openai.sqlite import SqliteDatabase
2626
from pyqt_openai.util.llamapage_script import GPTLLamaIndexWrapper
2727

28-
os.environ['OPENAI_API_KEY'] = ''
29-
3028
DB = SqliteDatabase()
3129

3230
LLAMAINDEX_WRAPPER = GPTLLamaIndexWrapper()
@@ -41,21 +39,9 @@
4139
base_url=LLAMA_REQUEST_URL
4240
)
4341

44-
OPENAI_API_VALID = False
45-
46-
def set_openai_enabled(f):
47-
global OPENAI_API_VALID
48-
OPENAI_API_VALID = f
49-
return OPENAI_API_VALID
50-
51-
def is_openai_enabled():
52-
return OPENAI_API_VALID
53-
54-
def set_openai_api_key(api_key):
55-
os.environ['OPENAI_API_KEY'] = api_key
56-
OPENAI_CLIENT.api_key = os.environ['OPENAI_API_KEY']
57-
5842
def set_api_key(env_var_name, api_key):
43+
if env_var_name == 'OPENAI_API_KEY':
44+
OPENAI_CLIENT.api_key = api_key
5945
if env_var_name == 'GEMINI_API_KEY':
6046
genai.configure(api_key=api_key)
6147
if env_var_name == 'CLAUDE_API_KEY':
@@ -289,15 +275,23 @@ def get_api_response(args, get_content_only=True):
289275
else:
290276
return response
291277

278+
def get_g4f_response(args, get_content_only=True):
279+
response = G4F_CLIENT.chat.completions.create(
280+
model=args['model'],
281+
stream=args['stream'],
282+
messages=args['messages'],
283+
)
284+
if args['stream']:
285+
return stream_response(platform='', response=response, is_g4f=True)
286+
else:
287+
if get_content_only:
288+
return response.choices[0].message.content
289+
else:
290+
return response
291+
292292
def get_response(args, get_content_only=True, is_g4f=False):
293293
if is_g4f:
294-
response = G4F_CLIENT.chat.completions.create(
295-
model=args['model'],
296-
stream=args['stream'],
297-
messages=args['messages'],
298-
)
299-
# Platform doesn't matter in G4F
300-
return stream_response(platform='', response=response, is_g4f=True)
294+
return get_g4f_response(args, get_content_only)
301295
else:
302296
return get_api_response(args, get_content_only)
303297

@@ -307,7 +301,6 @@ def init_llama():
307301
'use_llama_index'):
308302
LLAMAINDEX_WRAPPER.set_directory(llama_index_directory)
309303

310-
311304
# TTS
312305
class StreamThread(QThread):
313306
errorGenerated = Signal(str)

pyqt_openai/mainWindow.py

Lines changed: 3 additions & 49 deletions
< 10000 /tr>
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import os
21
import webbrowser
32

43
from PySide6.QtCore import Qt
@@ -13,24 +12,21 @@
1312
ICON_CLOSE, \
1413
DEFAULT_SHORTCUT_SETTING, TRANSPARENT_RANGE, TRANSPARENT_INIT_VAL, ICON_GITHUB, ICON_DISCORD, PAYPAL_URL, KOFI_URL, \
1514
DISCORD_URL, GITHUB_URL, DEFAULT_SHORTCUT_FOCUS_MODE, ICON_FOCUS_MODE, ICON_SETTING, DEFAULT_SHORTCUT_SHOW_TOOLBAR, \
16-
DEFAULT_SHORTCUT_SHOW_SECONDARY_TOOLBAR, DEFAULT_SHORTCUT_STACK_ON_TOP, DEFAULT_API_CONFIGS
15+
DEFAULT_SHORTCUT_SHOW_SECONDARY_TOOLBAR, DEFAULT_SHORTCUT_STACK_ON_TOP
1716
from pyqt_openai.aboutDialog import AboutDialog
18-
from pyqt_openai.apiDialog import ApiDialog
17+
from pyqt_openai.chat_widget.chatMainWidget import ChatMainWidget
1918
from pyqt_openai.config_loader import CONFIG_MANAGER
2019
from pyqt_openai.customizeDialog import CustomizeDialog
2120
from pyqt_openai.dalle_widget.dalleMainWidget import DallEMainWidget
2221
from pyqt_openai.doNotAskAgainDialog import DoNotAskAgainDialog
2322
from pyqt_openai.globals import init_llama, set_api_key
24-
from pyqt_openai.chat_widget.chatMainWidget import ChatMainWidget
2523
from pyqt_openai.lang.translations import LangClass
2624
from pyqt_openai.models import SettingsParamsContainer, CustomizeParamsContainer
27-
from pyqt_openai.openaiApiWidget import OpenAIApiWidget
2825
from pyqt_openai.replicate_widget.replicateMainWidget import ReplicateMainWidget
2926
from pyqt_openai.settings_dialog.settingsDialog import SettingsDialog
3027
from pyqt_openai.shortcutDialog import ShortcutDialog
3128
from pyqt_openai.updateSoftwareDialog import update_software
3229
from pyqt_openai.util.script import restart_app, show_message_box_after_change_to_restart, set_auto_start_windows
33-
from pyqt_openai.widgets.animationButton import AnimationButton
3430
from pyqt_openai.widgets.button import Button
3531

3632

@@ -66,14 +62,6 @@ def __initUi(self):
6662

6763
self.__loadApiKeyInConf()
6864

69-
# check if loaded API_KEY from ini file is not empty
70-
if os.environ['OPENAI_API_KEY']:
71-
self.__openaiApiWidget.setApi()
72-
# if it is empty
73-
else:
74-
self.__setAIEnabled(False)
75-
self.__openaiApiWidget.showApiCheckPreviewLbl(False)
76-
7765
self.setCentralWidget(self.__mainWidget)
7866
self.resize(*APP_INITIAL_WINDOW_SIZE)
7967

@@ -173,17 +161,6 @@ def __setActions(self):
173161
transparencyActionWidget.setLayout(lay)
174162
self.__transparentAction.setDefaultWidget(transparencyActionWidget)
175163

176-
self.__openaiApiWidget = OpenAIApiWidget(self)
177-
self.__openaiApiWidget.onAIEnabled.connect(self.__setAIEnabled)
178-
179-
self.__otherApiButton = AnimationButton(text='Other API', parent=self)
180-
self.__otherApiButton.clicked.connect(self.__showApiDialog)
181-
182-
lay = QHBoxLayout()
183-
lay.addWidget(self.__openaiApiWidget)
184-
lay.addWidget(self.__otherApiButton)
185-
lay.setContentsMargins(0, 0, 0, 0)
186-
187164
self.__apiWidget = QWidget()
188165
self.__apiWidget.setLayout(lay)
189166

@@ -296,37 +273,14 @@ def __setToolBar(self):
296273
currentWidget.showSecondaryToolBar(self.__settingsParamContainer.show_secondary_toolbar)
297274

298275
def __loadApiKeyInConf(self):
299-
self.__openaiApiWidget.setApiKeyAndClient(CONFIG_MANAGER.get_general_property('OPENAI_API_KEY'))
276+
set_api_key('OPENAI_API_KEY', CONFIG_MANAGER.get_general_property('OPENAI_API_KEY'))
300277
set_api_key('GEMINI_API_KEY', CONFIG_MANAGER.get_general_property('GEMINI_API_KEY'))
301278
set_api_key('CLAUDE_API_KEY', CONFIG_MANAGER.get_general_property('CLAUDE_API_KEY'))
302279
set_api_key('LLAMA_API_KEY', CONFIG_MANAGER.get_general_property('LLAMA_API_KEY'))
303280

304281
# Set llama index directory if it exists
305282
init_llama()
306283

307-
def __setAIEnabled(self, f):
308-
self.__chatMainWidget.setAIEnabled(f)
309-
self.__dallEWidget.setAIEnabled(f)
310-
311-
def __showApiDialog(self):
312-
configs = []
313-
# Get the api keys from the conf file with the env var name
314-
for conf in DEFAULT_API_CONFIGS:
315-
_conf = {
316-
'display_name': conf['display_name'],
317-
'env_var_name': conf['env_var_name'],
318-
'api_key': CONFIG_MANAGER.get_general_property(conf['env_var_name'])
319-
}
320-
configs.append(_conf)
321-
322-
self.__apiDialog = ApiDialog(configs, self)
323-
reply = self.__apiDialog.exec()
324-
if reply == QDialog.DialogCode.Accepted:
325-
# Save the api keys to the conf file
326-
for k, v in self.__apiDialog.getApiKeys().items():
327-
CONFIG_MANAGER.set_general_property(k, v)
328-
set_api_key(k, v)
329-
330284
def __showAboutDialog(self):
331285
aboutDialog = AboutDialog(self)
332286
aboutDialog.exec()

pyqt_openai/openaiApiWidget.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def __init__(self, parent=None):
1919

2020
def __initUi(self):
2121
self.__apiCheckPreviewLbl = QLabel()
22-
self.__apiCheckPreviewLbl.setFont(QFont(SMALL_LABEL_PARAM))
22+
self.__apiCheckPreviewLbl.setFont(QFont(*SMALL_LABEL_PARAM))
2323

2424
apiLbl = QLabel(LangClass.TRANSLATIONS['OpenAI API Key'])
2525

0 commit comments

Comments
 (0)
0