Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

feat: add tool execution engine with sequential/parallel modes

xf gongb728c00905d6
diff --git a/cubepi/agent/tools.py b/cubepi/agent/tools.py
new file mode 100644
index 0000000..c9c3ce8
--- /dev/null
+++ b/cubepi/agent/tools.py
@@ -0,0 +1,396 @@
+from __future__ import annotations
+
+import asyncio
+import time
+from dataclasses import dataclass
+from typing import Any, Callable
+
+from pydantic import ValidationError
+
+from cubepi.agent.types import (
+ AfterToolCallContext,
+ AfterToolCallResult,
+ AgentContext,
+ AgentTool,
+ AgentToolResult,
+ BeforeToolCallContext,
+ BeforeToolCallResult,
+ MessageEndEvent,
+ MessageStartEvent,
+ ToolExecutionEndEvent,
+ ToolExecutionStartEvent,
+ ToolExecutionUpdateEvent,
+)
+from cubepi.providers.base import (
+ AssistantMessage,
+ TextContent,
+ ToolCall,
+ ToolResultMessage,
+)
+
+
+@dataclass
+class ToolCallBatch:
+ messages: list[ToolResultMessage]
+ terminate: bool
+
+
+@dataclass
+class _PreparedToolCall:
+ tool_call: ToolCall
+ tool: AgentTool
+ args: Any
+
+
+@dataclass
+class _ImmediateOutcome:
+ result: AgentToolResult
+ is_error: bool
+
+
+@dataclass
+class _FinalizedOutcome:
+ tool_call: ToolCall
+ result: AgentToolResult
+ is_error: bool
+
+
+def _error_result(message: str) -> AgentToolResult:
+ return AgentToolResult(content=[TextContent(text=message)])
+
+
+def _make_tool_result_message(finalized: _FinalizedOutcome) -> ToolResultMessage:
+ return ToolResultMessage(
+ tool_call_id=finalized.tool_call.id,
+ tool_name=finalized.tool_call.name,
+ content=finalized.result.content,
+ is_error=finalized.is_error,
+ timestamp=time.time(),
+ )
+
+
+async def _emit(emit_fn: Callable, event: Any) -> None:
+ result = emit_fn(event)
+ if asyncio.iscoroutine(result):
+ await result
+
+
+async def _prepare_tool_call(
+ context: AgentContext,
+ assistant_message: AssistantMessage,
+ tool_call: ToolCall,
+ before_tool_call: Callable | None,
+ signal: asyncio.Event | None,
+) -> _PreparedToolCall | _ImmediateOutcome:
+ tool = None
+ if context.tools:
+ for t in context.tools:
+ if t.name == tool_call.name:
+ tool = t
+ break
+
+ if tool is None:
+ return _ImmediateOutcome(
+ result=_error_result(f"Tool {tool_call.name} not found"),
+ is_error=True,
+ )
+
+ try:
+ validated_args = tool.parameters.model_validate(tool_call.arguments)
+ except (ValidationError, Exception) as exc:
+ return _ImmediateOutcome(result=_error_result(str(exc)), is_error=True)
+
+ if before_tool_call:
+ try:
+ before_ctx = BeforeToolCallContext(
+ assistant_message=assistant_message,
+ tool_call=tool_call,
+ args=validated_args,
+ context=context,
+ )
+ before_result = await before_tool_call(before_ctx, signal=signal)
+ if before_result and before_result.block:
+ return _ImmediateOutcome(
+ result=_error_result(
+ before_result.reason or "Tool execution was blocked"
+ ),
+ is_error=True,
+ )
+ except Exception as exc:
+ return _ImmediateOutcome(result=_error_result(str(exc)), is_error=True)
+
+ return _PreparedToolCall(tool_call=tool_call, tool=tool, args=validated_args)
+
+
+async def _execute_prepared(
+ prepared: _PreparedToolCall,
+ signal: asyncio.Event | None,
+ emit_fn: Callable,
+) -> tuple[AgentToolResult, bool]:
+ try:
+ result = await prepared.tool.execute(
+ prepared.tool_call.id,
+ prepared.args,
+ signal=signal,
+ on_update=lambda partial: _emit(
+ emit_fn,
+ ToolExecutionUpdateEvent(
+ tool_call_id=prepared.tool_call.id,
+ tool_name=prepared.tool_call.name,
+ args=prepared.tool_call.arguments,
+ partial_result=partial,
+ ),
+ ),
+ )
+ return result, False
+ except Exception as exc:
+ return _error_result(str(exc)), True
+
+
+async def _finalize(
+ context: AgentContext,
+ assistant_message: AssistantMessage,
+ prepared: _PreparedToolCall,
+ result: AgentToolResult,
+ is_error: bool,
+ after_tool_call: Callable | None,
+ signal: asyncio.Event | None,
+) -> _FinalizedOutcome:
+ if after_tool_call:
+ try:
+ after_ctx = AfterToolCallContext(
+ assistant_message=assistant_message,
+ tool_call=prepared.tool_call,
+ args=prepared.args,
+ result=result,
+ is_error=is_error,
+ context=context,
+ )
+ after_result = await after_tool_call(after_ctx, signal=signal)
+ if after_result:
+ result = AgentToolResult(
+ content=(
+ after_result.content
+ if after_result.content is not None
+ else result.content
+ ),
+ details=(
+ after_result.details
+ if after_result.details is not None
+ else result.details
+ ),
+ terminate=(
+ after_result.terminate
+ if after_result.terminate is not None
+ else result.terminate
+ ),
+ )
+ is_error = (
+ after_result.is_error
+ if after_result.is_error is not None
+ else is_error
+ )
+ except Exception as exc:
+ result = _error_result(str(exc))
+ is_error = True
+
+ return _FinalizedOutcome(
+ tool_call=prepared.tool_call, result=result, is_error=is_error
+ )
+
+
+def _should_terminate(finalized: list[_FinalizedOutcome]) -> bool:
+ return len(finalized) > 0 and all(
+ f.result.terminate is True for f in finalized
+ )
+
+
+async def execute_tool_calls(
+ context: AgentContext,
+ assistant_message: AssistantMessage,
+ *,
+ tool_execution: str = "parallel",
+ before_tool_call: Callable | None = None,
+ after_tool_call: Callable | None = None,
+ signal: asyncio.Event | None = None,
+ emit: Callable,
+) -> ToolCallBatch:
+ tool_calls = [
+ c for c in assistant_message.content if isinstance(c, ToolCall)
+ ]
+
+ has_sequential = any(
+ t.execution_mode == "sequential"
+ for tc in tool_calls
+ if context.tools
+ for t in context.tools
+ if t.name == tc.name
+ )
+
+ if tool_execution == "sequential" or has_sequential:
+ return await _execute_sequential(
+ context,
+ assistant_message,
+ tool_calls,
+ before_tool_call,
+ after_tool_call,
+ signal,
+ emit,
+ )
+ return await _execute_parallel(
+ context,
+ assistant_message,
+ tool_calls,
+ before_tool_call,
+ after_tool_call,
+ signal,
+ emit,
+ )
+
+
+async def _execute_sequential(
+ context: AgentContext,
+ assistant_message: AssistantMessage,
+ tool_calls: list[ToolCall],
+ before_tool_call: Callable | None,
+ after_tool_call: Callable | None,
+ signal: asyncio.Event | None,
+ emit_fn: Callable,
+) -> ToolCallBatch:
+ finalized_list: list[_FinalizedOutcome] = []
+ messages: list[ToolResultMessage] = []
+
+ for tc in tool_calls:
+ await _emit(
+ emit_fn,
+ ToolExecutionStartEvent(
+ tool_call_id=tc.id, tool_name=tc.name, args=tc.arguments
+ ),
+ )
+
+ preparation = await _prepare_tool_call(
+ context, assistant_message, tc, before_tool_call, signal
+ )
+
+ if isinstance(preparation, _ImmediateOutcome):
+ finalized = _FinalizedOutcome(
+ tool_call=tc,
+ result=preparation.result,
+ is_error=preparation.is_error,
+ )
+ else:
+ result, is_error = await _execute_prepared(preparation, signal, emit_fn)
+ finalized = await _finalize(
+ context,
+ assistant_message,
+ preparation,
+ result,
+ is_error,
+ after_tool_call,
+ signal,
+ )
+
+ await _emit(
+ emit_fn,
+ ToolExecutionEndEvent(
+ tool_call_id=tc.id,
+ tool_name=tc.name,
+ result=finalized.result,
+ is_error=finalized.is_error,
+ ),
+ )
+ tool_msg = _make_tool_result_message(finalized)
+ await _emit(emit_fn, MessageStartEvent(message=tool_msg))
+ await _emit(emit_fn, MessageEndEvent(message=tool_msg))
+ finalized_list.append(finalized)
+ messages.append(tool_msg)
+
+ return ToolCallBatch(
+ messages=messages, terminate=_should_terminate(finalized_list)
+ )
+
+
+async def _execute_parallel(
+ context: AgentContext,
+ assistant_message: AssistantMessage,
+ tool_calls: list[ToolCall],
+ before_tool_call: Callable | None,
+ after_tool_call: Callable | None,
+ signal: asyncio.Event | None,
+ emit_fn: Callable,
+) -> ToolCallBatch:
+ entries: list[_FinalizedOutcome | asyncio.Task] = []
+
+ for tc in tool_calls:
+ await _emit(
+ emit_fn,
+ ToolExecutionStartEvent(
+ tool_call_id=tc.id, tool_name=tc.name, args=tc.arguments
+ ),
+ )
+
+ preparation = await _prepare_tool_call(
+ context, assistant_message, tc, before_tool_call, signal
+ )
+
+ if isinstance(preparation, _ImmediateOutcome):
+ finalized = _FinalizedOutcome(
+ tool_call=tc,
+ result=preparation.result,
+ is_error=preparation.is_error,
+ )
+ await _emit(
+ emit_fn,
+ ToolExecutionEndEvent(
+ tool_call_id=tc.id,
+ tool_name=tc.name,
+ result=finalized.result,
+ is_error=finalized.is_error,
+ ),
+ )
+ entries.append(finalized)
+ else:
+
+ async def _run(prep=preparation):
+ result, is_error = await _execute_prepared(
+ prep, signal, emit_fn
+ )
+ fin = await _finalize(
+ context,
+ assistant_message,
+ prep,
+ result,
+ is_error,
+ after_tool_call,
+ signal,
+ )
+ await _emit(
+ emit_fn,
+ ToolExecutionEndEvent(
+ tool_call_id=prep.tool_call.id,
+ tool_name=prep.tool_call.name,
+ result=fin.result,
+ is_error=fin.is_error,
+ ),
+ )
+ return fin
+
+ entries.append(asyncio.create_task(_run()))
+
+ finalized_list: list[_FinalizedOutcome] = []
+ for entry in entries:
+ if isinstance(entry, asyncio.Task):
+ finalized_list.append(await entry)
+ else:
+ finalized_list.append(entry)
+
+ messages: list[ToolResultMessage] = []
+ for finalized in finalized_list:
+ tool_msg = _make_tool_result_message(finalized)
+ await _emit(emit_fn, MessageStartEvent(message=tool_msg))
+ await _emit(emit_fn, MessageEndEvent(message=tool_msg))
+ messages.append(tool_msg)
+
+ return ToolCallBatch(
+ messages=messages, terminate=_should_terminate(finalized_list)
+ )
diff --git a/tests/agent/test_tools.py b/tests/agent/test_tools.py
new file mode 100644
index 0000000..8a5452c
--- /dev/null
+++ b/tests/agent/test_tools.py
@@ -0,0 +1,237 @@
+import asyncio
+
+from pydantic import BaseModel
+
+from cubepi.agent.tools import execute_tool_calls
+from cubepi.agent.types import (
+ AfterToolCallResult,
+ AgentContext,
+ AgentTool,
+ AgentToolResult,
+ BeforeToolCallResult,
+)
+from cubepi.providers.base import AssistantMessage, TextContent, ToolCall
+
+
+class EchoParams(BaseModel):
+ value: str
+
+
+def make_echo_tool(
+ *,
+ name: str = "echo",
+ execution_mode=None,
+ execute_fn=None,
+) -> AgentTool:
+ async def default_execute(tool_call_id, params, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text=f"echoed: {params.value}")])
+
+ return AgentTool(
+ name=name,
+ description="Echo tool",
+ parameters=EchoParams,
+ execute=execute_fn or default_execute,
+ execution_mode=execution_mode,
+ )
+
+
+def make_assistant_msg(tool_calls: list[ToolCall]) -> AssistantMessage:
+ return AssistantMessage(content=tool_calls, stop_reason="tool_use")
+
+
+def make_context(tools: list[AgentTool]) -> AgentContext:
+ return AgentContext(system_prompt="", messages=[], tools=tools)
+
+
+class TestSequentialExecution:
+ async def test_single_tool_call(self):
+ tool = make_echo_tool()
+ ctx = make_context([tool])
+ msg = make_assistant_msg([ToolCall(id="t1", name="echo", arguments={"value": "hi"})])
+
+ events = []
+ batch = await execute_tool_calls(
+ ctx, msg, tool_execution="sequential",
+ emit=lambda e: events.append(e),
+ )
+
+ assert len(batch.messages) == 1
+ assert batch.messages[0].tool_call_id == "t1"
+ assert not batch.messages[0].is_error
+ assert batch.terminate is False
+
+ async def test_multiple_tool_calls_run_sequentially(self):
+ order = []
+
+ async def tracked_execute(tool_call_id, params, *, signal=None, on_update=None):
+ order.append(f"start:{params.value}")
+ await asyncio.sleep(0.01)
+ order.append(f"end:{params.value}")
+ return AgentToolResult(content=[TextContent(text=f"echoed: {params.value}")])
+
+ tool = make_echo_tool(execute_fn=tracked_execute)
+ ctx = make_context([tool])
+ msg = make_assistant_msg([
+ ToolCall(id="t1", name="echo", arguments={"value": "first"}),
+ ToolCall(id="t2", name="echo", arguments={"value": "second"}),
+ ])
+
+ batch = await execute_tool_calls(ctx, msg, tool_execution="sequential", emit=lambda e: None)
+
+ assert order == ["start:first", "end:first", "start:second", "end:second"]
+
+ async def test_unknown_tool_returns_error(self):
+ ctx = make_context([])
+ msg = make_assistant_msg([ToolCall(id="t1", name="unknown", arguments={})])
+
+ batch = await execute_tool_calls(ctx, msg, tool_execution="sequential", emit=lambda e: None)
+
+ assert len(batch.messages) == 1
+ assert batch.messages[0].is_error
+ assert "not found" in batch.messages[0].content[0].text.lower()
+
+
+class TestParallelExecution:
+ async def test_tools_run_concurrently(self):
+ first_resolved = False
+ parallel_observed = False
+ release = asyncio.Event()
+
+ async def slow_execute(tool_call_id, params, *, signal=None, on_update=None):
+ nonlocal first_resolved, parallel_observed
+ if params.value == "first":
+ await release.wait()
+ first_resolved = True
+ if params.value == "second" and not first_resolved:
+ parallel_observed = True
+ return AgentToolResult(content=[TextContent(text=f"echoed: {params.value}")])
+
+ tool = make_echo_tool(execute_fn=slow_execute)
+ ctx = make_context([tool])
+ msg = make_assistant_msg([
+ ToolCall(id="t1", name="echo", arguments={"value": "first"}),
+ ToolCall(id="t2", name="echo", arguments={"value": "second"}),
+ ])
+
+ async def run():
+ await asyncio.sleep(0.02)
+ release.set()
+
+ asyncio.create_task(run())
+ batch = await execute_tool_calls(ctx, msg, tool_execution="parallel", emit=lambda e: None)
+
+ assert parallel_observed
+ assert len(batch.messages) == 2
+ assert batch.messages[0].tool_call_id == "t1"
+ assert batch.messages[1].tool_call_id == "t2"
+
+ async def test_sequential_tool_forces_sequential_mode(self):
+ order = []
+
+ async def tracked(tool_call_id, params, *, signal=None, on_update=None):
+ order.append(f"start:{params.value}")
+ await asyncio.sleep(0.01)
+ order.append(f"end:{params.value}")
+ return AgentToolResult(content=[TextContent(text="ok")])
+
+ tool = make_echo_tool(execute_fn=tracked, execution_mode="sequential")
+ ctx = make_context([tool])
+ msg = make_assistant_msg([
+ ToolCall(id="t1", name="echo", arguments={"value": "a"}),
+ ToolCall(id="t2", name="echo", arguments={"value": "b"}),
+ ])
+
+ batch = await execute_tool_calls(ctx, msg, tool_execution="parallel", emit=lambda e: None)
+
+ assert order[0] == "start:a"
+ assert order[1] == "end:a"
+
+
+class TestBeforeToolCall:
+ async def test_block_prevents_execution(self):
+ tool = make_echo_tool()
+ ctx = make_context([tool])
+ msg = make_assistant_msg([ToolCall(id="t1", name="echo", arguments={"value": "hi"})])
+
+ async def before(ctx_arg, *, signal=None):
+ return BeforeToolCallResult(block=True, reason="Blocked by test")
+
+ batch = await execute_tool_calls(
+ ctx, msg, tool_execution="sequential",
+ before_tool_call=before, emit=lambda e: None,
+ )
+
+ assert len(batch.messages) == 1
+ assert batch.messages[0].is_error
+ assert "Blocked by test" in batch.messages[0].content[0].text
+
+
+class TestAfterToolCall:
+ async def test_override_result(self):
+ tool = make_echo_tool()
+ ctx = make_context([tool])
+ msg = make_assistant_msg([ToolCall(id="t1", name="echo", arguments={"value": "hi"})])
+
+ async def after(ctx_arg, *, signal=None):
+ return AfterToolCallResult(
+ content=[TextContent(text="overridden")],
+ terminate=True,
+ )
+
+ batch = await execute_tool_calls(
+ ctx, msg, tool_execution="sequential",
+ after_tool_call=after, emit=lambda e: None,
+ )
+
+ assert batch.messages[0].content[0].text == "overridden"
+ assert batch.terminate is True
+
+
+class TestTermination:
+ async def test_all_terminate_stops_loop(self):
+ async def term_execute(tool_call_id, params, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text="done")], terminate=True)
+
+ tool = make_echo_tool(execute_fn=term_execute)
+ ctx = make_context([tool])
+ msg = make_assistant_msg([ToolCall(id="t1", name="echo", arguments={"value": "a"})])
+
+ batch = await execute_tool_calls(ctx, msg, tool_execution="sequential", emit=lambda e: None)
+ assert batch.terminate is True
+
+ async def test_partial_terminate_continues(self):
+ async def maybe_term(tool_call_id, params, *, signal=None, on_update=None):
+ return AgentToolResult(
+ content=[TextContent(text="done")],
+ terminate=(params.value == "first"),
+ )
+
+ tool = make_echo_tool(execute_fn=maybe_term)
+ ctx = make_context([tool])
+ msg = make_assistant_msg([
+ ToolCall(id="t1", name="echo", arguments={"value": "first"}),
+ ToolCall(id="t2", name="echo", arguments={"value": "second"}),
+ ])
+
+ batch = await execute_tool_calls(ctx, msg, tool_execution="parallel", emit=lambda e: None)
+ assert batch.terminate is False
+
+
+class TestToolEvents:
+ async def test_emits_execution_lifecycle_events(self):
+ tool = make_echo_tool()
+ ctx = make_context([tool])
+ msg = make_assistant_msg([ToolCall(id="t1", name="echo", arguments={"value": "hi"})])
+
+ events = []
+ batch = await execute_tool_calls(
+ ctx, msg, tool_execution="sequential",
+ emit=lambda e: events.append(e),
+ )
+
+ types = [e.type for e in events]
+ assert "tool_execution_start" in types
+ assert "tool_execution_end" in types
+ start_idx = types.index("tool_execution_start")
+ end_idx = types.index("tool_execution_end")
+ assert start_idx < end_idx