aiecs 1.5.1__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.
Files changed (302) hide show
  1. aiecs/__init__.py +72 -0
  2. aiecs/__main__.py +41 -0
  3. aiecs/aiecs_client.py +469 -0
  4. aiecs/application/__init__.py +10 -0
  5. aiecs/application/executors/__init__.py +10 -0
  6. aiecs/application/executors/operation_executor.py +363 -0
  7. aiecs/application/knowledge_graph/__init__.py +7 -0
  8. aiecs/application/knowledge_graph/builder/__init__.py +37 -0
  9. aiecs/application/knowledge_graph/builder/document_builder.py +375 -0
  10. aiecs/application/knowledge_graph/builder/graph_builder.py +356 -0
  11. aiecs/application/knowledge_graph/builder/schema_mapping.py +531 -0
  12. aiecs/application/knowledge_graph/builder/structured_pipeline.py +443 -0
  13. aiecs/application/knowledge_graph/builder/text_chunker.py +319 -0
  14. aiecs/application/knowledge_graph/extractors/__init__.py +27 -0
  15. aiecs/application/knowledge_graph/extractors/base.py +100 -0
  16. aiecs/application/knowledge_graph/extractors/llm_entity_extractor.py +327 -0
  17. aiecs/application/knowledge_graph/extractors/llm_relation_extractor.py +349 -0
  18. aiecs/application/knowledge_graph/extractors/ner_entity_extractor.py +244 -0
  19. aiecs/application/knowledge_graph/fusion/__init__.py +23 -0
  20. aiecs/application/knowledge_graph/fusion/entity_deduplicator.py +387 -0
  21. aiecs/application/knowledge_graph/fusion/entity_linker.py +343 -0
  22. aiecs/application/knowledge_graph/fusion/knowledge_fusion.py +580 -0
  23. aiecs/application/knowledge_graph/fusion/relation_deduplicator.py +189 -0
  24. aiecs/application/knowledge_graph/pattern_matching/__init__.py +21 -0
  25. aiecs/application/knowledge_graph/pattern_matching/pattern_matcher.py +344 -0
  26. aiecs/application/knowledge_graph/pattern_matching/query_executor.py +378 -0
  27. aiecs/application/knowledge_graph/profiling/__init__.py +12 -0
  28. aiecs/application/knowledge_graph/profiling/query_plan_visualizer.py +199 -0
  29. aiecs/application/knowledge_graph/profiling/query_profiler.py +223 -0
  30. aiecs/application/knowledge_graph/reasoning/__init__.py +27 -0
  31. aiecs/application/knowledge_graph/reasoning/evidence_synthesis.py +347 -0
  32. aiecs/application/knowledge_graph/reasoning/inference_engine.py +504 -0
  33. aiecs/application/knowledge_graph/reasoning/logic_form_parser.py +167 -0
  34. aiecs/application/knowledge_graph/reasoning/logic_parser/__init__.py +79 -0
  35. aiecs/application/knowledge_graph/reasoning/logic_parser/ast_builder.py +513 -0
  36. aiecs/application/knowledge_graph/reasoning/logic_parser/ast_nodes.py +630 -0
  37. aiecs/application/knowledge_graph/reasoning/logic_parser/ast_validator.py +654 -0
  38. aiecs/application/knowledge_graph/reasoning/logic_parser/error_handler.py +477 -0
  39. aiecs/application/knowledge_graph/reasoning/logic_parser/parser.py +390 -0
  40. aiecs/application/knowledge_graph/reasoning/logic_parser/query_context.py +217 -0
  41. aiecs/application/knowledge_graph/reasoning/logic_query_integration.py +169 -0
  42. aiecs/application/knowledge_graph/reasoning/query_planner.py +872 -0
  43. aiecs/application/knowledge_graph/reasoning/reasoning_engine.py +554 -0
  44. aiecs/application/knowledge_graph/retrieval/__init__.py +19 -0
  45. aiecs/application/knowledge_graph/retrieval/retrieval_strategies.py +596 -0
  46. aiecs/application/knowledge_graph/search/__init__.py +59 -0
  47. aiecs/application/knowledge_graph/search/hybrid_search.py +423 -0
  48. aiecs/application/knowledge_graph/search/reranker.py +295 -0
  49. aiecs/application/knowledge_graph/search/reranker_strategies.py +553 -0
  50. aiecs/application/knowledge_graph/search/text_similarity.py +398 -0
  51. aiecs/application/knowledge_graph/traversal/__init__.py +15 -0
  52. aiecs/application/knowledge_graph/traversal/enhanced_traversal.py +329 -0
  53. aiecs/application/knowledge_graph/traversal/path_scorer.py +269 -0
  54. aiecs/application/knowledge_graph/validators/__init__.py +13 -0
  55. aiecs/application/knowledge_graph/validators/relation_validator.py +189 -0
  56. aiecs/application/knowledge_graph/visualization/__init__.py +11 -0
  57. aiecs/application/knowledge_graph/visualization/graph_visualizer.py +321 -0
  58. aiecs/common/__init__.py +9 -0
  59. aiecs/common/knowledge_graph/__init__.py +17 -0
  60. aiecs/common/knowledge_graph/runnable.py +484 -0
  61. aiecs/config/__init__.py +16 -0
  62. aiecs/config/config.py +498 -0
  63. aiecs/config/graph_config.py +137 -0
  64. aiecs/config/registry.py +23 -0
  65. aiecs/core/__init__.py +46 -0
  66. aiecs/core/interface/__init__.py +34 -0
  67. aiecs/core/interface/execution_interface.py +152 -0
  68. aiecs/core/interface/storage_interface.py +171 -0
  69. aiecs/domain/__init__.py +289 -0
  70. aiecs/domain/agent/__init__.py +189 -0
  71. aiecs/domain/agent/base_agent.py +697 -0
  72. aiecs/domain/agent/exceptions.py +103 -0
  73. aiecs/domain/agent/graph_aware_mixin.py +559 -0
  74. aiecs/domain/agent/hybrid_agent.py +490 -0
  75. aiecs/domain/agent/integration/__init__.py +26 -0
  76. aiecs/domain/agent/integration/context_compressor.py +222 -0
  77. aiecs/domain/agent/integration/context_engine_adapter.py +252 -0
  78. aiecs/domain/agent/integration/retry_policy.py +219 -0
  79. aiecs/domain/agent/integration/role_config.py +213 -0
  80. aiecs/domain/agent/knowledge_aware_agent.py +646 -0
  81. aiecs/domain/agent/lifecycle.py +296 -0
  82. aiecs/domain/agent/llm_agent.py +300 -0
  83. aiecs/domain/agent/memory/__init__.py +12 -0
  84. aiecs/domain/agent/memory/conversation.py +197 -0
  85. aiecs/domain/agent/migration/__init__.py +14 -0
  86. aiecs/domain/agent/migration/conversion.py +160 -0
  87. aiecs/domain/agent/migration/legacy_wrapper.py +90 -0
  88. aiecs/domain/agent/models.py +317 -0
  89. aiecs/domain/agent/observability.py +407 -0
  90. aiecs/domain/agent/persistence.py +289 -0
  91. aiecs/domain/agent/prompts/__init__.py +29 -0
  92. aiecs/domain/agent/prompts/builder.py +161 -0
  93. aiecs/domain/agent/prompts/formatters.py +189 -0
  94. aiecs/domain/agent/prompts/template.py +255 -0
  95. aiecs/domain/agent/registry.py +260 -0
  96. aiecs/domain/agent/tool_agent.py +257 -0
  97. aiecs/domain/agent/tools/__init__.py +12 -0
  98. aiecs/domain/agent/tools/schema_generator.py +221 -0
  99. aiecs/domain/community/__init__.py +155 -0
  100. aiecs/domain/community/agent_adapter.py +477 -0
  101. aiecs/domain/community/analytics.py +481 -0
  102. aiecs/domain/community/collaborative_workflow.py +642 -0
  103. aiecs/domain/community/communication_hub.py +645 -0
  104. aiecs/domain/community/community_builder.py +320 -0
  105. aiecs/domain/community/community_integration.py +800 -0
  106. aiecs/domain/community/community_manager.py +813 -0
  107. aiecs/domain/community/decision_engine.py +879 -0
  108. aiecs/domain/community/exceptions.py +225 -0
  109. aiecs/domain/community/models/__init__.py +33 -0
  110. aiecs/domain/community/models/community_models.py +268 -0
  111. aiecs/domain/community/resource_manager.py +457 -0
  112. aiecs/domain/community/shared_context_manager.py +603 -0
  113. aiecs/domain/context/__init__.py +58 -0
  114. aiecs/domain/context/context_engine.py +989 -0
  115. aiecs/domain/context/conversation_models.py +354 -0
  116. aiecs/domain/context/graph_memory.py +467 -0
  117. aiecs/domain/execution/__init__.py +12 -0
  118. aiecs/domain/execution/model.py +57 -0
  119. aiecs/domain/knowledge_graph/__init__.py +19 -0
  120. aiecs/domain/knowledge_graph/models/__init__.py +52 -0
  121. aiecs/domain/knowledge_graph/models/entity.py +130 -0
  122. aiecs/domain/knowledge_graph/models/evidence.py +194 -0
  123. aiecs/domain/knowledge_graph/models/inference_rule.py +186 -0
  124. aiecs/domain/knowledge_graph/models/path.py +179 -0
  125. aiecs/domain/knowledge_graph/models/path_pattern.py +173 -0
  126. aiecs/domain/knowledge_graph/models/query.py +272 -0
  127. aiecs/domain/knowledge_graph/models/query_plan.py +187 -0
  128. aiecs/domain/knowledge_graph/models/relation.py +136 -0
  129. aiecs/domain/knowledge_graph/schema/__init__.py +23 -0
  130. aiecs/domain/knowledge_graph/schema/entity_type.py +135 -0
  131. aiecs/domain/knowledge_graph/schema/graph_schema.py +271 -0
  132. aiecs/domain/knowledge_graph/schema/property_schema.py +155 -0
  133. aiecs/domain/knowledge_graph/schema/relation_type.py +171 -0
  134. aiecs/domain/knowledge_graph/schema/schema_manager.py +496 -0
  135. aiecs/domain/knowledge_graph/schema/type_enums.py +205 -0
  136. aiecs/domain/task/__init__.py +13 -0
  137. aiecs/domain/task/dsl_processor.py +613 -0
  138. aiecs/domain/task/model.py +62 -0
  139. aiecs/domain/task/task_context.py +268 -0
  140. aiecs/infrastructure/__init__.py +24 -0
  141. aiecs/infrastructure/graph_storage/__init__.py +11 -0
  142. aiecs/infrastructure/graph_storage/base.py +601 -0
  143. aiecs/infrastructure/graph_storage/batch_operations.py +449 -0
  144. aiecs/infrastructure/graph_storage/cache.py +429 -0
  145. aiecs/infrastructure/graph_storage/distributed.py +226 -0
  146. aiecs/infrastructure/graph_storage/error_handling.py +390 -0
  147. aiecs/infrastructure/graph_storage/graceful_degradation.py +306 -0
  148. aiecs/infrastructure/graph_storage/health_checks.py +378 -0
  149. aiecs/infrastructure/graph_storage/in_memory.py +514 -0
  150. aiecs/infrastructure/graph_storage/index_optimization.py +483 -0
  151. aiecs/infrastructure/graph_storage/lazy_loading.py +410 -0
  152. aiecs/infrastructure/graph_storage/metrics.py +357 -0
  153. aiecs/infrastructure/graph_storage/migration.py +413 -0
  154. aiecs/infrastructure/graph_storage/pagination.py +471 -0
  155. aiecs/infrastructure/graph_storage/performance_monitoring.py +466 -0
  156. aiecs/infrastructure/graph_storage/postgres.py +871 -0
  157. aiecs/infrastructure/graph_storage/query_optimizer.py +635 -0
  158. aiecs/infrastructure/graph_storage/schema_cache.py +290 -0
  159. aiecs/infrastructure/graph_storage/sqlite.py +623 -0
  160. aiecs/infrastructure/graph_storage/streaming.py +495 -0
  161. aiecs/infrastructure/messaging/__init__.py +13 -0
  162. aiecs/infrastructure/messaging/celery_task_manager.py +383 -0
  163. aiecs/infrastructure/messaging/websocket_manager.py +298 -0
  164. aiecs/infrastructure/monitoring/__init__.py +34 -0
  165. aiecs/infrastructure/monitoring/executor_metrics.py +174 -0
  166. aiecs/infrastructure/monitoring/global_metrics_manager.py +213 -0
  167. aiecs/infrastructure/monitoring/structured_logger.py +48 -0
  168. aiecs/infrastructure/monitoring/tracing_manager.py +410 -0
  169. aiecs/infrastructure/persistence/__init__.py +24 -0
  170. aiecs/infrastructure/persistence/context_engine_client.py +187 -0
  171. aiecs/infrastructure/persistence/database_manager.py +333 -0
  172. aiecs/infrastructure/persistence/file_storage.py +754 -0
  173. aiecs/infrastructure/persistence/redis_client.py +220 -0
  174. aiecs/llm/__init__.py +86 -0
  175. aiecs/llm/callbacks/__init__.py +11 -0
  176. aiecs/llm/callbacks/custom_callbacks.py +264 -0
  177. aiecs/llm/client_factory.py +420 -0
  178. aiecs/llm/clients/__init__.py +33 -0
  179. aiecs/llm/clients/base_client.py +193 -0
  180. aiecs/llm/clients/googleai_client.py +181 -0
  181. aiecs/llm/clients/openai_client.py +131 -0
  182. aiecs/llm/clients/vertex_client.py +437 -0
  183. aiecs/llm/clients/xai_client.py +184 -0
  184. aiecs/llm/config/__init__.py +51 -0
  185. aiecs/llm/config/config_loader.py +275 -0
  186. aiecs/llm/config/config_validator.py +236 -0
  187. aiecs/llm/config/model_config.py +151 -0
  188. aiecs/llm/utils/__init__.py +10 -0
  189. aiecs/llm/utils/validate_config.py +91 -0
  190. aiecs/main.py +363 -0
  191. aiecs/scripts/__init__.py +3 -0
  192. aiecs/scripts/aid/VERSION_MANAGEMENT.md +97 -0
  193. aiecs/scripts/aid/__init__.py +19 -0
  194. aiecs/scripts/aid/version_manager.py +215 -0
  195. aiecs/scripts/dependance_check/DEPENDENCY_SYSTEM_SUMMARY.md +242 -0
  196. aiecs/scripts/dependance_check/README_DEPENDENCY_CHECKER.md +310 -0
  197. aiecs/scripts/dependance_check/__init__.py +17 -0
  198. aiecs/scripts/dependance_check/dependency_checker.py +938 -0
  199. aiecs/scripts/dependance_check/dependency_fixer.py +391 -0
  200. aiecs/scripts/dependance_check/download_nlp_data.py +396 -0
  201. aiecs/scripts/dependance_check/quick_dependency_check.py +270 -0
  202. aiecs/scripts/dependance_check/setup_nlp_data.sh +217 -0
  203. aiecs/scripts/dependance_patch/__init__.py +7 -0
  204. aiecs/scripts/dependance_patch/fix_weasel/README_WEASEL_PATCH.md +126 -0
  205. aiecs/scripts/dependance_patch/fix_weasel/__init__.py +11 -0
  206. aiecs/scripts/dependance_patch/fix_weasel/fix_weasel_validator.py +128 -0
  207. aiecs/scripts/dependance_patch/fix_weasel/fix_weasel_validator.sh +82 -0
  208. aiecs/scripts/dependance_patch/fix_weasel/patch_weasel_library.sh +188 -0
  209. aiecs/scripts/dependance_patch/fix_weasel/run_weasel_patch.sh +41 -0
  210. aiecs/scripts/tools_develop/README.md +449 -0
  211. aiecs/scripts/tools_develop/TOOL_AUTO_DISCOVERY.md +234 -0
  212. aiecs/scripts/tools_develop/__init__.py +21 -0
  213. aiecs/scripts/tools_develop/check_type_annotations.py +259 -0
  214. aiecs/scripts/tools_develop/validate_tool_schemas.py +422 -0
  215. aiecs/scripts/tools_develop/verify_tools.py +356 -0
  216. aiecs/tasks/__init__.py +1 -0
  217. aiecs/tasks/worker.py +172 -0
  218. aiecs/tools/__init__.py +299 -0
  219. aiecs/tools/apisource/__init__.py +99 -0
  220. aiecs/tools/apisource/intelligence/__init__.py +19 -0
  221. aiecs/tools/apisource/intelligence/data_fusion.py +381 -0
  222. aiecs/tools/apisource/intelligence/query_analyzer.py +413 -0
  223. aiecs/tools/apisource/intelligence/search_enhancer.py +388 -0
  224. aiecs/tools/apisource/monitoring/__init__.py +9 -0
  225. aiecs/tools/apisource/monitoring/metrics.py +303 -0
  226. aiecs/tools/apisource/providers/__init__.py +115 -0
  227. aiecs/tools/apisource/providers/base.py +664 -0
  228. aiecs/tools/apisource/providers/census.py +401 -0
  229. aiecs/tools/apisource/providers/fred.py +564 -0
  230. aiecs/tools/apisource/providers/newsapi.py +412 -0
  231. aiecs/tools/apisource/providers/worldbank.py +357 -0
  232. aiecs/tools/apisource/reliability/__init__.py +12 -0
  233. aiecs/tools/apisource/reliability/error_handler.py +375 -0
  234. aiecs/tools/apisource/reliability/fallback_strategy.py +391 -0
  235. aiecs/tools/apisource/tool.py +850 -0
  236. aiecs/tools/apisource/utils/__init__.py +9 -0
  237. aiecs/tools/apisource/utils/validators.py +338 -0
  238. aiecs/tools/base_tool.py +201 -0
  239. aiecs/tools/docs/__init__.py +121 -0
  240. aiecs/tools/docs/ai_document_orchestrator.py +599 -0
  241. aiecs/tools/docs/ai_document_writer_orchestrator.py +2403 -0
  242. aiecs/tools/docs/content_insertion_tool.py +1333 -0
  243. aiecs/tools/docs/document_creator_tool.py +1317 -0
  244. aiecs/tools/docs/document_layout_tool.py +1166 -0
  245. aiecs/tools/docs/document_parser_tool.py +994 -0
  246. aiecs/tools/docs/document_writer_tool.py +1818 -0
  247. aiecs/tools/knowledge_graph/__init__.py +17 -0
  248. aiecs/tools/knowledge_graph/graph_reasoning_tool.py +734 -0
  249. aiecs/tools/knowledge_graph/graph_search_tool.py +923 -0
  250. aiecs/tools/knowledge_graph/kg_builder_tool.py +476 -0
  251. aiecs/tools/langchain_adapter.py +542 -0
  252. aiecs/tools/schema_generator.py +275 -0
  253. aiecs/tools/search_tool/__init__.py +100 -0
  254. aiecs/tools/search_tool/analyzers.py +589 -0
  255. aiecs/tools/search_tool/cache.py +260 -0
  256. aiecs/tools/search_tool/constants.py +128 -0
  257. aiecs/tools/search_tool/context.py +216 -0
  258. aiecs/tools/search_tool/core.py +749 -0
  259. aiecs/tools/search_tool/deduplicator.py +123 -0
  260. aiecs/tools/search_tool/error_handler.py +271 -0
  261. aiecs/tools/search_tool/metrics.py +371 -0
  262. aiecs/tools/search_tool/rate_limiter.py +178 -0
  263. aiecs/tools/search_tool/schemas.py +277 -0
  264. aiecs/tools/statistics/__init__.py +80 -0
  265. aiecs/tools/statistics/ai_data_analysis_orchestrator.py +643 -0
  266. aiecs/tools/statistics/ai_insight_generator_tool.py +505 -0
  267. aiecs/tools/statistics/ai_report_orchestrator_tool.py +694 -0
  268. aiecs/tools/statistics/data_loader_tool.py +564 -0
  269. aiecs/tools/statistics/data_profiler_tool.py +658 -0
  270. aiecs/tools/statistics/data_transformer_tool.py +573 -0
  271. aiecs/tools/statistics/data_visualizer_tool.py +495 -0
  272. aiecs/tools/statistics/model_trainer_tool.py +487 -0
  273. aiecs/tools/statistics/statistical_analyzer_tool.py +459 -0
  274. aiecs/tools/task_tools/__init__.py +86 -0
  275. aiecs/tools/task_tools/chart_tool.py +732 -0
  276. aiecs/tools/task_tools/classfire_tool.py +922 -0
  277. aiecs/tools/task_tools/image_tool.py +447 -0
  278. aiecs/tools/task_tools/office_tool.py +684 -0
  279. aiecs/tools/task_tools/pandas_tool.py +635 -0
  280. aiecs/tools/task_tools/report_tool.py +635 -0
  281. aiecs/tools/task_tools/research_tool.py +392 -0
  282. aiecs/tools/task_tools/scraper_tool.py +715 -0
  283. aiecs/tools/task_tools/stats_tool.py +688 -0
  284. aiecs/tools/temp_file_manager.py +130 -0
  285. aiecs/tools/tool_executor/__init__.py +37 -0
  286. aiecs/tools/tool_executor/tool_executor.py +881 -0
  287. aiecs/utils/LLM_output_structor.py +445 -0
  288. aiecs/utils/__init__.py +34 -0
  289. aiecs/utils/base_callback.py +47 -0
  290. aiecs/utils/cache_provider.py +695 -0
  291. aiecs/utils/execution_utils.py +184 -0
  292. aiecs/utils/logging.py +1 -0
  293. aiecs/utils/prompt_loader.py +14 -0
  294. aiecs/utils/token_usage_repository.py +323 -0
  295. aiecs/ws/__init__.py +0 -0
  296. aiecs/ws/socket_server.py +52 -0
  297. aiecs-1.5.1.dist-info/METADATA +608 -0
  298. aiecs-1.5.1.dist-info/RECORD +302 -0
  299. aiecs-1.5.1.dist-info/WHEEL +5 -0
  300. aiecs-1.5.1.dist-info/entry_points.txt +10 -0
  301. aiecs-1.5.1.dist-info/licenses/LICENSE +225 -0
  302. aiecs-1.5.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,422 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ 工具 Schema 质量验证器
4
+
5
+ 用于工具开发和维护,验证自动生成的 Schema 质量。
6
+ 帮助开发者识别需要改进的文档字符串,提升 Schema 描述质量。
7
+
8
+ 使用方法:
9
+ # 验证所有工具
10
+ aiecs tools validate-schemas
11
+
12
+ # 验证特定工具
13
+ aiecs tools validate-schemas pandas
14
+
15
+ # 显示详细的改进建议
16
+ aiecs tools validate-schemas pandas --verbose
17
+
18
+ # 显示示例 Schema
19
+ aiecs tools validate-schemas pandas --show-examples
20
+ """
21
+
22
+ from aiecs.tools.schema_generator import generate_schema_from_method
23
+ from aiecs.tools import discover_tools, TOOL_CLASSES
24
+ import sys
25
+ from typing import Dict, List, Any, Type, Optional
26
+ from pydantic import BaseModel
27
+
28
+ # 确保可以导入 aiecs
29
+ import os
30
+
31
+ sys.path.insert(
32
+ 0,
33
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))),
34
+ )
35
+
36
+
37
+ class SchemaQualityMetrics:
38
+ """Schema 质量指标"""
39
+
40
+ def __init__(self):
41
+ self.total_methods = 0
42
+ self.schemas_generated = 0
43
+ self.schemas_failed = 0
44
+ self.total_fields = 0
45
+ self.fields_with_meaningful_descriptions = 0
46
+ self.fields_with_types = 0
47
+ self.quality_issues = []
48
+
49
+ def add_method(self, has_schema: bool):
50
+ """添加方法统计"""
51
+ self.total_methods += 1
52
+ if has_schema:
53
+ self.schemas_generated += 1
54
+ else:
55
+ self.schemas_failed += 1
56
+
57
+ def add_field(self, has_type: bool, has_meaningful_desc: bool):
58
+ """添加字段统计"""
59
+ self.total_fields += 1
60
+ if has_type:
61
+ self.fields_with_types += 1
62
+ if has_meaningful_desc:
63
+ self.fields_with_meaningful_descriptions += 1
64
+
65
+ def add_issue(self, issue: str):
66
+ """添加质量问题"""
67
+ self.quality_issues.append(issue)
68
+
69
+ def get_scores(self) -> Dict[str, float]:
70
+ """计算质量分数"""
71
+ generation_rate = (
72
+ (self.schemas_generated / self.total_methods * 100) if self.total_methods > 0 else 0
73
+ )
74
+ description_rate = (
75
+ (self.fields_with_meaningful_descriptions / self.total_fields * 100)
76
+ if self.total_fields > 0
77
+ else 0
78
+ )
79
+ type_coverage = (
80
+ (self.fields_with_types / self.total_fields * 100) if self.total_fields > 0 else 0
81
+ )
82
+
83
+ return {
84
+ "generation_rate": generation_rate,
85
+ "description_quality": description_rate,
86
+ "type_coverage": type_coverage,
87
+ "overall_score": (generation_rate + description_rate + type_coverage) / 3,
88
+ }
89
+
90
+
91
+ def validate_schema_quality(
92
+ schema: Type[BaseModel], method: callable, method_name: str
93
+ ) -> List[str]:
94
+ """
95
+ 验证单个 Schema 的质量
96
+
97
+ Returns:
98
+ 质量问题列表(改进建议)
99
+ """
100
+ issues = []
101
+
102
+ # 1. 检查 Schema 描述
103
+ if not schema.__doc__ or schema.__doc__.strip() == f"Execute {method_name} operation":
104
+ issues.append("💡 在方法文档字符串的第一行添加有意义的描述")
105
+
106
+ # 2. 检查字段
107
+ if not schema.model_fields:
108
+ return issues
109
+
110
+ for field_name, field_info in schema.model_fields.items():
111
+ # 检查字段描述
112
+ description = field_info.description
113
+ if not description or description == f"Parameter {field_name}":
114
+ issues.append(f"💡 在文档字符串的 Args 部分为参数 '{field_name}' 添加描述")
115
+
116
+ return issues
117
+
118
+
119
+ def find_manual_schema(tool_class: Type, method_name: str) -> Optional[Type[BaseModel]]:
120
+ """
121
+ 查找手动定义的 Schema(与 langchain_adapter 逻辑一致)
122
+
123
+ Args:
124
+ tool_class: 工具类
125
+ method_name: 方法名
126
+
127
+ Returns:
128
+ 找到的 Schema 类,如果没有则返回 None
129
+ """
130
+ schemas = {}
131
+
132
+ # 1. 检查类级别的 schemas
133
+ for attr_name in dir(tool_class):
134
+ attr = getattr(tool_class, attr_name)
135
+ if (
136
+ isinstance(attr, type)
137
+ and issubclass(attr, BaseModel)
138
+ and attr.__name__.endswith("Schema")
139
+ ):
140
+ # 标准化:移除 'Schema' 后缀,转小写,移除下划线
141
+ schema_base_name = attr.__name__.replace("Schema", "")
142
+ normalized_name = schema_base_name.replace("_", "").lower()
143
+ schemas[normalized_name] = attr
144
+
145
+ # 2. 检查模块级别的 schemas
146
+ import inspect
147
+
148
+ tool_module = inspect.getmodule(tool_class)
149
+ if tool_module:
150
+ for attr_name in dir(tool_module):
151
+ if attr_name.startswith("_"):
152
+ continue
153
+ attr = getattr(tool_module, attr_name)
154
+ if (
155
+ isinstance(attr, type)
156
+ and issubclass(attr, BaseModel)
157
+ and attr.__name__.endswith("Schema")
158
+ ):
159
+ schema_base_name = attr.__name__.replace("Schema", "")
160
+ normalized_name = schema_base_name.replace("_", "").lower()
161
+ if normalized_name not in schemas:
162
+ schemas[normalized_name] = attr
163
+
164
+ # 标准化方法名:移除下划线并转小写
165
+ normalized_method_name = method_name.replace("_", "").lower()
166
+
167
+ # 查找匹配的 schema
168
+ return schemas.get(normalized_method_name)
169
+
170
+
171
+ def analyze_tool_schemas(tool_name: str, tool_class: Type) -> Dict[str, Any]:
172
+ """分析工具的 Schema 生成情况(支持手动定义和自动生成)"""
173
+
174
+ metrics = SchemaQualityMetrics()
175
+ methods_info = []
176
+
177
+ for method_name in dir(tool_class):
178
+ # 跳过私有方法和特殊方法
179
+ if method_name.startswith("_"):
180
+ continue
181
+
182
+ # 跳过基类方法
183
+ if method_name in ["run", "run_async", "run_batch"]:
184
+ continue
185
+
186
+ method = getattr(tool_class, method_name)
187
+
188
+ # 跳过非方法属性
189
+ if not callable(method) or isinstance(method, type):
190
+ continue
191
+
192
+ # 首先尝试查找手动定义的 Schema
193
+ manual_schema = find_manual_schema(tool_class, method_name)
194
+
195
+ if manual_schema:
196
+ schema = manual_schema
197
+ schema_type = "manual"
198
+ else:
199
+ # 如果没有手动 Schema,则自动生成
200
+ schema = generate_schema_from_method(method, method_name)
201
+ schema_type = "auto"
202
+
203
+ method_info = {
204
+ "name": method_name,
205
+ "schema": schema,
206
+ "schema_type": schema_type,
207
+ "issues": [],
208
+ }
209
+
210
+ if schema:
211
+ metrics.add_method(True)
212
+
213
+ # 验证质量
214
+ issues = validate_schema_quality(schema, method, method_name)
215
+ method_info["issues"] = issues
216
+
217
+ # 统计字段
218
+ for field_name, field_info in schema.model_fields.items():
219
+ has_type = field_info.annotation is not None
220
+ has_meaningful_desc = (
221
+ field_info.description and field_info.description != f"Parameter {field_name}"
222
+ )
223
+ metrics.add_field(has_type, has_meaningful_desc)
224
+
225
+ # 记录问题
226
+ for issue in issues:
227
+ metrics.add_issue(f"{tool_name}.{method_name}: {issue}")
228
+ else:
229
+ metrics.add_method(False)
230
+ method_info["issues"] = ["⚠️ 无法生成 Schema(可能是无参数方法)"]
231
+
232
+ methods_info.append(method_info)
233
+
234
+ return {"metrics": metrics, "methods": methods_info}
235
+
236
+
237
+ def print_tool_report(
238
+ tool_name: str,
239
+ result: Dict,
240
+ verbose: bool = False,
241
+ show_examples: bool = False,
242
+ ):
243
+ """打印工具报告"""
244
+
245
+ metrics = result["metrics"]
246
+ methods = result["methods"]
247
+ scores = metrics.get_scores()
248
+
249
+ # 统计手动和自动 schema
250
+ manual_schemas = [m for m in methods if m.get("schema_type") == "manual"]
251
+ auto_schemas = [m for m in methods if m.get("schema_type") == "auto"]
252
+
253
+ # 状态图标
254
+ overall = scores["overall_score"]
255
+ if overall >= 90:
256
+ status = "✅"
257
+ grade = "A (优秀)"
258
+ elif overall >= 80:
259
+ status = "⚠️"
260
+ grade = "B (良好)"
261
+ elif overall >= 70:
262
+ status = "⚠️"
263
+ grade = "C (中等)"
264
+ else:
265
+ status = "❌"
266
+ grade = "D (需改进)"
267
+
268
+ print(f"\n{status} {tool_name}")
269
+ print(f" 方法数: {metrics.total_methods}")
270
+ print(f" 成功生成 Schema: {metrics.schemas_generated} ({scores['generation_rate']:.1f}%)")
271
+ print(f" - 手动定义: {len(manual_schemas)} 个")
272
+ print(f" - 自动生成: {len(auto_schemas)} 个")
273
+ print(f" 描述质量: {scores['description_quality']:.1f}%")
274
+ print(f" 综合评分: {scores['overall_score']:.1f}% ({grade})")
275
+
276
+ # 显示需要改进的方法
277
+ methods_with_issues = [m for m in methods if m["issues"] and m["schema"]]
278
+
279
+ if methods_with_issues and (verbose or scores["description_quality"] < 80):
280
+ print(f"\n 需要改进的方法 ({len(methods_with_issues)} 个):")
281
+
282
+ for method_info in methods_with_issues[: 5 if not verbose else None]:
283
+ print(f"\n {method_info['name']}:")
284
+ for issue in method_info["issues"]:
285
+ print(f" {issue}")
286
+
287
+ if not verbose and len(methods_with_issues) > 5:
288
+ print(f"\n ... 还有 {len(methods_with_issues) - 5} 个方法需要改进")
289
+ print(" 使用 --verbose 查看全部")
290
+
291
+ # 显示示例 Schema
292
+ if show_examples:
293
+ methods_with_schema = [m for m in methods if m["schema"]]
294
+ if methods_with_schema:
295
+ print("\n 示例 Schema:")
296
+ for method_info in methods_with_schema[:2]:
297
+ schema = method_info["schema"]
298
+ schema_type_label = (
299
+ "🔧 手动定义" if method_info.get("schema_type") == "manual" else "🤖 自动生成"
300
+ )
301
+ print(f"\n {method_info['name']} → {schema.__name__} [{schema_type_label}]")
302
+ print(f" 描述: {schema.__doc__}")
303
+ print(" 字段:")
304
+ for field_name, field_info in list(schema.model_fields.items())[:3]:
305
+ required = "必需" if field_info.is_required() else "可选"
306
+ print(f" - {field_name}: {field_info.description} [{required}]")
307
+
308
+
309
+ def validate_schemas(
310
+ tool_names: Optional[List[str]] = None,
311
+ verbose: bool = False,
312
+ show_examples: bool = False,
313
+ ):
314
+ """
315
+ 验证工具的 Schema 质量
316
+
317
+ Args:
318
+ tool_names: 要验证的工具名称列表,None 表示验证所有工具
319
+ verbose: 是否显示详细信息
320
+ show_examples: 是否显示示例 Schema
321
+ """
322
+ print("=" * 100)
323
+ print("工具 Schema 质量验证器")
324
+ print("=" * 100)
325
+
326
+ discover_tools()
327
+
328
+ # 确定要验证的工具
329
+ if tool_names:
330
+ tools_to_check = {}
331
+ for name in tool_names:
332
+ if name in TOOL_CLASSES:
333
+ tools_to_check[name] = TOOL_CLASSES[name]
334
+ else:
335
+ print(f"\n❌ 工具 '{name}' 不存在")
336
+
337
+ if not tools_to_check:
338
+ print("\n没有找到要验证的工具")
339
+ return
340
+ else:
341
+ tools_to_check = TOOL_CLASSES
342
+
343
+ # 验证每个工具
344
+ all_results = {}
345
+ for tool_name in sorted(tools_to_check.keys()):
346
+ tool_class = tools_to_check[tool_name]
347
+ result = analyze_tool_schemas(tool_name, tool_class)
348
+ all_results[tool_name] = result
349
+
350
+ print_tool_report(tool_name, result, verbose, show_examples)
351
+
352
+ # 总体统计
353
+ if len(all_results) > 1:
354
+ total_methods = sum(r["metrics"].total_methods for r in all_results.values())
355
+ total_generated = sum(r["metrics"].schemas_generated for r in all_results.values())
356
+ total_fields = sum(r["metrics"].total_fields for r in all_results.values())
357
+ total_meaningful = sum(
358
+ r["metrics"].fields_with_meaningful_descriptions for r in all_results.values()
359
+ )
360
+
361
+ overall_generation = (total_generated / total_methods * 100) if total_methods > 0 else 0
362
+ overall_description = (total_meaningful / total_fields * 100) if total_fields > 0 else 0
363
+
364
+ print("\n" + "=" * 100)
365
+ print("总体统计:")
366
+ print(f" 方法数: {total_methods}")
367
+ print(f" Schema 生成率: {total_generated}/{total_methods} ({overall_generation:.1f}%)")
368
+ print(f" 描述质量: {overall_description:.1f}%")
369
+ print("=" * 100)
370
+
371
+ print("\n💡 改进建议:")
372
+ print(" 1. 在方法的文档字符串第一行添加简短描述")
373
+ print(" 2. 在 Args 部分为每个参数添加详细描述")
374
+ print(" 3. 使用 Google 或 NumPy 风格的文档字符串")
375
+ print("\n示例:")
376
+ print(" def filter(self, records: List[Dict], condition: str) -> List[Dict]:")
377
+ print(' """')
378
+ print(" Filter DataFrame based on a condition.")
379
+ print(" ")
380
+ print(" Args:")
381
+ print(" records: List of records to filter")
382
+ print(" condition: Filter condition (pandas query syntax)")
383
+ print(' """')
384
+
385
+
386
+ def main():
387
+ """命令行入口"""
388
+ import argparse
389
+
390
+ parser = argparse.ArgumentParser(
391
+ description="验证工具 Schema 的生成质量",
392
+ formatter_class=argparse.RawDescriptionHelpFormatter,
393
+ epilog="""
394
+ 示例:
395
+ # 验证所有工具
396
+ aiecs tools validate-schemas
397
+
398
+ # 验证特定工具
399
+ aiecs tools validate-schemas pandas
400
+
401
+ # 显示详细的改进建议
402
+ aiecs tools validate-schemas pandas --verbose
403
+
404
+ # 显示示例 Schema
405
+ aiecs tools validate-schemas pandas --show-examples
406
+ """,
407
+ )
408
+
409
+ parser.add_argument("tools", nargs="*", help="要验证的工具名称(不指定则验证所有工具)")
410
+
411
+ parser.add_argument("-v", "--verbose", action="store_true", help="显示详细的改进建议")
412
+
413
+ parser.add_argument("-e", "--show-examples", action="store_true", help="显示示例 Schema")
414
+
415
+ args = parser.parse_args()
416
+
417
+ tool_names = args.tools if args.tools else None
418
+ validate_schemas(tool_names, args.verbose, args.show_examples)
419
+
420
+
421
+ if __name__ == "__main__":
422
+ main()