lionagi 0.0.306__py3-none-any.whl → 0.0.308__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (78) hide show
  1. lionagi/__init__.py +2 -5
  2. lionagi/core/__init__.py +7 -5
  3. lionagi/core/agent/__init__.py +3 -0
  4. lionagi/core/agent/base_agent.py +10 -12
  5. lionagi/core/branch/__init__.py +4 -0
  6. lionagi/core/branch/base_branch.py +81 -81
  7. lionagi/core/branch/branch.py +16 -28
  8. lionagi/core/branch/branch_flow_mixin.py +3 -7
  9. lionagi/core/branch/executable_branch.py +86 -56
  10. lionagi/core/branch/util.py +77 -162
  11. lionagi/core/{flow/direct → direct}/__init__.py +1 -1
  12. lionagi/core/{flow/direct/predict.py → direct/parallel_predict.py} +39 -17
  13. lionagi/core/direct/parallel_react.py +0 -0
  14. lionagi/core/direct/parallel_score.py +0 -0
  15. lionagi/core/direct/parallel_select.py +0 -0
  16. lionagi/core/direct/parallel_sentiment.py +0 -0
  17. lionagi/core/direct/predict.py +174 -0
  18. lionagi/core/{flow/direct → direct}/react.py +2 -2
  19. lionagi/core/{flow/direct → direct}/score.py +28 -23
  20. lionagi/core/{flow/direct → direct}/select.py +48 -45
  21. lionagi/core/direct/utils.py +83 -0
  22. lionagi/core/flow/monoflow/ReAct.py +6 -5
  23. lionagi/core/flow/monoflow/__init__.py +9 -0
  24. lionagi/core/flow/monoflow/chat.py +10 -10
  25. lionagi/core/flow/monoflow/chat_mixin.py +11 -10
  26. lionagi/core/flow/monoflow/followup.py +6 -5
  27. lionagi/core/flow/polyflow/__init__.py +1 -0
  28. lionagi/core/flow/polyflow/chat.py +15 -3
  29. lionagi/core/mail/mail_manager.py +18 -19
  30. lionagi/core/mail/schema.py +5 -4
  31. lionagi/core/messages/schema.py +18 -20
  32. lionagi/core/prompt/__init__.py +0 -0
  33. lionagi/core/prompt/prompt_template.py +0 -0
  34. lionagi/core/schema/__init__.py +2 -2
  35. lionagi/core/schema/action_node.py +11 -3
  36. lionagi/core/schema/base_mixin.py +56 -59
  37. lionagi/core/schema/base_node.py +34 -37
  38. lionagi/core/schema/condition.py +24 -0
  39. lionagi/core/schema/data_logger.py +96 -99
  40. lionagi/core/schema/data_node.py +19 -19
  41. lionagi/core/schema/prompt_template.py +0 -0
  42. lionagi/core/schema/structure.py +171 -169
  43. lionagi/core/session/__init__.py +1 -3
  44. lionagi/core/session/session.py +196 -214
  45. lionagi/core/tool/tool_manager.py +95 -103
  46. lionagi/integrations/__init__.py +1 -3
  47. lionagi/integrations/bridge/langchain_/documents.py +17 -18
  48. lionagi/integrations/bridge/langchain_/langchain_bridge.py +14 -14
  49. lionagi/integrations/bridge/llamaindex_/llama_index_bridge.py +22 -22
  50. lionagi/integrations/bridge/llamaindex_/node_parser.py +12 -12
  51. lionagi/integrations/bridge/llamaindex_/reader.py +11 -11
  52. lionagi/integrations/bridge/llamaindex_/textnode.py +7 -7
  53. lionagi/integrations/config/openrouter_configs.py +0 -1
  54. lionagi/integrations/provider/oai.py +26 -26
  55. lionagi/integrations/provider/services.py +38 -38
  56. lionagi/libs/__init__.py +34 -1
  57. lionagi/libs/ln_api.py +211 -221
  58. lionagi/libs/ln_async.py +53 -60
  59. lionagi/libs/ln_convert.py +118 -120
  60. lionagi/libs/ln_dataframe.py +32 -33
  61. lionagi/libs/ln_func_call.py +334 -342
  62. lionagi/libs/ln_nested.py +99 -107
  63. lionagi/libs/ln_parse.py +161 -165
  64. lionagi/libs/sys_util.py +52 -52
  65. lionagi/tests/test_core/test_session.py +254 -266
  66. lionagi/tests/test_core/test_session_base_util.py +299 -300
  67. lionagi/tests/test_core/test_tool_manager.py +70 -74
  68. lionagi/tests/test_libs/test_nested.py +2 -7
  69. lionagi/tests/test_libs/test_parse.py +2 -2
  70. lionagi/version.py +1 -1
  71. {lionagi-0.0.306.dist-info → lionagi-0.0.308.dist-info}/METADATA +4 -2
  72. lionagi-0.0.308.dist-info/RECORD +115 -0
  73. lionagi/core/flow/direct/utils.py +0 -43
  74. lionagi-0.0.306.dist-info/RECORD +0 -106
  75. /lionagi/core/{flow/direct → direct}/sentiment.py +0 -0
  76. {lionagi-0.0.306.dist-info → lionagi-0.0.308.dist-info}/LICENSE +0 -0
  77. {lionagi-0.0.306.dist-info → lionagi-0.0.308.dist-info}/WHEEL +0 -0
  78. {lionagi-0.0.306.dist-info → lionagi-0.0.308.dist-info}/top_level.txt +0 -0
@@ -1,19 +1,15 @@
1
1
  from collections import deque
2
2
  from typing import Tuple
3
3
 
4
- from lionagi.libs.ln_api import BaseService
5
4
  from lionagi.libs.sys_util import PATH_TYPE
5
+ from lionagi.libs import BaseService, convert, dataframe
6
6
 
7
- from lionagi.libs import ln_convert as convert
8
- from lionagi.libs import ln_dataframe as dataframe
9
-
10
- from lionagi.core.schema.base_node import TOOL_TYPE, Tool
11
- from lionagi.core.schema.data_logger import DataLogger
12
- from lionagi.core.tool.tool_manager import ToolManager
13
- from lionagi.core.mail.mail_manager import MailManager
14
- from lionagi.core.messages.schema import System, Instruction
15
- from lionagi.core.branch.branch import Branch
16
- from lionagi.core.flow.polyflow.chat import PolyChat
7
+ from lionagi.core.schema import TOOL_TYPE, Tool, DataLogger
8
+ from lionagi.core.tool import ToolManager
9
+ from lionagi.core.mail import MailManager
10
+ from lionagi.core.messages import System, Instruction
11
+ from lionagi.core.branch import Branch
12
+ from lionagi.core.flow.polyflow import PolyChat
17
13
 
18
14
 
19
15
  class Session:
@@ -25,10 +21,10 @@ class Session:
25
21
  branches, configuring language learning models, managing tools, and handling session data logging.
26
22
 
27
23
  Attributes:
28
- branches (dict[str, Branch]): A dictionary of branch instances associated with the session.
29
- service (BaseService]): The external service instance associated with the | Nonesession.
30
- mail_manager (BranchManager): The manager for handling branches within the session.
31
- datalogger (Optional[Any]): The datalogger instance for session data logging.
24
+ branches (dict[str, Branch]): A dictionary of branch instances associated with the session.
25
+ service (BaseService]): The external service instance associated with the | Nonesession.
26
+ mail_manager (BranchManager): The manager for handling branches within the session.
27
+ datalogger (Optional[Any]): The datalogger instance for session data logging.
32
28
  """
33
29
 
34
30
  def __init__(
@@ -50,22 +46,22 @@ class Session:
50
46
  """Initialize a new session with optional configuration for managing conversations.
51
47
 
52
48
  Args:
53
- system (Optional[Union[str, System]]): The system message.
54
- sender (str | None): the default sender name for default branch
55
- llmconfig (dict[str, Any] | None): Configuration for language learning models.
56
- service (BaseService]): External service | Nonenstance.
57
- branches (dict[str, Branch] | None): dictionary of branch instances.
58
- default_branch (Branch | None): The default branch for the session.
59
- default_branch_name (str | None): The name of the default branch.
60
- tools (TOOL_TYPE | None): List of tools available for the session.
61
- instruction_sets (Optional[List[Instruction]]): List of instruction sets.
62
- tool_manager (Optional[Any]): Manager for handling tools.
63
- messages (Optional[List[dict[str, Any]]]): Initial list of messages.
64
- datalogger (Optional[Any]): Logger instance for the session.
65
- persist_path (str | None): Directory path for saving session data.
49
+ system (Optional[Union[str, System]]): The system message.
50
+ sender (str | None): the default sender name for default branch
51
+ llmconfig (dict[str, Any] | None): Configuration for language learning models.
52
+ service (BaseService]): External service | Nonenstance.
53
+ branches (dict[str, Branch] | None): dictionary of branch instances.
54
+ default_branch (Branch | None): The default branch for the session.
55
+ default_branch_name (str | None): The name of the default branch.
56
+ tools (TOOL_TYPE | None): List of tools available for the session.
57
+ instruction_sets (Optional[List[Instruction]]): List of instruction sets.
58
+ tool_manager (Optional[Any]): Manager for handling tools.
59
+ messages (Optional[List[dict[str, Any]]]): Initial list of messages.
60
+ datalogger (Optional[Any]): Logger instance for the session.
61
+ persist_path (str | None): Directory path for saving session data.
66
62
 
67
63
  Examples:
68
- >>> session = Session(system="you are a helpful assistant", sender="researcher")
64
+ >>> session = Session(system="you are a helpful assistant", sender="researcher")
69
65
  """
70
66
  self.branches = branches if isinstance(branches, dict) else {}
71
67
  self.service = service
@@ -100,12 +96,12 @@ class Session:
100
96
  Provides a descriptive summary of all messages in the branch.
101
97
 
102
98
  Returns:
103
- dict[str, Any]: A dictionary containing summaries of messages by role and sender, total message count,
104
- instruction sets, registered tools, and message details.
99
+ dict[str, Any]: A dictionary containing summaries of messages by role and sender, total message count,
100
+ instruction sets, registered tools, and message details.
105
101
 
106
102
  Examples:
107
- >>> session.messages_describe
108
- {'total_messages': 100, 'by_sender': {'User123': 60, 'Bot': 40}}
103
+ >>> session.messages_describe
104
+ {'total_messages': 100, 'by_sender': {'User123': 60, 'Bot': 40}}
109
105
  """
110
106
  return self.default_branch.messages_describe
111
107
 
@@ -115,11 +111,11 @@ class Session:
115
111
  Checks if there are any tools registered in the tool manager.
116
112
 
117
113
  Returns:
118
- bool: True if there are tools registered, False otherwise.
114
+ bool: True if there are tools registered, False otherwise.
119
115
 
120
116
  Examples:
121
- >>> session.has_tools
122
- True
117
+ >>> session.has_tools
118
+ True
123
119
  """
124
120
  return self.default_branch.has_tools
125
121
 
@@ -129,7 +125,7 @@ class Session:
129
125
  Retrieves the last message from the conversation.
130
126
 
131
127
  Returns:
132
- pd.Series: The last message as a pandas Series.
128
+ pd.Series: The last message as a pandas Series.
133
129
  """
134
130
  return self.default_branch.last_message
135
131
 
@@ -139,7 +135,7 @@ class Session:
139
135
  Retrieves the first system message from the conversation.
140
136
 
141
137
  Returns:
142
- pd.Series: The first system message as a pandas Series.
138
+ pd.Series: The first system message as a pandas Series.
143
139
  """
144
140
  return self.default_branch.first_system
145
141
 
@@ -149,7 +145,7 @@ class Session:
149
145
  Retrieves the last response message from the conversation.
150
146
 
151
147
  Returns:
152
- pd.Series: The last response message as a pandas Series.
148
+ pd.Series: The last response message as a pandas Series.
153
149
  """
154
150
  return self.default_branch.last_response
155
151
 
@@ -159,7 +155,7 @@ class Session:
159
155
  Retrieves the content of the last response message from the conversation.
160
156
 
161
157
  Returns:
162
- dict: The content of the last response message as a dictionary
158
+ dict: The content of the last response message as a dictionary
163
159
  """
164
160
  return self.default_branch.last_response_content
165
161
 
@@ -169,7 +165,7 @@ class Session:
169
165
  Retrieves all tool request messages from the conversation.
170
166
 
171
167
  Returns:
172
- dataframe.ln_DataFrame: A DataFrame containing all tool request messages.
168
+ dataframe.ln_DataFrame: A DataFrame containing all tool request messages.
173
169
  """
174
170
  return self.default_branch.tool_request
175
171
 
@@ -179,7 +175,7 @@ class Session:
179
175
  Retrieves all tool response messages from the conversation.
180
176
 
181
177
  Returns:
182
- dataframe.ln_DataFrame: A DataFrame containing all tool response messages.
178
+ dataframe.ln_DataFrame: A DataFrame containing all tool response messages.
183
179
  """
184
180
  return self.default_branch.tool_response
185
181
 
@@ -189,7 +185,7 @@ class Session:
189
185
  Retrieves all response messages from the conversation.
190
186
 
191
187
  Returns:
192
- dataframe.ln_DataFrame: A DataFrame containing all response messages.
188
+ dataframe.ln_DataFrame: A DataFrame containing all response messages.
193
189
  """
194
190
  return self.default_branch.responses
195
191
 
@@ -199,7 +195,7 @@ class Session:
199
195
  Retrieves all assistant responses from the conversation, excluding tool requests and responses.
200
196
 
201
197
  Returns:
202
- dataframe.ln_DataFrame: A DataFrame containing assistant responses excluding tool requests and responses.
198
+ dataframe.ln_DataFrame: A DataFrame containing assistant responses excluding tool requests and responses.
203
199
  """
204
200
  return self.default_branch.assistant_responses
205
201
 
@@ -209,7 +205,7 @@ class Session:
209
205
  Get a summary of the conversation messages categorized by role.
210
206
 
211
207
  Returns:
212
- dict[str, int]: A dictionary with keys as message roles and values as counts.
208
+ dict[str, int]: A dictionary with keys as message roles and values as counts.
213
209
  """
214
210
 
215
211
  return self.default_branch.info
@@ -220,7 +216,7 @@ class Session:
220
216
  Provides a descriptive summary of the conversation, including total message count and summary by sender.
221
217
 
222
218
  Returns:
223
- dict[str, Any]: A dictionary containing the total number of messages and a summary categorized by sender.
219
+ dict[str, Any]: A dictionary containing the total number of messages and a summary categorized by sender.
224
220
  """
225
221
  return self.default_branch.sender_info
226
222
 
@@ -236,8 +232,7 @@ class Session:
236
232
  llmconfig: dict[str, str | int | dict] | None = None,
237
233
  service: BaseService = None,
238
234
  default_branch_name: str = "main",
239
- tools: TOOL_TYPE = False,
240
- # instruction_sets=None,
235
+ tools: TOOL_TYPE = False, # instruction_sets=None,
241
236
  tool_manager=None,
242
237
  **kwargs,
243
238
  ) -> "Session":
@@ -245,24 +240,24 @@ class Session:
245
240
  Creates a Session instance from a CSV file containing messages.
246
241
 
247
242
  Args:
248
- filepath (str): Path to the CSV file.
249
- name (str | None): Name of the branch, default is None.
250
- instruction_sets (Optional[dict[str, InstructionSet]]): Instruction sets, default is None.
251
- tool_manager (Optional[ToolManager]): Tool manager for the branch, default is None.
252
- service (BaseService]): External service for the branch, default | Noneis None.
253
- llmconfig (Optional[dict]): Configuration for language learning models, default is None.
254
- tools (TOOL_TYPE | None): Initial list of tools to register, default is None.
255
- **kwargs: Additional keyword arguments for pd.read_csv().
243
+ filepath (str): Path to the CSV file.
244
+ name (str | None): Name of the branch, default is None.
245
+ instruction_sets (Optional[dict[str, InstructionSet]]): Instruction sets, default is None.
246
+ tool_manager (Optional[ToolManager]): Tool manager for the branch, default is None.
247
+ service (BaseService]): External service for the branch, default | Noneis None.
248
+ llmconfig (Optional[dict]): Configuration for language learning models, default is None.
249
+ tools (TOOL_TYPE | None): Initial list of tools to register, default is None.
250
+ **kwargs: Additional keyword arguments for pd.read_csv().
256
251
 
257
252
  Returns:
258
- Branch: A new Branch instance created from the CSV data.
253
+ Branch: A new Branch instance created from the CSV data.
259
254
 
260
255
  Examples:
261
- >>> branch = Branch.from_csv("path/to/messages.csv", name="ImportedBranch")
256
+ >>> branch = Branch.from_csv("path/to/messages.csv", name="ImportedBranch")
262
257
  """
263
258
  df = dataframe.read_csv(filepath, **kwargs)
264
259
 
265
- self = cls(
260
+ return cls(
266
261
  system=system,
267
262
  sender=sender,
268
263
  llmconfig=llmconfig,
@@ -274,8 +269,6 @@ class Session:
274
269
  **kwargs,
275
270
  )
276
271
 
277
- return self
278
-
279
272
  @classmethod
280
273
  def from_json(
281
274
  cls,
@@ -285,8 +278,7 @@ class Session:
285
278
  llmconfig: dict[str, str | int | dict] | None = None,
286
279
  service: BaseService = None,
287
280
  default_branch_name: str = "main",
288
- tools: TOOL_TYPE = False,
289
- # instruction_sets=None,
281
+ tools: TOOL_TYPE = False, # instruction_sets=None,
290
282
  tool_manager=None,
291
283
  **kwargs,
292
284
  ) -> "Session":
@@ -294,36 +286,33 @@ class Session:
294
286
  Creates a Branch instance from a JSON file containing messages.
295
287
 
296
288
  Args:
297
- filepath (str): Path to the JSON file.
298
- name (str | None): Name of the branch, default is None.
299
- instruction_sets (Optional[dict[str, InstructionSet]]): Instruction sets, default is None.
300
- tool_manager (Optional[ToolManager]): Tool manager for the branch, default is None.
301
- service (BaseService]): External service for the branch, default | Noneis None.
302
- llmconfig (Optional[dict]): Configuration for language learning models, default is None.
303
- **kwargs: Additional keyword arguments for pd.read_json().
289
+ filepath (str): Path to the JSON file.
290
+ name (str | None): Name of the branch, default is None.
291
+ instruction_sets (Optional[dict[str, InstructionSet]]): Instruction sets, default is None.
292
+ tool_manager (Optional[ToolManager]): Tool manager for the branch, default is None.
293
+ service (BaseService]): External service for the branch, default | Noneis None.
294
+ llmconfig (Optional[dict]): Configuration for language learning models, default is None.
295
+ **kwargs: Additional keyword arguments for pd.read_json().
304
296
 
305
297
  Returns:
306
- Branch: A new Branch instance created from the JSON data.
298
+ Branch: A new Branch instance created from the JSON data.
307
299
 
308
300
  Examples:
309
- >>> branch = Branch.from_json_string("path/to/messages.json", name="JSONBranch")
301
+ >>> branch = Branch.from_json_string("path/to/messages.json", name="JSONBranch")
310
302
  """
311
303
  df = dataframe.read_json(filepath, **kwargs)
312
- self = cls(
304
+ return cls(
313
305
  system=system,
314
306
  sender=sender,
315
307
  llmconfig=llmconfig,
316
308
  service=service,
317
309
  default_branch_name=default_branch_name,
318
- tools=tools,
319
- # instruction_sets=instruction_sets,
310
+ tools=tools, # instruction_sets=instruction_sets,
320
311
  tool_manager=tool_manager,
321
312
  messages=df,
322
313
  **kwargs,
323
314
  )
324
315
 
325
- return self
326
-
327
316
  def to_csv_file(
328
317
  self,
329
318
  filename: str = "messages.csv",
@@ -338,17 +327,17 @@ class Session:
338
327
  Saves the branch's messages to a CSV file.
339
328
 
340
329
  Args:
341
- filename (str): The name of the output CSV file, default is 'messages.csv'.
342
- dir_exist_ok (bool): If True, does not raise an error if the directory already exists, default is True.
343
- timestamp (bool): If True, appends a timestamp to the filename, default is True.
344
- time_prefix (bool): If True, adds a timestamp prefix to the filename, default is False.
345
- verbose (bool): If True, prints a message upon successful save, default is True.
346
- clear (bool): If True, clears the messages after saving, default is True.
347
- **kwargs: Additional keyword arguments for DataFrame.to_csv().
330
+ filename (str): The name of the output CSV file, default is 'messages.csv'.
331
+ dir_exist_ok (bool): If True, does not raise an error if the directory already exists, default is True.
332
+ timestamp (bool): If True, appends a timestamp to the filename, default is True.
333
+ time_prefix (bool): If True, adds a timestamp prefix to the filename, default is False.
334
+ verbose (bool): If True, prints a message upon successful save, default is True.
335
+ clear (bool): If True, clears the messages after saving, default is True.
336
+ **kwargs: Additional keyword arguments for DataFrame.to_csv().
348
337
 
349
338
  Examples:
350
- >>> branch.to_csv_file("exported_messages.csv")
351
- >>> branch.to_csv_file("timed_export.csv", timestamp=True, time_prefix=True)
339
+ >>> branch.to_csv_file("exported_messages.csv")
340
+ >>> branch.to_csv_file("timed_export.csv", timestamp=True, time_prefix=True)
352
341
  """
353
342
  for name, branch in self.branches.items():
354
343
  f_name = f"{name}_{filename}"
@@ -376,17 +365,17 @@ class Session:
376
365
  Saves the branch's messages to a JSON file.
377
366
 
378
367
  Args:
379
- filename (str): The name of the output JSON file, default is 'messages.json'.
380
- dir_exist_ok (bool): If True, does not raise an error if the directory already exists, default is True.
381
- timestamp (bool): If True, appends a timestamp to the filename, default is True.
382
- time_prefix (bool): If True, adds a timestamp prefix to the filename, default is False.
383
- verbose (bool): If True, prints a message upon successful save, default is True.
384
- clear (bool): If True, clears the messages after saving, default is True.
385
- **kwargs: Additional keyword arguments for DataFrame.to_json().
368
+ filename (str): The name of the output JSON file, default is 'messages.json'.
369
+ dir_exist_ok (bool): If True, does not raise an error if the directory already exists, default is True.
370
+ timestamp (bool): If True, appends a timestamp to the filename, default is True.
371
+ time_prefix (bool): If True, adds a timestamp prefix to the filename, default is False.
372
+ verbose (bool): If True, prints a message upon successful save, default is True.
373
+ clear (bool): If True, clears the messages after saving, default is True.
374
+ **kwargs: Additional keyword arguments for DataFrame.to_json().
386
375
 
387
376
  Examples:
388
- >>> branch.to_json_file("exported_messages.json")
389
- >>> branch.to_json_file("timed_export.json", timestamp=True, time_prefix=True)
377
+ >>> branch.to_json_file("exported_messages.json")
378
+ >>> branch.to_json_file("timed_export.json", timestamp=True, time_prefix=True)
390
379
  """
391
380
 
392
381
  for name, branch in self.branches.items():
@@ -418,17 +407,17 @@ class Session:
418
407
  to a CSV file for analysis or record-keeping.
419
408
 
420
409
  Args:
421
- filename (str): The name of the output CSV file. Defaults to 'log.csv'.
422
- dir_exist_ok (bool): If True, will not raise an error if the directory already exists. Defaults to True.
423
- timestamp (bool): If True, appends a timestamp to the filename for uniqueness. Defaults to True.
424
- time_prefix (bool): If True, adds a timestamp prefix to the filename. Defaults to False.
425
- verbose (bool): If True, prints a success message upon completion. Defaults to True.
426
- clear (bool): If True, clears the log after saving. Defaults to True.
427
- **kwargs: Additional keyword arguments for `DataFrame.to_csv()`.
410
+ filename (str): The name of the output CSV file. Defaults to 'log.csv'.
411
+ dir_exist_ok (bool): If True, will not raise an error if the directory already exists. Defaults to True.
412
+ timestamp (bool): If True, appends a timestamp to the filename for uniqueness. Defaults to True.
413
+ time_prefix (bool): If True, adds a timestamp prefix to the filename. Defaults to False.
414
+ verbose (bool): If True, prints a success message upon completion. Defaults to True.
415
+ clear (bool): If True, clears the log after saving. Defaults to True.
416
+ **kwargs: Additional keyword arguments for `DataFrame.to_csv()`.
428
417
 
429
418
  Examples:
430
- >>> branch.log_to_csv("branch_log.csv")
431
- >>> branch.log_to_csv("detailed_branch_log.csv", timestamp=True, verbose=True)
419
+ >>> branch.log_to_csv("branch_log.csv")
420
+ >>> branch.log_to_csv("detailed_branch_log.csv", timestamp=True, verbose=True)
432
421
  """
433
422
  for name, branch in self.branches.items():
434
423
  f_name = f"{name}_{filename}"
@@ -459,17 +448,17 @@ class Session:
459
448
  and services that consume JSON.
460
449
 
461
450
  Args:
462
- filename (str): The name of the output JSON file. Defaults to 'log.json'.
463
- dir_exist_ok (bool): If directory existence should not raise an error. Defaults to True.
464
- timestamp (bool): If True, appends a timestamp to the filename. Defaults to True.
465
- time_prefix (bool): If True, adds a timestamp prefix to the filename. Defaults to False.
466
- verbose (bool): If True, prints a success message upon completion. Defaults to True.
467
- clear (bool): If True, clears the log after saving. Defaults to True.
468
- **kwargs: Additional keyword arguments for `DataFrame.to_json()`.
451
+ filename (str): The name of the output JSON file. Defaults to 'log.json'.
452
+ dir_exist_ok (bool): If directory existence should not raise an error. Defaults to True.
453
+ timestamp (bool): If True, appends a timestamp to the filename. Defaults to True.
454
+ time_prefix (bool): If True, adds a timestamp prefix to the filename. Defaults to False.
455
+ verbose (bool): If True, prints a success message upon completion. Defaults to True.
456
+ clear (bool): If True, clears the log after saving. Defaults to True.
457
+ **kwargs: Additional keyword arguments for `DataFrame.to_json()`.
469
458
 
470
459
  Examples:
471
- >>> branch.log_to_json("branch_log.json")
472
- >>> branch.log_to_json("detailed_branch_log.json", verbose=True, timestamp=True)
460
+ >>> branch.log_to_json("branch_log.json")
461
+ >>> branch.log_to_json("detailed_branch_log.json", verbose=True, timestamp=True)
473
462
  """
474
463
  for name, branch in self.branches.items():
475
464
  f_name = f"{name}_{filename}"
@@ -507,12 +496,12 @@ class Session:
507
496
  This method prepares the messages for chat completion, sends the request to the configured service, and handles the response. The method supports additional keyword arguments that are passed directly to the service.
508
497
 
509
498
  Args:
510
- sender (str | None): The name of the sender to be included in the chat completion request. Defaults to None.
511
- with_sender (bool): If True, includes the sender's name in the messages. Defaults to False.
512
- **kwargs: Arbitrary keyword arguments passed directly to the chat completion service.
499
+ sender (str | None): The name of the sender to be included in the chat completion request. Defaults to None.
500
+ with_sender (bool): If True, includes the sender's name in the messages. Defaults to False.
501
+ **kwargs: Arbitrary keyword arguments passed directly to the chat completion service.
513
502
 
514
503
  Examples:
515
- >>> await branch.call_chatcompletion()
504
+ >>> await branch.call_chatcompletion()
516
505
  """
517
506
  branch = self.get_branch(branch)
518
507
  await branch.call_chatcompletion(
@@ -538,18 +527,18 @@ class Session:
538
527
  a chat conversation with LLM, processing instructions and system messages, optionally invoking tools.
539
528
 
540
529
  Args:
541
- branch: The Branch instance to perform chat operations.
542
- instruction (dict | list | Instruction | str): The instruction for the chat.
543
- context (Optional[Any]): Additional context for the chat.
544
- sender (str | None): The sender of the chat message.
545
- system (Optional[Union[System, str, dict[str, Any]]]): System message to be processed.
546
- tools (Union[bool, Tool, List[Tool], str, List[str]]): Specifies tools to be invoked.
547
- out (bool): If True, outputs the chat response.
548
- invoke (bool): If True, invokes tools as part of the chat.
549
- **kwargs: Arbitrary keyword arguments for chat completion.
530
+ branch: The Branch instance to perform chat operations.
531
+ instruction (dict | list | Instruction | str): The instruction for the chat.
532
+ context (Optional[Any]): Additional context for the chat.
533
+ sender (str | None): The sender of the chat message.
534
+ system (Optional[Union[System, str, dict[str, Any]]]): System message to be processed.
535
+ tools (Union[bool, Tool, List[Tool], str, List[str]]): Specifies tools to be invoked.
536
+ out (bool): If True, outputs the chat response.
537
+ invoke (bool): If True, invokes tools as part of the chat.
538
+ **kwargs: Arbitrary keyword arguments for chat completion.
550
539
 
551
540
  Examples:
552
- >>> await ChatFlow.chat(branch, "Ask about user preferences")
541
+ >>> await ChatFlow.chat(branch, "Ask about user preferences")
553
542
  """
554
543
 
555
544
  branch = self.get_branch(branch)
@@ -584,17 +573,17 @@ class Session:
584
573
  Performs a reason-tool cycle with optional tool invocation over multiple rounds.
585
574
 
586
575
  Args:
587
- branch: The Branch instance to perform ReAct operations.
588
- instruction (dict | list | Instruction | str): Initial instruction for the cycle.
589
- context: Context relevant to the instruction.
590
- sender (str | None): Identifier for the message sender.
591
- system: Initial system message or configuration.
592
- tools: Tools to be registered or used during the cycle.
593
- num_rounds (int): Number of reason-tool cycles to perform.
594
- **kwargs: Additional keyword arguments for customization.
576
+ branch: The Branch instance to perform ReAct operations.
577
+ instruction (dict | list | Instruction | str): Initial instruction for the cycle.
578
+ context: Context relevant to the instruction.
579
+ sender (str | None): Identifier for the message sender.
580
+ system: Initial system message or configuration.
581
+ tools: Tools to be registered or used during the cycle.
582
+ num_rounds (int): Number of reason-tool cycles to perform.
583
+ **kwargs: Additional keyword arguments for customization.
595
584
 
596
585
  Examples:
597
- >>> await ChatFlow.ReAct(branch, "Analyze user feedback", num_rounds=2)
586
+ >>> await ChatFlow.ReAct(branch, "Analyze user feedback", num_rounds=2)
598
587
  """
599
588
  branch = self.get_branch(branch)
600
589
 
@@ -631,18 +620,18 @@ class Session:
631
620
  Automatically performs follow-up tools based on chat intertools and tool invocations.
632
621
 
633
622
  Args:
634
- branch: The Branch instance to perform follow-up operations.
635
- instruction (dict | list | Instruction | str): The initial instruction for follow-up.
636
- context: Context relevant to the instruction.
637
- sender (str | None): Identifier for the message sender.
638
- system: Initial system message or configuration.
639
- tools: Specifies tools to be considered for follow-up tools.
640
- max_followup (int): Maximum number of follow-up chats allowed.
641
- out (bool): If True, outputs the result of the follow-up tool.
642
- **kwargs: Additional keyword arguments for follow-up customization.
623
+ branch: The Branch instance to perform follow-up operations.
624
+ instruction (dict | list | Instruction | str): The initial instruction for follow-up.
625
+ context: Context relevant to the instruction.
626
+ sender (str | None): Identifier for the message sender.
627
+ system: Initial system message or configuration.
628
+ tools: Specifies tools to be considered for follow-up tools.
629
+ max_followup (int): Maximum number of follow-up chats allowed.
630
+ out (bool): If True, outputs the result of the follow-up tool.
631
+ **kwargs: Additional keyword arguments for follow-up customization.
643
632
 
644
633
  Examples:
645
- >>> await ChatFlow.auto_followup(branch, "Finalize report", max_followup=2)
634
+ >>> await ChatFlow.auto_followup(branch, "Finalize report", max_followup=2)
646
635
  """
647
636
  branch = self.get_branch(branch)
648
637
  return await branch.followup(
@@ -672,14 +661,17 @@ class Session:
672
661
  invoke: bool = True,
673
662
  output_fields=None,
674
663
  persist_path=None,
675
- branch_config={},
664
+ branch_config=None,
676
665
  explode=False,
666
+ include_mapping=False,
677
667
  **kwargs,
678
668
  ):
679
669
  """
680
670
  parallel chat
681
671
  """
682
672
 
673
+ if branch_config is None:
674
+ branch_config = {}
683
675
  flow = PolyChat(self)
684
676
 
685
677
  return await flow.parallel_chat(
@@ -696,6 +688,7 @@ class Session:
696
688
  persist_path=persist_path,
697
689
  branch_config=branch_config,
698
690
  explode=explode,
691
+ include_mapping=include_mapping,
699
692
  **kwargs,
700
693
  )
701
694
 
@@ -714,21 +707,21 @@ class Session:
714
707
  """Create a new branch with the specified configurations.
715
708
 
716
709
  Args:
717
- branch_name (str | None): Name of the new branch.
718
- system (Optional[Union[System, str]]): System or context identifier for the new branch.
719
- sender (str | None): Default sender identifier for the new branch.
720
- messages (Optional[dataframe.ln_DataFrame]): Initial set of messages for the new branch.
721
- instruction_sets (Optional[Any]): Instruction sets for the new branch.
722
- tool_manager (Optional[Any]): Tool manager for handling tools in the new branch.
723
- service (BaseService]): External service instance for the ne | None branch.
724
- llmconfig (dict[str, Any] | None): Configuration for language learning models in the new branch.
725
- tools (TOOL_TYPE | None): List of tools available for the new branch.
710
+ branch_name (str | None): Name of the new branch.
711
+ system (Optional[Union[System, str]]): System or context identifier for the new branch.
712
+ sender (str | None): Default sender identifier for the new branch.
713
+ messages (Optional[dataframe.ln_DataFrame]): Initial set of messages for the new branch.
714
+ instruction_sets (Optional[Any]): Instruction sets for the new branch.
715
+ tool_manager (Optional[Any]): Tool manager for handling tools in the new branch.
716
+ service (BaseService]): External service instance for the ne | None branch.
717
+ llmconfig (dict[str, Any] | None): Configuration for language learning models in the new branch.
718
+ tools (TOOL_TYPE | None): List of tools available for the new branch.
726
719
 
727
720
  Raises:
728
- ValueError: If the branch name already exists.
721
+ ValueError: If the branch name already exists.
729
722
 
730
723
  Examples:
731
- >>> session.new_branch("new_branch_name")
724
+ >>> session.new_branch("new_branch_name")
732
725
  """
733
726
  if branch_name in self.branches.keys():
734
727
  raise ValueError(
@@ -758,36 +751,27 @@ class Session:
758
751
  Retrieve a branch by name or instance.
759
752
 
760
753
  Args:
761
- branch (Optional[Branch | str]): The branch name or instance to retrieve.
762
- get_name (bool): If True, returns a tuple of the branch instance and its name.
754
+ branch (Optional[Branch | str]): The branch name or instance to retrieve.
755
+ get_name (bool): If True, returns a tuple of the branch instance and its name.
763
756
 
764
757
  Returns:
765
- Union[Branch, Tuple[Branch, str]]: The branch instance or a tuple of the branch instance and its name.
758
+ Union[Branch, Tuple[Branch, str]]: The branch instance or a tuple of the branch instance and its name.
766
759
 
767
760
  Raises:
768
- ValueError: If the branch name does not exist or the branch input is invalid.
761
+ ValueError: If the branch name does not exist or the branch input is invalid.
769
762
 
770
763
  Examples:
771
- >>> branch_instance = session.get_branch("existing_branch_name")
772
- >>> branch_instance, branch_name = session.get_branch("existing_branch_name", get_name=True)
764
+ >>> branch_instance = session.get_branch("existing_branch_name")
765
+ >>> branch_instance, branch_name = session.get_branch("existing_branch_name", get_name=True)
773
766
  """
774
767
  if isinstance(branch, str):
775
768
  if branch not in self.branches.keys():
776
769
  raise ValueError(f"Invalid branch name {branch}. Not exist.")
777
- else:
778
- if get_name:
779
- return self.branches[branch], branch
780
- return self.branches[branch]
781
-
770
+ return (
771
+ (self.branches[branch], branch) if get_name else self.branches[branch]
772
+ )
782
773
  elif isinstance(branch, Branch) and branch in self.branches.values():
783
- if get_name:
784
- return (
785
- branch,
786
- # [key for key, value in self.branches.items() if value == branch][0],
787
- branch.name,
788
- )
789
- return branch
790
-
774
+ return (branch, branch.name) if get_name else branch
791
775
  elif branch is None:
792
776
  if get_name:
793
777
  return self.default_branch, self.default_branch_name
@@ -800,10 +784,10 @@ class Session:
800
784
  """Change the default branch of the session.
801
785
 
802
786
  Args:
803
- branch (str | Branch): The branch name or instance to set as the new default.
787
+ branch (str | Branch): The branch name or instance to set as the new default.
804
788
 
805
789
  Examples:
806
- >>> session.change_default_branch("new_default_branch")
790
+ >>> session.change_default_branch("new_default_branch")
807
791
  """
808
792
  branch_, name_ = self.get_branch(branch, get_name=True)
809
793
  self.default_branch = branch_
@@ -813,17 +797,17 @@ class Session:
813
797
  """Delete a branch from the session.
814
798
 
815
799
  Args:
816
- branch (Branch | str): The branch name or instance to delete.
817
- verbose (bool): If True, prints a message upon deletion.
800
+ branch (Branch | str): The branch name or instance to delete.
801
+ verbose (bool): If True, prints a message upon deletion.
818
802
 
819
803
  Returns:
820
- bool: True if the branch was successfully deleted.
804
+ bool: True if the branch was successfully deleted.
821
805
 
822
806
  Raises:
823
- ValueError: If attempting to delete the current default branch.
807
+ ValueError: If attempting to delete the current default branch.
824
808
 
825
809
  Examples:
826
- >>> session.delete_branch("branch_to_delete")
810
+ >>> session.delete_branch("branch_to_delete")
827
811
  """
828
812
  _, branch_name = self.get_branch(branch, get_name=True)
829
813
 
@@ -831,13 +815,12 @@ class Session:
831
815
  raise ValueError(
832
816
  f"{branch_name} is the current default branch, please switch to another branch before delete it."
833
817
  )
834
- else:
835
- self.branches.pop(branch_name)
836
- # self.mail_manager.sources.pop(branch_name)
837
- self.mail_manager.mails.pop(branch_name)
838
- if verbose:
839
- print(f"Branch {branch_name} is deleted.")
840
- return True
818
+ self.branches.pop(branch_name)
819
+ # self.mail_manager.sources.pop(branch_name)
820
+ self.mail_manager.mails.pop(branch_name)
821
+ if verbose:
822
+ print(f"Branch {branch_name} is deleted.")
823
+ return True
841
824
 
842
825
  def merge_branch(
843
826
  self,
@@ -849,13 +832,13 @@ class Session:
849
832
  """Merge messages and settings from one branch to another.
850
833
 
851
834
  Args:
852
- from_ (str | Branch): The source branch name or instance.
853
- to_branch (str | Branch): The target branch name or instance where the merge will happen.
854
- update (bool): If True, updates the target branch with the source branch's settings.
855
- del_ (bool): If True, deletes the source branch after merging.
835
+ from_ (str | Branch): The source branch name or instance.
836
+ to_branch (str | Branch): The target branch name or instance where the merge will happen.
837
+ update (bool): If True, updates the target branch with the source branch's settings.
838
+ del_ (bool): If True, deletes the source branch after merging.
856
839
 
857
840
  Examples:
858
- >>> session.merge_branch("source_branch", "target_branch", del_=True)
841
+ >>> session.merge_branch("source_branch", "target_branch", del_=True)
859
842
  """
860
843
  from_ = self.get_branch(branch=from_)
861
844
  to_branch, to_name = self.get_branch(branch=to_branch, get_name=True)
@@ -879,14 +862,14 @@ class Session:
879
862
  This method is intended to aggregate data or requests from one or more branches for processing or analysis.
880
863
 
881
864
  Args:
882
- from_ (Optional[Union[str, Branch, List[str | Branch]]]): The branch(es) from which to collect requests.
883
- Can be a single branch name, a single branch instance, a list of branch names, a list of branch instances, or None.
884
- If None, requests are collected from all branches.
865
+ from_ (Optional[Union[str, Branch, List[str | Branch]]]): The branch(es) from which to collect requests.
866
+ Can be a single branch name, a single branch instance, a list of branch names, a list of branch instances, or None.
867
+ If None, requests are collected from all branches.
885
868
 
886
869
  Examples:
887
- >>> session.collect("branch_name")
888
- >>> session.collect([branch_instance_1, "branch_name_2"])
889
- >>> session.collect() # Collects from all branches
870
+ >>> session.collect("branch_name")
871
+ >>> session.collect([branch_instance_1, "branch_name_2"])
872
+ >>> session.collect() # Collects from all branches
890
873
  """
891
874
  if from_ is None:
892
875
  for branch in self.branches.keys():
@@ -907,14 +890,14 @@ class Session:
907
890
  This method facilitates the distribution of data or requests to one or more branches, potentially for further tool or processing.
908
891
 
909
892
  Args:
910
- to_ (Optional[Union[str, Branch, List[str | Branch]]]): The target branch(es) to which to send requests.
911
- Can be a single branch name, a single branch instance, a list of branch names, a list of branch instances, or None.
912
- If None, requests are sent to all branches.
893
+ to_ (Optional[Union[str, Branch, List[str | Branch]]]): The target branch(es) to which to send requests.
894
+ Can be a single branch name, a single branch instance, a list of branch names, a list of branch instances, or None.
895
+ If None, requests are sent to all branches.
913
896
 
914
897
  Examples:
915
- >>> session.send("target_branch")
916
- >>> session.send([branch_instance_1, "target_branch_2"])
917
- >>> session.send() # Sends to all branches
898
+ >>> session.send("target_branch")
899
+ >>> session.send([branch_instance_1, "target_branch_2"])
900
+ >>> session.send() # Sends to all branches
918
901
  """
919
902
  if to_ is None:
920
903
  for branch in self.branches.keys():
@@ -936,12 +919,12 @@ class Session:
936
919
  useful in scenarios where data or requests need to be aggregated and then distributed uniformly.
937
920
 
938
921
  Args:
939
- receive_all (bool): If True, triggers a `receive_all` method on each branch after sending requests,
940
- which can be used to process or acknowledge the received data.
922
+ receive_all (bool): If True, triggers a `receive_all` method on each branch after sending requests,
923
+ which can be used to process or acknowledge the received data.
941
924
 
942
925
  Examples:
943
- >>> session.collect_send_all()
944
- >>> session.collect_send_all(receive_all=True)
926
+ >>> session.collect_send_all()
927
+ >>> session.collect_send_all(receive_all=True)
945
928
  """
946
929
  self.collect()
947
930
  self.send()
@@ -971,8 +954,7 @@ class Session:
971
954
  sender,
972
955
  default_branch,
973
956
  default_branch_name,
974
- messages,
975
- # instruction_sets,
957
+ messages, # instruction_sets,
976
958
  tool_manager,
977
959
  service,
978
960
  llmconfig,