beta.agents: direct tool handlers returning bytes or Mapping with NaN/Infinity bypass output validation and submit success=True

Aperta
#4,303 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
62/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python

Direzione di ricerca

Start with result_event() in src/openai/lib/streaming/agents/_tools.py around lines 24-39, and compare it with _tool_output() in src/openai/lib/beta/agents/_tools.py, which already rejects bytes and uses allow_nan=False. Read test_nonfinite_model_results_rejected in tests/lib/beta/agents/test_tools.py for the expected pattern. Done when bytes-like and NaN/Infinity handler returns fail at stage="output", on_tool_error fires, and the tool result is submitted with success=False, with regression tests added for each case.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Confirm this is an issue with the Python library and not an underlying OpenAI API
  • This is an issue with the Python library
Describe the bug

In src/openai/lib/streaming/agents/_tools.py:24-39, result_event() normalizes and validates return values from direct tool_handlers before submitting agent.session.input.tool_result:

def result_event(call: AgentFunctionCallItem, output: ToolOutput) -> SessionInputParamAgentSessionInputToolResult:
    if isinstance(output, Mapping):
        output = json.dumps(dict(output), separators=(",", ":"))
    # Materialize iterators here so serialization failures produce a failed tool result.
    if output is not None and not isinstance(output, str):
        output = list(output)
    # Use the same content normalization as events.create before checking JSON encoding.
    output = maybe_transform(output, AgentFunctionCallOutputParam)
    openapi_dumps(output)

Two invalid direct-handler return values bypass the stage="output" error path (failed_event + on_tool_error) and are submitted with success=True:

  1. bytes / bytearray / memoryview are silently encoded as list[int]: Because binary buffers are non-str iterables, list(output) turns b"hello" into [104, 101, 108, 108, 111]. maybe_transform and openapi_dumps accept a list of integers, so the SDK sends {"success": true, "output": [104, 101, 108, 108, 111]} instead of rejecting binary output with TypeError at stage="output".
  2. Non-finite floats (NaN / Infinity / -Infinity) in Mapping outputs emit invalid RFC 8259 JSON: json.dumps(dict(output), separators=(",", ":")) omits allow_nan=False, producing '{"score":NaN}' / '{"ratio":Infinity}'. Because output is now a str, the subsequent openapi_dumps(output) check (allow_nan=False) sees a plain string and succeeds, forwarding invalid JSON inside output with success=True.

By contrast, sibling _tool_output() in src/openai/lib/beta/agents/_tools.py:119, 132 explicitly excludes (bytes, bytearray) and passes allow_nan=False (pinned by test_nonfinite_model_results_rejected in tests/lib/beta/agents/test_tools.py:481-490), and openapi_dumps() in src/openai/_utils/_json.py:24 enforces allow_nan=False.

To Reproduce
  1. Register direct tool_handlers on client.beta.agents.sessions.stream(...) (sync or async) returning b"hello" (or bytearray/memoryview) and {"score": float("nan")} (or float("inf") / -float("inf")).
  2. Attach an on_tool_error callback and consume the stream.
  3. Observe that on_tool_error is never called (count: 0) and both tool results are posted with success=True and corrupted/non-RFC-8259 payloads ([104, 101, 108, 108, 111] and '{"score":NaN}').
Code snippets
import json
import httpx2
from openai import OpenAI
from openai.lib.beta.agents import AgentToolError

submitted = []

def handle(request: httpx2.Request) -> httpx2.Response:
    session_obj = {
        "id": "session_test",
        "object": "agent.session",
        "status": "idle",
        "agent": {
            "id": "a", "object": "agent", "created_at": 1, "updated_at": 1,
            "metadata": {}, "model": "m", "multi_agent": {"enabled": True},
            "reasoning": {}, "service_tier": "default",
            "text": {"format": {"type": "text"}, "verbosity": "medium"}, "tools": [],
        },
        "created_at": 1, "last_active_at": 1, "environment": {"type": "none"},
        "metadata": {}, "required_actions": [], "vault_ids": [],
    }
    if request.method == "GET" and request.url.path.endswith("/sessions/session_test"):
        return httpx2.Response(200, json=session_obj)
    if request.method == "POST" and request.url.path.endswith("/events"):
        submitted.append(json.loads(request.content))
        return httpx2.Response(200, json={"object": "list", "data": []})
    events = [
        {"event_id": "1", "type": "agent.session.turn.created", "session_id": "session_test", "turn_id": "turn_1",
         "turn": {"id": "turn_1", "object": "agent.session.turn", "agent_id": "a", "session_id": "session_test", "created_at": 1, "status": "in_progress", "subagent_id": None}},
        {"event_id": "2", "type": "agent.session.turn.item.added", "session_id": "session_test", "turn_id": "turn_1",
         "item": {"id": "item_1", "type": "function_call", "name": "bin_tool", "call_id": "call_1", "arguments": "{}", "status": "in_progress", "turn_id": "turn_1"}},
        {"event_id": "3", "type": "agent.session.turn.item.added", "session_id": "session_test", "turn_id": "turn_1",
         "item": {"id": "item_2", "type": "function_call", "name": "nan_tool", "call_id": "call_2", "arguments": "{}", "status": "in_progress", "turn_id": "turn_1"}},
        {"event_id": "4", "type": "agent.session.turn.completed", "session_id": "session_test", "turn_id": "turn_1",
         "turn": {"id": "turn_1", "object": "agent.session.turn", "agent_id": "a", "session_id": "session_test", "created_at": 1, "status": "completed", "subagent_id": None}},
        {"event_id": "5", "type": "agent.session.idle", "session": session_obj},
    ]
    body = "".join(f"data: {json.dumps(e)}\n\n" for e in events).encode()
    return httpx2.Response(200, headers={"content-type": "text/event-stream"}, content=body)

errors: list[AgentToolError] = []
with OpenAI(api_key="test", http_client=httpx2.Client(transport=httpx2.MockTransport(handle))) as client:
    with client.beta.agents.sessions.stream(
        "session_test",
        input="Run tools",
        tool_handlers={
            "bin_tool": lambda _args: b"hello",
            "nan_tool": lambda _args: {"score": float("nan")},
        },
        on_tool_error=errors.append,
    ) as stream:
        stream.until_done()

print("on_tool_error count:", len(errors))
for payload in submitted[1:]:
    print(payload["events"][0])

Actual output:

on_tool_error count: 0
{'type': 'agent.session.input.tool_result', 'turn_id': 'turn_1', 'call_id': 'call_1', 'success': True, 'output': [104, 101, 108, 108, 111]}
{'type': 'agent.session.input.tool_result', 'turn_id': 'turn_1', 'call_id': 'call_2', 'success': True, 'output': '{"score":NaN}'}

Expected behavior:
Both handlers should fail at stage="output" (TypeError for bytes/bytearray/memoryview, ValueError for non-finite floats), invoke on_tool_error, and submit {"success": False, "error": "Tool handler failed."}.

Suggested Fix

In src/openai/lib/streaming/agents/_tools.py:

 def result_event(call: AgentFunctionCallItem, output: ToolOutput) -> SessionInputParamAgentSessionInputToolResult:
+    if isinstance(output, (bytes, bytearray, memoryview)):
+        raise TypeError("Tool output must be a string, mapping, or sequence of content items, not bytes")
     if isinstance(output, Mapping):
-        output = json.dumps(dict(output), separators=(",", ":"))
+        output = json.dumps(dict(output), separators=(",", ":"), allow_nan=False)

(Verified locally with sync/async regression tests covering bytes, bytearray, memoryview, nan, inf, and -inf: 525 passed across tests/lib/streaming/agents/, tests/lib/beta/agents/test_tools.py, and tests/test_agents_budget_events.py, with ruff check and ruff format --check clean.)

OS

macOS

Python version

Python 3.14.8

Library version

openai v3.57.0 (main@f63f14b)

Lingua principale
Python
Stelle
32.2k
Fork
5.8k
Merge medio
12h 29m
PR unite (30g)
112

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di openai/openai-python

Tutte le issue di openai/openai-python

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.