Coloring commited on
Commit
525fa7a
·
1 Parent(s): 3e308c9
Files changed (4) hide show
  1. .gitignore +1 -0
  2. README.md +1 -1
  3. app.py +196 -0
  4. requirements.txt +3 -0
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ .vscode
README.md CHANGED
@@ -4,7 +4,7 @@ emoji: 🔥
4
  colorFrom: blue
5
  colorTo: pink
6
  sdk: gradio
7
- sdk_version: 5.47.0
8
  app_file: app.py
9
  pinned: false
10
  ---
 
4
  colorFrom: blue
5
  colorTo: pink
6
  sdk: gradio
7
+ sdk_version: 5.29.1
8
  app_file: app.py
9
  pinned: false
10
  ---
app.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+
4
+ import gradio as gr
5
+ import modelscope_studio.components.antd as antd
6
+ import modelscope_studio.components.antdx as antdx
7
+ import modelscope_studio.components.base as ms
8
+ import modelscope_studio.components.pro as pro
9
+ from modelscope_studio.components.pro.chatbot import (ChatbotBotConfig,
10
+ ChatbotPromptsConfig,
11
+ ChatbotUserConfig,
12
+ ChatbotWelcomeConfig)
13
+ from openai import OpenAI
14
+
15
+ client = OpenAI(
16
+ base_url=os.getenv("ENDPOINT"),
17
+ api_key=os.getenv("API_KEY"),
18
+ )
19
+
20
+ model = "Qwen/Qwen2.5-7B-Instruct"
21
+
22
+
23
+ def prompt_select(e: gr.EventData):
24
+ return gr.update(value=e._data["payload"][0]["value"]["description"])
25
+
26
+
27
+ def clear():
28
+ return gr.update(value=None)
29
+
30
+
31
+ def retry(chatbot_value, e: gr.EventData):
32
+ index = e._data["payload"][0]["index"]
33
+ chatbot_value = chatbot_value[:index]
34
+
35
+ yield gr.update(loading=True), gr.update(value=chatbot_value), gr.update(
36
+ disabled=True)
37
+ for chunk in submit(None, chatbot_value):
38
+ yield chunk
39
+
40
+
41
+ def cancel(chatbot_value):
42
+ chatbot_value[-1]["loading"] = False
43
+ chatbot_value[-1]["status"] = "done"
44
+ chatbot_value[-1]["footer"] = "Chat completion paused"
45
+ return gr.update(value=chatbot_value), gr.update(loading=False), gr.update(
46
+ disabled=False)
47
+
48
+
49
+ def format_history(history):
50
+ messages = [{"role": "system", "content": "You are a helpful assistant."}]
51
+ for item in history:
52
+ if item["role"] == "user":
53
+ messages.append({"role": "user", "content": item["content"]})
54
+ elif item["role"] == "assistant":
55
+ # ignore thought message
56
+ messages.append({
57
+ "role": "assistant",
58
+ "content": item["content"][-1]["content"]
59
+ })
60
+ return messages
61
+
62
+
63
+ def submit(sender_value, chatbot_value):
64
+ if sender_value is not None:
65
+ chatbot_value.append({
66
+ "role": "user",
67
+ "content": sender_value,
68
+ })
69
+ history_messages = format_history(chatbot_value)
70
+ chatbot_value.append({
71
+ "role": "assistant",
72
+ "content": [],
73
+ "loading": True,
74
+ "status": "pending"
75
+ })
76
+ yield {
77
+ sender: gr.update(value=None, loading=True),
78
+ clear_btn: gr.update(disabled=True),
79
+ chatbot: gr.update(value=chatbot_value)
80
+ }
81
+
82
+ try:
83
+ response = client.chat.completions.create(model=model,
84
+ messages=history_messages,
85
+ stream=True)
86
+ start_time = time.time()
87
+ message_content = chatbot_value[-1]["content"]
88
+ # content
89
+ message_content.append({
90
+ "type": "text",
91
+ "content": "",
92
+ })
93
+ for chunk in response:
94
+ delta = chunk.choices[0].delta
95
+ chatbot_value[-1]["loading"] = False
96
+ message_content[-1]["content"] += delta.content or ""
97
+ yield {chatbot: gr.update(value=chatbot_value)}
98
+
99
+ chatbot_value[-1]["footer"] = "{:.2f}".format(time.time() -
100
+ start_time) + 's'
101
+ chatbot_value[-1]["status"] = "done"
102
+ yield {
103
+ clear_btn: gr.update(disabled=False),
104
+ sender: gr.update(loading=False),
105
+ chatbot: gr.update(value=chatbot_value),
106
+ }
107
+ except Exception as e:
108
+ chatbot_value[-1]["loading"] = False
109
+ chatbot_value[-1]["status"] = "done"
110
+ chatbot_value[-1]["content"] = "Failed to respond, please try again."
111
+ yield {
112
+ clear_btn: gr.update(disabled=False),
113
+ sender: gr.update(loading=False),
114
+ chatbot: gr.update(value=chatbot_value),
115
+ }
116
+ raise e
117
+
118
+
119
+ with gr.Blocks() as demo, ms.Application(), antdx.XProvider():
120
+ with antd.Flex(vertical=True, gap="middle"):
121
+ chatbot = pro.Chatbot(
122
+ height=600,
123
+ welcome_config=ChatbotWelcomeConfig(
124
+ variant="borderless",
125
+ icon=
126
+ "https://assets.alicdn.com/g/qwenweb/qwen-webui-fe/0.0.44/static/favicon.png",
127
+ title=f"Hello, I'm {model}",
128
+ description="You can input text to get started.",
129
+ prompts=ChatbotPromptsConfig(
130
+ title="How can I help you today?",
131
+ styles={
132
+ "list": {
133
+ "width": '100%',
134
+ },
135
+ "item": {
136
+ "flex": 1,
137
+ },
138
+ },
139
+ items=[{
140
+ "label":
141
+ "📅 Make a plan",
142
+ "children": [{
143
+ "description":
144
+ "Help me with a plan to start a business"
145
+ }, {
146
+ "description":
147
+ "Help me with a plan to achieve my goals"
148
+ }, {
149
+ "description":
150
+ "Help me with a plan for a successful interview"
151
+ }]
152
+ }, {
153
+ "label":
154
+ "🖋 Help me write",
155
+ "children": [{
156
+ "description":
157
+ "Help me write a story with a twist ending"
158
+ }, {
159
+ "description":
160
+ "Help me write a blog post on mental health"
161
+ }, {
162
+ "description":
163
+ "Help me write a letter to my future self"
164
+ }]
165
+ }])),
166
+ user_config=ChatbotUserConfig(
167
+ avatar="https://api.dicebear.com/7.x/miniavs/svg?seed=3"),
168
+ bot_config=ChatbotBotConfig(
169
+ header=model,
170
+ avatar=
171
+ "https://assets.alicdn.com/g/qwenweb/qwen-webui-fe/0.0.44/static/favicon.png",
172
+ actions=["copy", "retry"]),
173
+ )
174
+
175
+ with antdx.Sender() as sender:
176
+ with ms.Slot("prefix"):
177
+ with antd.Button(value=None, color="default",
178
+ variant="text") as clear_btn:
179
+ with ms.Slot("icon"):
180
+ antd.Icon("ClearOutlined")
181
+ clear_btn.click(fn=clear, outputs=[chatbot])
182
+ submit_event = sender.submit(fn=submit,
183
+ inputs=[sender, chatbot],
184
+ outputs=[sender, chatbot, clear_btn])
185
+ sender.cancel(fn=cancel,
186
+ inputs=[chatbot],
187
+ outputs=[chatbot, sender, clear_btn],
188
+ cancels=[submit_event],
189
+ queue=False)
190
+ chatbot.retry(fn=retry,
191
+ inputs=[chatbot],
192
+ outputs=[sender, chatbot, clear_btn])
193
+ chatbot.welcome_prompt_select(fn=prompt_select, outputs=[sender])
194
+
195
+ if __name__ == "__main__":
196
+ demo.queue().launch(ssr_mode=False)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ modelscope_studio
2
+ gradio
3
+ openai