WANGRUI-ZB wangrui Yingfeng Kevin Hu commited on
Commit
0e469cf
·
1 Parent(s): 446c54c

Template conversion adds Jinjia2 syntax support (#4545)

Browse files

### What problem does this PR solve?

Template conversion adds Jinjia2 syntax support

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

---------

Co-authored-by: wangrui <[email protected]>
Co-authored-by: Yingfeng <[email protected]>
Co-authored-by: Kevin Hu <[email protected]>

agent/component/template.py CHANGED
@@ -13,8 +13,10 @@
13
  # See the License for the specific language governing permissions and
14
  # limitations under the License.
15
  #
 
16
  import re
17
  from agent.component.base import ComponentBase, ComponentParamBase
 
18
 
19
 
20
  class TemplateParam(ComponentParamBase):
@@ -36,10 +38,15 @@ class Template(ComponentBase):
36
  component_name = "Template"
37
 
38
  def get_dependent_components(self):
39
- cpnts = set([para["component_id"].split("@")[0] for para in self._param.parameters \
40
- if para.get("component_id") \
41
- and para["component_id"].lower().find("answer") < 0 \
42
- and para["component_id"].lower().find("begin") < 0])
 
 
 
 
 
43
  return list(cpnts)
44
 
45
  def _run(self, history, **kwargs):
@@ -54,9 +61,8 @@ class Template(ComponentBase):
54
  cpn_id, key = para["component_id"].split("@")
55
  for p in self._canvas.get_component(cpn_id)["obj"]._param.query:
56
  if p["key"] == key:
57
- kwargs[para["key"]] = p.get("value", "")
58
- self._param.inputs.append(
59
- {"component_id": para["component_id"], "content": kwargs[para["key"]]})
60
  break
61
  else:
62
  assert False, f"Can't find parameter '{key}' for {cpn_id}"
@@ -69,18 +75,49 @@ class Template(ComponentBase):
69
  hist = hist[0]["content"]
70
  else:
71
  hist = ""
72
- kwargs[para["key"]] = hist
73
  continue
74
 
75
  _, out = cpn.output(allow_partial=False)
76
- if "content" not in out.columns:
77
- kwargs[para["key"]] = ""
78
- else:
79
- kwargs[para["key"]] = " - "+"\n - ".join([o if isinstance(o, str) else str(o) for o in out["content"]])
80
- self._param.inputs.append({"component_id": para["component_id"], "content": kwargs[para["key"]]})
 
 
 
 
 
 
 
 
 
 
81
 
82
  for n, v in kwargs.items():
83
- content = re.sub(r"\{%s\}" % re.escape(n), str(v).replace("\\", " "), content)
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
  return Template.be_output(content)
86
 
 
 
 
 
 
 
 
 
 
 
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
 
21
 
22
  class TemplateParam(ComponentParamBase):
 
38
  component_name = "Template"
39
 
40
  def get_dependent_components(self):
41
+ cpnts = set(
42
+ [
43
+ para["component_id"].split("@")[0]
44
+ for para in self._param.parameters
45
+ if para.get("component_id")
46
+ and para["component_id"].lower().find("answer") < 0
47
+ and para["component_id"].lower().find("begin") < 0
48
+ ]
49
+ )
50
  return list(cpnts)
51
 
52
  def _run(self, history, **kwargs):
 
61
  cpn_id, key = para["component_id"].split("@")
62
  for p in self._canvas.get_component(cpn_id)["obj"]._param.query:
63
  if p["key"] == key:
64
+ value = p.get("value", "")
65
+ self.make_kwargs(para, kwargs, value)
 
66
  break
67
  else:
68
  assert False, f"Can't find parameter '{key}' for {cpn_id}"
 
75
  hist = hist[0]["content"]
76
  else:
77
  hist = ""
78
+ self.make_kwargs(para, kwargs, hist)
79
  continue
80
 
81
  _, out = cpn.output(allow_partial=False)
82
+
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
+
89
+ self.make_kwargs(para, kwargs, result)
90
+
91
+ template = Jinja2Template(content)
92
+
93
+ try:
94
+ content = template.render(kwargs)
95
+ except Exception:
96
+ pass
97
 
98
  for n, v in kwargs.items():
99
+ try:
100
+ v = json.dumps(v, ensure_ascii=False)
101
+ except Exception:
102
+ pass
103
+ content = re.sub(
104
+ r"\{%s\}" % re.escape(n), v, content
105
+ )
106
+ content = re.sub(
107
+ r"(\\\"|\")", "", content
108
+ )
109
+ content = re.sub(
110
+ r"(#+)", r" \1 ", content
111
+ )
112
 
113
  return Template.be_output(content)
114
 
115
+ def make_kwargs(self, para, kwargs, value):
116
+ self._param.inputs.append(
117
+ {"component_id": para["component_id"], "content": value}
118
+ )
119
+ try:
120
+ value = json.loads(value)
121
+ except Exception:
122
+ pass
123
+ kwargs[para["key"]] = value
web/src/locales/en.ts CHANGED
@@ -1123,7 +1123,7 @@ This procedure will improve precision of retrieval by adding more information to
1123
  testRun: 'Test Run',
1124
  template: 'Template',
1125
  templateDescription:
1126
- 'A component that formats user inputs or the outputs of other components.',
1127
  emailComponent: 'Email',
1128
  emailDescription: 'Send an email to a specified address.',
1129
  smtpServer: 'SMTP Server',
 
1123
  testRun: 'Test Run',
1124
  template: 'Template',
1125
  templateDescription:
1126
+ 'A component that formats the output of other components.1. Supports Jinja2 templates, will first convert the input to an object and then render the template, 2. Simultaneously retains the original method of using {parameter} string replacement',
1127
  emailComponent: 'Email',
1128
  emailDescription: 'Send an email to a specified address.',
1129
  smtpServer: 'SMTP Server',
web/src/locales/ja.ts CHANGED
@@ -1049,7 +1049,7 @@ export default {
1049
  testRun: 'テスト実行',
1050
  template: 'テンプレート',
1051
  templateDescription:
1052
- 'このコンポーネントは、さまざまなコンポーネントの出力を組版するために使用されます。',
1053
  emailComponent: 'メール',
1054
  emailDescription: '指定されたアドレスにメールを送信',
1055
  smtpServer: 'SMTPサーバー',
 
1049
  testRun: 'テスト実行',
1050
  template: 'テンプレート',
1051
  templateDescription:
1052
+ 'このコンポーネントは、さまざまなコンポーネントの出力を組版するために使用されます。1. Jinja2テンプレートをサポートし、最初に入力をオブジェクトに変換してからテンプレートをレンダリングします。2. {parameter}文字列置換を使用する元の方法も同時に保持します',
1053
  emailComponent: 'メール',
1054
  emailDescription: '指定されたアドレスにメールを送信',
1055
  smtpServer: 'SMTPサーバー',
web/src/locales/vi.ts CHANGED
@@ -1073,7 +1073,7 @@ export default {
1073
  pasteFileLink: 'Dán liên kết tệp',
1074
  testRun: 'Chạy thử nghiệm',
1075
  template: 'Mẫu',
1076
- templateDescription: `Thành phần này được sử dụng để sắp chữ đầu ra của nhiều thành phần khác nhau.`,
1077
  arXivTip: `Thành phần này được sử dụng để lấy kết quả tìm kiếm từ https://arxiv.org/. Thông thường, nó hoạt động như một phần bổ sung cho cơ sở tri thức. Top N chỉ định số lượng kết quả tìm kiếm bạn cần điều chỉnh.`,
1078
  googleTip: `Thành phần này được sử dụng để lấy kết quả tìm kiếm từ https://www.google.com/. Thông thường, nó hoạt động như một phần bổ sung cho cơ sở tri thức. Top N và khóa API SerpApi chỉ định số lượng kết quả tìm kiếm bạn cần điều chỉnh.`,
1079
  bingTip: `Thành phần này được sử dụng để lấy kết quả tìm kiếm từ https://www.bing.com/. Thông thường, nó hoạt động như một phần bổ sung cho cơ sở tri thức. Top N và khóa đăng ký Bing chỉ định số lượng kết quả tìm kiếm bạn cần điều chỉnh.`,
 
1073
  pasteFileLink: 'Dán liên kết tệp',
1074
  testRun: 'Chạy thử nghiệm',
1075
  template: 'Mẫu',
1076
+ templateDescription: `Thành phần này được sử dụng để sắp chữ đầu ra của nhiều thành phần khác nhau.1. Hỗ trợ mẫu Jinja2, trước tiên chuyển đầu vào thành đối tượng và sau đó kết xuất mẫu. 2. Phương pháp ban đầu sử dụng thay thế chuỗi {parameter} cũng được giữ lại đồng thời`,
1077
  arXivTip: `Thành phần này được sử dụng để lấy kết quả tìm kiếm từ https://arxiv.org/. Thông thường, nó hoạt động như một phần bổ sung cho cơ sở tri thức. Top N chỉ định số lượng kết quả tìm kiếm bạn cần điều chỉnh.`,
1078
  googleTip: `Thành phần này được sử dụng để lấy kết quả tìm kiếm từ https://www.google.com/. Thông thường, nó hoạt động như một phần bổ sung cho cơ sở tri thức. Top N và khóa API SerpApi chỉ định số lượng kết quả tìm kiếm bạn cần điều chỉnh.`,
1079
  bingTip: `Thành phần này được sử dụng để lấy kết quả tìm kiếm từ https://www.bing.com/. Thông thường, nó hoạt động như một phần bổ sung cho cơ sở tri thức. Top N và khóa đăng ký Bing chỉ định số lượng kết quả tìm kiếm bạn cần điều chỉnh.`,
web/src/locales/zh-traditional.ts CHANGED
@@ -1087,7 +1087,7 @@ export default {
1087
  pasteFileLink: '貼上文件連結',
1088
  testRun: '試運行',
1089
  template: '模板轉換',
1090
- templateDescription: '此元件用於排版各種元件的輸出。 ',
1091
  jsonUploadTypeErrorMessage: '請上傳json檔',
1092
  jsonUploadContentErrorMessage: 'json 檔案錯誤',
1093
  iterationDescription: `此元件首先透過「分隔符號」將輸入拆分為陣列。
 
1087
  pasteFileLink: '貼上文件連結',
1088
  testRun: '試運行',
1089
  template: '模板轉換',
1090
+ templateDescription: '此元件用於排版各種元件的輸出。1、支持Jinja2模板,會先將輸入轉為對象後進行模板渲染2、同時保留原使用{參數}字符串替換的方式',
1091
  jsonUploadTypeErrorMessage: '請上傳json檔',
1092
  jsonUploadContentErrorMessage: 'json 檔案錯誤',
1093
  iterationDescription: `此元件首先透過「分隔符號」將輸入拆分為陣列。
web/src/locales/zh.ts CHANGED
@@ -1107,7 +1107,7 @@ General:实体和关系提取提示来自 GitHub - microsoft/graphrag:基于
1107
  pasteFileLink: '粘贴文件链接',
1108
  testRun: '试运行',
1109
  template: '模板转换',
1110
- templateDescription: '该组件用于排版各种组件的输出。',
1111
  emailComponent: '邮件',
1112
  emailDescription: '发送邮件到指定邮箱',
1113
  smtpServer: 'SMTP服务器',
 
1107
  pasteFileLink: '粘贴文件链接',
1108
  testRun: '试运行',
1109
  template: '模板转换',
1110
+ templateDescription: '该组件用于排版各种组件的输出。1、支持Jinja2模板,会先将输入转为对象后进行模版渲染2、同时保留原使用{参数}字符串替换的方式',
1111
  emailComponent: '邮件',
1112
  emailDescription: '发送邮件到指定邮箱',
1113
  smtpServer: 'SMTP服务器',