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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
import threading
|
| 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 (
|
| 10 |
+
ChatbotBotConfig,
|
| 11 |
+
ChatbotPromptsConfig,
|
| 12 |
+
ChatbotUserConfig,
|
| 13 |
+
ChatbotWelcomeConfig
|
| 14 |
+
)
|
| 15 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
# Load the Sarvam AI model and tokenizer
|
| 19 |
+
model_name = "sarvamai/sarvam-m"
|
| 20 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 21 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
|
| 22 |
+
|
| 23 |
+
def prompt_select(e: gr.EventData):
|
| 24 |
+
return gr.update(value=e._data["payload"][0]["value"]["description"])
|
| 25 |
+
|
| 26 |
+
def clear():
|
| 27 |
+
return gr.update(value=None)
|
| 28 |
+
|
| 29 |
+
def retry(chatbot_value, e: gr.EventData):
|
| 30 |
+
index = e._data["payload"][0]["index"]
|
| 31 |
+
chatbot_value = chatbot_value[:index]
|
| 32 |
+
|
| 33 |
+
yield gr.update(loading=True), gr.update(value=chatbot_value), gr.update(disabled=True)
|
| 34 |
+
for chunk in submit(None, chatbot_value):
|
| 35 |
+
yield chunk
|
| 36 |
+
|
| 37 |
+
def cancel(chatbot_value):
|
| 38 |
+
chatbot_value[-1]["loading"] = False
|
| 39 |
+
chatbot_value[-1]["status"] = "done"
|
| 40 |
+
chatbot_value[-1]["footer"] = "Chat completion paused"
|
| 41 |
+
return gr.update(value=chatbot_value), gr.update(loading=False), gr.update(disabled=False)
|
| 42 |
+
|
| 43 |
+
def format_history(history):
|
| 44 |
+
messages = [{"role": "system", "content": "You are a helpful assistant."}]
|
| 45 |
+
for item in history:
|
| 46 |
+
if item["role"] == "user":
|
| 47 |
+
messages.append({"role": "user", "content": item["content"]})
|
| 48 |
+
elif item["role"] == "assistant":
|
| 49 |
+
messages.append({"role": "assistant", "content": item["content"][-1]["content"]})
|
| 50 |
+
return messages
|
| 51 |
+
|
| 52 |
+
def generate_response(messages, chatbot_value, sender, clear_btn):
|
| 53 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False, enable_thinking=True)
|
| 54 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
| 55 |
+
|
| 56 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 57 |
+
generate_kwargs = dict(
|
| 58 |
+
**model_inputs,
|
| 59 |
+
streamer=streamer,
|
| 60 |
+
max_new_tokens=8192,
|
| 61 |
+
do_sample=True,
|
| 62 |
+
temperature=0.7
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
thread = threading.Thread(target=model.generate, kwargs=generate_kwargs)
|
| 66 |
+
thread.start()
|
| 67 |
+
|
| 68 |
+
thought_done = False
|
| 69 |
+
start_time = time.time()
|
| 70 |
+
message_content = chatbot_value[-1]["content"]
|
| 71 |
+
message_content.append({
|
| 72 |
+
"copyable": False,
|
| 73 |
+
"editable": False,
|
| 74 |
+
"type": "tool",
|
| 75 |
+
"content": "",
|
| 76 |
+
"options": {"title": "Thinking..."}
|
| 77 |
+
})
|
| 78 |
+
message_content.append({"type": "text", "content": "",})
|
| 79 |
+
|
| 80 |
+
reasoning_content = ""
|
| 81 |
+
content = ""
|
| 82 |
+
for new_text in streamer:
|
| 83 |
+
if "</think>" in new_text:
|
| 84 |
+
reasoning_content = new_text.split("</think>")[0].rstrip("\n")
|
| 85 |
+
content = new_text.split("</think>")[-1].lstrip("\n").rstrip("</s>")
|
| 86 |
+
else:
|
| 87 |
+
content = new_text
|
| 88 |
+
|
| 89 |
+
chatbot_value[-1]["loading"] = False
|
| 90 |
+
if reasoning_content and not thought_done:
|
| 91 |
+
message_content[-2]["content"] = reasoning_content
|
| 92 |
+
thought_done = True
|
| 93 |
+
thought_cost_time = "{:.2f}".format(time.time() - start_time)
|
| 94 |
+
message_content[-2]["options"]["title"] = f"End of Thought ({thought_cost_time}s)"
|
| 95 |
+
message_content[-2]["options"]["status"] = "done"
|
| 96 |
+
message_content[-1]["content"] += content
|
| 97 |
+
yield {
|
| 98 |
+
clear_btn: gr.update(disabled=False),
|
| 99 |
+
sender: gr.update(loading=False),
|
| 100 |
+
chatbot: gr.update(value=chatbot_value),
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
chatbot_value[-1]["footer"] = "{:.2f}".format(time.time() - start_time) + 's'
|
| 104 |
+
chatbot_value[-1]["status"] = "done"
|
| 105 |
+
yield {
|
| 106 |
+
clear_btn: gr.update(disabled=False),
|
| 107 |
+
sender: gr.update(loading=False),
|
| 108 |
+
chatbot: gr.update(value=chatbot_value),
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
def submit(sender_value, chatbot_value):
|
| 112 |
+
if sender_value is not None:
|
| 113 |
+
chatbot_value.append({"role": "user", "content": sender_value})
|
| 114 |
+
history_messages = format_history(chatbot_value)
|
| 115 |
+
chatbot_value.append({"role": "assistant", "content": [], "loading": True, "status": "pending"})
|
| 116 |
+
yield {
|
| 117 |
+
sender: gr.update(value=None, loading=True),
|
| 118 |
+
clear_btn: gr.update(disabled=True),
|
| 119 |
+
chatbot: gr.update(value=chatbot_value)
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
try:
|
| 123 |
+
for chunk in generate_response(history_messages, chatbot_value, sender, clear_btn):
|
| 124 |
+
yield chunk
|
| 125 |
+
except Exception as e:
|
| 126 |
+
chatbot_value[-1]["loading"] = False
|
| 127 |
+
chatbot_value[-1]["status"] = "done"
|
| 128 |
+
chatbot_value[-1]["content"] = "Failed to respond, please try again."
|
| 129 |
+
yield {
|
| 130 |
+
clear_btn: gr.update(disabled=False),
|
| 131 |
+
sender: gr.update(loading=False),
|
| 132 |
+
chatbot: gr.update(value=chatbot_value),
|
| 133 |
+
}
|
| 134 |
+
raise e
|
| 135 |
+
|
| 136 |
+
with gr.Blocks() as demo, ms.Application(), antdx.XProvider():
|
| 137 |
+
with antd.Flex(vertical=True, gap="middle"):
|
| 138 |
+
chatbot = pro.Chatbot(
|
| 139 |
+
height=600,
|
| 140 |
+
welcome_config=ChatbotWelcomeConfig(
|
| 141 |
+
variant="borderless",
|
| 142 |
+
icon="https://cdn-avatars.huggingface.co/v1/production/uploads/60270a7c32856987162c641a/umd13GCWVijwTDGZzw3q-.png",
|
| 143 |
+
title=f"Hello, I'm Sarvam AI",
|
| 144 |
+
description="You can input text to get started.",
|
| 145 |
+
prompts=ChatbotPromptsConfig(
|
| 146 |
+
title="How can I help you today?",
|
| 147 |
+
styles={
|
| 148 |
+
"list": {"width": '100%'},
|
| 149 |
+
"item": {"flex": 1},
|
| 150 |
+
},
|
| 151 |
+
items=[
|
| 152 |
+
{
|
| 153 |
+
"label": "π
Make a plan",
|
| 154 |
+
"children": [
|
| 155 |
+
{"description": "Help me with a plan to start a business"},
|
| 156 |
+
{"description": "Help me with a plan to achieve my goals"},
|
| 157 |
+
{"description": "Help me with a plan for a successful interview"}
|
| 158 |
+
]
|
| 159 |
+
},
|
| 160 |
+
{
|
| 161 |
+
"label": "π Help me write",
|
| 162 |
+
"children": [
|
| 163 |
+
{"description": "Help me write a story with a twist ending"},
|
| 164 |
+
{"description": "Help me write a blog post on mental health"},
|
| 165 |
+
{"description": "Help me write a letter to my future self"}
|
| 166 |
+
]
|
| 167 |
+
}
|
| 168 |
+
]
|
| 169 |
+
)
|
| 170 |
+
),
|
| 171 |
+
user_config=ChatbotUserConfig(avatar="https://api.dicebear.com/7.x/miniavs/svg?seed=3"),
|
| 172 |
+
bot_config=ChatbotBotConfig(
|
| 173 |
+
header="Sarvam AI",
|
| 174 |
+
avatar="https://cdn-avatars.huggingface.co/v1/production/uploads/60270a7c32856987162c641a/umd13GCWVijwTDGZzw3q-.png",
|
| 175 |
+
actions=["copy", "retry"]
|
| 176 |
+
),
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
with antdx.Sender() as sender:
|
| 180 |
+
with ms.Slot("prefix"):
|
| 181 |
+
with antd.Button(value=None, color="default", variant="text") as clear_btn:
|
| 182 |
+
with ms.Slot("icon"):
|
| 183 |
+
antd.Icon("ClearOutlined")
|
| 184 |
+
clear_btn.click(fn=clear, outputs=[chatbot])
|
| 185 |
+
submit_event = sender.submit(fn=submit, inputs=[sender, chatbot], outputs=[sender, chatbot, clear_btn])
|
| 186 |
+
sender.cancel(fn=cancel, inputs=[chatbot], outputs=[chatbot, sender, clear_btn], cancels=[submit_event], queue=False)
|
| 187 |
+
chatbot.retry(fn=retry, inputs=[chatbot], outputs=[sender, chatbot, clear_btn])
|
| 188 |
+
chatbot.welcome_prompt_select(fn=prompt_select, outputs=[sender])
|
| 189 |
+
|
| 190 |
+
if __name__ == "__main__":
|
| 191 |
+
demo.launch(mcp_server=True)
|