perf(agent): skip transcript snapshots without run hooks

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-15 10:48:59 +08:00
1 parent 2ad0da786d
commit c58bfa71bc
5 files changed
+151 -8

No files matched your search

+15
View File
@@ -73,6 +73,13 @@ class AgentHook:
def wants_streaming(self) -> bool:
return False
def has_run_hooks(self) -> bool:
"""Whether run-level callbacks consume a detached context snapshot."""
return any(
getattr(getattr(self, name), "__func__", None) is not getattr(AgentHook, name)
for name in ("before_run", "after_run", "on_error", "on_finally")
)
async def before_run(self, context: AgentRunHookContext) -> None:
pass
@@ -172,6 +179,14 @@ class CompositeHook(AgentHook):
def wants_streaming(self) -> bool:
return any(h.wants_streaming() for h in self._hooks)
def has_run_hooks(self) -> bool:
if any(
getattr(getattr(self, name), "__func__", None) is not getattr(CompositeHook, name)
for name in ("before_run", "after_run", "on_error", "on_finally")
):
return True
return any(h.has_run_hooks() for h in self._hooks)
async def _for_each_hook_safe(self, method_name: str, *args: Any, **kwargs: Any) -> None:
for h in self._hooks:
if getattr(h, "_reraise", False):
+6 -5
View File
@@ -291,8 +291,9 @@ class AgentRunner:
async def run(self, spec: AgentRunSpec) -> AgentRunResult:
hook = spec.hook or AgentHook()
has_run_hooks = hook.has_run_hooks()
messages, compaction = self._initial_transcript_and_compaction(spec)
context = AgentRunHookContext(messages=deepcopy(messages))
context = AgentRunHookContext(messages=deepcopy(messages) if has_run_hooks else [])
llm_usage_source_token = bind_llm_usage_source(
spec.llm_usage_source or source_from_session_key(spec.session_key)
)
@@ -301,20 +302,20 @@ class AgentRunner:
await hook.before_run(context)
result = await self._run_core(spec, hook, messages, compaction)
except asyncio.CancelledError as exc:
context.messages = deepcopy(messages)
context.messages = deepcopy(messages) if has_run_hooks else []
context.stop_reason = "cancelled"
context.error = None
context.exception = exc
raise
except Exception as exc:
context.messages = deepcopy(messages)
context.messages = deepcopy(messages) if has_run_hooks else []
context.stop_reason = "error"
context.error = f"Error: {type(exc).__name__}: {exc}"
context.exception = exc
await hook.on_error(context)
raise
else:
context.messages = deepcopy(result.messages)
context.messages = deepcopy(result.messages) if has_run_hooks else []
context.final_content = result.final_content
context.tools_used = list(result.tools_used)
context.usage = result.usage
@@ -329,7 +330,7 @@ class AgentRunner:
return result
finally:
try:
context.messages = deepcopy(messages)
context.messages = deepcopy(messages) if has_run_hooks else []
if context.exception is None:
await hook.on_finally(context)
else: