lionagi 0.0.115__py3-none-any.whl → 0.0.204__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (123) hide show
  1. lionagi/__init__.py +1 -2
  2. lionagi/_services/__init__.py +5 -0
  3. lionagi/_services/anthropic.py +79 -0
  4. lionagi/_services/base_service.py +414 -0
  5. lionagi/_services/oai.py +98 -0
  6. lionagi/_services/openrouter.py +44 -0
  7. lionagi/_services/services.py +91 -0
  8. lionagi/_services/transformers.py +46 -0
  9. lionagi/bridge/langchain.py +26 -16
  10. lionagi/bridge/llama_index.py +50 -20
  11. lionagi/configs/oai_configs.py +2 -14
  12. lionagi/configs/openrouter_configs.py +2 -2
  13. lionagi/core/__init__.py +7 -8
  14. lionagi/core/branch/branch.py +589 -0
  15. lionagi/core/branch/branch_manager.py +139 -0
  16. lionagi/core/branch/conversation.py +484 -0
  17. lionagi/core/core_util.py +59 -0
  18. lionagi/core/flow/flow.py +19 -0
  19. lionagi/core/flow/flow_util.py +62 -0
  20. lionagi/core/instruction_set/__init__.py +0 -5
  21. lionagi/core/instruction_set/instruction_set.py +343 -0
  22. lionagi/core/messages/messages.py +176 -0
  23. lionagi/core/sessions/__init__.py +0 -5
  24. lionagi/core/sessions/session.py +428 -0
  25. lionagi/loaders/chunker.py +51 -47
  26. lionagi/loaders/load_util.py +2 -2
  27. lionagi/loaders/reader.py +45 -39
  28. lionagi/models/imodel.py +53 -0
  29. lionagi/schema/async_queue.py +158 -0
  30. lionagi/schema/base_node.py +318 -147
  31. lionagi/schema/base_tool.py +31 -1
  32. lionagi/schema/data_logger.py +74 -38
  33. lionagi/schema/data_node.py +57 -6
  34. lionagi/structures/graph.py +132 -10
  35. lionagi/structures/relationship.py +58 -20
  36. lionagi/structures/structure.py +36 -25
  37. lionagi/tests/test_utils/test_api_util.py +219 -0
  38. lionagi/tests/test_utils/test_call_util.py +785 -0
  39. lionagi/tests/test_utils/test_encrypt_util.py +323 -0
  40. lionagi/tests/test_utils/test_io_util.py +238 -0
  41. lionagi/tests/test_utils/test_nested_util.py +338 -0
  42. lionagi/tests/test_utils/test_sys_util.py +358 -0
  43. lionagi/tools/tool_manager.py +186 -0
  44. lionagi/tools/tool_util.py +266 -3
  45. lionagi/utils/__init__.py +21 -61
  46. lionagi/utils/api_util.py +359 -71
  47. lionagi/utils/call_util.py +839 -264
  48. lionagi/utils/encrypt_util.py +283 -16
  49. lionagi/utils/io_util.py +178 -93
  50. lionagi/utils/nested_util.py +672 -0
  51. lionagi/utils/pd_util.py +57 -0
  52. lionagi/utils/sys_util.py +284 -156
  53. lionagi/utils/url_util.py +55 -0
  54. lionagi/version.py +1 -1
  55. {lionagi-0.0.115.dist-info → lionagi-0.0.204.dist-info}/METADATA +21 -17
  56. lionagi-0.0.204.dist-info/RECORD +106 -0
  57. lionagi/core/conversations/__init__.py +0 -5
  58. lionagi/core/conversations/conversation.py +0 -107
  59. lionagi/core/flows/__init__.py +0 -8
  60. lionagi/core/flows/flow.py +0 -8
  61. lionagi/core/flows/flow_util.py +0 -62
  62. lionagi/core/instruction_set/instruction_sets.py +0 -7
  63. lionagi/core/sessions/sessions.py +0 -185
  64. lionagi/endpoints/__init__.py +0 -5
  65. lionagi/endpoints/audio.py +0 -17
  66. lionagi/endpoints/chatcompletion.py +0 -54
  67. lionagi/messages/__init__.py +0 -11
  68. lionagi/messages/instruction.py +0 -15
  69. lionagi/messages/message.py +0 -110
  70. lionagi/messages/response.py +0 -33
  71. lionagi/messages/system.py +0 -12
  72. lionagi/objs/__init__.py +0 -11
  73. lionagi/objs/abc_objs.py +0 -39
  74. lionagi/objs/async_queue.py +0 -135
  75. lionagi/objs/messenger.py +0 -85
  76. lionagi/objs/tool_manager.py +0 -253
  77. lionagi/services/__init__.py +0 -11
  78. lionagi/services/base_api_service.py +0 -230
  79. lionagi/services/oai.py +0 -34
  80. lionagi/services/openrouter.py +0 -31
  81. lionagi/tests/test_api_util.py +0 -46
  82. lionagi/tests/test_call_util.py +0 -115
  83. lionagi/tests/test_convert_util.py +0 -202
  84. lionagi/tests/test_encrypt_util.py +0 -33
  85. lionagi/tests/test_flat_util.py +0 -426
  86. lionagi/tests/test_sys_util.py +0 -0
  87. lionagi/utils/convert_util.py +0 -229
  88. lionagi/utils/flat_util.py +0 -599
  89. lionagi-0.0.115.dist-info/RECORD +0 -110
  90. /lionagi/{services → _services}/anyscale.py +0 -0
  91. /lionagi/{services → _services}/azure.py +0 -0
  92. /lionagi/{services → _services}/bedrock.py +0 -0
  93. /lionagi/{services → _services}/everlyai.py +0 -0
  94. /lionagi/{services → _services}/gemini.py +0 -0
  95. /lionagi/{services → _services}/gpt4all.py +0 -0
  96. /lionagi/{services → _services}/huggingface.py +0 -0
  97. /lionagi/{services → _services}/litellm.py +0 -0
  98. /lionagi/{services → _services}/localai.py +0 -0
  99. /lionagi/{services → _services}/mistralai.py +0 -0
  100. /lionagi/{services → _services}/ollama.py +0 -0
  101. /lionagi/{services → _services}/openllm.py +0 -0
  102. /lionagi/{services → _services}/perplexity.py +0 -0
  103. /lionagi/{services → _services}/predibase.py +0 -0
  104. /lionagi/{services → _services}/rungpt.py +0 -0
  105. /lionagi/{services → _services}/vllm.py +0 -0
  106. /lionagi/{services → _services}/xinference.py +0 -0
  107. /lionagi/{endpoints/assistants.py → agents/__init__.py} +0 -0
  108. /lionagi/{tools → agents}/planner.py +0 -0
  109. /lionagi/{tools → agents}/prompter.py +0 -0
  110. /lionagi/{tools → agents}/scorer.py +0 -0
  111. /lionagi/{tools → agents}/summarizer.py +0 -0
  112. /lionagi/{tools → agents}/validator.py +0 -0
  113. /lionagi/{endpoints/embeddings.py → core/branch/__init__.py} +0 -0
  114. /lionagi/{services/anthropic.py → core/branch/cluster.py} +0 -0
  115. /lionagi/{endpoints/finetune.py → core/flow/__init__.py} +0 -0
  116. /lionagi/{endpoints/image.py → core/messages/__init__.py} +0 -0
  117. /lionagi/{endpoints/moderation.py → models/__init__.py} +0 -0
  118. /lionagi/{endpoints/vision.py → models/base_model.py} +0 -0
  119. /lionagi/{objs → schema}/status_tracker.py +0 -0
  120. /lionagi/tests/{test_io_util.py → test_utils/__init__.py} +0 -0
  121. {lionagi-0.0.115.dist-info → lionagi-0.0.204.dist-info}/LICENSE +0 -0
  122. {lionagi-0.0.115.dist-info → lionagi-0.0.204.dist-info}/WHEEL +0 -0
  123. {lionagi-0.0.115.dist-info → lionagi-0.0.204.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,428 @@
1
+ import pandas as pd
2
+ from typing import Any, List, Union, Dict, Optional, Callable, Tuple
3
+ from dotenv import load_dotenv
4
+
5
+ from lionagi.schema import Tool
6
+ from lionagi._services.oai import OpenAIService
7
+ from ..messages.messages import System, Instruction
8
+ from ..branch.branch import Branch
9
+ from ..branch.branch_manager import BranchManager
10
+
11
+
12
+ load_dotenv()
13
+ OAIService = OpenAIService()
14
+
15
+ class Session:
16
+ """
17
+ Represents a session with conversation branches, tool management, and logging.
18
+
19
+ This class encapsulates the management of different conversation branches, each with its own
20
+ messages, instruction sets, and tools. It also handles logging and interactions with an external service.
21
+
22
+ Attributes:
23
+ branches (Dict[str, Branch]): A dictionary of conversation branches.
24
+ default_branch (Branch): The default branch for the session.
25
+ default_branch_name (str): The name of the default branch.
26
+ llmconfig (Dict[str, Any]): Configuration settings for the language model.
27
+ logger_ (DataLogger): Logger for session data.
28
+ service (OpenAIService): Service used for handling chat completions and other operations.
29
+ """
30
+ def __init__(
31
+ self,
32
+ system: Optional[Union[str, System]] = None,
33
+ sender: Optional[str] = None,
34
+ dir: Optional[str] = None,
35
+ llmconfig: Optional[Dict[str, Any]] = None,
36
+ service: OpenAIService = OAIService,
37
+ branches: Optional[Dict[str, Branch]] = None,
38
+ default_branch: Optional[Branch] = None,
39
+ default_branch_name: str = 'main',
40
+ ):
41
+ """
42
+ Initialize a Session object.
43
+
44
+ Args:
45
+ system (Union[str, System]): Initial system message or System object for the default branch.
46
+ dir (str, optional): Directory path for storing logs.
47
+ llmconfig (Dict[str, Any], optional): Configuration settings for the language model.
48
+ service (OpenAIService, optional): Service used for handling chat completions and other operations.
49
+ branches (Dict[str, Branch], optional): Pre-existing branches to initialize in the session.
50
+ default_branch (Branch, optional): Default branch for the session.
51
+ default_branch_name (str, optional): Name of the default branch, defaults to 'main'.
52
+ """
53
+
54
+ self.branches = branches if isinstance(branches, dict) else {}
55
+ self.default_branch = default_branch if default_branch else Branch(name=default_branch_name, service=service, llmconfig=llmconfig)
56
+ self.default_branch_name = default_branch_name
57
+ if system:
58
+ self.default_branch.add_message(system=system, sender=sender)
59
+ if self.branches:
60
+ if self.default_branch_name not in self.branches.keys():
61
+ raise ValueError('default branch name is not in imported branches')
62
+ if self.default_branch is not self.branches[self.default_branch_name]:
63
+ raise ValueError(f'default branch does not match Branch object under {self.default_branch_name}')
64
+ if not self.branches:
65
+ self.branches[self.default_branch_name] = self.default_branch
66
+ if dir:
67
+ self.default_branch.dir = dir
68
+
69
+ self.branch_manager = BranchManager(self.branches)
70
+
71
+ def new_branch(
72
+ self,
73
+ branch_name: str,
74
+ dir: Optional[str] = None,
75
+ messages: Optional[pd.DataFrame] = None,
76
+ tools: Optional[Union[Tool, List[Tool]]] = None,
77
+ system: Optional[Union[str, System]] = None,
78
+ sender: Optional[str] = None,
79
+ service: Optional[OpenAIService] = None,
80
+ llmconfig: Optional[Dict] = None,
81
+ ) -> None:
82
+ """
83
+ Create a new branch in the session.
84
+
85
+ Args:
86
+ branch_name (str): Name of the new branch.
87
+ dir (str, optional): Directory path for storing logs.
88
+ messages (Optional[pd.DataFrame]): A DataFrame containing conversation messages.
89
+ system (Union[str, System], optional): Initial system message or System object for the new branch.
90
+ tools (Optional[Union[Tool, List[Tool]]], optional): Tools to register with the new branch.
91
+ sender (Optional[str], optional): Sender of the initial system message.
92
+ service (OpenAIService, optional): Service used for the new branch if different from the session's service.
93
+ llmconfig (Dict[str, Any], optional): Configuration settings for the language model.
94
+
95
+ Raises:
96
+ ValueError: If the branch name already exists in the session.
97
+ """
98
+ if branch_name in self.branches.keys():
99
+ raise ValueError(f'Invalid new branch name {branch_name}. Already existed.')
100
+ new_ = Branch(name=branch_name, dir=dir, messages=messages, service=service, llmconfig=llmconfig)
101
+ if system:
102
+ new_.add_message(system=system, sender=sender)
103
+ if tools:
104
+ new_.register_tools(tools=tools)
105
+ self.branches[branch_name] = new_
106
+
107
+ self.branch_manager.sources[branch_name] = new_
108
+ self.branch_manager.requests[branch_name] = {}
109
+
110
+ def get_branch(
111
+ self,
112
+ branch: Optional[Union[Branch, str]] = None,
113
+ get_name: bool = False
114
+ ) -> Union[Branch, Tuple[Branch, str]]:
115
+ """
116
+ Retrieve a branch from the session.
117
+
118
+ Args:
119
+ branch (Optional[Union[Branch, str]], optional): The branch or its name to retrieve.
120
+ Defaults to the default branch if not specified.
121
+ get_name (bool, optional): If True, returns the name of the branch along with the branch object.
122
+
123
+ Returns:
124
+ Union[Branch, Tuple[Branch, str]]: The branch object or a tuple of the branch object and its name.
125
+
126
+ Raises:
127
+ ValueError: If the branch does not exist in the session.
128
+ """
129
+ if isinstance(branch, str):
130
+ if branch not in self.branches.keys():
131
+ raise ValueError(f'Invalid branch name {branch}. Not exist.')
132
+ else:
133
+ if get_name:
134
+ return self.branches[branch], branch
135
+ return self.branches[branch]
136
+
137
+ elif isinstance(branch, Branch) and branch in self.branches.values():
138
+ if get_name:
139
+ return branch, [key for key, value in self.branches.items() if value == branch][0]
140
+ return branch
141
+
142
+ elif branch is None:
143
+ if get_name:
144
+ return self.default_branch, self.default_branch_name
145
+ return self.default_branch
146
+
147
+ else:
148
+ raise ValueError(f'Invalid branch input {branch}.')
149
+
150
+ def change_default(self, branch: Union[str, Branch]) -> None:
151
+ """
152
+ Change the default branch of the session.
153
+
154
+ Args:
155
+ branch (Union[str, Branch]): The branch or its name to set as the new default.
156
+ """
157
+ branch_, name_ = self.get_branch(branch, get_name=True)
158
+ self.default_branch = branch_
159
+ self.default_branch_name = name_
160
+
161
+ def delete_branch(self, branch: Union[Branch, str], verbose: bool = True) -> bool:
162
+ """
163
+ Delete a branch from the session.
164
+
165
+ Args:
166
+ branch (Union[Branch, str]): The branch object or its name to be deleted.
167
+ verbose (bool, optional): If True, prints a confirmation message.
168
+
169
+ Returns:
170
+ bool: True if the branch is successfully deleted, False otherwise.
171
+
172
+ Raises:
173
+ ValueError: If trying to delete the current default branch.
174
+ """
175
+ _, branch_name = self.get_branch(branch, get_name=True)
176
+
177
+ if branch_name == self.default_branch_name:
178
+ raise ValueError(
179
+ f'{branch_name} is the current default branch, please switch to another branch before delete it.'
180
+ )
181
+ else:
182
+ self.branches.pop(branch_name)
183
+ # self.branch_manager.sources.pop(branch_name)
184
+ self.branch_manager.requests.pop(branch_name)
185
+ if verbose:
186
+ print(f'Branch {branch_name} is deleted.')
187
+ return True
188
+
189
+ def merge_branch(
190
+ self,
191
+ from_: Union[str, Branch],
192
+ to_: Union[str, Branch],
193
+ update: bool = True,
194
+ del_: bool = False
195
+ ) -> None:
196
+ """
197
+ Merge one branch into another within the session.
198
+
199
+ Args:
200
+ from_ (Union[str, Branch]): The branch or its name to merge from.
201
+ to_ (Union[str, Branch]): The branch or its name to merge into.
202
+ update (bool, optional): If True, updates the target branch's system message to be same as `from_`.
203
+ del_ (bool, optional): If True, deletes the 'from' branch after merging.
204
+
205
+ Raises:
206
+ ValueError: If the branch does not exist in the session.
207
+ """
208
+ from_ = self.get_branch(branch=from_)
209
+ to_, to_name = self.get_branch(branch=to_, get_name=True)
210
+ to_.merge_branch(from_, update=update)
211
+
212
+ if del_:
213
+ if from_ == self.default_branch:
214
+ self.default_branch_name = to_name
215
+ self.default_branch = to_
216
+ self.delete_branch(from_, verbose=False)
217
+
218
+ async def chat(
219
+ self,
220
+ instruction: Union[Instruction, str],
221
+ to_: Optional[Union[Branch, str]] = None,
222
+ system: Optional[Union[System, str, Dict]] = None,
223
+ context: Optional[Any] = None,
224
+ out: bool = True,
225
+ sender: Optional[str] = None,
226
+ invoke: bool = True,
227
+ tools: Union[bool, Tool, List[Tool], str, List[str]] = False,
228
+ fallback: Optional[Callable] = None,
229
+ fallback_kwargs: Dict = {},
230
+ **kwargs
231
+ ) -> None:
232
+ """
233
+ Initiate a chat with the specified branch using an instruction.
234
+
235
+ Args:
236
+ instruction (Union[Instruction, str]): The instruction or message to send.
237
+ to_ (Optional[Union[Branch, str]], optional): The target branch or its name. Default is the main branch.
238
+ system (Optional[Union[System, str, Dict]], optional): System message or data to use.
239
+ context (Optional[Any], optional): Additional context for the chat.
240
+ out (bool, optional): If True, sends the output message.
241
+ sender (Optional[str], optional): The sender's name.
242
+ invoke (bool, optional): If True, invokes tool processing.
243
+ tools (Union[bool, Tool, List[Tool], str, List[str]], optional): Tools to be used or not used.
244
+ fallback (Optional[Callable], optional): Fallback function to call in case of an exception.
245
+ fallback_kwargs (Dict, optional): Keyword arguments for the fallback function.
246
+ **kwargs: Additional keyword arguments.
247
+
248
+ Raises:
249
+ Exception: If an exception occurs in the chat process and no fallback is provided.
250
+ """
251
+ branch_ = self.get_branch(to_)
252
+ if fallback:
253
+ try:
254
+ return await branch_.chat(
255
+ instruction=instruction, system=system, context=context,
256
+ out=out, sender=sender, invoke=invoke, tools=tools, **kwargs
257
+ )
258
+ except:
259
+ return fallback(**fallback_kwargs)
260
+
261
+ return await branch_.chat(
262
+ instruction=instruction, system=system, context=context,
263
+ out=out, sender=sender, invoke=invoke, tools=tools, **kwargs)
264
+
265
+
266
+ async def auto_followup(
267
+ self,
268
+ instruction: Union[Instruction, str],
269
+ to_: Optional[Union[Branch, str]] = None,
270
+ num: int = 3,
271
+ tools: Union[bool, Tool, List[Tool], str, List[str], List[Dict]] = False,
272
+ fallback: Optional[Callable] = None,
273
+ fallback_kwargs: Dict = {},
274
+ **kwargs
275
+ ) -> None:
276
+ """
277
+ Automatically follow up on a chat conversation within a branch with multiple messages.
278
+
279
+ Args:
280
+ instruction (Union[Instruction, str]): The initial instruction or message to send.
281
+ to_ (Optional[Union[Branch, str]], optional): The target branch or its name. Default is the main branch.
282
+ num (int, optional): The number of follow-up messages to send.
283
+ tools (Union[bool, Tool, List[Tool], str, List[str], List[Dict]], optional): Tools to be used or not used.
284
+ fallback (Optional[Callable], optional): Fallback function to call in case of an exception.
285
+ fallback_kwargs (Dict, optional): Keyword arguments for the fallback function.
286
+ **kwargs: Additional keyword arguments.
287
+
288
+ Raises:
289
+ Exception: If an exception occurs in the auto-followup process and no fallback is provided.
290
+ """
291
+
292
+ branch_ = self.get_branch(to_)
293
+ if fallback:
294
+ try:
295
+ return await branch_.auto_followup(
296
+ instruction=instruction, num=num, tools=tools,**kwargs
297
+ )
298
+ except:
299
+ return fallback(**fallback_kwargs)
300
+
301
+ return await branch_.auto_followup(
302
+ instruction=instruction, num=num, tools=tools,**kwargs
303
+ )
304
+
305
+ def change_first_system_message(self, system: Union[System, str]) -> None:
306
+ """
307
+ Change the system message of the current default branch.
308
+
309
+ Args:
310
+ system (Union[System, str]): The new system message or a System object.
311
+ """
312
+ self.default_branch.change_first_system_message(system)
313
+
314
+ def collect(self, from_: Union[str, Branch, List[str], List[Branch]] = None):
315
+ """
316
+ Collect requests from specified branches or all branches if none specified.
317
+
318
+ Args:
319
+ from_ (Union[str, Branch, List[str], List[Branch]], optional): The source branch(es) from which to collect requests.
320
+ If None, data is collected from all branches. Can be a single branch or a list of branches.
321
+ """
322
+ if from_ is None:
323
+ for branch in self.branches.keys():
324
+ self.branch_manager.collect(branch)
325
+ else:
326
+ if not isinstance(from_, list):
327
+ from_ = [from_]
328
+ for branch in from_:
329
+ if isinstance(branch, Branch):
330
+ branch = branch.name
331
+ if isinstance(branch, str):
332
+ self.branch_manager.collect(branch)
333
+
334
+ def send(self, to_: Union[str, Branch, List[str], List[Branch]] = None):
335
+ """
336
+ Collect requests from specified branches or all branches if none specified.
337
+
338
+ Args:
339
+ to_ (Union[str, Branch, List[str], List[Branch]], optional): The target branch(es) to which to send requests.
340
+ If None, requests are sent to all branches. Can be a single branch or a list of branches.
341
+ """
342
+ if to_ is None:
343
+ for branch in self.branches.keys():
344
+ self.branch_manager.send(branch)
345
+ else:
346
+ if not isinstance(to_, list):
347
+ to_ = [to_]
348
+ for branch in to_:
349
+ if isinstance(branch, Branch):
350
+ branch = branch.name
351
+ if isinstance(branch, str):
352
+ self.branch_manager.send(branch)
353
+
354
+ def collect_send_all(self, receive_all=False):
355
+ """
356
+ Collect and send requests across all branches, with an option to invoke receive_all on each branch.
357
+
358
+ Args:
359
+ receive_all (bool, optional): If True, triggers the receive_all method on each branch after sending requests.
360
+ """
361
+ self.collect()
362
+ self.send()
363
+ if receive_all:
364
+ for branch in self.branches.values():
365
+ branch.receive_all()
366
+
367
+ def register_tools(self, tools: Union[Tool, List[Tool]]) -> None:
368
+ """
369
+ Registers one or more tools to the current active branch.
370
+
371
+ Args:
372
+ tools (Union[Tool, List[Tool]]): The tool or list of tools to register.
373
+ """
374
+ self.default_branch.register_tools(tools)
375
+
376
+ def delete_tool(self, name: str) -> bool:
377
+ """
378
+ Deletes a tool from the current active branch.
379
+
380
+ Args:
381
+ name (str): The name of the tool to delete.
382
+
383
+ Returns:
384
+ bool: True if the tool is deleted, False otherwise.
385
+ """
386
+ return self.default_branch.delete_tool(name)
387
+
388
+ @property
389
+ def describe(self) -> Dict[str, Any]:
390
+ """
391
+ Generates a report of the current active branch.
392
+
393
+ Returns:
394
+ Dict[str, Any]: The report of the current active branch.
395
+ """
396
+ return self.default_branch.describe
397
+
398
+ @property
399
+ def messages(self) -> pd.DataFrame:
400
+ """
401
+ Get the DataFrame containing conversation messages.
402
+
403
+ Returns:
404
+ pd.DataFrame: A DataFrame containing conversation messages.
405
+ """
406
+ return self.default_branch.messages
407
+
408
+ # def add_instruction_set(self, name: str, instruction_set: InstructionSet) -> None:
409
+ # """
410
+ # Adds an instruction set to the current active branch.
411
+ #
412
+ # Args:
413
+ # name (str): The name of the instruction set.
414
+ # instruction_set (InstructionSet): The instruction set to add.
415
+ # """
416
+ # self.default_branch.add_instruction_set(name, instruction_set)
417
+ #
418
+ # def remove_instruction_set(self, name: str) -> bool:
419
+ # """
420
+ # Removes an instruction set from the current active branch.
421
+ #
422
+ # Args:
423
+ # name (str): The name of the instruction set to remove.
424
+ #
425
+ # Returns:
426
+ # bool: True if the instruction set is removed, False otherwise.
427
+ # """
428
+ # return self.default_branch.remove_instruction_set(name)
@@ -1,24 +1,25 @@
1
- # use utils, schema and bridge
2
1
  from typing import Union, Callable
3
2
 
4
- from lionagi.utils import lcall
5
- from lionagi.schema import DataNode
6
- from lionagi.bridge import langchain_text_splitter, from_langchain, llama_index_node_parser, from_llama_index
3
+ from ..utils import lcall
4
+ from ..schema import DataNode
5
+ from ..bridge import langchain_text_splitter, from_langchain, llama_index_node_parser, from_llama_index
7
6
  from .load_util import ChunkerType, file_to_chunks
8
7
 
9
8
 
10
- # Function to convert documents to a specific format based on the chunker type
11
9
  def datanodes_convert(documents, chunker_type):
12
10
  """
13
- Converts a lionagi DataNode documents to a specific format based on the chunker type.
14
-
15
- Parameters:
16
- documents (List[DataNode]): A list of DataNode instances to be converted.
17
-
18
- chunker_type (ChunkerType): The chunker type to determine the conversion format.
19
-
11
+ Converts a list of DataNode documents to a specific format based on the chunker type.
12
+
13
+ Args:
14
+ documents: A list of DataNode instances to be converted.
15
+ chunker_type: The chunker type to determine the conversion format.
16
+
20
17
  Returns:
21
- List[DataNode]: The list of converted DataNode instances.
18
+ The list of converted DataNode instances.
19
+
20
+ Example usage:
21
+ >>> documents = [DataNode(content="Example content")]
22
+ >>> converted = datanodes_convert(documents, ChunkerType.LANGCHAIN)
22
23
  """
23
24
  for i in range(len(documents)):
24
25
  if type(documents[i]) == DataNode:
@@ -28,20 +29,23 @@ def datanodes_convert(documents, chunker_type):
28
29
  documents[i] = documents[i].to_langchain()
29
30
  return documents
30
31
 
31
- # Function to chunk text documents
32
32
  def text_chunker(documents, args, kwargs):
33
33
  """
34
34
  Chunks text documents into smaller pieces.
35
-
36
- Parameters:
37
- documents (List[DataNode]): A list of DataNode instances to be chunked.
38
35
 
39
- args (List[Any]): Positional arguments to be passed to the chunking function.
36
+ Args:
37
+ documents: A list of DataNode instances to be chunked.
38
+ args: Positional arguments to be passed to the chunking function.
39
+ kwargs: Keyword arguments to be passed to the chunking function.
40
40
 
41
- kwargs (dict): Keyword arguments to be passed to the chunking function.
42
-
43
41
  Returns:
44
- List[DataNode]: A list of chunked DataNode instances.
42
+ A list of chunked DataNode instances.
43
+
44
+ Example usage:
45
+ >>> documents = [DataNode(content="Example content")]
46
+ >>> args = []
47
+ >>> kwargs = {"chunk_size": 100}
48
+ >>> chunked_docs = text_chunker(documents, args, kwargs)
45
49
  """
46
50
  def chunk_node(node):
47
51
  chunks = file_to_chunks(node.to_dict(), *args, **kwargs)
@@ -58,17 +62,21 @@ def text_chunker(documents, args, kwargs):
58
62
  def _datanode_parser(nodes, parser):
59
63
  """
60
64
  Parses raw data into DataNode instances using the provided parser function.
61
-
62
- Parameters:
63
- nodes (List[Any]): A list of raw data to be parsed.
64
65
 
65
- parser (Callable): A function that parses raw data into DataNode instances.
66
-
66
+ Args:
67
+ nodes: A list of raw data to be parsed.
68
+ parser: A function that parses raw data into DataNode instances.
69
+
67
70
  Returns:
68
- List[DataNode]: A list of parsed DataNode instances.
69
-
71
+ A list of parsed DataNode instances.
72
+
70
73
  Raises:
71
74
  ValueError: If the parser function fails.
75
+
76
+ Example usage:
77
+ >>> raw_data = [{"content": "Example content"}]
78
+ >>> parser = lambda x: [DataNode(**d) for d in x]
79
+ >>> parsed_nodes = _datanode_parser(raw_data, parser)
72
80
  """
73
81
  try:
74
82
  nodes = parser(nodes)
@@ -87,30 +95,26 @@ def chunk(documents,
87
95
  to_datanode: Union[bool, Callable] = True):
88
96
  """
89
97
  Chunks documents using the specified chunker and chunker type.
90
-
91
- Parameters:
92
- documents (List[Any]): A list of documents to be chunked.
93
98
 
94
- chunker (Callable): The chunking function to be used.
99
+ Args:
100
+ documents: A list of documents to be chunked.
101
+ chunker: The chunking function to be used.
102
+ chunker_type: The type of the chunker. Defaults to ChunkerType.PLAIN.
103
+ chunker_args: Positional arguments for the chunker function. Defaults to an empty list.
104
+ chunker_kwargs: Keyword arguments for the chunker function. Defaults to an empty dict.
105
+ chunking_kwargs: Additional keyword arguments for the chunking process. Defaults to an empty dict.
106
+ documents_convert_func: A function to convert documents to a specific format. Defaults to None.
107
+ to_datanode: Determines whether to convert the result into DataNode instances, or a callable to convert the result. Defaults to True.
95
108
 
96
- chunker_type (ChunkerType): The type of the chunker. Defaults to ChunkerType.PLAIN.
97
-
98
- chunker_args (List[Any]): Positional arguments for the chunker function. Defaults to an empty list.
99
-
100
- chunker_kwargs (dict): Keyword arguments for the chunker function. Defaults to an empty dict.
101
-
102
- chunking_kwargs (dict): Additional keyword arguments for the chunking process. Defaults to an empty dict.
103
-
104
- documents_convert_func (Callable): A function to convert documents to a specific format. Defaults to None.
105
-
106
- to_datanode (Union[bool, Callable]): Determines whether to convert the result into DataNode instances, or
107
- a callable to convert the result. Defaults to True.
108
-
109
109
  Returns:
110
- List[DataNode]: A list of chunked DataNode instances after applying the chunker.
111
-
110
+ A list of chunked DataNode instances after applying the chunker.
111
+
112
112
  Raises:
113
113
  ValueError: If the chunker fails or an unsupported chunker type is provided.
114
+
115
+ Example usage:
116
+ >>> documents = ["Long text document...", "Another long text..."]
117
+ >>> chunked_docs = chunk(documents, text_chunker, ChunkerType.PLAIN, chunker_args=[], chunker_kwargs={"chunk_size": 100})
114
118
  """
115
119
  if chunker_type == ChunkerType.PLAIN:
116
120
  try:
@@ -4,8 +4,8 @@ from enum import Enum
4
4
  from pathlib import Path
5
5
  from typing import List, Union, Dict, Any, Tuple
6
6
 
7
- from lionagi.utils import to_list, lcall
8
- from lionagi.schema import DataNode
7
+ from ..utils import to_list, lcall
8
+ from ..schema import DataNode
9
9
 
10
10
  class ReaderType(str, Enum):
11
11
  PLAIN = 'plain'