dzip commited on
Commit
5241b7b
·
verified ·
1 Parent(s): 900dc63

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -89
app.py CHANGED
@@ -1,104 +1,96 @@
1
- import gradio as gr
2
  import openai
 
3
 
4
- # Initialize the OpenAI client with your proxy API
5
  client = openai.OpenAI(
6
  api_key="sk-hm35RR1E0dfB26C8873BT3BlBKFJE681B3d87a6c4B3e8C44",
7
  base_url="https://aigptx.top/"
8
  )
9
 
10
- # Function to handle predictions
11
- def predict(inputs, top_p, temperature, system_prompt, chat_counter, chatbot=[], history=[]):
12
- # Build the system prompt if provided
13
- messages = []
14
- if system_prompt:
15
- messages.append({"role": "system", "content": system_prompt})
16
-
17
- # Add previous conversation history
18
- if chat_counter != 0:
19
- for data in chatbot:
20
- messages.append({"role": "user", "content": data[0]})
21
- messages.append({"role": "assistant", "content": data[1]})
22
-
23
- # Add the current user input to the messages
24
- messages.append({"role": "user", "content": inputs})
25
-
26
- payload = {
27
- "model": "gpt-3.5-turbo",
28
- "messages": messages,
29
- "temperature": temperature,
30
- "top_p": top_p,
31
- "n": 1,
32
- "stream": True,
33
- "presence_penalty": 0,
34
- "frequency_penalty": 0,
35
- }
36
 
37
- # Set the chat counter
38
- chat_counter += 1
39
- history.append(inputs)
40
 
41
- # Using the proxy API to get the response
42
- response = client.ChatCompletion.create(
43
- model=payload["model"],
44
- messages=payload["messages"],
45
- temperature=payload["temperature"],
46
- top_p=payload["top_p"],
47
- stream=payload["stream"],
48
- presence_penalty=payload["presence_penalty"],
49
- frequency_penalty=payload["frequency_penalty"]
 
50
  )
51
 
52
- token_counter = 0
53
- partial_words = ""
54
-
55
- for chunk in response:
56
- if 'choices' in chunk:
57
- delta = chunk['choices'][0]['delta']
58
- if 'content' in delta:
59
- partial_words += delta['content']
60
- if token_counter == 0:
61
- history.append(" " + partial_words)
62
- else:
63
- history[-1] = partial_words
64
- chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2)]
65
- token_counter += 1
66
- yield chat, history, chat_counter
67
 
68
- # Function to reset the textbox
69
- def reset_textbox():
70
- return gr.update(value='')
 
 
 
 
71
 
72
- # UI Components
73
- title = """<h1 align="center">Customizable Chatbot with OpenAI API</h1>"""
74
- description = """
75
- Explore the outputs of a GPT-3.5 model, with the ability to customize system prompts and interact with a history of conversation logs.
76
- """
 
 
 
 
 
 
77
 
78
- with gr.Blocks(css="""#col_container {width: 1000px; margin-left: auto; margin-right: auto;}
79
- #chatbot {height: 520px; overflow: auto;}""") as demo:
80
-
81
- gr.HTML(title)
82
- with gr.Column(elem_id="col_container"):
83
- # Removed the API key input field
84
- # openai_api_key = gr.Textbox(type='password', label="Enter your OpenAI API key here")
85
- system_prompt = gr.Textbox(placeholder="Enter system prompt (optional)", label="System Prompt", lines=2)
86
- chatbot = gr.Chatbot(elem_id='chatbot')
87
- inputs = gr.Textbox(placeholder="Type your message here!", label="Input", lines=1)
88
- send_btn = gr.Button("Send")
89
- state = gr.State([])
90
- chat_counter = gr.Number(value=0, visible=False, precision=0)
91
- reset_btn = gr.Button("Reset Chat")
92
-
93
- # Input parameters for OpenAI API
94
- with gr.Accordion("Model Parameters", open=False):
95
- top_p = gr.Slider(minimum=0, maximum=1.0, value=1.0, step=0.05, interactive=True, label="Top-p (Nucleus Sampling)")
96
- temperature = gr.Slider(minimum=0, maximum=5.0, value=1.0, step=0.1, interactive=True, label="Temperature")
97
-
98
- # Submit input for model prediction with the send button
99
- send_btn.click(predict, [inputs, top_p, temperature, system_prompt, chat_counter, chatbot, state],
100
- [chatbot, state, chat_counter])
101
- reset_btn.click(reset_textbox, [], [inputs])
102
- inputs.submit(reset_textbox, [], [inputs])
103
 
104
- demo.queue().launch(debug=True)
 
 
 
1
  import openai
2
+ import gradio as gr
3
 
4
+ # 初始化 OpenAI API 客户端
5
  client = openai.OpenAI(
6
  api_key="sk-hm35RR1E0dfB26C8873BT3BlBKFJE681B3d87a6c4B3e8C44",
7
  base_url="https://aigptx.top/"
8
  )
9
 
10
+ # 默认系统消息(可以通过UI定制)
11
+ system_prompt = "您好!欢迎来到聊天机器人。请随时提出您的问题或想法。"
12
+
13
+ # 添加用户消息到聊天记录
14
+ def add_text(history, text, custom_prompt):
15
+ if not custom_prompt:
16
+ custom_prompt = system_prompt # 使用默认系统提示
17
+ if text:
18
+ if not history:
19
+ history = [("System Message", custom_prompt)]
20
+ history.append((text, None))
21
+ else:
22
+ history.append(("System Message", "您发送了一个空消息,请输入您的问题或想法。"))
23
+ return history, ""
24
+
25
+ # 调用 OpenAI GPT 生成回复
26
+ def predict(history, custom_prompt):
27
+ if not custom_prompt:
28
+ custom_prompt = system_prompt # 使用默认系统提示
29
+ if not history or (len(history) == 1 and history[0][0] == "System Message"):
30
+ history = [("System Message", custom_prompt)]
31
+ yield history
32
+ return history, ""
 
 
 
33
 
34
+ history_ = history[1:] if history[0][0] == "System Message" else history
 
 
35
 
36
+ history_openai_format = [{"role": "user", "content": human} for human, assistant in history_ if human]
37
+
38
+ if not history_openai_format:
39
+ yield history
40
+ return history
41
+
42
+ response = client.chat.completions.create(
43
+ model='gpt-4-1106-preview',
44
+ messages=[{"role": "system", "content": custom_prompt}] + history_openai_format,
45
+ temperature=0.9,
46
  )
47
 
48
+ history[-1][1] = response.choices[0].message.content
49
+ yield history
50
+
51
+ # 构建 Gradio 界面
52
+ with gr.Blocks() as demo:
53
+ gr.Markdown("<h1><center>聊天机器人</center></h1>")
54
+
55
+ with gr.Row():
56
+ with gr.Column(scale=2):
57
+ chatbot = gr.Chatbot(
58
+ value=[("System Message", system_prompt)],
59
+ )
60
+ with gr.Row():
61
+ textbox = gr.Textbox(placeholder="请输入您的问题或想法", show_label=False, scale=2)
62
+ submit = gr.Button("💬 发送", scale=1)
63
 
64
+ # 自定义系统消息输入框
65
+ custom_system_prompt = gr.Textbox(
66
+ value=system_prompt,
67
+ placeholder="自定义系统消息,例如:'我是一个乐于助人的助手,请告诉我如何帮您'",
68
+ label="自定义系统提示",
69
+ lines=2
70
+ )
71
 
72
+ # 在用户输入消息时,传递自定义系统提示给 GPT 模型
73
+ textbox_msg = textbox.submit(
74
+ add_text,
75
+ [chatbot, textbox, custom_system_prompt],
76
+ [chatbot, textbox],
77
+ queue=False
78
+ ).then(
79
+ predict,
80
+ [chatbot, custom_system_prompt],
81
+ chatbot
82
+ )
83
 
84
+ submit.click(
85
+ add_text,
86
+ inputs=[chatbot, textbox, custom_system_prompt],
87
+ outputs=[chatbot, textbox],
88
+ queue=False
89
+ ).then(
90
+ predict,
91
+ [chatbot, custom_system_prompt],
92
+ chatbot
93
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
+ demo.queue()
96
+ demo.launch()