Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions cyclops/core/compaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
10 changes: 4 additions & 6 deletions cyclops/core/completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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()
Expand Down
4 changes: 2 additions & 2 deletions cyclops/core/fallback.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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():
Expand Down
90 changes: 73 additions & 17 deletions cyclops/core/hooks.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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(
Comment thread
gopaljigaur marked this conversation as resolved.
Resolved
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"]
21 changes: 9 additions & 12 deletions cyclops/core/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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)
Expand All @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down
16 changes: 12 additions & 4 deletions cyclops/core/subagents.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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__(
Expand Down Expand Up @@ -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"]
29 changes: 21 additions & 8 deletions cyclops/core/tool_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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] = []
Expand Down
6 changes: 6 additions & 0 deletions cyclops/core/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading
Loading