aiecs 1.0.1__py3-none-any.whl → 1.7.6__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 +399 -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 +3870 -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 +1435 -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 +884 -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 +364 -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 +224 -36
  195. aiecs/llm/client_resolver.py +155 -0
  196. aiecs/llm/clients/__init__.py +38 -0
  197. aiecs/llm/clients/base_client.py +324 -0
  198. aiecs/llm/clients/google_function_calling_mixin.py +457 -0
  199. aiecs/llm/clients/googleai_client.py +241 -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 +897 -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 +1323 -0
  269. aiecs/tools/docs/document_layout_tool.py +1160 -0
  270. aiecs/tools/docs/document_parser_tool.py +1011 -0
  271. aiecs/tools/docs/document_writer_tool.py +1829 -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 +175 -131
  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.6.dist-info}/METADATA +52 -15
  321. aiecs-1.7.6.dist-info/RECORD +337 -0
  322. aiecs-1.7.6.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.6.dist-info}/WHEEL +0 -0
  339. {aiecs-1.0.1.dist-info → aiecs-1.7.6.dist-info}/licenses/LICENSE +0 -0
  340. {aiecs-1.0.1.dist-info → aiecs-1.7.6.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,884 @@
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
+ # Timestamps
385
+ last_reset_at: Optional[datetime] = Field(None, description="When metrics were last reset")
386
+ updated_at: datetime = Field(default_factory=datetime.utcnow, description="Last metrics update")
387
+
388
+ model_config = ConfigDict()
389
+
390
+
391
+ class GraphMetrics(BaseModel):
392
+ """Model for tracking knowledge graph retrieval metrics."""
393
+
394
+ # Query metrics
395
+ total_graph_queries: int = Field(default=0, ge=0, description="Total number of graph queries executed")
396
+ total_entities_retrieved: int = Field(default=0, ge=0, description="Total number of entities retrieved")
397
+ total_relationships_traversed: int = Field(default=0, ge=0, description="Total number of relationships traversed")
398
+
399
+ # Performance metrics
400
+ average_graph_query_time: float = Field(default=0.0, ge=0, description="Average graph query time in seconds")
401
+ total_graph_query_time: float = Field(default=0.0, ge=0, description="Total graph query time in seconds")
402
+ min_graph_query_time: Optional[float] = Field(None, ge=0, description="Minimum graph query time in seconds")
403
+ max_graph_query_time: Optional[float] = Field(None, ge=0, description="Maximum graph query time in seconds")
404
+
405
+ # Cache metrics
406
+ cache_hit_rate: float = Field(default=0.0, ge=0.0, le=1.0, description="Cache hit rate (0-1)")
407
+ cache_hits: int = Field(default=0, ge=0, description="Number of cache hits")
408
+ cache_misses: int = Field(default=0, ge=0, description="Number of cache misses")
409
+
410
+ # Strategy metrics
411
+ vector_search_count: int = Field(default=0, ge=0, description="Number of vector-only searches")
412
+ graph_search_count: int = Field(default=0, ge=0, description="Number of graph-only searches")
413
+ hybrid_search_count: int = Field(default=0, ge=0, description="Number of hybrid searches")
414
+
415
+ # Entity extraction metrics
416
+ entity_extraction_count: int = Field(default=0, ge=0, description="Number of entity extractions performed")
417
+ average_extraction_time: float = Field(default=0.0, ge=0, description="Average entity extraction time in seconds")
418
+ total_extraction_time: float = Field(default=0.0, ge=0, description="Total entity extraction time in seconds")
419
+
420
+ # Timestamps
421
+ last_reset_at: Optional[datetime] = Field(None, description="When metrics were last reset")
422
+ updated_at: datetime = Field(default_factory=datetime.utcnow, description="Last metrics update")
423
+
424
+ model_config = ConfigDict()
425
+
426
+
427
+ class AgentInteraction(BaseModel):
428
+ """Model representing an agent interaction."""
429
+
430
+ interaction_id: str = Field(
431
+ default_factory=lambda: str(uuid.uuid4()),
432
+ description="Unique interaction identifier",
433
+ )
434
+ agent_id: str = Field(..., description="Agent ID involved in interaction")
435
+ interaction_type: str = Field(
436
+ ...,
437
+ description="Type of interaction (e.g., 'task', 'message', 'tool_call')",
438
+ )
439
+ content: Dict[str, Any] = Field(..., description="Interaction content")
440
+
441
+ # Timestamps
442
+ timestamp: datetime = Field(default_factory=datetime.utcnow, description="Interaction timestamp")
443
+ duration_seconds: Optional[float] = Field(None, ge=0, description="Interaction duration")
444
+
445
+ # Metadata
446
+ metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional interaction metadata")
447
+
448
+ model_config = ConfigDict()
449
+
450
+
451
+ class AgentMemory(BaseModel):
452
+ """Model for agent memory interface (base model, not implementation)."""
453
+
454
+ memory_id: str = Field(
455
+ default_factory=lambda: str(uuid.uuid4()),
456
+ description="Unique memory identifier",
457
+ )
458
+ agent_id: str = Field(..., description="Associated agent ID")
459
+ memory_type: MemoryType = Field(..., description="Type of memory")
460
+ key: str = Field(..., description="Memory key")
461
+ value: Any = Field(..., description="Memory value")
462
+ timestamp: datetime = Field(default_factory=datetime.utcnow, description="When memory was stored")
463
+
464
+ # Metadata
465
+ metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional memory metadata")
466
+
467
+ model_config = ConfigDict()
468
+
469
+
470
+ class Experience(BaseModel):
471
+ """
472
+ Model for recording agent learning experiences.
473
+
474
+ Tracks task execution experiences to enable learning and adaptation.
475
+ Used by agents to improve performance over time by learning from
476
+ past successes and failures. Experiences are used to recommend
477
+ optimal approaches for similar tasks.
478
+
479
+ **Key Features:**
480
+ - Comprehensive task execution tracking
481
+ - Success/failure outcome recording
482
+ - Quality scoring and error classification
483
+ - Learning insights and recommendations
484
+ - Context and performance metrics
485
+
486
+ Attributes:
487
+ experience_id: Unique identifier for the experience
488
+ agent_id: ID of the agent that had this experience
489
+ task_type: Type/category of task (e.g., "data_analysis", "search")
490
+ task_description: Human-readable task description
491
+ task_complexity: Task complexity level (simple, medium, complex)
492
+ approach: Approach/strategy used (e.g., "parallel_tools", "sequential")
493
+ tools_used: List of tool names used in execution
494
+ execution_time: Execution time in seconds
495
+ success: Whether task execution succeeded
496
+ quality_score: Quality score from 0.0 to 1.0 (None if not available)
497
+ error_type: Type of error if failed (e.g., "timeout", "validation_error")
498
+ error_message: Error message if failed
499
+ context_size: Context size in tokens (if applicable)
500
+ iterations: Number of iterations/attempts (if applicable)
501
+ lessons_learned: Human-readable lessons learned from this experience
502
+ recommended_improvements: Recommended improvements for future tasks
503
+ timestamp: When the experience occurred
504
+ metadata: Additional experience metadata
505
+
506
+ Examples:
507
+ # Example 1: Successful experience
508
+ experience = Experience(
509
+ agent_id="agent-1",
510
+ task_type="data_analysis",
511
+ task_description="Analyze sales data for Q4",
512
+ task_complexity="medium",
513
+ approach="parallel_tools",
514
+ tools_used=["pandas", "numpy"],
515
+ execution_time=2.5,
516
+ success=True,
517
+ quality_score=0.95,
518
+ context_size=5000,
519
+ iterations=1
520
+ )
521
+
522
+ # Example 2: Failed experience with error details
523
+ experience = Experience(
524
+ agent_id="agent-1",
525
+ task_type="web_scraping",
526
+ task_description="Scrape product prices",
527
+ task_complexity="simple",
528
+ approach="single_tool",
529
+ tools_used=["scraper"],
530
+ execution_time=30.0,
531
+ success=False,
532
+ error_type="timeout",
533
+ error_message="Request timed out after 30 seconds",
534
+ lessons_learned="Use retry logic for network operations",
535
+ recommended_improvements="Add exponential backoff retry"
536
+ )
537
+
538
+ # Example 3: Experience with learning insights
539
+ experience = Experience(
540
+ agent_id="agent-1",
541
+ task_type="data_analysis",
542
+ task_description="Analyze customer feedback",
543
+ approach="parallel_tools",
544
+ tools_used=["nlp", "sentiment"],
545
+ execution_time=5.2,
546
+ success=True,
547
+ quality_score=0.88,
548
+ lessons_learned="Parallel execution reduced time by 40%",
549
+ recommended_improvements="Use parallel approach for similar tasks"
550
+ )
551
+ """
552
+
553
+ experience_id: str = Field(
554
+ default_factory=lambda: str(uuid.uuid4()),
555
+ description="Unique experience identifier",
556
+ )
557
+ agent_id: str = Field(..., description="Agent that had this experience")
558
+
559
+ # Task information
560
+ task_type: str = Field(..., description="Type/category of task")
561
+ task_description: str = Field(..., description="Task description")
562
+ task_complexity: Optional[str] = Field(None, description="Task complexity (simple, medium, complex)")
563
+
564
+ # Execution details
565
+ approach: str = Field(..., description="Approach/strategy used")
566
+ tools_used: List[str] = Field(default_factory=list, description="Tools used in execution")
567
+ execution_time: float = Field(..., ge=0, description="Execution time in seconds")
568
+
569
+ # Outcome
570
+ success: bool = Field(..., description="Whether task was successful")
571
+ quality_score: Optional[float] = Field(None, ge=0.0, le=1.0, description="Quality score (0-1)")
572
+ error_type: Optional[str] = Field(None, description="Error type if failed")
573
+ error_message: Optional[str] = Field(None, description="Error message if failed")
574
+
575
+ # Context
576
+ context_size: Optional[int] = Field(None, ge=0, description="Context size in tokens")
577
+ iterations: Optional[int] = Field(None, ge=0, description="Number of iterations")
578
+
579
+ # Learning insights
580
+ lessons_learned: Optional[str] = Field(None, description="Lessons learned from experience")
581
+ recommended_improvements: Optional[str] = Field(None, description="Recommended improvements")
582
+
583
+ # Timestamps
584
+ timestamp: datetime = Field(default_factory=datetime.utcnow, description="When experience occurred")
585
+
586
+ # Metadata
587
+ metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional experience metadata")
588
+
589
+ model_config = ConfigDict()
590
+
591
+
592
+ class ResourceLimits(BaseModel):
593
+ """
594
+ Configuration for agent resource limits and rate limiting.
595
+
596
+ Provides control over resource usage to prevent exhaustion and
597
+ ensure stable operation in production environments. Supports
598
+ token bucket algorithm for rate limiting, concurrent task limits,
599
+ and memory constraints.
600
+
601
+ **Key Features:**
602
+ - Concurrent task limits to prevent overload
603
+ - Token rate limiting with burst support (token bucket algorithm)
604
+ - Tool call rate limiting per minute/hour
605
+ - Memory usage limits
606
+ - Task timeout configuration
607
+ - Configurable enforcement (enforce vs monitor)
608
+
609
+ Attributes:
610
+ max_concurrent_tasks: Maximum number of concurrent tasks (default: 10)
611
+ max_tokens_per_minute: Maximum tokens per minute (None = unlimited)
612
+ max_tokens_per_hour: Maximum tokens per hour (None = unlimited)
613
+ token_burst_size: Token burst size for token bucket (None = use max_tokens_per_minute)
614
+ max_tool_calls_per_minute: Maximum tool calls per minute (None = unlimited)
615
+ max_tool_calls_per_hour: Maximum tool calls per hour (None = unlimited)
616
+ max_memory_mb: Maximum memory usage in MB (None = unlimited)
617
+ task_timeout_seconds: Maximum task execution time in seconds (None = unlimited)
618
+ resource_wait_timeout_seconds: Maximum time to wait for resources (default: 60)
619
+ enforce_limits: Whether to enforce resource limits (default: True)
620
+ reject_on_limit: Reject requests when limit reached vs wait (default: False)
621
+
622
+ Examples:
623
+ # Example 1: Basic rate limiting
624
+ limits = ResourceLimits(
625
+ max_concurrent_tasks=5,
626
+ max_tokens_per_minute=10000,
627
+ max_tool_calls_per_minute=100
628
+ )
629
+
630
+ # Example 2: Token bucket with burst support
631
+ limits = ResourceLimits(
632
+ max_tokens_per_minute=10000,
633
+ token_burst_size=20000, # Allow 2x burst
634
+ max_tool_calls_per_minute=100
635
+ )
636
+
637
+ # Example 3: Strict limits for production
638
+ limits = ResourceLimits(
639
+ max_concurrent_tasks=10,
640
+ max_tokens_per_minute=50000,
641
+ max_tokens_per_hour=2000000,
642
+ max_tool_calls_per_minute=500,
643
+ max_memory_mb=2048,
644
+ task_timeout_seconds=300,
645
+ enforce_limits=True,
646
+ reject_on_limit=True # Reject instead of waiting
647
+ )
648
+
649
+ # Example 4: Monitoring mode (don't enforce)
650
+ limits = ResourceLimits(
651
+ max_concurrent_tasks=10,
652
+ max_tokens_per_minute=10000,
653
+ enforce_limits=False # Monitor but don't enforce
654
+ )
655
+
656
+ # Example 5: Wait for resources instead of rejecting
657
+ limits = ResourceLimits(
658
+ max_concurrent_tasks=5,
659
+ max_tokens_per_minute=10000,
660
+ resource_wait_timeout_seconds=120, # Wait up to 2 minutes
661
+ reject_on_limit=False # Wait instead of reject
662
+ )
663
+ """
664
+
665
+ # Concurrent task limits
666
+ max_concurrent_tasks: int = Field(default=10, ge=1, description="Maximum number of concurrent tasks")
667
+
668
+ # Token rate limits (token bucket algorithm)
669
+ max_tokens_per_minute: Optional[int] = Field(None, ge=0, description="Maximum tokens per minute (None = unlimited)")
670
+ max_tokens_per_hour: Optional[int] = Field(None, ge=0, description="Maximum tokens per hour (None = unlimited)")
671
+ token_burst_size: Optional[int] = Field(
672
+ None,
673
+ ge=0,
674
+ description="Token burst size for token bucket (None = use max_tokens_per_minute)",
675
+ )
676
+
677
+ # Tool call rate limits
678
+ max_tool_calls_per_minute: Optional[int] = Field(None, ge=0, description="Maximum tool calls per minute (None = unlimited)")
679
+ max_tool_calls_per_hour: Optional[int] = Field(None, ge=0, description="Maximum tool calls per hour (None = unlimited)")
680
+
681
+ # Memory limits
682
+ max_memory_mb: Optional[int] = Field(None, ge=0, description="Maximum memory usage in MB (None = unlimited)")
683
+
684
+ # Timeout settings
685
+ task_timeout_seconds: Optional[int] = Field(None, ge=0, description="Maximum task execution time in seconds (None = unlimited)")
686
+ resource_wait_timeout_seconds: int = Field(default=60, ge=0, description="Maximum time to wait for resources")
687
+
688
+ # Enforcement
689
+ enforce_limits: bool = Field(default=True, description="Whether to enforce resource limits")
690
+ reject_on_limit: bool = Field(default=False, description="Reject requests when limit reached (vs wait)")
691
+
692
+ model_config = ConfigDict()
693
+
694
+
695
+ class ToolObservation(BaseModel):
696
+ """
697
+ Structured observation of tool execution results.
698
+
699
+ Provides a standardized format for tracking tool execution with
700
+ success/error status, execution time, and timestamps. Used for
701
+ debugging, analysis, and LLM reasoning loops.
702
+
703
+ This pattern is essential for MasterController compatibility and
704
+ observation-based reasoning. Observations can be converted to text
705
+ format for inclusion in LLM prompts or to dictionaries for serialization.
706
+
707
+ **Key Features:**
708
+ - Automatic success/error tracking
709
+ - Execution time measurement
710
+ - ISO timestamp generation
711
+ - Text formatting for LLM context
712
+ - Dictionary serialization for storage
713
+
714
+ Attributes:
715
+ tool_name: Name of the tool that was executed
716
+ parameters: Dictionary of parameters passed to the tool
717
+ result: Tool execution result (any type)
718
+ success: Whether tool execution succeeded (True/False)
719
+ error: Error message if execution failed (None if successful)
720
+ execution_time_ms: Execution time in milliseconds (None if not measured)
721
+ timestamp: ISO format timestamp of execution
722
+
723
+ Examples:
724
+ # Example 1: Successful tool execution
725
+ from aiecs.domain.agent.models import ToolObservation
726
+
727
+ obs = ToolObservation(
728
+ tool_name="search",
729
+ parameters={"query": "AI", "limit": 10},
730
+ result=["result1", "result2", "result3"],
731
+ success=True,
732
+ execution_time_ms=250.5
733
+ )
734
+
735
+ # Convert to text for LLM context
736
+ text = obs.to_text()
737
+ # "Tool: search
738
+ # Parameters: {'query': 'AI', 'limit': 10}
739
+ # Status: SUCCESS
740
+ # Result: ['result1', 'result2', 'result3']
741
+ # Execution time: 250.5ms"
742
+
743
+ # Example 2: Failed tool execution
744
+ obs = ToolObservation(
745
+ tool_name="calculator",
746
+ parameters={"operation": "divide", "a": 10, "b": 0},
747
+ result=None,
748
+ success=False,
749
+ error="Division by zero",
750
+ execution_time_ms=5.2
751
+ )
752
+
753
+ text = obs.to_text()
754
+ # "Tool: calculator
755
+ # Parameters: {'operation': 'divide', 'a': 10, 'b': 0}
756
+ # Status: ERROR
757
+ # Error: Division by zero
758
+ # Execution time: 5.2ms"
759
+
760
+ # Example 3: Using with agent execution
761
+ from aiecs.domain.agent import HybridAgent
762
+
763
+ agent = HybridAgent(...)
764
+ obs = await agent._execute_tool_with_observation(
765
+ tool_name="search",
766
+ operation="query",
767
+ parameters={"q": "Python"}
768
+ )
769
+
770
+ # Check success
771
+ if obs.success:
772
+ print(f"Found {len(obs.result)} results")
773
+ else:
774
+ print(f"Error: {obs.error}")
775
+
776
+ # Example 4: Serialization for storage
777
+ obs = ToolObservation(
778
+ tool_name="api_call",
779
+ parameters={"endpoint": "/data", "method": "GET"},
780
+ result={"status": 200, "data": {...}},
781
+ success=True,
782
+ execution_time_ms=1234.5
783
+ )
784
+
785
+ # Convert to dict for JSON serialization
786
+ data = obs.to_dict()
787
+ # {'tool_name': 'api_call', 'parameters': {...}, 'success': True, ...}
788
+
789
+ # Example 5: Using in observation-based reasoning loop
790
+ observations = []
791
+ for tool_call in tool_calls:
792
+ obs = await agent._execute_tool_with_observation(
793
+ tool_name=tool_call["tool"],
794
+ parameters=tool_call["parameters"]
795
+ )
796
+ observations.append(obs)
797
+
798
+ # Format observations for LLM context
799
+ observation_text = "\\n\\n".join([obs.to_text() for obs in observations])
800
+ # Include in LLM prompt for reasoning
801
+ """
802
+
803
+ tool_name: str = Field(..., description="Name of the tool that was executed")
804
+ parameters: Dict[str, Any] = Field(default_factory=dict, description="Parameters passed to the tool")
805
+ result: Any = Field(None, description="Tool execution result")
806
+ success: bool = Field(..., description="Whether tool execution succeeded")
807
+ error: Optional[str] = Field(None, description="Error message if execution failed")
808
+ execution_time_ms: Optional[float] = Field(None, ge=0, description="Execution time in milliseconds")
809
+ timestamp: str = Field(
810
+ default_factory=lambda: datetime.utcnow().isoformat(),
811
+ description="ISO format timestamp of execution",
812
+ )
813
+
814
+ model_config = ConfigDict()
815
+
816
+ def to_dict(self) -> Dict[str, Any]:
817
+ """
818
+ Convert observation to dictionary.
819
+
820
+ Returns:
821
+ Dict representation of the observation
822
+
823
+ Example:
824
+ ```python
825
+ obs = ToolObservation(tool_name="search", success=True, result="data")
826
+ data = obs.to_dict()
827
+ # {'tool_name': 'search', 'success': True, 'result': 'data', ...}
828
+ ```
829
+ """
830
+ return {
831
+ "tool_name": self.tool_name,
832
+ "parameters": self.parameters,
833
+ "result": self.result,
834
+ "success": self.success,
835
+ "error": self.error,
836
+ "execution_time_ms": self.execution_time_ms,
837
+ "timestamp": self.timestamp,
838
+ }
839
+
840
+ def to_text(self) -> str:
841
+ """
842
+ Format observation as text for LLM context.
843
+
844
+ Provides a human-readable format suitable for including in
845
+ LLM prompts and reasoning loops.
846
+
847
+ Returns:
848
+ Formatted text representation
849
+
850
+ Example:
851
+ ```python
852
+ obs = ToolObservation(
853
+ tool_name="search",
854
+ parameters={"query": "AI"},
855
+ success=True,
856
+ result="Found 10 results",
857
+ execution_time_ms=250.5
858
+ )
859
+ text = obs.to_text()
860
+ # "Tool: search
861
+ # Parameters: {'query': 'AI'}
862
+ # Status: SUCCESS
863
+ # Result: Found 10 results
864
+ # Execution time: 250.5ms"
865
+ ```
866
+ """
867
+ lines = [
868
+ f"Tool: {self.tool_name}",
869
+ f"Parameters: {self.parameters}",
870
+ ]
871
+
872
+ if self.success:
873
+ lines.append("Status: SUCCESS")
874
+ lines.append(f"Result: {self.result}")
875
+ else:
876
+ lines.append("Status: FAILURE")
877
+ lines.append(f"Error: {self.error}")
878
+
879
+ if self.execution_time_ms is not None:
880
+ lines.append(f"Execution time: {self.execution_time_ms:.2f}ms")
881
+
882
+ lines.append(f"Timestamp: {self.timestamp}")
883
+
884
+ return "\n".join(lines)