Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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. ans = ""
  50. if isinstance(v, partial):
  51. for t in v():
  52. ans += t
  53. elif isinstance(v, list) and delimeter:
  54. ans = delimeter.join([str(vv) for vv in v])
  55. elif not isinstance(v, str):
  56. try:
  57. ans = json.dumps(v, ensure_ascii=False)
  58. except Exception:
  59. pass
  60. else:
  61. ans = v
  62. if not ans:
  63. ans = ""
  64. kwargs[k] = ans
  65. self.set_input_value(k, ans)
  66. _kwargs = {}
  67. for n, v in kwargs.items():
  68. _n = re.sub("[@:.]", "_", n)
  69. script = re.sub(r"\{%s\}" % re.escape(n), _n, script)
  70. _kwargs[_n] = v
  71. return script, _kwargs
  72. def _stream(self, rand_cnt:str):
  73. s = 0
  74. all_content = ""
  75. cache = {}
  76. for r in re.finditer(self.variable_ref_patt, rand_cnt, flags=re.DOTALL):
  77. all_content += rand_cnt[s: r.start()]
  78. yield rand_cnt[s: r.start()]
  79. s = r.end()
  80. exp = r.group(1)
  81. if exp in cache:
  82. yield cache[exp]
  83. all_content += cache[exp]
  84. continue
  85. v = self._canvas.get_variable_value(exp)
  86. if isinstance(v, partial):
  87. cnt = ""
  88. for t in v():
  89. all_content += t
  90. cnt += t
  91. yield t
  92. continue
  93. elif not isinstance(v, str):
  94. try:
  95. v = json.dumps(v, ensure_ascii=False, indent=2)
  96. except Exception:
  97. v = str(v)
  98. yield v
  99. all_content += v
  100. cache[exp] = v
  101. if s < len(rand_cnt):
  102. all_content += rand_cnt[s: ]
  103. yield rand_cnt[s: ]
  104. self.set_output("content", all_content)
  105. def _is_jinjia2(self, content:str) -> bool:
  106. patt = [
  107. r"\{%.*%\}", "{{", "}}"
  108. ]
  109. return any([re.search(p, content) for p in patt])
  110. @timeout(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10*60))
  111. def _invoke(self, **kwargs):
  112. rand_cnt = random.choice(self._param.content)
  113. if self._param.stream and not self._is_jinjia2(rand_cnt):
  114. self.set_output("content", partial(self._stream, rand_cnt))
  115. return
  116. rand_cnt, kwargs = self.get_kwargs(rand_cnt, kwargs)
  117. template = Jinja2Template(rand_cnt)
  118. try:
  119. content = template.render(kwargs)
  120. except Exception:
  121. pass
  122. for n, v in kwargs.items():
  123. content = re.sub(n, v, content)
  124. self.set_output("content", content)
  125. def thoughts(self) -> str:
  126. return ""