MiniCPM5-1B-WebDemo / utils_chatbot.py
R-Kentaren's picture
Add CPU support, custom system prompt, and zero-API-key web search (DuckDuckGo, safe-search off)
9b652a9 verified
Raw
History Blame Contribute Delete
1.53 kB
def organize_messages(message, history=None, system_prompt: str = "", web_context: str = ""):
"""Build chat messages from history tuples [[user, assistant], ...].
Args:
message: the latest user message.
history: optional list of [user, assistant] turns.
system_prompt: optional custom system prompt. Falls back to a
sensible default if empty / whitespace-only.
web_context: optional web-search context block to prepend to the
latest user message so the model can ground its answer.
"""
default_sys = "You are a helpful assistant."
sys_text = system_prompt.strip() if system_prompt and system_prompt.strip() else default_sys
msg_ls = [{"role": "system", "content": sys_text}]
if history:
for turn in history:
if not turn:
continue
user_text = turn[0] if len(turn) > 0 else None
assistant_text = turn[1] if len(turn) > 1 else None
if user_text:
msg_ls.append({"role": "user", "content": user_text})
if assistant_text:
msg_ls.append({"role": "assistant", "content": assistant_text})
final_user_content = message
if web_context:
# Prepend the search results block; keep the user's question intact
# so the model still sees it verbatim at the end.
final_user_content = f"{web_context}\n\nUser question: {message}"
msg_ls.append({"role": "user", "content": final_user_content})
return msg_ls