builtin_tool.py 5.0 KB

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