lionagi 0.0.312__py3-none-any.whl → 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. lionagi/__init__.py +61 -3
  2. lionagi/core/__init__.py +0 -14
  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/__init__.py +0 -3
  11. lionagi/core/agent/base_agent.py +45 -36
  12. lionagi/core/agent/eval/evaluator.py +1 -0
  13. lionagi/core/agent/eval/vote.py +40 -0
  14. lionagi/core/agent/learn/learner.py +59 -0
  15. lionagi/core/agent/plan/unit_template.py +1 -0
  16. lionagi/core/collections/__init__.py +17 -0
  17. lionagi/core/collections/_logger.py +319 -0
  18. lionagi/core/collections/abc/__init__.py +53 -0
  19. lionagi/core/collections/abc/component.py +615 -0
  20. lionagi/core/collections/abc/concepts.py +297 -0
  21. lionagi/core/collections/abc/exceptions.py +150 -0
  22. lionagi/core/collections/abc/util.py +45 -0
  23. lionagi/core/collections/exchange.py +161 -0
  24. lionagi/core/collections/flow.py +426 -0
  25. lionagi/core/collections/model.py +419 -0
  26. lionagi/core/collections/pile.py +913 -0
  27. lionagi/core/collections/progression.py +236 -0
  28. lionagi/core/collections/util.py +64 -0
  29. lionagi/core/director/direct.py +314 -0
  30. lionagi/core/director/director.py +2 -0
  31. lionagi/core/engine/branch_engine.py +333 -0
  32. lionagi/core/engine/instruction_map_engine.py +204 -0
  33. lionagi/core/engine/sandbox_.py +14 -0
  34. lionagi/core/engine/script_engine.py +99 -0
  35. lionagi/core/executor/base_executor.py +90 -0
  36. lionagi/core/executor/graph_executor.py +330 -0
  37. lionagi/core/executor/neo4j_executor.py +384 -0
  38. lionagi/core/generic/__init__.py +7 -0
  39. lionagi/core/generic/edge.py +112 -0
  40. lionagi/core/generic/edge_condition.py +16 -0
  41. lionagi/core/generic/graph.py +236 -0
  42. lionagi/core/generic/hyperedge.py +1 -0
  43. lionagi/core/generic/node.py +220 -0
  44. lionagi/core/generic/tree.py +48 -0
  45. lionagi/core/generic/tree_node.py +79 -0
  46. lionagi/core/mail/__init__.py +7 -3
  47. lionagi/core/mail/mail.py +25 -0
  48. lionagi/core/mail/mail_manager.py +142 -58
  49. lionagi/core/mail/package.py +45 -0
  50. lionagi/core/mail/start_mail.py +36 -0
  51. lionagi/core/message/__init__.py +19 -0
  52. lionagi/core/message/action_request.py +133 -0
  53. lionagi/core/message/action_response.py +135 -0
  54. lionagi/core/message/assistant_response.py +95 -0
  55. lionagi/core/message/instruction.py +234 -0
  56. lionagi/core/message/message.py +101 -0
  57. lionagi/core/message/system.py +86 -0
  58. lionagi/core/message/util.py +283 -0
  59. lionagi/core/report/__init__.py +4 -0
  60. lionagi/core/report/base.py +217 -0
  61. lionagi/core/report/form.py +231 -0
  62. lionagi/core/report/report.py +166 -0
  63. lionagi/core/report/util.py +28 -0
  64. lionagi/core/rule/__init__.py +0 -0
  65. lionagi/core/rule/_default.py +16 -0
  66. lionagi/core/rule/action.py +99 -0
  67. lionagi/core/rule/base.py +238 -0
  68. lionagi/core/rule/boolean.py +56 -0
  69. lionagi/core/rule/choice.py +47 -0
  70. lionagi/core/rule/mapping.py +96 -0
  71. lionagi/core/rule/number.py +71 -0
  72. lionagi/core/rule/rulebook.py +109 -0
  73. lionagi/core/rule/string.py +52 -0
  74. lionagi/core/rule/util.py +35 -0
  75. lionagi/core/session/__init__.py +0 -3
  76. lionagi/core/session/branch.py +431 -0
  77. lionagi/core/session/directive_mixin.py +287 -0
  78. lionagi/core/session/session.py +230 -902
  79. lionagi/core/structure/__init__.py +1 -0
  80. lionagi/core/structure/chain.py +1 -0
  81. lionagi/core/structure/forest.py +1 -0
  82. lionagi/core/structure/graph.py +1 -0
  83. lionagi/core/structure/tree.py +1 -0
  84. lionagi/core/unit/__init__.py +5 -0
  85. lionagi/core/unit/parallel_unit.py +245 -0
  86. lionagi/core/unit/template/__init__.py +0 -0
  87. lionagi/core/unit/template/action.py +81 -0
  88. lionagi/core/unit/template/base.py +51 -0
  89. lionagi/core/unit/template/plan.py +84 -0
  90. lionagi/core/unit/template/predict.py +109 -0
  91. lionagi/core/unit/template/score.py +124 -0
  92. lionagi/core/unit/template/select.py +104 -0
  93. lionagi/core/unit/unit.py +362 -0
  94. lionagi/core/unit/unit_form.py +305 -0
  95. lionagi/core/unit/unit_mixin.py +1168 -0
  96. lionagi/core/unit/util.py +71 -0
  97. lionagi/core/validator/__init__.py +0 -0
  98. lionagi/core/validator/validator.py +364 -0
  99. lionagi/core/work/__init__.py +0 -0
  100. lionagi/core/work/work.py +76 -0
  101. lionagi/core/work/work_function.py +101 -0
  102. lionagi/core/work/work_queue.py +103 -0
  103. lionagi/core/work/worker.py +258 -0
  104. lionagi/core/work/worklog.py +120 -0
  105. lionagi/experimental/__init__.py +0 -0
  106. lionagi/experimental/compressor/__init__.py +0 -0
  107. lionagi/experimental/compressor/base.py +46 -0
  108. lionagi/experimental/compressor/llm_compressor.py +247 -0
  109. lionagi/experimental/compressor/llm_summarizer.py +61 -0
  110. lionagi/experimental/compressor/util.py +70 -0
  111. lionagi/experimental/directive/__init__.py +19 -0
  112. lionagi/experimental/directive/parser/__init__.py +0 -0
  113. lionagi/experimental/directive/parser/base_parser.py +282 -0
  114. lionagi/experimental/directive/template/__init__.py +0 -0
  115. lionagi/experimental/directive/template/base_template.py +79 -0
  116. lionagi/experimental/directive/template/schema.py +36 -0
  117. lionagi/experimental/directive/tokenizer.py +73 -0
  118. lionagi/experimental/evaluator/__init__.py +0 -0
  119. lionagi/experimental/evaluator/ast_evaluator.py +131 -0
  120. lionagi/experimental/evaluator/base_evaluator.py +218 -0
  121. lionagi/experimental/knowledge/__init__.py +0 -0
  122. lionagi/experimental/knowledge/base.py +10 -0
  123. lionagi/experimental/knowledge/graph.py +0 -0
  124. lionagi/experimental/memory/__init__.py +0 -0
  125. lionagi/experimental/strategies/__init__.py +0 -0
  126. lionagi/experimental/strategies/base.py +1 -0
  127. lionagi/integrations/bridge/autogen_/__init__.py +0 -0
  128. lionagi/integrations/bridge/autogen_/autogen_.py +124 -0
  129. lionagi/integrations/bridge/langchain_/documents.py +4 -0
  130. lionagi/integrations/bridge/llamaindex_/index.py +30 -0
  131. lionagi/integrations/bridge/llamaindex_/llama_index_bridge.py +6 -0
  132. lionagi/integrations/bridge/llamaindex_/llama_pack.py +227 -0
  133. lionagi/integrations/bridge/llamaindex_/node_parser.py +6 -9
  134. lionagi/integrations/bridge/pydantic_/pydantic_bridge.py +1 -0
  135. lionagi/integrations/bridge/transformers_/__init__.py +0 -0
  136. lionagi/integrations/bridge/transformers_/install_.py +36 -0
  137. lionagi/integrations/chunker/__init__.py +0 -0
  138. lionagi/integrations/chunker/chunk.py +312 -0
  139. lionagi/integrations/config/oai_configs.py +38 -7
  140. lionagi/integrations/config/ollama_configs.py +1 -1
  141. lionagi/integrations/config/openrouter_configs.py +14 -2
  142. lionagi/integrations/loader/__init__.py +0 -0
  143. lionagi/integrations/loader/load.py +253 -0
  144. lionagi/integrations/loader/load_util.py +195 -0
  145. lionagi/integrations/provider/_mapping.py +46 -0
  146. lionagi/integrations/provider/litellm.py +2 -1
  147. lionagi/integrations/provider/mlx_service.py +16 -9
  148. lionagi/integrations/provider/oai.py +91 -4
  149. lionagi/integrations/provider/ollama.py +7 -6
  150. lionagi/integrations/provider/openrouter.py +115 -8
  151. lionagi/integrations/provider/services.py +2 -2
  152. lionagi/integrations/provider/transformers.py +18 -22
  153. lionagi/integrations/storage/__init__.py +3 -0
  154. lionagi/integrations/storage/neo4j.py +665 -0
  155. lionagi/integrations/storage/storage_util.py +287 -0
  156. lionagi/integrations/storage/structure_excel.py +285 -0
  157. lionagi/integrations/storage/to_csv.py +63 -0
  158. lionagi/integrations/storage/to_excel.py +83 -0
  159. lionagi/libs/__init__.py +26 -1
  160. lionagi/libs/ln_api.py +78 -23
  161. lionagi/libs/ln_context.py +37 -0
  162. lionagi/libs/ln_convert.py +21 -9
  163. lionagi/libs/ln_func_call.py +69 -28
  164. lionagi/libs/ln_image.py +107 -0
  165. lionagi/libs/ln_knowledge_graph.py +405 -0
  166. lionagi/libs/ln_nested.py +26 -11
  167. lionagi/libs/ln_parse.py +110 -14
  168. lionagi/libs/ln_queue.py +117 -0
  169. lionagi/libs/ln_tokenize.py +164 -0
  170. lionagi/{core/prompt/field_validator.py → libs/ln_validate.py} +79 -14
  171. lionagi/libs/special_tokens.py +172 -0
  172. lionagi/libs/sys_util.py +107 -2
  173. lionagi/lions/__init__.py +0 -0
  174. lionagi/lions/coder/__init__.py +0 -0
  175. lionagi/lions/coder/add_feature.py +20 -0
  176. lionagi/lions/coder/base_prompts.py +22 -0
  177. lionagi/lions/coder/code_form.py +13 -0
  178. lionagi/lions/coder/coder.py +168 -0
  179. lionagi/lions/coder/util.py +96 -0
  180. lionagi/lions/researcher/__init__.py +0 -0
  181. lionagi/lions/researcher/data_source/__init__.py +0 -0
  182. lionagi/lions/researcher/data_source/finhub_.py +191 -0
  183. lionagi/lions/researcher/data_source/google_.py +199 -0
  184. lionagi/lions/researcher/data_source/wiki_.py +96 -0
  185. lionagi/lions/researcher/data_source/yfinance_.py +21 -0
  186. lionagi/tests/integrations/__init__.py +0 -0
  187. lionagi/tests/libs/__init__.py +0 -0
  188. lionagi/tests/libs/test_field_validators.py +353 -0
  189. lionagi/tests/{test_libs → libs}/test_func_call.py +23 -21
  190. lionagi/tests/{test_libs → libs}/test_nested.py +36 -21
  191. lionagi/tests/{test_libs → libs}/test_parse.py +1 -1
  192. lionagi/tests/libs/test_queue.py +67 -0
  193. lionagi/tests/test_core/collections/__init__.py +0 -0
  194. lionagi/tests/test_core/collections/test_component.py +206 -0
  195. lionagi/tests/test_core/collections/test_exchange.py +138 -0
  196. lionagi/tests/test_core/collections/test_flow.py +145 -0
  197. lionagi/tests/test_core/collections/test_pile.py +171 -0
  198. lionagi/tests/test_core/collections/test_progression.py +129 -0
  199. lionagi/tests/test_core/generic/__init__.py +0 -0
  200. lionagi/tests/test_core/generic/test_edge.py +67 -0
  201. lionagi/tests/test_core/generic/test_graph.py +96 -0
  202. lionagi/tests/test_core/generic/test_node.py +106 -0
  203. lionagi/tests/test_core/generic/test_tree_node.py +73 -0
  204. lionagi/tests/test_core/test_branch.py +115 -292
  205. lionagi/tests/test_core/test_form.py +46 -0
  206. lionagi/tests/test_core/test_report.py +105 -0
  207. lionagi/tests/test_core/test_validator.py +111 -0
  208. lionagi/version.py +1 -1
  209. {lionagi-0.0.312.dist-info → lionagi-0.2.1.dist-info}/LICENSE +12 -11
  210. {lionagi-0.0.312.dist-info → lionagi-0.2.1.dist-info}/METADATA +19 -118
  211. lionagi-0.2.1.dist-info/RECORD +240 -0
  212. lionagi/core/branch/__init__.py +0 -4
  213. lionagi/core/branch/base_branch.py +0 -654
  214. lionagi/core/branch/branch.py +0 -471
  215. lionagi/core/branch/branch_flow_mixin.py +0 -96
  216. lionagi/core/branch/executable_branch.py +0 -347
  217. lionagi/core/branch/util.py +0 -323
  218. lionagi/core/direct/__init__.py +0 -6
  219. lionagi/core/direct/predict.py +0 -161
  220. lionagi/core/direct/score.py +0 -278
  221. lionagi/core/direct/select.py +0 -169
  222. lionagi/core/direct/utils.py +0 -87
  223. lionagi/core/direct/vote.py +0 -64
  224. lionagi/core/flow/base/baseflow.py +0 -23
  225. lionagi/core/flow/monoflow/ReAct.py +0 -238
  226. lionagi/core/flow/monoflow/__init__.py +0 -9
  227. lionagi/core/flow/monoflow/chat.py +0 -95
  228. lionagi/core/flow/monoflow/chat_mixin.py +0 -263
  229. lionagi/core/flow/monoflow/followup.py +0 -214
  230. lionagi/core/flow/polyflow/__init__.py +0 -1
  231. lionagi/core/flow/polyflow/chat.py +0 -248
  232. lionagi/core/mail/schema.py +0 -56
  233. lionagi/core/messages/__init__.py +0 -3
  234. lionagi/core/messages/schema.py +0 -533
  235. lionagi/core/prompt/prompt_template.py +0 -316
  236. lionagi/core/schema/__init__.py +0 -22
  237. lionagi/core/schema/action_node.py +0 -29
  238. lionagi/core/schema/base_mixin.py +0 -296
  239. lionagi/core/schema/base_node.py +0 -199
  240. lionagi/core/schema/condition.py +0 -24
  241. lionagi/core/schema/data_logger.py +0 -354
  242. lionagi/core/schema/data_node.py +0 -93
  243. lionagi/core/schema/prompt_template.py +0 -67
  244. lionagi/core/schema/structure.py +0 -910
  245. lionagi/core/tool/__init__.py +0 -3
  246. lionagi/core/tool/tool_manager.py +0 -280
  247. lionagi/integrations/bridge/pydantic_/base_model.py +0 -7
  248. lionagi/tests/test_core/test_base_branch.py +0 -427
  249. lionagi/tests/test_core/test_chat_flow.py +0 -63
  250. lionagi/tests/test_core/test_mail_manager.py +0 -75
  251. lionagi/tests/test_core/test_prompts.py +0 -51
  252. lionagi/tests/test_core/test_session.py +0 -254
  253. lionagi/tests/test_core/test_session_base_util.py +0 -312
  254. lionagi/tests/test_core/test_tool_manager.py +0 -95
  255. lionagi-0.0.312.dist-info/RECORD +0 -111
  256. /lionagi/core/{branch/base → _setting}/__init__.py +0 -0
  257. /lionagi/core/{flow → agent/eval}/__init__.py +0 -0
  258. /lionagi/core/{flow/base → agent/learn}/__init__.py +0 -0
  259. /lionagi/core/{prompt → agent/plan}/__init__.py +0 -0
  260. /lionagi/core/{tool/manual.py → agent/plan/plan.py} +0 -0
  261. /lionagi/{tests/test_integrations → core/director}/__init__.py +0 -0
  262. /lionagi/{tests/test_libs → core/engine}/__init__.py +0 -0
  263. /lionagi/{tests/test_libs/test_async.py → core/executor/__init__.py} +0 -0
  264. /lionagi/tests/{test_libs → libs}/test_api.py +0 -0
  265. /lionagi/tests/{test_libs → libs}/test_convert.py +0 -0
  266. /lionagi/tests/{test_libs → libs}/test_sys_util.py +0 -0
  267. {lionagi-0.0.312.dist-info → lionagi-0.2.1.dist-info}/WHEEL +0 -0
  268. {lionagi-0.0.312.dist-info → lionagi-0.2.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,124 @@
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 lionagi.core.collections.abc import Field
19
+ from lionagi.core.unit import UnitForm
20
+
21
+
22
+ class ScoreTemplate(UnitForm):
23
+ """
24
+ A template for performing a scoring task based on given instructions and context.
25
+
26
+ Inherits from `UnitForm` and adds fields and methods specific to scoring tasks.
27
+
28
+ Attributes:
29
+ confidence_score (float | None): A numeric score between 0 to 1 formatted to 2 decimal places, indicating confidence in the score.
30
+ reason (str | None): A brief reason for the given output.
31
+ template_name (str): The name of the template.
32
+ score (float | None): A score for the given context and task.
33
+ assignment (str): A string representing the task assignment for the score.
34
+ """
35
+
36
+ confidence_score: float | None = Field(
37
+ None,
38
+ description="a numeric score between 0 to 1 formatted in num:0.2f, 1 being very confident and 0 being not confident at all",
39
+ validation_kwargs={
40
+ "upper_bound": 1,
41
+ "lower_bound": 0,
42
+ "num_type": float,
43
+ "precision": 2,
44
+ },
45
+ )
46
+
47
+ reason: str | None = Field(
48
+ None,
49
+ description="brief reason for the given output, format: This is my best response because ...",
50
+ )
51
+
52
+ template_name: str = "score_template"
53
+
54
+ score: float | None = Field(
55
+ None,
56
+ description="a score for the given context and task, numeric",
57
+ )
58
+
59
+ assignment: str = "task -> score"
60
+
61
+ @property
62
+ def answer(self):
63
+ """
64
+ Gets the score attribute.
65
+
66
+ Returns:
67
+ float | None: The score for the given context and task.
68
+ """
69
+ return getattr(self, "score", None)
70
+
71
+ def __init__(
72
+ self,
73
+ *,
74
+ instruction=None,
75
+ context=None,
76
+ score_range=(0, 10),
77
+ include_endpoints=True,
78
+ num_digit=0,
79
+ confidence_score=False,
80
+ reason=False,
81
+ **kwargs,
82
+ ):
83
+ """
84
+ Initializes a new instance of the ScoreTemplate class.
85
+
86
+ Args:
87
+ instruction (str, optional): Additional instructions for the scoring task.
88
+ context (str, optional): Additional context for the scoring task.
89
+ score_range (tuple, optional): The range of the score. Defaults to (0, 10).
90
+ include_endpoints (bool, optional): Whether to include the endpoints in the score range. Defaults to True.
91
+ num_digit (int, optional): The number of digits allowed after the decimal point. Defaults to 0.
92
+ confidence_score (bool, optional): Whether to include a confidence score. Defaults to False.
93
+ reason (bool, optional): Whether to include a reasoning field. Defaults to False.
94
+ **kwargs: Additional keyword arguments.
95
+ """
96
+ super().__init__(**kwargs)
97
+
98
+ return_precision = ""
99
+
100
+ if num_digit == 0:
101
+ return_precision = "integer"
102
+ else:
103
+ return_precision = f"num:{to_str(num_digit)}f"
104
+
105
+ self.task = f"""
106
+ perform scoring task according to the following constraints:
107
+ 1. additional objective: {to_str(instruction or "N/A")}.
108
+ 2. score range: {to_str(score_range)}.
109
+ 3. include_endpoints: {"yes" if include_endpoints else "no"}.
110
+ 4. precision, (max number of digits allowed after "."): {return_precision}.
111
+ 5. additional information: {to_str(context or "N/A")}.
112
+ """
113
+ if reason:
114
+ self.append_to_request("reason")
115
+
116
+ if confidence_score:
117
+ self.append_to_request("confidence_score")
118
+
119
+ self.validation_kwargs["score"] = {
120
+ "upper_bound": score_range[1],
121
+ "lower_bound": score_range[0],
122
+ "num_type": int if num_digit == 0 else float,
123
+ "precision": num_digit if num_digit != 0 else None,
124
+ }
@@ -0,0 +1,104 @@
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 enum import Enum
18
+ from .base import BaseUnitForm, Field
19
+
20
+
21
+ class SelectTemplate(BaseUnitForm):
22
+ """
23
+ A template for performing a selection task based on given instructions and context.
24
+
25
+ Inherits from `BaseUnitForm` and adds fields and methods specific to selection tasks.
26
+
27
+ Attributes:
28
+ confidence_score (float | None): A numeric score between 0 to 1 formatted to 2 decimal places, indicating confidence in the selection.
29
+ reason (str | None): A brief reason for the given output.
30
+ template_name (str): The name of the template.
31
+ selection (Enum | str | list | None): The selection from given choices.
32
+ choices (list): The given choices to select from.
33
+ assignment (str): A string representing the task assignment for the selection.
34
+ """
35
+
36
+ confidence_score: float | None = Field(
37
+ None,
38
+ 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",
39
+ validation_kwargs={
40
+ "upper_bound": 1,
41
+ "lower_bound": 0,
42
+ "num_type": float,
43
+ "precision": 2,
44
+ },
45
+ )
46
+
47
+ reason: str | None = Field(
48
+ default_factory=str,
49
+ description="brief reason for the given output, format: This is my best response because ...",
50
+ )
51
+
52
+ template_name: str = "default_select"
53
+
54
+ selection: Enum | str | list | None = Field(
55
+ None, description="selection from given choices"
56
+ )
57
+ choices: list = Field(default_factory=list, description="the given choices")
58
+
59
+ assignment: str = "task -> selection"
60
+
61
+ @property
62
+ def answer(self):
63
+ """
64
+ Gets the selection attribute.
65
+
66
+ Returns:
67
+ Enum | str | list | None: The selection from given choices.
68
+ """
69
+ return getattr(self, "selection", None)
70
+
71
+ def __init__(
72
+ self,
73
+ *,
74
+ instruction=None,
75
+ context=None,
76
+ choices=None,
77
+ reason=False,
78
+ confidence_score=False,
79
+ **kwargs,
80
+ ):
81
+ """
82
+ Initializes a new instance of the SelectTemplate class.
83
+
84
+ Args:
85
+ instruction (str, optional): Additional instructions for the selection task.
86
+ context (str, optional): Additional context for the selection task.
87
+ choices (list, optional): The choices to select from.
88
+ reason (bool, optional): Whether to include a reasoning field. Defaults to False.
89
+ confidence_score (bool, optional): Whether to include a confidence score. Defaults to False.
90
+ **kwargs: Additional keyword arguments.
91
+ """
92
+ super().__init__(**kwargs)
93
+
94
+ self.choices = choices
95
+ self.task = f"""
96
+ select 1 item from the provided choices {choices}.
97
+ 1. additional objective: {instruction or "N/A"}.
98
+ 2. additional information: {context or "N/A"}.
99
+ """
100
+ if reason:
101
+ self.append_to_request("reason")
102
+
103
+ if confidence_score:
104
+ self.append_to_request("confidence_score")
@@ -0,0 +1,362 @@
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 strip_lower
18
+ from lionagi.libs.ln_func_call import rcall
19
+ from lionagi.core.collections.abc import Directive
20
+ from lionagi.core.validator.validator import Validator
21
+ from lionagi.core.collections import iModel
22
+ from .unit_form import UnitForm
23
+ from .unit_mixin import DirectiveMixin
24
+ from .util import retry_kwargs
25
+
26
+
27
+ class Unit(Directive, DirectiveMixin):
28
+ """
29
+ Unit is a class that extends Directive and DirectiveMixin to provide
30
+ advanced operations like chat, direct actions, and predictions using a
31
+ specific branch and model.
32
+
33
+ Attributes:
34
+ branch (Branch): The branch instance associated with the Unit.
35
+ imodel (iModel): The model instance used for the Unit.
36
+ form_template (Type[Form]): The form template to use for operations.
37
+ validator (Validator): The validator instance for response validation.
38
+ """
39
+
40
+ default_template = UnitForm
41
+
42
+ def __init__(
43
+ self, branch, imodel: iModel = None, template=None, rulebook=None, verbose=False
44
+ ) -> None:
45
+ self.branch = branch
46
+ if imodel and isinstance(imodel, iModel):
47
+ branch.imodel = imodel
48
+ self.imodel = imodel
49
+ else:
50
+ self.imodel = branch.imodel
51
+ self.form_template = template or self.default_template
52
+ self.validator = Validator(rulebook=rulebook) if rulebook else Validator()
53
+ self.verbose = verbose
54
+
55
+ async def chat(
56
+ self,
57
+ instruction=None,
58
+ context=None,
59
+ system=None,
60
+ sender=None,
61
+ recipient=None,
62
+ branch=None,
63
+ requested_fields=None,
64
+ form=None,
65
+ tools=False,
66
+ invoke_tool=True,
67
+ return_form=True,
68
+ strict=False,
69
+ rulebook=None,
70
+ imodel=None,
71
+ clear_messages=False,
72
+ use_annotation=True,
73
+ return_branch=False,
74
+ **kwargs,
75
+ ):
76
+ """
77
+ Asynchronously performs a chat operation.
78
+
79
+ Args:
80
+ instruction (str, optional): Instruction message.
81
+ context (str, optional): Context message.
82
+ system (str, optional): System message.
83
+ sender (str, optional): Sender identifier.
84
+ recipient (str, optional): Recipient identifier.
85
+ branch (Branch, optional): Branch instance.
86
+ requested_fields (list, optional): Fields requested in the response.
87
+ form (Form, optional): Form data.
88
+ tools (bool, optional): Flag indicating if tools should be used.
89
+ invoke_tool (bool, optional): Flag indicating if tools should be invoked.
90
+ return_form (bool, optional): Flag indicating if form should be returned.
91
+ strict (bool, optional): Flag indicating if strict validation should be applied.
92
+ rulebook (Rulebook, optional): Rulebook instance for validation.
93
+ imodel (iModel, optional): Model instance.
94
+ clear_messages (bool, optional): Flag indicating if messages should be cleared.
95
+ use_annotation (bool, optional): Flag indicating if annotations should be used.
96
+ return_branch (bool, optional): Flag indicating if branch should be returned.
97
+ kwargs: Additional keyword arguments.
98
+
99
+ Returns:
100
+ Any: The processed response.
101
+ """
102
+ kwargs = {**retry_kwargs, **kwargs}
103
+ return await rcall(
104
+ self._chat,
105
+ instruction=instruction,
106
+ context=context,
107
+ system=system,
108
+ sender=sender,
109
+ recipient=recipient,
110
+ branch=branch,
111
+ requested_fields=requested_fields,
112
+ form=form,
113
+ tools=tools,
114
+ invoke_tool=invoke_tool,
115
+ return_form=return_form,
116
+ strict=strict,
117
+ rulebook=rulebook,
118
+ imodel=imodel,
119
+ clear_messages=clear_messages,
120
+ use_annotation=use_annotation,
121
+ return_branch=return_branch,
122
+ **kwargs,
123
+ )
124
+
125
+ async def direct(
126
+ self,
127
+ instruction=None,
128
+ *,
129
+ context=None,
130
+ form=None,
131
+ branch=None,
132
+ tools=None,
133
+ return_branch=False,
134
+ reason: bool = False,
135
+ predict: bool = False,
136
+ score=None,
137
+ select=None,
138
+ plan=None,
139
+ allow_action: bool = False,
140
+ allow_extension: bool = False,
141
+ max_extension: int = None,
142
+ confidence=None,
143
+ score_num_digits=None,
144
+ score_range=None,
145
+ select_choices=None,
146
+ plan_num_step=None,
147
+ predict_num_sentences=None,
148
+ directive: str = None,
149
+ verbose=None,
150
+ **kwargs,
151
+ ):
152
+ """
153
+ Asynchronously directs the operation based on the provided parameters.
154
+
155
+ Args:
156
+ instruction (str, optional): Instruction message.
157
+ context (str, optional): Context message.
158
+ form (Form, optional): Form data.
159
+ branch (Branch, optional): Branch instance.
160
+ tools (Any, optional): Tools to be used.
161
+ return_branch (bool, optional): Flag indicating if branch should be returned.
162
+ reason (bool, optional): Flag indicating if reason should be included.
163
+ predict (bool, optional): Flag indicating if prediction should be included.
164
+ score (Any, optional): Score parameters.
165
+ select (Any, optional): Select parameters.
166
+ plan (Any, optional): Plan parameters.
167
+ allow_action (bool, optional): Flag indicating if action should be allowed.
168
+ allow_extension (bool, optional): Flag indicating if extension should be allowed.
169
+ max_extension (int, optional): Maximum extension value.
170
+ confidence (Any, optional): Confidence parameters.
171
+ score_num_digits (int, optional): Number of digits for score.
172
+ score_range (tuple, optional): Range for score.
173
+ select_choices (list, optional): Choices for selection.
174
+ plan_num_step (int, optional): Number of steps for plan.
175
+ predict_num_sentences (int, optional): Number of sentences for prediction.
176
+ directive (str, optional): Directive for the operation.
177
+ kwargs: Additional keyword arguments.
178
+
179
+ Returns:
180
+ Any: The processed response.
181
+ """
182
+ kwargs = {**retry_kwargs, **kwargs}
183
+ verbose = verbose if verbose is not None else self.verbose
184
+
185
+ if not directive:
186
+
187
+ out = await rcall(
188
+ self._direct,
189
+ instruction=instruction,
190
+ context=context,
191
+ form=form,
192
+ branch=branch,
193
+ tools=tools,
194
+ return_branch=return_branch,
195
+ reason=reason,
196
+ predict=predict,
197
+ score=score,
198
+ select=select,
199
+ plan=plan,
200
+ allow_action=allow_action,
201
+ allow_extension=allow_extension,
202
+ max_extension=max_extension,
203
+ confidence=confidence,
204
+ score_num_digits=score_num_digits,
205
+ score_range=score_range,
206
+ select_choices=select_choices,
207
+ plan_num_step=plan_num_step,
208
+ predict_num_sentences=predict_num_sentences,
209
+ verbose=verbose,
210
+ **kwargs,
211
+ )
212
+
213
+ if verbose:
214
+ print(
215
+ "\n--------------------------------------------------------------"
216
+ )
217
+ print(f"Directive successfully completed!")
218
+
219
+ return out
220
+
221
+ out = await rcall(
222
+ self._mono_direct,
223
+ directive=directive,
224
+ instruction=instruction,
225
+ context=context,
226
+ branch=branch,
227
+ tools=tools,
228
+ verbose=verbose,
229
+ **kwargs,
230
+ )
231
+
232
+ if verbose:
233
+ print("--------------------------------------------------------------")
234
+ print(f"Directive successfully completed!")
235
+
236
+ return out
237
+
238
+ async def select(self, *args, **kwargs):
239
+ """
240
+ Asynchronously performs a select operation using the _select method with
241
+ retry logic.
242
+
243
+ Args:
244
+ *args: Positional arguments to pass to the _select method.
245
+ **kwargs: Keyword arguments to pass to the _select method, including
246
+ retry configurations.
247
+
248
+ Returns:
249
+ Any: The result of the select operation.
250
+ """
251
+ from .template.select import SelectTemplate
252
+
253
+ kwargs = {**retry_kwargs, **kwargs}
254
+ kwargs["template"] = kwargs.get("template", SelectTemplate)
255
+ return await rcall(self._select, *args, **kwargs)
256
+
257
+ async def predict(self, *args, **kwargs):
258
+ """
259
+ Asynchronously performs a predict operation using the _predict method with
260
+ retry logic.
261
+
262
+ Args:
263
+ *args: Positional arguments to pass to the _predict method.
264
+ **kwargs: Keyword arguments to pass to the _predict method, including
265
+ retry configurations.
266
+
267
+ Returns:
268
+ Any: The result of the predict operation.
269
+ """
270
+ from .template.predict import PredictTemplate
271
+
272
+ kwargs = {**retry_kwargs, **kwargs}
273
+ kwargs["template"] = kwargs.get("template", PredictTemplate)
274
+ return await rcall(self._predict, *args, **kwargs)
275
+
276
+ async def score(self, *args, **kwargs):
277
+ """
278
+ Asynchronously performs a score operation using the _score method with retry logic.
279
+
280
+ Args:
281
+ *args: Positional arguments to pass to the _score method.
282
+ **kwargs: Keyword arguments to pass to the _score method, including retry configurations.
283
+
284
+ Returns:
285
+ Any: The result of the score operation.
286
+ """
287
+ from .template.score import ScoreTemplate
288
+
289
+ kwargs = {**retry_kwargs, **kwargs}
290
+ kwargs["template"] = kwargs.get("template", ScoreTemplate)
291
+ return await rcall(self._score, *args, **kwargs)
292
+
293
+ async def plan(self, *args, **kwargs):
294
+ """
295
+ Asynchronously performs a plan operation using the _plan method with retry logic.
296
+
297
+ Args:
298
+ *args: Positional arguments to pass to the _plan method.
299
+ **kwargs: Keyword arguments to pass to the _plan method, including retry configurations.
300
+
301
+ Returns:
302
+ Any: The result of the plan operation.
303
+ """
304
+ from .template.plan import PlanTemplate
305
+
306
+ kwargs = {**retry_kwargs, **kwargs}
307
+ kwargs["template"] = kwargs.get("template", PlanTemplate)
308
+ return await rcall(self._plan, *args, **kwargs)
309
+
310
+ async def _mono_direct(
311
+ self,
312
+ directive: str, # examples, "chat", "predict", "act"
313
+ instruction=None, # additional instruction
314
+ context=None, # context to perform the instruction on
315
+ system=None, # optionally swap system message
316
+ branch=None,
317
+ tools=None,
318
+ template=None,
319
+ verbose=None,
320
+ **kwargs,
321
+ ):
322
+ """
323
+ Asynchronously performs a single direct operation.
324
+
325
+ Args:
326
+ directive (str): The directive for the operation.
327
+ instruction (str, optional): Additional instruction.
328
+ context (str, optional): Context for the operation.
329
+ system (str, optional): System message.
330
+ branch (Branch, optional): Branch instance.
331
+ tools (Any, optional): Tools to be used.
332
+ template (Any, optional): Template for the operation.
333
+ kwargs: Additional keyword arguments.
334
+
335
+ Returns:
336
+ Any: The result of the direct operation.
337
+ """
338
+
339
+ if template:
340
+ kwargs["template"] = template
341
+
342
+ kwargs = {**retry_kwargs, **kwargs}
343
+ branch = branch or self.branch
344
+
345
+ if system:
346
+ branch.add_message(system=system)
347
+
348
+ if hasattr(self, strip_lower(directive)):
349
+ directive = getattr(self, strip_lower(directive))
350
+
351
+ verbose = verbose if verbose is not None else self.verbose
352
+ if verbose:
353
+ print(f"Performing directive: {directive}...")
354
+
355
+ return await directive(
356
+ context=context,
357
+ instruction=instruction,
358
+ tools=tools,
359
+ **kwargs,
360
+ )
361
+
362
+ raise ValueError(f"invalid directive: {directive}")