builtin_tool.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. from typing import Optional
  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. return ModelInvocationUtils.invoke(
  29. user_id=user_id,
  30. tenant_id=self.runtime.tenant_id,
  31. tool_type="builtin",
  32. tool_name=self.identity.name,
  33. prompt_messages=prompt_messages,
  34. )
  35. def tool_provider_type(self) -> ToolProviderType:
  36. return ToolProviderType.BUILT_IN
  37. def get_max_tokens(self) -> int:
  38. """
  39. get max tokens
  40. :param model_config: the model config
  41. :return: the max tokens
  42. """
  43. return ModelInvocationUtils.get_max_llm_context_tokens(
  44. tenant_id=self.runtime.tenant_id,
  45. )
  46. def get_prompt_tokens(self, prompt_messages: list[PromptMessage]) -> int:
  47. """
  48. get prompt tokens
  49. :param prompt_messages: the prompt messages
  50. :return: the tokens
  51. """
  52. return ModelInvocationUtils.calculate_tokens(tenant_id=self.runtime.tenant_id, prompt_messages=prompt_messages)
  53. def summary(self, user_id: str, content: str) -> str:
  54. max_tokens = self.get_max_tokens()
  55. if self.get_prompt_tokens(prompt_messages=[UserPromptMessage(content=content)]) < max_tokens * 0.6:
  56. return content
  57. def get_prompt_tokens(content: str) -> int:
  58. return self.get_prompt_tokens(
  59. prompt_messages=[SystemPromptMessage(content=_SUMMARY_PROMPT), UserPromptMessage(content=content)]
  60. )
  61. def summarize(content: str) -> str:
  62. summary = self.invoke_model(
  63. user_id=user_id,
  64. prompt_messages=[SystemPromptMessage(content=_SUMMARY_PROMPT), UserPromptMessage(content=content)],
  65. stop=[],
  66. )
  67. return summary.message.content
  68. lines = content.split("\n")
  69. new_lines = []
  70. # split long line into multiple lines
  71. for i in range(len(lines)):
  72. line = lines[i]
  73. if not line.strip():
  74. continue
  75. if len(line) < max_tokens * 0.5:
  76. new_lines.append(line)
  77. elif get_prompt_tokens(line) > max_tokens * 0.7:
  78. while get_prompt_tokens(line) > max_tokens * 0.7:
  79. new_lines.append(line[: int(max_tokens * 0.5)])
  80. line = line[int(max_tokens * 0.5) :]
  81. new_lines.append(line)
  82. else:
  83. new_lines.append(line)
  84. # merge lines into messages with max tokens
  85. messages: list[str] = []
  86. for i in new_lines:
  87. if len(messages) == 0:
  88. messages.append(i)
  89. else:
  90. if len(messages[-1]) + len(i) < max_tokens * 0.5:
  91. messages[-1] += i
  92. if get_prompt_tokens(messages[-1] + i) > max_tokens * 0.7:
  93. messages.append(i)
  94. else:
  95. messages[-1] += i
  96. summaries = []
  97. for i in range(len(messages)):
  98. message = messages[i]
  99. summary = summarize(message)
  100. summaries.append(summary)
  101. result = "\n".join(summaries)
  102. if self.get_prompt_tokens(prompt_messages=[UserPromptMessage(content=result)]) > max_tokens * 0.7:
  103. return self.summary(user_id=user_id, content=result)
  104. return result
  105. def get_url(self, url: str, user_agent: Optional[str] = None) -> str:
  106. """
  107. get url
  108. """
  109. return get_url(url, user_agent=user_agent)