Skip to content

Commit 39324dd

Browse files
committed
Merge main and preserve tool guardrail result forwarding
2 parents af69e37 + 8fd9a7c commit 39324dd

48 files changed

Lines changed: 7593 additions & 368 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/human_in_the_loop.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ agent = Agent(
4444

4545
For local `ShellTool` and `ApplyPatchTool`, approval is opt-in: `needs_approval` defaults to `False`. An `on_approval` callback alone does not enable approval. Set `needs_approval=True` or a callable approval policy as well; the SDK invokes the callback only for calls that require approval and have no existing approval decision. See [approval for local shell and file edits](tools.md#approval-for-local-shell-and-file-edits) for execution responsibilities and example configurations.
4646

47+
For `ComputerTool`, use `on_safety_check` to accept or reject safety checks returned by the Responses API. This callback runs only for computer calls with pending checks and does not use the pause-and-resume approval flow described on this page. See [computer safety checks](tools.md#pending-computer-safety-checks) for details and an example.
48+
4749
## How the approval flow works
4850

4951
1. When the model emits a tool call, the runner evaluates its approval rule (`needs_approval`, `require_approval`, or the hosted MCP equivalent).

‎docs/tools.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,33 @@ agent = Agent(
330330
)
331331
```
332332

333+
#### Pending computer safety checks
334+
335+
The Responses API can include `pending_safety_checks` in a `computer_call` to flag concerns for your application to review. Each check has an `id` and optional `code` and `message` fields that describe the type of concern and provide details. These checks come from the API; the Agents SDK passes them to your callback. See the [Responses API reference](https://developers.openai.com/api/reference/resources/responses/methods/create) for `pending_safety_checks` and `acknowledged_safety_checks`, and the [computer-use safety guidance](https://developers.openai.com/api/docs/guides/tools-computer-use#run-safely) for application-level precautions.
336+
337+
Configure [`ComputerTool.on_safety_check`][agents.tool.ComputerTool.on_safety_check] to decide whether to proceed with a flagged computer call. The SDK invokes this callback only when the call includes pending checks, before executing the call's actions.
338+
339+
The callback receives one [`ComputerToolSafetyCheckData`][agents.tool.ComputerToolSafetyCheckData] at a time. Return `True` to acknowledge that check. Return `False` to raise [`UserError`][agents.exceptions.UserError] before the call's actions or screenshot execute. The SDK requires all reported checks to be acknowledged when a callback is configured. The callback can be synchronous or asynchronous.
340+
341+
If `on_safety_check` is omitted, the SDK proceeds with execution and leaves the checks unacknowledged. The SDK does not prompt a person automatically. Configure the callback explicitly when your application requires review of flagged calls. For example, this conservative policy rejects every flagged call:
342+
343+
```python
344+
from agents import AsyncComputer, Computer, ComputerTool
345+
from agents.tool import ComputerToolSafetyCheckData
346+
347+
348+
def reject_flagged_call(data: ComputerToolSafetyCheckData) -> bool:
349+
return False
350+
351+
352+
def computer_tool_with_safety_checks(computer: Computer | AsyncComputer) -> ComputerTool:
353+
return ComputerTool(computer=computer, on_safety_check=reject_flagged_call)
354+
```
355+
356+
To allow reviewed calls, replace `reject_flagged_call` with a callback that presents `data.safety_check` and the proposed `data.tool_call` to your application's reviewer, waits for a decision, and returns that decision. Treat unknown check codes as requiring review as well.
357+
358+
Computer calls without pending checks do not invoke this callback. Enforce any policy that must apply to every computer action in your computer harness. To collect a person's decision, your callback must arrange that interaction and return the decision; the SDK does not populate `RunResult.interruptions` or use the pause-and-resume flow described in [Human-in-the-loop](human_in_the_loop.md).
359+
333360
## Function tools
334361

335362
You can use any Python function as a tool. The Agents SDK will set up the tool automatically:
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
openai-agents
22
httpx2>=2.13.1
3-
pyjwt>=2.15.0
3+
pyjwt>=2.15.1
44
python-multipart>=0.0.32
55
urllib3>=2.8.0
66
fastapi
77
starlette>=1.7.0
88
uvicorn[standard]
99
websockets
1010
python-dotenv>=1.2.3
11-
twilio>=9.11.1,<10
11+
twilio>=9.11.2,<10
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
fastapi>=0.141.1
22
starlette>=1.7.0
3-
openai>=3.19.1,<4
3+
openai>=3.20.0,<4
44
httpx2>=2.13.1
5-
uvicorn[standard]>=0.53.0
5+
uvicorn[standard]>=0.54.0
66
python-dotenv>=1.2.3

‎src/agents/extensions/memory/redis_session.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import redis.asyncio as redis
3434
import redis.asyncio.connection as redis_connection
3535
from redis.asyncio import BlockingConnectionPool, Redis
36+
from redis.asyncio.cluster import RedisCluster
3637
from redis.event import AsyncAfterConnectionReleasedEvent
3738
from redis.exceptions import ConnectionError as RedisConnectionError, ResponseError, WatchError
3839
except ImportError as e:
@@ -372,7 +373,8 @@ def __init__(
372373
373374
Args:
374375
session_id (str): Unique identifier for the conversation.
375-
redis_client (Redis[bytes]): A pre-configured Redis async client.
376+
redis_client (Redis[bytes]): A pre-configured standalone Redis async client.
377+
RedisCluster clients are not supported.
376378
key_prefix (str, optional): Prefix for Redis keys to avoid collisions.
377379
Defaults to "agents:session".
378380
ttl (int | None, optional): Time-to-live in seconds for session data.
@@ -381,6 +383,12 @@ def __init__(
381383
session_settings (SessionSettings | None): Session configuration settings including
382384
default limit for retrieving items. If None, uses default SessionSettings().
383385
"""
386+
if isinstance(redis_client, RedisCluster):
387+
raise TypeError(
388+
"RedisSession does not support RedisCluster clients. "
389+
"Use redis.asyncio.Redis connected to a standalone Redis server, "
390+
"or implement a custom Session backend for Redis Cluster."
391+
)
384392
self.session_id = session_id
385393
self.session_settings = (
386394
coerce_session_settings(session_settings)

‎src/agents/result.py‎

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from pydantic import GetCoreSchemaHandler
1212
from pydantic_core import core_schema
1313

14+
from ._tool_invocation import tool_output_identity
1415
from .agent import Agent
1516
from .agent_output import AgentOutputSchemaBase
1617
from .exceptions import (
@@ -29,6 +30,7 @@
2930
ModelResponse,
3031
RunItem,
3132
ToolApprovalItem,
33+
ToolCallOutputItem,
3234
TResponseInputItem,
3335
)
3436
from .logger import log_tool_action_warning, logger
@@ -46,7 +48,7 @@
4648
ProcessedResponse,
4749
QueueCompleteSentinel,
4850
)
49-
from .run_state import RunState
51+
from .run_state import RunState, _PendingSessionWrite
5052
from .stream_events import StreamEvent
5153
from .tool_guardrails import ToolInputGuardrailResult, ToolOutputGuardrailResult
5254
from .tracing import Trace
@@ -156,6 +158,9 @@ def _populate_state_from_result(
156158
else:
157159
state._generated_prompt_cache_key = getattr(result, "_generated_prompt_cache_key", None)
158160
state._pending_input = copy.deepcopy(getattr(result, "_pending_input_for_state", []))
161+
state._pending_session_write = copy.deepcopy(
162+
getattr(result, "_pending_session_write", None)
163+
)
159164
state._current_step = getattr(result, "_current_step_for_state", None)
160165
state._reasoning_item_id_policy = getattr(result, "_reasoning_item_id_policy", None)
161166

@@ -289,6 +294,52 @@ def _input_items_for_result(
289294
if not isinstance(model_input_items, list):
290295
return session_items
291296

297+
if isinstance(result, RunResultStreaming):
298+
# Execution checkpoints can contain accepted outputs that final guardrails
299+
# have not released. Keep them private in every public history view.
300+
from .run_internal.blocked_output import (
301+
_current_response_boundary,
302+
_identity_sequence_start,
303+
)
304+
305+
processed = result._last_processed_response
306+
if processed is None and isinstance(result._state, RunState):
307+
processed = result._state._last_processed_response
308+
if processed is not None:
309+
legacy_public_outputs: set[tuple[str, str]] = set()
310+
start = _identity_sequence_start(model_input_items, processed.new_items)
311+
if start is None and isinstance(result._state, RunState):
312+
# Legacy first-turn checkpoints have no shared processed-item identities.
313+
# Prove their boundary against this result's captured history, since the
314+
# caller can resume the source RunState before inspecting an earlier result.
315+
boundary_state = copy.copy(result._state)
316+
boundary_state._generated_items = model_input_items
317+
boundary_state._session_items = result.new_items
318+
boundary_state._current_turn = result.current_turn
319+
boundary = _current_response_boundary((), processed, boundary_state)
320+
start = boundary.generated_start
321+
if start is None and boundary_state._terminal_unrecoverable:
322+
return session_items
323+
if start is not None and boundary.session_start is not None:
324+
public_start = boundary.session_start + len(boundary.processed_items)
325+
legacy_public_outputs = {
326+
identity
327+
for item in result.new_items[public_start:]
328+
if isinstance(item, ToolCallOutputItem)
329+
and (identity := tool_output_identity(item.raw_item)) is not None
330+
}
331+
if start is not None:
332+
output_start = start + len(processed.new_items)
333+
public_items = {id(item) for item in result.new_items}
334+
model_input_items = [
335+
item
336+
for index, item in enumerate(model_input_items)
337+
if index < output_start
338+
or not isinstance(item, ToolCallOutputItem)
339+
or id(item) in public_items
340+
or tool_output_identity(item.raw_item) in legacy_public_outputs
341+
]
342+
292343
# When the runner marks a divergence, generated_items already reflect the continuation input
293344
# chosen for the next local run after applying handoff/input filtering.
294345
return run_items_to_input_items(model_input_items, reasoning_item_id_policy)
@@ -367,6 +418,10 @@ class RunResultBase(abc.ABC):
367418
default_factory=list, init=False, repr=False
368419
)
369420
"""Pending input preserved when a non-streaming result is converted back to RunState."""
421+
_pending_session_write: _PendingSessionWrite | None = field(
422+
default=None, init=False, repr=False
423+
)
424+
"""Held pending Session write preserved when a non-streaming result becomes a RunState."""
370425
_current_step_for_state: Any = field(default=None, init=False, repr=False)
371426
"""Current step preserved when a non-streaming result is converted back to RunState."""
372427

@@ -1250,5 +1305,20 @@ def to_state(self) -> RunState[Any]:
12501305
previous_response_id=self._previous_response_id,
12511306
auto_previous_response_id=self._auto_previous_response_id,
12521307
)
1308+
if (
1309+
isinstance(self._state, RunState)
1310+
and self._last_processed_response is not None
1311+
and self._state._last_processed_response is self._last_processed_response
1312+
):
1313+
# The checkpoint retains records withheld from the public result until guardrails pass.
1314+
error = self.run_loop_exception
1315+
if error is not None and _is_error_data_redacted(error):
1316+
state._tool_input_guardrail_results = list(
1317+
self._state._tool_input_guardrail_results
1318+
)
1319+
if self._last_processed_response.tool_output_guardrail_result_start is not None:
1320+
state._tool_output_guardrail_results = list(
1321+
self._state._tool_output_guardrail_results
1322+
)
12531323
_copy_pending_nested_agent_tool_states(state, self)
12541324
return state

0 commit comments

Comments
 (0)