Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

template.py 3.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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. cpnts = set(
  35. [
  36. para["component_id"].split("@")[0]
  37. for para in self._param.parameters
  38. if para.get("component_id")
  39. and para["component_id"].lower().find("answer") < 0
  40. and para["component_id"].lower().find("begin") < 0
  41. ]
  42. )
  43. return list(cpnts)
  44. def _run(self, history, **kwargs):
  45. content = self._param.content
  46. self._param.inputs = []
  47. for para in self._param.parameters:
  48. if not para.get("component_id"):
  49. continue
  50. component_id = para["component_id"].split("@")[0]
  51. if para["component_id"].lower().find("@") >= 0:
  52. cpn_id, key = para["component_id"].split("@")
  53. for p in self._canvas.get_component(cpn_id)["obj"]._param.query:
  54. if p["key"] == key:
  55. value = p.get("value", "")
  56. self.make_kwargs(para, kwargs, value)
  57. break
  58. else:
  59. assert False, f"Can't find parameter '{key}' for {cpn_id}"
  60. continue
  61. cpn = self._canvas.get_component(component_id)["obj"]
  62. if cpn.component_name.lower() == "answer":
  63. hist = self._canvas.get_history(1)
  64. if hist:
  65. hist = hist[0]["content"]
  66. else:
  67. hist = ""
  68. self.make_kwargs(para, kwargs, hist)
  69. continue
  70. _, out = cpn.output(allow_partial=False)
  71. result = ""
  72. if "content" in out.columns:
  73. result = "\n".join(
  74. [o if isinstance(o, str) else str(o) for o in out["content"]]
  75. )
  76. self.make_kwargs(para, kwargs, result)
  77. template = Jinja2Template(content)
  78. try:
  79. content = template.render(kwargs)
  80. except Exception:
  81. pass
  82. for n, v in kwargs.items():
  83. try:
  84. v = json.dumps(v, ensure_ascii=False)
  85. except Exception:
  86. pass
  87. content = re.sub(
  88. r"\{%s\}" % re.escape(n), v, content
  89. )
  90. content = re.sub(
  91. r"(\\\"|\")", "", content
  92. )
  93. content = re.sub(
  94. r"(#+)", r" \1 ", content
  95. )
  96. return Template.be_output(content)
  97. def make_kwargs(self, para, kwargs, value):
  98. self._param.inputs.append(
  99. {"component_id": para["component_id"], "content": value}
  100. )
  101. try:
  102. value = json.loads(value)
  103. except Exception:
  104. pass
  105. kwargs[para["key"]] = value