|
| 1 | +import re |
| 2 | +from typing import Any, Dict, List, Tuple, Union |
| 3 | +import json |
| 4 | +import uuid |
| 5 | + |
| 6 | +# default |
| 7 | +TOOL_SYSTEM_PROMPT = """Answer the following questions as best you can. You have access to the following tools: |
| 8 | +
|
| 9 | +{tool_text} |
| 10 | +
|
| 11 | +Use the following format: |
| 12 | +
|
| 13 | +Question: the input question you must answer |
| 14 | +Thought: you should always think about what to do |
| 15 | +Action: the action to take, should be one of [{tool_names}] |
| 16 | +Action Input: the input to the action |
| 17 | +Observation: the result of the action |
| 18 | +... (this Thought/Action/Action Input/Observation can be repeated zero or more times) |
| 19 | +Thought: I now know the final answer |
| 20 | +Final Answer: the final answer to the original input question |
| 21 | +
|
| 22 | +Begin! |
| 23 | +
|
| 24 | +Question:""" |
| 25 | + |
| 26 | + |
| 27 | +def qwen_tool_formatter(tools: List[Dict[str, Any]]) -> str: |
| 28 | + tool_names = [] |
| 29 | + param_text_list = [] |
| 30 | + for tool in tools: |
| 31 | + tool = tool["function"] |
| 32 | + param_text = """{tool_name}: Call this tool to interact with the {tool_name} API. What is the {tool_name} API useful for? {description} Parameters: {parameters} Format the arguments as a JSON object.""" |
| 33 | + parameters = [] |
| 34 | + for name, param in tool["parameters"]["properties"].items(): |
| 35 | + parameters.append( |
| 36 | + { |
| 37 | + "name": name, |
| 38 | + "description": param.get("description", ""), |
| 39 | + "required": ( |
| 40 | + True if name in tool["parameters"]["required"] else False |
| 41 | + ), |
| 42 | + "schema": {"type": param["type"]}, |
| 43 | + } |
| 44 | + ) |
| 45 | + param_text_str = param_text.format( |
| 46 | + tool_name=tool["name"], |
| 47 | + description=tool["description"], |
| 48 | + parameters=parameters, |
| 49 | + ) |
| 50 | + param_text_list.append(param_text_str) |
| 51 | + |
| 52 | + tool_names.append(tool["name"]) |
| 53 | + |
| 54 | + tool_text = "\n\n".join(param_text_list).strip() |
| 55 | + return TOOL_SYSTEM_PROMPT.format( |
| 56 | + tool_text=tool_text, |
| 57 | + tool_names=", ".join(tool_names), |
| 58 | + ) |
| 59 | + |
| 60 | + |
| 61 | +def qwen_tool_extractor(content: str) -> Union[str, List[Tuple[str, str]]]: |
| 62 | + |
| 63 | + i = content.rfind("Action:") |
| 64 | + j = content.rfind("Action Input:") |
| 65 | + tool_name = content[i + len("Action:") : j].strip().strip(".") |
| 66 | + tool_input = content[j + len("Action Input:") :].strip() |
| 67 | + try: |
| 68 | + json.loads(tool_input) |
| 69 | + except json.JSONDecodeError: |
| 70 | + return content |
| 71 | + tool_calls = [] |
| 72 | + tool_call = { |
| 73 | + "id": "call_{}".format(uuid.uuid4().hex), |
| 74 | + "function": {"name": tool_name, "arguments": tool_input}, |
| 75 | + } |
| 76 | + tool_calls.append(tool_call) |
| 77 | + |
| 78 | + return tool_calls |
| 79 | + |
| 80 | + |
| 81 | +if __name__ == "__main__": |
| 82 | + import json |
| 83 | + |
| 84 | + tools_str = """[{'type': 'function', 'function': {'name': 'track', 'description': '追踪指定股票的实时价格', 'parameters': {'type': 'object', 'properties': {'symbol': {'description': '需要追踪的股票代码', 'type': 'integer'}}, 'required': ['symbol']}}}, {'type': 'function', 'function': {'name': 'text-to-speech', 'description': '将文本转换为语音', 'parameters': {'type': 'object', 'properties': {'text': {'description': '需要转换成语音的文本', 'type': 'string'}, 'voice': {'description': '要使用的语音类型(男声、女声等', 'default': '男声', 'type': 'string'}, 'speed': {'description': '语音的速度(快、中等、慢等', 'default': '中等', 'type': 'string'}}, 'required': ['text']}}}]""" |
| 85 | + tools_str = tools_str.replace("'", '"') |
| 86 | + tools = json.loads(tools_str) |
| 87 | + res = qwen_tool_formatter(tools=tools) |
| 88 | + print(res) |
| 89 | + out = 'Action: multiply.\nAction Input: {"first_int": 8, "second_int": 9}\n' |
| 90 | + r = qwen_tool_extractor(out) |
| 91 | + print("\n\n") |
| 92 | + print(r) |
0 commit comments