Skip to content
Draft
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
6 changes: 4 additions & 2 deletions src/agents/_run_state_agent_identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
from .agent import Agent
from .handoffs import Handoff
from .logger import logger
from .sandbox.capabilities.capability import Capability
from .sandbox.session.base_sandbox_session import BaseSandboxSession
from .tool import (
ApplyPatchTool,
ComputerTool,
Expand Down Expand Up @@ -191,6 +189,8 @@ def _tool_identity_signature(tool: Any) -> dict[str, Any]:


def _is_capability_runtime_only_value(value: Any) -> bool:
from .sandbox.session.base_sandbox_session import BaseSandboxSession

return isinstance(
value,
(
Expand Down Expand Up @@ -257,6 +257,8 @@ def _normalize_capability_identity_value(
finally:
seen.remove(object_id)

from .sandbox.capabilities.capability import Capability

if isinstance(value, Capability):
seen.add(object_id)
try:
Expand Down
5 changes: 3 additions & 2 deletions src/agents/function_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
from dataclasses import dataclass
from typing import Annotated, Any, Literal, cast, get_args, get_origin, get_type_hints

# griffelib exposes the `griffe` package at runtime but currently does not ship typing markers.
from griffe import Docstring, DocstringSectionKind # type: ignore[import-untyped]
from pydantic import BaseModel, ConfigDict, Field, create_model
from pydantic.fields import FieldInfo

Expand Down Expand Up @@ -261,6 +259,9 @@ def generate_func_documentation(
if not doc:
return FuncDocumentation(name=name, description=None, param_descriptions=None)

# Griffe is only needed when the function has documentation to parse.
from griffe import Docstring, DocstringSectionKind # type: ignore[import-untyped]

# Resolve the style against the original docstring before any normalization.
resolved_style = style or _detect_docstring_style(doc)
if resolved_style == "google":
Expand Down
48 changes: 47 additions & 1 deletion src/agents/lifecycle.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
from typing import Any, Generic
from collections.abc import Awaitable, Callable
from types import FunctionType, MethodType
from typing import Any, Generic, cast

from typing_extensions import TypeVar

from .agent import Agent, AgentBase
from .items import ModelResponse, TResponseInputItem
from .run_context import AgentHookContext, RunContextWrapper, TContext
from .tool import Tool
from .util import _coro
from .util._asyncio_tasks import gather_with_cancel

TAgent = TypeVar("TAgent", bound=AgentBase, default=AgentBase)

Expand Down Expand Up @@ -231,3 +235,45 @@ async def on_llm_end(

AgentHooks = AgentHooksBase[TContext, Agent]
"""Agent hooks for `Agent`s."""


_DEFAULT_HOOK_CALLBACKS = frozenset(
callback
for base in (RunHooksBase, AgentHooksBase)
for name, callback in vars(base).items()
if name.startswith("on_")
)


_SKIP_HOOK = object()


def _hook_awaitable(callback: Callable[..., Awaitable[Any]], *args: Any) -> object:
"""Invoke a hook factory before resolving the next hook reference."""
from .run_internal.guardrails import input_guardrail_dispatch_is_preserved

if (
not input_guardrail_dispatch_is_preserved()
and type(callback) is MethodType
and type(callback.__func__) is FunctionType
and callback.__func__ in _DEFAULT_HOOK_CALLBACKS
):
return _SKIP_HOOK
return callback(*args)


async def _run_hook_callbacks(*callbacks: object) -> None:
"""Gather real hook awaitables while retaining their task and cancellation boundaries."""
from .run_internal.guardrails import input_guardrail_dispatch_is_preserved

if input_guardrail_dispatch_is_preserved():
awaitables = [
_coro.noop_coroutine() if callback is _SKIP_HOOK else cast(Awaitable[Any], callback)
for callback in callbacks
]
else:
awaitables = [
cast(Awaitable[Any], callback) for callback in callbacks if callback is not _SKIP_HOOK
]
if awaitables:
await gather_with_cancel(*awaitables)
10 changes: 8 additions & 2 deletions src/agents/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,10 @@
build_run_error_data,
resolve_run_error_handler_result,
)
from .run_internal.guardrails import input_guardrail_tool_gate_scope
from .run_internal.guardrails import (
input_guardrail_tool_gate_scope,
preserve_parallel_input_guardrail_dispatch,
)
from .run_internal.items import (
copy_input_items,
ensure_nested_history_run_item_occurrence_key,
Expand Down Expand Up @@ -168,7 +171,6 @@
serialize_tool_use_tracker,
)
from .run_state import RunState
from .sandbox.memory.rollouts import terminal_metadata_for_exception
from .sandbox.runtime import SandboxRuntime
from .tool import dispose_resolved_computers
from .tool_guardrails import ToolInputGuardrailResult, ToolOutputGuardrailResult
Expand Down Expand Up @@ -1059,6 +1061,8 @@ def _mark_response_hooks_started() -> None:
g for g in all_input_guardrails if not g.run_in_parallel
]
parallel_guardrails = [g for g in all_input_guardrails if g.run_in_parallel]
if parallel_guardrails:
preserve_parallel_input_guardrail_dispatch()
if sandbox_runtime.enabled and sequential_guardrails:
# Blocking first-turn guardrails must run before sandbox prep so a tripwire
# can prevent session creation, startup, or live-session mutation.
Expand Down Expand Up @@ -2476,6 +2480,8 @@ def on_tool_error_selected() -> None:
input_override=memory_input,
)
elif run_exception is not None:
from .sandbox.memory.rollouts import terminal_metadata_for_exception

current_step = getattr(run_state, "_current_step", None)
await sandbox_runtime.enqueue_memory_payload(
input=memory_input,
Expand Down
9 changes: 6 additions & 3 deletions src/agents/run_internal/agent_tool_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,12 @@ def _observe_tools(active: list[_ToolResolution], tools: tuple[Tool, ...]) -> No
if len(active) > 1 and any(
resolution.tools_assigned
or len(resolution.initial_tools) != len(tools)
or any(
before is not after
for before, after in zip(resolution.initial_tools, tools, strict=False)
or (
resolution.initial_tools is not tools
and any(
before is not after
for before, after in zip(resolution.initial_tools, tools, strict=False)
)
)
for resolution in active
):
Expand Down
13 changes: 13 additions & 0 deletions src/agents/run_internal/guardrails.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ class _InputGuardrailToolGate:
should_cancel: Callable[[], bool] | None = None
rejection: InputGuardrailResult | None = None
cancel_tools: set[Callable[[], None]] = field(default_factory=set)
preserve_dispatch: bool = False


_input_guardrail_tool_gate: ContextVar[_InputGuardrailToolGate | None] = ContextVar(
Expand All @@ -56,6 +57,18 @@ def input_guardrail_tool_gate_scope(
_input_guardrail_tool_gate.reset(token)


def preserve_parallel_input_guardrail_dispatch() -> None:
"""Keep original dispatch checkpoints for a run racing parallel input guardrails."""
gate = _input_guardrail_tool_gate.get()
if gate is not None:
gate.preserve_dispatch = True


def input_guardrail_dispatch_is_preserved() -> bool:
gate = _input_guardrail_tool_gate.get()
return gate is not None and gate.preserve_dispatch


def _reject_input_guardrail_tools(result: InputGuardrailResult) -> None:
gate = _input_guardrail_tool_gate.get()
if gate is not None and gate.rejection is None:
Expand Down
Loading
Loading