aiecs 1.0.1__py3-none-any.whl → 1.7.17__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of aiecs might be problematic. Click here for more details.

Files changed (340) hide show
  1. aiecs/__init__.py +13 -16
  2. aiecs/__main__.py +7 -7
  3. aiecs/aiecs_client.py +269 -75
  4. aiecs/application/executors/operation_executor.py +79 -54
  5. aiecs/application/knowledge_graph/__init__.py +7 -0
  6. aiecs/application/knowledge_graph/builder/__init__.py +37 -0
  7. aiecs/application/knowledge_graph/builder/data_quality.py +302 -0
  8. aiecs/application/knowledge_graph/builder/data_reshaping.py +293 -0
  9. aiecs/application/knowledge_graph/builder/document_builder.py +369 -0
  10. aiecs/application/knowledge_graph/builder/graph_builder.py +490 -0
  11. aiecs/application/knowledge_graph/builder/import_optimizer.py +396 -0
  12. aiecs/application/knowledge_graph/builder/schema_inference.py +462 -0
  13. aiecs/application/knowledge_graph/builder/schema_mapping.py +563 -0
  14. aiecs/application/knowledge_graph/builder/structured_pipeline.py +1384 -0
  15. aiecs/application/knowledge_graph/builder/text_chunker.py +317 -0
  16. aiecs/application/knowledge_graph/extractors/__init__.py +27 -0
  17. aiecs/application/knowledge_graph/extractors/base.py +98 -0
  18. aiecs/application/knowledge_graph/extractors/llm_entity_extractor.py +422 -0
  19. aiecs/application/knowledge_graph/extractors/llm_relation_extractor.py +347 -0
  20. aiecs/application/knowledge_graph/extractors/ner_entity_extractor.py +241 -0
  21. aiecs/application/knowledge_graph/fusion/__init__.py +78 -0
  22. aiecs/application/knowledge_graph/fusion/ab_testing.py +395 -0
  23. aiecs/application/knowledge_graph/fusion/abbreviation_expander.py +327 -0
  24. aiecs/application/knowledge_graph/fusion/alias_index.py +597 -0
  25. aiecs/application/knowledge_graph/fusion/alias_matcher.py +384 -0
  26. aiecs/application/knowledge_graph/fusion/cache_coordinator.py +343 -0
  27. aiecs/application/knowledge_graph/fusion/entity_deduplicator.py +433 -0
  28. aiecs/application/knowledge_graph/fusion/entity_linker.py +511 -0
  29. aiecs/application/knowledge_graph/fusion/evaluation_dataset.py +240 -0
  30. aiecs/application/knowledge_graph/fusion/knowledge_fusion.py +632 -0
  31. aiecs/application/knowledge_graph/fusion/matching_config.py +489 -0
  32. aiecs/application/knowledge_graph/fusion/name_normalizer.py +352 -0
  33. aiecs/application/knowledge_graph/fusion/relation_deduplicator.py +183 -0
  34. aiecs/application/knowledge_graph/fusion/semantic_name_matcher.py +464 -0
  35. aiecs/application/knowledge_graph/fusion/similarity_pipeline.py +534 -0
  36. aiecs/application/knowledge_graph/pattern_matching/__init__.py +21 -0
  37. aiecs/application/knowledge_graph/pattern_matching/pattern_matcher.py +342 -0
  38. aiecs/application/knowledge_graph/pattern_matching/query_executor.py +366 -0
  39. aiecs/application/knowledge_graph/profiling/__init__.py +12 -0
  40. aiecs/application/knowledge_graph/profiling/query_plan_visualizer.py +195 -0
  41. aiecs/application/knowledge_graph/profiling/query_profiler.py +223 -0
  42. aiecs/application/knowledge_graph/reasoning/__init__.py +27 -0
  43. aiecs/application/knowledge_graph/reasoning/evidence_synthesis.py +341 -0
  44. aiecs/application/knowledge_graph/reasoning/inference_engine.py +500 -0
  45. aiecs/application/knowledge_graph/reasoning/logic_form_parser.py +163 -0
  46. aiecs/application/knowledge_graph/reasoning/logic_parser/__init__.py +79 -0
  47. aiecs/application/knowledge_graph/reasoning/logic_parser/ast_builder.py +513 -0
  48. aiecs/application/knowledge_graph/reasoning/logic_parser/ast_nodes.py +913 -0
  49. aiecs/application/knowledge_graph/reasoning/logic_parser/ast_validator.py +866 -0
  50. aiecs/application/knowledge_graph/reasoning/logic_parser/error_handler.py +475 -0
  51. aiecs/application/knowledge_graph/reasoning/logic_parser/parser.py +396 -0
  52. aiecs/application/knowledge_graph/reasoning/logic_parser/query_context.py +208 -0
  53. aiecs/application/knowledge_graph/reasoning/logic_query_integration.py +170 -0
  54. aiecs/application/knowledge_graph/reasoning/query_planner.py +855 -0
  55. aiecs/application/knowledge_graph/reasoning/reasoning_engine.py +518 -0
  56. aiecs/application/knowledge_graph/retrieval/__init__.py +27 -0
  57. aiecs/application/knowledge_graph/retrieval/query_intent_classifier.py +211 -0
  58. aiecs/application/knowledge_graph/retrieval/retrieval_strategies.py +592 -0
  59. aiecs/application/knowledge_graph/retrieval/strategy_types.py +23 -0
  60. aiecs/application/knowledge_graph/search/__init__.py +59 -0
  61. aiecs/application/knowledge_graph/search/hybrid_search.py +457 -0
  62. aiecs/application/knowledge_graph/search/reranker.py +293 -0
  63. aiecs/application/knowledge_graph/search/reranker_strategies.py +535 -0
  64. aiecs/application/knowledge_graph/search/text_similarity.py +392 -0
  65. aiecs/application/knowledge_graph/traversal/__init__.py +15 -0
  66. aiecs/application/knowledge_graph/traversal/enhanced_traversal.py +305 -0
  67. aiecs/application/knowledge_graph/traversal/path_scorer.py +271 -0
  68. aiecs/application/knowledge_graph/validators/__init__.py +13 -0
  69. aiecs/application/knowledge_graph/validators/relation_validator.py +239 -0
  70. aiecs/application/knowledge_graph/visualization/__init__.py +11 -0
  71. aiecs/application/knowledge_graph/visualization/graph_visualizer.py +313 -0
  72. aiecs/common/__init__.py +9 -0
  73. aiecs/common/knowledge_graph/__init__.py +17 -0
  74. aiecs/common/knowledge_graph/runnable.py +471 -0
  75. aiecs/config/__init__.py +20 -5
  76. aiecs/config/config.py +762 -31
  77. aiecs/config/graph_config.py +131 -0
  78. aiecs/config/tool_config.py +435 -0
  79. aiecs/core/__init__.py +29 -13
  80. aiecs/core/interface/__init__.py +2 -2
  81. aiecs/core/interface/execution_interface.py +22 -22
  82. aiecs/core/interface/storage_interface.py +37 -88
  83. aiecs/core/registry/__init__.py +31 -0
  84. aiecs/core/registry/service_registry.py +92 -0
  85. aiecs/domain/__init__.py +270 -1
  86. aiecs/domain/agent/__init__.py +191 -0
  87. aiecs/domain/agent/base_agent.py +3949 -0
  88. aiecs/domain/agent/exceptions.py +99 -0
  89. aiecs/domain/agent/graph_aware_mixin.py +569 -0
  90. aiecs/domain/agent/hybrid_agent.py +1731 -0
  91. aiecs/domain/agent/integration/__init__.py +29 -0
  92. aiecs/domain/agent/integration/context_compressor.py +216 -0
  93. aiecs/domain/agent/integration/context_engine_adapter.py +587 -0
  94. aiecs/domain/agent/integration/protocols.py +281 -0
  95. aiecs/domain/agent/integration/retry_policy.py +218 -0
  96. aiecs/domain/agent/integration/role_config.py +213 -0
  97. aiecs/domain/agent/knowledge_aware_agent.py +1892 -0
  98. aiecs/domain/agent/lifecycle.py +291 -0
  99. aiecs/domain/agent/llm_agent.py +692 -0
  100. aiecs/domain/agent/memory/__init__.py +12 -0
  101. aiecs/domain/agent/memory/conversation.py +1124 -0
  102. aiecs/domain/agent/migration/__init__.py +14 -0
  103. aiecs/domain/agent/migration/conversion.py +163 -0
  104. aiecs/domain/agent/migration/legacy_wrapper.py +86 -0
  105. aiecs/domain/agent/models.py +894 -0
  106. aiecs/domain/agent/observability.py +479 -0
  107. aiecs/domain/agent/persistence.py +449 -0
  108. aiecs/domain/agent/prompts/__init__.py +29 -0
  109. aiecs/domain/agent/prompts/builder.py +159 -0
  110. aiecs/domain/agent/prompts/formatters.py +187 -0
  111. aiecs/domain/agent/prompts/template.py +255 -0
  112. aiecs/domain/agent/registry.py +253 -0
  113. aiecs/domain/agent/tool_agent.py +444 -0
  114. aiecs/domain/agent/tools/__init__.py +15 -0
  115. aiecs/domain/agent/tools/schema_generator.py +377 -0
  116. aiecs/domain/community/__init__.py +155 -0
  117. aiecs/domain/community/agent_adapter.py +469 -0
  118. aiecs/domain/community/analytics.py +432 -0
  119. aiecs/domain/community/collaborative_workflow.py +648 -0
  120. aiecs/domain/community/communication_hub.py +634 -0
  121. aiecs/domain/community/community_builder.py +320 -0
  122. aiecs/domain/community/community_integration.py +796 -0
  123. aiecs/domain/community/community_manager.py +803 -0
  124. aiecs/domain/community/decision_engine.py +849 -0
  125. aiecs/domain/community/exceptions.py +231 -0
  126. aiecs/domain/community/models/__init__.py +33 -0
  127. aiecs/domain/community/models/community_models.py +234 -0
  128. aiecs/domain/community/resource_manager.py +461 -0
  129. aiecs/domain/community/shared_context_manager.py +589 -0
  130. aiecs/domain/context/__init__.py +40 -10
  131. aiecs/domain/context/context_engine.py +1910 -0
  132. aiecs/domain/context/conversation_models.py +87 -53
  133. aiecs/domain/context/graph_memory.py +582 -0
  134. aiecs/domain/execution/model.py +12 -4
  135. aiecs/domain/knowledge_graph/__init__.py +19 -0
  136. aiecs/domain/knowledge_graph/models/__init__.py +52 -0
  137. aiecs/domain/knowledge_graph/models/entity.py +148 -0
  138. aiecs/domain/knowledge_graph/models/evidence.py +178 -0
  139. aiecs/domain/knowledge_graph/models/inference_rule.py +184 -0
  140. aiecs/domain/knowledge_graph/models/path.py +171 -0
  141. aiecs/domain/knowledge_graph/models/path_pattern.py +171 -0
  142. aiecs/domain/knowledge_graph/models/query.py +261 -0
  143. aiecs/domain/knowledge_graph/models/query_plan.py +181 -0
  144. aiecs/domain/knowledge_graph/models/relation.py +202 -0
  145. aiecs/domain/knowledge_graph/schema/__init__.py +23 -0
  146. aiecs/domain/knowledge_graph/schema/entity_type.py +131 -0
  147. aiecs/domain/knowledge_graph/schema/graph_schema.py +253 -0
  148. aiecs/domain/knowledge_graph/schema/property_schema.py +143 -0
  149. aiecs/domain/knowledge_graph/schema/relation_type.py +163 -0
  150. aiecs/domain/knowledge_graph/schema/schema_manager.py +691 -0
  151. aiecs/domain/knowledge_graph/schema/type_enums.py +209 -0
  152. aiecs/domain/task/dsl_processor.py +172 -56
  153. aiecs/domain/task/model.py +20 -8
  154. aiecs/domain/task/task_context.py +27 -24
  155. aiecs/infrastructure/__init__.py +0 -2
  156. aiecs/infrastructure/graph_storage/__init__.py +11 -0
  157. aiecs/infrastructure/graph_storage/base.py +837 -0
  158. aiecs/infrastructure/graph_storage/batch_operations.py +458 -0
  159. aiecs/infrastructure/graph_storage/cache.py +424 -0
  160. aiecs/infrastructure/graph_storage/distributed.py +223 -0
  161. aiecs/infrastructure/graph_storage/error_handling.py +380 -0
  162. aiecs/infrastructure/graph_storage/graceful_degradation.py +294 -0
  163. aiecs/infrastructure/graph_storage/health_checks.py +378 -0
  164. aiecs/infrastructure/graph_storage/in_memory.py +1197 -0
  165. aiecs/infrastructure/graph_storage/index_optimization.py +446 -0
  166. aiecs/infrastructure/graph_storage/lazy_loading.py +431 -0
  167. aiecs/infrastructure/graph_storage/metrics.py +344 -0
  168. aiecs/infrastructure/graph_storage/migration.py +400 -0
  169. aiecs/infrastructure/graph_storage/pagination.py +483 -0
  170. aiecs/infrastructure/graph_storage/performance_monitoring.py +456 -0
  171. aiecs/infrastructure/graph_storage/postgres.py +1563 -0
  172. aiecs/infrastructure/graph_storage/property_storage.py +353 -0
  173. aiecs/infrastructure/graph_storage/protocols.py +76 -0
  174. aiecs/infrastructure/graph_storage/query_optimizer.py +642 -0
  175. aiecs/infrastructure/graph_storage/schema_cache.py +290 -0
  176. aiecs/infrastructure/graph_storage/sqlite.py +1373 -0
  177. aiecs/infrastructure/graph_storage/streaming.py +487 -0
  178. aiecs/infrastructure/graph_storage/tenant.py +412 -0
  179. aiecs/infrastructure/messaging/celery_task_manager.py +92 -54
  180. aiecs/infrastructure/messaging/websocket_manager.py +51 -35
  181. aiecs/infrastructure/monitoring/__init__.py +22 -0
  182. aiecs/infrastructure/monitoring/executor_metrics.py +45 -11
  183. aiecs/infrastructure/monitoring/global_metrics_manager.py +212 -0
  184. aiecs/infrastructure/monitoring/structured_logger.py +3 -7
  185. aiecs/infrastructure/monitoring/tracing_manager.py +63 -35
  186. aiecs/infrastructure/persistence/__init__.py +14 -1
  187. aiecs/infrastructure/persistence/context_engine_client.py +184 -0
  188. aiecs/infrastructure/persistence/database_manager.py +67 -43
  189. aiecs/infrastructure/persistence/file_storage.py +180 -103
  190. aiecs/infrastructure/persistence/redis_client.py +74 -21
  191. aiecs/llm/__init__.py +73 -25
  192. aiecs/llm/callbacks/__init__.py +11 -0
  193. aiecs/llm/{custom_callbacks.py → callbacks/custom_callbacks.py} +26 -19
  194. aiecs/llm/client_factory.py +230 -37
  195. aiecs/llm/client_resolver.py +155 -0
  196. aiecs/llm/clients/__init__.py +38 -0
  197. aiecs/llm/clients/base_client.py +328 -0
  198. aiecs/llm/clients/google_function_calling_mixin.py +415 -0
  199. aiecs/llm/clients/googleai_client.py +314 -0
  200. aiecs/llm/clients/openai_client.py +158 -0
  201. aiecs/llm/clients/openai_compatible_mixin.py +367 -0
  202. aiecs/llm/clients/vertex_client.py +1186 -0
  203. aiecs/llm/clients/xai_client.py +201 -0
  204. aiecs/llm/config/__init__.py +51 -0
  205. aiecs/llm/config/config_loader.py +272 -0
  206. aiecs/llm/config/config_validator.py +206 -0
  207. aiecs/llm/config/model_config.py +143 -0
  208. aiecs/llm/protocols.py +149 -0
  209. aiecs/llm/utils/__init__.py +10 -0
  210. aiecs/llm/utils/validate_config.py +89 -0
  211. aiecs/main.py +140 -121
  212. aiecs/scripts/aid/VERSION_MANAGEMENT.md +138 -0
  213. aiecs/scripts/aid/__init__.py +19 -0
  214. aiecs/scripts/aid/module_checker.py +499 -0
  215. aiecs/scripts/aid/version_manager.py +235 -0
  216. aiecs/scripts/{DEPENDENCY_SYSTEM_SUMMARY.md → dependance_check/DEPENDENCY_SYSTEM_SUMMARY.md} +1 -0
  217. aiecs/scripts/{README_DEPENDENCY_CHECKER.md → dependance_check/README_DEPENDENCY_CHECKER.md} +1 -0
  218. aiecs/scripts/dependance_check/__init__.py +15 -0
  219. aiecs/scripts/dependance_check/dependency_checker.py +1835 -0
  220. aiecs/scripts/{dependency_fixer.py → dependance_check/dependency_fixer.py} +192 -90
  221. aiecs/scripts/{download_nlp_data.py → dependance_check/download_nlp_data.py} +203 -71
  222. aiecs/scripts/dependance_patch/__init__.py +7 -0
  223. aiecs/scripts/dependance_patch/fix_weasel/__init__.py +11 -0
  224. aiecs/scripts/{fix_weasel_validator.py → dependance_patch/fix_weasel/fix_weasel_validator.py} +21 -14
  225. aiecs/scripts/{patch_weasel_library.sh → dependance_patch/fix_weasel/patch_weasel_library.sh} +1 -1
  226. aiecs/scripts/knowledge_graph/__init__.py +3 -0
  227. aiecs/scripts/knowledge_graph/run_threshold_experiments.py +212 -0
  228. aiecs/scripts/migrations/multi_tenancy/README.md +142 -0
  229. aiecs/scripts/tools_develop/README.md +671 -0
  230. aiecs/scripts/tools_develop/README_CONFIG_CHECKER.md +273 -0
  231. aiecs/scripts/tools_develop/TOOLS_CONFIG_GUIDE.md +1287 -0
  232. aiecs/scripts/tools_develop/TOOL_AUTO_DISCOVERY.md +234 -0
  233. aiecs/scripts/tools_develop/__init__.py +21 -0
  234. aiecs/scripts/tools_develop/check_all_tools_config.py +548 -0
  235. aiecs/scripts/tools_develop/check_type_annotations.py +257 -0
  236. aiecs/scripts/tools_develop/pre-commit-schema-coverage.sh +66 -0
  237. aiecs/scripts/tools_develop/schema_coverage.py +511 -0
  238. aiecs/scripts/tools_develop/validate_tool_schemas.py +475 -0
  239. aiecs/scripts/tools_develop/verify_executor_config_fix.py +98 -0
  240. aiecs/scripts/tools_develop/verify_tools.py +352 -0
  241. aiecs/tasks/__init__.py +0 -1
  242. aiecs/tasks/worker.py +115 -47
  243. aiecs/tools/__init__.py +194 -72
  244. aiecs/tools/apisource/__init__.py +99 -0
  245. aiecs/tools/apisource/intelligence/__init__.py +19 -0
  246. aiecs/tools/apisource/intelligence/data_fusion.py +632 -0
  247. aiecs/tools/apisource/intelligence/query_analyzer.py +417 -0
  248. aiecs/tools/apisource/intelligence/search_enhancer.py +385 -0
  249. aiecs/tools/apisource/monitoring/__init__.py +9 -0
  250. aiecs/tools/apisource/monitoring/metrics.py +330 -0
  251. aiecs/tools/apisource/providers/__init__.py +112 -0
  252. aiecs/tools/apisource/providers/base.py +671 -0
  253. aiecs/tools/apisource/providers/census.py +397 -0
  254. aiecs/tools/apisource/providers/fred.py +535 -0
  255. aiecs/tools/apisource/providers/newsapi.py +409 -0
  256. aiecs/tools/apisource/providers/worldbank.py +352 -0
  257. aiecs/tools/apisource/reliability/__init__.py +12 -0
  258. aiecs/tools/apisource/reliability/error_handler.py +363 -0
  259. aiecs/tools/apisource/reliability/fallback_strategy.py +376 -0
  260. aiecs/tools/apisource/tool.py +832 -0
  261. aiecs/tools/apisource/utils/__init__.py +9 -0
  262. aiecs/tools/apisource/utils/validators.py +334 -0
  263. aiecs/tools/base_tool.py +415 -21
  264. aiecs/tools/docs/__init__.py +121 -0
  265. aiecs/tools/docs/ai_document_orchestrator.py +607 -0
  266. aiecs/tools/docs/ai_document_writer_orchestrator.py +2350 -0
  267. aiecs/tools/docs/content_insertion_tool.py +1320 -0
  268. aiecs/tools/docs/document_creator_tool.py +1464 -0
  269. aiecs/tools/docs/document_layout_tool.py +1160 -0
  270. aiecs/tools/docs/document_parser_tool.py +1016 -0
  271. aiecs/tools/docs/document_writer_tool.py +2008 -0
  272. aiecs/tools/knowledge_graph/__init__.py +17 -0
  273. aiecs/tools/knowledge_graph/graph_reasoning_tool.py +807 -0
  274. aiecs/tools/knowledge_graph/graph_search_tool.py +944 -0
  275. aiecs/tools/knowledge_graph/kg_builder_tool.py +524 -0
  276. aiecs/tools/langchain_adapter.py +300 -138
  277. aiecs/tools/schema_generator.py +455 -0
  278. aiecs/tools/search_tool/__init__.py +100 -0
  279. aiecs/tools/search_tool/analyzers.py +581 -0
  280. aiecs/tools/search_tool/cache.py +264 -0
  281. aiecs/tools/search_tool/constants.py +128 -0
  282. aiecs/tools/search_tool/context.py +224 -0
  283. aiecs/tools/search_tool/core.py +778 -0
  284. aiecs/tools/search_tool/deduplicator.py +119 -0
  285. aiecs/tools/search_tool/error_handler.py +242 -0
  286. aiecs/tools/search_tool/metrics.py +343 -0
  287. aiecs/tools/search_tool/rate_limiter.py +172 -0
  288. aiecs/tools/search_tool/schemas.py +275 -0
  289. aiecs/tools/statistics/__init__.py +80 -0
  290. aiecs/tools/statistics/ai_data_analysis_orchestrator.py +646 -0
  291. aiecs/tools/statistics/ai_insight_generator_tool.py +508 -0
  292. aiecs/tools/statistics/ai_report_orchestrator_tool.py +684 -0
  293. aiecs/tools/statistics/data_loader_tool.py +555 -0
  294. aiecs/tools/statistics/data_profiler_tool.py +638 -0
  295. aiecs/tools/statistics/data_transformer_tool.py +580 -0
  296. aiecs/tools/statistics/data_visualizer_tool.py +498 -0
  297. aiecs/tools/statistics/model_trainer_tool.py +507 -0
  298. aiecs/tools/statistics/statistical_analyzer_tool.py +472 -0
  299. aiecs/tools/task_tools/__init__.py +49 -36
  300. aiecs/tools/task_tools/chart_tool.py +200 -184
  301. aiecs/tools/task_tools/classfire_tool.py +268 -267
  302. aiecs/tools/task_tools/image_tool.py +220 -141
  303. aiecs/tools/task_tools/office_tool.py +226 -146
  304. aiecs/tools/task_tools/pandas_tool.py +477 -121
  305. aiecs/tools/task_tools/report_tool.py +390 -142
  306. aiecs/tools/task_tools/research_tool.py +149 -79
  307. aiecs/tools/task_tools/scraper_tool.py +339 -145
  308. aiecs/tools/task_tools/stats_tool.py +448 -209
  309. aiecs/tools/temp_file_manager.py +26 -24
  310. aiecs/tools/tool_executor/__init__.py +18 -16
  311. aiecs/tools/tool_executor/tool_executor.py +364 -52
  312. aiecs/utils/LLM_output_structor.py +74 -48
  313. aiecs/utils/__init__.py +14 -3
  314. aiecs/utils/base_callback.py +0 -3
  315. aiecs/utils/cache_provider.py +696 -0
  316. aiecs/utils/execution_utils.py +50 -31
  317. aiecs/utils/prompt_loader.py +1 -0
  318. aiecs/utils/token_usage_repository.py +37 -11
  319. aiecs/ws/socket_server.py +14 -4
  320. {aiecs-1.0.1.dist-info → aiecs-1.7.17.dist-info}/METADATA +52 -15
  321. aiecs-1.7.17.dist-info/RECORD +337 -0
  322. aiecs-1.7.17.dist-info/entry_points.txt +13 -0
  323. aiecs/config/registry.py +0 -19
  324. aiecs/domain/context/content_engine.py +0 -982
  325. aiecs/llm/base_client.py +0 -99
  326. aiecs/llm/openai_client.py +0 -125
  327. aiecs/llm/vertex_client.py +0 -186
  328. aiecs/llm/xai_client.py +0 -184
  329. aiecs/scripts/dependency_checker.py +0 -857
  330. aiecs/scripts/quick_dependency_check.py +0 -269
  331. aiecs/tools/task_tools/search_api.py +0 -7
  332. aiecs-1.0.1.dist-info/RECORD +0 -90
  333. aiecs-1.0.1.dist-info/entry_points.txt +0 -7
  334. /aiecs/scripts/{setup_nlp_data.sh → dependance_check/setup_nlp_data.sh} +0 -0
  335. /aiecs/scripts/{README_WEASEL_PATCH.md → dependance_patch/fix_weasel/README_WEASEL_PATCH.md} +0 -0
  336. /aiecs/scripts/{fix_weasel_validator.sh → dependance_patch/fix_weasel/fix_weasel_validator.sh} +0 -0
  337. /aiecs/scripts/{run_weasel_patch.sh → dependance_patch/fix_weasel/run_weasel_patch.sh} +0 -0
  338. {aiecs-1.0.1.dist-info → aiecs-1.7.17.dist-info}/WHEEL +0 -0
  339. {aiecs-1.0.1.dist-info → aiecs-1.7.17.dist-info}/licenses/LICENSE +0 -0
  340. {aiecs-1.0.1.dist-info → aiecs-1.7.17.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,894 @@
1
+ """
2
+ Agent Domain Models
3
+
4
+ Defines the core data models for the base AI agent system.
5
+ """
6
+
7
+ from datetime import datetime
8
+ from typing import Dict, List, Any, Optional
9
+ from enum import Enum
10
+ from pydantic import BaseModel, Field, ConfigDict
11
+ import uuid
12
+
13
+
14
+ class AgentState(str, Enum):
15
+ """Agent lifecycle states."""
16
+
17
+ CREATED = "created"
18
+ INITIALIZING = "initializing"
19
+ ACTIVE = "active"
20
+ IDLE = "idle"
21
+ BUSY = "busy"
22
+ ERROR = "error"
23
+ STOPPED = "stopped"
24
+
25
+
26
+ class AgentType(str, Enum):
27
+ """Types of AI agents."""
28
+
29
+ CONVERSATIONAL = "conversational"
30
+ TASK_EXECUTOR = "task_executor"
31
+ RESEARCHER = "researcher"
32
+ ANALYST = "analyst"
33
+ CREATIVE = "creative"
34
+ DEVELOPER = "developer"
35
+ COORDINATOR = "coordinator"
36
+
37
+
38
+ class GoalStatus(str, Enum):
39
+ """Status of agent goals."""
40
+
41
+ PENDING = "pending"
42
+ IN_PROGRESS = "in_progress"
43
+ ACHIEVED = "achieved"
44
+ FAILED = "failed"
45
+ ABANDONED = "abandoned"
46
+
47
+
48
+ class GoalPriority(str, Enum):
49
+ """Priority levels for goals."""
50
+
51
+ LOW = "low"
52
+ MEDIUM = "medium"
53
+ HIGH = "high"
54
+ CRITICAL = "critical"
55
+
56
+
57
+ class CapabilityLevel(str, Enum):
58
+ """Proficiency levels for agent capabilities."""
59
+
60
+ BASIC = "basic"
61
+ INTERMEDIATE = "intermediate"
62
+ ADVANCED = "advanced"
63
+ EXPERT = "expert"
64
+
65
+
66
+ class MemoryType(str, Enum):
67
+ """Types of agent memory."""
68
+
69
+ SHORT_TERM = "short_term"
70
+ LONG_TERM = "long_term"
71
+
72
+
73
+ class RecoveryStrategy(str, Enum):
74
+ """
75
+ Recovery strategies for error handling.
76
+
77
+ Defines different strategies for recovering from task execution failures.
78
+ Strategies are typically applied in sequence until one succeeds or all fail.
79
+
80
+ **Strategy Descriptions:**
81
+ - RETRY: Retry the same task with exponential backoff (for transient errors)
82
+ - SIMPLIFY: Simplify the task and retry (break down complex tasks)
83
+ - FALLBACK: Use a fallback approach or alternative method
84
+ - DELEGATE: Delegate the task to another capable agent
85
+ - ABORT: Abort execution and return error (terminal strategy)
86
+
87
+ **Usage Pattern:**
88
+ Strategies are typically chained together, trying each in sequence:
89
+ 1. RETRY - Quick retry for transient errors
90
+ 2. SIMPLIFY - Break down complex tasks
91
+ 3. FALLBACK - Use alternative approach
92
+ 4. DELEGATE - Hand off to another agent
93
+ 5. ABORT - Give up and return error
94
+
95
+ Examples:
96
+ # Example 1: Basic retry strategy
97
+ from aiecs.domain.agent.models import RecoveryStrategy
98
+
99
+ strategies = [RecoveryStrategy.RETRY]
100
+ result = await agent.execute_with_recovery(
101
+ task=task,
102
+ context=context,
103
+ strategies=strategies
104
+ )
105
+
106
+ # Example 2: Full recovery chain
107
+ strategies = [
108
+ RecoveryStrategy.RETRY,
109
+ RecoveryStrategy.SIMPLIFY,
110
+ RecoveryStrategy.FALLBACK,
111
+ RecoveryStrategy.DELEGATE
112
+ ]
113
+ result = await agent.execute_with_recovery(
114
+ task=task,
115
+ context=context,
116
+ strategies=strategies
117
+ )
118
+
119
+ # Example 3: Conservative recovery (no delegation)
120
+ strategies = [
121
+ RecoveryStrategy.RETRY,
122
+ RecoveryStrategy.SIMPLIFY,
123
+ RecoveryStrategy.FALLBACK
124
+ ]
125
+ result = await agent.execute_with_recovery(
126
+ task=task,
127
+ context=context,
128
+ strategies=strategies
129
+ )
130
+
131
+ # Example 4: Quick fail (abort after retry)
132
+ strategies = [
133
+ RecoveryStrategy.RETRY,
134
+ RecoveryStrategy.ABORT
135
+ ]
136
+ result = await agent.execute_with_recovery(
137
+ task=task,
138
+ context=context,
139
+ strategies=strategies
140
+ )
141
+ """
142
+
143
+ RETRY = "retry" # Retry with exponential backoff
144
+ SIMPLIFY = "simplify" # Simplify task and retry
145
+ FALLBACK = "fallback" # Use fallback approach
146
+ DELEGATE = "delegate" # Delegate to another agent
147
+ ABORT = "abort" # Abort execution
148
+
149
+
150
+ class RetryPolicy(BaseModel):
151
+ """Retry policy configuration for agent operations."""
152
+
153
+ max_retries: int = Field(default=5, ge=0, description="Maximum number of retry attempts")
154
+ base_delay: float = Field(
155
+ default=1.0,
156
+ ge=0,
157
+ description="Base delay in seconds for exponential backoff",
158
+ )
159
+ max_delay: float = Field(default=32.0, ge=0, description="Maximum delay cap in seconds")
160
+ exponential_factor: float = Field(default=2.0, ge=1.0, description="Exponential factor for backoff")
161
+ jitter_factor: float = Field(
162
+ default=0.2,
163
+ ge=0.0,
164
+ le=1.0,
165
+ description="Jitter factor (±percentage) for randomization",
166
+ )
167
+ rate_limit_base_delay: float = Field(default=5.0, ge=0, description="Base delay for rate limit errors")
168
+ rate_limit_max_delay: float = Field(default=120.0, ge=0, description="Maximum delay for rate limit errors")
169
+
170
+ model_config = ConfigDict()
171
+
172
+
173
+ class AgentConfiguration(BaseModel):
174
+ """Configuration model for agent behavior and capabilities."""
175
+
176
+ # LLM settings
177
+ llm_provider: Optional[str] = Field(None, description="LLM provider name (e.g., 'openai', 'vertex')")
178
+ llm_model: Optional[str] = Field(None, description="LLM model name")
179
+ temperature: float = Field(default=0.7, ge=0.0, le=2.0, description="LLM temperature setting")
180
+ max_tokens: int = Field(default=4096, ge=1, description="Maximum tokens for LLM responses")
181
+
182
+ # RAG strategy selection LLM configuration
183
+ strategy_selection_llm_provider: Optional[str] = Field(
184
+ None,
185
+ description="LLM provider for RAG strategy selection (supports custom providers registered via LLMClientFactory)",
186
+ )
187
+ strategy_selection_llm_model: Optional[str] = Field(
188
+ None,
189
+ description="LLM model for RAG strategy selection (lightweight model recommended)",
190
+ )
191
+ strategy_selection_temperature: float = Field(
192
+ default=0.0,
193
+ ge=0.0,
194
+ le=2.0,
195
+ description="Temperature for strategy selection (0.0 for deterministic classification)",
196
+ )
197
+ strategy_selection_max_tokens: int = Field(
198
+ default=100,
199
+ ge=1,
200
+ description="Maximum tokens for strategy selection response",
201
+ )
202
+
203
+ # Tool access
204
+ allowed_tools: List[str] = Field(default_factory=list, description="List of tool names agent can use")
205
+ tool_selection_strategy: str = Field(
206
+ default="llm_based",
207
+ description="Strategy for tool selection ('llm_based', 'rule_based')",
208
+ )
209
+
210
+ # Memory configuration
211
+ memory_enabled: bool = Field(default=True, description="Whether memory is enabled")
212
+ memory_capacity: int = Field(default=1000, ge=0, description="Maximum number of memory items")
213
+ memory_ttl_seconds: Optional[int] = Field(None, ge=0, description="Time-to-live for short-term memory in seconds")
214
+
215
+ # Behavior parameters
216
+ max_iterations: int = Field(default=10, ge=1, description="Maximum iterations for ReAct loop")
217
+ timeout_seconds: Optional[int] = Field(None, ge=0, description="Task execution timeout")
218
+ verbose: bool = Field(default=False, description="Verbose logging")
219
+
220
+ # Retry policy
221
+ retry_policy: RetryPolicy = Field(default_factory=RetryPolicy, description="Retry policy configuration")
222
+
223
+ # Goal and context
224
+ goal: Optional[str] = Field(None, description="Agent's primary goal")
225
+ backstory: Optional[str] = Field(None, description="Agent's backstory/context")
226
+ domain_knowledge: Optional[str] = Field(None, description="Domain-specific knowledge")
227
+ reasoning_guidance: Optional[str] = Field(None, description="Guidance for reasoning approach")
228
+
229
+ # System prompt configuration
230
+ system_prompt: Optional[str] = Field(
231
+ None,
232
+ description="Custom system prompt that takes precedence over assembled prompt from goal/backstory/etc. "
233
+ "If provided, goal, backstory, domain_knowledge, and reasoning_guidance are ignored for system prompt construction.",
234
+ )
235
+
236
+ # Prompt caching configuration
237
+ enable_prompt_caching: bool = Field(
238
+ default=True,
239
+ description="Enable provider-level prompt caching for system prompts and tool schemas. "
240
+ "Reduces cost and latency for repeated context.",
241
+ )
242
+
243
+ # Context compression
244
+ context_window_limit: int = Field(default=20000, ge=0, description="Token limit for context window")
245
+ enable_context_compression: bool = Field(default=True, description="Enable automatic context compression")
246
+
247
+ # Knowledge retrieval configuration
248
+ retrieval_strategy: str = Field(
249
+ default="hybrid",
250
+ description="Knowledge retrieval strategy: 'vector' (semantic similarity), 'graph' (graph traversal), 'hybrid' (combination), or 'auto' (automatic selection)",
251
+ )
252
+ enable_knowledge_caching: bool = Field(
253
+ default=True,
254
+ description="Enable caching for knowledge retrieval results",
255
+ )
256
+ cache_ttl: int = Field(
257
+ default=300,
258
+ ge=0,
259
+ description="Cache time-to-live in seconds (default: 300 = 5 minutes)",
260
+ )
261
+ max_context_size: int = Field(
262
+ default=50,
263
+ ge=1,
264
+ description="Maximum number of knowledge entities to include in context (default: 50)",
265
+ )
266
+ entity_extraction_provider: str = Field(
267
+ default="llm",
268
+ description="Entity extraction provider: 'llm' (LLM-based extraction), 'ner' (Named Entity Recognition), or custom provider name",
269
+ )
270
+
271
+ # Metadata
272
+ metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional configuration metadata")
273
+
274
+ model_config = ConfigDict()
275
+
276
+
277
+ class AgentGoal(BaseModel):
278
+ """Model representing an agent goal."""
279
+
280
+ goal_id: str = Field(
281
+ default_factory=lambda: str(uuid.uuid4()),
282
+ description="Unique goal identifier",
283
+ )
284
+ description: str = Field(..., description="Goal description")
285
+ status: GoalStatus = Field(default=GoalStatus.PENDING, description="Current goal status")
286
+ priority: GoalPriority = Field(default=GoalPriority.MEDIUM, description="Goal priority level")
287
+ progress: float = Field(
288
+ default=0.0,
289
+ ge=0.0,
290
+ le=100.0,
291
+ description="Progress percentage (0-100)",
292
+ )
293
+
294
+ # Success criteria
295
+ success_criteria: Optional[str] = Field(None, description="Criteria for goal achievement")
296
+ deadline: Optional[datetime] = Field(None, description="Goal deadline")
297
+
298
+ # Dependencies
299
+ parent_goal_id: Optional[str] = Field(None, description="Parent goal ID if this is a sub-goal")
300
+ depends_on: List[str] = Field(default_factory=list, description="List of goal IDs this depends on")
301
+
302
+ # Timestamps
303
+ created_at: datetime = Field(default_factory=datetime.utcnow, description="Goal creation timestamp")
304
+ started_at: Optional[datetime] = Field(None, description="When goal execution started")
305
+ achieved_at: Optional[datetime] = Field(None, description="When goal was achieved")
306
+
307
+ # Metadata
308
+ metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional goal metadata")
309
+
310
+ model_config = ConfigDict()
311
+
312
+
313
+ class AgentCapabilityDeclaration(BaseModel):
314
+ """Model declaring an agent capability."""
315
+
316
+ capability_type: str = Field(
317
+ ...,
318
+ description="Type of capability (e.g., 'text_generation', 'code_generation')",
319
+ )
320
+ level: CapabilityLevel = Field(..., description="Proficiency level")
321
+ constraints: Dict[str, Any] = Field(default_factory=dict, description="Capability constraints")
322
+ description: Optional[str] = Field(None, description="Capability description")
323
+
324
+ # Timestamps
325
+ acquired_at: datetime = Field(
326
+ default_factory=datetime.utcnow,
327
+ description="When capability was acquired",
328
+ )
329
+
330
+ model_config = ConfigDict()
331
+
332
+
333
+ class AgentMetrics(BaseModel):
334
+ """Model for tracking agent performance metrics."""
335
+
336
+ # Task execution metrics
337
+ total_tasks_executed: int = Field(default=0, ge=0, description="Total number of tasks executed")
338
+ successful_tasks: int = Field(default=0, ge=0, description="Number of successful tasks")
339
+ failed_tasks: int = Field(default=0, ge=0, description="Number of failed tasks")
340
+ success_rate: float = Field(default=0.0, ge=0.0, le=100.0, description="Success rate percentage")
341
+
342
+ # Execution time metrics
343
+ average_execution_time: Optional[float] = Field(None, ge=0, description="Average task execution time in seconds")
344
+ total_execution_time: float = Field(default=0.0, ge=0, description="Total execution time in seconds")
345
+ min_execution_time: Optional[float] = Field(None, ge=0, description="Minimum execution time in seconds")
346
+ max_execution_time: Optional[float] = Field(None, ge=0, description="Maximum execution time in seconds")
347
+
348
+ # Quality metrics
349
+ average_quality_score: Optional[float] = Field(None, ge=0.0, le=1.0, description="Average quality score (0-1)")
350
+
351
+ # Resource usage
352
+ total_tokens_used: int = Field(default=0, ge=0, description="Total LLM tokens used")
353
+ total_tool_calls: int = Field(default=0, ge=0, description="Total tool calls made")
354
+ total_api_cost: Optional[float] = Field(None, ge=0, description="Total API cost (if tracked)")
355
+
356
+ # Retry metrics
357
+ total_retries: int = Field(default=0, ge=0, description="Total number of retry attempts")
358
+ retry_successes: int = Field(default=0, ge=0, description="Number of successful retries")
359
+
360
+ # Error tracking
361
+ error_count: int = Field(default=0, ge=0, description="Total number of errors")
362
+ error_types: Dict[str, int] = Field(default_factory=dict, description="Count of errors by type")
363
+
364
+ # Session-level metrics (Phase 2 enhancement)
365
+ total_sessions: int = Field(default=0, ge=0, description="Total number of sessions created")
366
+ active_sessions: int = Field(default=0, ge=0, description="Number of currently active sessions")
367
+ completed_sessions: int = Field(default=0, ge=0, description="Number of completed sessions")
368
+ failed_sessions: int = Field(default=0, ge=0, description="Number of failed sessions")
369
+ expired_sessions: int = Field(default=0, ge=0, description="Number of expired sessions")
370
+ total_session_requests: int = Field(default=0, ge=0, description="Total requests across all sessions")
371
+ total_session_errors: int = Field(default=0, ge=0, description="Total errors across all sessions")
372
+ average_session_duration: Optional[float] = Field(None, ge=0, description="Average session duration in seconds")
373
+ average_requests_per_session: Optional[float] = Field(None, ge=0, description="Average number of requests per session")
374
+
375
+ # Operation-level metrics (Phase 3 enhancement)
376
+ operation_history: List[Dict[str, Any]] = Field(default_factory=list, description="Recent operation timing history (limited to last 100)")
377
+ operation_counts: Dict[str, int] = Field(default_factory=dict, description="Count of operations by name")
378
+ operation_total_time: Dict[str, float] = Field(default_factory=dict, description="Total time spent in each operation type (seconds)")
379
+ operation_error_counts: Dict[str, int] = Field(default_factory=dict, description="Error count by operation type")
380
+ p50_operation_time: Optional[float] = Field(None, ge=0, description="50th percentile operation time (median) in seconds")
381
+ p95_operation_time: Optional[float] = Field(None, ge=0, description="95th percentile operation time in seconds")
382
+ p99_operation_time: Optional[float] = Field(None, ge=0, description="99th percentile operation time in seconds")
383
+
384
+ # Prompt cache metrics (for LLM provider-level caching observability)
385
+ total_llm_requests: int = Field(default=0, ge=0, description="Total number of LLM requests made")
386
+ cache_hits: int = Field(default=0, ge=0, description="Number of LLM requests with cache hits")
387
+ cache_misses: int = Field(default=0, ge=0, description="Number of LLM requests without cache hits (cache creation)")
388
+ cache_hit_rate: float = Field(default=0.0, ge=0.0, le=1.0, description="Prompt cache hit rate (0-1)")
389
+ total_cache_read_tokens: int = Field(default=0, ge=0, description="Total tokens read from prompt cache")
390
+ total_cache_creation_tokens: int = Field(default=0, ge=0, description="Total tokens used to create cache entries")
391
+ estimated_cache_savings_tokens: int = Field(default=0, ge=0, description="Estimated tokens saved from cache (cache_read_tokens * 0.9)")
392
+ estimated_cache_savings_cost: float = Field(default=0.0, ge=0, description="Estimated cost saved from cache in USD")
393
+
394
+ # Timestamps
395
+ last_reset_at: Optional[datetime] = Field(None, description="When metrics were last reset")
396
+ updated_at: datetime = Field(default_factory=datetime.utcnow, description="Last metrics update")
397
+
398
+ model_config = ConfigDict()
399
+
400
+
401
+ class GraphMetrics(BaseModel):
402
+ """Model for tracking knowledge graph retrieval metrics."""
403
+
404
+ # Query metrics
405
+ total_graph_queries: int = Field(default=0, ge=0, description="Total number of graph queries executed")
406
+ total_entities_retrieved: int = Field(default=0, ge=0, description="Total number of entities retrieved")
407
+ total_relationships_traversed: int = Field(default=0, ge=0, description="Total number of relationships traversed")
408
+
409
+ # Performance metrics
410
+ average_graph_query_time: float = Field(default=0.0, ge=0, description="Average graph query time in seconds")
411
+ total_graph_query_time: float = Field(default=0.0, ge=0, description="Total graph query time in seconds")
412
+ min_graph_query_time: Optional[float] = Field(None, ge=0, description="Minimum graph query time in seconds")
413
+ max_graph_query_time: Optional[float] = Field(None, ge=0, description="Maximum graph query time in seconds")
414
+
415
+ # Cache metrics
416
+ cache_hit_rate: float = Field(default=0.0, ge=0.0, le=1.0, description="Cache hit rate (0-1)")
417
+ cache_hits: int = Field(default=0, ge=0, description="Number of cache hits")
418
+ cache_misses: int = Field(default=0, ge=0, description="Number of cache misses")
419
+
420
+ # Strategy metrics
421
+ vector_search_count: int = Field(default=0, ge=0, description="Number of vector-only searches")
422
+ graph_search_count: int = Field(default=0, ge=0, description="Number of graph-only searches")
423
+ hybrid_search_count: int = Field(default=0, ge=0, description="Number of hybrid searches")
424
+
425
+ # Entity extraction metrics
426
+ entity_extraction_count: int = Field(default=0, ge=0, description="Number of entity extractions performed")
427
+ average_extraction_time: float = Field(default=0.0, ge=0, description="Average entity extraction time in seconds")
428
+ total_extraction_time: float = Field(default=0.0, ge=0, description="Total entity extraction time in seconds")
429
+
430
+ # Timestamps
431
+ last_reset_at: Optional[datetime] = Field(None, description="When metrics were last reset")
432
+ updated_at: datetime = Field(default_factory=datetime.utcnow, description="Last metrics update")
433
+
434
+ model_config = ConfigDict()
435
+
436
+
437
+ class AgentInteraction(BaseModel):
438
+ """Model representing an agent interaction."""
439
+
440
+ interaction_id: str = Field(
441
+ default_factory=lambda: str(uuid.uuid4()),
442
+ description="Unique interaction identifier",
443
+ )
444
+ agent_id: str = Field(..., description="Agent ID involved in interaction")
445
+ interaction_type: str = Field(
446
+ ...,
447
+ description="Type of interaction (e.g., 'task', 'message', 'tool_call')",
448
+ )
449
+ content: Dict[str, Any] = Field(..., description="Interaction content")
450
+
451
+ # Timestamps
452
+ timestamp: datetime = Field(default_factory=datetime.utcnow, description="Interaction timestamp")
453
+ duration_seconds: Optional[float] = Field(None, ge=0, description="Interaction duration")
454
+
455
+ # Metadata
456
+ metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional interaction metadata")
457
+
458
+ model_config = ConfigDict()
459
+
460
+
461
+ class AgentMemory(BaseModel):
462
+ """Model for agent memory interface (base model, not implementation)."""
463
+
464
+ memory_id: str = Field(
465
+ default_factory=lambda: str(uuid.uuid4()),
466
+ description="Unique memory identifier",
467
+ )
468
+ agent_id: str = Field(..., description="Associated agent ID")
469
+ memory_type: MemoryType = Field(..., description="Type of memory")
470
+ key: str = Field(..., description="Memory key")
471
+ value: Any = Field(..., description="Memory value")
472
+ timestamp: datetime = Field(default_factory=datetime.utcnow, description="When memory was stored")
473
+
474
+ # Metadata
475
+ metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional memory metadata")
476
+
477
+ model_config = ConfigDict()
478
+
479
+
480
+ class Experience(BaseModel):
481
+ """
482
+ Model for recording agent learning experiences.
483
+
484
+ Tracks task execution experiences to enable learning and adaptation.
485
+ Used by agents to improve performance over time by learning from
486
+ past successes and failures. Experiences are used to recommend
487
+ optimal approaches for similar tasks.
488
+
489
+ **Key Features:**
490
+ - Comprehensive task execution tracking
491
+ - Success/failure outcome recording
492
+ - Quality scoring and error classification
493
+ - Learning insights and recommendations
494
+ - Context and performance metrics
495
+
496
+ Attributes:
497
+ experience_id: Unique identifier for the experience
498
+ agent_id: ID of the agent that had this experience
499
+ task_type: Type/category of task (e.g., "data_analysis", "search")
500
+ task_description: Human-readable task description
501
+ task_complexity: Task complexity level (simple, medium, complex)
502
+ approach: Approach/strategy used (e.g., "parallel_tools", "sequential")
503
+ tools_used: List of tool names used in execution
504
+ execution_time: Execution time in seconds
505
+ success: Whether task execution succeeded
506
+ quality_score: Quality score from 0.0 to 1.0 (None if not available)
507
+ error_type: Type of error if failed (e.g., "timeout", "validation_error")
508
+ error_message: Error message if failed
509
+ context_size: Context size in tokens (if applicable)
510
+ iterations: Number of iterations/attempts (if applicable)
511
+ lessons_learned: Human-readable lessons learned from this experience
512
+ recommended_improvements: Recommended improvements for future tasks
513
+ timestamp: When the experience occurred
514
+ metadata: Additional experience metadata
515
+
516
+ Examples:
517
+ # Example 1: Successful experience
518
+ experience = Experience(
519
+ agent_id="agent-1",
520
+ task_type="data_analysis",
521
+ task_description="Analyze sales data for Q4",
522
+ task_complexity="medium",
523
+ approach="parallel_tools",
524
+ tools_used=["pandas", "numpy"],
525
+ execution_time=2.5,
526
+ success=True,
527
+ quality_score=0.95,
528
+ context_size=5000,
529
+ iterations=1
530
+ )
531
+
532
+ # Example 2: Failed experience with error details
533
+ experience = Experience(
534
+ agent_id="agent-1",
535
+ task_type="web_scraping",
536
+ task_description="Scrape product prices",
537
+ task_complexity="simple",
538
+ approach="single_tool",
539
+ tools_used=["scraper"],
540
+ execution_time=30.0,
541
+ success=False,
542
+ error_type="timeout",
543
+ error_message="Request timed out after 30 seconds",
544
+ lessons_learned="Use retry logic for network operations",
545
+ recommended_improvements="Add exponential backoff retry"
546
+ )
547
+
548
+ # Example 3: Experience with learning insights
549
+ experience = Experience(
550
+ agent_id="agent-1",
551
+ task_type="data_analysis",
552
+ task_description="Analyze customer feedback",
553
+ approach="parallel_tools",
554
+ tools_used=["nlp", "sentiment"],
555
+ execution_time=5.2,
556
+ success=True,
557
+ quality_score=0.88,
558
+ lessons_learned="Parallel execution reduced time by 40%",
559
+ recommended_improvements="Use parallel approach for similar tasks"
560
+ )
561
+ """
562
+
563
+ experience_id: str = Field(
564
+ default_factory=lambda: str(uuid.uuid4()),
565
+ description="Unique experience identifier",
566
+ )
567
+ agent_id: str = Field(..., description="Agent that had this experience")
568
+
569
+ # Task information
570
+ task_type: str = Field(..., description="Type/category of task")
571
+ task_description: str = Field(..., description="Task description")
572
+ task_complexity: Optional[str] = Field(None, description="Task complexity (simple, medium, complex)")
573
+
574
+ # Execution details
575
+ approach: str = Field(..., description="Approach/strategy used")
576
+ tools_used: List[str] = Field(default_factory=list, description="Tools used in execution")
577
+ execution_time: float = Field(..., ge=0, description="Execution time in seconds")
578
+
579
+ # Outcome
580
+ success: bool = Field(..., description="Whether task was successful")
581
+ quality_score: Optional[float] = Field(None, ge=0.0, le=1.0, description="Quality score (0-1)")
582
+ error_type: Optional[str] = Field(None, description="Error type if failed")
583
+ error_message: Optional[str] = Field(None, description="Error message if failed")
584
+
585
+ # Context
586
+ context_size: Optional[int] = Field(None, ge=0, description="Context size in tokens")
587
+ iterations: Optional[int] = Field(None, ge=0, description="Number of iterations")
588
+
589
+ # Learning insights
590
+ lessons_learned: Optional[str] = Field(None, description="Lessons learned from experience")
591
+ recommended_improvements: Optional[str] = Field(None, description="Recommended improvements")
592
+
593
+ # Timestamps
594
+ timestamp: datetime = Field(default_factory=datetime.utcnow, description="When experience occurred")
595
+
596
+ # Metadata
597
+ metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional experience metadata")
598
+
599
+ model_config = ConfigDict()
600
+
601
+
602
+ class ResourceLimits(BaseModel):
603
+ """
604
+ Configuration for agent resource limits and rate limiting.
605
+
606
+ Provides control over resource usage to prevent exhaustion and
607
+ ensure stable operation in production environments. Supports
608
+ token bucket algorithm for rate limiting, concurrent task limits,
609
+ and memory constraints.
610
+
611
+ **Key Features:**
612
+ - Concurrent task limits to prevent overload
613
+ - Token rate limiting with burst support (token bucket algorithm)
614
+ - Tool call rate limiting per minute/hour
615
+ - Memory usage limits
616
+ - Task timeout configuration
617
+ - Configurable enforcement (enforce vs monitor)
618
+
619
+ Attributes:
620
+ max_concurrent_tasks: Maximum number of concurrent tasks (default: 10)
621
+ max_tokens_per_minute: Maximum tokens per minute (None = unlimited)
622
+ max_tokens_per_hour: Maximum tokens per hour (None = unlimited)
623
+ token_burst_size: Token burst size for token bucket (None = use max_tokens_per_minute)
624
+ max_tool_calls_per_minute: Maximum tool calls per minute (None = unlimited)
625
+ max_tool_calls_per_hour: Maximum tool calls per hour (None = unlimited)
626
+ max_memory_mb: Maximum memory usage in MB (None = unlimited)
627
+ task_timeout_seconds: Maximum task execution time in seconds (None = unlimited)
628
+ resource_wait_timeout_seconds: Maximum time to wait for resources (default: 60)
629
+ enforce_limits: Whether to enforce resource limits (default: True)
630
+ reject_on_limit: Reject requests when limit reached vs wait (default: False)
631
+
632
+ Examples:
633
+ # Example 1: Basic rate limiting
634
+ limits = ResourceLimits(
635
+ max_concurrent_tasks=5,
636
+ max_tokens_per_minute=10000,
637
+ max_tool_calls_per_minute=100
638
+ )
639
+
640
+ # Example 2: Token bucket with burst support
641
+ limits = ResourceLimits(
642
+ max_tokens_per_minute=10000,
643
+ token_burst_size=20000, # Allow 2x burst
644
+ max_tool_calls_per_minute=100
645
+ )
646
+
647
+ # Example 3: Strict limits for production
648
+ limits = ResourceLimits(
649
+ max_concurrent_tasks=10,
650
+ max_tokens_per_minute=50000,
651
+ max_tokens_per_hour=2000000,
652
+ max_tool_calls_per_minute=500,
653
+ max_memory_mb=2048,
654
+ task_timeout_seconds=300,
655
+ enforce_limits=True,
656
+ reject_on_limit=True # Reject instead of waiting
657
+ )
658
+
659
+ # Example 4: Monitoring mode (don't enforce)
660
+ limits = ResourceLimits(
661
+ max_concurrent_tasks=10,
662
+ max_tokens_per_minute=10000,
663
+ enforce_limits=False # Monitor but don't enforce
664
+ )
665
+
666
+ # Example 5: Wait for resources instead of rejecting
667
+ limits = ResourceLimits(
668
+ max_concurrent_tasks=5,
669
+ max_tokens_per_minute=10000,
670
+ resource_wait_timeout_seconds=120, # Wait up to 2 minutes
671
+ reject_on_limit=False # Wait instead of reject
672
+ )
673
+ """
674
+
675
+ # Concurrent task limits
676
+ max_concurrent_tasks: int = Field(default=10, ge=1, description="Maximum number of concurrent tasks")
677
+
678
+ # Token rate limits (token bucket algorithm)
679
+ max_tokens_per_minute: Optional[int] = Field(None, ge=0, description="Maximum tokens per minute (None = unlimited)")
680
+ max_tokens_per_hour: Optional[int] = Field(None, ge=0, description="Maximum tokens per hour (None = unlimited)")
681
+ token_burst_size: Optional[int] = Field(
682
+ None,
683
+ ge=0,
684
+ description="Token burst size for token bucket (None = use max_tokens_per_minute)",
685
+ )
686
+
687
+ # Tool call rate limits
688
+ max_tool_calls_per_minute: Optional[int] = Field(None, ge=0, description="Maximum tool calls per minute (None = unlimited)")
689
+ max_tool_calls_per_hour: Optional[int] = Field(None, ge=0, description="Maximum tool calls per hour (None = unlimited)")
690
+
691
+ # Memory limits
692
+ max_memory_mb: Optional[int] = Field(None, ge=0, description="Maximum memory usage in MB (None = unlimited)")
693
+
694
+ # Timeout settings
695
+ task_timeout_seconds: Optional[int] = Field(None, ge=0, description="Maximum task execution time in seconds (None = unlimited)")
696
+ resource_wait_timeout_seconds: int = Field(default=60, ge=0, description="Maximum time to wait for resources")
697
+
698
+ # Enforcement
699
+ enforce_limits: bool = Field(default=True, description="Whether to enforce resource limits")
700
+ reject_on_limit: bool = Field(default=False, description="Reject requests when limit reached (vs wait)")
701
+
702
+ model_config = ConfigDict()
703
+
704
+
705
+ class ToolObservation(BaseModel):
706
+ """
707
+ Structured observation of tool execution results.
708
+
709
+ Provides a standardized format for tracking tool execution with
710
+ success/error status, execution time, and timestamps. Used for
711
+ debugging, analysis, and LLM reasoning loops.
712
+
713
+ This pattern is essential for MasterController compatibility and
714
+ observation-based reasoning. Observations can be converted to text
715
+ format for inclusion in LLM prompts or to dictionaries for serialization.
716
+
717
+ **Key Features:**
718
+ - Automatic success/error tracking
719
+ - Execution time measurement
720
+ - ISO timestamp generation
721
+ - Text formatting for LLM context
722
+ - Dictionary serialization for storage
723
+
724
+ Attributes:
725
+ tool_name: Name of the tool that was executed
726
+ parameters: Dictionary of parameters passed to the tool
727
+ result: Tool execution result (any type)
728
+ success: Whether tool execution succeeded (True/False)
729
+ error: Error message if execution failed (None if successful)
730
+ execution_time_ms: Execution time in milliseconds (None if not measured)
731
+ timestamp: ISO format timestamp of execution
732
+
733
+ Examples:
734
+ # Example 1: Successful tool execution
735
+ from aiecs.domain.agent.models import ToolObservation
736
+
737
+ obs = ToolObservation(
738
+ tool_name="search",
739
+ parameters={"query": "AI", "limit": 10},
740
+ result=["result1", "result2", "result3"],
741
+ success=True,
742
+ execution_time_ms=250.5
743
+ )
744
+
745
+ # Convert to text for LLM context
746
+ text = obs.to_text()
747
+ # "Tool: search
748
+ # Parameters: {'query': 'AI', 'limit': 10}
749
+ # Status: SUCCESS
750
+ # Result: ['result1', 'result2', 'result3']
751
+ # Execution time: 250.5ms"
752
+
753
+ # Example 2: Failed tool execution
754
+ obs = ToolObservation(
755
+ tool_name="calculator",
756
+ parameters={"operation": "divide", "a": 10, "b": 0},
757
+ result=None,
758
+ success=False,
759
+ error="Division by zero",
760
+ execution_time_ms=5.2
761
+ )
762
+
763
+ text = obs.to_text()
764
+ # "Tool: calculator
765
+ # Parameters: {'operation': 'divide', 'a': 10, 'b': 0}
766
+ # Status: ERROR
767
+ # Error: Division by zero
768
+ # Execution time: 5.2ms"
769
+
770
+ # Example 3: Using with agent execution
771
+ from aiecs.domain.agent import HybridAgent
772
+
773
+ agent = HybridAgent(...)
774
+ obs = await agent._execute_tool_with_observation(
775
+ tool_name="search",
776
+ operation="query",
777
+ parameters={"q": "Python"}
778
+ )
779
+
780
+ # Check success
781
+ if obs.success:
782
+ print(f"Found {len(obs.result)} results")
783
+ else:
784
+ print(f"Error: {obs.error}")
785
+
786
+ # Example 4: Serialization for storage
787
+ obs = ToolObservation(
788
+ tool_name="api_call",
789
+ parameters={"endpoint": "/data", "method": "GET"},
790
+ result={"status": 200, "data": {...}},
791
+ success=True,
792
+ execution_time_ms=1234.5
793
+ )
794
+
795
+ # Convert to dict for JSON serialization
796
+ data = obs.to_dict()
797
+ # {'tool_name': 'api_call', 'parameters': {...}, 'success': True, ...}
798
+
799
+ # Example 5: Using in observation-based reasoning loop
800
+ observations = []
801
+ for tool_call in tool_calls:
802
+ obs = await agent._execute_tool_with_observation(
803
+ tool_name=tool_call["tool"],
804
+ parameters=tool_call["parameters"]
805
+ )
806
+ observations.append(obs)
807
+
808
+ # Format observations for LLM context
809
+ observation_text = "\\n\\n".join([obs.to_text() for obs in observations])
810
+ # Include in LLM prompt for reasoning
811
+ """
812
+
813
+ tool_name: str = Field(..., description="Name of the tool that was executed")
814
+ parameters: Dict[str, Any] = Field(default_factory=dict, description="Parameters passed to the tool")
815
+ result: Any = Field(None, description="Tool execution result")
816
+ success: bool = Field(..., description="Whether tool execution succeeded")
817
+ error: Optional[str] = Field(None, description="Error message if execution failed")
818
+ execution_time_ms: Optional[float] = Field(None, ge=0, description="Execution time in milliseconds")
819
+ timestamp: str = Field(
820
+ default_factory=lambda: datetime.utcnow().isoformat(),
821
+ description="ISO format timestamp of execution",
822
+ )
823
+
824
+ model_config = ConfigDict()
825
+
826
+ def to_dict(self) -> Dict[str, Any]:
827
+ """
828
+ Convert observation to dictionary.
829
+
830
+ Returns:
831
+ Dict representation of the observation
832
+
833
+ Example:
834
+ ```python
835
+ obs = ToolObservation(tool_name="search", success=True, result="data")
836
+ data = obs.to_dict()
837
+ # {'tool_name': 'search', 'success': True, 'result': 'data', ...}
838
+ ```
839
+ """
840
+ return {
841
+ "tool_name": self.tool_name,
842
+ "parameters": self.parameters,
843
+ "result": self.result,
844
+ "success": self.success,
845
+ "error": self.error,
846
+ "execution_time_ms": self.execution_time_ms,
847
+ "timestamp": self.timestamp,
848
+ }
849
+
850
+ def to_text(self) -> str:
851
+ """
852
+ Format observation as text for LLM context.
853
+
854
+ Provides a human-readable format suitable for including in
855
+ LLM prompts and reasoning loops.
856
+
857
+ Returns:
858
+ Formatted text representation
859
+
860
+ Example:
861
+ ```python
862
+ obs = ToolObservation(
863
+ tool_name="search",
864
+ parameters={"query": "AI"},
865
+ success=True,
866
+ result="Found 10 results",
867
+ execution_time_ms=250.5
868
+ )
869
+ text = obs.to_text()
870
+ # "Tool: search
871
+ # Parameters: {'query': 'AI'}
872
+ # Status: SUCCESS
873
+ # Result: Found 10 results
874
+ # Execution time: 250.5ms"
875
+ ```
876
+ """
877
+ lines = [
878
+ f"Tool: {self.tool_name}",
879
+ f"Parameters: {self.parameters}",
880
+ ]
881
+
882
+ if self.success:
883
+ lines.append("Status: SUCCESS")
884
+ lines.append(f"Result: {self.result}")
885
+ else:
886
+ lines.append("Status: FAILURE")
887
+ lines.append(f"Error: {self.error}")
888
+
889
+ if self.execution_time_ms is not None:
890
+ lines.append(f"Execution time: {self.execution_time_ms:.2f}ms")
891
+
892
+ lines.append(f"Timestamp: {self.timestamp}")
893
+
894
+ return "\n".join(lines)