You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import json
  17. import os
  18. import random
  19. import re
  20. from functools import partial
  21. from typing import Any
  22. from agent.component.base import ComponentBase, ComponentParamBase
  23. from jinja2 import Template as Jinja2Template
  24. from api.utils.api_utils import timeout
  25. class MessageParam(ComponentParamBase):
  26. """
  27. Define the Message component parameters.
  28. """
  29. def __init__(self):
  30. super().__init__()
  31. self.content = []
  32. self.stream = True
  33. self.outputs = {
  34. "content": {
  35. "type": "str"
  36. }
  37. }
  38. def check(self):
  39. self.check_empty(self.content, "[Message] Content")
  40. self.check_boolean(self.stream, "[Message] stream")
  41. return True
  42. class Message(ComponentBase):
  43. component_name = "Message"
  44. def get_kwargs(self, script:str, kwargs:dict = {}, delimeter:str=None) -> tuple[str, dict[str, str | list | Any]]:
  45. for k,v in self.get_input_elements_from_text(script).items():
  46. if k in kwargs:
  47. continue
  48. v = v["value"]
  49. if not v:
  50. v = ""
  51. ans = ""
  52. if isinstance(v, partial):
  53. for t in v():
  54. ans += t
  55. elif isinstance(v, list) and delimeter:
  56. ans = delimeter.join([str(vv) for vv in v])
  57. elif not isinstance(v, str):
  58. try:
  59. ans = json.dumps(v, ensure_ascii=False)
  60. except Exception:
  61. pass
  62. else:
  63. ans = v
  64. if not ans:
  65. ans = ""
  66. kwargs[k] = ans
  67. self.set_input_value(k, ans)
  68. _kwargs = {}
  69. for n, v in kwargs.items():
  70. _n = re.sub("[@:.]", "_", n)
  71. script = re.sub(r"\{%s\}" % re.escape(n), _n, script)
  72. _kwargs[_n] = v
  73. return script, _kwargs
  74. def _stream(self, rand_cnt:str):
  75. s = 0
  76. all_content = ""
  77. cache = {}
  78. for r in re.finditer(self.variable_ref_patt, rand_cnt, flags=re.DOTALL):
  79. all_content += rand_cnt[s: r.start()]
  80. yield rand_cnt[s: r.start()]
  81. s = r.end()
  82. exp = r.group(1)
  83. if exp in cache:
  84. yield cache[exp]
  85. all_content += cache[exp]
  86. continue
  87. v = self._canvas.get_variable_value(exp)
  88. if not v:
  89. v = ""
  90. if isinstance(v, partial):
  91. cnt = ""
  92. for t in v():
  93. all_content += t
  94. cnt += t
  95. yield t
  96. continue
  97. elif not isinstance(v, str):
  98. try:
  99. v = json.dumps(v, ensure_ascii=False, indent=2)
  100. except Exception:
  101. v = str(v)
  102. yield v
  103. all_content += v
  104. cache[exp] = v
  105. if s < len(rand_cnt):
  106. all_content += rand_cnt[s: ]
  107. yield rand_cnt[s: ]
  108. self.set_output("content", all_content)
  109. def _is_jinjia2(self, content:str) -> bool:
  110. patt = [
  111. r"\{%.*%\}", "{{", "}}"
  112. ]
  113. return any([re.search(p, content) for p in patt])
  114. @timeout(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10*60))
  115. def _invoke(self, **kwargs):
  116. rand_cnt = random.choice(self._param.content)
  117. if self._param.stream and not self._is_jinjia2(rand_cnt):
  118. self.set_output("content", partial(self._stream, rand_cnt))
  119. return
  120. rand_cnt, kwargs = self.get_kwargs(rand_cnt, kwargs)
  121. template = Jinja2Template(rand_cnt)
  122. try:
  123. content = template.render(kwargs)
  124. except Exception:
  125. pass
  126. for n, v in kwargs.items():
  127. content = re.sub(n, v, content)
  128. self.set_output("content", content)
  129. def thoughts(self) -> str:
  130. return ""