lionagi 0.0.312__py3-none-any.whl → 0.2.1__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 +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
@@ -1,471 +0,0 @@
1
- """
2
- This module contains the Branch class, which represents a branch in a conversation tree.
3
- """
4
-
5
- from collections import deque
6
- from typing import Any, Union, TypeVar, Callable
7
-
8
- from lionagi.libs.sys_util import PATH_TYPE
9
- from lionagi.libs import StatusTracker, BaseService, convert, dataframe
10
-
11
- from ..schema import TOOL_TYPE, Tool, DataLogger
12
- from ..tool import ToolManager, func_to_tool
13
-
14
- from ..messages import System
15
- from ..mail import BaseMail
16
-
17
- from .util import MessageUtil
18
- from .base_branch import BaseBranch
19
- from .branch_flow_mixin import BranchFlowMixin
20
-
21
- from dotenv import load_dotenv
22
-
23
- load_dotenv()
24
-
25
- T = TypeVar("T", bound=Tool)
26
-
27
-
28
- class Branch(BaseBranch, BranchFlowMixin):
29
- """
30
- Represents a branch in a conversation tree.
31
-
32
- Attributes:
33
- sender (str): The sender of the branch (default: "system").
34
- tool_manager (ToolManager): The tool manager for the branch.
35
- service (BaseService): The service associated with the branch.
36
- llmconfig (dict): The configuration for the language model.
37
- status_tracker (StatusTracker): The status tracker for the branch.
38
- pending_ins (dict): The pending incoming mails for the branch.
39
- pending_outs (deque): The pending outgoing mails for the branch.
40
-
41
- Methods:
42
- __init__(self, name=None, system=None, messages=None, service=None, sender=None,
43
- llmconfig=None, tools=None, datalogger=None, persist_path=None,
44
- tool_manager=None, **kwargs) -> None:
45
- Initializes the Branch instance.
46
-
47
- from_csv(cls, filepath, name=None, service=None, llmconfig=None, tools=None,
48
- datalogger=None, persist_path=None, tool_manager=None, read_kwargs=None,
49
- **kwargs) -> Branch:
50
- Creates a Branch instance from a CSV file.
51
-
52
- from_json_string(cls, filepath, name=None, service=None, llmconfig=None, tools=None,
53
- datalogger=None, persist_path=None, tool_manager=None, read_kwargs=None,
54
- **kwargs) -> Branch:
55
- Creates a Branch instance from a JSON string file.
56
-
57
- messages_describe(self) -> dict[str, Any]:
58
- Describes the messages in the branch.
59
-
60
- has_tools(self) -> bool:
61
- Checks if the branch has any registered tools.
62
-
63
- merge_branch(self, branch: Branch, update=True) -> None:
64
- Merges another branch into the current branch.
65
-
66
- register_tools(self, tools: Union[Tool, list[Tool]]) -> None:
67
- Registers tools in the branch's tool manager.
68
-
69
- delete_tools(self, tools: Union[T, list[T], str, list[str]], verbose=True) -> bool:
70
- Deletes tools from the branch's tool manager.
71
-
72
- send(self, recipient: str, category: str, package: Any) -> None:
73
- Sends a mail to a recipient.
74
-
75
- receive(self, sender: str, messages=True, tools=True, service=True, llmconfig=True) -> None:
76
- Receives mails from a sender and updates the branch accordingly.
77
-
78
- receive_all(self) -> None:
79
- Receives all pending mails and updates the branch accordingly.
80
-
81
- _add_service(service, llmconfig) -> tuple[BaseService, dict]:
82
- Adds a service and its configuration to the branch.
83
-
84
- _is_invoked(self) -> bool:
85
- Checks if the conversation has been invoked with an action response.
86
- """
87
-
88
- def __init__(
89
- self,
90
- name: str | None = None,
91
- system: dict | list | System | None = None,
92
- messages: dataframe.ln_DataFrame | None = None,
93
- service: BaseService | None = None,
94
- sender: str | None = None,
95
- llmconfig: dict[str, str | int | dict] | None = None,
96
- tools: list[Callable | Tool] | None = None,
97
- datalogger: None | DataLogger = None,
98
- persist_path: PATH_TYPE | None = None, # instruction_sets=None,
99
- tool_manager: ToolManager | None = None,
100
- **kwargs,
101
- ):
102
- """
103
- Initializes the Branch instance.
104
-
105
- Args:
106
- name (str): The name of the branch (optional).
107
- system (dict | list | System): The system message for the branch (optional).
108
- messages (dataframe.ln_DataFrame): The messages in the branch (optional).
109
- service (BaseService): The service associated with the branch (optional).
110
- sender (str): The sender of the branch (optional, default: "system").
111
- llmconfig (dict[str, str | int | dict]): The configuration for the language model (optional).
112
- tools (list[Callable | Tool]): The tools to register in the branch (optional).
113
- datalogger (DataLogger): The data logger for the branch (optional).
114
- persist_path (PATH_TYPE): The path to persist the branch data (optional).
115
- tool_manager (ToolManager): The tool manager for the branch (optional).
116
- **kwargs: Additional keyword arguments.
117
-
118
- Raises:
119
- TypeError: If there is an error in registering the tools.
120
- """
121
-
122
- super().__init__(
123
- messages=messages,
124
- datalogger=datalogger,
125
- persist_path=persist_path,
126
- name=name,
127
- **kwargs,
128
- )
129
-
130
- self.sender = sender or "system"
131
- self.tool_manager = tool_manager or ToolManager()
132
-
133
- if tools:
134
- try:
135
- tools_ = []
136
- _tools = convert.to_list(tools)
137
- for i in _tools:
138
- if isinstance(i, Tool):
139
- tools_.append(i)
140
- else:
141
- tools_.append(func_to_tool(i))
142
-
143
- self.register_tools(tools_)
144
- except Exception as e:
145
- raise TypeError(f"Error in registering tools: {e}") from e
146
-
147
- self.service, self.llmconfig = self._add_service(service, llmconfig)
148
- self.status_tracker = StatusTracker()
149
-
150
- # add instruction sets
151
- # self.instruction_sets = instruction_sets
152
-
153
- self.pending_ins = {}
154
- self.pending_outs = deque()
155
-
156
- if system is not None:
157
- self.add_message(system=system)
158
-
159
- @classmethod
160
- def from_csv(
161
- cls,
162
- filepath,
163
- name: str | None = None,
164
- service: BaseService | None = None,
165
- llmconfig: dict[str, str | int | dict] | None = None,
166
- tools: TOOL_TYPE | None = None,
167
- datalogger: None | DataLogger = None,
168
- persist_path: PATH_TYPE | None = None, # instruction_sets=None,
169
- tool_manager: ToolManager | None = None,
170
- read_kwargs=None,
171
- **kwargs,
172
- ) -> "Branch":
173
- """
174
- Creates a Branch instance from a CSV file.
175
-
176
- Args:
177
- filepath: The path to the CSV file.
178
- name (str): The name of the branch (optional).
179
- service (BaseService): The service associated with the branch (optional).
180
- llmconfig (dict[str, str | int | dict]): The configuration for the language model (optional).
181
- tools (TOOL_TYPE): The tools to register in the branch (optional).
182
- datalogger (DataLogger): The data logger for the branch (optional).
183
- persist_path (PATH_TYPE): The path to persist the branch data (optional).
184
- tool_manager (ToolManager): The tool manager for the branch (optional).
185
- read_kwargs: Additional keyword arguments for reading the CSV file (optional).
186
- **kwargs: Additional keyword arguments.
187
-
188
- Returns:
189
- Branch: The created Branch instance.
190
- """
191
- return cls._from_csv(
192
- filepath=filepath,
193
- read_kwargs=read_kwargs,
194
- name=name,
195
- service=service,
196
- llmconfig=llmconfig,
197
- tools=tools,
198
- datalogger=datalogger,
199
- persist_path=persist_path,
200
- # instruction_sets=instruction_sets,
201
- tool_manager=tool_manager,
202
- **kwargs,
203
- )
204
-
205
- @classmethod
206
- def from_json_string(
207
- cls,
208
- filepath,
209
- name: str | None = None,
210
- service: BaseService | None = None,
211
- llmconfig: dict[str, str | int | dict] | None = None,
212
- tools: TOOL_TYPE | None = None,
213
- datalogger: None | DataLogger = None,
214
- persist_path: PATH_TYPE | None = None, # instruction_sets=None,
215
- tool_manager: ToolManager | None = None,
216
- read_kwargs=None,
217
- **kwargs,
218
- ) -> "Branch":
219
- """
220
- Creates a Branch instance from a JSON string file.
221
-
222
- Args:
223
- filepath: The path to the JSON string file.
224
- name (str): The name of the branch (optional).
225
- service (BaseService): The service associated with the branch (optional).
226
- llmconfig (dict[str, str | int | dict]): The configuration for the language model (optional).
227
- tools (TOOL_TYPE): The tools to register in the branch (optional).
228
- datalogger (DataLogger): The data logger for the branch (optional).
229
- persist_path (PATH_TYPE): The path to persist the branch data (optional).
230
- tool_manager (ToolManager): The tool manager for the branch (optional).
231
- read_kwargs: Additional keyword arguments for reading the JSON string file (optional).
232
- **kwargs: Additional keyword arguments.
233
-
234
- Returns:
235
- Branch: The created Branch instance.
236
- """
237
- return cls._from_json(
238
- filepath=filepath,
239
- read_kwargs=read_kwargs,
240
- name=name,
241
- service=service,
242
- llmconfig=llmconfig,
243
- tools=tools,
244
- datalogger=datalogger,
245
- persist_path=persist_path,
246
- # instruction_sets=instruction_sets,
247
- tool_manager=tool_manager,
248
- **kwargs,
249
- )
250
-
251
- def messages_describe(self) -> dict[str, Any]:
252
- """
253
- Describes the messages in the branch.
254
-
255
- Returns:
256
- dict[str, Any]: A dictionary describing the messages in the branch.
257
- """
258
- return dict(
259
- total_messages=len(self.messages),
260
- summary_by_role=self._info(),
261
- summary_by_sender=self._info(use_sender=True),
262
- # instruction_sets=self.instruction_sets,
263
- registered_tools=self.tool_manager.registry,
264
- messages=[msg.to_dict() for _, msg in self.messages.iterrows()],
265
- )
266
-
267
- @property
268
- def has_tools(self) -> bool:
269
- """
270
- Checks if the branch has any registered tools.
271
-
272
- Returns:
273
- bool: True if the branch has registered tools, False otherwise.
274
- """
275
- return self.tool_manager.registry != {}
276
-
277
- # todo: also update other attributes
278
- def merge_branch(self, branch: "Branch", update: bool = True) -> None:
279
- """
280
- Merges another branch into the current branch.
281
-
282
- Args:
283
- branch (Branch): The branch to merge.
284
- update (bool): Whether to update the existing attributes or add new ones (default: True).
285
- """
286
- message_copy = branch.messages.copy()
287
- self.messages = self.messages.merge(message_copy, how="outer")
288
- self.datalogger.extend(branch.datalogger.log)
289
-
290
- if update:
291
- # self.instruction_sets.update(branch.instruction_sets)
292
- self.tool_manager.registry.update(branch.tool_manager.registry)
293
- else:
294
- for key, value in branch.instruction_sets.items():
295
- if key not in self.instruction_sets:
296
- self.instruction_sets[key] = value
297
-
298
- for key, value in branch.tool_manager.registry.items():
299
- if key not in self.tool_manager.registry:
300
- self.tool_manager.registry[key] = value
301
-
302
- # ----- tool manager methods ----- #
303
- def register_tools(
304
- self, tools: Union[Tool, list[Tool | Callable], Callable]
305
- ) -> None:
306
- """
307
- Registers tools in the branch's tool manager.
308
-
309
- Args:
310
- tools (Union[Tool, list[Tool]]): The tool(s) to register.
311
- """
312
- if not isinstance(tools, list):
313
- tools = [tools]
314
- self.tool_manager.register_tools(tools=tools)
315
-
316
- def delete_tools(
317
- self,
318
- tools: Union[T, list[T], str, list[str]],
319
- verbose: bool = True,
320
- ) -> bool:
321
- """
322
- Deletes tools from the branch's tool manager.
323
-
324
- Args:
325
- tools (Union[T, list[T], str, list[str]]): The tool(s) to delete.
326
- verbose (bool): Whether to print success/failure messages (default: True).
327
-
328
- Returns:
329
- bool: True if the tools were successfully deleted, False otherwise.
330
- """
331
- if not isinstance(tools, list):
332
- tools = [tools]
333
- if convert.is_same_dtype(tools, str):
334
- for act_ in tools:
335
- if act_ in self.tool_manager.registry:
336
- self.tool_manager.registry.pop(act_)
337
- if verbose:
338
- print("tools successfully deleted")
339
- return True
340
- elif convert.is_same_dtype(tools, Tool):
341
- for act_ in tools:
342
- if act_.schema_["function"]["name"] in self.tool_manager.registry:
343
- self.tool_manager.registry.pop(act_.schema_["function"]["name"])
344
- if verbose:
345
- print("tools successfully deleted")
346
- return True
347
- if verbose:
348
- print("tools deletion failed")
349
- return False
350
-
351
- def send(self, recipient: str, category: str, package: Any) -> None:
352
- """
353
- Sends a mail to a recipient.
354
-
355
- Args:
356
- recipient (str): The recipient of the mail.
357
- category (str): The category of the mail.
358
- package (Any): The package to send in the mail.
359
- """
360
- mail_ = BaseMail(
361
- sender=self.sender, recipient=recipient, category=category, package=package
362
- )
363
- self.pending_outs.append(mail_)
364
-
365
- def receive(
366
- self,
367
- sender: str,
368
- messages: bool = True,
369
- tools: bool = True,
370
- service: bool = True,
371
- llmconfig: bool = True,
372
- ) -> None:
373
- """
374
- Receives mails from a sender and updates the branch accordingly.
375
-
376
- Args:
377
- sender (str): The sender of the mails.
378
- messages (bool): Whether to receive message updates (default: True).
379
- tools (bool): Whether to receive tool updates (default: True).
380
- service (bool): Whether to receive service updates (default: True).
381
- llmconfig (bool): Whether to receive language model configuration updates (default: True).
382
-
383
- Raises:
384
- ValueError: If there are no packages from the specified sender.
385
- If the messages format is invalid.
386
- If the tools format is invalid.
387
- If the provider format is invalid.
388
- If the llmconfig format is invalid.
389
- """
390
- skipped_requests = deque()
391
- if sender not in self.pending_ins:
392
- raise ValueError(f"No package from {sender}")
393
- while self.pending_ins[sender]:
394
- mail_ = self.pending_ins[sender].popleft()
395
-
396
- if mail_.category == "messages" and messages:
397
- if not isinstance(mail_.package, dataframe.ln_DataFrame):
398
- raise ValueError("Invalid messages format")
399
- MessageUtil.validate_messages(mail_.package)
400
- self.messages = self.messages.merge(mail_.package, how="outer")
401
-
402
- elif mail_.category == "tools" and tools:
403
- if not isinstance(mail_.package, Tool):
404
- raise ValueError("Invalid tools format")
405
- self.tool_manager.register_tools([mail_.package])
406
-
407
- elif mail_.category == "provider" and service:
408
- from lionagi.libs.ln_api import BaseService
409
-
410
- if not isinstance(mail_.package, BaseService):
411
- raise ValueError("Invalid provider format")
412
- self.service = mail_.package
413
-
414
- elif mail_.category == "llmconfig" and llmconfig:
415
- if not isinstance(mail_.package, dict):
416
- raise ValueError("Invalid llmconfig format")
417
- self.llmconfig.update(mail_.package)
418
-
419
- else:
420
- skipped_requests.append(mail_)
421
-
422
- self.pending_ins[sender] = skipped_requests
423
- if self.pending_ins[sender] == deque():
424
- self.pending_ins.pop(sender)
425
-
426
- def receive_all(self) -> None:
427
- """
428
- Receives all pending mails and updates the branch accordingly.
429
- """
430
- for key in list(self.pending_ins.keys()):
431
- self.receive(key)
432
-
433
- @staticmethod
434
- def _add_service(service, llmconfig):
435
- from lionagi.integrations.provider.oai import OpenAIService
436
-
437
- if service is None:
438
- try:
439
- from lionagi.integrations.provider import Services
440
-
441
- service = Services.OpenAI()
442
-
443
- except:
444
- raise ValueError("No available service")
445
- if llmconfig is None:
446
- if isinstance(service, OpenAIService):
447
- from lionagi.integrations.config import oai_schema
448
-
449
- llmconfig = oai_schema["chat/completions"]["config"]
450
- else:
451
- llmconfig = {}
452
- return service, llmconfig
453
-
454
- def _is_invoked(self) -> bool:
455
- """
456
- Check if the conversation has been invoked with an action response.
457
-
458
- Returns:
459
- bool: True if the conversation has been invoked, False otherwise.
460
-
461
- """
462
- content = self.messages.iloc[-1]["content"]
463
- try:
464
- if convert.to_dict(content)["action_response"].keys() >= {
465
- "function",
466
- "arguments",
467
- "output",
468
- }:
469
- return True
470
- except Exception:
471
- return False
@@ -1,96 +0,0 @@
1
- from abc import ABC
2
- from typing import Any, Optional, Union, TypeVar
3
-
4
- from ..schema import TOOL_TYPE, Tool
5
- from ..messages import Instruction, System
6
- from ..flow.monoflow import MonoChat, MonoFollowup, MonoReAct
7
-
8
- T = TypeVar("T", bound=Tool)
9
-
10
-
11
- class BranchFlowMixin(ABC):
12
-
13
- async def chat(
14
- self,
15
- instruction: Union[Instruction, str] = None,
16
- context: Optional[Any] = None,
17
- sender: Optional[str] = None,
18
- system: Optional[Union[System, str, dict[str, Any]]] = None,
19
- tools: TOOL_TYPE = False,
20
- out: bool = True,
21
- invoke: bool = True,
22
- output_fields=None,
23
- prompt_template=None,
24
- **kwargs,
25
- ) -> Any:
26
- flow = MonoChat(self)
27
- return await flow.chat(
28
- instruction=instruction,
29
- context=context,
30
- sender=sender,
31
- system=system,
32
- tools=tools,
33
- out=out,
34
- invoke=invoke,
35
- output_fields=output_fields,
36
- prompt_template=prompt_template,
37
- **kwargs,
38
- )
39
-
40
- async def ReAct(
41
- self,
42
- instruction: Instruction | str | dict[str, dict | str],
43
- context=None,
44
- sender=None,
45
- system=None,
46
- tools=None,
47
- auto=False,
48
- num_rounds: int = 1,
49
- reason_prompt=None,
50
- action_prompt=None,
51
- output_prompt=None,
52
- **kwargs,
53
- ):
54
- flow = MonoReAct(self)
55
- return await flow.ReAct(
56
- instruction=instruction,
57
- context=context,
58
- sender=sender,
59
- system=system,
60
- tools=tools,
61
- auto=auto,
62
- num_rounds=num_rounds,
63
- reason_prompt=reason_prompt,
64
- action_prompt=action_prompt,
65
- output_prompt=output_prompt,
66
- **kwargs,
67
- )
68
-
69
- async def followup(
70
- self,
71
- instruction: Instruction | str | dict[str, dict | str],
72
- context=None,
73
- sender=None,
74
- system=None,
75
- tools=None,
76
- max_followup: int = 1,
77
- auto=False,
78
- followup_prompt=None,
79
- output_prompt=None,
80
- out=True,
81
- **kwargs,
82
- ):
83
- flow = MonoFollowup(self)
84
- return await flow.followup(
85
- instruction=instruction,
86
- context=context,
87
- sender=sender,
88
- system=system,
89
- tools=tools,
90
- max_followup=max_followup,
91
- auto=auto,
92
- followup_prompt=followup_prompt,
93
- output_prompt=output_prompt,
94
- out=out,
95
- **kwargs,
96
- )