diff --git a/apps/agentfabric/app.py b/apps/agentfabric/app.py index 247f675e7..20780cf6b 100644 --- a/apps/agentfabric/app.py +++ b/apps/agentfabric/app.py @@ -102,18 +102,19 @@ def check_uuid(uuid_str): create_chatbot = mgr.Chatbot( show_label=False, value=[[None, start_text]], - flushing=False, show_copy_button=True, llm_thinking_presets=[ qwen( action_input_title='调用 ', action_output_title='完成调用') ]) - create_chat_input = gr.Textbox( + create_chat_input = mgr.MultimodalInput( label=i18n.get('message'), - placeholder=i18n.get('message_placeholder')) - create_send_button = gr.Button( - i18n.get('sendOnLoading'), interactive=False) + placeholder=i18n.get('message_placeholder'), + interactive=False, + upload_button_props=dict(visible=False), + submit_button_props=dict( + label=i18n.get('sendOnLoading'))) configure_tab = gr.Tab(i18n.get_whole('configure'), id=1) with configure_tab: @@ -231,21 +232,19 @@ def check_uuid(uuid_str): action_input_title='调用 ', action_output_title='完成调用') ]) - preview_chat_input = gr.Textbox( + preview_chat_input = mgr.MultimodalInput( + interactive=False, label=i18n.get('message'), - placeholder=i18n.get('message_placeholder')) + placeholder=i18n.get('message_placeholder'), + upload_button_props=dict( + label=i18n.get('upload_btn'), + file_types=['file', 'image', 'audio', 'video', 'text'], + file_count='multiple'), + submit_button_props=dict(label=i18n.get('sendOnLoading'))) user_chat_bot_suggest = gr.Dataset( label=i18n.get('prompt_suggestion'), components=[preview_chat_input], samples=[]) - # preview_send_button = gr.Button('Send') - with gr.Row(): - upload_button = gr.UploadButton( - i18n.get('upload_btn'), - file_types=['file', 'image', 'audio', 'video', 'text'], - file_count='multiple') - preview_send_button = gr.Button( - i18n.get('sendOnLoading'), interactive=False) user_chat_bot_suggest.select( lambda evt: evt[0], inputs=[user_chat_bot_suggest], @@ -282,8 +281,8 @@ def check_uuid(uuid_str): # bot user_chat_bot_cover, user_chat_bot_suggest, - preview_send_button, - create_send_button, + preview_chat_input, + create_chat_input, ] # 初始化表单 @@ -388,14 +387,14 @@ def create_send_message(chatbot, input, _state, uuid_str): uuid_str = check_uuid(uuid_str) # 将发送的消息添加到聊天历史 builder_agent = _state['builder_agent'] - chatbot.append((input, '')) + chatbot.append([{'text': input.text, 'files': input.files}, None]) yield { create_chatbot: chatbot, - create_chat_input: gr.Textbox(value=''), + create_chat_input: None, } response = '' for frame in builder_agent.stream_run( - input, print_info=True, uuid_str=uuid_str): + input.text, print_info=True, uuid_str=uuid_str): llm_result = frame.get('llm_text', '') exec_result = frame.get('exec_result', '') step_result = frame.get('step', '') @@ -419,12 +418,12 @@ def create_send_message(chatbot, input, _state, uuid_str): frame_text = content response = beauty_output(f'{response}{frame_text}', step_result) - chatbot[-1] = (input, response) + chatbot[-1][1] = response yield { create_chatbot: chatbot, } - create_send_button.click( + create_chat_input.submit( create_send_message, inputs=[create_chatbot, create_chat_input, state, uuid_str], outputs=[ @@ -544,26 +543,32 @@ def preview_send_message(chatbot, input, _state, uuid_str): # 将发送的消息添加到聊天历史 _uuid_str = check_uuid(uuid_str) user_agent = _state['user_agent'] - if 'new_file_paths' in _state: - new_file_paths = _state['new_file_paths'] - else: - new_file_paths = [] - _state['new_file_paths'] = [] + append_files = [] + for file in input.files: + file_name = os.path.basename(file.path) + # covert xxx.json to xxx_uuid_str.json + file_name = file_name.replace('.', f'_{uuid_str}.') + file_path = os.path.join(get_ci_dir(), file_name) + if not os.path.exists(file_path): + # make sure file path's directory exists + os.makedirs(os.path.dirname(file_path), exist_ok=True) + shutil.copy(file.path, file_path) + append_files.append(file_path) - chatbot.append((input, '')) + chatbot.append([{'text': input.text, 'files': input.files}, None]) yield { user_chatbot: mgr.Chatbot(visible=True, value=chatbot), user_chat_bot_cover: gr.HTML(visible=False), - preview_chat_input: gr.Textbox(value='') + preview_chat_input: None } response = '' try: for frame in user_agent.stream_run( - input, + input.text, print_info=True, remote=False, - append_files=new_file_paths, + append_files=append_files, uuid=_uuid_str): llm_result = frame.get('llm_text', '') exec_result = frame.get('exec_result', '') @@ -578,7 +583,7 @@ def preview_send_message(chatbot, input, _state, uuid_str): # important! do not change this response += frame_text - chatbot[-1] = (input, response) + chatbot[-1][1] = response yield {user_chatbot: chatbot} except Exception as e: if 'dashscope.common.error.AuthenticationError' in str(e): @@ -588,51 +593,14 @@ def preview_send_message(chatbot, input, _state, uuid_str): msg = 'Too many people are calling, please try again later.' else: msg = str(e) - chatbot[-1] = (input, msg) + chatbot[-1][1] = msg yield {user_chatbot: chatbot} - preview_send_button.click( + preview_chat_input.submit( preview_send_message, inputs=[user_chatbot, preview_chat_input, state, uuid_str], outputs=[user_chatbot, user_chat_bot_cover, preview_chat_input]) - def upload_file(chatbot, upload_button, _state, uuid_str): - uuid_str = check_uuid(uuid_str) - new_file_paths = [] - if 'file_paths' in _state: - file_paths = _state['file_paths'] - else: - file_paths = [] - for file in upload_button: - file_name = os.path.basename(file.name) - # covert xxx.json to xxx_uuid_str.json - file_name = file_name.replace('.', f'_{uuid_str}.') - file_path = os.path.join(get_ci_dir(), file_name) - if not os.path.exists(file_path): - # make sure file path's directory exists - os.makedirs(os.path.dirname(file_path), exist_ok=True) - shutil.copy(file.name, file_path) - file_paths.append(file_path) - new_file_paths.append(file_path) - if file_name.endswith(('.jpeg', '.png', '.jpg')): - chatbot += [((file_path, ), None)] - - else: - chatbot.append((None, f'上传文件{file_name},成功')) - yield { - user_chatbot: mgr.Chatbot(visible=True, value=chatbot), - user_chat_bot_cover: gr.HTML(visible=False), - preview_chat_input: gr.Textbox(value='') - } - - _state['file_paths'] = file_paths - _state['new_file_paths'] = new_file_paths - - upload_button.upload( - upload_file, - inputs=[user_chatbot, upload_button, state, uuid_str], - outputs=[user_chatbot, user_chat_bot_cover, preview_chat_input]) - # configuration for publish def publish_agent(name, uuid_str, state): uuid_str = check_uuid(uuid_str) @@ -700,26 +668,26 @@ def change_lang(language): preview_header: gr.HTML( f"""
{i18n.get('preview')}
"""), - preview_send_button: - gr.Button(value=i18n.get('send')), + preview_chat_input: + mgr.MultimodalInput( + label=i18n.get('message'), + placeholder=i18n.get('message_placeholder'), + submit_button_props=dict(label=i18n.get('send')), + upload_button_props=dict( + label=i18n.get('upload_btn'), + file_types=['file', 'image', 'audio', 'video', 'text'], + file_count='multiple')), create_chat_input: - gr.Textbox( + mgr.MultimodalInput( label=i18n.get('message'), - placeholder=i18n.get('message_placeholder')), - create_send_button: - gr.Button(value=i18n.get('send')), + placeholder=i18n.get('message_placeholder'), + submit_button_props=dict(label=i18n.get('send'))), user_chat_bot_suggest: gr.Dataset( components=[preview_chat_input], label=i18n.get('prompt_suggestion')), - preview_chat_input: - gr.Textbox( - label=i18n.get('message'), - placeholder=i18n.get('message_placeholder')), publish_accordion: gr.Accordion(label=i18n.get('publish')), - upload_button: - gr.UploadButton(i18n.get('upload_btn')), header: gr.Markdown(i18n.get('header')), publish_alert_md: @@ -735,9 +703,8 @@ def change_lang(language): inputs=[language], outputs=configure_updated_outputs + [ configure_button, create_chat_input, open_api_accordion, - preview_header, preview_chat_input, publish_accordion, - upload_button, header, publish_alert_md, build_hint_md, - publish_hint_md + preview_header, preview_chat_input, publish_accordion, header, + publish_alert_md, build_hint_md, publish_hint_md ]) def init_all(uuid_str, _state): @@ -752,10 +719,14 @@ def init_all(uuid_str, _state): yield { state: _state, - preview_send_button: - gr.Button(value=i18n.get('send'), interactive=True), - create_send_button: - gr.Button(value=i18n.get('send'), interactive=True), + preview_chat_input: + mgr.MultimodalInput( + submit_button_props=dict(label=i18n.get('send')), + interactive=True), + create_chat_input: + mgr.MultimodalInput( + submit_button_props=dict(label=i18n.get('send')), + interactive=True), } demo.load( diff --git a/apps/agentfabric/appBot.py b/apps/agentfabric/appBot.py index f91295d5e..141179518 100644 --- a/apps/agentfabric/appBot.py +++ b/apps/agentfabric/appBot.py @@ -69,20 +69,19 @@ def init_user(state): latex_delimiters=[], show_label=False, show_copy_button=True, - llm_thinking_presets=[qwen()]) + llm_thinking_presets=[ + qwen( + action_input_title='调用 ', + action_output_title='完成调用') + ]) with gr.Row(): - with gr.Column(scale=12): - preview_chat_input = gr.Textbox( - show_label=False, - container=False, - placeholder='跟我聊聊吧~') - with gr.Column(min_width=70, scale=1): - upload_button = gr.UploadButton( - '上传', - file_types=['file', 'image', 'audio', 'video', 'text'], - file_count='multiple') - with gr.Column(min_width=70, scale=1): - preview_send_button = gr.Button('发送', variant='primary') + user_chatbot_input = mgr.MultimodalInput( + interactive=True, + placeholder='跟我聊聊吧~', + upload_button_props=dict( + file_count='multiple', + file_types=['file', 'image', 'audio', 'video', + 'text'])) with gr.Column(scale=1): user_chat_bot_cover = gr.HTML( @@ -90,43 +89,7 @@ def init_user(state): user_chat_bot_suggest = gr.Examples( label='Prompt Suggestions', examples=suggests, - inputs=[preview_chat_input]) - - def upload_file(chatbot, upload_button, _state): - _uuid_str = check_uuid(uuid_str) - new_file_paths = [] - if 'file_paths' in _state: - file_paths = _state['file_paths'] - else: - file_paths = [] - for file in upload_button: - file_name = os.path.basename(file.name) - # covert xxx.json to xxx_uuid_str.json - file_name = file_name.replace('.', f'_{_uuid_str}.') - file_path = os.path.join(get_ci_dir(), file_name) - if not os.path.exists(file_path): - # make sure file path's directory exists - os.makedirs(os.path.dirname(file_path), exist_ok=True) - shutil.copy(file.name, file_path) - file_paths.append(file_path) - new_file_paths.append(file_path) - if file_name.endswith(('.jpeg', '.png', '.jpg')): - chatbot += [((file_path, ), None)] - - else: - chatbot.append((None, f'上传文件{file_name},成功')) - yield { - user_chatbot: gr.Chatbot.update(visible=True, value=chatbot), - preview_chat_input: gr.Textbox.update(value='') - } - - _state['file_paths'] = file_paths - _state['new_file_paths'] = new_file_paths - - upload_button.upload( - upload_file, - inputs=[user_chatbot, upload_button, state], - outputs=[user_chatbot, preview_chat_input]) + inputs=[user_chatbot_input]) def send_message(chatbot, input, _state): # 将发送的消息添加到聊天历史 @@ -134,24 +97,20 @@ def send_message(chatbot, input, _state): init_user(_state) user_agent = _state['user_agent'] - if 'new_file_paths' in _state: - new_file_paths = _state['new_file_paths'] - else: - new_file_paths = [] - _state['new_file_paths'] = [] - chatbot.append((input, '')) + append_files = list(map(lambda f: f.path, input.files)) + chatbot.append([{'text': input.text, 'files': input.files}, None]) yield { user_chatbot: chatbot, - preview_chat_input: gr.Textbox(value=''), + user_chatbot_input: None, } response = '' try: for frame in user_agent.stream_run( - input, + input.text, print_info=True, remote=False, - append_files=new_file_paths): + append_files=append_files): # is_final = frame.get("frame_is_final") llm_result = frame.get('llm_text', '') exec_result = frame.get('exec_result', '') @@ -167,7 +126,7 @@ def send_message(chatbot, input, _state): # important! do not change this response += frame_text - chatbot[-1] = (input, response) + chatbot[-1][1] = response yield { user_chatbot: chatbot, } @@ -179,13 +138,13 @@ def send_message(chatbot, input, _state): msg = 'Too many people are calling, please try again later.' else: msg = str(e) - chatbot[-1] = (input, msg) + chatbot[-1][1] = msg yield {user_chatbot: chatbot} - preview_send_button.click( - send_message, - inputs=[user_chatbot, preview_chat_input, state], - outputs=[user_chatbot, preview_chat_input]) + gr.on([user_chatbot_input.submit], + fn=send_message, + inputs=[user_chatbot, user_chatbot_input, state], + outputs=[user_chatbot, user_chatbot_input]) demo.load(init_user, inputs=[state], outputs=[state]) diff --git a/apps/agentfabric/gradio_utils.py b/apps/agentfabric/gradio_utils.py index fecc0f90d..7fedcbeac 100644 --- a/apps/agentfabric/gradio_utils.py +++ b/apps/agentfabric/gradio_utils.py @@ -6,10 +6,6 @@ from urllib import parse import json -import markdown -from gradio.components import Chatbot as ChatBotBase -from modelscope_agent.action_parser import MRKLActionParser -from PIL import Image ALREADY_CONVERTED_MARK = '' @@ -104,331 +100,3 @@ def postprocess_messages( bot_message, ]) return processed_messages - - -class ChatBot(ChatBotBase): - - def normalize_markdown(self, bot_message): - lines = bot_message.split('\n') - normalized_lines = [] - inside_list = False - - for i, line in enumerate(lines): - if re.match(r'^(\d+\.|-|\*|\+)\s', line.strip()): - if not inside_list and i > 0 and lines[i - 1].strip() != '': - normalized_lines.append('') - inside_list = True - normalized_lines.append(line) - elif inside_list and line.strip() == '': - if i < len(lines) - 1 and not re.match(r'^(\d+\.|-|\*|\+)\s', - lines[i + 1].strip()): - normalized_lines.append(line) - continue - else: - inside_list = False - normalized_lines.append(line) - - return '\n'.join(normalized_lines) - - def convert_markdown(self, bot_message): - if bot_message.count('```') % 2 != 0: - bot_message += '\n```' - - bot_message = self.normalize_markdown(bot_message) - - result = markdown.markdown( - bot_message, - extensions=[ - 'toc', 'extra', 'tables', 'codehilite', - 'markdown_cjk_spacing.cjk_spacing', 'pymdownx.magiclink' - ], - extension_configs={ - 'markdown_katex': { - 'no_inline_svg': True, # fix for WeasyPrint - 'insert_fonts_css': True, - }, - 'codehilite': { - 'linenums': False, - 'guess_lang': True - }, - 'mdx_truly_sane_lists': { - 'nested_indent': 2, - 'truly_sane': True, - } - }) - result = ''.join(result) - return result - - @staticmethod - def prompt_parse(message): - output = '' - if 'Thought' in message: - if 'Action' in message or 'Action Input:' in message: - re_pattern_thought = re.compile( - pattern=r'([\s\S]+)Thought:([\s\S]+)Action:') - - res = re_pattern_thought.search(message) - - if res is None: - re_pattern_thought_only = re.compile( - pattern=r'Thought:([\s\S]+)Action:') - res = re_pattern_thought_only.search(message) - llm_result = '' - else: - llm_result = res.group(1).strip() - action_thought_result = res.group(2).strip() - - re_pattern_action = re.compile( - pattern= - r'Action:([\s\S]+)Action Input:([\s\S]+)<\|startofexec\|>') - res = re_pattern_action.search(message) - if res is None: - action, action_parameters = MRKLActionParser( - ).parse_response(message) - else: - action = res.group(1).strip() - action_parameters = res.group(2) - action_result = json.dumps({ - 'api_name': action, - 'parameters': action_parameters - }) - output += f'{llm_result}\n{action_thought_result}\n<|startofthink|>\n{action_result}\n<|endofthink|>\n' - if '<|startofexec|>' in message: - re_pattern3 = re.compile( - pattern=r'<\|startofexec\|>([\s\S]+)<\|endofexec\|>') - res3 = re_pattern3.search(message) - observation = res3.group(1).strip() - output += f'\n<|startofexec|>\n{observation}\n<|endofexec|>\n' - if 'Final Answer' in message: - re_pattern2 = re.compile( - pattern=r'Thought:([\s\S]+)Final Answer:([\s\S]+)') - res2 = re_pattern2.search(message) - # final_thought_result = res2.group(1).strip() - final_answer_result = res2.group(2).strip() - output += f'{final_answer_result}\n' - - if output == '': - return message - print(output) - return output - else: - return message - - def convert_bot_message(self, bot_message): - - bot_message = ChatBot.prompt_parse(bot_message) - # print('processed bot message----------') - # print(bot_message) - # print('processed bot message done') - start_pos = 0 - result = '' - find_json_pattern = re.compile(r'{[\s\S]+}') - START_OF_THINK_TAG, END_OF_THINK_TAG = '<|startofthink|>', '<|endofthink|>' - START_OF_EXEC_TAG, END_OF_EXEC_TAG = '<|startofexec|>', '<|endofexec|>' - while start_pos < len(bot_message): - try: - start_of_think_pos = bot_message.index(START_OF_THINK_TAG, - start_pos) - end_of_think_pos = bot_message.index(END_OF_THINK_TAG, - start_pos) - if start_pos < start_of_think_pos: - result += self.convert_markdown( - bot_message[start_pos:start_of_think_pos]) - think_content = bot_message[start_of_think_pos - + len(START_OF_THINK_TAG - ):end_of_think_pos].strip() - json_content = find_json_pattern.search(think_content) - think_content = json_content.group( - ) if json_content else think_content - try: - think_node = json.loads(think_content) - plugin_name = think_node.get( - 'plugin_name', - think_node.get('plugin', - think_node.get('api_name', 'unknown'))) - summary = f'选择插件【{plugin_name}】,调用处理中...' - del think_node['url'] - # think_node.pop('url', None) - - detail = f'```json\n\n{json.dumps(think_node, indent=3, ensure_ascii=False)}\n\n```' - except Exception: - summary = '思考中...' - detail = think_content - # traceback.print_exc() - # detail += traceback.format_exc() - result += '
' + summary + '' + self.convert_markdown( - detail) + '
' - # print(f'detail:{detail}') - start_pos = end_of_think_pos + len(END_OF_THINK_TAG) - except Exception: - # result += traceback.format_exc() - break - # continue - - try: - start_of_exec_pos = bot_message.index(START_OF_EXEC_TAG, - start_pos) - end_of_exec_pos = bot_message.index(END_OF_EXEC_TAG, start_pos) - # print(start_of_exec_pos) - # print(end_of_exec_pos) - # print(bot_message[start_of_exec_pos:end_of_exec_pos]) - # print('------------------------') - if start_pos < start_of_exec_pos: - result += self.convert_markdown( - bot_message[start_pos:start_of_think_pos]) - exec_content = bot_message[start_of_exec_pos - + len(START_OF_EXEC_TAG - ):end_of_exec_pos].strip() - try: - summary = '完成插件调用.' - detail = f'```json\n\n{exec_content}\n\n```' - except Exception: - pass - - result += '
' + summary + '' + self.convert_markdown( - detail) + '
' - - start_pos = end_of_exec_pos + len(END_OF_EXEC_TAG) - except Exception: - # result += traceback.format_exc() - continue - if start_pos < len(bot_message): - result += self.convert_markdown(bot_message[start_pos:]) - result += ALREADY_CONVERTED_MARK - return result - - def convert_bot_message_for_qwen(self, bot_message): - - start_pos = 0 - result = '' - find_json_pattern = re.compile(r'{[\s\S]+}') - ACTION = 'Action:' - ACTION_INPUT = 'Action Input' - OBSERVATION = 'Observation' - RESULT_START = '' - RESULT_END = '' - while start_pos < len(bot_message): - try: - action_pos = bot_message.index(ACTION, start_pos) - action_input_pos = bot_message.index(ACTION_INPUT, start_pos) - result += self.convert_markdown( - bot_message[start_pos:action_pos]) - # Action: image_gen - # Action Input - # {"text": "金庸武侠 世界", "resolution": "1280x720"} - # Observation: ![IMAGEGEN](https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/1d/e9/20231116/723609ee/d046d2d9-0c95-420b-9467-f0e831f5e2b7-1.png?Expires=1700227460&OSSAccessKeyId=LTAI5tQZd8AEcZX6KZV4G8qL&Signature=R0PlEazQF9uBD%2Fh9tkzOkJMGyg8%3D) # noqa E501 - action_name = bot_message[action_pos - + len(ACTION - ):action_input_pos].strip() - # action_start action_end 使用 Action Input 到 Observation 之间 - action_input_end = bot_message[action_input_pos:].index( - OBSERVATION) - 1 - action_input = bot_message[action_input_pos:action_input_pos - + action_input_end].strip() - is_json = find_json_pattern.search(action_input) - if is_json: - action_input = is_json.group() - else: - action_input = re.sub(r'^Action Input[:]?[\s]*', '', - action_input) - - summary = f'调用工具 {action_name}' - if is_json: - detail = f'```json\n\n{json.dumps(json.loads(action_input), indent=4, ensure_ascii=False)}\n\n```' - else: - detail = action_input - result += '
' + summary + '' + self.convert_markdown( - detail) + '
' - start_pos = action_input_pos + action_input_end + 1 - try: - observation_pos = bot_message.index(OBSERVATION, start_pos) - idx = observation_pos + len(OBSERVATION) - obs_message = bot_message[idx:] - observation_start_id = obs_message.index( - RESULT_START) + len(RESULT_START) - observation_end_idx = obs_message.index(RESULT_END) - summary = '完成调用' - exec_content = obs_message[ - observation_start_id:observation_end_idx] - detail = f'```\n\n{exec_content}\n\n```' - start_pos = idx + observation_end_idx + len(RESULT_END) - except Exception: - summary = '执行中...' - detail = '' - exec_content = None - - result += '
' + summary + '' + self.convert_markdown( - detail) + '
' - if exec_content is not None and '[IMAGEGEN]' in exec_content: - # convert local file to base64 - re_pattern = re.compile(pattern=r'!\[[^\]]+\]\(([^)]+)\)') - res = re_pattern.search(exec_content) - if res: - image_path = res.group(1).strip() - if os.path.isfile(image_path): - exec_content = convert_url( - exec_content, - covert_image_to_base64(image_path)) - result += self.convert_markdown(f'{exec_content}') - - except Exception: - # import traceback; traceback.print_exc() - result += self.convert_markdown(bot_message[start_pos:]) - start_pos = len(bot_message[start_pos:]) - break - - result += ALREADY_CONVERTED_MARK - return result - - def postprocess( - self, - message_pairs: list[list[str | tuple[str] | tuple[str, str] | None] - | tuple], - ) -> list[list[str | dict | None]]: - """ - Parameters: - message_pairs: List of lists representing the message and response pairs. - Each message and response should be a string, which may be in Markdown format. - It can also be a tuple whose first element is a string or pathlib. - Path filepath or URL to an image/video/audio, and second (optional) element is the alt text, - in which case the media file is displayed. It can also be None, in which case that message is not displayed. - Returns: - List of lists representing the message and response. Each message and response will be a string of HTML, - or a dictionary with media information. Or None if the message is not to be displayed. - """ - if message_pairs is None: - return [] - processed_messages = [] - for message_pair in message_pairs: - assert isinstance( - message_pair, (tuple, list) - ), f'Expected a list of lists or list of tuples. Received: {message_pair}' - assert ( - len(message_pair) == 2 - ), f'Expected a list of lists of length 2 or list of tuples of length 2. Received: {message_pair}' - if isinstance(message_pair[0], tuple) or isinstance( - message_pair[1], tuple): - processed_messages.append([ - self._postprocess_chat_messages(message_pair[0]), - self._postprocess_chat_messages(message_pair[1]), - ]) - else: - # 处理不是元组的情况 - user_message, bot_message = message_pair - - if user_message and not user_message.endswith( - ALREADY_CONVERTED_MARK): - convert_md = self.convert_markdown( - html.escape(user_message)) - user_message = f'{convert_md}' + ALREADY_CONVERTED_MARK - if bot_message and not bot_message.endswith( - ALREADY_CONVERTED_MARK): - # bot_message = self.convert_bot_message(bot_message) - bot_message = self.convert_bot_message_for_qwen( - bot_message) - processed_messages.append([ - user_message, - bot_message, - ]) - - return processed_messages