diff --git a/cyclops/core/compaction.py b/cyclops/core/compaction.py index 1e98aba..f759ca0 100644 --- a/cyclops/core/compaction.py +++ b/cyclops/core/compaction.py @@ -10,6 +10,7 @@ from cyclops.core.completion import _acompletion, _completion_kwargs, _usage from cyclops.core.events import Compacted from cyclops.core.providers import _asks_server, _model_info +from cyclops.core.hooks import _call_hook from cyclops.core.types import AgentConfig, Compaction, Usage from cyclops.toolkit.types import ToolResult @@ -238,8 +239,7 @@ async def compact( after, threshold, ) - if self.config.hooks: - self.config.hooks.on_compaction(summary, before, after) + await _call_hook(self.config, "on_compaction", summary, before, after) return Compacted( summary=summary, replaced_messages=cut, @@ -306,8 +306,7 @@ async def _summarize( config, messages=[{"role": "user", "content": prompt}], **kwargs ) api_duration = time.perf_counter() - start - if config.hooks: - config.hooks.on_llm_end(response) + await _call_hook(config, "on_llm_end", response) self.spend(config.model, _usage(response, api_duration)) choice = response.choices[0] summary = choice.message.content diff --git a/cyclops/core/completion.py b/cyclops/core/completion.py index 0bccaa7..441770e 100644 --- a/cyclops/core/completion.py +++ b/cyclops/core/completion.py @@ -28,6 +28,7 @@ _response_schema, _takes_param, ) +from cyclops.core.hooks import _call_hook from cyclops.core.types import AgentConfig, Usage from cyclops.utils.compat import asyncio_timeout @@ -140,15 +141,13 @@ def _retry_delay( async def _attempt(config: AgentConfig, /, **kwargs): - if config.hooks: - config.hooks.on_llm_start(kwargs.get("messages", [])) + await _call_hook(config, "on_llm_start", kwargs.get("messages", [])) try: if config.router: return await config.router.acompletion(model=config.model, **kwargs) return await litellm.acompletion(model=config.model, **kwargs) except Exception as e: - if config.hooks: - config.hooks.on_llm_error(e) + await _call_hook(config, "on_llm_error", e) raise @@ -199,8 +198,7 @@ async def _astream_completion( yield chunk idle_timeout = config.stream_idle_timeout except Exception as e: - if config.hooks: - config.hooks.on_llm_error(e) + await _call_hook(config, "on_llm_error", e) raise finally: await response.aclose() diff --git a/cyclops/core/fallback.py b/cyclops/core/fallback.py index f6c4155..b332517 100644 --- a/cyclops/core/fallback.py +++ b/cyclops/core/fallback.py @@ -15,6 +15,7 @@ ) from cyclops.core.events import Event, ModelFallback from cyclops.core.run_state import _Run +from cyclops.core.hooks import _call_hook from cyclops.core.types import AgentConfig, Usage # A model's config and the arguments of its completions. @@ -97,8 +98,7 @@ async def _complete_with_fallbacks( continue if watched.emitted or response.choices[0].finish_reason != "content_filter": return config.model, response, usage - if config.hooks: - config.hooks.on_llm_end(response) + await _call_hook(config, "on_llm_end", response) # A refused completion is billed too. run.spend(config.model, usage) if run.over_budget(): diff --git a/cyclops/core/hooks.py b/cyclops/core/hooks.py index 21161de..e010a89 100644 --- a/cyclops/core/hooks.py +++ b/cyclops/core/hooks.py @@ -1,7 +1,28 @@ -"""Agent lifecycle hooks — standard event callbacks for the agent run loop.""" +"""Agent lifecycle hooks: standard event callbacks for the agent run loop.""" +import inspect from contextvars import ContextVar -from typing import Any, Dict, List, Optional, Union +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Dict, + List, + Optional, + Tuple, + TypeVar, + Union, +) + +from cyclops.utils.compat import asyncio_timeout + +if TYPE_CHECKING: + from cyclops.core.content import UserContent + from cyclops.core.types import AgentConfig, RunResult + +_T = TypeVar("_T") +# What a hook returns, sync or async. +MaybeAwaitable = Union[_T, Awaitable[_T]] _tool_call_id: ContextVar[Optional[str]] = ContextVar( "cyclops_tool_call_id", default=None @@ -24,56 +45,91 @@ def current_tool_call_id() -> Optional[str]: class AgentHooks: """Base class for agent lifecycle hooks. - Override any method to intercept events. All methods are no-ops by default. - - on_tool_start is the exception: it controls execution. Return "deny" to - block the tool call; any other return value (including None) allows it. + Override any method to intercept events, as a plain or an async method. + All methods are no-ops by default. on_run_start may replace the run's + input and on_tool_start may block a tool call; the others only observe. """ - def on_run_start(self, input_message: Union[str, List[Dict[str, Any]]]) -> None: + def on_run_start( + self, input_message: Union[str, List[Dict[str, Any]]] + ) -> MaybeAwaitable[Optional["UserContent"]]: """Fired once when agent.run / agent.stream is called. - input_message is the run's text, or its list of content parts. + input_message is the run's text, or its list of content parts. Return + text or content parts to replace it, or None to keep it. """ + return None - def on_run_end(self, content: str) -> None: + def on_run_end(self, content: str) -> MaybeAwaitable[None]: """Fired when a run completes, streamed or not.""" - def on_run_error(self, error: BaseException) -> None: + def on_run_error(self, error: BaseException) -> MaybeAwaitable[None]: """Fired instead of on_run_end when a run raises or is cancelled. A run its caller stopped, such as a stream closed early, gets a CancelledError whose args are (RUN_STOPPED,). """ - def on_llm_start(self, messages: List[Dict[str, Any]]) -> None: + def on_subagent_start( + self, agent_path: Tuple[str, ...], input_message: str + ) -> MaybeAwaitable[None]: + """Fired before a subagent run nested in this agent's run starts. + + agent_path names the nested agents down to it, outermost first. + """ + + def on_subagent_end( + self, agent_path: Tuple[str, ...], result: "RunResult" + ) -> MaybeAwaitable[None]: + """Fired when that subagent run ends, with its result, however it ended.""" + + def on_llm_start(self, messages: List[Dict[str, Any]]) -> MaybeAwaitable[None]: """Fired before each LiteLLM completion call.""" - def on_llm_end(self, response: Any) -> None: + def on_llm_end(self, response: Any) -> MaybeAwaitable[None]: """Fired after each LiteLLM completion; for a stream, with the assembled response.""" - def on_llm_error(self, error: Exception) -> None: + def on_llm_error(self, error: Exception) -> MaybeAwaitable[None]: """Fired when a LiteLLM call raises.""" def on_compaction( self, summary: str, tokens_before: int, tokens_after: int - ) -> None: + ) -> MaybeAwaitable[None]: """Fired when a summary replaced the older part of the transcript.""" - def on_tool_start(self, tool_name: str, args: Dict[str, Any]) -> Optional[str]: + def on_tool_start( + self, tool_name: str, args: Dict[str, Any] + ) -> MaybeAwaitable[Optional[str]]: """Fired before each tool execution. Return "deny" to block the tool call. Any other value (or None) allows it. """ return "allow" - def on_tool_end(self, tool_name: str, args: Dict[str, Any], result: str) -> None: + def on_tool_end( + self, tool_name: str, args: Dict[str, Any], result: str + ) -> MaybeAwaitable[None]: """Fired after successful tool execution.""" def on_tool_error( self, tool_name: str, args: Dict[str, Any], error: BaseException - ) -> None: + ) -> MaybeAwaitable[None]: """Fired when a tool raises an exception or is cancelled.""" +async def _call_hook(config: "AgentConfig", name: str, *args: Any) -> Any: + """Call config.hooks' method name, if any hooks are set. + + An async hook gets config.hook_timeout and raises TimeoutError past it, as + a hook that raises does. A plain hook runs inline, since nothing can stop it. + """ + if config.hooks is None: + return None + hook = getattr(config.hooks, name) + if not inspect.iscoroutinefunction(hook): + return hook(*args) + async with asyncio_timeout(config.hook_timeout): + return await hook(*args) + + __all__ = ["AgentHooks", "RUN_STOPPED", "current_tool_call_id"] diff --git a/cyclops/core/run.py b/cyclops/core/run.py index 7ebc888..dae0d52 100644 --- a/cyclops/core/run.py +++ b/cyclops/core/run.py @@ -31,10 +31,10 @@ TextDelta, ) from cyclops.core.fallback import _complete_with_fallbacks, _Request, _requests -from cyclops.core.hooks import RUN_STOPPED +from cyclops.core.hooks import RUN_STOPPED, _call_hook from cyclops.core.middleware import GuardContext from cyclops.core.providers import _every_deployment, _lacks_tools -from cyclops.core.content import _Content +from cyclops.core.content import _Content, _user_content from cyclops.core.run_state import _Run from cyclops.core.session import _SessionSaver from cyclops.core.tool_execution import ( @@ -167,9 +167,10 @@ async def _end_session(self, failed: bool = False) -> None: async def _loop(self, input_message: _Content) -> None: run = self.run - if self.config.hooks: - self.config.hooks.on_run_start(input_message) try: + replaced = await _call_hook(self.config, "on_run_start", input_message) + if replaced is not None: + input_message = _user_content(self.config, replaced) # Compaction may replace earlier messages too, so the transcript is # restored as a whole. before = list(run.history) @@ -188,8 +189,7 @@ async def _loop(self, input_message: _Content) -> None: await self._steps(input_message, "naive") except BaseException as e: # Failures, cancellation and a stream closed early all end the run here. - if self.config.hooks: - self.config.hooks.on_run_error(e) + await _call_hook(self.config, "on_run_error", e) await self._end_session(failed=True) raise # Steering the run had no step left for waits for the session's next run; @@ -199,11 +199,9 @@ async def _loop(self, input_message: _Content) -> None: try: await self._end_session() except BaseException as e: - if self.config.hooks: - self.config.hooks.on_run_error(e) + await _call_hook(self.config, "on_run_error", e) raise - if self.config.hooks: - self.config.hooks.on_run_end(run.result.content) + await _call_hook(self.config, "on_run_end", run.result.content) async def _steps(self, input_message: _Content, mode: str) -> None: run, agent = self.run, self.agent @@ -256,8 +254,7 @@ async def _steps(self, input_message: _Content, mode: str) -> None: result.stop_reason = "budget" return model, response, step_usage = answer - if self.config.hooks: - self.config.hooks.on_llm_end(response) + await _call_hook(self.config, "on_llm_end", response) del run.steering[:steered] result.steps += 1 run.spend(model, step_usage) diff --git a/cyclops/core/subagents.py b/cyclops/core/subagents.py index 2ce7f9a..b2abf50 100644 --- a/cyclops/core/subagents.py +++ b/cyclops/core/subagents.py @@ -4,7 +4,7 @@ from typing import TYPE_CHECKING, Any, Optional from weakref import WeakKeyDictionary -from cyclops.core.hooks import RUN_STOPPED +from cyclops.core.hooks import RUN_STOPPED, _call_hook from cyclops.core.run import _current_loop, _RunLoop from cyclops.core.run_state import _Run from cyclops.core.types import RunResult @@ -32,8 +32,9 @@ class AgentTool(BaseTool): transcript. Called by another agent, the run is nested in that agent's run: it is cancelled with it, streams when it streams, its events go to that run's events with agent_path extended by the tool name, and its - usage counts in that run's usage and budgets. A run that fails or stops - without an answer gives an error result. + usage counts in that run's usage and budgets, and that agent's + on_subagent_start and on_subagent_end hooks see it start and end. A run + that fails or stops without an answer gives an error result. """ def __init__( @@ -82,7 +83,14 @@ async def _run(self, input_message: str) -> RunResult: _slots[parent] = asyncio.Semaphore(parent.config.max_concurrent_subagents) async with _slots[parent]: run = _Run(config, [], None, parent=parent, name=self.name) - return await _RunLoop(self.agent, run, caller.stream).execute(input_message) + path = run.agent_path + await _call_hook(parent.config, "on_subagent_start", path, input_message) + try: + return await _RunLoop(self.agent, run, caller.stream).execute( + input_message + ) + finally: + await _call_hook(parent.config, "on_subagent_end", path, run.result) __all__ = ["AgentTool"] diff --git a/cyclops/core/tool_execution.py b/cyclops/core/tool_execution.py index 6823549..b63a901 100644 --- a/cyclops/core/tool_execution.py +++ b/cyclops/core/tool_execution.py @@ -10,7 +10,7 @@ from typing import Any, Dict, List, NamedTuple, Optional, Tuple, Union from cyclops.core.events import ToolCallFinished, ToolCallStarted -from cyclops.core.hooks import AgentHooks, _tool_call_id +from cyclops.core.hooks import _call_hook, _tool_call_id from cyclops.core.middleware import Deny, ToolCallContext, ToolMiddleware from cyclops.core.providers import _every_deployment, _takes_tool_message_images from cyclops.core.run_state import _Run @@ -152,25 +152,38 @@ def _append_tool_result(history: List[Dict[str, Any]], tc, content: Any) -> None class _HooksMiddleware(ToolMiddleware): """Runs the AgentHooks tool callbacks as the innermost middleware.""" - def __init__(self, hooks: AgentHooks) -> None: - self.hooks = hooks + def __init__(self, config: AgentConfig) -> None: + self.config = config # The result on_tool_end saw; each call gets its own instance. self.rendered: Optional[_Rendered] = None async def before_tool(self, call): - if self.hooks.on_tool_start(call.tool_name, call.arguments) == "deny": + decision = await _call_hook( + self.config, "on_tool_start", call.tool_name, call.arguments + ) + if decision == "deny": return Deny(f"Tool '{call.tool_name}' was not approved") return None async def after_tool(self, call, result, error): if error is not None: - self.hooks.on_tool_error(call.tool_name, call.arguments, error) + await _call_hook( + self.config, "on_tool_error", call.tool_name, call.arguments, error + ) return None try: rendered = _render(result) - self.hooks.on_tool_end(call.tool_name, call.arguments, rendered.text) + await _call_hook( + self.config, + "on_tool_end", + call.tool_name, + call.arguments, + rendered.text, + ) except Exception as e: - self.hooks.on_tool_error(call.tool_name, call.arguments, e) + await _call_hook( + self.config, "on_tool_error", call.tool_name, call.arguments, e + ) return ToolResult.error_result(f"{call.tool_name} failed: {e}") self.rendered = rendered return None @@ -368,7 +381,7 @@ async def _run_tool( middleware = list(self.config.middleware) hooks = None if self.config.hooks: - hooks = _HooksMiddleware(self.config.hooks) + hooks = _HooksMiddleware(self.config) middleware.append(hooks) timeout = self.config.tool_timeout if tool.timeout is None else tool.timeout allowed: List[ToolMiddleware] = [] diff --git a/cyclops/core/types.py b/cyclops/core/types.py index ed887a5..6fb927d 100644 --- a/cyclops/core/types.py +++ b/cyclops/core/types.py @@ -97,6 +97,12 @@ class AgentConfig(BaseModel): description="Seconds a tool call may run; a tool's own timeout wins", ) hooks: Optional[AgentHooks] = None + hook_timeout: Optional[float] = Field( + default=None, + gt=0, + description="Seconds each async hook call may run before it raises " + "TimeoutError", + ) middleware: List[ToolMiddleware] = Field(default_factory=list) guards: List[Guard] = Field(default_factory=list) max_guard_rounds: int = Field( diff --git a/docs/api-reference.md b/docs/api-reference.md index 82c23a5..59564fb 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -70,6 +70,7 @@ class AgentConfig(BaseModel): max_parallel_tool_calls: int = 10 tool_timeout: Optional[float] = None # seconds hooks: Optional[AgentHooks] = None + hook_timeout: Optional[float] = None # seconds num_retries: int = 2 timeout: float = 600 # seconds stream_idle_timeout: float = 120 # seconds @@ -235,10 +236,13 @@ class DeniedToolCall(BaseModel): Lifecycle callback base class. Subclass and override any methods you need. ```python +# Any method may be async def. MaybeAwaitable[T] is T or an awaitable of T. class AgentHooks: - def on_run_start(self, input_message: Union[str, List[Dict[str, Any]]]) -> None: ... + def on_run_start(self, input_message: Union[str, List[Dict[str, Any]]]) -> MaybeAwaitable[Optional[UserContent]]: ... def on_run_end(self, content: str) -> None: ... def on_run_error(self, error: BaseException) -> None: ... + def on_subagent_start(self, agent_path: Tuple[str, ...], input_message: str) -> None: ... + def on_subagent_end(self, agent_path: Tuple[str, ...], result: RunResult) -> None: ... def on_llm_start(self, messages: List[Dict[str, Any]]) -> None: ... def on_llm_end(self, response: Any) -> None: ... def on_llm_error(self, error: Exception) -> None: ... diff --git a/docs/guide/agents.md b/docs/guide/agents.md index 21aa071..1a49f94 100644 --- a/docs/guide/agents.md +++ b/docs/guide/agents.md @@ -34,6 +34,7 @@ config = AgentConfig( | `max_parallel_tool_calls` | `int` | `10` | Most tool calls of one step that run at the same time; at least 1. See [Parallel calls and timeouts](tools.md#parallel-calls-and-timeouts). | | `tool_timeout` | `float \| None` | `None` | Seconds a tool call may run before it is cancelled and returns an error. A tool's own `timeout` wins. | | `hooks` | `AgentHooks \| None` | `None` | Lifecycle callbacks for observability and tool approval. See [Hooks](hooks.md). | +| `hook_timeout` | `float \| None` | `None` | Seconds each async hook call may run before it raises `TimeoutError`. See [Hook timeouts](hooks.md#hook-timeouts). | | `num_retries` | `int` | `2` | Retries of a completion after a rate limit, overload, 5xx, timeout or connection error. See [Retries and timeouts](#retries-and-timeouts). | | `timeout` | `float` | `600` | Seconds LiteLLM's HTTP client waits to connect and for each read or write. | | `stream_idle_timeout` | `float` | `120` | Seconds a stream may go without a chunk after its first. | diff --git a/docs/guide/hooks.md b/docs/guide/hooks.md index 6a56f6c..c2eb3a4 100644 --- a/docs/guide/hooks.md +++ b/docs/guide/hooks.md @@ -1,6 +1,6 @@ # Hooks -`AgentHooks` is a lifecycle callback system that lets you observe and control every stage of an agent run: from the initial call, through each LLM request, to every tool execution. Subclass `AgentHooks`, override the methods you need, and pass an instance to `AgentConfig`. +`AgentHooks` is a lifecycle callback system that lets you observe and control every stage of an agent run: from the initial call, through each LLM request, to every tool execution. Subclass `AgentHooks`, override the methods you need, and pass an instance to `AgentConfig`. Each method may be a plain method or an `async def` one; an async one is awaited. ## Quick example @@ -33,9 +33,11 @@ agent.run("What is the weather in London?") | Method | When it fires | Return value | |---|---|---| -| `on_run_start(input_message)` | Once at the start of `run()`, `arun()`, `stream()`, or `astream()`, with the input text or its list of content parts | `None` | +| `on_run_start(input_message)` | Once at the start of `run()`, `arun()`, `stream()`, or `astream()`, with the input text or its list of content parts | Text or content parts to replace the input, or `None` to keep it | | `on_run_end(content)` | When a run finishes, streamed or not | `None` | | `on_run_error(error)` | Instead of `on_run_end` when a run raises, is cancelled, or its stream is closed early. A run its caller stopped (`handle.cancel()`, or a stream closed early) gets a `CancelledError` whose `args` are `(RUN_STOPPED,)`, from `cyclops.core.hooks`. A handle cancelled before its run started fires no hooks at all; its events still end with `RunFinished`. | `None` | +| `on_subagent_start(agent_path, input_message)` | Before a [subagent](subagents.md) run nested in this agent's run starts. `agent_path` names the nested agents down to it, outermost first, as in events. | `None` | +| `on_subagent_end(agent_path, result)` | When that subagent run ends, with its `RunResult`, whether it completed, failed or was cancelled | `None` | | `on_llm_start(messages)` | Before each LiteLLM completion call | `None` | | `on_llm_end(response)` | After each LiteLLM completion; for a stream, with the assembled response | `None` | | `on_llm_error(error)` | When a LiteLLM call raises an exception | `None` | @@ -48,9 +50,49 @@ All methods are no-ops by default. Override only the ones you need. In the tool hooks, `cyclops.core.hooks.current_tool_call_id()` returns the id of the native tool call being run (`None` in naive mode). Each native call runs in its own asyncio task, so the id is exact when calls run in parallel. +## Rewriting the input with on_run_start + +`on_run_start` may return text or a list of content parts to use in place of the run's input, for instance to add context the model should see with the message. `None` keeps the input. The replacement is checked as run input is, so content the model can't take fails the run with `ValueError` and fires `on_run_error`, and it is what the model and the session get. + +```python +from datetime import date + +from cyclops import AgentConfig, AgentHooks + + +class AddDate(AgentHooks): + def on_run_start(self, input_message): + today = f"Today is {date.today()}." + if isinstance(input_message, str): + return f"{today}\n\n{input_message}" + return [{"type": "text", "text": today}, *input_message] + + +config = AgentConfig(model="gpt-4o-mini", hooks=AddDate()) +``` + +## Subagent runs + +A subagent run fires its own agent's hooks, from `on_run_start` to `on_run_end`. The calling agent's hooks see it as one tool call, and also get `on_subagent_start` and `on_subagent_end` around it. Only the direct caller's hooks get them: for a subagent of a subagent, give the middle agent the same hooks to see it from the top. + +```python +class SubagentLog(AgentHooks): + def on_subagent_start(self, agent_path, input_message): + print(f"[{'/'.join(agent_path)}] started: {input_message}") + + def on_subagent_end(self, agent_path, result): + print(f"[{'/'.join(agent_path)}] {result.stop_reason}: {result.content}") +``` + +## Hook timeouts + +`AgentConfig.hook_timeout` caps how many seconds each async hook call may run. A hook that takes longer is cancelled and raises `TimeoutError`, and the run treats it as a hook that raised: in `on_tool_start` it fails the run, as middleware that raises does, so a slow approval never lets a call through. Without `hook_timeout`, hooks run as long as they take. + +Plain hooks run inline on the event loop and are not bounded, since asyncio cannot interrupt blocking code. Write a hook as `async def` to bound it with `hook_timeout`. + ## Tool approval with on_tool_start -`on_tool_start` is the only hook with side effects: returning the string `"deny"` blocks the tool call. Any other return value (including `None`) allows it. The agent receives `"Error: Tool '' was not approved"` as the tool result and continues. +`on_tool_start` controls execution: returning the string `"deny"` blocks the tool call. Any other return value (including `None`) allows it. The agent receives `"Error: Tool '' was not approved"` as the tool result and continues. ```python from cyclops import Agent, AgentConfig, AgentHooks @@ -220,4 +262,4 @@ class ErrorHooks(AgentHooks): ## Default behaviour -The default `AgentHooks` base class implements `on_tool_start` to return `"allow"` and all other methods as no-ops. You do not need to call `super()` in your overrides. +The default `AgentHooks` base class implements `on_tool_start` to return `"allow"`, `on_run_start` to return `None`, and all other methods as no-ops. You do not need to call `super()` in your overrides. diff --git a/docs/guide/subagents.md b/docs/guide/subagents.md index f0a8eeb..2cb3806 100644 --- a/docs/guide/subagents.md +++ b/docs/guide/subagents.md @@ -38,7 +38,7 @@ A call from another agent's run nests the subagent's run in it: - **Events.** The subagent's events go to the parent's event stream with `agent_path` extended by the tool name: `("researcher",)` for the researcher's events, `("researcher", "checker")` for an agent the researcher calls in turn. Its `RunFinished` is forwarded too, so filter on `agent_path` to find the parent's last event. `astream()` and `stream()` yield only the text of the agent you ran. The subagent's run streams when the parent's does. - **Usage and budgets.** The subagent's usage counts in its own `RunResult` and in every run it is nested in, so the parent's `usage` covers all of them and its `max_total_tokens` and `max_cost` apply to all of them. A subagent checks its own limits and those of every run above it before each step, its first included, so it stops with `budget` once the parent's budget is spent, and a call made or waiting for a slot after that makes no completion. `steps` and `StepFinished.usage` count only an agent's own completions. `usage_by_model` splits the parent's usage by model, so subagents on other models keep their own entries. - **Middleware and guards.** The subagent's tool calls go through its own `AgentConfig.middleware`, and its answers through its own guards. Their `ToolCallContext.agent_path` and `GuardContext.agent_path` hold the nested path, so middleware shared between agents can tell the calls apart. The parent's middleware sees the subagent call itself, like any other tool call. -- **Hooks and tracing.** Each agent fires its own hooks. With `TelemetryHooks`, the subagent's `invoke_agent` span is a child of the parent's `execute_tool` span. +- **Hooks and tracing.** Each agent fires its own hooks, and the calling agent's hooks also get `on_subagent_start` and `on_subagent_end` around each subagent run. With `TelemetryHooks`, the subagent's `invoke_agent` span is a child of the parent's `execute_tool` span. ```python async for event in lead.astream_events("Compare the populations of Paris and Berlin."): diff --git a/tests/test_agent.py b/tests/test_agent.py index 2ec961a..e181887 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -767,6 +767,7 @@ def test_failed_run_returns_error_result_with_usage_so_far(): def test_error_result_follows_on_run_error(): hooks = MagicMock(spec=AgentHooks) + hooks.on_run_start.return_value = None agent = Agent(config=_make_config(hooks=hooks, num_retries=0)) error = litellm.APIConnectionError( message="down", llm_provider="openai", model="gpt-3.5-turbo" @@ -1472,6 +1473,8 @@ def fail() -> ToolResult: return ToolResult.error_result("no access") hooks = MagicMock(spec=AgentHooks) + + hooks.on_run_start.return_value = None hooks.on_tool_start.return_value = "allow" agent = Agent(config=_make_config(hooks=hooks), tools=[data, text, fail]) messages = _run_tool_calls(agent, "data", "text", "fail") @@ -2034,6 +2037,8 @@ async def two() -> str: return "done" hooks = MagicMock(spec=AgentHooks) + + hooks.on_run_start.return_value = None hooks.on_tool_start.return_value = "allow" agent = Agent( config=_make_config(hooks=hooks), diff --git a/tests/test_fallback.py b/tests/test_fallback.py index fe4e816..7d48060 100644 --- a/tests/test_fallback.py +++ b/tests/test_fallback.py @@ -138,6 +138,7 @@ async def test_refusal_switches_and_its_usage_is_counted(): refused = _response(PRIMARY, "", "content_filter") mock = AsyncMock(side_effect=[refused, _response(FALLBACK)]) hooks = MagicMock(spec=AgentHooks) + hooks.on_run_start.return_value = None with patch("litellm.acompletion", new=mock): result = await Agent(_config(hooks=hooks)).arun_with_response("hi") diff --git a/tests/test_hooks.py b/tests/test_hooks.py new file mode 100644 index 0000000..1349309 --- /dev/null +++ b/tests/test_hooks.py @@ -0,0 +1,389 @@ +"""Tests for async hooks, hook timeouts, input rewriting and subagent hooks""" + +import asyncio +import threading +import time +from unittest.mock import AsyncMock, patch + +import litellm +import pytest + +from cyclops.core.agent import Agent +from cyclops.core.hooks import AgentHooks +from cyclops.core.session import Session +from cyclops.core.types import RunResult +from cyclops.toolkit.tool import Tool +from tests.test_agent import ( + _make_completion_response, + _make_config, + _make_simple_tool, + _make_tool_call, +) +from tests.test_subagents import _agents, _asks, _call, _make_completion, _scripted + + +def _sent_input(mock: AsyncMock): + """The user message of the first completion.""" + return mock.call_args_list[0].kwargs["messages"][-1]["content"] + + +@pytest.mark.asyncio +async def test_on_run_start_replaces_the_input(): + class Rewrite(AgentHooks): + def on_run_start(self, input_message): + return input_message.upper() + + session = Session() + agent = Agent(_make_config(hooks=Rewrite())) + mock = AsyncMock(return_value=_make_completion_response("ok")) + with patch("litellm.acompletion", new=mock): + assert await agent.arun("hello", session=session) == "ok" + + assert _sent_input(mock) == "HELLO" + assert session.messages[0] == {"role": "user", "content": "HELLO"} + + +@pytest.mark.asyncio +async def test_async_on_run_start_adds_context_as_parts(): + class AddContext(AgentHooks): + async def on_run_start(self, input_message): + return [ + {"type": "text", "text": "The user is in Paris."}, + {"type": "text", "text": input_message}, + ] + + agent = Agent(_make_config(hooks=AddContext())) + mock = AsyncMock(return_value=_make_completion_response("ok")) + with patch("litellm.acompletion", new=mock): + await agent.arun("weather?") + + assert _sent_input(mock) == [ + {"type": "text", "text": "The user is in Paris."}, + {"type": "text", "text": "weather?"}, + ] + + +@pytest.mark.asyncio +async def test_replacement_input_is_checked_as_run_input_is(): + errors = [] + + class Empty(AgentHooks): + def on_run_start(self, input_message): + return [] + + def on_run_error(self, error): + errors.append(error) + + agent = Agent(_make_config(hooks=Empty())) + mock = AsyncMock(return_value=_make_completion_response("ok")) + with patch("litellm.acompletion", new=mock): + result = await agent.arun_with_response("hi") + + assert isinstance(result.error, ValueError) + assert errors == [result.error] + mock.assert_not_called() + + +@pytest.mark.asyncio +async def test_on_run_start_past_its_timeout_fires_on_run_error(): + errors = [] + + class Slow(AgentHooks): + async def on_run_start(self, input_message): + await asyncio.sleep(10) + + def on_run_error(self, error): + errors.append(error) + + agent = Agent(_make_config(hooks=Slow(), hook_timeout=0.01)) + mock = AsyncMock(return_value=_make_completion_response("ok")) + with patch("litellm.acompletion", new=mock): + result = await agent.arun_with_response("hi") + + assert isinstance(result.error, asyncio.TimeoutError) + assert errors == [result.error] + mock.assert_not_called() + + +@pytest.mark.asyncio +async def test_async_hooks_are_awaited(): + seen = [] + + class Async(AgentHooks): + async def on_llm_end(self, response): + await asyncio.sleep(0) + seen.append("llm_end") + + async def on_tool_start(self, tool_name, args): + seen.append(f"tool_start {tool_name}") + return "deny" + + async def on_run_end(self, content): + seen.append(f"run_end {content}") + + agent = Agent(_make_config(hooks=Async()), tools=[_make_simple_tool()]) + asks = _make_completion_response( + None, tool_calls=[_make_tool_call("tc_1", "add", '{"a": 1, "b": 2}')] + ) + mock = AsyncMock(side_effect=[asks, _make_completion_response("done")]) + with patch("litellm.acompletion", new=mock): + result = await agent.arun_with_response("go") + + assert seen == [ + "llm_end", + "tool_start add", + "llm_end", + "run_end done", + ] + assert [d.name for d in result.denied_tool_calls] == ["add"] + + +@pytest.mark.asyncio +async def test_async_hook_past_its_timeout_fails_the_run(): + class Slow(AgentHooks): + async def on_llm_end(self, response): + await asyncio.sleep(10) + + agent = Agent(_make_config(hooks=Slow(), hook_timeout=0.01)) + mock = AsyncMock(return_value=_make_completion_response("ok")) + with patch("litellm.acompletion", new=mock): + result = await agent.arun_with_response("hi") + + assert result.stop_reason == "error" + assert isinstance(result.error, asyncio.TimeoutError) + + +@pytest.mark.asyncio +async def test_async_on_tool_start_past_its_timeout_fails_closed(): + ran = [] + + def add(a: int, b: int) -> int: + ran.append((a, b)) + return a + b + + class Slow(AgentHooks): + async def on_tool_start(self, tool_name, args): + await asyncio.sleep(10) + + agent = Agent( + _make_config(hooks=Slow(), hook_timeout=0.01), + tools=[Tool("add", "Add two numbers", add)], + ) + asks = _make_completion_response( + None, tool_calls=[_make_tool_call("tc_1", "add", '{"a": 1, "b": 2}')] + ) + mock = AsyncMock(side_effect=[asks, _make_completion_response("done")]) + with patch("litellm.acompletion", new=mock): + result = await agent.arun_with_response("hi") + + assert isinstance(result.error, asyncio.TimeoutError) + assert ran == [] + + +@pytest.mark.asyncio +async def test_plain_hooks_run_inline_without_a_timeout(): + """hook_timeout bounds async hooks only; a plain hook runs on the loop's thread.""" + threads = [] + + class Plain(AgentHooks): + def on_run_start(self, input_message): + time.sleep(0.05) + threads.append(threading.get_ident()) + + agent = Agent(_make_config(hooks=Plain(), hook_timeout=0.01)) + mock = AsyncMock(return_value=_make_completion_response("ok")) + with patch("litellm.acompletion", new=mock): + result = await agent.arun_with_response("hi") + + assert result.content == "ok" + assert threads == [threading.get_ident()] + + +@pytest.mark.asyncio +async def test_cancelling_a_run_during_a_hook(): + started = asyncio.Event() + errors = [] + + class Waits(AgentHooks): + async def on_tool_start(self, tool_name, args): + started.set() + await asyncio.sleep(10) + + def on_run_error(self, error): + errors.append(error) + + agent = Agent( + _make_config(hooks=Waits(), hook_timeout=10), tools=[_make_simple_tool()] + ) + asks = _make_completion_response( + None, tool_calls=[_make_tool_call("tc_1", "add", '{"a": 1, "b": 2}')] + ) + mock = AsyncMock(side_effect=[asks, _make_completion_response("done")]) + with patch("litellm.acompletion", new=mock): + handle = agent.start("hi", stream=False) + await started.wait() + handle.cancel() + result = await handle + + assert result.stop_reason == "cancelled" + assert result.error is None + assert [type(e) for e in errors] == [asyncio.CancelledError] + + +@pytest.mark.asyncio +async def test_hooks_within_their_timeout_run_as_without_one(): + class Hooks(AgentHooks): + def on_run_start(self, input_message): + return "rewritten" + + async def on_tool_start(self, tool_name, args): + return "deny" + + agent = Agent( + _make_config(hooks=Hooks(), hook_timeout=5), tools=[_make_simple_tool()] + ) + asks = _make_completion_response( + None, tool_calls=[_make_tool_call("tc_1", "add", '{"a": 1, "b": 2}')] + ) + mock = AsyncMock(side_effect=[asks, _make_completion_response("done")]) + with patch("litellm.acompletion", new=mock): + result = await agent.arun_with_response("hi") + + assert result.content == "done" + assert _sent_input(mock) == "rewritten" + assert [d.name for d in result.denied_tool_calls] == ["add"] + + +@pytest.mark.asyncio +async def test_base_hooks_change_nothing(): + """A run with AgentHooks' defaults sends what a run without hooks sends.""" + sent = [] + for hooks in (None, AgentHooks()): + agent = Agent(_make_config(hooks=hooks), tools=[_make_simple_tool()]) + asks = _make_completion_response( + None, tool_calls=[_make_tool_call("tc_1", "add", '{"a": 1, "b": 2}')] + ) + mock = AsyncMock(side_effect=[asks, _make_completion_response("done")]) + with patch("litellm.acompletion", new=mock): + result = await agent.arun_with_response("hi") + assert result.content == "done" + sent.append([c.kwargs["messages"] for c in mock.call_args_list]) + + assert sent[0] == sent[1] + + +class _Watch(AgentHooks): + def __init__(self): + self.seen = [] + + def on_subagent_start(self, agent_path, input_message): + self.seen.append(("start", agent_path, input_message)) + + async def on_subagent_end(self, agent_path, result): + self.seen.append(("end", agent_path, result)) + + +def test_parent_hooks_see_a_subagent_run(): + lead, _ = _agents() + watch = _Watch() + lead.config.hooks = watch + acompletion, _ = _scripted( + { + "lead": [_asks(_call("researcher", "find x")), _make_completion("x is 5")], + "child": [_make_completion("found: 5")], + } + ) + with patch("litellm.acompletion", new=acompletion): + assert lead.run("what is x?") == "x is 5" + + assert [s[:2] for s in watch.seen] == [ + ("start", ("researcher",)), + ("end", ("researcher",)), + ] + assert watch.seen[0][2] == "find x" + result = watch.seen[1][2] + assert isinstance(result, RunResult) + assert result.content == "found: 5" + assert result.stop_reason == "completed" + + +def test_parent_hooks_see_a_failed_subagent_run(): + lead, _ = _agents(num_retries=0) + watch = _Watch() + lead.config.hooks = watch + error = litellm.APIConnectionError(message="down", llm_provider="openai", model="m") + acompletion, _ = _scripted( + { + "lead": [_asks(_call("researcher", "find x")), _make_completion("sorry")], + "child": [error], + } + ) + with patch("litellm.acompletion", new=acompletion): + assert lead.run("what is x?") == "sorry" + + result = watch.seen[-1][2] + assert result.stop_reason == "error" + assert result.error is error + + +def test_subagent_hooks_go_to_the_direct_parent_only(): + """A subagent's own hooks see its subagents; its parent's hooks do not.""" + grandchild = Agent(_make_config(system_prompt="grandchild")) + child_watch, lead_watch = _Watch(), _Watch() + child = Agent( + _make_config(system_prompt="child", hooks=child_watch), + tools=[grandchild.as_tool("digger", "Digs")], + ) + lead = Agent( + _make_config(system_prompt="lead", hooks=lead_watch), + tools=[child.as_tool("researcher", "Researches")], + ) + acompletion, _ = _scripted( + { + "lead": [_asks(_call("researcher", "find x")), _make_completion("x is 5")], + "child": [_asks(_call("digger", "dig")), _make_completion("found: 5")], + "grandchild": [_make_completion("5")], + } + ) + with patch("litellm.acompletion", new=acompletion): + assert lead.run("what is x?") == "x is 5" + + assert [s[:2] for s in lead_watch.seen] == [ + ("start", ("researcher",)), + ("end", ("researcher",)), + ] + assert [s[:2] for s in child_watch.seen] == [ + ("start", ("researcher", "digger")), + ("end", ("researcher", "digger")), + ] + + +@pytest.mark.asyncio +async def test_parent_hooks_see_a_cancelled_subagent_run(): + started = asyncio.Event() + + class Waits(AgentHooks): + async def on_llm_start(self, messages): + started.set() + await asyncio.sleep(10) + + lead, child = _agents() + child.config.hooks = Waits() + watch = _Watch() + lead.config.hooks = watch + acompletion, _ = _scripted( + { + "lead": [_asks(_call("researcher", "find x"))], + "child": [_make_completion("found: 5")], + } + ) + with patch("litellm.acompletion", new=acompletion): + handle = lead.start("what is x?", stream=False) + await started.wait() + handle.cancel() + result = await handle + + assert result.stop_reason == "cancelled" + assert [(s[0], s[1], s[2].stop_reason) for s in watch.seen[1:]] == [ + ("end", ("researcher",), "cancelled") + ] diff --git a/tests/test_retries.py b/tests/test_retries.py index 3632aa0..e8fca54 100644 --- a/tests/test_retries.py +++ b/tests/test_retries.py @@ -204,6 +204,7 @@ def test_router_retries_by_its_own_policy(): def test_each_attempt_fires_the_llm_hooks(delays): hooks = MagicMock(spec=AgentHooks) + hooks.on_run_start.return_value = None error = _overloaded() with patch("litellm.acompletion", new=AsyncMock(side_effect=[error, _response()])): Agent(AgentConfig(model=MODEL, hooks=hooks)).run("hi") diff --git a/website/src/content/docs/api-reference.md b/website/src/content/docs/api-reference.md index 04df252..9c0ee4f 100644 --- a/website/src/content/docs/api-reference.md +++ b/website/src/content/docs/api-reference.md @@ -77,6 +77,7 @@ class AgentConfig(BaseModel): max_parallel_tool_calls: int = 10 tool_timeout: Optional[float] = None # seconds hooks: Optional[AgentHooks] = None + hook_timeout: Optional[float] = None # seconds num_retries: int = 2 timeout: float = 600 # seconds stream_idle_timeout: float = 120 # seconds @@ -108,6 +109,7 @@ class AgentConfig(BaseModel): | `max_parallel_tool_calls` | `10` | Most tool calls of one step that run at the same time. | | `tool_timeout` | `None` | Seconds a tool call may run before it is cancelled and fails. A tool's own `timeout` wins. | | `hooks` | `None` | `AgentHooks` instance for lifecycle callbacks and tool approval. | +| `hook_timeout` | `None` | Seconds each async hook call may run before it raises `TimeoutError`. See [Hook timeouts](/guides/hooks/#hook-timeouts). | | `num_retries` | `2` | Retries of a completion after a rate limit, overload, 5xx, timeout or connection error. | | `timeout` | `600` | Seconds LiteLLM's HTTP client waits to connect and for each read or write. | | `stream_idle_timeout` | `120` | Seconds a stream may go without a chunk after its first. | @@ -279,10 +281,13 @@ class DeniedToolCall(BaseModel): Lifecycle callback base class. Subclass and override any methods you need. ```python +# Any method may be async def. MaybeAwaitable[T] is T or an awaitable of T. class AgentHooks: - def on_run_start(self, input_message: Union[str, List[Dict[str, Any]]]) -> None: ... + def on_run_start(self, input_message: Union[str, List[Dict[str, Any]]]) -> MaybeAwaitable[Optional[UserContent]]: ... def on_run_end(self, content: str) -> None: ... def on_run_error(self, error: BaseException) -> None: ... + def on_subagent_start(self, agent_path: Tuple[str, ...], input_message: str) -> None: ... + def on_subagent_end(self, agent_path: Tuple[str, ...], result: RunResult) -> None: ... def on_llm_start(self, messages: List[Dict[str, Any]]) -> None: ... def on_llm_end(self, response: Any) -> None: ... def on_llm_error(self, error: Exception) -> None: ... @@ -294,9 +299,11 @@ class AgentHooks: | Method | When it fires | Return value | |---|---|---| -| `on_run_start` | Once at the start of `run()`, `arun()`, `stream()`, or `astream()`, with the input text or its list of content parts | `None` | +| `on_run_start` | Once at the start of `run()`, `arun()`, `stream()`, or `astream()`, with the input text or its list of content parts | Text or content parts to replace the input, or `None` to keep it | | `on_run_end` | When a run finishes, streamed or not | `None` | | `on_run_error` | Instead of `on_run_end` when a run raises, is cancelled, or its stream is closed early. A run its caller stopped (a stream closed early) gets a `CancelledError` whose `args` are `(RUN_STOPPED,)`, from `cyclops.core.hooks`. | `None` | +| `on_subagent_start` | Before a subagent run nested in this agent's run starts, with its `agent_path` and input | `None` | +| `on_subagent_end` | When that subagent run ends, however it ended, with its `agent_path` and `RunResult` | `None` | | `on_llm_start` | Before each LiteLLM completion call | `None` | | `on_llm_end` | After each completion; for a stream, with the assembled response | `None` | | `on_llm_error` | When a LiteLLM call raises an exception | `None` | diff --git a/website/src/content/docs/guides/agents.mdx b/website/src/content/docs/guides/agents.mdx index 21bf802..82e9ef7 100644 --- a/website/src/content/docs/guides/agents.mdx +++ b/website/src/content/docs/guides/agents.mdx @@ -40,6 +40,7 @@ config = AgentConfig( | `max_parallel_tool_calls` | `int` | `10` | Most tool calls of one step that run at the same time; at least 1. See [Parallel calls and timeouts](/guides/tools/#parallel-calls-and-timeouts). | | `tool_timeout` | `float \| None` | `None` | Seconds a tool call may run before it is cancelled and returns an error. A tool's own `timeout` wins. | | `hooks` | `AgentHooks \| None` | `None` | Lifecycle callbacks for observability and tool approval. See [Hooks](/guides/hooks/). | +| `hook_timeout` | `float \| None` | `None` | Seconds each async hook call may run before it raises `TimeoutError`. See [Hook timeouts](/guides/hooks/#hook-timeouts). | | `num_retries` | `int` | `2` | Retries of a completion after a rate limit, overload, 5xx, timeout or connection error. See [Retries and timeouts](#retries-and-timeouts). | | `timeout` | `float` | `600` | Seconds LiteLLM's HTTP client waits to connect and for each read or write. | | `stream_idle_timeout` | `float` | `120` | Seconds a stream may go without a chunk after its first. | diff --git a/website/src/content/docs/guides/hooks.mdx b/website/src/content/docs/guides/hooks.mdx index 3190bad..4b131ff 100644 --- a/website/src/content/docs/guides/hooks.mdx +++ b/website/src/content/docs/guides/hooks.mdx @@ -6,7 +6,7 @@ description: Observe and control agent execution with lifecycle callbacks. import exampleSrc from '../../../../../examples/hooks_example.py?raw'; import { Code } from '@astrojs/starlight/components'; -`AgentHooks` is a lifecycle callback system that lets you observe and control every stage of an agent run: from the initial call, through each LLM request, to every tool execution. Subclass `AgentHooks`, override the methods you need, and pass an instance to `AgentConfig`. +`AgentHooks` is a lifecycle callback system that lets you observe and control every stage of an agent run: from the initial call, through each LLM request, to every tool execution. Subclass `AgentHooks`, override the methods you need, and pass an instance to `AgentConfig`. Each method may be a plain method or an `async def` one; an async one is awaited. ## Quick example @@ -39,9 +39,11 @@ agent.run("What is the weather in London?") | Method | When it fires | Return value | |---|---|---| -| `on_run_start(input_message)` | Once at the start of `run()`, `arun()`, `stream()`, or `astream()`, with the input text or its list of content parts | `None` | +| `on_run_start(input_message)` | Once at the start of `run()`, `arun()`, `stream()`, or `astream()`, with the input text or its list of content parts | Text or content parts to replace the input, or `None` to keep it | | `on_run_end(content)` | When a run finishes, streamed or not | `None` | | `on_run_error(error)` | Instead of `on_run_end` when a run raises, is cancelled, or its stream is closed early. A run its caller stopped (`handle.cancel()`, or a stream closed early) gets a `CancelledError` whose `args` are `(RUN_STOPPED,)`, from `cyclops.core.hooks`. A handle cancelled before its run started fires no hooks at all; its events still end with `RunFinished`. | `None` | +| `on_subagent_start(agent_path, input_message)` | Before a [subagent](/guides/subagents/) run nested in this agent's run starts. `agent_path` names the nested agents down to it, outermost first, as in events. | `None` | +| `on_subagent_end(agent_path, result)` | When that subagent run ends, with its `RunResult`, whether it completed, failed or was cancelled | `None` | | `on_llm_start(messages)` | Before each LiteLLM completion call | `None` | | `on_llm_end(response)` | After each LiteLLM completion; for a stream, with the assembled response | `None` | | `on_llm_error(error)` | When a LiteLLM call raises an exception | `None` | @@ -54,9 +56,49 @@ All methods are no-ops by default. Override only the ones you need. In the tool hooks, `cyclops.core.hooks.current_tool_call_id()` returns the id of the native tool call being run (`None` in naive mode). Each native call runs in its own asyncio task, so the id is exact when calls run in parallel. +## Rewriting the input with on_run_start + +`on_run_start` may return text or a list of content parts to use in place of the run's input, for instance to add context the model should see with the message. `None` keeps the input. The replacement is checked as run input is, so content the model can't take fails the run with `ValueError` and fires `on_run_error`, and it is what the model and the session get. + +```python +from datetime import date + +from cyclops import AgentConfig, AgentHooks + + +class AddDate(AgentHooks): + def on_run_start(self, input_message): + today = f"Today is {date.today()}." + if isinstance(input_message, str): + return f"{today}\n\n{input_message}" + return [{"type": "text", "text": today}, *input_message] + + +config = AgentConfig(model="gpt-4o-mini", hooks=AddDate()) +``` + +## Subagent runs + +A subagent run fires its own agent's hooks, from `on_run_start` to `on_run_end`. The calling agent's hooks see it as one tool call, and also get `on_subagent_start` and `on_subagent_end` around it. Only the direct caller's hooks get them: for a subagent of a subagent, give the middle agent the same hooks to see it from the top. + +```python +class SubagentLog(AgentHooks): + def on_subagent_start(self, agent_path, input_message): + print(f"[{'/'.join(agent_path)}] started: {input_message}") + + def on_subagent_end(self, agent_path, result): + print(f"[{'/'.join(agent_path)}] {result.stop_reason}: {result.content}") +``` + +## Hook timeouts + +`AgentConfig.hook_timeout` caps how many seconds each async hook call may run. A hook that takes longer is cancelled and raises `TimeoutError`, and the run treats it as a hook that raised: in `on_tool_start` it fails the run, as middleware that raises does, so a slow approval never lets a call through. Without `hook_timeout`, hooks run as long as they take. + +Plain hooks run inline on the event loop and are not bounded, since asyncio cannot interrupt blocking code. Write a hook as `async def` to bound it with `hook_timeout`. + ## Tool approval with on_tool_start -`on_tool_start` is the only hook with side effects: returning the string `"deny"` blocks the tool call. Any other return value (including `None`) allows it. The agent receives `"Error: Tool '' was not approved"` as the tool result and continues. +`on_tool_start` controls execution: returning the string `"deny"` blocks the tool call. Any other return value (including `None`) allows it. The agent receives `"Error: Tool '' was not approved"` as the tool result and continues. ```python from cyclops import Agent, AgentConfig, AgentHooks @@ -226,7 +268,7 @@ class ErrorHooks(AgentHooks): ## Default behaviour -The default `AgentHooks` base class implements `on_tool_start` to return `"allow"` and all other methods as no-ops. You do not need to call `super()` in your overrides. +The default `AgentHooks` base class implements `on_tool_start` to return `"allow"`, `on_run_start` to return `None`, and all other methods as no-ops. You do not need to call `super()` in your overrides. ## Full example diff --git a/website/src/content/docs/guides/subagents.mdx b/website/src/content/docs/guides/subagents.mdx index d77e82e..2e05e6e 100644 --- a/website/src/content/docs/guides/subagents.mdx +++ b/website/src/content/docs/guides/subagents.mdx @@ -44,7 +44,7 @@ A call from another agent's run nests the subagent's run in it: - **Events.** The subagent's events go to the parent's event stream with `agent_path` extended by the tool name: `("researcher",)` for the researcher's events, `("researcher", "checker")` for an agent the researcher calls in turn. Its `RunFinished` is forwarded too, so filter on `agent_path` to find the parent's last event. `astream()` and `stream()` yield only the text of the agent you ran. The subagent's run streams when the parent's does. - **Usage and budgets.** The subagent's usage counts in its own `RunResult` and in every run it is nested in, so the parent's `usage` covers all of them and its `max_total_tokens` and `max_cost` apply to all of them. A subagent checks its own limits and those of every run above it before each step, its first included, so it stops with `budget` once the parent's budget is spent, and a call made or waiting for a slot after that makes no completion. `steps` and `StepFinished.usage` count only an agent's own completions. `usage_by_model` splits the parent's usage by model, so subagents on other models keep their own entries. - **Middleware and guards.** The subagent's tool calls go through its own `AgentConfig.middleware`, and its answers through its own guards. Their `ToolCallContext.agent_path` and `GuardContext.agent_path` hold the nested path, so middleware shared between agents can tell the calls apart. The parent's middleware sees the subagent call itself, like any other tool call. -- **Hooks and tracing.** Each agent fires its own hooks. With `TelemetryHooks`, the subagent's `invoke_agent` span is a child of the parent's `execute_tool` span. +- **Hooks and tracing.** Each agent fires its own hooks, and the calling agent's hooks also get `on_subagent_start` and `on_subagent_end` around each subagent run. With `TelemetryHooks`, the subagent's `invoke_agent` span is a child of the parent's `execute_tool` span. ```python async for event in lead.astream_events("Compare the populations of Paris and Berlin."):