@@ -127,6 +127,26 @@ def messages(self) -> List[Dict]:
127127 return self ._messages
128128
129129
130+ def get_openai_config ():
131+ openai_config = json .loads (pywebio_battery .get_localstorage ('openai_config' ) or '{}' )
132+ if not openai_config :
133+ openai_config = input_group ('OpenAI API Config' , [
134+ input ('API Key' , name = 'api_key' , type = TEXT , required = True ,
135+ help_text = 'Get your API key from https://platform.openai.com/account/api-keys' ),
136+ input ('API Server' , name = 'api_base' , type = TEXT , value = 'https://api.openai.com' , required = True ),
137+ ])
138+ openai_config ['api_base' ] = openai_config ['api_base' ].removesuffix ('/v1' ).strip ('/' ) + '/v1'
139+ pywebio_battery .set_localstorage ('openai_config' , json .dumps (openai_config ))
140+
141+ put_button ('Reset OpenAI API Key' , reset_openai_config , link_style = True )
142+ return openai_config
143+
144+
145+ def reset_openai_config ():
146+ pywebio_battery .set_localstorage ('openai_config' , json .dumps (None ))
147+ toast ("Please refresh the page to take effect" )
148+
149+
130150def main ():
131151 """"""
132152 set_env (input_panel_fixed = False , output_animation = False )
@@ -135,20 +155,11 @@ def main():
135155 A ChatGPT client implemented with PyWebIO. [Source Code](https://github.com/pywebio/PyWebIO/blob/dev/demos/chatgpt.py)
136156 TIPS: refresh page to open a new chat.
137157 """ )
138-
139158 put_select ('model' , ['gpt-3.5-turbo' , 'gpt-4' ], label = 'Model' )
140159
141- openai_config = json .loads (pywebio_battery .get_localstorage ('openai_config' ) or '{}' )
142- if not openai_config :
143- openai_config = input_group ('OpenAI API Config' , [
144- input ('API Key' , name = 'api_key' , type = TEXT , required = True ,
145- help_text = 'Get your API key from https://platform.openai.com/account/api-keys' ),
146- input ('API Server' , name = 'api_base' , type = TEXT , value = 'https://api.openai.com' , required = True ),
147- ])
148- pywebio_battery .set_localstorage ('openai_config' , json .dumps (openai_config ))
160+ openai_config = get_openai_config ()
149161
150- api_base = openai_config ['api_base' ].removesuffix ('/v1' ).strip ('/' ) + '/v1'
151- bot = ChatGPT (api_key = openai_config ['api_key' ], api_base = api_base , model = pin .model )
162+ bot = ChatGPT (api_key = openai_config ['api_key' ], api_base = openai_config ['api_base' ], model = pin .model )
152163 while True :
153164 form = input_group ('' , [
154165 input (name = 'msg' , placeholder = 'Ask ChatGPT' ),
@@ -194,4 +205,4 @@ def main():
194205if __name__ == '__main__' :
195206 from pywebio import start_server
196207
197- start_server (main , port = 8085 , debug = True , cdn = False )
208+ start_server (main , port = 8080 , debug = True , cdn = False )
0 commit comments