web_demo.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. import random
  2. import re
  3. import json
  4. import os
  5. import sys
  6. from threading import Thread
  7. import torch
  8. import numpy as np
  9. import streamlit as st
  10. from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
  11. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
  12. from trainer.trainer_utils import safe_math_eval
  13. st.set_page_config(page_title="MiniMind", initial_sidebar_state="collapsed")
  14. st.markdown("""
  15. <style>
  16. /* 添加操作按钮样式 */
  17. .stButton button {
  18. border-radius: 50% !important; /* 改为圆形 */
  19. width: 32px !important; /* 固定宽度 */
  20. height: 32px !important; /* 固定高度 */
  21. padding: 0 !important; /* 移除内边距 */
  22. background-color: transparent !important;
  23. border: 1px solid #ddd !important;
  24. display: flex !important;
  25. align-items: center !important;
  26. justify-content: center !important;
  27. font-size: 14px !important;
  28. color: #666 !important; /* 更柔和的颜色 */
  29. margin: 5px 10px 5px 0 !important; /* 调整按钮间距 */
  30. }
  31. .stButton button:hover {
  32. border-color: #999 !important;
  33. color: #333 !important;
  34. background-color: #f5f5f5 !important;
  35. }
  36. .stMainBlockContainer > div:first-child {
  37. margin-top: -50px !important;
  38. }
  39. .stApp > div:last-child {
  40. margin-bottom: -35px !important;
  41. }
  42. /* 重置按钮基础样式 */
  43. .stButton > button {
  44. all: unset !important; /* 重置所有默认样式 */
  45. box-sizing: border-box !important;
  46. border-radius: 50% !important;
  47. width: 18px !important;
  48. height: 18px !important;
  49. min-width: 18px !important;
  50. min-height: 18px !important;
  51. max-width: 18px !important;
  52. max-height: 18px !important;
  53. padding: 0 !important;
  54. background-color: transparent !important;
  55. border: 1px solid #ddd !important;
  56. display: flex !important;
  57. align-items: center !important;
  58. justify-content: center !important;
  59. font-size: 14px !important;
  60. color: #888 !important;
  61. cursor: pointer !important;
  62. transition: all 0.2s ease !important;
  63. margin: 0 2px !important; /* 调整这里的 margin 值 */
  64. }
  65. </style>
  66. """, unsafe_allow_html=True)
  67. device = "cuda" if torch.cuda.is_available() else "cpu"
  68. # 多语言文本
  69. LANG_TEXTS = {
  70. 'zh': {
  71. 'settings': '模型设定调整',
  72. 'history_rounds': '历史对话轮次',
  73. 'max_length': '最大生成长度',
  74. 'temperature': '温度',
  75. 'thinking': '思考',
  76. 'tools': '工具',
  77. 'language': '语言',
  78. 'send': '给 MiniMind 发送消息',
  79. 'disclaimer': 'AI 生成内容可能存在错误,请仔细核实',
  80. 'think_tip': '自适应思考,目前多轮对话或Tool Call共存时思考不稳定',
  81. 'tool_select': '工具选择(最多4个)',
  82. },
  83. 'en': {
  84. 'settings': 'Model Settings',
  85. 'history_rounds': 'History Rounds',
  86. 'max_length': 'Max Length',
  87. 'temperature': 'Temperature',
  88. 'thinking': 'Thinking',
  89. 'tools': 'Tools',
  90. 'language': 'Language',
  91. 'send': 'Send a message to MiniMind',
  92. 'disclaimer': 'AI-generated content may be inaccurate, please verify',
  93. 'think_tip': 'Adaptive thinking; may be unstable with multi-turn or Tool Call',
  94. 'tool_select': 'Tool Selection (max 4)',
  95. }
  96. }
  97. def get_text(key):
  98. lang = st.session_state.get('lang', 'en')
  99. return LANG_TEXTS.get(lang, {}).get(key, LANG_TEXTS['zh'].get(key, key))
  100. # 工具定义
  101. TOOLS = [
  102. {"type": "function", "function": {"name": "calculate_math", "description": "计算数学表达式", "parameters": {"type": "object", "properties": {"expression": {"type": "string", "description": "数学表达式"}}, "required": ["expression"]}}},
  103. {"type": "function", "function": {"name": "get_current_time", "description": "获取当前时间", "parameters": {"type": "object", "properties": {"timezone": {"type": "string", "default": "Asia/Shanghai"}}, "required": []}}},
  104. {"type": "function", "function": {"name": "random_number", "description": "生成随机数", "parameters": {"type": "object", "properties": {"min": {"type": "integer"}, "max": {"type": "integer"}}, "required": ["min", "max"]}}},
  105. {"type": "function", "function": {"name": "text_length", "description": "计算文本长度", "parameters": {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}}},
  106. {"type": "function", "function": {"name": "unit_converter", "description": "单位转换", "parameters": {"type": "object", "properties": {"value": {"type": "number"}, "from_unit": {"type": "string"}, "to_unit": {"type": "string"}}, "required": ["value", "from_unit", "to_unit"]}}},
  107. {"type": "function", "function": {"name": "get_current_weather", "description": "获取天气", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}},
  108. {"type": "function", "function": {"name": "get_exchange_rate", "description": "获取汇率", "parameters": {"type": "object", "properties": {"from_currency": {"type": "string"}, "to_currency": {"type": "string"}}, "required": ["from_currency", "to_currency"]}}},
  109. {"type": "function", "function": {"name": "translate_text", "description": "翻译文本", "parameters": {"type": "object", "properties": {"text": {"type": "string"}, "target_lang": {"type": "string"}}, "required": ["text", "target_lang"]}}},
  110. ]
  111. TOOL_SHORT_NAMES = {
  112. 'calculate_math': '数学', 'get_current_time': '时间', 'random_number': '随机',
  113. 'text_length': '字数', 'unit_converter': '单位', 'get_current_weather': '天气',
  114. 'get_exchange_rate': '汇率', 'translate_text': '翻译'
  115. }
  116. def execute_tool(tool_name, args):
  117. import datetime
  118. try:
  119. if tool_name == 'calculate_math':
  120. return {"result": safe_math_eval(args.get('expression', '0'))}
  121. elif tool_name == 'get_current_time':
  122. tz = args.get('timezone', 'Asia/Shanghai')
  123. return {"result": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
  124. elif tool_name == 'random_number':
  125. return {"result": random.randint(args.get('min', 0), args.get('max', 100))}
  126. elif tool_name == 'text_length':
  127. return {"result": len(args.get('text', ''))}
  128. elif tool_name == 'unit_converter':
  129. return {"result": f"{args.get('value', 0)} {args.get('from_unit', '')} = ? {args.get('to_unit', '')}"}
  130. elif tool_name == 'get_current_weather':
  131. return {"result": f"{args.get('city', 'Unknown')}: 晴, 7~10°C"}
  132. elif tool_name == 'get_exchange_rate':
  133. return {"result": f"1 {args.get('from_currency', 'USD')} = 7.2 {args.get('to_currency', 'CNY')}"}
  134. elif tool_name == 'translate_text':
  135. return {"result": f"[翻译结果]: hello world"}
  136. return {"result": "Unknown tool"}
  137. except Exception as e:
  138. return {"error": str(e)}
  139. def process_assistant_content(content, is_streaming=False):
  140. # 处理tool_call标签,格式化显示
  141. if '<tool_call>' in content:
  142. def format_tool_call(match):
  143. try:
  144. tc = json.loads(match.group(1))
  145. name = tc.get('name', 'unknown')
  146. args = tc.get('arguments', {})
  147. return f'<div style="background: rgba(80, 110, 150, 0.20); border: 1px solid rgba(140, 170, 210, 0.30); padding: 10px 12px; border-radius: 12px; margin: 6px 0;"><div style="font-size:12px;opacity:.75;display:block;margin:0 0 6px 0;line-height:1;">ToolCalling</div><div><b>{name}</b>: {json.dumps(args, ensure_ascii=False)}</div></div>'
  148. except:
  149. return match.group(0)
  150. content = re.sub(r'<tool_call>(.*?)</tool_call>', format_tool_call, content, flags=re.DOTALL)
  151. # 流式生成且开启思考时,一开始就放到折叠里
  152. if is_streaming and st.session_state.get('enable_thinking', False) and '</think>' not in content and '<think>' not in content:
  153. m = re.search(r'(\n\n(?:我是|您好|你好)[^\n]*)', content)
  154. if m and m.start(1) > 5:
  155. i = m.start(1)
  156. think_part = content[:i]
  157. answer_part = content[i:]
  158. return f'<details open style="border-left: 2px solid #666; padding-left: 12px; margin: 8px 0;"><summary style="cursor: pointer; color: #888;">已思考</summary><div style="color: #aaa; font-size: 0.95em; margin-top: 8px; max-height: 100px; overflow-y: auto;">{think_part.strip()}</div></details>{answer_part}'
  159. elif len(content) > 5:
  160. return f'<details open style="border-left: 2px solid #666; padding-left: 12px; margin: 8px 0;"><summary style="cursor: pointer; color: #888;">思考中...</summary><div style="color: #aaa; font-size: 0.95em; margin-top: 8px; max-height: 100px; overflow-y: auto; display: flex; flex-direction: column-reverse;"><div style="margin-bottom: auto;">{content.strip().replace(chr(10), "<br>")}</div></div></details>'
  161. if '<think>' in content and '</think>' in content:
  162. def format_think(match):
  163. think_content = match.group(2)
  164. if think_content.replace('\n', '').strip(): # 不是全换行
  165. return f'<details open style="border-left: 2px solid #666; padding-left: 12px; margin: 8px 0;"><summary style="cursor: pointer; color: #888;">已思考</summary><div style="color: #aaa; font-size: 0.95em; margin-top: 8px; max-height: 100px; overflow-y: auto;">{think_content.strip()}</div></details>'
  166. return ''
  167. content = re.sub(r'(<think>)(.*?)(</think>)', format_think, content, flags=re.DOTALL)
  168. if '<think>' in content and '</think>' not in content:
  169. def format_think_in_progress(match):
  170. tc = match.group(1)
  171. return f'<details open style="border-left: 2px solid #666; padding-left: 12px; margin: 8px 0;"><summary style="cursor: pointer; color: #888;">思考中...</summary><div style="color: #aaa; font-size: 0.95em; margin-top: 8px; max-height: 100px; overflow-y: auto; display: flex; flex-direction: column-reverse;"><div style="margin-bottom: auto;">{tc.strip().replace(chr(10), "<br>")}</div></div></details>'
  172. content = re.sub(r'<think>(.*?)$', format_think_in_progress, content, flags=re.DOTALL)
  173. if '<think>' not in content and '</think>' in content:
  174. def format_think_no_start(match):
  175. think_content = match.group(1)
  176. if think_content.replace('\n', '').strip():
  177. return f'<details open style="border-left: 2px solid #666; padding-left: 12px; margin: 8px 0;"><summary style="cursor: pointer; color: #888;">已思考</summary><div style="color: #aaa; font-size: 0.95em; margin-top: 8px; max-height: 100px; overflow-y: auto;">{think_content.strip()}</div></details>'
  178. return ''
  179. content = re.sub(r'(.*?)</think>', format_think_no_start, content, flags=re.DOTALL)
  180. return content
  181. @st.cache_resource
  182. def load_model_tokenizer(model_path):
  183. model = AutoModelForCausalLM.from_pretrained(
  184. model_path,
  185. trust_remote_code=True
  186. )
  187. tokenizer = AutoTokenizer.from_pretrained(
  188. model_path,
  189. trust_remote_code=True
  190. )
  191. if torch.device(device).type == 'cuda': model = model.half()
  192. model = model.eval().to(device)
  193. return model, tokenizer
  194. def clear_chat_messages():
  195. del st.session_state.messages
  196. del st.session_state.chat_messages
  197. def init_chat_messages():
  198. if "messages" in st.session_state:
  199. for i, message in enumerate(st.session_state.messages):
  200. if message["role"] == "assistant":
  201. st.markdown(process_assistant_content(message["content"]), unsafe_allow_html=True)
  202. else:
  203. st.markdown(
  204. f'<div style="display: flex; justify-content: flex-end;"><div style="display: inline-block; margin: 10px 0; padding: 8px 12px 8px 12px; background-color: #3d4450; border-radius: 22px; color: white;">{message["content"]}</div></div>',
  205. unsafe_allow_html=True)
  206. else:
  207. st.session_state.messages = []
  208. st.session_state.chat_messages = []
  209. return st.session_state.messages
  210. def regenerate_answer(index):
  211. st.session_state.messages.pop()
  212. st.session_state.chat_messages.pop()
  213. st.rerun()
  214. # 动态扫描模型目录
  215. script_dir = os.path.dirname(os.path.abspath(__file__))
  216. MODEL_PATHS = {}
  217. for d in sorted(os.listdir(script_dir), reverse=True):
  218. full_path = os.path.join(script_dir, d)
  219. if os.path.isdir(full_path) and not d.startswith('.') and not d.startswith('_'):
  220. if any(f.endswith(('.bin', '.safetensors', '.pt')) or os.path.exists(os.path.join(full_path, 'model.safetensors.index.json')) for f in os.listdir(full_path) if os.path.isfile(os.path.join(full_path, f))):
  221. MODEL_PATHS[d] = [d, d]
  222. if not MODEL_PATHS:
  223. MODEL_PATHS = {"No models found": ["", "No models"]}
  224. # 模型选择
  225. selected_model = st.sidebar.selectbox('Model', list(MODEL_PATHS.keys()), index=0)
  226. model_path = MODEL_PATHS[selected_model][0]
  227. slogan = f"我是 {MODEL_PATHS[selected_model][1]},有什么可以帮你的?" if st.session_state.get('lang', 'en') == 'zh' else f"I am {MODEL_PATHS[selected_model][1]}, how can I help you?"
  228. st.sidebar.markdown('<hr style="margin: 12px 0 16px 0;">', unsafe_allow_html=True)
  229. # 语言选择
  230. lang_options = {'中文': 'zh', 'English': 'en'}
  231. current_lang = st.session_state.get('lang', 'en')
  232. lang_index = 0 if current_lang == 'zh' else 1
  233. lang_label = st.sidebar.radio('Language / 语言', list(lang_options.keys()), index=lang_index, horizontal=True)
  234. if lang_options[lang_label] != current_lang:
  235. st.session_state.lang = lang_options[lang_label]
  236. st.rerun()
  237. st.sidebar.markdown('<hr style="margin: 12px 0 16px 0;">', unsafe_allow_html=True)
  238. # 参数设置
  239. st.session_state.history_chat_num = st.sidebar.slider(get_text('history_rounds'), 0, 8, 0, step=2)
  240. st.session_state.max_new_tokens = st.sidebar.slider(get_text('max_length'), 256, 8192, 8192, step=1)
  241. st.session_state.temperature = st.sidebar.slider(get_text('temperature'), 0.6, 1.2, 0.90, step=0.01)
  242. st.sidebar.markdown('<hr style="margin: 12px 0 16px 0;">', unsafe_allow_html=True)
  243. # 功能开关
  244. st.session_state.enable_thinking = st.sidebar.checkbox(get_text('thinking'), value=False, help=get_text('think_tip'))
  245. st.session_state.selected_tools = []
  246. with st.sidebar.expander(get_text('tools')):
  247. st.caption(get_text('tool_select'))
  248. selected_count = sum(1 for tool in TOOLS if st.session_state.get(f"tool_{tool['function']['name']}", False))
  249. for tool in TOOLS:
  250. name = tool['function']['name']
  251. short_name = TOOL_SHORT_NAMES.get(name, name)
  252. checked = st.checkbox(short_name, key=f"tool_{name}", disabled=(selected_count >= 4 and not st.session_state.get(f"tool_{name}", False)))
  253. if checked and len(st.session_state.selected_tools) < 4:
  254. st.session_state.selected_tools.append(name)
  255. image_url = "https://www.modelscope.cn/api/v1/studio/gongjy/MiniMind/repo?Revision=master&FilePath=images%2Flogo2.png&View=true"
  256. st.markdown(
  257. f'<div style="display: flex; flex-direction: column; align-items: center; text-align: center; margin: 0; padding: 0;">'
  258. '<div style="font-style: italic; font-weight: 900; margin: 0; padding-top: 4px; display: flex; align-items: center; justify-content: center; flex-wrap: wrap; width: 100%;">'
  259. f'<img src="{image_url}" style="width: 40px; height: 40px; "> '
  260. f'<span style="font-size: 26px; margin-left: 10px;">{slogan}</span>'
  261. '</div>'
  262. f'<span style="color: #bbb; font-style: italic; margin-top: 6px; margin-bottom: 10px;">{get_text("disclaimer")}</span>'
  263. '</div>',
  264. unsafe_allow_html=True
  265. )
  266. def setup_seed(seed):
  267. random.seed(seed)
  268. np.random.seed(seed)
  269. torch.manual_seed(seed)
  270. torch.cuda.manual_seed(seed)
  271. torch.cuda.manual_seed_all(seed)
  272. torch.backends.cudnn.deterministic = True
  273. torch.backends.cudnn.benchmark = False
  274. def main():
  275. model, tokenizer = load_model_tokenizer(model_path)
  276. if "messages" not in st.session_state:
  277. st.session_state.messages = []
  278. st.session_state.chat_messages = []
  279. messages = st.session_state.messages
  280. for i, message in enumerate(messages):
  281. if message["role"] == "assistant":
  282. st.markdown(process_assistant_content(message["content"]), unsafe_allow_html=True)
  283. else:
  284. st.markdown(
  285. f'<div style="display: flex; justify-content: flex-end;"><div style="display: inline-block; margin: 10px 0; padding: 8px 12px 8px 12px; background-color: #3d4450; border-radius: 22px; color: white;">{message["content"]}</div></div>',
  286. unsafe_allow_html=True)
  287. prompt = st.chat_input(key="input", placeholder=get_text('send'))
  288. if hasattr(st.session_state, 'regenerate') and st.session_state.regenerate:
  289. prompt = st.session_state.last_user_message
  290. regenerate_index = st.session_state.regenerate_index
  291. delattr(st.session_state, 'regenerate')
  292. delattr(st.session_state, 'last_user_message')
  293. delattr(st.session_state, 'regenerate_index')
  294. if prompt:
  295. st.markdown(
  296. f'<div style="display: flex; justify-content: flex-end;"><div style="display: inline-block; margin: 10px 0; padding: 8px 12px 8px 12px; background-color: #3d4450; border-radius: 22px; color: white;">{prompt}</div></div>',
  297. unsafe_allow_html=True)
  298. messages.append({"role": "user", "content": prompt})
  299. st.session_state.chat_messages.append({"role": "user", "content": prompt})
  300. placeholder = st.empty()
  301. random_seed = random.randint(0, 2 ** 32 - 1)
  302. setup_seed(random_seed)
  303. tools = [t for t in TOOLS if t['function']['name'] in st.session_state.get('selected_tools', [])] or None
  304. sys_prompt = [] if tools else [{"role": "system", "content": "你是MiniMind,一个乐于助人、知识渊博的AI助手。请用完整且友好的方式回答用户问题。"}]
  305. st.session_state.chat_messages = sys_prompt + st.session_state.chat_messages[-(st.session_state.history_chat_num + 1):]
  306. template_kwargs = {"tokenize": False, "add_generation_prompt": True}
  307. if st.session_state.get('enable_thinking', False):
  308. template_kwargs["open_thinking"] = True
  309. if tools:
  310. template_kwargs["tools"] = tools
  311. new_prompt = tokenizer.apply_chat_template(st.session_state.chat_messages, **template_kwargs)
  312. inputs = tokenizer(new_prompt, return_tensors="pt", truncation=True).to(device)
  313. streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
  314. generation_kwargs = {
  315. "input_ids": inputs.input_ids,
  316. "max_length": inputs.input_ids.shape[1] + st.session_state.max_new_tokens,
  317. "num_return_sequences": 1,
  318. "do_sample": True,
  319. "attention_mask": inputs.attention_mask,
  320. "pad_token_id": tokenizer.pad_token_id,
  321. "eos_token_id": tokenizer.eos_token_id,
  322. "temperature": st.session_state.temperature,
  323. "top_p": 0.85,
  324. "streamer": streamer,
  325. }
  326. Thread(target=model.generate, kwargs=generation_kwargs).start()
  327. answer = ""
  328. for new_text in streamer:
  329. answer += new_text
  330. placeholder.markdown(process_assistant_content(answer, is_streaming=True), unsafe_allow_html=True)
  331. full_answer = answer
  332. for _ in range(16):
  333. tool_calls = re.findall(r'<tool_call>(.*?)</tool_call>', answer, re.DOTALL)
  334. if not tool_calls:
  335. break
  336. st.session_state.chat_messages.append({"role": "assistant", "content": answer})
  337. tool_results = []
  338. for tc_str in tool_calls:
  339. try:
  340. tc = json.loads(tc_str.strip())
  341. result = execute_tool(tc.get('name', ''), tc.get('arguments', {}))
  342. st.session_state.chat_messages.append({"role": "tool", "content": json.dumps(result, ensure_ascii=False)})
  343. tool_results.append(f'<div style="background: rgba(90, 130, 110, 0.20); border: 1px solid rgba(150, 200, 170, 0.30); padding: 10px 12px; border-radius: 12px; margin: 6px 0;"><div style="font-size:12px;opacity:.75;display:block;margin:0 0 6px 0;line-height:1;">ToolCalled</div><div><b>{tc.get("name", "")}</b>: {json.dumps(result, ensure_ascii=False)}</div></div>')
  344. except:
  345. pass
  346. full_answer += "\n" + "\n".join(tool_results) + "\n"
  347. placeholder.markdown(process_assistant_content(full_answer, is_streaming=True), unsafe_allow_html=True)
  348. new_prompt = tokenizer.apply_chat_template(st.session_state.chat_messages, **template_kwargs)
  349. inputs = tokenizer(new_prompt, return_tensors="pt", truncation=True).to(device)
  350. streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
  351. generation_kwargs["input_ids"] = inputs.input_ids
  352. generation_kwargs["attention_mask"] = inputs.attention_mask
  353. generation_kwargs["max_length"] = inputs.input_ids.shape[1] + st.session_state.max_new_tokens
  354. generation_kwargs["streamer"] = streamer
  355. Thread(target=model.generate, kwargs=generation_kwargs).start()
  356. answer = ""
  357. for new_text in streamer:
  358. answer += new_text
  359. placeholder.markdown(process_assistant_content(full_answer + answer, is_streaming=True), unsafe_allow_html=True)
  360. full_answer += answer
  361. answer = full_answer
  362. messages.append({"role": "assistant", "content": answer})
  363. st.session_state.chat_messages.append({"role": "assistant", "content": answer})
  364. if __name__ == "__main__":
  365. main()