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.

template.py 4.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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 re
  18. from agent.component.base import ComponentBase, ComponentParamBase
  19. from jinja2 import Template as Jinja2Template
  20. class TemplateParam(ComponentParamBase):
  21. """
  22. Define the Generate component parameters.
  23. """
  24. def __init__(self):
  25. super().__init__()
  26. self.content = ""
  27. self.parameters = []
  28. def check(self):
  29. self.check_empty(self.content, "[Template] Content")
  30. return True
  31. class Template(ComponentBase):
  32. component_name = "Template"
  33. def get_dependent_components(self):
  34. inputs = self.get_input_elements()
  35. cpnts = set([i["key"] for i in inputs if i["key"].lower().find("answer") < 0 and i["key"].lower().find("begin") < 0])
  36. return list(cpnts)
  37. def get_input_elements(self):
  38. key_set = set([])
  39. res = []
  40. for r in re.finditer(r"\{([a-z]+[:@][a-z0-9_-]+)\}", self._param.content, flags=re.IGNORECASE):
  41. cpn_id = r.group(1)
  42. if cpn_id in key_set:
  43. continue
  44. if cpn_id.lower().find("begin@") == 0:
  45. cpn_id, key = cpn_id.split("@")
  46. for p in self._canvas.get_component(cpn_id)["obj"]._param.query:
  47. if p["key"] != key:
  48. continue
  49. res.append({"key": r.group(1), "name": p["name"]})
  50. key_set.add(r.group(1))
  51. continue
  52. cpn_nm = self._canvas.get_component_name(cpn_id)
  53. if not cpn_nm:
  54. continue
  55. res.append({"key": cpn_id, "name": cpn_nm})
  56. key_set.add(cpn_id)
  57. return res
  58. def _run(self, history, **kwargs):
  59. content = self._param.content
  60. self._param.inputs = []
  61. for para in self.get_input_elements():
  62. if para["key"].lower().find("begin@") == 0:
  63. cpn_id, key = para["key"].split("@")
  64. for p in self._canvas.get_component(cpn_id)["obj"]._param.query:
  65. if p["key"] == key:
  66. value = p.get("value", "")
  67. self.make_kwargs(para, kwargs, value)
  68. break
  69. else:
  70. assert False, f"Can't find parameter '{key}' for {cpn_id}"
  71. continue
  72. component_id = para["key"]
  73. cpn = self._canvas.get_component(component_id)["obj"]
  74. if cpn.component_name.lower() == "answer":
  75. hist = self._canvas.get_history(1)
  76. if hist:
  77. hist = hist[0]["content"]
  78. else:
  79. hist = ""
  80. self.make_kwargs(para, kwargs, hist)
  81. continue
  82. _, out = cpn.output(allow_partial=False)
  83. result = ""
  84. if "content" in out.columns:
  85. result = "\n".join(
  86. [o if isinstance(o, str) else str(o) for o in out["content"]]
  87. )
  88. self.make_kwargs(para, kwargs, result)
  89. template = Jinja2Template(content)
  90. try:
  91. content = template.render(kwargs)
  92. except Exception:
  93. pass
  94. for n, v in kwargs.items():
  95. if not isinstance(v, str):
  96. try:
  97. v = json.dumps(v, ensure_ascii=False)
  98. except Exception:
  99. pass
  100. content = re.sub(
  101. r"\{%s\}" % re.escape(n), v, content
  102. )
  103. content = re.sub(
  104. r"(#+)", r" \1 ", content
  105. )
  106. return Template.be_output(content)
  107. def make_kwargs(self, para, kwargs, value):
  108. self._param.inputs.append(
  109. {"component_id": para["key"], "content": value}
  110. )
  111. try:
  112. value = json.loads(value)
  113. except Exception:
  114. pass
  115. kwargs[para["key"]] = value