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

Abierto
#4,303 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
62/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python

Línea de trabajo

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.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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)

Lenguaje dominante
Python
Estrellas
32.2k
Forks
5.8k
Merge medio
12 h 29 min
PR fusionados (30 d)
112

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de openai/openai-python

Todos los issues de openai/openai-python

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.