lionagi 0.4.0__py3-none-any.whl → 0.5.0__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (584) hide show
  1. lionagi/__init__.py +14 -46
  2. lionagi/core/__init__.py +3 -1
  3. lionagi/core/_class_registry.py +69 -0
  4. lionagi/core/action/__init__.py +3 -13
  5. lionagi/core/action/action_manager.py +287 -0
  6. lionagi/core/action/base.py +109 -0
  7. lionagi/core/action/function_calling.py +127 -92
  8. lionagi/core/action/tool.py +172 -70
  9. lionagi/core/action/types.py +16 -0
  10. lionagi/core/communication/__init__.py +3 -0
  11. lionagi/core/communication/action_request.py +163 -0
  12. lionagi/core/communication/action_response.py +149 -0
  13. lionagi/core/communication/assistant_response.py +161 -0
  14. lionagi/core/communication/base_mail.py +49 -0
  15. lionagi/core/communication/instruction.py +376 -0
  16. lionagi/core/communication/message.py +286 -0
  17. lionagi/core/communication/message_manager.py +530 -0
  18. lionagi/core/communication/system.py +116 -0
  19. lionagi/core/communication/templates/README.md +28 -0
  20. lionagi/core/communication/templates/action_request.jinja2 +5 -0
  21. lionagi/core/communication/templates/action_response.jinja2 +9 -0
  22. lionagi/core/communication/templates/assistant_response.jinja2 +2 -0
  23. lionagi/core/communication/templates/instruction_message.jinja2 +61 -0
  24. lionagi/core/communication/templates/system_message.jinja2 +11 -0
  25. lionagi/core/communication/templates/tool_schemas.jinja2 +7 -0
  26. lionagi/core/communication/types.py +27 -0
  27. lionagi/core/communication/utils.py +254 -0
  28. lionagi/core/forms/__init__.py +3 -0
  29. lionagi/core/forms/base.py +232 -0
  30. lionagi/core/forms/form.py +791 -0
  31. lionagi/core/forms/report.py +321 -0
  32. lionagi/core/forms/types.py +13 -0
  33. lionagi/core/forms/utils.py +26 -0
  34. lionagi/core/generic/__init__.py +3 -6
  35. lionagi/core/generic/component.py +422 -0
  36. lionagi/core/generic/edge.py +143 -101
  37. lionagi/core/generic/element.py +195 -0
  38. lionagi/core/generic/graph.py +297 -180
  39. lionagi/core/generic/log.py +151 -0
  40. lionagi/core/generic/log_manager.py +320 -0
  41. lionagi/core/generic/node.py +7 -229
  42. lionagi/core/generic/pile.py +1017 -0
  43. lionagi/core/generic/progression.py +388 -0
  44. lionagi/core/generic/types.py +23 -0
  45. lionagi/core/generic/utils.py +50 -0
  46. lionagi/core/models/__init__.py +5 -0
  47. lionagi/core/models/base.py +85 -0
  48. lionagi/core/models/field_model.py +122 -0
  49. lionagi/core/models/new_model_params.py +195 -0
  50. lionagi/core/models/note.py +351 -0
  51. lionagi/core/models/operable_model.py +392 -0
  52. lionagi/core/models/schema_model.py +50 -0
  53. lionagi/core/models/types.py +10 -0
  54. lionagi/core/session/__init__.py +3 -0
  55. lionagi/core/session/branch.py +115 -415
  56. lionagi/core/session/branch_mixins.py +507 -0
  57. lionagi/core/session/session.py +122 -257
  58. lionagi/core/session/types.py +8 -0
  59. lionagi/core/typing/__init__.py +9 -0
  60. lionagi/core/typing/concepts.py +132 -0
  61. lionagi/core/typing/config.py +15 -0
  62. lionagi/core/typing/id.py +221 -0
  63. lionagi/core/typing/pydantic_.py +33 -0
  64. lionagi/core/typing/typing_.py +54 -0
  65. lionagi/integrations/__init__.py +0 -1
  66. lionagi/integrations/anthropic_/AnthropicModel.py +268 -0
  67. lionagi/integrations/anthropic_/AnthropicService.py +113 -0
  68. lionagi/integrations/anthropic_/__init__.py +3 -0
  69. lionagi/integrations/anthropic_/anthropic_max_output_token_data.yaml +7 -0
  70. lionagi/integrations/anthropic_/anthropic_price_data.yaml +14 -0
  71. lionagi/integrations/anthropic_/api_endpoints/__init__.py +3 -0
  72. lionagi/integrations/anthropic_/api_endpoints/api_request.py +277 -0
  73. lionagi/integrations/anthropic_/api_endpoints/data_models.py +40 -0
  74. lionagi/integrations/anthropic_/api_endpoints/match_response.py +119 -0
  75. lionagi/integrations/anthropic_/api_endpoints/messages/__init__.py +3 -0
  76. lionagi/integrations/anthropic_/api_endpoints/messages/request/__init__.py +3 -0
  77. lionagi/integrations/anthropic_/api_endpoints/messages/request/message_models.py +14 -0
  78. lionagi/integrations/anthropic_/api_endpoints/messages/request/request_body.py +74 -0
  79. lionagi/integrations/anthropic_/api_endpoints/messages/response/content_models.py +32 -0
  80. lionagi/integrations/anthropic_/api_endpoints/messages/response/response_body.py +101 -0
  81. lionagi/integrations/anthropic_/api_endpoints/messages/response/usage_models.py +25 -0
  82. lionagi/integrations/anthropic_/version.py +5 -0
  83. lionagi/integrations/groq_/GroqModel.py +318 -0
  84. lionagi/integrations/groq_/GroqService.py +147 -0
  85. lionagi/integrations/groq_/__init__.py +3 -0
  86. lionagi/integrations/groq_/api_endpoints/data_models.py +187 -0
  87. lionagi/integrations/groq_/api_endpoints/groq_request.py +288 -0
  88. lionagi/integrations/groq_/api_endpoints/match_response.py +106 -0
  89. lionagi/integrations/groq_/api_endpoints/response_utils.py +105 -0
  90. lionagi/integrations/groq_/groq_max_output_token_data.yaml +21 -0
  91. lionagi/integrations/groq_/groq_price_data.yaml +58 -0
  92. lionagi/integrations/groq_/groq_rate_limits.yaml +105 -0
  93. lionagi/integrations/groq_/version.py +5 -0
  94. lionagi/integrations/litellm_/__init__.py +3 -0
  95. lionagi/integrations/litellm_/imodel.py +69 -0
  96. lionagi/integrations/ollama_/OllamaModel.py +244 -0
  97. lionagi/integrations/ollama_/OllamaService.py +138 -0
  98. lionagi/integrations/ollama_/__init__.py +3 -0
  99. lionagi/integrations/ollama_/api_endpoints/__init__.py +3 -0
  100. lionagi/integrations/ollama_/api_endpoints/api_request.py +179 -0
  101. lionagi/integrations/ollama_/api_endpoints/chat_completion/__init__.py +3 -0
  102. lionagi/integrations/ollama_/api_endpoints/chat_completion/message_models.py +31 -0
  103. lionagi/integrations/ollama_/api_endpoints/chat_completion/request_body.py +46 -0
  104. lionagi/integrations/ollama_/api_endpoints/chat_completion/response_body.py +67 -0
  105. lionagi/integrations/ollama_/api_endpoints/chat_completion/tool_models.py +49 -0
  106. lionagi/integrations/ollama_/api_endpoints/completion/request_body.py +72 -0
  107. lionagi/integrations/ollama_/api_endpoints/completion/response_body.py +59 -0
  108. lionagi/integrations/ollama_/api_endpoints/data_models.py +15 -0
  109. lionagi/integrations/ollama_/api_endpoints/embedding/request_body.py +33 -0
  110. lionagi/integrations/ollama_/api_endpoints/embedding/response_body.py +29 -0
  111. lionagi/integrations/ollama_/api_endpoints/match_data_model.py +62 -0
  112. lionagi/integrations/ollama_/api_endpoints/match_response.py +190 -0
  113. lionagi/integrations/ollama_/api_endpoints/model/__init__.py +3 -0
  114. lionagi/integrations/ollama_/api_endpoints/model/copy_model.py +13 -0
  115. lionagi/integrations/ollama_/api_endpoints/model/create_model.py +28 -0
  116. lionagi/integrations/ollama_/api_endpoints/model/delete_model.py +11 -0
  117. lionagi/integrations/ollama_/api_endpoints/model/list_model.py +60 -0
  118. lionagi/integrations/ollama_/api_endpoints/model/pull_model.py +34 -0
  119. lionagi/integrations/ollama_/api_endpoints/model/push_model.py +35 -0
  120. lionagi/integrations/ollama_/api_endpoints/model/show_model.py +36 -0
  121. lionagi/integrations/ollama_/api_endpoints/option_models.py +68 -0
  122. lionagi/integrations/openai_/OpenAIModel.py +414 -0
  123. lionagi/integrations/openai_/OpenAIService.py +426 -0
  124. lionagi/integrations/openai_/api_endpoints/__init__.py +3 -0
  125. lionagi/integrations/openai_/api_endpoints/api_request.py +277 -0
  126. lionagi/integrations/openai_/api_endpoints/audio/__init__.py +9 -0
  127. lionagi/integrations/openai_/api_endpoints/audio/speech_models.py +34 -0
  128. lionagi/integrations/openai_/api_endpoints/audio/transcription_models.py +136 -0
  129. lionagi/integrations/openai_/api_endpoints/audio/translation_models.py +41 -0
  130. lionagi/integrations/openai_/api_endpoints/audio/types.py +41 -0
  131. lionagi/integrations/openai_/api_endpoints/batch/__init__.py +17 -0
  132. lionagi/integrations/openai_/api_endpoints/batch/batch_models.py +146 -0
  133. lionagi/integrations/openai_/api_endpoints/batch/cancel_batch.py +7 -0
  134. lionagi/integrations/openai_/api_endpoints/batch/create_batch.py +26 -0
  135. lionagi/integrations/openai_/api_endpoints/batch/list_batch.py +37 -0
  136. lionagi/integrations/openai_/api_endpoints/batch/request_object_models.py +65 -0
  137. lionagi/integrations/openai_/api_endpoints/batch/retrieve_batch.py +7 -0
  138. lionagi/integrations/openai_/api_endpoints/batch/types.py +4 -0
  139. lionagi/integrations/openai_/api_endpoints/chat_completions/__init__.py +1 -0
  140. lionagi/integrations/openai_/api_endpoints/chat_completions/request/__init__.py +39 -0
  141. lionagi/integrations/openai_/api_endpoints/chat_completions/request/message_models.py +121 -0
  142. lionagi/integrations/openai_/api_endpoints/chat_completions/request/request_body.py +221 -0
  143. lionagi/integrations/openai_/api_endpoints/chat_completions/request/response_format.py +71 -0
  144. lionagi/integrations/openai_/api_endpoints/chat_completions/request/stream_options.py +14 -0
  145. lionagi/integrations/openai_/api_endpoints/chat_completions/request/tool_choice_models.py +17 -0
  146. lionagi/integrations/openai_/api_endpoints/chat_completions/request/tool_models.py +54 -0
  147. lionagi/integrations/openai_/api_endpoints/chat_completions/request/types.py +18 -0
  148. lionagi/integrations/openai_/api_endpoints/chat_completions/response/choice_models.py +62 -0
  149. lionagi/integrations/openai_/api_endpoints/chat_completions/response/function_models.py +16 -0
  150. lionagi/integrations/openai_/api_endpoints/chat_completions/response/log_prob_models.py +47 -0
  151. lionagi/integrations/openai_/api_endpoints/chat_completions/response/message_models.py +25 -0
  152. lionagi/integrations/openai_/api_endpoints/chat_completions/response/response_body.py +99 -0
  153. lionagi/integrations/openai_/api_endpoints/chat_completions/response/types.py +8 -0
  154. lionagi/integrations/openai_/api_endpoints/chat_completions/response/usage_models.py +24 -0
  155. lionagi/integrations/openai_/api_endpoints/chat_completions/util.py +46 -0
  156. lionagi/integrations/openai_/api_endpoints/data_models.py +23 -0
  157. lionagi/integrations/openai_/api_endpoints/embeddings/__init__.py +3 -0
  158. lionagi/integrations/openai_/api_endpoints/embeddings/request_body.py +79 -0
  159. lionagi/integrations/openai_/api_endpoints/embeddings/response_body.py +67 -0
  160. lionagi/integrations/openai_/api_endpoints/files/__init__.py +11 -0
  161. lionagi/integrations/openai_/api_endpoints/files/delete_file.py +20 -0
  162. lionagi/integrations/openai_/api_endpoints/files/file_models.py +56 -0
  163. lionagi/integrations/openai_/api_endpoints/files/list_files.py +27 -0
  164. lionagi/integrations/openai_/api_endpoints/files/retrieve_file.py +9 -0
  165. lionagi/integrations/openai_/api_endpoints/files/upload_file.py +38 -0
  166. lionagi/integrations/openai_/api_endpoints/fine_tuning/__init__.py +37 -0
  167. lionagi/integrations/openai_/api_endpoints/fine_tuning/cancel_jobs.py +9 -0
  168. lionagi/integrations/openai_/api_endpoints/fine_tuning/create_jobs.py +133 -0
  169. lionagi/integrations/openai_/api_endpoints/fine_tuning/fine_tuning_job_checkpoint_models.py +58 -0
  170. lionagi/integrations/openai_/api_endpoints/fine_tuning/fine_tuning_job_event_models.py +31 -0
  171. lionagi/integrations/openai_/api_endpoints/fine_tuning/fine_tuning_job_models.py +140 -0
  172. lionagi/integrations/openai_/api_endpoints/fine_tuning/list_fine_tuning_checkpoints.py +51 -0
  173. lionagi/integrations/openai_/api_endpoints/fine_tuning/list_fine_tuning_events.py +42 -0
  174. lionagi/integrations/openai_/api_endpoints/fine_tuning/list_fine_tuning_jobs.py +31 -0
  175. lionagi/integrations/openai_/api_endpoints/fine_tuning/retrieve_jobs.py +9 -0
  176. lionagi/integrations/openai_/api_endpoints/fine_tuning/training_format.py +30 -0
  177. lionagi/integrations/openai_/api_endpoints/images/__init__.py +9 -0
  178. lionagi/integrations/openai_/api_endpoints/images/image_edit_models.py +69 -0
  179. lionagi/integrations/openai_/api_endpoints/images/image_models.py +56 -0
  180. lionagi/integrations/openai_/api_endpoints/images/image_variation_models.py +56 -0
  181. lionagi/integrations/openai_/api_endpoints/images/response_body.py +30 -0
  182. lionagi/integrations/openai_/api_endpoints/match_data_model.py +197 -0
  183. lionagi/integrations/openai_/api_endpoints/match_response.py +336 -0
  184. lionagi/integrations/openai_/api_endpoints/models/__init__.py +7 -0
  185. lionagi/integrations/openai_/api_endpoints/models/delete_fine_tuned_model.py +17 -0
  186. lionagi/integrations/openai_/api_endpoints/models/models_models.py +31 -0
  187. lionagi/integrations/openai_/api_endpoints/models/retrieve_model.py +9 -0
  188. lionagi/integrations/openai_/api_endpoints/moderations/__init__.py +3 -0
  189. lionagi/integrations/openai_/api_endpoints/moderations/request_body.py +20 -0
  190. lionagi/integrations/openai_/api_endpoints/moderations/response_body.py +139 -0
  191. lionagi/integrations/openai_/api_endpoints/uploads/__init__.py +19 -0
  192. lionagi/integrations/openai_/api_endpoints/uploads/add_upload_part.py +11 -0
  193. lionagi/integrations/openai_/api_endpoints/uploads/cancel_upload.py +7 -0
  194. lionagi/integrations/openai_/api_endpoints/uploads/complete_upload.py +18 -0
  195. lionagi/integrations/openai_/api_endpoints/uploads/create_upload.py +17 -0
  196. lionagi/integrations/openai_/api_endpoints/uploads/uploads_models.py +52 -0
  197. lionagi/integrations/openai_/image_token_calculator/image_token_calculator.py +92 -0
  198. lionagi/integrations/openai_/image_token_calculator/openai_image_token_data.yaml +15 -0
  199. lionagi/integrations/openai_/openai_max_output_token_data.yaml +12 -0
  200. lionagi/integrations/openai_/openai_price_data.yaml +26 -0
  201. lionagi/integrations/openai_/version.py +1 -0
  202. lionagi/integrations/pandas_/__init__.py +24 -0
  203. lionagi/integrations/pandas_/extend_df.py +61 -0
  204. lionagi/integrations/pandas_/read.py +103 -0
  205. lionagi/integrations/pandas_/remove_rows.py +61 -0
  206. lionagi/integrations/pandas_/replace_keywords.py +65 -0
  207. lionagi/integrations/pandas_/save.py +131 -0
  208. lionagi/integrations/pandas_/search_keywords.py +69 -0
  209. lionagi/integrations/pandas_/to_df.py +196 -0
  210. lionagi/integrations/pandas_/update_cells.py +54 -0
  211. lionagi/integrations/perplexity_/PerplexityModel.py +269 -0
  212. lionagi/integrations/perplexity_/PerplexityService.py +109 -0
  213. lionagi/integrations/perplexity_/__init__.py +3 -0
  214. lionagi/integrations/perplexity_/api_endpoints/api_request.py +171 -0
  215. lionagi/integrations/perplexity_/api_endpoints/chat_completions/request/request_body.py +121 -0
  216. lionagi/integrations/perplexity_/api_endpoints/chat_completions/response/response_body.py +146 -0
  217. lionagi/integrations/perplexity_/api_endpoints/data_models.py +63 -0
  218. lionagi/integrations/perplexity_/api_endpoints/match_response.py +26 -0
  219. lionagi/integrations/perplexity_/perplexity_max_output_token_data.yaml +3 -0
  220. lionagi/integrations/perplexity_/perplexity_price_data.yaml +10 -0
  221. lionagi/integrations/perplexity_/version.py +1 -0
  222. lionagi/integrations/pydantic_/__init__.py +8 -0
  223. lionagi/integrations/pydantic_/break_down_annotation.py +81 -0
  224. lionagi/integrations/pydantic_/new_model.py +208 -0
  225. lionagi/integrations/services.py +17 -0
  226. lionagi/libs/__init__.py +0 -55
  227. lionagi/libs/compress/models.py +62 -0
  228. lionagi/libs/compress/utils.py +81 -0
  229. lionagi/libs/constants.py +98 -0
  230. lionagi/libs/file/chunk.py +265 -0
  231. lionagi/libs/file/file_ops.py +114 -0
  232. lionagi/libs/file/params.py +212 -0
  233. lionagi/libs/file/path.py +301 -0
  234. lionagi/libs/file/process.py +139 -0
  235. lionagi/libs/file/save.py +90 -0
  236. lionagi/libs/file/types.py +22 -0
  237. lionagi/libs/func/async_calls/__init__.py +21 -0
  238. lionagi/libs/func/async_calls/alcall.py +157 -0
  239. lionagi/libs/func/async_calls/bcall.py +82 -0
  240. lionagi/libs/func/async_calls/mcall.py +134 -0
  241. lionagi/libs/func/async_calls/pcall.py +149 -0
  242. lionagi/libs/func/async_calls/rcall.py +185 -0
  243. lionagi/libs/func/async_calls/tcall.py +114 -0
  244. lionagi/libs/func/async_calls/ucall.py +85 -0
  245. lionagi/libs/func/decorators.py +277 -0
  246. lionagi/libs/func/lcall.py +57 -0
  247. lionagi/libs/func/params.py +64 -0
  248. lionagi/libs/func/throttle.py +119 -0
  249. lionagi/libs/func/types.py +39 -0
  250. lionagi/libs/func/utils.py +96 -0
  251. lionagi/libs/package/imports.py +162 -0
  252. lionagi/libs/package/management.py +58 -0
  253. lionagi/libs/package/params.py +26 -0
  254. lionagi/libs/package/system.py +18 -0
  255. lionagi/libs/package/types.py +26 -0
  256. lionagi/libs/parse/__init__.py +1 -0
  257. lionagi/libs/parse/flatten/__init__.py +9 -0
  258. lionagi/libs/parse/flatten/flatten.py +168 -0
  259. lionagi/libs/parse/flatten/params.py +52 -0
  260. lionagi/libs/parse/flatten/unflatten.py +79 -0
  261. lionagi/libs/parse/json/__init__.py +27 -0
  262. lionagi/libs/parse/json/as_readable.py +104 -0
  263. lionagi/libs/parse/json/extract.py +102 -0
  264. lionagi/libs/parse/json/parse.py +179 -0
  265. lionagi/libs/parse/json/schema.py +227 -0
  266. lionagi/libs/parse/json/to_json.py +71 -0
  267. lionagi/libs/parse/nested/__init__.py +33 -0
  268. lionagi/libs/parse/nested/nfilter.py +55 -0
  269. lionagi/libs/parse/nested/nget.py +40 -0
  270. lionagi/libs/parse/nested/ninsert.py +103 -0
  271. lionagi/libs/parse/nested/nmerge.py +155 -0
  272. lionagi/libs/parse/nested/npop.py +66 -0
  273. lionagi/libs/parse/nested/nset.py +89 -0
  274. lionagi/libs/parse/nested/to_flat_list.py +64 -0
  275. lionagi/libs/parse/nested/utils.py +185 -0
  276. lionagi/libs/parse/string_parse/__init__.py +11 -0
  277. lionagi/libs/parse/string_parse/code_block.py +73 -0
  278. lionagi/libs/parse/string_parse/docstring.py +179 -0
  279. lionagi/libs/parse/string_parse/function_.py +92 -0
  280. lionagi/libs/parse/type_convert/__init__.py +19 -0
  281. lionagi/libs/parse/type_convert/params.py +145 -0
  282. lionagi/libs/parse/type_convert/to_dict.py +333 -0
  283. lionagi/libs/parse/type_convert/to_list.py +186 -0
  284. lionagi/libs/parse/type_convert/to_num.py +358 -0
  285. lionagi/libs/parse/type_convert/to_str.py +195 -0
  286. lionagi/libs/parse/types.py +9 -0
  287. lionagi/libs/parse/validate/__init__.py +14 -0
  288. lionagi/libs/parse/validate/boolean.py +96 -0
  289. lionagi/libs/parse/validate/keys.py +150 -0
  290. lionagi/libs/parse/validate/mapping.py +109 -0
  291. lionagi/libs/parse/validate/params.py +62 -0
  292. lionagi/libs/parse/xml/__init__.py +10 -0
  293. lionagi/libs/parse/xml/convert.py +56 -0
  294. lionagi/libs/parse/xml/parser.py +93 -0
  295. lionagi/libs/string_similarity/__init__.py +32 -0
  296. lionagi/libs/string_similarity/algorithms.py +219 -0
  297. lionagi/libs/string_similarity/matcher.py +102 -0
  298. lionagi/libs/string_similarity/utils.py +15 -0
  299. lionagi/libs/utils.py +255 -0
  300. lionagi/operations/__init__.py +3 -6
  301. lionagi/operations/brainstorm/__init__.py +3 -0
  302. lionagi/operations/brainstorm/brainstorm.py +204 -0
  303. lionagi/operations/brainstorm/prompt.py +1 -0
  304. lionagi/operations/plan/__init__.py +3 -0
  305. lionagi/operations/plan/plan.py +172 -0
  306. lionagi/operations/plan/prompt.py +21 -0
  307. lionagi/operations/select/__init__.py +3 -0
  308. lionagi/operations/select/prompt.py +1 -0
  309. lionagi/operations/select/select.py +100 -0
  310. lionagi/operations/select/utils.py +107 -0
  311. lionagi/operations/utils.py +35 -0
  312. lionagi/protocols/adapters/adapter.py +79 -0
  313. lionagi/protocols/adapters/json_adapter.py +43 -0
  314. lionagi/protocols/adapters/pandas_adapter.py +96 -0
  315. lionagi/protocols/configs/__init__.py +15 -0
  316. lionagi/protocols/configs/branch_config.py +86 -0
  317. lionagi/protocols/configs/id_config.py +15 -0
  318. lionagi/protocols/configs/imodel_config.py +73 -0
  319. lionagi/protocols/configs/log_config.py +93 -0
  320. lionagi/protocols/configs/retry_config.py +29 -0
  321. lionagi/protocols/operatives/__init__.py +15 -0
  322. lionagi/protocols/operatives/action.py +181 -0
  323. lionagi/protocols/operatives/instruct.py +196 -0
  324. lionagi/protocols/operatives/operative.py +182 -0
  325. lionagi/protocols/operatives/prompts.py +232 -0
  326. lionagi/protocols/operatives/reason.py +56 -0
  327. lionagi/protocols/operatives/step.py +217 -0
  328. lionagi/protocols/registries/_component_registry.py +19 -0
  329. lionagi/protocols/registries/_pile_registry.py +26 -0
  330. lionagi/service/__init__.py +13 -0
  331. lionagi/service/complete_request_info.py +11 -0
  332. lionagi/service/imodel.py +110 -0
  333. lionagi/service/rate_limiter.py +108 -0
  334. lionagi/service/service.py +37 -0
  335. lionagi/service/service_match_util.py +131 -0
  336. lionagi/service/service_util.py +72 -0
  337. lionagi/service/token_calculator.py +51 -0
  338. lionagi/settings.py +136 -0
  339. lionagi/strategies/base.py +53 -0
  340. lionagi/strategies/concurrent.py +71 -0
  341. lionagi/strategies/concurrent_chunk.py +43 -0
  342. lionagi/strategies/concurrent_sequential_chunk.py +104 -0
  343. lionagi/strategies/params.py +128 -0
  344. lionagi/strategies/sequential.py +23 -0
  345. lionagi/strategies/sequential_chunk.py +89 -0
  346. lionagi/strategies/sequential_concurrent_chunk.py +100 -0
  347. lionagi/strategies/types.py +21 -0
  348. lionagi/strategies/utils.py +49 -0
  349. lionagi/version.py +1 -1
  350. lionagi-0.5.0.dist-info/METADATA +348 -0
  351. lionagi-0.5.0.dist-info/RECORD +373 -0
  352. {lionagi-0.4.0.dist-info → lionagi-0.5.0.dist-info}/WHEEL +1 -1
  353. lionagi/core/_setting/_setting.py +0 -59
  354. lionagi/core/action/README.md +0 -20
  355. lionagi/core/action/manual.py +0 -1
  356. lionagi/core/action/node.py +0 -94
  357. lionagi/core/action/tool_manager.py +0 -342
  358. lionagi/core/agent/README.md +0 -1
  359. lionagi/core/agent/base_agent.py +0 -82
  360. lionagi/core/agent/eval/README.md +0 -1
  361. lionagi/core/agent/eval/evaluator.py +0 -1
  362. lionagi/core/agent/eval/vote.py +0 -40
  363. lionagi/core/agent/learn/learner.py +0 -59
  364. lionagi/core/agent/plan/unit_template.py +0 -1
  365. lionagi/core/collections/README.md +0 -23
  366. lionagi/core/collections/__init__.py +0 -16
  367. lionagi/core/collections/_logger.py +0 -312
  368. lionagi/core/collections/abc/README.md +0 -63
  369. lionagi/core/collections/abc/__init__.py +0 -53
  370. lionagi/core/collections/abc/component.py +0 -620
  371. lionagi/core/collections/abc/concepts.py +0 -277
  372. lionagi/core/collections/abc/exceptions.py +0 -136
  373. lionagi/core/collections/abc/util.py +0 -45
  374. lionagi/core/collections/exchange.py +0 -146
  375. lionagi/core/collections/flow.py +0 -416
  376. lionagi/core/collections/model.py +0 -465
  377. lionagi/core/collections/pile.py +0 -1232
  378. lionagi/core/collections/progression.py +0 -221
  379. lionagi/core/collections/util.py +0 -73
  380. lionagi/core/director/README.md +0 -1
  381. lionagi/core/director/direct.py +0 -298
  382. lionagi/core/director/director.py +0 -2
  383. lionagi/core/director/operations/select.py +0 -3
  384. lionagi/core/director/operations/utils.py +0 -6
  385. lionagi/core/engine/branch_engine.py +0 -361
  386. lionagi/core/engine/instruction_map_engine.py +0 -213
  387. lionagi/core/engine/sandbox_.py +0 -16
  388. lionagi/core/engine/script_engine.py +0 -89
  389. lionagi/core/executor/base_executor.py +0 -97
  390. lionagi/core/executor/graph_executor.py +0 -335
  391. lionagi/core/executor/neo4j_executor.py +0 -394
  392. lionagi/core/generic/README.md +0 -0
  393. lionagi/core/generic/edge_condition.py +0 -17
  394. lionagi/core/generic/hyperedge.py +0 -1
  395. lionagi/core/generic/tree.py +0 -49
  396. lionagi/core/generic/tree_node.py +0 -85
  397. lionagi/core/mail/__init__.py +0 -11
  398. lionagi/core/mail/mail.py +0 -26
  399. lionagi/core/mail/mail_manager.py +0 -185
  400. lionagi/core/mail/package.py +0 -49
  401. lionagi/core/mail/start_mail.py +0 -36
  402. lionagi/core/message/__init__.py +0 -18
  403. lionagi/core/message/action_request.py +0 -114
  404. lionagi/core/message/action_response.py +0 -121
  405. lionagi/core/message/assistant_response.py +0 -80
  406. lionagi/core/message/instruction.py +0 -194
  407. lionagi/core/message/message.py +0 -86
  408. lionagi/core/message/system.py +0 -71
  409. lionagi/core/message/util.py +0 -274
  410. lionagi/core/report/__init__.py +0 -4
  411. lionagi/core/report/base.py +0 -201
  412. lionagi/core/report/form.py +0 -212
  413. lionagi/core/report/report.py +0 -150
  414. lionagi/core/report/util.py +0 -15
  415. lionagi/core/rule/_default.py +0 -17
  416. lionagi/core/rule/action.py +0 -87
  417. lionagi/core/rule/base.py +0 -234
  418. lionagi/core/rule/boolean.py +0 -56
  419. lionagi/core/rule/choice.py +0 -48
  420. lionagi/core/rule/mapping.py +0 -82
  421. lionagi/core/rule/number.py +0 -73
  422. lionagi/core/rule/rulebook.py +0 -45
  423. lionagi/core/rule/string.py +0 -43
  424. lionagi/core/rule/util.py +0 -0
  425. lionagi/core/session/directive_mixin.py +0 -307
  426. lionagi/core/structure/__init__.py +0 -1
  427. lionagi/core/structure/chain.py +0 -1
  428. lionagi/core/structure/forest.py +0 -1
  429. lionagi/core/structure/graph.py +0 -1
  430. lionagi/core/structure/tree.py +0 -1
  431. lionagi/core/unit/__init__.py +0 -4
  432. lionagi/core/unit/parallel_unit.py +0 -234
  433. lionagi/core/unit/template/action.py +0 -65
  434. lionagi/core/unit/template/base.py +0 -35
  435. lionagi/core/unit/template/plan.py +0 -69
  436. lionagi/core/unit/template/predict.py +0 -95
  437. lionagi/core/unit/template/score.py +0 -108
  438. lionagi/core/unit/template/select.py +0 -91
  439. lionagi/core/unit/unit.py +0 -452
  440. lionagi/core/unit/unit_form.py +0 -290
  441. lionagi/core/unit/unit_mixin.py +0 -1166
  442. lionagi/core/unit/util.py +0 -103
  443. lionagi/core/validator/validator.py +0 -376
  444. lionagi/core/work/work.py +0 -59
  445. lionagi/core/work/work_edge.py +0 -102
  446. lionagi/core/work/work_function.py +0 -114
  447. lionagi/core/work/work_function_node.py +0 -50
  448. lionagi/core/work/work_queue.py +0 -90
  449. lionagi/core/work/work_task.py +0 -151
  450. lionagi/core/work/worker.py +0 -410
  451. lionagi/core/work/worker_engine.py +0 -208
  452. lionagi/core/work/worklog.py +0 -108
  453. lionagi/experimental/compressor/base.py +0 -47
  454. lionagi/experimental/compressor/llm_compressor.py +0 -265
  455. lionagi/experimental/compressor/llm_summarizer.py +0 -61
  456. lionagi/experimental/compressor/util.py +0 -70
  457. lionagi/experimental/directive/README.md +0 -1
  458. lionagi/experimental/directive/__init__.py +0 -19
  459. lionagi/experimental/directive/parser/base_parser.py +0 -294
  460. lionagi/experimental/directive/parser/base_syntax.txt +0 -200
  461. lionagi/experimental/directive/template/base_template.py +0 -71
  462. lionagi/experimental/directive/template/schema.py +0 -36
  463. lionagi/experimental/directive/tokenizer.py +0 -59
  464. lionagi/experimental/evaluator/README.md +0 -1
  465. lionagi/experimental/evaluator/ast_evaluator.py +0 -119
  466. lionagi/experimental/evaluator/base_evaluator.py +0 -213
  467. lionagi/experimental/knowledge/__init__.py +0 -0
  468. lionagi/experimental/knowledge/base.py +0 -10
  469. lionagi/experimental/knowledge/graph.py +0 -0
  470. lionagi/experimental/memory/__init__.py +0 -0
  471. lionagi/experimental/strategies/__init__.py +0 -0
  472. lionagi/experimental/strategies/base.py +0 -1
  473. lionagi/integrations/bridge/__init__.py +0 -4
  474. lionagi/integrations/bridge/autogen_/__init__.py +0 -0
  475. lionagi/integrations/bridge/autogen_/autogen_.py +0 -127
  476. lionagi/integrations/bridge/langchain_/__init__.py +0 -0
  477. lionagi/integrations/bridge/langchain_/documents.py +0 -138
  478. lionagi/integrations/bridge/langchain_/langchain_bridge.py +0 -68
  479. lionagi/integrations/bridge/llamaindex_/__init__.py +0 -0
  480. lionagi/integrations/bridge/llamaindex_/index.py +0 -36
  481. lionagi/integrations/bridge/llamaindex_/llama_index_bridge.py +0 -108
  482. lionagi/integrations/bridge/llamaindex_/llama_pack.py +0 -256
  483. lionagi/integrations/bridge/llamaindex_/node_parser.py +0 -92
  484. lionagi/integrations/bridge/llamaindex_/reader.py +0 -201
  485. lionagi/integrations/bridge/llamaindex_/textnode.py +0 -59
  486. lionagi/integrations/bridge/pydantic_/__init__.py +0 -0
  487. lionagi/integrations/bridge/pydantic_/pydantic_bridge.py +0 -7
  488. lionagi/integrations/bridge/transformers_/__init__.py +0 -0
  489. lionagi/integrations/bridge/transformers_/install_.py +0 -39
  490. lionagi/integrations/chunker/__init__.py +0 -0
  491. lionagi/integrations/chunker/chunk.py +0 -314
  492. lionagi/integrations/config/__init__.py +0 -4
  493. lionagi/integrations/config/mlx_configs.py +0 -1
  494. lionagi/integrations/config/oai_configs.py +0 -154
  495. lionagi/integrations/config/ollama_configs.py +0 -1
  496. lionagi/integrations/config/openrouter_configs.py +0 -74
  497. lionagi/integrations/langchain_/__init__.py +0 -0
  498. lionagi/integrations/llamaindex_/__init__.py +0 -0
  499. lionagi/integrations/loader/__init__.py +0 -0
  500. lionagi/integrations/loader/load.py +0 -257
  501. lionagi/integrations/loader/load_util.py +0 -214
  502. lionagi/integrations/provider/__init__.py +0 -11
  503. lionagi/integrations/provider/_mapping.py +0 -47
  504. lionagi/integrations/provider/litellm.py +0 -53
  505. lionagi/integrations/provider/mistralai.py +0 -1
  506. lionagi/integrations/provider/mlx_service.py +0 -55
  507. lionagi/integrations/provider/oai.py +0 -196
  508. lionagi/integrations/provider/ollama.py +0 -55
  509. lionagi/integrations/provider/openrouter.py +0 -170
  510. lionagi/integrations/provider/services.py +0 -138
  511. lionagi/integrations/provider/transformers.py +0 -108
  512. lionagi/integrations/storage/__init__.py +0 -3
  513. lionagi/integrations/storage/neo4j.py +0 -681
  514. lionagi/integrations/storage/storage_util.py +0 -302
  515. lionagi/integrations/storage/structure_excel.py +0 -291
  516. lionagi/integrations/storage/to_csv.py +0 -70
  517. lionagi/integrations/storage/to_excel.py +0 -91
  518. lionagi/libs/ln_api.py +0 -944
  519. lionagi/libs/ln_async.py +0 -208
  520. lionagi/libs/ln_context.py +0 -37
  521. lionagi/libs/ln_convert.py +0 -671
  522. lionagi/libs/ln_dataframe.py +0 -187
  523. lionagi/libs/ln_func_call.py +0 -1328
  524. lionagi/libs/ln_image.py +0 -114
  525. lionagi/libs/ln_knowledge_graph.py +0 -422
  526. lionagi/libs/ln_nested.py +0 -822
  527. lionagi/libs/ln_parse.py +0 -750
  528. lionagi/libs/ln_queue.py +0 -107
  529. lionagi/libs/ln_tokenize.py +0 -179
  530. lionagi/libs/ln_validate.py +0 -299
  531. lionagi/libs/special_tokens.py +0 -172
  532. lionagi/libs/sys_util.py +0 -710
  533. lionagi/lions/__init__.py +0 -0
  534. lionagi/lions/coder/__init__.py +0 -0
  535. lionagi/lions/coder/add_feature.py +0 -20
  536. lionagi/lions/coder/base_prompts.py +0 -22
  537. lionagi/lions/coder/code_form.py +0 -15
  538. lionagi/lions/coder/coder.py +0 -184
  539. lionagi/lions/coder/util.py +0 -101
  540. lionagi/lions/director/__init__.py +0 -0
  541. lionagi/lions/judge/__init__.py +0 -0
  542. lionagi/lions/judge/config.py +0 -8
  543. lionagi/lions/judge/data/__init__.py +0 -0
  544. lionagi/lions/judge/data/sample_codes.py +0 -526
  545. lionagi/lions/judge/data/sample_rurbic.py +0 -48
  546. lionagi/lions/judge/forms/__init__.py +0 -0
  547. lionagi/lions/judge/forms/code_analysis_form.py +0 -126
  548. lionagi/lions/judge/rubric.py +0 -34
  549. lionagi/lions/judge/services/__init__.py +0 -0
  550. lionagi/lions/judge/services/judge_code.py +0 -49
  551. lionagi/lions/researcher/__init__.py +0 -0
  552. lionagi/lions/researcher/data_source/__init__.py +0 -0
  553. lionagi/lions/researcher/data_source/finhub_.py +0 -192
  554. lionagi/lions/researcher/data_source/google_.py +0 -207
  555. lionagi/lions/researcher/data_source/wiki_.py +0 -98
  556. lionagi/lions/researcher/data_source/yfinance_.py +0 -21
  557. lionagi/operations/brainstorm.py +0 -87
  558. lionagi/operations/config.py +0 -6
  559. lionagi/operations/rank.py +0 -102
  560. lionagi/operations/score.py +0 -144
  561. lionagi/operations/select.py +0 -141
  562. lionagi-0.4.0.dist-info/METADATA +0 -241
  563. lionagi-0.4.0.dist-info/RECORD +0 -249
  564. /lionagi/{core/_setting → integrations/anthropic_/api_endpoints/messages/response}/__init__.py +0 -0
  565. /lionagi/{core/agent → integrations/groq_/api_endpoints}/__init__.py +0 -0
  566. /lionagi/{core/agent/eval → integrations/ollama_/api_endpoints/completion}/__init__.py +0 -0
  567. /lionagi/{core/agent/learn → integrations/ollama_/api_endpoints/embedding}/__init__.py +0 -0
  568. /lionagi/{core/agent/plan → integrations/openai_}/__init__.py +0 -0
  569. /lionagi/{core/director → integrations/openai_/api_endpoints/chat_completions/response}/__init__.py +0 -0
  570. /lionagi/{core/director/operations → integrations/openai_/image_token_calculator}/__init__.py +0 -0
  571. /lionagi/{core/engine → integrations/perplexity_/api_endpoints}/__init__.py +0 -0
  572. /lionagi/{core/executor → integrations/perplexity_/api_endpoints/chat_completions}/__init__.py +0 -0
  573. /lionagi/{core/generic/registry/component_registry → integrations/perplexity_/api_endpoints/chat_completions/request}/__init__.py +0 -0
  574. /lionagi/{core/rule → integrations/perplexity_/api_endpoints/chat_completions/response}/__init__.py +0 -0
  575. /lionagi/{core/unit/template → libs/compress}/__init__.py +0 -0
  576. /lionagi/{core/validator → libs/file}/__init__.py +0 -0
  577. /lionagi/{core/work → libs/func}/__init__.py +0 -0
  578. /lionagi/{experimental → libs/package}/__init__.py +0 -0
  579. /lionagi/{core/agent/plan/plan.py → libs/parse/params.py} +0 -0
  580. /lionagi/{experimental/compressor → protocols}/__init__.py +0 -0
  581. /lionagi/{experimental/directive/parser → protocols/adapters}/__init__.py +0 -0
  582. /lionagi/{experimental/directive/template → protocols/registries}/__init__.py +0 -0
  583. /lionagi/{experimental/evaluator → strategies}/__init__.py +0 -0
  584. {lionagi-0.4.0.dist-info → lionagi-0.5.0.dist-info/licenses}/LICENSE +0 -0
@@ -1,1232 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import asyncio
4
- from collections.abc import AsyncIterator, Callable, Iterable
5
- from functools import wraps
6
- from typing import Any, Generic, TypeVar
7
-
8
- from pydantic import Field, field_validator
9
-
10
- from lionagi.libs.ln_convert import is_same_dtype, to_df, to_dict
11
- from lionagi.libs.ln_func_call import CallDecorator as cd
12
- from lionagi.libs.ln_func_call import alcall
13
-
14
- from .abc import (
15
- Component,
16
- Element,
17
- ItemNotFoundError,
18
- LionIDable,
19
- LionTypeError,
20
- LionValueError,
21
- ModelLimitExceededError,
22
- Ordering,
23
- Record,
24
- get_lion_id,
25
- )
26
- from .model import iModel
27
- from .util import _validate_order, to_list_type
28
-
29
- T = TypeVar("T")
30
-
31
-
32
- def async_synchronized(func: Callable):
33
- @wraps(func)
34
- async def wrapper(self, *args, **kwargs):
35
- async with self.async_lock:
36
- return await func(self, *args, **kwargs)
37
-
38
- return wrapper
39
-
40
-
41
- class Pile(Element, Record, Generic[T]):
42
- """
43
- Collection class for managing Element objects.
44
-
45
- Facilitates ordered and type-validated storage and access, supporting
46
- both index-based and key-based retrieval.
47
-
48
- Attributes:
49
- pile (dict[str, T]): Maps unique identifiers to items.
50
- item_type (set[Type[Element]] | None): Allowed item types.
51
- name (str | None): Optional name for the pile.
52
- order (list[str]): Order of item identifiers.
53
- use_obj (bool): If True, treat Record and Ordering as objects.
54
- """
55
-
56
- use_obj: bool = False
57
- pile: dict[str, T] = Field(default_factory=dict)
58
- item_type: set[type[Element]] | None = Field(default=None)
59
- name: str | None = None
60
- order: list[str] = Field(default_factory=list)
61
- index: Any = None
62
- engines: dict[str, Any] = Field(default_factory=dict)
63
- query_response: list = []
64
- tools: dict = {}
65
-
66
- def __pydantic_extra__(self) -> dict[str, Any]:
67
- return {
68
- "_async": Field(default_factory=asyncio.Lock),
69
- }
70
-
71
- def __pydantic_private__(self) -> dict[str, Any]:
72
- return self.__pydantic_extra__()
73
-
74
- def __init__(
75
- self,
76
- items=None,
77
- item_type=None,
78
- order=None,
79
- use_obj=None,
80
- ):
81
- super().__init__()
82
-
83
- self.use_obj = use_obj or False
84
- self.pile = self._validate_pile(items or {})
85
- self.item_type = self._validate_item_type(item_type)
86
-
87
- order = order or list(self.pile.keys())
88
- if not len(order) == len(self):
89
- raise ValueError(
90
- "The length of the order does not match the length of the pile"
91
- )
92
- self.order = order
93
-
94
- def __getitem__(self, key) -> T | Pile[T]:
95
- """
96
- Retrieve items from the pile using a key.
97
-
98
- Supports multiple types of key access:
99
- - By index or slice (list-like access)
100
- - By LionID (dictionary-like access)
101
- - By other complex types if item is of LionIDable
102
-
103
- Args:
104
- key: Key to retrieve items.
105
-
106
- Returns:
107
- The requested item(s). Single items returned directly,
108
- multiple items returned in a new `Pile` instance.
109
-
110
- Raises:
111
- ItemNotFoundError: If requested item(s) not found.
112
- LionTypeError: If provided key is invalid.
113
- """
114
- try:
115
- if isinstance(key, (int, slice)):
116
- # Handle list-like index or slice
117
- _key = self.order[key]
118
- _key = [_key] if isinstance(key, int) else _key
119
- _out = [self.pile.get(i) for i in _key]
120
- return (
121
- _out[0]
122
- if len(_out) == 1
123
- else pile(_out, self.item_type, _key)
124
- )
125
- except IndexError as e:
126
- raise ItemNotFoundError(key) from e
127
-
128
- keys = to_list_type(key)
129
- for idx, item in enumerate(keys):
130
- if isinstance(item, str):
131
- keys[idx] = item
132
- continue
133
- if hasattr(item, "ln_id"):
134
- keys[idx] = item.ln_id
135
-
136
- if not all(keys):
137
- raise LionTypeError(
138
- "Invalid item type. Expected LionIDable object(s)."
139
- )
140
-
141
- try:
142
- if len(keys) == 1:
143
- return self.pile.get(keys[0])
144
- return pile([self.pile.get(i) for i in keys], self.item_type, keys)
145
- except KeyError as e:
146
- raise ItemNotFoundError(key) from e
147
-
148
- def __setitem__(self, key, item) -> None:
149
- """
150
- Set new values in the pile using various key types.
151
-
152
- Handles single/multiple assignments, ensures type consistency.
153
- Supports index/slice, LionID, and LionIDable key access.
154
-
155
- Args:
156
- key: Key to set items. Can be index, slice, LionID, LionIDable.
157
- item: Item(s) to set. Can be single item or collection.
158
-
159
- Raises:
160
- ValueError: Length mismatch or multiple items to single key.
161
- LionTypeError: Item type doesn't match allowed types.
162
- """
163
- item = self._validate_pile(item)
164
-
165
- if isinstance(key, (int, slice)):
166
- # Handle list-like index or slice
167
- try:
168
- _key = self.order[key]
169
- except IndexError as e:
170
- raise e
171
-
172
- if isinstance(_key, str) and len(item) != 1:
173
- raise ValueError(
174
- "Cannot assign multiple items to a single item."
175
- )
176
-
177
- if isinstance(_key, list) and len(item) != len(_key):
178
- raise ValueError(
179
- "The length of values does not match the length of the slice"
180
- )
181
-
182
- for k, v in item.items():
183
- if self.item_type and type(v) not in self.item_type:
184
- raise LionTypeError(
185
- f"Invalid item type. Expected {self.item_type}"
186
- )
187
-
188
- self.pile[k] = v
189
- self.order[key] = k
190
- self.pile.pop(_key)
191
- return
192
-
193
- if len(to_list_type(key)) != len(item):
194
- raise ValueError(
195
- "The length of keys does not match the length of values"
196
- )
197
-
198
- self.pile.update(item)
199
- self.order.extend(item.keys())
200
-
201
- def __contains__(self, item: Any) -> bool:
202
- """
203
- Check if item(s) are present in the pile.
204
-
205
- Accepts individual items and collections. Returns `True` if all
206
- provided items are found, `False` otherwise.
207
-
208
- Args:
209
- item: Item(s) to check. Can be single item or collection.
210
-
211
- Returns:
212
- `True` if all items are found, `False` otherwise.
213
- """
214
- item = to_list_type(item)
215
- for i in item:
216
- try:
217
- a = i if isinstance(i, str) else get_lion_id(i)
218
- if a not in self.pile:
219
- return False
220
- except Exception:
221
- return False
222
-
223
- return True
224
-
225
- def pop(self, key: Any, default=...) -> T | Pile[T] | None:
226
- """
227
- Remove and return item(s) associated with given key.
228
-
229
- Raises `ItemNotFoundError` if key not found and no default given.
230
- Returns default if provided and key not found.
231
-
232
- Args:
233
- key: Key of item(s) to remove and return. Can be single key
234
- or collection of keys.
235
- default: Default value if key not found. If not specified
236
- and key not found, raises `ItemNotFoundError`.
237
-
238
- Returns:
239
- Removed item(s) associated with key. Single items returned
240
- directly, multiple items in new `Pile`. Returns default if
241
- provided and key not found.
242
-
243
- Raises:
244
- ItemNotFoundError: If key not found and no default specified.
245
- """
246
- key = to_list_type(key)
247
- items = []
248
-
249
- for i in key:
250
- if i not in self:
251
- if default == ...:
252
- raise ItemNotFoundError(i)
253
- return default
254
-
255
- for i in key:
256
- _id = get_lion_id(i)
257
- items.append(self.pile.pop(_id))
258
- self.order.remove(_id)
259
-
260
- return pile(items) if len(items) > 1 else items[0]
261
-
262
- def get(self, key: Any, default=...) -> T | Pile[T] | None:
263
- """
264
- Retrieve item(s) associated with given key.
265
-
266
- Raises `ItemNotFoundError` if key not found and no default given.
267
- Returns default if provided and key not found.
268
-
269
- Args:
270
- key: Key of item(s) to retrieve. Can be single or collection.
271
- default: Default value if key not found. If not specified
272
- and key not found, raises `ItemNotFoundError`.
273
-
274
- Returns:
275
- Retrieved item(s) associated with key. Single items returned
276
- directly, multiple items in new `Pile`. Returns default if
277
- provided and key not found.
278
-
279
- Raises:
280
- ItemNotFoundError: If key not found and no default specified.
281
- """
282
- try:
283
- return self[key]
284
- except ItemNotFoundError as e:
285
- if default == ...:
286
- raise e
287
- return default
288
-
289
- def update(self, other: Any):
290
- """
291
- Update pile with another collection of items.
292
-
293
- Accepts `Pile` or any iterable. Provided items added to current
294
- pile, overwriting existing items with same keys.
295
-
296
- Args:
297
- other: Collection to update with. Can be any LionIDable
298
- """
299
- p = pile(other)
300
- self[p] = p
301
-
302
- def clear(self):
303
- """Clear all items, resetting pile to empty state."""
304
- self.pile.clear()
305
- self.order.clear()
306
-
307
- def include(self, item: Any) -> bool:
308
- """
309
- Include item(s) in pile if not already present.
310
-
311
- Accepts individual items and collections. Adds items if not
312
- present. Returns `True` if item(s) in pile after operation,
313
- `False` otherwise.
314
-
315
- Args:
316
- item: Item(s) to include. Can be single item or collection.
317
-
318
- Returns:
319
- `True` if item(s) in pile after operation, `False` otherwise.
320
- """
321
- item = to_list_type(item)
322
- if item not in self:
323
- self[item] = item
324
- return item in self
325
-
326
- def exclude(self, item: Any) -> bool:
327
- """
328
- Exclude item(s) from pile if present.
329
-
330
- Accepts individual items and collections. Removes items if
331
- present. Returns `True` if item(s) not in pile after operation,
332
- `False` otherwise.
333
-
334
- Args:
335
- item: Item(s) to exclude. Can be single item or collection.
336
-
337
- Returns:
338
- `True` if item(s) not in pile after operation, `False` else.
339
- """
340
- item = to_list_type(item)
341
- for i in item:
342
- if item in self:
343
- self.pop(i)
344
- return item not in self
345
-
346
- def is_homogenous(self) -> bool:
347
- """
348
- Check if all items have the same data type.
349
-
350
- Returns:
351
- `True` if all items have the same type, `False` otherwise.
352
- Empty pile or single-item pile considered homogenous.
353
- """
354
- return len(self.pile) < 2 or all(is_same_dtype(self.pile.values()))
355
-
356
- def is_empty(self) -> bool:
357
- """
358
- Check if the pile is empty.
359
-
360
- Returns:
361
- bool: `True` if the pile is empty, `False` otherwise.
362
- """
363
- return not self.pile
364
-
365
- def __iter__(self):
366
- """Return an iterator over the items in the pile.
367
-
368
- Yields:
369
- The items in the pile in the order they were added.
370
- """
371
- return iter(self.values())
372
-
373
- def __len__(self) -> int:
374
- """Get the number of items in the pile.
375
-
376
- Returns:
377
- int: The number of items in the pile.
378
- """
379
- return len(self.pile)
380
-
381
- def __add__(self, other: T) -> Pile:
382
- """Create a new pile by including item(s) using `+`.
383
-
384
- Returns a new `Pile` with all items from the current pile plus
385
- provided item(s). Raises `LionValueError` if item(s) can't be
386
- included.
387
-
388
- Args:
389
- other: Item(s) to include. Can be single item or collection.
390
-
391
- Returns:
392
- New `Pile` with all items from current pile plus item(s).
393
-
394
- Raises:
395
- LionValueError: If item(s) can't be included.
396
- """
397
- _copy = self.model_copy(deep=True)
398
- if _copy.include(other):
399
- return _copy
400
- raise LionValueError("Item cannot be included in the pile.")
401
-
402
- def __sub__(self, other) -> Pile:
403
- """
404
- Create a new pile by excluding item(s) using `-`.
405
-
406
- Returns a new `Pile` with all items from the current pile except
407
- provided item(s). Raises `ItemNotFoundError` if item(s) not found.
408
-
409
- Args:
410
- other: Item(s) to exclude. Can be single item or collection.
411
-
412
- Returns:
413
- New `Pile` with all items from current pile except item(s).
414
-
415
- Raises:
416
- ItemNotFoundError: If item(s) not found in pile.
417
- """
418
- _copy = self.model_copy(deep=True)
419
- if other not in self:
420
- raise ItemNotFoundError(other)
421
-
422
- length = len(_copy)
423
- if not _copy.exclude(other) or len(_copy) == length:
424
- raise LionValueError("Item cannot be excluded from the pile.")
425
- return _copy
426
-
427
- def __iadd__(self, other: T) -> Pile:
428
- """
429
- Include item(s) in the current pile in place using `+=`.
430
-
431
- Modifies the current pile in-place by including item(s). Returns
432
- the modified pile.
433
-
434
- Args:
435
- other: Item(s) to include. Can be single item or collection.
436
- """
437
-
438
- return self + other
439
-
440
- def __isub__(self, other: LionIDable) -> Pile:
441
- """
442
- Exclude item(s) from the current pile using `-=`.
443
-
444
- Modifies the current pile in-place by excluding item(s). Returns
445
- the modified pile.
446
-
447
- Args:
448
- other: Item(s) to exclude. Can be single item or collection.
449
-
450
- Returns:
451
- Modified pile after excluding item(s).
452
- """
453
- return self - other
454
-
455
- def __radd__(self, other: T) -> Pile:
456
- return other + self
457
-
458
- def __ior__(self, other: Any | Pile) -> Pile:
459
- if not isinstance(other, Pile):
460
- raise LionTypeError(
461
- "Invalid type for Pile operation.",
462
- expected_type=Pile,
463
- actual_type=type(other),
464
- )
465
- other = self._validate_pile(list(other))
466
- self.include(other)
467
- return self
468
-
469
- def __or__(self, other: Any | Pile) -> Pile:
470
- if not isinstance(other, Pile):
471
- raise LionTypeError(
472
- "Invalid type for Pile operation.",
473
- expected_type=Pile,
474
- actual_type=type(other),
475
- )
476
-
477
- result = self.__class__(
478
- items=self.values(),
479
- item_type=self.item_type,
480
- order=self.order,
481
- )
482
- result.include(list(other))
483
- return result
484
-
485
- def __ixor__(self, other: Any | Pile) -> Pile:
486
- if not isinstance(other, Pile):
487
- raise LionTypeError(
488
- "Invalid type for Pile operation.",
489
- expected_type=Pile,
490
- actual_type=type(other),
491
- )
492
-
493
- to_exclude = []
494
- for i in other:
495
- if i in self:
496
- to_exclude.append(i)
497
-
498
- other = [i for i in other if i not in to_exclude]
499
- self.exclude(to_exclude)
500
- self.include(other)
501
- return self
502
-
503
- def __xor__(self, other: Any | Pile) -> Pile:
504
- if not isinstance(other, Pile):
505
- raise LionTypeError(
506
- "Invalid type for Pile operation.",
507
- expected_type=Pile,
508
- actual_type=type(other),
509
- )
510
-
511
- to_exclude = []
512
- for i in other:
513
- if i in self:
514
- to_exclude.append(i)
515
-
516
- values = [i for i in self if i not in to_exclude] + [
517
- i for i in other if i not in to_exclude
518
- ]
519
-
520
- result = self.__class__(
521
- items=values,
522
- item_type=self.item_type,
523
- )
524
- return result
525
-
526
- def __iand__(self, other: Any) -> Pile:
527
- if not isinstance(other, Pile):
528
- raise LionTypeError(
529
- "Invalid type for Pile operation.",
530
- expected_type=Pile,
531
- actual_type=type(other),
532
- )
533
-
534
- to_exclude = []
535
- for i in self.values():
536
- if i not in other:
537
- to_exclude.append(i)
538
- self.exclude(to_exclude)
539
- return self
540
-
541
- def __and__(self, other: Any | Pile) -> Pile:
542
- if not isinstance(other, Pile):
543
- raise LionTypeError(
544
- "Invalid type for Pile operation.",
545
- expected_type=Pile,
546
- actual_type=type(other),
547
- )
548
-
549
- values = [i for i in self if i in other]
550
- return self.__class__(
551
- items=values,
552
- item_type=self.item_type,
553
- )
554
-
555
- def size(self) -> int:
556
- """Return the total size of the pile."""
557
- return sum([len(i) for i in self])
558
-
559
- def insert(self, index, item):
560
- """
561
- Insert item(s) at specific position.
562
-
563
- Inserts item(s) at specified index. Index must be integer.
564
- Raises `IndexError` if index out of range.
565
-
566
- Args:
567
- index: Index to insert item(s). Must be integer.
568
- item: Item(s) to insert. Can be single item or collection.
569
-
570
- Raises:
571
- ValueError: If index not an integer.
572
- IndexError: If index out of range.
573
- """
574
- if not isinstance(index, int):
575
- raise ValueError("Index must be an integer for pile insertion.")
576
- item = self._validate_pile(item)
577
- for k, v in item.items():
578
- self.order.insert(index, k)
579
- self.pile[k] = v
580
-
581
- def append(self, item: T):
582
- """
583
- Append item to end of pile.
584
-
585
- Appends item to end of pile. If item is `Pile`, added as single
586
- item, preserving structure. Only way to add `Pile` into another.
587
- Other methods assume pile as container only.
588
-
589
- Args:
590
- item: Item to append. Can be any object, including `Pile`.
591
- """
592
- self.pile[item.ln_id] = item
593
- self.order.append(item.ln_id)
594
-
595
- def keys(self):
596
- """Yield the keys of the items in the pile."""
597
- return self.order
598
-
599
- def values(self):
600
- """Yield the values of the items in the pile."""
601
- yield from (self.pile.get(i) for i in self.order)
602
-
603
- def items(self):
604
- """
605
- Yield the items in the pile as (key, value) pairs.
606
-
607
- Yields:
608
- tuple: A tuple containing the key and value of each item in the pile.
609
- """
610
- yield from ((i, self.pile.get(i)) for i in self.order)
611
-
612
- @field_validator("order", mode="before")
613
- def _validate_order(cls, value):
614
- return _validate_order(value)
615
-
616
- def _validate_item_type(self, value):
617
- """
618
- Validate the item type for the pile.
619
-
620
- Ensures that the provided item type is a subclass of Element or iModel.
621
- Raises an error if the validation fails.
622
-
623
- Args:
624
- value: The item type to validate. Can be a single type or a list of types.
625
-
626
- Returns:
627
- set: A set of validated item types.
628
-
629
- Raises:
630
- LionTypeError: If an invalid item type is provided.
631
- LionValueError: If duplicate item types are detected.
632
- """
633
- if value is None:
634
- return None
635
-
636
- value = to_list_type(value)
637
-
638
- for i in value:
639
- if not isinstance(i, (type(Element), type(iModel))):
640
- raise LionTypeError(
641
- "Invalid item type. Expected a subclass of Component."
642
- )
643
-
644
- if len(value) != len(set(value)):
645
- raise LionValueError(
646
- "Detected duplicated item types in item_type."
647
- )
648
-
649
- if len(value) > 0:
650
- return set(value)
651
-
652
- def _validate_pile(
653
- self,
654
- value,
655
- ):
656
- if value == {}:
657
- return value
658
-
659
- if isinstance(value, Component):
660
- return {value.ln_id: value}
661
-
662
- if self.use_obj:
663
- if not isinstance(value, list):
664
- value = [value]
665
- if isinstance(value[0], (Record, Ordering)):
666
- return {getattr(i, "ln_id"): i for i in value}
667
-
668
- value = to_list_type(value)
669
- if getattr(self, "item_type", None) is not None:
670
- for i in value:
671
- if not type(i) in self.item_type:
672
- raise LionTypeError(
673
- f"Invalid item type in pile. Expected {self.item_type}"
674
- )
675
-
676
- if isinstance(value, list):
677
- if len(value) == 1:
678
- if isinstance(value[0], dict) and value[0] != {}:
679
- k = list(value[0].keys())[0]
680
- v = value[0][k]
681
- return {k: v}
682
-
683
- # [item]
684
- k = getattr(value[0], "ln_id", None)
685
- if k:
686
- return {k: value[0]}
687
-
688
- return {i.ln_id: i for i in value}
689
-
690
- raise LionValueError("Invalid pile value")
691
-
692
- def to_df(self):
693
- """Return the pile as a DataFrame."""
694
- dicts_ = []
695
- for i in self.values():
696
- _dict = i.to_dict()
697
- if _dict.get("embedding", None):
698
- _dict["embedding"] = str(_dict.get("embedding"))
699
- dicts_.append(_dict)
700
- return to_df(dicts_)
701
-
702
- def create_index(self, index_type="llama_index", **kwargs):
703
- """
704
- Create an index for the pile.
705
-
706
- Args:
707
- index_type (str): The type of index to use. Default is "llama_index".
708
- **kwargs: Additional keyword arguments for the index creation.
709
-
710
- Returns:
711
- The created index.
712
-
713
- Raises:
714
- ValueError: If an invalid index type is provided.
715
- """
716
- if index_type == "llama_index":
717
- from lionagi.integrations.bridge import LlamaIndexBridge
718
-
719
- index_nodes = None
720
-
721
- try:
722
- index_nodes = [i.to_llama_index_node() for i in self]
723
- except AttributeError:
724
- raise LionTypeError(
725
- "Invalid item type. Expected a subclass of Component."
726
- )
727
-
728
- self.index = LlamaIndexBridge.index(index_nodes, **kwargs)
729
- return self.index
730
-
731
- raise ValueError("Invalid index type")
732
-
733
- def create_query_engine(
734
- self, index_type="llama_index", engine_kwargs={}, **kwargs
735
- ):
736
- """
737
- Create a query engine for the pile.
738
-
739
- Args:
740
- index_type (str): The type of index to use. Default is "llama_index".
741
- engine_kwargs (dict): Additional keyword arguments for the engine.
742
- **kwargs: Additional keyword arguments for the index creation.
743
-
744
- Raises:
745
- ValueError: If an invalid index type is provided.
746
- """
747
- if index_type == "llama_index":
748
- if "node_postprocessor" in kwargs:
749
- engine_kwargs["node_postprocessor"] = kwargs.pop(
750
- "node_postprocessor"
751
- )
752
- if "llm" in kwargs:
753
- engine_kwargs["llm"] = kwargs.pop("llm")
754
- if not self.index:
755
- self.create_index(index_type, **kwargs)
756
- query_engine = self.index.as_query_engine(**engine_kwargs)
757
- self.engines["query"] = query_engine
758
- else:
759
- raise ValueError("Invalid index type")
760
-
761
- def create_chat_engine(
762
- self, index_type="llama_index", engine_kwargs={}, **kwargs
763
- ):
764
- """
765
- Create a chat engine for the pile.
766
-
767
- Args:
768
- index_type (str): The type of index to use. Default is "llama_index".
769
- engine_kwargs (dict): Additional keyword arguments for the engine.
770
- **kwargs: Additional keyword arguments for the index creation.
771
-
772
- Raises:
773
- ValueError: If an invalid index type is provided.
774
- """
775
- if index_type == "llama_index":
776
- if "node_postprocessor" in kwargs:
777
- engine_kwargs["node_postprocessor"] = kwargs.pop(
778
- "node_postprocessor"
779
- )
780
- if "llm" in kwargs:
781
- engine_kwargs["llm"] = kwargs.pop("llm")
782
- if not self.index:
783
- self.create_index(index_type, **kwargs)
784
- query_engine = self.index.as_chat_engine(**engine_kwargs)
785
- self.engines["chat"] = query_engine
786
- else:
787
- raise ValueError("Invalid index type")
788
-
789
- async def query_pile(
790
- self, query, engine_kwargs={}, return_dict=False, **kwargs
791
- ):
792
- """
793
- Query the pile using the created query engine.
794
-
795
- Args:
796
- query (str): The query to send.
797
- engine_kwargs (dict): Additional keyword arguments for the engine.
798
- **kwargs: Additional keyword arguments for the query.
799
-
800
- Returns:
801
- str: The response from the query engine.
802
- """
803
- if not self.engines.get("query", None):
804
- self.create_query_engine(**engine_kwargs)
805
- response = await self.engines["query"].aquery(query, **kwargs)
806
- self.query_response.append(response)
807
- if return_dict:
808
- return to_dict(response)
809
- return str(response)
810
-
811
- async def chat_pile(
812
- self, query, engine_kwargs={}, return_dict=False, **kwargs
813
- ):
814
- """
815
- Chat with the pile using the created chat engine.
816
-
817
- Args:
818
- query (str): The query to send.
819
- engine_kwargs (dict): Additional keyword arguments for the engine.
820
- **kwargs: Additional keyword arguments for the query.
821
-
822
- Returns:
823
- str: The response from the chat engine.
824
- """
825
- if not self.engines.get("chat", None):
826
- self.create_chat_engine(**engine_kwargs)
827
- response = await self.engines["chat"].achat(query, **kwargs)
828
- self.query_response.append(response)
829
- if return_dict:
830
- return to_dict(response)
831
- return str(response)
832
-
833
- async def embed_pile(
834
- self,
835
- imodel=None,
836
- field="content",
837
- embed_kwargs={},
838
- verbose=True,
839
- **kwargs,
840
- ):
841
- """
842
- Embed the items in the pile.
843
-
844
- Args:
845
- imodel: The embedding model to use.
846
- field (str): The field to embed. Default is "content".
847
- embed_kwargs (dict): Additional keyword arguments for the embedding.
848
- verbose (bool): Whether to print verbose messages. Default is True.
849
- **kwargs: Additional keyword arguments for the embedding.
850
-
851
- Raises:
852
- ModelLimitExceededError: If the model limit is exceeded.
853
- """
854
- from .model import iModel
855
-
856
- imodel = imodel or iModel(endpoint="embeddings", **kwargs)
857
-
858
- max_concurrency = kwargs.get("max_concurrency", None) or 100
859
-
860
- @cd.max_concurrency(max_concurrency)
861
- async def _embed_item(item):
862
- try:
863
- return await imodel.embed_node(
864
- item, field=field, **embed_kwargs
865
- )
866
- except ModelLimitExceededError:
867
- pass
868
- return None
869
-
870
- await alcall(list(self), _embed_item)
871
-
872
- a = len([i for i in self if "embedding" in i._all_fields])
873
- if len(self) > a and verbose:
874
- print(
875
- f"Successfully embedded {a}/{len(self)} items, Failed to embed {len(self) - a}/{len(self)} items"
876
- )
877
- return
878
-
879
- print(f"Successfully embedded all {a}/{a} items")
880
-
881
- def to_csv(self, file_name, **kwargs):
882
- """
883
- Save the pile to a CSV file.
884
-
885
- Args:
886
- file_name (str): The name of the CSV file.
887
- **kwargs: Additional keyword arguments for the CSV writer.
888
- """
889
- self.to_df().to_csv(file_name, index=False, **kwargs)
890
-
891
- @classmethod
892
- def from_csv(cls, file_name, **kwargs):
893
- """
894
- Load a pile from a CSV file.
895
-
896
- Args:
897
- file_name (str): The name of the CSV file.
898
- **kwargs: Additional keyword arguments for the CSV reader.
899
-
900
- Returns:
901
- Pile: The loaded pile.
902
- """
903
- from pandas import read_csv
904
-
905
- df = read_csv(file_name, **kwargs)
906
- items = Component.from_obj(df)
907
- return cls(items)
908
-
909
- @classmethod
910
- def from_df(cls, df):
911
- """
912
- Load a pile from a DataFrame.
913
-
914
- Args:
915
- df (DataFrame): The DataFrame to load.
916
-
917
- Returns:
918
- Pile: The loaded pile.
919
- """
920
- items = Component.from_obj(df)
921
- return cls(items)
922
-
923
- def as_query_tool(
924
- self,
925
- index_type="llama_index",
926
- query_type="query",
927
- name=None,
928
- guidance=None,
929
- query_description=None,
930
- return_dict=False,
931
- **kwargs,
932
- ):
933
- """
934
- Create a query tool for the pile.
935
-
936
- Args:
937
- index_type (str): The type of index to use. Default is "llama_index".
938
- query_type (str): The type of query engine to use. Default is "query".
939
- name (str): The name of the query tool. Default is "query".
940
- guidance (str): The guidance for the query tool.
941
- query_description (str): The description of the query parameter.
942
- **kwargs: Additional keyword arguments for the query engine.
943
-
944
- Returns:
945
- Tool: The created query tool.
946
- """
947
- if not self.engines.get(query_type, None):
948
- if query_type == "query":
949
- self.create_query_engine(index_type=index_type, **kwargs)
950
- elif query_type == "chat":
951
- self.create_chat_engine(index_type=index_type, **kwargs)
952
-
953
- from lionagi.core.action.tool_manager import func_to_tool
954
-
955
- if not guidance:
956
- if query_type == "query":
957
- guidance = "Query a QA bot"
958
- elif query_type == "chat":
959
- guidance = "Chat with a QA bot"
960
-
961
- if not query_description:
962
- if query_type == "query":
963
- query_description = "The query to send"
964
- elif query_type == "chat":
965
- query_description = "The message to send"
966
-
967
- async def query(query: str):
968
- if query_type == "query":
969
- return await self.query_pile(
970
- query, return_dict=return_dict, **kwargs
971
- )
972
-
973
- elif query_type == "chat":
974
- return await self.chat_pile(
975
- query, return_dict=return_dict, **kwargs
976
- )
977
-
978
- name = name or "query"
979
- tool = func_to_tool(query)[0]
980
- tool.schema_["function"]["name"] = name
981
- tool.schema_["function"]["description"] = guidance
982
- tool.schema_["function"]["parameters"]["properties"]["query"][
983
- "description"
984
- ] = query_description
985
- self.tools[query_type] = tool
986
- return self.tools[query_type]
987
-
988
- def __list__(self):
989
- """
990
- Get a list of the items in the pile.
991
-
992
- Returns:
993
- list: The items in the pile.
994
- """
995
- return list(self.pile.values())
996
-
997
- def __str__(self):
998
- """
999
- Get the string representation of the pile.
1000
-
1001
- Returns:
1002
- str: The string representation of the pile.
1003
- """
1004
- return self.to_df().__str__()
1005
-
1006
- def __repr__(self):
1007
- """
1008
- Get the representation of the pile.
1009
-
1010
- Returns:
1011
- str: The representation of the pile.
1012
- """
1013
- return self.to_df().__repr__()
1014
-
1015
- def __getstate__(self):
1016
- """Prepare the Pile instance for pickling."""
1017
- state = self.__dict__.copy()
1018
- state["_async_lock"] = None
1019
- return state
1020
-
1021
- def __setstate__(self, state):
1022
- """Restore the Pile instance after unpickling."""
1023
- self.__dict__.update(state)
1024
- self._async_lock = asyncio.Lock()
1025
-
1026
- @property
1027
- def async_lock(self):
1028
- """Ensure the async lock is always available, even during unpickling"""
1029
- if not hasattr(self, "_async_lock") or self._async_lock is None:
1030
- self._async_lock = asyncio.Lock()
1031
- return self._async_lock
1032
-
1033
- # Async Interface methods
1034
- @async_synchronized
1035
- async def asetitem(
1036
- self,
1037
- key: Any,
1038
- item: T | Iterable[T],
1039
- /,
1040
- ) -> None:
1041
- """Asynchronously set an item or items in the Pile.
1042
-
1043
- Args:
1044
- key: The key to set. Can be an integer index, a string ID, or a
1045
- slice.
1046
- item: The item or items to set. Must be of type T or an iterable
1047
- of T for slices.
1048
-
1049
- Raises:
1050
- TypeError: If the item type is not allowed.
1051
- KeyError: If the key is invalid.
1052
- ValueError: If trying to set multiple items with a non-slice key.
1053
- """
1054
- self._setitem(key, item)
1055
-
1056
- @async_synchronized
1057
- async def apop(
1058
- self,
1059
- key: Any,
1060
- default: Any = ...,
1061
- /,
1062
- ):
1063
- """Asynchronously remove and return an item or items from the Pile.
1064
-
1065
- Args:
1066
- key: The key of the item(s) to remove. Can be an integer index,
1067
- a string ID, or a slice.
1068
- default: The value to return if the key is not found. Defaults to
1069
- ....
1070
-
1071
- Returns:
1072
- The removed item(s), or the default value if not found.
1073
-
1074
- Raises:
1075
- KeyError: If the key is not found and no default is provided.
1076
- """
1077
- return self._pop(key, default)
1078
-
1079
- @async_synchronized
1080
- async def aremove(
1081
- self,
1082
- item: T,
1083
- /,
1084
- ) -> None:
1085
- """Asynchronously remove a specific item from the Pile.
1086
-
1087
- Args:
1088
- item: The item to remove.
1089
-
1090
- Raises:
1091
- ValueError: If the item is not found in the Pile.
1092
- """
1093
- self._remove(item)
1094
-
1095
- @async_synchronized
1096
- async def ainclude(
1097
- self,
1098
- item: T | Iterable[T],
1099
- /,
1100
- ) -> None:
1101
- """Asynchronously include item(s) in the Pile if not already present.
1102
-
1103
- Args:
1104
- item: Item or iterable of items to include.
1105
-
1106
- Raises:
1107
- TypeError: If the item(s) are not of allowed types.
1108
- """
1109
- self._include(item)
1110
- if item not in self:
1111
- raise LionTypeError(f"Item {item} is not of allowed types")
1112
-
1113
- @async_synchronized
1114
- async def aexclude(
1115
- self,
1116
- item: T | Iterable[T],
1117
- /,
1118
- ) -> None:
1119
- """Asynchronously exclude item(s) from the Pile if present.
1120
-
1121
- Args:
1122
- item: Item or iterable of items to exclude.
1123
-
1124
- Note:
1125
- This method does not raise an error if an item is not found.
1126
- """
1127
- self._exclude(item)
1128
-
1129
- @async_synchronized
1130
- async def aclear(self) -> None:
1131
- self._clear()
1132
-
1133
- @async_synchronized
1134
- async def aupdate(
1135
- self,
1136
- other: Any,
1137
- /,
1138
- ) -> None:
1139
- self._update(other)
1140
-
1141
- @async_synchronized
1142
- async def aget(
1143
- self,
1144
- key: Any,
1145
- default=...,
1146
- /,
1147
- ) -> list | Any | T:
1148
- return self._get(key, default)
1149
-
1150
- async def __aiter__(self) -> AsyncIterator[T]:
1151
- """Return an asynchronous iterator over the items in the Pile.
1152
-
1153
- This method creates a snapshot of the current order to prevent
1154
- issues with concurrent modifications during iteration.
1155
-
1156
- Yields:
1157
- Items in the Pile in their current order.
1158
-
1159
- Note:
1160
- This method yields control to the event loop after each item,
1161
- allowing other async operations to run between iterations.
1162
- """
1163
-
1164
- async with self.async_lock:
1165
- current_order = list(self.order)
1166
-
1167
- for key in current_order:
1168
- yield self.pile_[key]
1169
- await asyncio.sleep(0) # Yield control to the event loop
1170
-
1171
- async def __anext__(self) -> T:
1172
- """Asynchronously return the next item in the Pile."""
1173
- try:
1174
- return await anext(self.AsyncPileIterator(self))
1175
- except StopAsyncIteration:
1176
- raise StopAsyncIteration("End of pile")
1177
-
1178
- class AsyncPileIterator:
1179
- def __init__(self, pile: Pile):
1180
- self.pile = pile
1181
- self.index = 0
1182
-
1183
- def __aiter__(self) -> AsyncIterator[T]:
1184
- return self
1185
-
1186
- async def __anext__(self) -> T:
1187
- if self.index >= len(self.pile):
1188
- raise StopAsyncIteration
1189
- item = self.pile[self.pile.order[self.index]]
1190
- self.index += 1
1191
- await asyncio.sleep(0) # Yield control to the event loop
1192
- return item
1193
-
1194
-
1195
- def pile(
1196
- items: Iterable[T] | None = None,
1197
- item_type: set[type] | None = None,
1198
- order=None,
1199
- use_obj=None,
1200
- csv_file=None,
1201
- df=None,
1202
- **kwargs,
1203
- ) -> Pile[T]:
1204
- """
1205
- Create a new Pile instance.
1206
-
1207
- This function provides various ways to create a Pile instance:
1208
- - Directly from items
1209
- - From a CSV file
1210
- - From a DataFrame
1211
-
1212
- Args:
1213
- items (Iterable[T] | None): The items to include in the pile.
1214
- item_type (set[Type] | None): The allowed types of items in the pile.
1215
- order (list[str] | None): The order of items.
1216
- use_obj (bool | None): Whether to treat Record and Ordering as objects.
1217
- csv_file (str | None): The path to a CSV file to load items from.
1218
- df (DataFrame | None): A DataFrame to load items from.
1219
- **kwargs: Additional keyword arguments for loading from CSV or DataFrame.
1220
-
1221
- Returns:
1222
- Pile[T]: A new Pile instance.
1223
-
1224
- Raises:
1225
- ValueError: If invalid arguments are provided.
1226
- """
1227
- if csv_file:
1228
- return Pile.from_csv(csv_file, **kwargs)
1229
- if df:
1230
- return Pile.from_df(df)
1231
-
1232
- return Pile(items, item_type, order, use_obj)