lionagi 0.3.8__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.3.8.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.3.8.dist-info/METADATA +0 -241
  563. lionagi-0.3.8.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.3.8.dist-info → lionagi-0.5.0.dist-info/licenses}/LICENSE +0 -0
@@ -1,361 +0,0 @@
1
- import contextlib
2
-
3
- from lionagi.core.action import ActionNode
4
- from lionagi.core.collections import Pile, Progression
5
- from lionagi.core.executor.base_executor import BaseExecutor
6
- from lionagi.core.generic.edge import Edge
7
- from lionagi.core.mail.mail import Mail
8
- from lionagi.core.message import Instruction, System
9
- from lionagi.core.session.branch import Branch
10
- from lionagi.libs import AsyncUtil, ParseUtil, convert
11
-
12
-
13
- class BranchExecutor(Branch, BaseExecutor):
14
-
15
- def __init__(
16
- self,
17
- context=None,
18
- verbose=True,
19
- system=None,
20
- user=None,
21
- messages=None,
22
- progress=None,
23
- tool_manager=None,
24
- tools=None,
25
- imodel=None,
26
- **kwargs,
27
- ):
28
- super().__init__(
29
- system=system,
30
- user=user,
31
- messages=messages,
32
- progress=progress,
33
- tool_manager=tool_manager,
34
- tools=tools,
35
- imodel=imodel,
36
- **kwargs,
37
- )
38
- self.context = context
39
- self.verbose = verbose
40
-
41
- async def forward(self) -> None:
42
- """
43
- Forwards the execution by processing all pending incoming mails in each branch. Depending on the category of the mail,
44
- it processes starts, nodes, node lists, conditions, or ends, accordingly executing different functions.
45
- """
46
- for key in list(self.mailbox.pending_ins.keys()):
47
- while self.mailbox.pending_ins.get(key, Pile()).size() > 0:
48
- mail_id = self.mailbox.pending_ins[key].popleft()
49
- mail = self.mailbox.pile.pop(mail_id)
50
- if mail.category == "start":
51
- self._process_start(mail)
52
- elif mail.category == "node":
53
- await self._process_node(mail)
54
- elif mail.category == "node_list":
55
- self._process_node_list(mail)
56
- elif mail.category == "condition":
57
- await self._process_condition(mail)
58
- elif mail.category == "end":
59
- self._process_end(mail)
60
- if (
61
- key in self.mailbox.pending_ins
62
- and self.mailbox.pending_ins.get(key, Pile()).size() == 0
63
- ):
64
- self.mailbox.pending_ins.pop(key)
65
-
66
- async def execute(self, refresh_time=1) -> None:
67
- """
68
- Executes the forward process repeatedly at specified time intervals until execution is instructed to stop.
69
-
70
- Args:
71
- refresh_time (int): The interval, in seconds, at which the forward method is called repeatedly.
72
- """
73
- while not self.execute_stop:
74
- await self.forward()
75
- await AsyncUtil.sleep(refresh_time)
76
-
77
- async def _process_node(self, mail: Mail):
78
- """
79
- Processes a single node based on the node type specified in the mail's package. It handles different types of nodes such as System,
80
- Instruction, ActionNode, and generic nodes through separate processes.
81
-
82
- Args:
83
- mail (Mail): The mail containing the node to be processed along with associated details.
84
-
85
- Raises:
86
- ValueError: If an invalid mail is encountered or the process encounters errors.
87
- """
88
- node = mail.package.package
89
- if isinstance(node, System):
90
- self._system_process(node, verbose=self.verbose)
91
- self.send(
92
- recipient=mail.sender,
93
- category="node_id",
94
- package=node.ln_id,
95
- request_source=self.ln_id,
96
- )
97
-
98
- elif isinstance(node, Instruction):
99
- await self._instruction_process(node, verbose=self.verbose)
100
- self.send(
101
- recipient=mail.sender,
102
- category="node_id",
103
- package=node.ln_id,
104
- request_source=self.ln_id,
105
- )
106
-
107
- elif isinstance(node, ActionNode):
108
- await self._action_process(node, verbose=self.verbose)
109
- self.send(
110
- recipient=mail.sender,
111
- category="node_id",
112
- package=node.instruction.ln_id,
113
- request_source=self.ln_id,
114
- )
115
- else:
116
- try:
117
- await self._agent_process(node, verbose=self.verbose)
118
- self.send(
119
- recipient=mail.sender,
120
- category="node_id",
121
- package=node.ln_id,
122
- request_source=self.ln_id,
123
- )
124
- except Exception as e:
125
- raise ValueError(
126
- f"Invalid mail to process. Mail:{mail}, Error: {e}"
127
- )
128
-
129
- def _process_node_list(self, mail: Mail):
130
- """
131
- Processes a list of nodes provided in the mail, but currently only sends an end signal as multiple path selection is not supported.
132
-
133
- Args:
134
- mail (BaseMail): The mail containing a list of nodes to be processed.
135
-
136
- Raises:
137
- ValueError: When trying to process multiple paths which is currently unsupported.
138
- """
139
- self.send(
140
- mail.sender,
141
- category="end",
142
- package="end",
143
- request_source=self.ln_id,
144
- )
145
- self.execute_stop = True
146
- raise ValueError(
147
- "Multiple path selection is not supported in BranchExecutor"
148
- )
149
-
150
- async def _process_condition(self, mail: Mail):
151
- """
152
- Processes a condition associated with an edge based on the mail's package, setting up the result of the condition check.
153
-
154
- Args:
155
- mail (BaseMail): The mail containing the condition to be processed.
156
- """
157
- edge: Edge = mail.package.package
158
- check_result = await edge.check_condition(self)
159
- back_mail = {
160
- "from": self.ln_id,
161
- "edge_id": edge.ln_id,
162
- "check_result": check_result,
163
- }
164
- self.send(
165
- recipient=mail.sender,
166
- category="condition",
167
- package=back_mail,
168
- request_source=self.ln_id,
169
- )
170
-
171
- def _system_process(
172
- self, system: System, verbose=True, context_verbose=False
173
- ):
174
- """
175
- Processes a system node, possibly displaying its content and context if verbose is enabled.
176
-
177
- Args:
178
- system (System): The system node to process.
179
- verbose (bool): Flag to enable verbose output.
180
- context_verbose (bool): Flag to enable verbose output specifically for context.
181
- """
182
- from lionagi.libs import SysUtil
183
-
184
- SysUtil.check_import("IPython")
185
- from IPython.display import Markdown, display
186
-
187
- if verbose:
188
- print(
189
- f"------------------Welcome: {system.sender}--------------------"
190
- )
191
- with contextlib.suppress(Exception):
192
- system.content = ParseUtil.fuzzy_parse_json(system.content)
193
- display(Markdown(f"system: {convert.to_str(system.system_info)}"))
194
- if self.context and context_verbose:
195
- display(Markdown(f"context: {convert.to_str(self.context)}"))
196
-
197
- self.add_message(system=system)
198
-
199
- async def _instruction_process(
200
- self, instruction: Instruction, verbose=True, **kwargs
201
- ):
202
- """
203
- Processes an instruction node, possibly displaying its content if verbose is enabled, and handling any additional keyword arguments.
204
-
205
- Args:
206
- instruction (Instruction): The instruction node to process.
207
- verbose (bool): Flag to enable verbose output.
208
- **kwargs: Additional keyword arguments that might affect how instructions are processed.
209
- """
210
- from lionagi.libs import SysUtil
211
-
212
- SysUtil.check_import("IPython")
213
- from IPython.display import Markdown, display
214
-
215
- if verbose:
216
- with contextlib.suppress(Exception):
217
- instruction.content = ParseUtil.fuzzy_parse_json(
218
- instruction.content
219
- )
220
- display(
221
- Markdown(
222
- f"{instruction.sender}: {convert.to_str(instruction.instruct)}"
223
- )
224
- )
225
-
226
- if self.context:
227
- result = await self.chat(
228
- instruction=instruction.instruct,
229
- context=self.context,
230
- **kwargs,
231
- )
232
- self.context = None
233
- else:
234
- result = await self.chat(
235
- instruction=instruction.instruct, **kwargs
236
- )
237
- # instruction._add_context(context=self.context)
238
- # self.context_log.append(self.context)
239
- # self.context = None
240
-
241
- with contextlib.suppress(Exception):
242
- result = ParseUtil.fuzzy_parse_json(result)
243
- if "assistant_response" in result.keys():
244
- result = result["assistant_response"]
245
- if verbose:
246
- display(
247
- Markdown(f"assistant {self.ln_id}: {convert.to_str(result)}")
248
- )
249
- print("-----------------------------------------------------")
250
-
251
- self.execution_responses.append(result)
252
-
253
- async def _action_process(self, action: ActionNode, verbose=True):
254
- """
255
- Processes an action node, executing the defined action along with any tools specified within the node.
256
-
257
- Args:
258
- action (ActionNode): The action node to process.
259
- verbose (bool): Flag to enable verbose output of the action results.
260
- """
261
- from lionagi.libs import SysUtil
262
-
263
- SysUtil.check_import("IPython")
264
- from IPython.display import Markdown, display
265
-
266
- # try:
267
- # func = getattr(self, action.action)
268
- # except:
269
- # raise ValueError(f"{action.action} is not a valid action")
270
-
271
- if verbose:
272
- display(
273
- Markdown(
274
- f"{action.instruction.sender}: {convert.to_str(action.instruction.instruct)}"
275
- )
276
- )
277
-
278
- # if action.tools:
279
- # self.register_tools(action.tools)
280
- # if self.context:
281
- # result = await self.direct(
282
- # action.directive,
283
- # instruction=action.instruction.instruct,
284
- # context=self.context,
285
- # tools=action.tools,
286
- # **action.directive_kwargs,
287
- # )
288
- result = await action.invoke(branch=self, context=self.context)
289
- self.context = None
290
- # else:
291
- # result = await self.direct(
292
- # action.directive,
293
- # instruction=action.instruction.content,
294
- # tools=action.tools,
295
- # **action.directive_kwargs
296
- # )
297
-
298
- if verbose:
299
- if action.directive == "chat":
300
- display(
301
- Markdown(
302
- f"assistant {self.ln_id}: {convert.to_str(result)}"
303
- )
304
- )
305
- else:
306
- display(Markdown(f"assistant {self.ln_id}:\n"))
307
- for k, v in result.work_fields.items():
308
- display(Markdown(f"{k}: \n{v}\n"))
309
- print("-----------------------------------------------------")
310
-
311
- self.execution_responses.append(result)
312
-
313
- async def _agent_process(self, agent, verbose=True):
314
- """
315
- Processes an agent.
316
-
317
- Args:
318
- agent: The agent to process.
319
- verbose (bool): A flag indicating whether to provide verbose output (default: True).
320
- """
321
- context = [msg["content"] for msg in self.to_chat_messages()]
322
- if verbose:
323
- print("*****************************************************")
324
- result = await agent.execute(context)
325
-
326
- if verbose:
327
- print("*****************************************************")
328
-
329
- self.context = result
330
- self.execution_responses.append(result)
331
-
332
- def _process_start(self, mail):
333
- """
334
- Processes a start mail.
335
-
336
- Args:
337
- mail (BaseMail): The start mail to process.
338
- """
339
- start_mail_content = mail.package.package
340
- self.context = start_mail_content["context"]
341
- self.send(
342
- recipient=start_mail_content["structure_id"],
343
- category="start",
344
- package="start",
345
- request_source=self.ln_id,
346
- )
347
-
348
- def _process_end(self, mail: Mail):
349
- """
350
- Processes an end mail.
351
-
352
- Args:
353
- mail (BaseMail): The end mail to process.
354
- """
355
- self.execute_stop = True
356
- self.send(
357
- recipient=mail.sender,
358
- category="end",
359
- package="end",
360
- request_source=self.ln_id,
361
- )
@@ -1,213 +0,0 @@
1
- import asyncio
2
-
3
- from pydantic import Field
4
-
5
- from lionagi.core.collections import Exchange, Pile, pile, progression
6
- from lionagi.core.engine.branch_engine import BranchExecutor
7
- from lionagi.core.executor.base_executor import BaseExecutor
8
- from lionagi.core.mail.mail import Mail, Package
9
- from lionagi.core.mail.mail_manager import MailManager
10
-
11
-
12
- class InstructionMapEngine(BaseExecutor):
13
- """
14
- Manages the execution of a mapped set of instructions across multiple branches within an executable structure.
15
-
16
- Attributes:
17
- branches (dict[str, BranchExecutor]): A dictionary of branch executors managing individual instruction flows.
18
- structure_id (str): The identifier for the structure within which these branches operate.
19
- mail_transfer (Exchange): Handles the transfer of mail between branches and other components.
20
- branch_kwargs (dict): Keyword arguments used for initializing branches.
21
- num_end_branches (int): Tracks the number of branches that have completed execution.
22
- mail_manager (MailManager): Manages the distribution and collection of mails across branches.
23
- """
24
-
25
- branches: Pile[BranchExecutor] = Field(
26
- default_factory=dict,
27
- description="The branches of the instruction mapping.",
28
- )
29
- structure_id: str = Field(
30
- "", description="The ID of the executable structure."
31
- )
32
- mail_transfer: Exchange = Field(
33
- default_factory=Exchange, description="The mail transfer."
34
- )
35
- branch_kwargs: dict = Field(
36
- default_factory=dict,
37
- description="The keyword arguments for the initializing the branches.",
38
- )
39
- num_end_branches: int = Field(0, description="The number of end branches.")
40
- mail_manager: MailManager = Field(
41
- default_factory=MailManager, description="The mail manager."
42
- )
43
-
44
- def __init__(self, **kwargs):
45
- """
46
- Initializes an InstructionMapExecutor with the given parameters.
47
-
48
- Args:
49
- **kwargs: Arbitrary keyword arguments passed to the base executor and used for initializing branch executors.
50
- """
51
- super().__init__(**kwargs)
52
- self.mail_manager = MailManager([self.mail_transfer])
53
-
54
- def transfer_ins(self):
55
- """
56
- Processes incoming mails, directing them appropriately based on their categories, and handles the initial setup
57
- of branches or the routing of node and condition mails.
58
- """
59
- for key in list(self.mailbox.pending_ins.keys()):
60
- while self.mailbox.pending_ins[key].size() > 0:
61
- mail_id = self.mailbox.pending_ins[key].popleft()
62
- mail = self.mailbox.pile.pop(mail_id)
63
- if mail.category == "start":
64
- self._process_start(mail)
65
- elif mail.category == "node_list":
66
- self._process_node_list(mail)
67
- elif (
68
- (mail.category == "node")
69
- or (mail.category == "condition")
70
- or (mail.category == "end")
71
- ):
72
- mail.sender = self.mail_transfer.ln_id
73
- mail.recipient = mail.package.request_source
74
- self.mail_transfer.include(mail, "out")
75
-
76
- def transfer_outs(self):
77
- """
78
- Processes outgoing mails from the central mail transfer, handling end-of-execution notifications and routing
79
- other mails to appropriate recipients.
80
- """
81
- for key in list(self.mail_transfer.pending_ins.keys()):
82
- while self.mail_transfer.pending_ins[key].size() > 0:
83
- mail_id = self.mail_transfer.pending_ins[key].popleft()
84
- mail = self.mail_transfer.pile.pop(mail_id)
85
- if mail.category == "end":
86
- self.num_end_branches += 1
87
- if self.num_end_branches == len(
88
- self.branches
89
- ): # tell when structure should stop
90
- mail.sender = self.ln_id
91
- mail.recipient = self.structure_id
92
- self.mailbox.include(mail, "out")
93
- self.execute_stop = True
94
- else:
95
- mail.sender = self.ln_id
96
- mail.recipient = self.structure_id
97
- self.mailbox.include(mail, "out")
98
-
99
- def _process_start(self, start_mail: Mail):
100
- """
101
- Processes a start mail to initialize a new branch executor and configures it based on the mail's package content.
102
-
103
- Args:
104
- start_mail (BaseMail): The mail initiating the start of a new branch execution.
105
- """
106
- branch = BranchExecutor(verbose=self.verbose, **self.branch_kwargs)
107
- branch.context = start_mail.package.package["context"]
108
- self.branches[branch.ln_id] = branch
109
- self.mail_manager.add_sources([branch])
110
- self.structure_id = start_mail.package.package["structure_id"]
111
-
112
- pack = Package(
113
- category="start", package="start", request_source=branch.ln_id
114
- )
115
- mail = Mail(
116
- sender=self.ln_id,
117
- recipient=self.structure_id,
118
- package=pack,
119
- )
120
- self.mailbox.include(mail, "out")
121
-
122
- def _process_node_list(self, nl_mail: Mail):
123
- """
124
- Processes a node list mail, setting up new branches or propagating the execution context based on the node list
125
- provided in the mail.
126
-
127
- Args:
128
- nl_mail (BaseMail): The mail containing a list of nodes to be processed in subsequent branches.
129
- """
130
- source_branch_id = nl_mail.package.request_source
131
- node_list = nl_mail.package.package
132
- shared_context = self.branches[source_branch_id].context
133
- shared_context_log = self.branches[source_branch_id].context_log
134
- base_branch = self.branches[source_branch_id]
135
-
136
- pack = Package(
137
- category="node",
138
- package=node_list[0],
139
- request_source=source_branch_id,
140
- )
141
- mail = Mail(
142
- sender=self.mail_transfer.ln_id,
143
- recipient=source_branch_id,
144
- package=pack,
145
- )
146
- self.mail_transfer.include(mail, "out")
147
-
148
- for i in range(1, len(node_list)):
149
- system = base_branch.system.clone() if base_branch.system else None
150
- if system:
151
- system.sender = base_branch.ln_id
152
- progress = progression()
153
- messages = pile()
154
-
155
- for id_ in base_branch.progress:
156
- clone_message = base_branch.messages[id_].clone()
157
- progress.append(clone_message.ln_id)
158
- messages.append(clone_message)
159
-
160
- branch = BranchExecutor(
161
- verbose=self.verbose,
162
- messages=messages,
163
- user=base_branch.user,
164
- system=base_branch.system.clone(),
165
- progress=progress,
166
- imodel=base_branch.imodel,
167
- )
168
- for message in branch.messages:
169
- message.sender = base_branch.ln_id
170
- message.recipient = branch.ln_id
171
-
172
- branch.context = shared_context
173
- branch.context_log = shared_context_log
174
- self.branches[branch.ln_id] = branch
175
- self.mail_manager.add_sources([branch])
176
- node_pacakge = Package(
177
- category="node",
178
- package=node_list[i],
179
- request_source=source_branch_id,
180
- )
181
- node_mail = Mail(
182
- sender=self.mail_transfer.ln_id,
183
- recipient=branch.ln_id,
184
- package=node_pacakge,
185
- )
186
- self.mail_transfer.include(node_mail, "out")
187
-
188
- async def forward(self):
189
- """
190
- Forwards the execution by processing all incoming and outgoing mails and advancing the state of all active branches.
191
- """
192
- self.transfer_ins()
193
- self.transfer_outs()
194
- self.mail_manager.collect_all()
195
- self.mail_manager.send_all()
196
- tasks = [
197
- branch.forward()
198
- for branch in self.branches.values()
199
- if branch.mailbox.pending_ins
200
- ]
201
- await asyncio.gather(*tasks)
202
- return
203
-
204
- async def execute(self, refresh_time=1):
205
- """
206
- Continuously executes the forward process at specified intervals until instructed to stop.
207
-
208
- Args:
209
- refresh_time (int): The time in seconds between execution cycles.
210
- """
211
- while not self.execute_stop:
212
- await self.forward()
213
- await asyncio.sleep(refresh_time)
@@ -1,16 +0,0 @@
1
- # filename: enhanced_script_engine.py
2
- import ast
3
-
4
-
5
- class SandboxTransformer(ast.NodeTransformer):
6
- """AST transformer to enforce restrictions in sandbox mode."""
7
-
8
- def visit_Import(self, node):
9
- raise RuntimeError(
10
- "Import statements are not allowed in sandbox mode."
11
- )
12
-
13
- def visit_Exec(self, node):
14
- raise RuntimeError("Exec statements are not allowed in sandbox mode.")
15
-
16
- # Add other visit methods for disallowed operations or nodes
@@ -1,89 +0,0 @@
1
- import ast
2
- from functools import lru_cache
3
-
4
- from lionagi.libs import AsyncUtil
5
-
6
- from ..evaluator.base_evaluator import BaseEvaluator
7
- from .sandbox_ import SandboxTransformer
8
-
9
-
10
- class ScriptEngine:
11
- def __init__(self):
12
- self.variables = {}
13
- self.safe_evaluator = BaseEvaluator()
14
- self.functions = {
15
- "processData": self.process_data,
16
- }
17
-
18
- def process_data(self, data):
19
- return data * 2
20
-
21
- def _evaluate_expression(self, expression):
22
- return self.safe_evaluator.evaluate(expression, self.variables)
23
-
24
- def _assign_variable(self, var_name, value):
25
- self.variables[var_name] = value
26
-
27
- def _execute_function(self, func_name, arg):
28
- if func_name in self.functions:
29
- return self.functions[func_name](arg)
30
- else:
31
- raise ValueError(f"Function {func_name} not defined.")
32
-
33
- def execute(self, script):
34
- tree = ast.parse(script)
35
- for stmt in tree.body:
36
- if isinstance(stmt, ast.Assign):
37
- var_name = stmt.targets[0].id
38
- value = self._evaluate_expression(ast.unparse(stmt.value))
39
- self._assign_variable(var_name, value)
40
- elif isinstance(stmt, ast.Expr) and isinstance(
41
- stmt.value, ast.Call
42
- ):
43
- func_name = stmt.value.func.id
44
- arg = self._evaluate_expression(
45
- ast.unparse(stmt.value.args[0])
46
- )
47
- result = self._execute_function(func_name, arg)
48
- # For demonstration, manually update 'x' to simulate expected behavior
49
- if func_name == "processData":
50
- self._assign_variable("x", result)
51
-
52
- def add_hook(self, event_name, callback):
53
- """Subscribe a callback function to a specific event."""
54
- self.hooks[event_name].append(callback)
55
-
56
- def trigger_hooks(self, event_name, *args, **kwargs):
57
- """Trigger all callbacks attached to a specific event."""
58
- for callback in self.hooks[event_name]:
59
- callback(*args, **kwargs)
60
-
61
- async def process_data(self, data):
62
- # Example asynchronous function
63
- return data * 2
64
-
65
- @lru_cache(maxsize=128)
66
- def evaluate_expression(self, expression):
67
- return self.safe_evaluator.evaluate(expression, self.variables)
68
-
69
- async def _execute_function_async(self, func_name, arg):
70
- if func_name in self.functions:
71
- func = self.functions[func_name]
72
- if AsyncUtil.is_coroutine_func(func):
73
- return await func(arg)
74
- else:
75
- return func(arg)
76
- else:
77
- raise ValueError(f"Function {func_name} not defined.")
78
-
79
- def execute_sandboxed(self, script):
80
- # Parse and sanitize the script
81
- tree = ast.parse(script, mode="exec")
82
- sanitized_tree = SandboxTransformer().visit(tree)
83
- ast.fix_missing_locations(sanitized_tree)
84
-
85
- # Compile the sanitized AST
86
- code = compile(sanitized_tree, "<sandbox>", "exec")
87
-
88
- # Execute the code in a restricted namespace
89
- exec(code, {"__builtins__": None}, self.variables)