File size: 8,252 Bytes
3193174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
"""
Execution components for running agents on a graph.

Provides both simple sequential execution and advanced adaptive execution
with dynamic topology, pruning, fallback and parallel execution.

Features:
- Typed errors and error policies
- Budget tracking (tokens, requests, time)
- Structured execution logging
- Parallel execution with retries
- Integrated agent memory (working/long-term)
- Shared memory pool between agents
- **LangGraph-like streaming execution** (stream/astream)
- **Multi-model support** (per-agent LLM configuration)

Example (simple batch):
    from execution import MACPRunner

    runner = MACPRunner(llm_caller=my_llm)
    result = runner.run_round(graph)

Example (streaming - like LangGraph's stream()):
    from execution import (
        MACPRunner, StreamEventType, format_event
    )

    runner = MACPRunner(llm_caller=my_llm)

    # Sync streaming
    for event in runner.stream(graph):
        if event.event_type == StreamEventType.AGENT_OUTPUT:
            print(f"{event.agent_id}: {event.content}")
        elif event.event_type == StreamEventType.TOKEN:
            print(event.token, end="", flush=True)

    # Async streaming
    async for event in runner.astream(graph):
        print(format_event(event))

Example (token-level streaming):
    from execution import MACPRunner, RunnerConfig

    config = RunnerConfig(enable_token_streaming=True)
    runner = MACPRunner(
        streaming_llm_caller=my_streaming_llm,  # yields tokens
        config=config
    )

    for event in runner.stream(graph):
        if event.event_type == StreamEventType.TOKEN:
            print(event.token, end="", flush=True)

Example (with budgets and logging):
    from execution import (
        MACPRunner, RunnerConfig, BudgetConfig, ErrorPolicy
    )

    config = RunnerConfig(
        adaptive=True,
        budget_config=BudgetConfig(
            total_token_limit=10000,
            max_prompt_length=4000,
        ),
        enable_logging=True,
    )
    runner = MACPRunner(llm_caller=my_llm, config=config)
    result = runner.run_round(graph)
    print(result.metrics.to_dict())

Example (with memory):
    from execution import (
        MACPRunner, RunnerConfig, MemoryConfig
    )

    config = RunnerConfig(
        enable_memory=True,
        memory_config=MemoryConfig(
            working_max_entries=10,
            long_term_max_entries=50,
        ),
        memory_context_limit=3,  # include last 3 entries in prompt
    )
    runner = MACPRunner(llm_caller=my_llm, config=config)
    result = runner.run_round(graph)

    # Access agent memory after execution
    agent_memory = runner.get_agent_memory("agent_id")

Example (streaming with buffer):
    from execution import (
        MACPRunner, StreamBuffer, stream_to_string
    )

    # Collect all events and get final answer
    buffer = StreamBuffer()
    for event in runner.stream(graph):
        buffer.add(event)
        # process event...

    print(f"Final: {buffer.final_answer}")
    print(f"Agents: {list(buffer.agent_outputs.keys())}")

    # Or use helper function
    answer = stream_to_string(runner.stream(graph))

Example (with tools - function calling):
    from execution import MACPRunner, RunnerConfig
    from tools import ToolRegistry, ShellTool, FunctionTool

    # Create tool registry
    registry = ToolRegistry()
    registry.register(ShellTool(timeout=10))

    # Register custom functions
    func_tool = FunctionTool()

    @func_tool.register
    def calculate(expression: str) -> str:
        \"\"\"Evaluate a mathematical expression.\"\"\"
        return str(eval(expression))

    registry.register(func_tool)

    # Enable tools in config
    config = RunnerConfig(enable_tools=True)
    runner = MACPRunner(llm_caller=my_llm, tool_registry=registry, config=config)

    result = runner.run_round(graph)
"""

# Re-export callbacks for convenience
from callbacks import (
    AsyncCallbackHandler,
    AsyncCallbackManager,
    BaseCallbackHandler,
    CallbackManager,
    FileCallbackHandler,
    MetricsCallbackHandler,
    StdoutCallbackHandler,
    collect_metrics,
    trace_as_callback,
)

from .budget import (
    Budget,
    BudgetConfig,
    BudgetTracker,
    NodeBudget,
)
from .errors import (
    AgentNotFoundError,
    BudgetExceededError,
    ErrorAction,
    # Error policy
    ErrorPolicy,
    # Error types
    ExecutionError,
    ExecutionMetrics,
    RetryExhaustedError,
    # Result types
    StepExecutionResult,
    ValidationError,
)
from .errors import (
    TimeoutError as ExecutionTimeoutError,
)
from .runner import (
    AgentMemory,
    # Dynamic topology
    EarlyStopCondition,
    HiddenState,
    # Multi-model support
    LLMCallerFactory,
    MACPResult,
    MACPRunner,
    MemoryConfig,
    RunnerConfig,
    SharedMemoryPool,
    StepContext,
    # Structured prompt support
    StructuredLLMCallerProtocol,
    StructuredPrompt,
    TopologyAction,
    create_openai_async_structured_caller,
    create_openai_caller,
    create_openai_structured_caller,
)
from .scheduler import (
    # Adaptive scheduling
    AdaptiveScheduler,
    # Conditional routing
    ConditionContext,
    ConditionEvaluator,
    EdgeCondition,
    ExecutionPlan,
    ExecutionStep,
    PruningConfig,
    RoutingPolicy,
    StepResult,
    # Core functions
    build_execution_order,
    extract_agent_adjacency,
    filter_reachable_agents,
    get_incoming_agents,
    get_outgoing_agents,
    get_parallel_groups,
)
from .streaming import (
    AgentErrorEvent,
    AgentOutputEvent,
    AgentStartEvent,
    AsyncStreamCallback,
    BudgetExceededEvent,
    BudgetWarningEvent,
    FallbackEvent,
    MemoryReadEvent,
    MemoryWriteEvent,
    ParallelEndEvent,
    ParallelStartEvent,
    PruneEvent,
    RunEndEvent,
    # Specific events
    RunStartEvent,
    # Utilities
    StreamBuffer,
    # Callback types
    StreamCallback,
    StreamEvent,
    # Event types
    StreamEventType,
    TokenEvent,
    TopologyChangedEvent,
    aprint_stream,
    astream_to_string,
    format_event,
    print_stream,
    stream_to_string,
)

__all__ = [
    # Adaptive scheduling
    "AdaptiveScheduler",
    "AgentErrorEvent",
    # Memory
    "AgentMemory",
    "AgentNotFoundError",
    "AgentOutputEvent",
    "AgentStartEvent",
    "AsyncCallbackHandler",
    "AsyncCallbackManager",
    "AsyncStreamCallback",
    "BaseCallbackHandler",
    # Budget
    "Budget",
    "BudgetConfig",
    "BudgetExceededError",
    "BudgetExceededEvent",
    "BudgetTracker",
    "BudgetWarningEvent",
    "CallbackManager",
    # Conditional routing
    "ConditionContext",
    "ConditionEvaluator",
    # Dynamic topology
    "EarlyStopCondition",
    "EdgeCondition",
    "ErrorAction",
    "ErrorPolicy",
    # Errors
    "ExecutionError",
    "ExecutionMetrics",
    "ExecutionPlan",
    "ExecutionStep",
    "ExecutionTimeoutError",
    "FallbackEvent",
    "FileCallbackHandler",
    "HiddenState",
    # Multi-model support
    "LLMCallerFactory",
    "MACPResult",
    # Runner
    "MACPRunner",
    "MemoryConfig",
    "MemoryReadEvent",
    "MemoryWriteEvent",
    "MetricsCallbackHandler",
    "NodeBudget",
    "ParallelEndEvent",
    "ParallelStartEvent",
    "PruneEvent",
    "PruningConfig",
    "RetryExhaustedError",
    "RoutingPolicy",
    "RunEndEvent",
    "RunStartEvent",
    "RunnerConfig",
    "SharedMemoryPool",
    "StdoutCallbackHandler",
    "StepContext",
    "StepExecutionResult",
    "StepResult",
    "StreamBuffer",
    "StreamCallback",
    "StreamEvent",
    # Streaming
    "StreamEventType",
    # Structured prompt support
    "StructuredLLMCallerProtocol",
    "StructuredPrompt",
    "TokenEvent",
    "TopologyAction",
    "TopologyChangedEvent",
    "ValidationError",
    "aprint_stream",
    "astream_to_string",
    # Core scheduling functions
    "build_execution_order",
    "collect_metrics",
    "create_openai_async_structured_caller",
    "create_openai_caller",
    "create_openai_structured_caller",
    "extract_agent_adjacency",
    "filter_reachable_agents",
    "format_event",
    "get_incoming_agents",
    "get_outgoing_agents",
    "get_parallel_groups",
    "print_stream",
    "stream_to_string",
    "trace_as_callback",
]