lionagi 0.1.2__py3-none-any.whl → 0.2.0__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (268) hide show
  1. lionagi/__init__.py +60 -5
  2. lionagi/core/__init__.py +0 -25
  3. lionagi/core/_setting/_setting.py +59 -0
  4. lionagi/core/action/__init__.py +14 -0
  5. lionagi/core/action/function_calling.py +136 -0
  6. lionagi/core/action/manual.py +1 -0
  7. lionagi/core/action/node.py +109 -0
  8. lionagi/core/action/tool.py +114 -0
  9. lionagi/core/action/tool_manager.py +356 -0
  10. lionagi/core/agent/base_agent.py +27 -13
  11. lionagi/core/agent/eval/evaluator.py +1 -0
  12. lionagi/core/agent/eval/vote.py +40 -0
  13. lionagi/core/agent/learn/learner.py +59 -0
  14. lionagi/core/agent/plan/unit_template.py +1 -0
  15. lionagi/core/collections/__init__.py +17 -0
  16. lionagi/core/{generic/data_logger.py → collections/_logger.py} +69 -55
  17. lionagi/core/collections/abc/__init__.py +53 -0
  18. lionagi/core/collections/abc/component.py +615 -0
  19. lionagi/core/collections/abc/concepts.py +297 -0
  20. lionagi/core/collections/abc/exceptions.py +150 -0
  21. lionagi/core/collections/abc/util.py +45 -0
  22. lionagi/core/collections/exchange.py +161 -0
  23. lionagi/core/collections/flow.py +426 -0
  24. lionagi/core/collections/model.py +419 -0
  25. lionagi/core/collections/pile.py +913 -0
  26. lionagi/core/collections/progression.py +236 -0
  27. lionagi/core/collections/util.py +64 -0
  28. lionagi/core/director/direct.py +314 -0
  29. lionagi/core/director/director.py +2 -0
  30. lionagi/core/{execute/branch_executor.py → engine/branch_engine.py} +134 -97
  31. lionagi/core/{execute/instruction_map_executor.py → engine/instruction_map_engine.py} +80 -55
  32. lionagi/{experimental/directive/evaluator → core/engine}/script_engine.py +17 -1
  33. lionagi/core/executor/base_executor.py +90 -0
  34. lionagi/core/{execute/structure_executor.py → executor/graph_executor.py} +62 -66
  35. lionagi/core/{execute → executor}/neo4j_executor.py +70 -67
  36. lionagi/core/generic/__init__.py +3 -33
  37. lionagi/core/generic/edge.py +29 -79
  38. lionagi/core/generic/edge_condition.py +16 -0
  39. lionagi/core/generic/graph.py +236 -0
  40. lionagi/core/generic/hyperedge.py +1 -0
  41. lionagi/core/generic/node.py +156 -221
  42. lionagi/core/generic/tree.py +48 -0
  43. lionagi/core/generic/tree_node.py +79 -0
  44. lionagi/core/mail/__init__.py +12 -0
  45. lionagi/core/mail/mail.py +25 -0
  46. lionagi/core/mail/mail_manager.py +139 -58
  47. lionagi/core/mail/package.py +45 -0
  48. lionagi/core/mail/start_mail.py +36 -0
  49. lionagi/core/message/__init__.py +19 -0
  50. lionagi/core/message/action_request.py +133 -0
  51. lionagi/core/message/action_response.py +135 -0
  52. lionagi/core/message/assistant_response.py +95 -0
  53. lionagi/core/message/instruction.py +234 -0
  54. lionagi/core/message/message.py +101 -0
  55. lionagi/core/message/system.py +86 -0
  56. lionagi/core/message/util.py +283 -0
  57. lionagi/core/report/__init__.py +4 -0
  58. lionagi/core/report/base.py +217 -0
  59. lionagi/core/report/form.py +231 -0
  60. lionagi/core/report/report.py +166 -0
  61. lionagi/core/report/util.py +28 -0
  62. lionagi/core/rule/_default.py +16 -0
  63. lionagi/core/rule/action.py +99 -0
  64. lionagi/core/rule/base.py +238 -0
  65. lionagi/core/rule/boolean.py +56 -0
  66. lionagi/core/rule/choice.py +47 -0
  67. lionagi/core/rule/mapping.py +96 -0
  68. lionagi/core/rule/number.py +71 -0
  69. lionagi/core/rule/rulebook.py +109 -0
  70. lionagi/core/rule/string.py +52 -0
  71. lionagi/core/rule/util.py +35 -0
  72. lionagi/core/session/branch.py +431 -0
  73. lionagi/core/session/directive_mixin.py +287 -0
  74. lionagi/core/session/session.py +229 -903
  75. lionagi/core/structure/__init__.py +1 -0
  76. lionagi/core/structure/chain.py +1 -0
  77. lionagi/core/structure/forest.py +1 -0
  78. lionagi/core/structure/graph.py +1 -0
  79. lionagi/core/structure/tree.py +1 -0
  80. lionagi/core/unit/__init__.py +5 -0
  81. lionagi/core/unit/parallel_unit.py +245 -0
  82. lionagi/core/unit/template/action.py +81 -0
  83. lionagi/core/unit/template/base.py +51 -0
  84. lionagi/core/unit/template/plan.py +84 -0
  85. lionagi/core/unit/template/predict.py +109 -0
  86. lionagi/core/unit/template/score.py +124 -0
  87. lionagi/core/unit/template/select.py +104 -0
  88. lionagi/core/unit/unit.py +362 -0
  89. lionagi/core/unit/unit_form.py +305 -0
  90. lionagi/core/unit/unit_mixin.py +1168 -0
  91. lionagi/core/unit/util.py +71 -0
  92. lionagi/core/validator/validator.py +364 -0
  93. lionagi/core/work/work.py +74 -0
  94. lionagi/core/work/work_function.py +92 -0
  95. lionagi/core/work/work_queue.py +81 -0
  96. lionagi/core/work/worker.py +195 -0
  97. lionagi/core/work/worklog.py +124 -0
  98. lionagi/experimental/compressor/base.py +46 -0
  99. lionagi/experimental/compressor/llm_compressor.py +247 -0
  100. lionagi/experimental/compressor/llm_summarizer.py +61 -0
  101. lionagi/experimental/compressor/util.py +70 -0
  102. lionagi/experimental/directive/__init__.py +19 -0
  103. lionagi/experimental/directive/parser/base_parser.py +69 -2
  104. lionagi/experimental/directive/{template_ → template}/base_template.py +17 -1
  105. lionagi/{libs/ln_tokenizer.py → experimental/directive/tokenizer.py} +16 -0
  106. lionagi/experimental/{directive/evaluator → evaluator}/ast_evaluator.py +16 -0
  107. lionagi/experimental/{directive/evaluator → evaluator}/base_evaluator.py +16 -0
  108. lionagi/experimental/knowledge/base.py +10 -0
  109. lionagi/experimental/memory/__init__.py +0 -0
  110. lionagi/experimental/strategies/__init__.py +0 -0
  111. lionagi/experimental/strategies/base.py +1 -0
  112. lionagi/integrations/bridge/langchain_/documents.py +4 -0
  113. lionagi/integrations/bridge/llamaindex_/index.py +30 -0
  114. lionagi/integrations/bridge/llamaindex_/llama_index_bridge.py +6 -0
  115. lionagi/integrations/chunker/chunk.py +161 -24
  116. lionagi/integrations/config/oai_configs.py +34 -3
  117. lionagi/integrations/config/openrouter_configs.py +14 -2
  118. lionagi/integrations/loader/load.py +122 -21
  119. lionagi/integrations/loader/load_util.py +6 -77
  120. lionagi/integrations/provider/_mapping.py +46 -0
  121. lionagi/integrations/provider/litellm.py +2 -1
  122. lionagi/integrations/provider/mlx_service.py +16 -9
  123. lionagi/integrations/provider/oai.py +91 -4
  124. lionagi/integrations/provider/ollama.py +6 -5
  125. lionagi/integrations/provider/openrouter.py +115 -8
  126. lionagi/integrations/provider/services.py +2 -2
  127. lionagi/integrations/provider/transformers.py +18 -22
  128. lionagi/integrations/storage/__init__.py +3 -3
  129. lionagi/integrations/storage/neo4j.py +52 -60
  130. lionagi/integrations/storage/storage_util.py +44 -46
  131. lionagi/integrations/storage/structure_excel.py +43 -26
  132. lionagi/integrations/storage/to_excel.py +11 -4
  133. lionagi/libs/__init__.py +22 -1
  134. lionagi/libs/ln_api.py +75 -20
  135. lionagi/libs/ln_context.py +37 -0
  136. lionagi/libs/ln_convert.py +21 -9
  137. lionagi/libs/ln_func_call.py +69 -28
  138. lionagi/libs/ln_image.py +107 -0
  139. lionagi/libs/ln_nested.py +26 -11
  140. lionagi/libs/ln_parse.py +82 -23
  141. lionagi/libs/ln_queue.py +16 -0
  142. lionagi/libs/ln_tokenize.py +164 -0
  143. lionagi/libs/ln_validate.py +16 -0
  144. lionagi/libs/special_tokens.py +172 -0
  145. lionagi/libs/sys_util.py +95 -24
  146. lionagi/lions/coder/code_form.py +13 -0
  147. lionagi/lions/coder/coder.py +50 -3
  148. lionagi/lions/coder/util.py +30 -25
  149. lionagi/tests/libs/test_func_call.py +23 -21
  150. lionagi/tests/libs/test_nested.py +36 -21
  151. lionagi/tests/libs/test_parse.py +1 -1
  152. lionagi/tests/test_core/collections/__init__.py +0 -0
  153. lionagi/tests/test_core/collections/test_component.py +206 -0
  154. lionagi/tests/test_core/collections/test_exchange.py +138 -0
  155. lionagi/tests/test_core/collections/test_flow.py +145 -0
  156. lionagi/tests/test_core/collections/test_pile.py +171 -0
  157. lionagi/tests/test_core/collections/test_progression.py +129 -0
  158. lionagi/tests/test_core/generic/test_edge.py +67 -0
  159. lionagi/tests/test_core/generic/test_graph.py +96 -0
  160. lionagi/tests/test_core/generic/test_node.py +106 -0
  161. lionagi/tests/test_core/generic/test_tree_node.py +73 -0
  162. lionagi/tests/test_core/test_branch.py +115 -294
  163. lionagi/tests/test_core/test_form.py +46 -0
  164. lionagi/tests/test_core/test_report.py +105 -0
  165. lionagi/tests/test_core/test_validator.py +111 -0
  166. lionagi/version.py +1 -1
  167. lionagi-0.2.0.dist-info/LICENSE +202 -0
  168. lionagi-0.2.0.dist-info/METADATA +272 -0
  169. lionagi-0.2.0.dist-info/RECORD +240 -0
  170. lionagi/core/branch/base.py +0 -653
  171. lionagi/core/branch/branch.py +0 -474
  172. lionagi/core/branch/flow_mixin.py +0 -96
  173. lionagi/core/branch/util.py +0 -323
  174. lionagi/core/direct/__init__.py +0 -19
  175. lionagi/core/direct/cot.py +0 -123
  176. lionagi/core/direct/plan.py +0 -164
  177. lionagi/core/direct/predict.py +0 -166
  178. lionagi/core/direct/react.py +0 -171
  179. lionagi/core/direct/score.py +0 -279
  180. lionagi/core/direct/select.py +0 -170
  181. lionagi/core/direct/sentiment.py +0 -1
  182. lionagi/core/direct/utils.py +0 -110
  183. lionagi/core/direct/vote.py +0 -64
  184. lionagi/core/execute/base_executor.py +0 -47
  185. lionagi/core/flow/baseflow.py +0 -23
  186. lionagi/core/flow/monoflow/ReAct.py +0 -240
  187. lionagi/core/flow/monoflow/__init__.py +0 -9
  188. lionagi/core/flow/monoflow/chat.py +0 -95
  189. lionagi/core/flow/monoflow/chat_mixin.py +0 -253
  190. lionagi/core/flow/monoflow/followup.py +0 -215
  191. lionagi/core/flow/polyflow/__init__.py +0 -1
  192. lionagi/core/flow/polyflow/chat.py +0 -251
  193. lionagi/core/form/action_form.py +0 -26
  194. lionagi/core/form/field_validator.py +0 -287
  195. lionagi/core/form/form.py +0 -302
  196. lionagi/core/form/mixin.py +0 -214
  197. lionagi/core/form/scored_form.py +0 -13
  198. lionagi/core/generic/action.py +0 -26
  199. lionagi/core/generic/component.py +0 -532
  200. lionagi/core/generic/condition.py +0 -46
  201. lionagi/core/generic/mail.py +0 -90
  202. lionagi/core/generic/mailbox.py +0 -36
  203. lionagi/core/generic/relation.py +0 -70
  204. lionagi/core/generic/signal.py +0 -22
  205. lionagi/core/generic/structure.py +0 -362
  206. lionagi/core/generic/transfer.py +0 -20
  207. lionagi/core/generic/work.py +0 -40
  208. lionagi/core/graph/graph.py +0 -126
  209. lionagi/core/graph/tree.py +0 -190
  210. lionagi/core/mail/schema.py +0 -63
  211. lionagi/core/messages/schema.py +0 -325
  212. lionagi/core/tool/__init__.py +0 -5
  213. lionagi/core/tool/tool.py +0 -28
  214. lionagi/core/tool/tool_manager.py +0 -283
  215. lionagi/experimental/report/form.py +0 -64
  216. lionagi/experimental/report/report.py +0 -138
  217. lionagi/experimental/report/util.py +0 -47
  218. lionagi/experimental/tool/function_calling.py +0 -43
  219. lionagi/experimental/tool/manual.py +0 -66
  220. lionagi/experimental/tool/schema.py +0 -59
  221. lionagi/experimental/tool/tool_manager.py +0 -138
  222. lionagi/experimental/tool/util.py +0 -16
  223. lionagi/experimental/validator/rule.py +0 -139
  224. lionagi/experimental/validator/validator.py +0 -56
  225. lionagi/experimental/work/__init__.py +0 -10
  226. lionagi/experimental/work/async_queue.py +0 -54
  227. lionagi/experimental/work/schema.py +0 -73
  228. lionagi/experimental/work/work_function.py +0 -67
  229. lionagi/experimental/work/worker.py +0 -56
  230. lionagi/experimental/work2/form.py +0 -371
  231. lionagi/experimental/work2/report.py +0 -289
  232. lionagi/experimental/work2/schema.py +0 -30
  233. lionagi/experimental/work2/tests.py +0 -72
  234. lionagi/experimental/work2/work_function.py +0 -89
  235. lionagi/experimental/work2/worker.py +0 -12
  236. lionagi/integrations/bridge/llamaindex_/get_index.py +0 -294
  237. lionagi/tests/test_core/generic/test_component.py +0 -89
  238. lionagi/tests/test_core/test_base_branch.py +0 -426
  239. lionagi/tests/test_core/test_chat_flow.py +0 -63
  240. lionagi/tests/test_core/test_mail_manager.py +0 -75
  241. lionagi/tests/test_core/test_prompts.py +0 -51
  242. lionagi/tests/test_core/test_session.py +0 -254
  243. lionagi/tests/test_core/test_session_base_util.py +0 -313
  244. lionagi/tests/test_core/test_tool_manager.py +0 -95
  245. lionagi-0.1.2.dist-info/LICENSE +0 -9
  246. lionagi-0.1.2.dist-info/METADATA +0 -174
  247. lionagi-0.1.2.dist-info/RECORD +0 -206
  248. /lionagi/core/{branch → _setting}/__init__.py +0 -0
  249. /lionagi/core/{execute → agent/eval}/__init__.py +0 -0
  250. /lionagi/core/{flow → agent/learn}/__init__.py +0 -0
  251. /lionagi/core/{form → agent/plan}/__init__.py +0 -0
  252. /lionagi/core/{branch/executable_branch.py → agent/plan/plan.py} +0 -0
  253. /lionagi/core/{graph → director}/__init__.py +0 -0
  254. /lionagi/core/{messages → engine}/__init__.py +0 -0
  255. /lionagi/{experimental/directive/evaluator → core/engine}/sandbox_.py +0 -0
  256. /lionagi/{experimental/directive/evaluator → core/executor}/__init__.py +0 -0
  257. /lionagi/{experimental/directive/template_ → core/rule}/__init__.py +0 -0
  258. /lionagi/{experimental/report → core/unit/template}/__init__.py +0 -0
  259. /lionagi/{experimental/tool → core/validator}/__init__.py +0 -0
  260. /lionagi/{experimental/validator → core/work}/__init__.py +0 -0
  261. /lionagi/experimental/{work2 → compressor}/__init__.py +0 -0
  262. /lionagi/{core/flow/mono_chat_mixin.py → experimental/directive/template/__init__.py} +0 -0
  263. /lionagi/experimental/directive/{schema.py → template/schema.py} +0 -0
  264. /lionagi/experimental/{work2/util.py → evaluator/__init__.py} +0 -0
  265. /lionagi/experimental/{work2/work.py → knowledge/__init__.py} +0 -0
  266. /lionagi/{tests/libs/test_async.py → experimental/knowledge/graph.py} +0 -0
  267. {lionagi-0.1.2.dist-info → lionagi-0.2.0.dist-info}/WHEEL +0 -0
  268. {lionagi-0.1.2.dist-info → lionagi-0.2.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1 @@
1
+ # TODO
@@ -0,0 +1 @@
1
+ # TODO
@@ -0,0 +1 @@
1
+ # TODO
@@ -0,0 +1 @@
1
+ # TODO
@@ -0,0 +1 @@
1
+ # TODO
@@ -0,0 +1,5 @@
1
+ from .unit_form import UnitForm
2
+ from .unit import Unit
3
+
4
+
5
+ __all__ = ["UnitForm", "Unit"]
@@ -0,0 +1,245 @@
1
+ """
2
+ Copyright 2024 HaiyangLi
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
+
17
+ from lionagi.libs.ln_func_call import rcall, pcall
18
+ from lionagi.libs import convert, AsyncUtil
19
+
20
+ from lionagi.core.collections.abc import Directive
21
+ from lionagi.core.collections import iModel
22
+ from lionagi.core.validator.validator import Validator
23
+ from lionagi.core.session.branch import Branch
24
+ from lionagi.core.unit.util import retry_kwargs
25
+
26
+
27
+ class ParallelUnit(Directive):
28
+ """
29
+ A class representing a unit that can perform parallel chat interactions.
30
+
31
+ Attributes:
32
+ branch (Session): The session to which this ParallelUnit belongs.
33
+ imodel (iModel): The model to be used for interactions.
34
+ form_template (Form): The template for the form to be used.
35
+ validator (Validator): The validator to validate the forms.
36
+
37
+ Methods:
38
+ pchat(*args, **kwargs): Asynchronously performs a parallel chat interaction.
39
+ _parallel_chat(
40
+ instruction,
41
+ num_instances=1,
42
+ context=None,
43
+ sender=None,
44
+ messages=None,
45
+ tools=False,
46
+ out=True,
47
+ invoke=True,
48
+ requested_fields=None,
49
+ persist_path=None,
50
+ branch_config={},
51
+ explode=False,
52
+ include_mapping=True,
53
+ default_key="response",
54
+ **kwargs,
55
+ ): Asynchronously performs the core logic for parallel chat interactions.
56
+ """
57
+
58
+ default_template = None
59
+
60
+ def __init__(
61
+ self, session, imodel: iModel = None, template=None, rulebook=None
62
+ ) -> None:
63
+ """
64
+ Initializes a new instance of ParallelUnit.
65
+
66
+ Args:
67
+ session (Session): The session to which this ParallelUnit belongs.
68
+ imodel (iModel, optional): The model to be used for interactions.
69
+ template (Form, optional): The template for the form to be used.
70
+ rulebook (Rulebook, optional): The rulebook to validate the forms.
71
+ """
72
+ self.branch = session
73
+ if imodel and isinstance(imodel, iModel):
74
+ session.imodel = imodel
75
+ self.imodel = imodel
76
+ else:
77
+ self.imodel = session.imodel
78
+ self.form_template = template or self.default_template
79
+ self.validator = Validator(rulebook=rulebook) if rulebook else Validator()
80
+
81
+ async def pchat(self, *args, **kwargs):
82
+ """
83
+ Asynchronously performs a parallel chat interaction.
84
+
85
+ Args:
86
+ *args: Positional arguments to pass to the _parallel_chat method.
87
+ **kwargs: Keyword arguments to pass to the _parallel_chat method,
88
+ including retry configurations.
89
+
90
+ Returns:
91
+ Any: The result of the parallel chat interaction.
92
+ """
93
+ kwargs = {**retry_kwargs, **kwargs}
94
+ return await rcall(self._parallel_chat, *args, **kwargs)
95
+
96
+ async def _parallel_chat(
97
+ self,
98
+ instruction: str,
99
+ num_instances=1,
100
+ context=None,
101
+ sender=None,
102
+ messages=None,
103
+ tools=False,
104
+ out=True,
105
+ invoke: bool = True,
106
+ requested_fields=None,
107
+ persist_path=None,
108
+ branch_config={},
109
+ explode=False,
110
+ include_mapping=True,
111
+ default_key="response",
112
+ **kwargs,
113
+ ):
114
+ """
115
+ Asynchronously performs the core logic for parallel chat interactions.
116
+
117
+ Args:
118
+ instruction (str): The instruction to perform.
119
+ num_instances (int, optional): Number of instances to run in parallel.
120
+ Defaults to 1.
121
+ context (Any, optional): The context to perform the instruction on.
122
+ sender (str, optional): The sender of the instruction. Defaults to None.
123
+ messages (list, optional): The list of messages. Defaults to None.
124
+ tools (bool, optional): Flag indicating if tools should be used.
125
+ Defaults to False.
126
+ out (bool, optional): Flag indicating if output should be returned.
127
+ Defaults to True.
128
+ invoke (bool, optional): Flag indicating if tools should be invoked.
129
+ Defaults to True.
130
+ requested_fields (list, optional): Fields to request from the context.
131
+ Defaults to None.
132
+ persist_path (str, optional): Path to persist the branch. Defaults to None.
133
+ branch_config (dict, optional): Configuration for the branch. Defaults to {}.
134
+ explode (bool, optional): Flag indicating if combinations of instructions
135
+ and context should be exploded. Defaults to False.
136
+ include_mapping (bool, optional): Flag indicating if instruction, context,
137
+ and branch mapping should be included.
138
+ Defaults to True.
139
+ default_key (str, optional): The default key for the response. Defaults to "response".
140
+ **kwargs: Additional keyword arguments for further customization.
141
+
142
+ Returns:
143
+ Any: The result of the parallel chat interaction.
144
+ """
145
+
146
+ branches = {}
147
+
148
+ async def _inner(i, ins_, cxt_):
149
+
150
+ branch_ = Branch(
151
+ messages=messages,
152
+ service=self.session.default_branch.service,
153
+ llmconfig=self.session.default_branch.llmconfig,
154
+ persist_path=persist_path,
155
+ **branch_config,
156
+ )
157
+
158
+ branch_.branch_name = branch_.id_
159
+
160
+ if tools:
161
+ branch_.tool_manager = self.session.default_branch.tool_manager
162
+
163
+ res_ = await branch_.chat(
164
+ instruction=ins_ or instruction,
165
+ context=cxt_ or context,
166
+ sender=sender,
167
+ tools=tools,
168
+ invoke=invoke,
169
+ out=out,
170
+ requested_fields=requested_fields,
171
+ **kwargs,
172
+ )
173
+
174
+ branches[branch_.id_] = branch_
175
+ if include_mapping:
176
+ return {
177
+ "instruction": ins_ or instruction,
178
+ "context": cxt_ or context,
179
+ "branch_id": branch_.id_,
180
+ default_key: res_,
181
+ }
182
+
183
+ else:
184
+ return res_
185
+
186
+ async def _inner_2(i, ins_=None, cxt_=None):
187
+ """returns num_instances of branches performing for same task/context"""
188
+ tasks = [_inner(i, ins_, cxt_) for _ in range(num_instances)]
189
+ ress = await AsyncUtil.execute_tasks(*tasks)
190
+ return convert.to_list(ress)
191
+
192
+ async def _inner_3(i):
193
+ """different instructions but same context"""
194
+ tasks = [_inner_2(i, ins_=ins_) for ins_ in convert.to_list(instruction)]
195
+ ress = await AsyncUtil.execute_tasks(*tasks)
196
+ return convert.to_list(ress)
197
+
198
+ async def _inner_3_b(i):
199
+ """different context but same instruction"""
200
+ tasks = [_inner_2(i, cxt_=cxt_) for cxt_ in convert.to_list(context)]
201
+ ress = await AsyncUtil.execute_tasks(*tasks)
202
+ return convert.to_list(ress)
203
+
204
+ async def _inner_4(i):
205
+ """different instructions and different context"""
206
+
207
+ tasks = []
208
+ if explode:
209
+ tasks = [
210
+ _inner_2(i, ins_=ins_, cxt_=cxt_)
211
+ for ins_ in convert.to_list(instruction)
212
+ for cxt_ in convert.to_list(context)
213
+ ]
214
+ else:
215
+ tasks = [
216
+ _inner_2(i, ins_=ins_, cxt_=cxt_)
217
+ for ins_, cxt_ in zip(
218
+ convert.to_list(instruction), convert.to_list(context)
219
+ )
220
+ ]
221
+
222
+ ress = await AsyncUtil.execute_tasks(*tasks)
223
+ return convert.to_list(ress)
224
+
225
+ if len(convert.to_list(instruction)) == 1:
226
+ if len(convert.to_list(context)) == 1:
227
+ out_ = await _inner_2(0)
228
+ self.session.branches.update(branches)
229
+ return out_
230
+
231
+ elif len(convert.to_list(context)) > 1:
232
+ out_ = await _inner_3_b(0)
233
+ self.session.branches.update(branches)
234
+ return out_
235
+
236
+ elif len(convert.to_list(instruction)) > 1:
237
+ if len(convert.to_list(context)) == 1:
238
+ out_ = await _inner_3(0)
239
+ self.session.branches.update(branches)
240
+ return out_
241
+
242
+ elif len(convert.to_list(context)) > 1:
243
+ out_ = await _inner_4(0)
244
+ self.session.branches.update(branches)
245
+ return out_
@@ -0,0 +1,81 @@
1
+ """
2
+ Copyright 2024 HaiyangLi
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
+
17
+ from .base import BaseUnitForm, Field
18
+
19
+
20
+ class ActionTemplate(BaseUnitForm):
21
+ """
22
+ A template for actions that includes instructions, context, and confidence scoring.
23
+
24
+ Attributes:
25
+ action_required (bool | None): Indicates if actions are required.
26
+ actions (list[dict] | None): A list of actions to take, formatted as dictionaries.
27
+ answer (str | None): The output answer to the questions asked.
28
+ assignment (str): The assignment structure for the task.
29
+ """
30
+
31
+ action_required: bool | None = Field(
32
+ None,
33
+ description="Set to True if actions are required. Provide actions if True.",
34
+ )
35
+
36
+ actions: list[dict] | None = Field(
37
+ None,
38
+ description=(
39
+ "A list of actions to take. Format: [{'function': func, 'arguments': "
40
+ "{'param1':..., 'param2':...}}]. Leave blank if no actions are needed."
41
+ "must use provided functions and parameters, DO NOT MAKE UP NAMES!!!"
42
+ "Flag `action_required` as True if filled."
43
+ ),
44
+ )
45
+
46
+ answer: str | None = Field(
47
+ None,
48
+ description=(
49
+ "output answer to the questions asked if further actions are not needed,"
50
+ " leave blank if an accurate answer cannot be provided from context"
51
+ " during this step"
52
+ ),
53
+ )
54
+
55
+ assignment: str = "task -> reason, action_required, actions, answer"
56
+
57
+ def __init__(
58
+ self,
59
+ instruction=None,
60
+ context=None,
61
+ confidence_score=False,
62
+ **kwargs,
63
+ ):
64
+ """
65
+ Initializes an instance of the ActionTemplate class.
66
+
67
+ Args:
68
+ instruction (str, optional): Additional instruction for the task.
69
+ context (str, optional): Additional context for the task.
70
+ confidence_score (bool, optional): If True, includes confidence scoring.
71
+ **kwargs: Additional keyword arguments.
72
+ """
73
+ super().__init__(**kwargs)
74
+
75
+ self.task = f"""
76
+ Perform reasoning and prepare actions with GIVEN TOOLS ONLY.
77
+ 1. additional instruction: {instruction or "N/A"}.
78
+ 2. additional context: {context or "N/A"}.
79
+ """
80
+ if confidence_score:
81
+ self.append_to_request("confidence_score")
@@ -0,0 +1,51 @@
1
+ """
2
+ Copyright 2024 HaiyangLi
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
+
17
+ from lionagi.core.collections.abc import Field
18
+ from lionagi.core.report.form import Form
19
+
20
+
21
+ class BaseUnitForm(Form):
22
+ """
23
+ A base form class for units that includes fields for confidence scoring and reasoning.
24
+
25
+ Attributes:
26
+ template_name (str): The name of the template.
27
+ confidence_score (float): A numeric confidence score between 0 and 1 with precision to 2 decimal places.
28
+ reason (str | None): A field for providing concise reasoning for the process.
29
+ """
30
+
31
+ template_name: str = "UnitDirective"
32
+
33
+ confidence_score: float = Field(
34
+ None,
35
+ description=(
36
+ "Provide a numeric confidence score on how likely you successfully achieved the task between 0 and 1, with precision in 2 decimal places. 1 being very confident in a good job, 0 is not confident at all."
37
+ ),
38
+ validation_kwargs={
39
+ "upper_bound": 1,
40
+ "lower_bound": 0,
41
+ "num_type": float,
42
+ "precision": 2,
43
+ },
44
+ )
45
+
46
+ reason: str | None = Field(
47
+ None,
48
+ description=(
49
+ "Explain yourself, provide concise reasoning for the process. Must start with: Let's think step by step, "
50
+ ),
51
+ )
@@ -0,0 +1,84 @@
1
+ """
2
+ Copyright 2024 HaiyangLi
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
+
17
+ from lionagi.libs.ln_convert import to_str
18
+ from .base import BaseUnitForm, Field
19
+
20
+
21
+ class PlanTemplate(BaseUnitForm):
22
+ """
23
+ A template for generating a step-by-step plan based on given instructions and context.
24
+
25
+ Inherits from `BaseUnitForm` and adds fields and methods specific to plan generation.
26
+
27
+ Attributes:
28
+ template_name (str): The name of the template.
29
+ plan (dict | str): The generated step-by-step plan in the format {step_n: {plan: ..., reason: ...}}.
30
+ signature (str): A string representing the task signature for the plan.
31
+ """
32
+
33
+ template_name: str = "plan_template"
34
+
35
+ plan: dict | str = Field(
36
+ default_factory=dict,
37
+ description="the generated step by step plan, return as a dictionary following {step_n: {plan: ..., reason: ...}} format",
38
+ )
39
+
40
+ signature: str = "task -> plan"
41
+
42
+ @property
43
+ def answer(self):
44
+ """
45
+ Gets the plan attribute.
46
+
47
+ Returns:
48
+ dict | str: The generated plan.
49
+ """
50
+ return getattr(self, "plan", None)
51
+
52
+ def __init__(
53
+ self,
54
+ *,
55
+ instruction=None,
56
+ context=None,
57
+ confidence_score=False,
58
+ reason=False,
59
+ num_step=3,
60
+ **kwargs,
61
+ ):
62
+ """
63
+ Initializes a new instance of the PlanTemplate class.
64
+
65
+ Args:
66
+ instruction (str, optional): Additional instructions for the plan.
67
+ context (str, optional): Additional context for the plan.
68
+ confidence_score (bool, optional): Whether to include a confidence score.
69
+ reason (bool, optional): Whether to include a reasoning field.
70
+ num_step (int, optional): The number of steps in the plan. Defaults to 3.
71
+ **kwargs: Additional keyword arguments.
72
+ """
73
+ super().__init__(**kwargs)
74
+
75
+ self.task = f"""
76
+ Generate a {num_step}_step plan based on the given context
77
+ 1. additional instruction, {to_str(instruction or "N/A")}
78
+ 2. additional context, {to_str(context or "N/A")}
79
+ """
80
+ if reason:
81
+ self.append_to_request("reason")
82
+
83
+ if confidence_score:
84
+ self.append_to_request("confidence_score")
@@ -0,0 +1,109 @@
1
+ """
2
+ Copyright 2024 HaiyangLi
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
+
17
+ from .base import BaseUnitForm, Field
18
+
19
+
20
+ class PredictTemplate(BaseUnitForm):
21
+ """
22
+ A template for predicting the next sentence(s) based on given instructions and context.
23
+
24
+ Inherits from `BaseUnitForm` and adds fields and methods specific to prediction tasks.
25
+
26
+ Attributes:
27
+ confidence_score (float | None): A numeric score between 0 to 1 formatted to 2 decimal places, indicating confidence in the prediction.
28
+ reason (str | None): A brief reason for the given output.
29
+ template_name (str): The name of the template.
30
+ num_sentences (int): The number of sentences to predict.
31
+ prediction (None | str | list): The predicted sentence(s) or desired output.
32
+ assignment (str): A string representing the task assignment for the prediction.
33
+ """
34
+
35
+ confidence_score: float | None = Field(
36
+ None,
37
+ description="a numeric score between 0 to 1 formatted in num:0.2f, 1 being very confident and 0 being not confident at all, just guessing",
38
+ validation_kwargs={
39
+ "upper_bound": 1,
40
+ "lower_bound": 0,
41
+ "num_type": float,
42
+ "precision": 2,
43
+ },
44
+ )
45
+
46
+ reason: str | None = Field(
47
+ None,
48
+ description="brief reason for the given output, format: This is my best response because ...",
49
+ )
50
+
51
+ template_name: str = "predict_template"
52
+
53
+ num_sentences: int = Field(2, description="the number of sentences to predict")
54
+
55
+ prediction: None | str | list = Field(
56
+ None,
57
+ description="the predicted sentence(s) or desired output",
58
+ )
59
+
60
+ assignment: str = "task -> prediction"
61
+
62
+ @property
63
+ def answer(self):
64
+ """
65
+ Gets the prediction attribute.
66
+
67
+ Returns:
68
+ None | str | list: The predicted sentence(s) or desired output.
69
+ """
70
+ return getattr(self, "prediction", None)
71
+
72
+ def __init__(
73
+ self,
74
+ *,
75
+ instruction=None,
76
+ context=None,
77
+ num_sentences=2,
78
+ confidence_score=False,
79
+ reason=False,
80
+ **kwargs,
81
+ ):
82
+ """
83
+ Initializes a new instance of the PredictTemplate class.
84
+
85
+ Args:
86
+ instruction (str, optional): Additional instructions for the prediction.
87
+ context (str, optional): Additional context for the prediction.
88
+ num_sentences (int, optional): The number of sentences to predict. Defaults to 2.
89
+ confidence_score (bool, optional): Whether to include a confidence score. Defaults to False.
90
+ reason (bool, optional): Whether to include a reasoning field. Defaults to False.
91
+ **kwargs: Additional keyword arguments.
92
+ """
93
+
94
+ super().__init__(**kwargs)
95
+
96
+ self.num_sentences = num_sentences
97
+
98
+ self.task = f"""
99
+ predict the next sentence(s) according to the following constraints
100
+ 1. number of sentences: {self.num_sentences}
101
+ 2. additional objective , {instruction or "N/A"}
102
+ 3. additional information, {context or "N/A"}
103
+ """
104
+
105
+ if reason:
106
+ self.append_to_request("reason")
107
+
108
+ if confidence_score:
109
+ self.append_to_request("confidence_score")