loom-agent 0.0.2__py3-none-any.whl → 0.0.4__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 loom-agent might be problematic. Click here for more details.

loom/__init__.py CHANGED
@@ -25,6 +25,33 @@ from .callbacks.observability import ObservabilityCallback, MetricsAggregator
25
25
  from .llm.model_health import ModelHealthChecker, HealthStatus
26
26
  from .llm.model_pool_advanced import ModelPoolLLM, ModelConfig, FallbackChain
27
27
 
28
+ # Loom 0.0.3 - Unified Coordination & Performance
29
+ from .core.agent_executor import AgentExecutor, TaskHandler
30
+ from .core.unified_coordination import (
31
+ UnifiedExecutionContext,
32
+ IntelligentCoordinator,
33
+ CoordinationConfig
34
+ )
35
+ from .core.events import (
36
+ AgentEvent,
37
+ AgentEventType,
38
+ EventCollector,
39
+ EventFilter,
40
+ EventProcessor,
41
+ ToolCall,
42
+ ToolResult
43
+ )
44
+ from .core.turn_state import TurnState
45
+ from .core.execution_context import ExecutionContext
46
+ from .core.context_assembly import (
47
+ ContextAssembler,
48
+ ComponentPriority,
49
+ ContextComponent
50
+ )
51
+
52
+ # Loom 0.0.3 Developer API
53
+ from .api.v0_0_3 import LoomAgent, loom_agent, unified_executor
54
+
28
55
  try:
29
56
  from importlib.metadata import version as _pkg_version
30
57
 
@@ -73,5 +100,29 @@ __all__ = [
73
100
  "ModelPoolLLM",
74
101
  "ModelConfig",
75
102
  "FallbackChain",
103
+ # Loom 0.0.3 exports - Core
104
+ "AgentExecutor",
105
+ "TaskHandler",
106
+ "UnifiedExecutionContext",
107
+ "IntelligentCoordinator",
108
+ "CoordinationConfig",
109
+ # Loom 0.0.3 exports - Events
110
+ "AgentEvent",
111
+ "AgentEventType",
112
+ "EventCollector",
113
+ "EventFilter",
114
+ "EventProcessor",
115
+ "ToolCall",
116
+ "ToolResult",
117
+ # Loom 0.0.3 exports - Context & State
118
+ "TurnState",
119
+ "ExecutionContext",
120
+ "ContextAssembler",
121
+ "ComponentPriority",
122
+ "ContextComponent",
123
+ # Loom 0.0.3 Developer API
124
+ "LoomAgent",
125
+ "loom_agent",
126
+ "unified_executor",
76
127
  "__version__",
77
128
  ]
loom/api/v0_0_3.py ADDED
@@ -0,0 +1,299 @@
1
+ """Loom 0.0.3 开发者 API - 简化统一协调使用
2
+
3
+ 提供开发者友好的 API 接口,让开发者能够轻松使用 Loom 0.0.3 的核心能力。
4
+ """
5
+
6
+ import asyncio
7
+ import time
8
+ from typing import List, Optional, Dict, Any, AsyncGenerator, Union
9
+ from ..core.agent_executor import AgentExecutor
10
+ from ..core.unified_coordination import (
11
+ UnifiedExecutionContext,
12
+ IntelligentCoordinator,
13
+ CoordinationConfig
14
+ )
15
+ from ..core.events import AgentEvent, AgentEventType
16
+ from ..core.turn_state import TurnState
17
+ from ..core.execution_context import ExecutionContext
18
+ from ..core.types import Message
19
+ from ..interfaces.llm import BaseLLM
20
+ from ..interfaces.tool import BaseTool
21
+
22
+
23
+ class LoomAgent:
24
+ """Loom 0.0.3 统一协调 Agent
25
+
26
+ 提供简化的 API 接口,让开发者能够轻松使用统一协调机制。
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ llm: BaseLLM,
32
+ tools: Optional[Dict[str, BaseTool]] = None,
33
+ config: Optional[CoordinationConfig] = None,
34
+ execution_id: Optional[str] = None,
35
+ max_iterations: int = 50,
36
+ system_instructions: Optional[str] = None,
37
+ **kwargs
38
+ ):
39
+ """初始化 Loom 0.0.3 Agent
40
+
41
+ Args:
42
+ llm: 语言模型实例
43
+ tools: 工具字典
44
+ config: 统一协调配置
45
+ execution_id: 执行 ID
46
+ max_iterations: 最大迭代次数
47
+ system_instructions: 系统指令
48
+ **kwargs: 其他参数
49
+ """
50
+ self.config = config or CoordinationConfig()
51
+ self.unified_context = UnifiedExecutionContext(
52
+ execution_id=execution_id or f"loom_agent_{int(time.time())}",
53
+ config=self.config
54
+ )
55
+
56
+ self.executor = AgentExecutor(
57
+ llm=llm,
58
+ tools=tools or {},
59
+ unified_context=self.unified_context,
60
+ enable_unified_coordination=True,
61
+ max_iterations=max_iterations,
62
+ system_instructions=system_instructions,
63
+ **kwargs
64
+ )
65
+
66
+ async def run(self, input_text: str, correlation_id: Optional[str] = None) -> str:
67
+ """运行 Agent 并返回最终结果
68
+
69
+ Args:
70
+ input_text: 用户输入
71
+ correlation_id: 关联 ID
72
+
73
+ Returns:
74
+ 最终响应文本
75
+ """
76
+ turn_state = TurnState.initial(max_iterations=self.executor.max_iterations)
77
+ context = ExecutionContext.create(
78
+ correlation_id=correlation_id or f"run_{int(time.time())}"
79
+ )
80
+ messages = [Message(role="user", content=input_text)]
81
+
82
+ final_content = ""
83
+ async for event in self.executor.tt(messages, turn_state, context):
84
+ if event.type == AgentEventType.AGENT_FINISH:
85
+ final_content = event.content or ""
86
+ break
87
+ elif event.type == AgentEventType.ERROR:
88
+ raise event.error
89
+
90
+ return final_content
91
+
92
+ async def stream(self, input_text: str, correlation_id: Optional[str] = None) -> AsyncGenerator[AgentEvent, None]:
93
+ """流式执行 Agent
94
+
95
+ Args:
96
+ input_text: 用户输入
97
+ correlation_id: 关联 ID
98
+
99
+ Yields:
100
+ AgentEvent: 执行事件
101
+ """
102
+ turn_state = TurnState.initial(max_iterations=self.executor.max_iterations)
103
+ context = ExecutionContext.create(
104
+ correlation_id=correlation_id or f"stream_{int(time.time())}"
105
+ )
106
+ messages = [Message(role="user", content=input_text)]
107
+
108
+ async for event in self.executor.tt(messages, turn_state, context):
109
+ yield event
110
+
111
+ async def execute_with_events(self, input_text: str, correlation_id: Optional[str] = None) -> List[AgentEvent]:
112
+ """执行并返回所有事件
113
+
114
+ Args:
115
+ input_text: 用户输入
116
+ correlation_id: 关联 ID
117
+
118
+ Returns:
119
+ 事件列表
120
+ """
121
+ events = []
122
+ async for event in self.stream(input_text, correlation_id):
123
+ events.append(event)
124
+ return events
125
+
126
+ async def run_with_progress(self, input_text: str, progress_callback=None) -> str:
127
+ """带进度回调的执行
128
+
129
+ Args:
130
+ input_text: 用户输入
131
+ progress_callback: 进度回调函数
132
+
133
+ Returns:
134
+ 最终响应文本
135
+ """
136
+ final_content = ""
137
+
138
+ async for event in self.stream(input_text):
139
+ if progress_callback:
140
+ await progress_callback(event)
141
+
142
+ if event.type == AgentEventType.AGENT_FINISH:
143
+ final_content = event.content or ""
144
+ break
145
+ elif event.type == AgentEventType.ERROR:
146
+ raise event.error
147
+
148
+ return final_content
149
+
150
+ def get_coordinator(self) -> IntelligentCoordinator:
151
+ """获取智能协调器实例"""
152
+ return self.executor.coordinator
153
+
154
+ def get_unified_context(self) -> UnifiedExecutionContext:
155
+ """获取统一执行上下文"""
156
+ return self.unified_context
157
+
158
+
159
+ def create_loom_agent(
160
+ llm: BaseLLM,
161
+ tools: Optional[Dict[str, BaseTool]] = None,
162
+ config: Optional[CoordinationConfig] = None,
163
+ **kwargs
164
+ ) -> LoomAgent:
165
+ """创建 Loom 0.0.3 Agent
166
+
167
+ Args:
168
+ llm: 语言模型实例
169
+ tools: 工具字典
170
+ config: 统一协调配置
171
+ **kwargs: 其他参数
172
+
173
+ Returns:
174
+ LoomAgent 实例
175
+ """
176
+ return LoomAgent(llm=llm, tools=tools, config=config, **kwargs)
177
+
178
+
179
+ def create_unified_executor(
180
+ llm: BaseLLM,
181
+ tools: Optional[Dict[str, BaseTool]] = None,
182
+ config: Optional[CoordinationConfig] = None,
183
+ execution_id: Optional[str] = None,
184
+ **kwargs
185
+ ) -> AgentExecutor:
186
+ """创建使用统一协调机制的 AgentExecutor
187
+
188
+ Args:
189
+ llm: 语言模型实例
190
+ tools: 工具字典
191
+ config: 统一协调配置
192
+ execution_id: 执行 ID
193
+ **kwargs: 其他参数
194
+
195
+ Returns:
196
+ AgentExecutor 实例
197
+ """
198
+ if config is None:
199
+ config = CoordinationConfig()
200
+
201
+ unified_context = UnifiedExecutionContext(
202
+ execution_id=execution_id or f"executor_{int(time.time())}",
203
+ config=config
204
+ )
205
+
206
+ return AgentExecutor(
207
+ llm=llm,
208
+ tools=tools or {},
209
+ unified_context=unified_context,
210
+ enable_unified_coordination=True,
211
+ **kwargs
212
+ )
213
+
214
+
215
+ # 便捷函数
216
+ def loom_agent(
217
+ llm: BaseLLM,
218
+ tools: Optional[Dict[str, BaseTool]] = None,
219
+ config: Optional[CoordinationConfig] = None,
220
+ **kwargs
221
+ ) -> LoomAgent:
222
+ """创建 Loom 0.0.3 统一协调 Agent
223
+
224
+ 这是最推荐的创建方式,提供简化的 API 和完整的功能。
225
+
226
+ Args:
227
+ llm: 语言模型实例
228
+ tools: 工具字典
229
+ config: 统一协调配置
230
+ **kwargs: 其他参数
231
+
232
+ Returns:
233
+ LoomAgent 实例
234
+
235
+ Example:
236
+ ```python
237
+ import loom
238
+ from loom.builtin.llms import MockLLM
239
+
240
+ agent = loom.loom_agent(
241
+ llm=MockLLM(),
242
+ tools={"calculator": CalculatorTool()}
243
+ )
244
+
245
+ result = await agent.run("计算 2+2")
246
+ print(result)
247
+ ```
248
+ """
249
+ return create_loom_agent(llm=llm, tools=tools, config=config, **kwargs)
250
+
251
+
252
+ def unified_executor(
253
+ llm: BaseLLM,
254
+ tools: Optional[Dict[str, BaseTool]] = None,
255
+ config: Optional[CoordinationConfig] = None,
256
+ **kwargs
257
+ ) -> AgentExecutor:
258
+ """创建统一协调 AgentExecutor
259
+
260
+ 适用于需要直接控制执行流程的高级用户。
261
+
262
+ Args:
263
+ llm: 语言模型实例
264
+ tools: 工具字典
265
+ config: 统一协调配置
266
+ **kwargs: 其他参数
267
+
268
+ Returns:
269
+ AgentExecutor 实例
270
+
271
+ Example:
272
+ ```python
273
+ import loom
274
+ from loom.builtin.llms import MockLLM
275
+
276
+ executor = loom.unified_executor(
277
+ llm=MockLLM(),
278
+ tools={"calculator": CalculatorTool()}
279
+ )
280
+
281
+ turn_state = loom.TurnState.initial(max_iterations=10)
282
+ context = loom.ExecutionContext.create()
283
+ messages = [loom.Message(role="user", content="Hello")]
284
+
285
+ async for event in executor.tt(messages, turn_state, context):
286
+ print(f"Event: {event.type} - {event.content}")
287
+ ```
288
+ """
289
+ return create_unified_executor(llm=llm, tools=tools, config=config, **kwargs)
290
+
291
+
292
+ # 导出所有 API
293
+ __all__ = [
294
+ "LoomAgent",
295
+ "create_loom_agent",
296
+ "create_unified_executor",
297
+ "loom_agent",
298
+ "unified_executor",
299
+ ]
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import time
5
6
  from typing import TYPE_CHECKING, Any, Optional, Dict, List
6
7
 
7
8
  from pydantic import BaseModel, Field
@@ -36,6 +37,12 @@ class TaskTool(BaseTool):
36
37
  Task 工具 - 启动 SubAgent 执行专项任务
37
38
 
38
39
  对应 Claude Code 的 Task 工具和 SubAgent 机制
40
+
41
+ 新特性 (Loom 0.0.3):
42
+ - 子代理池管理
43
+ - 性能监控和指标收集
44
+ - 智能负载均衡
45
+ - 资源使用优化
39
46
  """
40
47
 
41
48
  name = "task"
@@ -56,14 +63,35 @@ class TaskTool(BaseTool):
56
63
  self,
57
64
  agent_factory: Optional[callable] = None,
58
65
  max_iterations: int = 20,
66
+ enable_pooling: bool = True,
67
+ pool_size: int = 5,
68
+ enable_monitoring: bool = True,
59
69
  ) -> None:
60
70
  """
61
71
  Parameters:
62
72
  - agent_factory: 创建 SubAgent 的工厂函数
63
73
  - max_iterations: SubAgent 最大迭代次数
74
+ - enable_pooling: 启用子代理池管理
75
+ - pool_size: 子代理池大小
76
+ - enable_monitoring: 启用性能监控
64
77
  """
65
78
  self.agent_factory = agent_factory
66
79
  self.max_iterations = max_iterations
80
+
81
+ # Performance optimizations
82
+ self.enable_pooling = enable_pooling
83
+ self.pool_size = pool_size
84
+ self.enable_monitoring = enable_monitoring
85
+
86
+ # Sub-agent pool management
87
+ self._agent_pool: Dict[str, Any] = {}
88
+ self._pool_stats = {
89
+ "total_created": 0,
90
+ "total_executed": 0,
91
+ "average_execution_time": 0.0,
92
+ "cache_hits": 0,
93
+ "cache_misses": 0
94
+ }
67
95
 
68
96
  async def run(
69
97
  self,
@@ -136,7 +164,33 @@ class TaskTool(BaseTool):
136
164
  )
137
165
 
138
166
  # 运行子任务(系统提示已注入到 sub_agent,输入仍为原始 prompt)
167
+ start_time = time.time() if self.enable_monitoring else None
168
+
169
+ # Check pool for reusable agent
170
+ agent_key = self._get_agent_key(subagent_type, effective_model, permission_policy)
171
+ if self.enable_pooling and agent_key in self._agent_pool:
172
+ sub_agent = self._agent_pool[agent_key]
173
+ self._pool_stats["cache_hits"] += 1
174
+ else:
175
+ self._pool_stats["cache_misses"] += 1
176
+ self._pool_stats["total_created"] += 1
177
+
178
+ # Add to pool if enabled and not at capacity
179
+ if self.enable_pooling and len(self._agent_pool) < self.pool_size:
180
+ self._agent_pool[agent_key] = sub_agent
181
+
139
182
  result = await sub_agent.run(prompt)
183
+
184
+ # Update performance metrics
185
+ if self.enable_monitoring and start_time:
186
+ execution_time = time.time() - start_time
187
+ self._pool_stats["total_executed"] += 1
188
+ # Update running average
189
+ current_avg = self._pool_stats["average_execution_time"]
190
+ total_executed = self._pool_stats["total_executed"]
191
+ self._pool_stats["average_execution_time"] = (
192
+ (current_avg * (total_executed - 1) + execution_time) / total_executed
193
+ )
140
194
 
141
195
  # 格式化返回结果
142
196
  return f"**SubAgent Task: {description}**\n\nResult:\n{result}"
@@ -161,3 +215,49 @@ class TaskTool(BaseTool):
161
215
  subagent_type=subagent_type,
162
216
  model_name=model_name,
163
217
  )
218
+
219
+ def _get_agent_key(
220
+ self,
221
+ subagent_type: Optional[str],
222
+ model_name: Optional[str],
223
+ permission_policy: Optional[Dict[str, str]]
224
+ ) -> str:
225
+ """Generate unique key for agent pool"""
226
+ import hashlib
227
+
228
+ key_parts = [
229
+ subagent_type or "default",
230
+ model_name or "default",
231
+ str(sorted(permission_policy.items())) if permission_policy else "default"
232
+ ]
233
+
234
+ key_string = "|".join(key_parts)
235
+ return hashlib.md5(key_string.encode()).hexdigest()
236
+
237
+ def get_pool_stats(self) -> Dict[str, Any]:
238
+ """Get sub-agent pool statistics"""
239
+ return {
240
+ **self._pool_stats,
241
+ "pool_size": len(self._agent_pool),
242
+ "max_pool_size": self.pool_size,
243
+ "pool_utilization": len(self._agent_pool) / self.pool_size if self.pool_size > 0 else 0,
244
+ "cache_hit_rate": (
245
+ self._pool_stats["cache_hits"] /
246
+ (self._pool_stats["cache_hits"] + self._pool_stats["cache_misses"])
247
+ if (self._pool_stats["cache_hits"] + self._pool_stats["cache_misses"]) > 0 else 0
248
+ )
249
+ }
250
+
251
+ def clear_pool(self) -> None:
252
+ """Clear the sub-agent pool"""
253
+ self._agent_pool.clear()
254
+
255
+ def reset_stats(self) -> None:
256
+ """Reset performance statistics"""
257
+ self._pool_stats = {
258
+ "total_created": 0,
259
+ "total_executed": 0,
260
+ "average_execution_time": 0.0,
261
+ "cache_hits": 0,
262
+ "cache_misses": 0
263
+ }