| |
| import json |
| import re |
| from typing import List, Optional, Union |
|
|
| from swift.infer_engine import Function |
| from .hermes import HermesAgentTemplate |
|
|
|
|
| def render_extra_keys(obj, handled_keys): |
| """Helper function to render extra keys not explicitly handled""" |
| result = '' |
| if isinstance(obj, dict): |
| for key, value in obj.items(): |
| if key not in handled_keys: |
| result += f'\n<{key}>{json.dumps(value, ensure_ascii=False)}</{key}>' |
| return result |
|
|
|
|
| TOOL_DESC_SUFFIX = ( |
| '</tools>\n\nIf you choose to call a function ONLY reply in the following format with ' |
| 'NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\n' |
| 'value_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\n' |
| 'that can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\n' |
| 'Reminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> ' |
| 'block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n' |
| '- You may provide optional reasoning for your function call in natural language BEFORE the function call, ' |
| 'but NOT after\n- If there is no function call available, ' |
| 'answer the question like normal with your current ' |
| 'knowledge and do not tell the user about function calls\n</IMPORTANT>') |
|
|
|
|
| class Qwen3CoderAgentTemplate(HermesAgentTemplate): |
|
|
| @staticmethod |
| def _find_function_call(single_content: str) -> Optional[Function]: |
| single_content = single_content.strip() |
| |
| if not single_content.startswith('<function=') or not single_content.endswith('</function>'): |
| return None |
|
|
| |
| func_name_match = re.search(r'<function=([^>]+)>', single_content) |
| if not func_name_match: |
| return None |
|
|
| func_name = func_name_match.group(1).strip() |
| parameters = {} |
|
|
| |
| |
| param_pattern = r'<parameter=([^>]+)>\s*(.*?)\s*</parameter>' |
| param_matches = re.findall(param_pattern, single_content, re.DOTALL) |
|
|
| for param_name, param_value in param_matches: |
| |
| clean_value = param_value.strip() |
| parameters[param_name.strip()] = clean_value |
|
|
| return Function(name=func_name, arguments=json.dumps(parameters, ensure_ascii=False)) |
|
|
| def get_toolcall(self, response: str) -> List[Function]: |
| |
| toolcall_list = re.findall(r'<tool_call>(.*?)</tool_call>', response, re.DOTALL) |
| functions = [] |
| for toolcall in toolcall_list: |
| function = self._find_function_call(toolcall) |
| if function: |
| functions.append(function) |
| if len(functions) == 0: |
| |
| return super(HermesAgentTemplate, self).get_toolcall(response) |
| return functions |
|
|
| def _format_tools(self, tools: List[Union[str, dict]], system: Optional[str] = None, user_message=None) -> str: |
| if system is None: |
| system = 'You are Qwen, a helpful AI assistant that can interact with a computer to solve tasks.' |
| tool_descs = [f'{system}\n\n# Tools\n\nYou have access to the following functions:\n\n<tools>'] |
| for tool in tools: |
| tool_desc = '' |
|
|
| |
| if isinstance(tool, dict) and 'function' in tool: |
| tool = tool['function'] |
|
|
| |
| tool_desc += f"<function>\n<name>{tool['name']}</name>" |
|
|
| |
| if 'description' in tool: |
| tool_desc += f"\n<description>{tool['description'].strip()}</description>" |
|
|
| |
| tool_desc += '\n<parameters>' |
|
|
| |
| if ('parameters' in tool and isinstance(tool['parameters'], dict) and 'properties' in tool['parameters'] |
| and isinstance(tool['parameters']['properties'], dict)): |
|
|
| for param_name, param_fields in tool['parameters']['properties'].items(): |
| tool_desc += '\n<parameter>' |
| tool_desc += f'\n<name>{param_name}</name>' |
|
|
| if 'type' in param_fields: |
| tool_desc += f"\n<type>{str(param_fields['type'])}</type>" |
|
|
| if 'description' in param_fields: |
| tool_desc += f"\n<description>{param_fields['description'].strip()}</description>" |
|
|
| |
| handled_param_keys = ['name', 'type', 'description'] |
| tool_desc += render_extra_keys(param_fields, handled_param_keys) |
|
|
| tool_desc += '\n</parameter>' |
| |
| handled_keys = ['type', 'properties'] |
| if 'parameters' in tool: |
| tool_desc += render_extra_keys(tool['parameters'], handled_keys) |
|
|
| tool_desc += '\n</parameters>' |
|
|
| |
| handled_keys = ['type', 'name', 'description', 'parameters'] |
| tool_desc += render_extra_keys(tool, handled_keys) |
|
|
| tool_desc += '\n</function>' |
|
|
| tool_descs.append(tool_desc) |
|
|
| tool_descs.append(TOOL_DESC_SUFFIX) |
| tool_descs = '\n'.join(tool_descs) |
| return tool_descs |
|
|
| def _format_tool_calls(self, tool_call_messages): |
| result_parts = [] |
| for idx, message in enumerate(tool_call_messages): |
| tool_call = self._parse_tool_call(message['content']) |
| result_parts.append(f"<tool_call>\n<function={tool_call['name']}>\n") |
| |
| if 'arguments' in tool_call and tool_call['arguments']: |
| for args_name, args_value in tool_call['arguments'].items(): |
| result_parts.append(f'<parameter={args_name}>\n') |
| |
| if isinstance(args_value, (dict, list)): |
| |
| args_value = json.dumps(args_value, ensure_ascii=False) |
| else: |
| |
| args_value = str(args_value) |
| result_parts.append(f'{args_value}\n</parameter>\n') |
| |
| result_parts.append('</function>\n</tool_call>') |
| |
| if idx != len(tool_call_messages) - 1: |
| result_parts.append('\n') |
| return ''.join(result_parts) |
|
|
| def _get_tool_responses(self, tool_messages): |
| res_tool = [] |
| for tool_message in tool_messages: |
| tool_content = tool_message['content'] |
| res_tool.append(f'<tool_response>\n{tool_content}\n</tool_response>\n') |
| return ''.join(res_tool) |
|
|
|
|
| class Qwen3_5AgentTemplate(Qwen3CoderAgentTemplate): |
|
|
| def _format_tools(self, tools: List[Union[str, dict]], system: Optional[str] = None, user_message=None) -> str: |
| tool_descs = [json.dumps(self.wrap_tool(tool), ensure_ascii=False) for tool in tools] |
| tools_prompt = """# Tools |
| |
| You have access to the following functions:\n\n<tools> |
| """ + '\n'.join(tool_descs) + f'\n{TOOL_DESC_SUFFIX}' |
| if system: |
| tools_prompt += f'\n\n{system}' |
| return tools_prompt |
|
|
| def _get_tool_responses(self, tool_messages): |
| res_tool = [] |
| for tool_message in tool_messages: |
| tool_content = tool_message['content'] |
| res_tool.append(f'<tool_response>\n{tool_content}\n</tool_response>') |
| return '\n'.join(res_tool) |
|
|