Leiyan525 commited on
Commit
38af40f
·
1 Parent(s): e8b43aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -20
app.py CHANGED
@@ -1,6 +1,7 @@
1
  import gradio as gr
2
  from llama_index import GPTVectorStoreIndex, SimpleDirectoryReader, Prompt
3
  import openai
 
4
 
5
  system_prompt = [
6
  {
@@ -12,27 +13,35 @@ system_prompt = [
12
 
13
 
14
 
15
- def respond(message, chat_history):
 
 
 
 
16
  re_messages = system_prompt
17
- for chat in chat_history:
18
- re_messages.append({"role": "user", "content": chat[0]})
19
- re_messages.append({"role": "assistant", "content": chat[1]})
20
- re_messages.append({"role": "user", "content": message})
21
  re_chat_completion = openai.ChatCompletion.create(
22
  model='gpt-3.5-turbo',
23
  messages=re_messages,
24
- temperature=0.7
25
- )
26
- bot_message = re_chat_completion.choices[0].message.content
27
- chat_history.append((message, bot_message))
28
- return "", chat_history
29
-
30
-
31
- with gr.Blocks() as demo:
32
- open_ai_key = gr.Textbox(label='OpenAI API Key', placeholder='输入你的OpenAI API Key')
33
- openai.api_key = open_ai_key
34
- chatbot = gr.Chatbot(label='历史会话')
35
- msg = gr.Textbox(label='回车输入')
36
- msg.submit(respond, [msg, chatbot], [msg, chatbot])
37
-
38
- demo.launch(share=True)
 
 
 
 
 
1
  import gradio as gr
2
  from llama_index import GPTVectorStoreIndex, SimpleDirectoryReader, Prompt
3
  import openai
4
+ openai.api_key = api_key
5
 
6
  system_prompt = [
7
  {
 
13
 
14
 
15
 
16
+ def clear(user_message, chat_history):
17
+ return "", chat_history + [[user_message, None]]
18
+
19
+
20
+ def respond(chat_history):
21
  re_messages = system_prompt
22
+ for chat in chat_history[0:-1]:
23
+ re_messages.append({"role": "user", "content": chat[0]})
24
+ re_messages.append({"role": "assistant", "content": chat[1]})
25
+ re_messages.append({"role": "user", "content": chat_history[-1][0]})
26
  re_chat_completion = openai.ChatCompletion.create(
27
  model='gpt-3.5-turbo',
28
  messages=re_messages,
29
+ stream=True
30
+ temperature = 0.7
31
+ )
32
+ chat_history[-1][1] = ""
33
+ for re_chunk in re_chat_completion:
34
+ chat_history[-1][1] += re_chunk['choices'][0]['delta'].get('content', '')
35
+ yield chat_history
36
+
37
+
38
+ with gr.Blocks() as demo:
39
+ chatbot = gr.Chatbot(label='历史对话')
40
+ msg = gr.Textbox(label='输入消息,按回车发送')
41
+ api_key = gr.Textbox(label='输入你的apikey')
42
+ msg.submit(clear, [msg, chatbot], [msg, chatbot]).then(
43
+ respond, chatbot, chatbot
44
+ )
45
+
46
+ demo.queue()
47
+ demo.launch()