web_demo.py 22 KB

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