tool_call_util.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """
  2. tool calls 常用转换方法
  3. 从 llm 接口获取的 tool calls 为 ChatCompletionMessageToolCall 形式,类型为 function
  4. 可通过 json() 获取 json 形式,格式如下:
  5. {
  6. "id": "tool_call_0",
  7. "function": {
  8. "name": "file_search",
  9. "arguments": "{\"file_keys\": [\"file_0\", \"file_1\"], \"query\": \"query\"}"
  10. }
  11. }
  12. 查询结果将放入 ["function"]["output"] 中
  13. """
  14. from typing import List
  15. import json
  16. from openai.types.chat.chat_completion_message import ChatCompletionMessageToolCall
  17. from app.core.tools.base_tool import BaseTool
  18. from app.core.tools.external_function_tool import ExternalFunctionTool
  19. def tool_call_recognize(tool_call: ChatCompletionMessageToolCall, tools: List[BaseTool]) -> (BaseTool, dict):
  20. """
  21. 对齐 tool call 和 tool,仅针对内部 tool call
  22. """
  23. tool_name = tool_call.function.name
  24. [tool] = [tool for tool in tools if tool.name == tool_name]
  25. if isinstance(tool, ExternalFunctionTool):
  26. tool = None
  27. return (tool, json.loads(tool_call.json()))
  28. def internal_tool_call_invoke(tool: BaseTool, tool_call_dict: dict) -> dict:
  29. """
  30. internal tool call 执行,结果写入 output
  31. """
  32. args = json.loads(tool_call_dict["function"]["arguments"])
  33. output = tool.run(**args)
  34. tool_call_dict["function"]["output"] = json.dumps(output, ensure_ascii=False)
  35. return tool_call_dict
  36. def tool_call_request(tool_call_dict: dict) -> dict:
  37. """
  38. tool call 结果需返回原始请求 & 结果
  39. 库中未存储 tool_call 原始请求,需进行重新组装
  40. """
  41. return {
  42. "id": tool_call_dict["id"],
  43. "type": "function",
  44. "function": {"name": tool_call_dict["function"]["name"], "arguments": tool_call_dict["function"]["arguments"]},
  45. }
  46. def tool_call_id(tool_call_dict: dict) -> str:
  47. """
  48. tool call id
  49. """
  50. return tool_call_dict["id"]
  51. def tool_call_output(tool_call_dict: dict) -> str:
  52. """
  53. tool call output
  54. """
  55. return tool_call_dict["function"]["output"]