aiforge-engine 0.0.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 (153) hide show
  1. aiforge/__init__.py +64 -0
  2. aiforge/adapters/__init__.py +5 -0
  3. aiforge/adapters/input/__init__.py +0 -0
  4. aiforge/adapters/input/cli_input_adapter.py +45 -0
  5. aiforge/adapters/input/gui_input_adapter.py +40 -0
  6. aiforge/adapters/input/input_adapter.py +67 -0
  7. aiforge/adapters/input/input_adapter_manager.py +101 -0
  8. aiforge/adapters/input/input_processors.py +48 -0
  9. aiforge/adapters/input/mobile_input_adapter.py +48 -0
  10. aiforge/adapters/input/voice_input_adapter.py +44 -0
  11. aiforge/adapters/input/web_input_adapter.py +48 -0
  12. aiforge/adapters/output/__init__.py +5 -0
  13. aiforge/adapters/output/ai_ui_adapter.py +120 -0
  14. aiforge/adapters/output/enhanced_hybrid_adapter.py +82 -0
  15. aiforge/adapters/output/learning_Interface.py +190 -0
  16. aiforge/adapters/output/rule_based_adapter.py +464 -0
  17. aiforge/adapters/output/task_type_detector.py +143 -0
  18. aiforge/adapters/output/ui_type_recommender.py +72 -0
  19. aiforge/api/__init__.py +0 -0
  20. aiforge/api/middleware/auth.py +0 -0
  21. aiforge/api/middleware/rate_limit.py +0 -0
  22. aiforge/api/routes/execution.py +0 -0
  23. aiforge/api/routes/llm.py +0 -0
  24. aiforge/api/routes/tasks.py +0 -0
  25. aiforge/api/server.py +0 -0
  26. aiforge/cache/__init__.py +3 -0
  27. aiforge/cache/action_matcher.py +318 -0
  28. aiforge/cache/code_cache.py +369 -0
  29. aiforge/cache/dynamic_task_type_manager.py +143 -0
  30. aiforge/cache/semantic_cache.py +839 -0
  31. aiforge/cli/__init__.py +0 -0
  32. aiforge/cli/cli.py +87 -0
  33. aiforge/cli/commands/manager.py +73 -0
  34. aiforge/cli/wizard.py +116 -0
  35. aiforge/config/__init__.py +3 -0
  36. aiforge/config/config.py +185 -0
  37. aiforge/config/config_sync.py +0 -0
  38. aiforge/config/default.toml +97 -0
  39. aiforge/config/extension_config.py +46 -0
  40. aiforge/config/extensions.toml +45 -0
  41. aiforge/config/remote_config.py +20 -0
  42. aiforge/core/__init__.py +9 -0
  43. aiforge/core/engine.py +149 -0
  44. aiforge/core/helpers/__init__.py +3 -0
  45. aiforge/core/helpers/cache_helper.py +53 -0
  46. aiforge/core/managers/__init__.py +4 -0
  47. aiforge/core/managers/config_manager.py +75 -0
  48. aiforge/core/managers/execution_manager.py +530 -0
  49. aiforge/core/managers/search_manager.py +402 -0
  50. aiforge/core/orchestrator.py +301 -0
  51. aiforge/core/prompt.py +345 -0
  52. aiforge/core/runner.py +154 -0
  53. aiforge/core/task/__init__.py +5 -0
  54. aiforge/core/task/executor.py +271 -0
  55. aiforge/core/task/manager.py +62 -0
  56. aiforge/core/task/task.py +147 -0
  57. aiforge/deployment/__init__.py +0 -0
  58. aiforge/deployment/cloud/aws_deploy.py +0 -0
  59. aiforge/deployment/cloud/azure_deploy.py +0 -0
  60. aiforge/deployment/docker/Dockerfile +0 -0
  61. aiforge/deployment/docker/docker-compose.yml +0 -0
  62. aiforge/deployment/kubernetes/deployment.yaml +0 -0
  63. aiforge/deployment/kubernetes/service.yaml +0 -0
  64. aiforge/enterprise/__init__.py +0 -0
  65. aiforge/enterprise/audit/audit_logger.py +0 -0
  66. aiforge/enterprise/audit/compliance_checker.py +0 -0
  67. aiforge/enterprise/auth/permission_manager.py +0 -0
  68. aiforge/enterprise/auth/user_manager.py +0 -0
  69. aiforge/enterprise/monitoring/alert_manager.py +0 -0
  70. aiforge/enterprise/monitoring/metrics_collector.py +0 -0
  71. aiforge/execution/__init__.py +16 -0
  72. aiforge/execution/analyzer.py +297 -0
  73. aiforge/execution/code_blocks.py +88 -0
  74. aiforge/execution/engine.py +667 -0
  75. aiforge/execution/executor_interface.py +16 -0
  76. aiforge/execution/result_formatter.py +81 -0
  77. aiforge/execution/result_processor.py +289 -0
  78. aiforge/execution/runtimes/__init__.py +0 -0
  79. aiforge/execution/runtimes/javascript_runtime.py +0 -0
  80. aiforge/execution/runtimes/python_runtime.py +0 -0
  81. aiforge/execution/runtimes/shell_runtime.py +0 -0
  82. aiforge/execution/unified_executor.py +28 -0
  83. aiforge/extensions/__init__.py +0 -0
  84. aiforge/extensions/extension_manager.py +48 -0
  85. aiforge/extensions/loader.py +115 -0
  86. aiforge/extensions/marketplace.py +23 -0
  87. aiforge/extensions/plugin_installer.py +0 -0
  88. aiforge/extensions/template_extension.py +90 -0
  89. aiforge/instruction/__init__.py +11 -0
  90. aiforge/instruction/analyzer.py +539 -0
  91. aiforge/instruction/classifier.py +268 -0
  92. aiforge/instruction/extractor.py +253 -0
  93. aiforge/instruction/parser.py +47 -0
  94. aiforge/llm/__init__.py +8 -0
  95. aiforge/llm/conversation_manager.py +115 -0
  96. aiforge/llm/llm_client.py +240 -0
  97. aiforge/llm/llm_manager.py +150 -0
  98. aiforge/llm/providers/__init__.py +0 -0
  99. aiforge/llm/providers/deepseek_client.py +0 -0
  100. aiforge/llm/providers/ollama_client.py +0 -0
  101. aiforge/llm/providers/openai_client.py +0 -0
  102. aiforge/models/__init__.py +0 -0
  103. aiforge/models/model_manager.py +141 -0
  104. aiforge/multimodal/__init__.py +0 -0
  105. aiforge/multimodal/audio/speech_to_text.py +0 -0
  106. aiforge/multimodal/audio/text_to_speech.py +0 -0
  107. aiforge/multimodal/document/pdf_parser.py +0 -0
  108. aiforge/multimodal/document/word_parser.py +0 -0
  109. aiforge/multimodal/vision/image_processor.py +0 -0
  110. aiforge/multimodal/vision/video_processor.py +0 -0
  111. aiforge/optimization/code_optimizer.py +163 -0
  112. aiforge/optimization/feedback_optimizer.py +42 -0
  113. aiforge/plugins/__init__.py +0 -0
  114. aiforge/plugins/builtin/data_analysis.py +0 -0
  115. aiforge/plugins/builtin/file_processing.py +0 -0
  116. aiforge/plugins/builtin/web_scraping.py +0 -0
  117. aiforge/plugins/plugin_interface.py +0 -0
  118. aiforge/plugins/plugin_manager.py +0 -0
  119. aiforge/strategies/__init__.py +41 -0
  120. aiforge/strategies/execution_strategy.py +106 -0
  121. aiforge/strategies/execution_strategy_manager.py +44 -0
  122. aiforge/strategies/parameter_mapping_service.py +895 -0
  123. aiforge/strategies/search_template_strategy.py +108 -0
  124. aiforge/strategies/semantic_field_strategy.py +257 -0
  125. aiforge/strategies/strategy/__init__.py +0 -0
  126. aiforge/strategies/strategy/class_instantiation.py +68 -0
  127. aiforge/strategies/strategy/direct_result.py +33 -0
  128. aiforge/strategies/strategy/file_operation.py +832 -0
  129. aiforge/strategies/strategy/file_operation_safety.py +317 -0
  130. aiforge/strategies/strategy/parameterized_function.py +168 -0
  131. aiforge/strategies/validation_strategy.py +125 -0
  132. aiforge/templates/__init__.py +9 -0
  133. aiforge/templates/builtin/automation.json +0 -0
  134. aiforge/templates/builtin/data_analysis.json +0 -0
  135. aiforge/templates/builtin/web_api.json +0 -0
  136. aiforge/templates/search_template.py +1311 -0
  137. aiforge/templates/template_manager.py +331 -0
  138. aiforge/utils/__init__.py +0 -0
  139. aiforge/utils/helpers.py +0 -0
  140. aiforge/utils/sentence_transformers_downloader.py +44 -0
  141. aiforge/utils/utils.py +290 -0
  142. aiforge/validation/code_validator.py +33 -0
  143. aiforge/validation/result_validator.py +260 -0
  144. aiforge/workflow/__init__.py +0 -0
  145. aiforge/workflow/nodes/data_node.py +0 -0
  146. aiforge/workflow/nodes/execution_node.py +0 -0
  147. aiforge/workflow/nodes/llm_node.py +0 -0
  148. aiforge/workflow/workflow_designer.py +0 -0
  149. aiforge/workflow/workflow_engine.py +0 -0
  150. aiforge_engine-0.0.1.dist-info/METADATA +11 -0
  151. aiforge_engine-0.0.1.dist-info/RECORD +153 -0
  152. aiforge_engine-0.0.1.dist-info/WHEEL +4 -0
  153. aiforge_engine-0.0.1.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,82 @@
1
+ from typing import Dict, Any, List, Tuple
2
+ from .rule_based_adapter import RuleBasedAdapter
3
+ from .ai_ui_adapter import AIUIAdapter
4
+ from .task_type_detector import TaskTypeDetector
5
+ from .ui_type_recommender import UITypeRecommender
6
+ from ...llm.llm_client import AIForgeLLMClient
7
+ from .learning_Interface import LearningInterface
8
+
9
+
10
+ class EnhancedHybridUIAdapter:
11
+ """增强的混合UI适配器"""
12
+
13
+ def __init__(self, llm_client: AIForgeLLMClient):
14
+ self.rule_based_adapter = RuleBasedAdapter()
15
+ self.ai_adapter = AIUIAdapter(llm_client)
16
+ self.task_detector = TaskTypeDetector()
17
+ self.ui_recommender = UITypeRecommender()
18
+
19
+ # 为阶段3预留的学习接口
20
+ self.learning_interface = LearningInterface()
21
+
22
+ def adapt_data(
23
+ self, result: Dict[str, Any], ui_type: str = None, context: str = "web"
24
+ ) -> Dict[str, Any]:
25
+ """智能适配数据为UI格式"""
26
+ data = result.get("data", {})
27
+
28
+ # 1. 智能检测任务类型(如果metadata中没有)
29
+ task_type = result.get("metadata", {}).get("task_type")
30
+ if not task_type:
31
+ task_type = self.task_detector.detect_from_data(data)
32
+
33
+ # 2. 智能推荐UI类型(如果未指定)
34
+ if not ui_type:
35
+ recommendations = self.ui_recommender.recommend_ui_types(data, task_type, context)
36
+ ui_type = recommendations[0][0] if recommendations else "web_card"
37
+
38
+ # 记录适配请求
39
+ self.learning_interface.record_adaptation_request(data, task_type, ui_type)
40
+
41
+ # 3. 优先使用规则适配
42
+ if self.rule_based_adapter.can_handle(task_type, ui_type):
43
+ adapted_result = self.rule_based_adapter.adapt(data, task_type, ui_type)
44
+ adapted_result["adaptation_method"] = "rule_based"
45
+ adapted_result["task_type"] = task_type
46
+
47
+ # 记录规则适配结果
48
+ self.learning_interface.record_rule_adaptation(task_type, ui_type, adapted_result)
49
+
50
+ return adapted_result
51
+
52
+ # 4. 回退到AI适配
53
+ adapted_result = self.ai_adapter.adapt_for_display(data, ui_type)
54
+ adapted_result["adaptation_method"] = "ai_based"
55
+ adapted_result["task_type"] = task_type
56
+
57
+ # 记录AI适配结果
58
+ self.learning_interface.record_ai_adaptation(task_type, ui_type, data, adapted_result)
59
+
60
+ return adapted_result
61
+
62
+ def get_supported_combinations(self) -> Dict[str, List[str]]:
63
+ """获取所有支持的任务类型和UI类型组合"""
64
+ return self.rule_based_adapter.get_supported_combinations()
65
+
66
+ def recommend_ui_types(
67
+ self, result: Dict[str, Any], context: str = "web"
68
+ ) -> List[Tuple[str, float]]:
69
+ """为结果推荐最适合的UI类型"""
70
+ data = result.get("data", {})
71
+ task_type = result.get("metadata", {}).get("task_type")
72
+
73
+ if not task_type:
74
+ task_type = self.task_detector.detect_from_data(data)
75
+
76
+ return self.ui_recommender.recommend_ui_types(data, task_type, context)
77
+
78
+ def get_adaptation_stats(self) -> Dict[str, Any]:
79
+ """获取适配统计信息"""
80
+ stats = self.learning_interface.get_stats()
81
+ stats["supported_combinations"] = self.get_supported_combinations()
82
+ return stats
@@ -0,0 +1,190 @@
1
+ from typing import Dict, Any
2
+
3
+
4
+ class LearningInterface:
5
+ """学习优化接口"""
6
+
7
+ def __init__(self):
8
+ self.adaptation_history = []
9
+ self.rule_usage_stats = {}
10
+ self.ai_usage_stats = {}
11
+ self.user_feedback = []
12
+ self.performance_metrics = {}
13
+
14
+ def record_adaptation_request(self, data: Dict[str, Any], task_type: str, ui_type: str):
15
+ """记录适配请求"""
16
+ import time
17
+
18
+ self.adaptation_history.append(
19
+ {
20
+ "timestamp": time.time(),
21
+ "task_type": task_type,
22
+ "ui_type": ui_type,
23
+ "data_structure": self._analyze_data_structure(data),
24
+ "data_size": len(str(data)),
25
+ }
26
+ )
27
+
28
+ def record_rule_adaptation(self, task_type: str, ui_type: str, result: Dict[str, Any]):
29
+ """记录规则适配结果"""
30
+ import time
31
+
32
+ key = f"{task_type}_{ui_type}"
33
+
34
+ if key not in self.rule_usage_stats:
35
+ self.rule_usage_stats[key] = {
36
+ "count": 0,
37
+ "success_rate": 1.0,
38
+ "avg_response_time": 0.0,
39
+ "last_used": time.time(),
40
+ }
41
+
42
+ self.rule_usage_stats[key]["count"] += 1
43
+ self.rule_usage_stats[key]["last_used"] = time.time()
44
+
45
+ # 记录性能指标
46
+ self._record_performance("rule_based", key, 0.001) # 规则适配通常很快
47
+
48
+ def record_ai_adaptation(
49
+ self, task_type: str, ui_type: str, data: Dict[str, Any], result: Dict[str, Any]
50
+ ):
51
+ """记录AI适配结果"""
52
+ import time
53
+
54
+ key = f"{task_type}_{ui_type}"
55
+
56
+ if key not in self.ai_usage_stats:
57
+ self.ai_usage_stats[key] = {
58
+ "count": 0,
59
+ "patterns": [],
60
+ "avg_response_time": 0.0,
61
+ "success_rate": 0.8, # AI适配的默认成功率
62
+ }
63
+
64
+ self.ai_usage_stats[key]["count"] += 1
65
+ self.ai_usage_stats[key]["patterns"].append(
66
+ {
67
+ "data_pattern": self._analyze_data_structure(data),
68
+ "result_pattern": self._analyze_result_structure(result),
69
+ "timestamp": time.time(),
70
+ }
71
+ )
72
+
73
+ # 记录性能指标(AI适配通常较慢)
74
+ self._record_performance("ai_based", key, 2.5)
75
+
76
+ def record_user_feedback(self, adaptation_id: str, feedback: Dict[str, Any]):
77
+ """记录用户反馈"""
78
+ import time
79
+
80
+ self.user_feedback.append(
81
+ {
82
+ "adaptation_id": adaptation_id,
83
+ "feedback": feedback,
84
+ "timestamp": time.time(),
85
+ "rating": feedback.get("rating", 3), # 1-5分评分
86
+ "comments": feedback.get("comments", ""),
87
+ }
88
+ )
89
+
90
+ def _record_performance(self, method: str, key: str, response_time: float):
91
+ """记录性能指标"""
92
+ if method not in self.performance_metrics:
93
+ self.performance_metrics[method] = {}
94
+
95
+ if key not in self.performance_metrics[method]:
96
+ self.performance_metrics[method][key] = {"total_time": 0.0, "count": 0, "avg_time": 0.0}
97
+
98
+ metrics = self.performance_metrics[method][key]
99
+ metrics["total_time"] += response_time
100
+ metrics["count"] += 1
101
+ metrics["avg_time"] = metrics["total_time"] / metrics["count"]
102
+
103
+ def get_stats(self) -> Dict[str, Any]:
104
+ """获取完整统计信息"""
105
+ return {
106
+ "total_adaptations": len(self.adaptation_history),
107
+ "rule_usage": self.rule_usage_stats,
108
+ "ai_usage": self.ai_usage_stats,
109
+ "feedback_count": len(self.user_feedback),
110
+ "performance_metrics": self.performance_metrics,
111
+ "avg_user_rating": self._calculate_avg_rating(),
112
+ "adaptation_trends": self._analyze_trends(),
113
+ }
114
+
115
+ def _calculate_avg_rating(self) -> float:
116
+ """计算平均用户评分"""
117
+ if not self.user_feedback:
118
+ return 0.0
119
+
120
+ total_rating = sum(feedback["rating"] for feedback in self.user_feedback)
121
+ return total_rating / len(self.user_feedback)
122
+
123
+ def _analyze_trends(self) -> Dict[str, Any]:
124
+ """分析适配趋势"""
125
+ if len(self.adaptation_history) < 2:
126
+ return {}
127
+
128
+ recent_adaptations = self.adaptation_history[-10:] # 最近10次
129
+
130
+ task_type_counts = {}
131
+ ui_type_counts = {}
132
+
133
+ for adaptation in recent_adaptations:
134
+ task_type = adaptation["task_type"]
135
+ ui_type = adaptation["ui_type"]
136
+
137
+ task_type_counts[task_type] = task_type_counts.get(task_type, 0) + 1
138
+ ui_type_counts[ui_type] = ui_type_counts.get(ui_type, 0) + 1
139
+
140
+ return {
141
+ "popular_task_types": sorted(
142
+ task_type_counts.items(), key=lambda x: x[1], reverse=True
143
+ ),
144
+ "popular_ui_types": sorted(ui_type_counts.items(), key=lambda x: x[1], reverse=True),
145
+ "rule_vs_ai_ratio": self._calculate_method_ratio(),
146
+ }
147
+
148
+ def _calculate_method_ratio(self) -> Dict[str, float]:
149
+ """计算规则适配vs AI适配的比例"""
150
+ total_rule = sum(stats["count"] for stats in self.rule_usage_stats.values())
151
+ total_ai = sum(stats["count"] for stats in self.ai_usage_stats.values())
152
+ total = total_rule + total_ai
153
+
154
+ if total == 0:
155
+ return {"rule_based": 0.0, "ai_based": 0.0}
156
+
157
+ return {"rule_based": total_rule / total, "ai_based": total_ai / total}
158
+
159
+ def _analyze_data_structure(self, data: Dict[str, Any]) -> Dict[str, Any]:
160
+ """分析数据结构模式"""
161
+ return {
162
+ "keys": list(data.keys()) if isinstance(data, dict) else [],
163
+ "types": (
164
+ {k: type(v).__name__ for k, v in data.items()} if isinstance(data, dict) else {}
165
+ ),
166
+ "depth": self._calculate_depth(data),
167
+ "has_lists": (
168
+ any(isinstance(v, list) for v in data.values()) if isinstance(data, dict) else False
169
+ ),
170
+ "has_nested_dicts": (
171
+ any(isinstance(v, dict) for v in data.values()) if isinstance(data, dict) else False
172
+ ),
173
+ }
174
+
175
+ def _analyze_result_structure(self, result: Dict[str, Any]) -> Dict[str, Any]:
176
+ """分析结果结构模式"""
177
+ return {
178
+ "display_items_count": len(result.get("display_items", [])),
179
+ "layout_type": result.get("layout_hints", {}).get("layout_type", ""),
180
+ "actions_count": len(result.get("actions", [])),
181
+ "has_summary": bool(result.get("summary_text")),
182
+ }
183
+
184
+ def _calculate_depth(self, obj, depth=0):
185
+ """计算数据结构深度"""
186
+ if isinstance(obj, dict):
187
+ return max([self._calculate_depth(v, depth + 1) for v in obj.values()], default=depth)
188
+ elif isinstance(obj, list) and obj:
189
+ return max([self._calculate_depth(item, depth + 1) for item in obj], default=depth)
190
+ return depth