lionagi 0.4.0__py3-none-any.whl → 0.5.1__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 +545 -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 +117 -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 +151 -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 +73 -0
  96. lionagi/integrations/ollama_/OllamaModel.py +244 -0
  97. lionagi/integrations/ollama_/OllamaService.py +142 -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 +418 -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 +113 -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 +125 -0
  333. lionagi/service/rate_limiter.py +108 -0
  334. lionagi/service/service.py +41 -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.1.dist-info/METADATA +545 -0
  351. lionagi-0.5.1.dist-info/RECORD +373 -0
  352. {lionagi-0.4.0.dist-info → lionagi-0.5.1.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.1.dist-info/licenses}/LICENSE +0 -0
@@ -0,0 +1,269 @@
1
+ # Copyright (c) 2023 - 2024, HaiyangLi <quantocean.li at gmail dot com>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+ import yaml
9
+ from dotenv import load_dotenv
10
+ from pydantic import (
11
+ BaseModel,
12
+ ConfigDict,
13
+ Field,
14
+ field_serializer,
15
+ model_validator,
16
+ )
17
+
18
+ from lionagi.integrations.perplexity_.api_endpoints.api_request import (
19
+ PerplexityRequest,
20
+ )
21
+ from lionagi.integrations.perplexity_.api_endpoints.chat_completions.request.request_body import (
22
+ PerplexityChatCompletionRequestBody,
23
+ )
24
+ from lionagi.integrations.perplexity_.api_endpoints.match_response import (
25
+ match_response,
26
+ )
27
+ from lionagi.service.rate_limiter import RateLimiter, RateLimitError
28
+ from lionagi.service.service_util import invoke_retry
29
+ from lionagi.service.token_calculator import TiktokenCalculator
30
+
31
+ load_dotenv()
32
+ path = Path(__file__).parent
33
+
34
+ price_config_file_name = path / "perplexity_price_data.yaml"
35
+ max_output_token_file_name = path / "perplexity_max_output_token_data.yaml"
36
+
37
+
38
+ class PerplexityModel(BaseModel):
39
+ model: str = Field(description="ID of the model to use.")
40
+
41
+ request_model: PerplexityRequest = Field(description="Making requests")
42
+
43
+ rate_limiter: RateLimiter = Field(
44
+ description="Rate Limiter to track usage"
45
+ )
46
+
47
+ text_token_calculator: TiktokenCalculator = Field(
48
+ default=None, description="Token Calculator"
49
+ )
50
+
51
+ estimated_output_len: int = Field(
52
+ default=0, description="Expected output len before making request"
53
+ )
54
+
55
+ model_config = ConfigDict(extra="forbid")
56
+
57
+ @model_validator(mode="before")
58
+ @classmethod
59
+ def parse_input(cls, data: dict):
60
+ if not isinstance(data, dict):
61
+ raise ValueError("Invalid init param")
62
+
63
+ # parse request model
64
+ request_model_params = {
65
+ "api_key": data.pop("api_key", None),
66
+ "endpoint": data.pop("endpoint", None),
67
+ "method": data.pop("method", None),
68
+ "content_type": data.pop("content_type", None),
69
+ }
70
+ try:
71
+ api_key = os.getenv(request_model_params["api_key"], None)
72
+ if api_key:
73
+ request_model_params["api_key"] = api_key
74
+ except Exception:
75
+ pass
76
+
77
+ data["request_model"] = PerplexityRequest(**request_model_params)
78
+
79
+ # parse rate limiter
80
+ if "rate_limiter" not in data:
81
+ rate_limiter_params = {}
82
+ if limit_tokens := data.pop("limit_tokens", None):
83
+ rate_limiter_params["limit_tokens"] = limit_tokens
84
+ if limit_requests := data.pop("limit_requests", None):
85
+ rate_limiter_params["limit_requests"] = limit_requests
86
+
87
+ data["rate_limiter"] = RateLimiter(**rate_limiter_params)
88
+
89
+ # parse token calculator
90
+ try:
91
+ # Perplexity uses cl100k_base encoding like OpenAI
92
+ text_calc = TiktokenCalculator(encoding_name="cl100k_base")
93
+ data["text_token_calculator"] = text_calc
94
+ except Exception:
95
+ pass
96
+
97
+ return data
98
+
99
+ @field_serializer("request_model")
100
+ def serialize_request_model(self, value: PerplexityRequest):
101
+ return value.model_dump(exclude_unset=True)
102
+
103
+ @invoke_retry(max_retries=3, base_delay=1, max_delay=60)
104
+ async def invoke(
105
+ self,
106
+ request_body: PerplexityChatCompletionRequestBody,
107
+ estimated_output_len: int = 0,
108
+ output_file=None,
109
+ parse_response=True,
110
+ ):
111
+ if request_model := getattr(request_body, "model"):
112
+ if request_model != self.model:
113
+ raise ValueError(
114
+ f"Request model does not match. Model is {self.model}, but request is made for {request_model}."
115
+ )
116
+
117
+ # check remaining rate limit
118
+ input_token_len = await self.get_input_token_len(request_body)
119
+
120
+ if getattr(request_body, "max_tokens", None):
121
+ estimated_output_len = request_body.max_tokens
122
+
123
+ invoke_viability_result = self.verify_invoke_viability(
124
+ input_tokens_len=input_token_len,
125
+ estimated_output_len=estimated_output_len,
126
+ )
127
+ if not invoke_viability_result:
128
+ raise RateLimitError(
129
+ message="Rate limit reached for requests",
130
+ input_token_len=input_token_len,
131
+ estimated_output_len=estimated_output_len,
132
+ )
133
+
134
+ try:
135
+ if getattr(request_body, "stream", None):
136
+ return await self.stream(
137
+ request_body,
138
+ output_file=output_file,
139
+ parse_response=parse_response,
140
+ )
141
+
142
+ response_body, response_headers = await self.request_model.invoke(
143
+ json_data=request_body,
144
+ output_file=output_file,
145
+ with_response_header=True,
146
+ parse_response=False,
147
+ )
148
+
149
+ if response_body:
150
+ # Update rate limit based on usage
151
+ if response_body.get("usage"):
152
+ total_token_usage = response_body["usage"]["total_tokens"]
153
+ if date_str := response_headers.get("date"):
154
+ self.rate_limiter.update_rate_limit(
155
+ date_str, total_token_usage
156
+ )
157
+ else:
158
+ self.rate_limiter.update_rate_limit(
159
+ None, total_token_usage
160
+ )
161
+ else:
162
+ self.rate_limiter.update_rate_limit(None)
163
+
164
+ if parse_response:
165
+ return match_response(self.request_model, response_body)
166
+ else:
167
+ return response_body
168
+
169
+ except Exception as e:
170
+ raise e
171
+
172
+ async def stream(
173
+ self,
174
+ request_body: PerplexityChatCompletionRequestBody,
175
+ output_file=None,
176
+ parse_response=True,
177
+ verbose=True,
178
+ ):
179
+ response_chunks = []
180
+ response_headers = None
181
+
182
+ async for chunk in self.request_model.stream(
183
+ json_data=request_body,
184
+ output_file=output_file,
185
+ with_response_header=True,
186
+ verbose=verbose,
187
+ ):
188
+ if isinstance(chunk, dict):
189
+ if "headers" in chunk:
190
+ response_headers = chunk["headers"]
191
+ else:
192
+ response_chunks.append(chunk)
193
+
194
+ # Update rate limit if we have usage information
195
+ if response_chunks and response_chunks[-1].get("usage"):
196
+ total_token_usage = response_chunks[-1]["usage"]["total_tokens"]
197
+ if date_str := response_headers.get("date"):
198
+ self.rate_limiter.update_rate_limit(
199
+ date_str, total_token_usage
200
+ )
201
+ else:
202
+ self.rate_limiter.update_rate_limit(None, total_token_usage)
203
+
204
+ if parse_response:
205
+ return match_response(self.request_model, response_chunks)
206
+ else:
207
+ return response_chunks
208
+
209
+ async def get_input_token_len(
210
+ self, request_body: PerplexityChatCompletionRequestBody
211
+ ):
212
+ if request_model := getattr(request_body, "model"):
213
+ if request_model != self.model:
214
+ raise ValueError(
215
+ f"Request model does not match. Model is {self.model}, but request is made for {request_model}."
216
+ )
217
+
218
+ total_tokens = 0
219
+ for message in request_body.messages:
220
+ total_tokens += self.text_token_calculator.calculate(
221
+ message.content
222
+ )
223
+
224
+ return total_tokens
225
+
226
+ def verify_invoke_viability(
227
+ self, input_tokens_len: int = 0, estimated_output_len: int = 0
228
+ ):
229
+ self.rate_limiter.release_tokens()
230
+
231
+ estimated_output_len = (
232
+ estimated_output_len
233
+ if estimated_output_len != 0
234
+ else self.estimated_output_len
235
+ )
236
+ if estimated_output_len == 0:
237
+ with open(max_output_token_file_name) as file:
238
+ output_token_config = yaml.safe_load(file)
239
+ estimated_output_len = output_token_config.get(self.model, 0)
240
+ self.estimated_output_len = estimated_output_len
241
+
242
+ if self.rate_limiter.check_availability(
243
+ input_tokens_len, estimated_output_len
244
+ ):
245
+ return True
246
+ else:
247
+ return False
248
+
249
+ def estimate_text_price(
250
+ self,
251
+ input_text: str,
252
+ estimated_num_of_output_tokens: int = 0,
253
+ ):
254
+ if self.text_token_calculator is None:
255
+ raise ValueError("Token calculator not available")
256
+
257
+ num_of_input_tokens = self.text_token_calculator.calculate(input_text)
258
+
259
+ with open(price_config_file_name) as file:
260
+ price_config = yaml.safe_load(file)
261
+
262
+ model_price_info_dict = price_config["model"][self.model]
263
+ estimated_price = (
264
+ model_price_info_dict["input_tokens"] * num_of_input_tokens
265
+ + model_price_info_dict["output_tokens"]
266
+ * estimated_num_of_output_tokens
267
+ )
268
+
269
+ return estimated_price
@@ -0,0 +1,113 @@
1
+ # Copyright (c) 2023 - 2024, HaiyangLi <quantocean.li at gmail dot com>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import inspect
6
+
7
+ from dotenv import load_dotenv
8
+
9
+ from lionagi.integrations.perplexity_.api_endpoints.chat_completions.request.request_body import (
10
+ PerplexityChatCompletionRequestBody,
11
+ )
12
+ from lionagi.service import Service, register_service
13
+
14
+ from .PerplexityModel import PerplexityModel
15
+
16
+ load_dotenv()
17
+
18
+
19
+ @register_service
20
+ class PerplexityService(Service):
21
+ def __init__(
22
+ self,
23
+ api_key: str,
24
+ name: str = None,
25
+ ):
26
+ super().__setattr__("_initialized", False)
27
+ self.api_key = api_key
28
+ self.name = name
29
+ self.rate_limiters = {} # model: RateLimiter
30
+ super().__setattr__("_initialized", True)
31
+
32
+ def __setattr__(self, key, value):
33
+ if getattr(self, "_initialized", False) and key in [
34
+ "api_key",
35
+ ]:
36
+ raise AttributeError(
37
+ f"Cannot modify '{key}' after initialization. "
38
+ f"Please set a new service object for new keys."
39
+ )
40
+ super().__setattr__(key, value)
41
+
42
+ def check_rate_limiter(
43
+ self,
44
+ perplexity_model: PerplexityModel,
45
+ limit_requests: int = None,
46
+ limit_tokens: int = None,
47
+ ):
48
+ # Map model versions to their base models for shared rate limiting
49
+ shared_models = {
50
+ "llama-3.1-sonar-small-128k-online": "llama-3.1-sonar-small",
51
+ "llama-3.1-sonar-medium-128k-online": "llama-3.1-sonar-medium",
52
+ "llama-3.1-sonar-large-128k-online": "llama-3.1-sonar-large",
53
+ }
54
+
55
+ if perplexity_model.model in shared_models:
56
+ model = shared_models[perplexity_model.model]
57
+ else:
58
+ model = perplexity_model.model
59
+
60
+ if model not in self.rate_limiters:
61
+ self.rate_limiters[model] = perplexity_model.rate_limiter
62
+ else:
63
+ perplexity_model.rate_limiter = self.rate_limiters[model]
64
+ if limit_requests:
65
+ perplexity_model.rate_limiter.limit_requests = limit_requests
66
+ if limit_tokens:
67
+ perplexity_model.rate_limiter.limit_tokens = limit_tokens
68
+
69
+ return perplexity_model
70
+
71
+ @staticmethod
72
+ def match_data_model(task_name: str) -> dict:
73
+ """Match task name to appropriate request and response models."""
74
+ if task_name == "create_chat_completion":
75
+ return {"request_body": PerplexityChatCompletionRequestBody}
76
+ raise ValueError(f"No data models found for task: {task_name}")
77
+
78
+ @classmethod
79
+ def list_tasks(cls):
80
+ methods = []
81
+ for name, member in inspect.getmembers(
82
+ cls, predicate=inspect.isfunction
83
+ ):
84
+ if name not in [
85
+ "__init__",
86
+ "__setattr__",
87
+ "check_rate_limiter",
88
+ "match_data_model",
89
+ ]:
90
+ methods.append(name)
91
+ return methods
92
+
93
+ # Chat Completions
94
+ def create_chat_completion(
95
+ self, model: str, limit_tokens: int = None, limit_requests: int = None
96
+ ):
97
+ model_obj = PerplexityModel(
98
+ model=model,
99
+ api_key=self.api_key,
100
+ endpoint="chat/completions",
101
+ method="POST",
102
+ content_type="application/json",
103
+ limit_tokens=limit_tokens,
104
+ limit_requests=limit_requests,
105
+ )
106
+
107
+ return self.check_rate_limiter(
108
+ model_obj, limit_requests=limit_requests, limit_tokens=limit_tokens
109
+ )
110
+
111
+ @property
112
+ def allowed_roles(self):
113
+ return ["user", "assistant", "system"]
@@ -0,0 +1,3 @@
1
+ # Copyright (c) 2023 - 2024, HaiyangLi <quantocean.li at gmail dot com>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,171 @@
1
+ import json
2
+ from collections.abc import AsyncGenerator
3
+ from typing import Any, Dict, Optional, Tuple, Union
4
+
5
+ import aiohttp
6
+ from pydantic import BaseModel, ConfigDict, Field
7
+
8
+ from lionagi.integrations.perplexity_.api_endpoints.data_models import (
9
+ PerplexityEndpointRequestBody,
10
+ )
11
+
12
+
13
+ class PerplexityRequest(BaseModel):
14
+ """Handler for making requests to the Perplexity API."""
15
+
16
+ api_key: str = Field(
17
+ description="API key for authentication", exclude=True
18
+ )
19
+ endpoint: str = Field(description="Endpoint for request")
20
+ method: str = Field(description="HTTP method")
21
+ content_type: str | None = "application/json"
22
+ base_url: str = "https://api.perplexity.ai"
23
+
24
+ model_config = ConfigDict(
25
+ arbitrary_types_allowed=True,
26
+ extra="allow", # Allow extra attributes for mocking in tests
27
+ )
28
+
29
+ async def invoke(
30
+ self,
31
+ json_data: None | (
32
+ dict[str, Any] | PerplexityEndpointRequestBody
33
+ ) = None,
34
+ form_data: BaseModel | None = None,
35
+ output_file: str | None = None,
36
+ with_response_header: bool = False,
37
+ parse_response: bool = True,
38
+ ) -> dict[str, Any] | tuple[dict[str, Any], dict[str, str]] | bytes | None:
39
+ """Make a request to the Perplexity API."""
40
+ url = f"{self.base_url}/{self.endpoint}"
41
+ headers = {
42
+ "Authorization": f"Bearer {self.api_key}",
43
+ }
44
+
45
+ if self.content_type:
46
+ headers["Content-Type"] = self.content_type
47
+
48
+ if isinstance(json_data, PerplexityEndpointRequestBody):
49
+ json_data = json_data.model_dump(exclude_unset=True)
50
+
51
+ async with aiohttp.ClientSession() as client:
52
+ response = await client.request(
53
+ method=self.method,
54
+ url=url,
55
+ headers=headers,
56
+ json=json_data,
57
+ data=form_data.model_dump() if form_data else None,
58
+ )
59
+ async with response:
60
+ if response.status != 200:
61
+ try:
62
+ error_body = await response.json()
63
+ error_msg = error_body.get("error", {}).get(
64
+ "message", str(error_body)
65
+ )
66
+ except Exception:
67
+ error_msg = await response.text()
68
+ raise Exception(
69
+ f"API request failed with status {response.status}: {error_msg}"
70
+ )
71
+
72
+ if output_file:
73
+ with open(output_file, "wb") as f:
74
+ async for chunk in response.content.iter_chunked(8192):
75
+ f.write(chunk)
76
+ return None
77
+
78
+ if parse_response:
79
+ response_body = await response.json()
80
+ else:
81
+ response_body = await response.text()
82
+ try:
83
+ response_body = json.loads(response_body)
84
+ except json.JSONDecodeError:
85
+ pass
86
+
87
+ if with_response_header:
88
+ headers = {
89
+ k.lower(): v for k, v in response.headers.items()
90
+ }
91
+ return response_body, headers
92
+ return response_body
93
+
94
+ async def stream(
95
+ self,
96
+ json_data: None | (
97
+ dict[str, Any] | PerplexityEndpointRequestBody
98
+ ) = None,
99
+ output_file: str | None = None,
100
+ with_response_header: bool = False,
101
+ verbose: bool = True,
102
+ ) -> AsyncGenerator[dict[str, Any], None]:
103
+ """Stream responses from the Perplexity API."""
104
+ if isinstance(json_data, PerplexityEndpointRequestBody):
105
+ json_data = json_data.model_dump(exclude_unset=True)
106
+
107
+ if not json_data.get("stream", False):
108
+ json_data["stream"] = True
109
+
110
+ url = f"{self.base_url}/{self.endpoint}"
111
+ headers = {
112
+ "Authorization": f"Bearer {self.api_key}",
113
+ "Content-Type": "application/json",
114
+ "Accept": "text/event-stream",
115
+ }
116
+
117
+ async with aiohttp.ClientSession() as client:
118
+ response = await client.post(url, headers=headers, json=json_data)
119
+ async with response:
120
+ if response.status != 200:
121
+ try:
122
+ error_body = await response.json()
123
+ error_msg = error_body.get("error", {}).get(
124
+ "message", str(error_body)
125
+ )
126
+ except Exception:
127
+ error_msg = await response.text()
128
+ raise Exception(
129
+ f"API request failed with status {response.status}: {error_msg}"
130
+ )
131
+
132
+ if with_response_header:
133
+ headers = {
134
+ k.lower(): v for k, v in response.headers.items()
135
+ }
136
+ yield {"headers": headers}
137
+
138
+ file_handle = None
139
+ if output_file:
140
+ try:
141
+ file_handle = open(output_file, "w")
142
+ except Exception as e:
143
+ raise ValueError(
144
+ f"Failed to open output file {output_file}: {e}"
145
+ )
146
+
147
+ try:
148
+ async for chunk in response.content:
149
+ if chunk:
150
+ chunk_str = chunk.decode("utf-8").strip()
151
+ if chunk_str.startswith("data: "):
152
+ chunk_str = chunk_str[
153
+ 6:
154
+ ] # Remove "data: " prefix
155
+ try:
156
+ chunk_data = json.loads(chunk_str)
157
+ if file_handle:
158
+ file_handle.write(
159
+ json.dumps(chunk_data) + "\n"
160
+ )
161
+ if verbose and "choices" in chunk_data:
162
+ content = chunk_data["choices"][0][
163
+ "delta"
164
+ ]["content"]
165
+ print(content, end="", flush=True)
166
+ yield chunk_data
167
+ except json.JSONDecodeError:
168
+ continue
169
+ finally:
170
+ if file_handle:
171
+ file_handle.close()
@@ -0,0 +1,121 @@
1
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
2
+
3
+ from lionagi.integrations.perplexity_.api_endpoints.data_models import (
4
+ PerplexityEndpointRequestBody,
5
+ )
6
+
7
+
8
+ class Message(BaseModel):
9
+ """A message in the chat completion request."""
10
+
11
+ role: str = Field(description="The role of the message author.")
12
+ content: str = Field(description="The content of the message.")
13
+
14
+ model_config = ConfigDict(extra="forbid")
15
+
16
+ @field_validator("role")
17
+ @classmethod
18
+ def validate_role(cls, role: str) -> str:
19
+ valid_roles = ["system", "user", "assistant"]
20
+ if role not in valid_roles:
21
+ raise ValueError(f"Role must be one of {valid_roles}")
22
+ return role
23
+
24
+ @field_validator("content")
25
+ @classmethod
26
+ def validate_content(cls, content: str) -> str:
27
+ if not content or not content.strip():
28
+ raise ValueError("Content cannot be empty")
29
+ return content
30
+
31
+
32
+ class PerplexityChatCompletionRequestBody(PerplexityEndpointRequestBody):
33
+ """Request body for chat completion requests."""
34
+
35
+ model: str = Field(description="ID of the model to use.")
36
+ messages: list[Message] = Field(
37
+ description="A list of messages comprising the conversation so far."
38
+ )
39
+ max_tokens: int | None = Field(
40
+ default=None,
41
+ description="The maximum number of tokens to generate in the completion.",
42
+ ge=1,
43
+ )
44
+ temperature: float | None = Field(
45
+ default=0.2,
46
+ description="What sampling temperature to use, between 0 and 2.",
47
+ ge=0,
48
+ lt=2,
49
+ )
50
+ top_p: float | None = Field(
51
+ default=0.9,
52
+ description="An alternative to sampling with temperature, called nucleus sampling.",
53
+ ge=0,
54
+ le=1,
55
+ )
56
+ search_domain_filter: list[str] | None = Field(
57
+ default=None,
58
+ description="List of domains to limit citations to.",
59
+ )
60
+ return_images: bool | None = Field(
61
+ default=False,
62
+ description="Whether to return images in the response.",
63
+ )
64
+ return_related_questions: bool | None = Field(
65
+ default=False,
66
+ description="Whether to return related questions in the response.",
67
+ )
68
+ search_recency_filter: str | None = Field(
69
+ default=None,
70
+ description="Filter for search results recency (month, week, day, hour).",
71
+ )
72
+ top_k: int | None = Field(
73
+ default=0,
74
+ description="The number of tokens to keep for highest top-k filtering.",
75
+ ge=0,
76
+ le=2048,
77
+ )
78
+ stream: bool | None = Field(
79
+ default=False,
80
+ description="Whether to stream back partial progress.",
81
+ )
82
+ presence_penalty: float | None = Field(
83
+ default=0,
84
+ description="Penalty for new tokens based on their presence in text so far.",
85
+ ge=-2,
86
+ le=2,
87
+ )
88
+ frequency_penalty: float | None = Field(
89
+ default=1,
90
+ description="Penalty for new tokens based on their frequency in text so far.",
91
+ gt=0,
92
+ )
93
+
94
+ model_config = ConfigDict(extra="forbid")
95
+
96
+ @field_validator("search_recency_filter")
97
+ @classmethod
98
+ def validate_search_recency_filter(cls, value: str | None) -> str | None:
99
+ if value is not None:
100
+ valid_filters = ["month", "week", "day", "hour"]
101
+ if value not in valid_filters:
102
+ raise ValueError(
103
+ f"Search recency filter must be one of {valid_filters}"
104
+ )
105
+ return value
106
+
107
+ @field_validator("search_domain_filter")
108
+ @classmethod
109
+ def validate_search_domain_filter(
110
+ cls, value: list[str] | None
111
+ ) -> list[str] | None:
112
+ if value is not None and len(value) > 3:
113
+ raise ValueError("Search domain filter is limited to 3 domains")
114
+ return value
115
+
116
+ @field_validator("messages")
117
+ @classmethod
118
+ def validate_messages(cls, messages: list[Message]) -> list[Message]:
119
+ if not messages:
120
+ raise ValueError("At least one message is required")
121
+ return messages