stupidHIGH commited on
Commit
16e2bb0
·
1 Parent(s): 20d7dfe
Files changed (1) hide show
  1. app.py +70 -94
app.py CHANGED
@@ -1,107 +1,83 @@
1
- # import gradio as gr
2
- # import os, openai
3
- #
4
- #
5
- # conversation = []
6
- #
7
- # class ChatGPT:
8
- #
9
- #
10
- # def __init__(self):
11
- # self.api_key = ""
12
- # self.messages = conversation
13
- # self.model = os.getenv("OPENAI_MODEL", default = "gpt-3.5-turbo")
14
- #
15
- # def save_api_key(self, user_input0):
16
- # self.api_key = user_input0
17
- #
18
- # def get_response(self, user_input):
19
- # openai.api_key = self.api_key
20
- # conversation.append({"role": "user", "content": user_input})
21
- #
22
- #
23
- # response = openai.ChatCompletion.create(
24
- # model=self.model,
25
- # messages = self.messages
26
- #
27
- # )
28
- #
29
- # conversation.append({"role": "assistant", "content": response['choices'][0]['message']['content']})
30
- #
31
- # print("AI回答內容:")
32
- # print(response['choices'][0]['message']['content'].strip())
33
- #
34
- #
35
- #
36
- # return response['choices'][0]['message']['content'].strip()
37
- #
38
- #
39
- # chatgpt = ChatGPT()
40
- #
41
- #
42
- # def greet(prompt, api_key):
43
- # chatgpt.save_api_key(api_key)
44
- #
45
- # reply_text = chatgpt.get_response(prompt)
46
- #
47
- # greeting = f"{reply_text}"
48
- #
49
- # return greeting
50
- #
51
- # demo = gr.Interface(
52
- # fn=greet,
53
- # inputs=["text", "text"],
54
- # outputs=["text"],
55
- # )
56
- #
57
- # demo.launch()
58
 
59
- import argparse
 
 
 
 
 
 
 
 
 
60
 
61
- import gradio as gr
62
- from loguru import logger
63
 
64
- from chat_completion import ChatCompletion
 
 
 
65
 
66
- parser = argparse.ArgumentParser()
67
- parser.add_argument('--api_key_path', type=str, default='./openai_api_key')
68
- parser.add_argument('--log_path', type=str, default='./log.txt')
69
- parser.add_argument('--share', action='store_true', default=False)
70
- parser.add_argument('--welcome', type=str, default='Say something to ChatGPT here ...')
71
- parser.add_argument('--title', type=str, default='ChatGPT')
72
- parser.add_argument('--setting', type=str, default=None)
73
- args = parser.parse_args()
74
 
75
- bot = ChatCompletion(api_key_path=args.api_key_path)
76
- logger.add(args.log_path)
 
 
 
 
 
77
 
78
- with gr.Blocks(title=args.title) as demo:
79
- chatbot = gr.Chatbot(show_label=False)
80
- msg = gr.TextArea(show_label=False, placeholder=args.welcome)
81
- send_btn = gr.Button('Send')
82
- retry_btn = gr.Button('Retry')
83
- reset_btn = gr.Button('Reset')
84
 
85
- def send(user_message, history):
86
- if not user_message:
87
- return '', history
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
- logger.info(f'[MSG] {user_message}')
90
- response = bot(user_message, setting=args.setting) if user_message != 'retry' else bot.retry()
91
- logger.info(f'[ANS] {response}')
92
- return '', history + [[user_message, response]]
93
 
94
- def reset():
95
- bot.reset()
96
- logger.info('[RESET]')
97
- return None, [[None, None]]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
- def retry(history):
100
- return send('retry', history)
 
101
 
102
- send_btn.click(send, inputs=[msg, chatbot], outputs=[msg, chatbot], show_progress=True)
103
- reset_btn.click(reset, inputs=None, outputs=[msg, chatbot])
104
- retry_btn.click(retry, inputs=chatbot, outputs=[msg, chatbot])
 
105
 
 
106
 
107
- demo.launch(share=args.share)
 
 
1
+ import gradio as gr
2
+ import openai
3
+ import time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ with gr.Blocks() as demo:
6
+ with gr.Row():
7
+ key = gr.Textbox(placeholder="API_KEY")
8
+ with gr.Row():
9
+ with gr.Column():
10
+ msg = gr.Textbox(placeholder="Question")
11
+ submit = gr.Button("Submit")
12
+ clear = gr.Button("Clear")
13
+ with gr.Column():
14
+ chatbot = gr.Chatbot()
15
 
 
 
16
 
17
+ # state = gr.State([])
18
+
19
+ def user(user_message, history):
20
+ return "", history + [[user_message, None]]
21
 
 
 
 
 
 
 
 
 
22
 
23
+ def bot(history, key):
24
+ openai.api_key = key
25
+ bot_message = ask_gpt(history)
26
+ print(history)
27
+ history[-1][1] = bot_message
28
+ time.sleep(1)
29
+ return history
30
 
 
 
 
 
 
 
31
 
32
+ def ask_gpt(history):
33
+ messages = []
34
+ for i in range(len(history) - 1):
35
+ messages.append({"role": "user", "content": history[i][0]})
36
+ messages.append({"role": "assistant", "content": history[i][1]})
37
+ messages.append({"role": "user", "content": history[-1][0]})
38
+ try:
39
+ response = openai.ChatCompletion.create(
40
+ model="gpt-3.5-turbo",
41
+ messages=messages
42
+ )
43
+ return response['choices'][0]['message']['content'].replace("```", "")
44
+ except Exception as e:
45
+ print(e)
46
+ return e
47
 
 
 
 
 
48
 
49
+ # def bot(history, messages_history, key):
50
+ # openai.api_key = key
51
+ # user_message = history[-1][0]
52
+ # bot_message, messages_history = ask_gpt(user_message, messages_history)
53
+ # messages_history += [{"role": "assistant", "content": bot_message}]
54
+ # history[-1][1] = bot_message
55
+ # time.sleep(1)
56
+ # return history, messages_history
57
+ #
58
+ #
59
+ # def ask_gpt(message, messages_history):
60
+ # try:
61
+ # messages_history += [{"role": "user", "content": message}]
62
+ # response = openai.ChatCompletion.create(
63
+ # model="gpt-3.5-turbo",
64
+ # messages=messages_history
65
+ # )
66
+ # return response['choices'][0]['message']['content'], messages_history
67
+ # except Exception as e:
68
+ # print(e)
69
+ # return e, messages_history
70
 
71
+ # def init_history(messages_history):
72
+ # messages_history = []
73
+ # return messages_history
74
 
75
+ submit.click(user, inputs=[msg, chatbot], outputs=[msg, chatbot], queue=True, api_name="submit").then(
76
+ bot, [chatbot, key], chatbot, api_name="bot_response"
77
+ )
78
+ clear.click(lambda: None, None, chatbot, queue=True, api_name="clear")
79
 
80
+ # clear.click(lambda: None, None, chatbot, queue=False, api_name="clear").then(init_history, [state], [state],api_name="init_history")
81
 
82
+ demo.queue()
83
+ demo.launch()