Events¶
The loop reports every fixed point of a run as an event: a task arriving, a model call, a response, a tool call and its result, the end of the run. Blocks attached to the event bus observe these events for logging, tracing or a user interface.
Some events can also be intercepted: allowed, denied or changed before they take effect. Permission checks, human approval and safety limits are built this way, outside the loop and outside the tools.
The interface¶
class EventBus(ABC):
def emit(self, e: LoopEvent) -> None: ... # observation: logging, tracing, UI
async def intercept(self, e: InterceptableEvent) -> Decision: ... # permissions, approval, hooks
Decision = Literal["allow"] | Deny | Modify
@dataclass
class Deny:
reason: str = ""
@dataclass
class Modify:
value: Any
emit() is called for every event and returns nothing. intercept() is called at the points where a decision is possible, and may wait, for example for a human to approve a call.
Events¶
Every event is a dictionary with a type and the run_id of the run it belongs to:
prompt: a task is about to be added to the conversation, with itscontent.request: the loop is about to call the model, with the number ofmessages.delta: a piece of the response as the model produces it: text, thinking or tool input.response: the model answered, with thestop_reasonand theusage.tool_call: a tool is about to run, with thecall_id, the toolnameand itsinput.tool_result: a tool ran, with itscontentandis_error.stop: the model ended its turn.compact: the context policy is about to compact the conversation.done: the run is over, with thereason.
Interception points¶
What a decision means depends on the event:
prompt:Denyblocks the run and the reason is returned as the answer;Modifyreplaces the task's content.tool_call:Denyanswers the call with an error that carries the reason;Modifyreplaces the input.tool_result:Denyreplaces the result with an error;Modifyreplaces the content.stop:Denykeeps the run going, and the reason becomes the next message to the model.compact:Denyskips the compaction.
flowchart TB
Call["Tool call from the model"] --> Intercept{"intercept()"}
Intercept -->|"allow"| Tool["The tool runs"]
Intercept -->|"Modify(input)"| Changed["The tool runs<br/>with the changed input"]
Intercept -->|"Deny(reason)"| Error["An error result<br/>goes back to the model"]
A denied call is not executed. The model receives an error result with the reason and can tell the user or try something else.
A bus¶
A bus that prints tool calls and results, refuses tasks about passwords and lower-cases note titles:
class AuditBus(EventBus):
"""Prints every tool call and result, refuses tasks that mention passwords, and lower-cases note titles."""
def emit(self, e):
if e["type"] == "tool_call":
print(f" call {e['name']}({e['input']})")
elif e["type"] == "tool_result":
print(f" result {e['content'][0]['text']} (error: {e['is_error']})")
async def intercept(self, e):
if e["type"] == "prompt" and "password" in str(e["content"]).lower():
return Deny("tasks about passwords are not accepted")
if e["type"] == "tool_call" and "title" in e["input"]:
return Modify({**e["input"], "title": e["input"]["title"].lower()})
return "allow"
agent = ComposedAgent(
model=model,
harness=Harness(loop=StandardLoop(), budget=TreeBudget(limit={"steps": 5}), tools=tools, events=AuditBus()),
)
for task in ["Note the trip.", "Store my password."]:
print(task)
outcome = await agent.run(task)
print(f" -> {outcome.reason}: {message_text(outcome.final)}")
print(sorted(NOTES))
Output:
Note the trip.
call write_note({'title': 'Trip', 'text': 'book the train'})
result saved trip (error: False)
-> end_turn: saved trip
Store my password.
-> blocked: tasks about passwords are not accepted
['groceries', 'trip']
The tool_call event still shows the input the model asked for, Trip, while the tool received the changed input and saved trip. The second task never reached the model.
Guard rules¶
GuardBus wraps another bus and adds rules on tool calls. Events pass through to the inner bus unchanged, and each tool call must get past every rule. A rule is a function that takes the tool call event and returns None for no objection, or a decision with an explanation:
def short_notes(e):
"""A custom rule: None means no objection."""
if e["name"] == "write_note" and len(e["input"]["text"]) > 100:
return Deny("notes are limited to 100 characters"), "write_note denied, the note is too long"
return None
guard = GuardBus(
TranscriptBus(label="notes_agent"),
forbid(tool="delete_note", reason="notes are never deleted"),
short_notes,
)
agent = ComposedAgent(
model=model,
harness=Harness(loop=StandardLoop(), budget=TreeBudget(limit={"steps": 5}), tools=tools, events=guard),
)
await agent.run("Clean up the groceries note.")
await agent.run("Write a long essay.")
Output:
[notes_agent] → delete_note(title='groceries')
[notes_agent] ⚑ guard: delete_note denied, notes are never deleted
[notes_agent] ✗ delete_note: the call to delete_note was denied: notes are never deleted
[notes_agent] ■ done (end_turn)
[notes_agent] → write_note(title='essay', text='word word word word word word word word word word word word w…
[notes_agent] ⚑ guard: write_note denied, the note is too long
[notes_agent] ✗ write_note: the call to write_note was denied: notes are limited to 100 characters
[notes_agent] ■ done (end_turn)
forbid(tool, reason) denies a tool outright. clamp(tool, field, lo, hi) keeps a numeric input within bounds by changing the call instead of denying it; the research team tutorial uses it. Rules see the changes made by earlier rules, and the first denial ends the check.
Ready blocks¶
TranscriptBus: prints tool calls and results as a tree, indented by how deep the agent is nested.
GuardBus, forbid() and clamp(): safety rules on tool calls, around any other bus.
The demo agent in the repository's examples/ directory has LoggingEventBus, which logs every event to stderr and denies tools by name.