tool.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. from core.model_runtime.entities.llm_entities import LLMResult
  2. from core.model_runtime.entities.message_entities import PromptMessage, SystemPromptMessage, UserPromptMessage
  3. from core.tools.__base.tool import Tool
  4. from core.tools.__base.tool_runtime import ToolRuntime
  5. from core.tools.entities.tool_entities import ToolProviderType
  6. from core.tools.utils.model_invocation_utils import ModelInvocationUtils
  7. _SUMMARY_PROMPT = """You are a professional language researcher, you are interested in the language
  8. and you can quickly aimed at the main point of an webpage and reproduce it in your own words but
  9. retain the original meaning and keep the key points.
  10. however, the text you got is too long, what you got is possible a part of the text.
  11. Please summarize the text you got.
  12. """
  13. class BuiltinTool(Tool):
  14. """
  15. Builtin tool
  16. :param meta: the meta data of a tool call processing
  17. """
  18. provider: str
  19. def __init__(self, provider: str, **kwargs):
  20. super().__init__(**kwargs)
  21. self.provider = provider
  22. def fork_tool_runtime(self, runtime: ToolRuntime) -> "BuiltinTool":
  23. """
  24. fork a new tool with meta data
  25. :param meta: the meta data of a tool call processing, tenant_id is required
  26. :return: the new tool
  27. """
  28. return self.__class__(
  29. entity=self.entity.model_copy(),
  30. runtime=runtime,
  31. provider=self.provider,
  32. )
  33. def invoke_model(self, user_id: str, prompt_messages: list[PromptMessage], stop: list[str]) -> LLMResult:
  34. """
  35. invoke model
  36. :param model_config: the model config
  37. :param prompt_messages: the prompt messages
  38. :param stop: the stop words
  39. :return: the model result
  40. """
  41. # invoke model
  42. return ModelInvocationUtils.invoke(
  43. user_id=user_id,
  44. tenant_id=self.runtime.tenant_id or "",
  45. tool_type="builtin",
  46. tool_name=self.entity.identity.name,
  47. prompt_messages=prompt_messages,
  48. )
  49. def tool_provider_type(self) -> ToolProviderType:
  50. return ToolProviderType.BUILT_IN
  51. def get_max_tokens(self) -> int:
  52. """
  53. get max tokens
  54. :param model_config: the model config
  55. :return: the max tokens
  56. """
  57. if self.runtime is None:
  58. raise ValueError("runtime is required")
  59. return ModelInvocationUtils.get_max_llm_context_tokens(
  60. tenant_id=self.runtime.tenant_id or "",
  61. )
  62. def get_prompt_tokens(self, prompt_messages: list[PromptMessage]) -> int:
  63. """
  64. get prompt tokens
  65. :param prompt_messages: the prompt messages
  66. :return: the tokens
  67. """
  68. if self.runtime is None:
  69. raise ValueError("runtime is required")
  70. return ModelInvocationUtils.calculate_tokens(
  71. tenant_id=self.runtime.tenant_id or "", prompt_messages=prompt_messages
  72. )
  73. def summary(self, user_id: str, content: str) -> str:
  74. max_tokens = self.get_max_tokens()
  75. if self.get_prompt_tokens(prompt_messages=[UserPromptMessage(content=content)]) < max_tokens * 0.6:
  76. return content
  77. def get_prompt_tokens(content: str) -> int:
  78. return self.get_prompt_tokens(
  79. prompt_messages=[SystemPromptMessage(content=_SUMMARY_PROMPT), UserPromptMessage(content=content)]
  80. )
  81. def summarize(content: str) -> str:
  82. summary = self.invoke_model(
  83. user_id=user_id,
  84. prompt_messages=[SystemPromptMessage(content=_SUMMARY_PROMPT), UserPromptMessage(content=content)],
  85. stop=[],
  86. )
  87. assert isinstance(summary.message.content, str)
  88. return summary.message.content
  89. lines = content.split("\n")
  90. new_lines = []
  91. # split long line into multiple lines
  92. for i in range(len(lines)):
  93. line = lines[i]
  94. if not line.strip():
  95. continue
  96. if len(line) < max_tokens * 0.5:
  97. new_lines.append(line)
  98. elif get_prompt_tokens(line) > max_tokens * 0.7:
  99. while get_prompt_tokens(line) > max_tokens * 0.7:
  100. new_lines.append(line[: int(max_tokens * 0.5)])
  101. line = line[int(max_tokens * 0.5) :]
  102. new_lines.append(line)
  103. else:
  104. new_lines.append(line)
  105. # merge lines into messages with max tokens
  106. messages: list[str] = []
  107. for j in new_lines:
  108. if len(messages) == 0:
  109. messages.append(j)
  110. else:
  111. if len(messages[-1]) + len(j) < max_tokens * 0.5:
  112. messages[-1] += j
  113. if get_prompt_tokens(messages[-1] + j) > max_tokens * 0.7:
  114. messages.append(j)
  115. else:
  116. messages[-1] += j
  117. summaries = []
  118. for i in range(len(messages)):
  119. message = messages[i]
  120. summary = summarize(message)
  121. summaries.append(summary)
  122. result = "\n".join(summaries)
  123. if self.get_prompt_tokens(prompt_messages=[UserPromptMessage(content=result)]) > max_tokens * 0.7:
  124. return self.summary(user_id=user_id, content=result)
  125. return result