beta.agents: direct tool handlers returning bytes or Mapping with NaN/Infinity bypass output validation and submit success=True
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
- Área
- backend-api-design
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:
bytes/bytearray/memoryvieware silently encoded aslist[int]: Because binary buffers are non-striterables,list(output)turnsb"hello"into[104, 101, 108, 108, 111].maybe_transformandopenapi_dumpsaccept a list of integers, so the SDK sends{"success": true, "output": [104, 101, 108, 108, 111]}instead of rejecting binary output withTypeErroratstage="output".- Non-finite floats (
NaN/Infinity/-Infinity) inMappingoutputs emit invalid RFC 8259 JSON:json.dumps(dict(output), separators=(",", ":"))omitsallow_nan=False, producing'{"score":NaN}'/'{"ratio":Infinity}'. Becauseoutputis now astr, the subsequentopenapi_dumps(output)check (allow_nan=False) sees a plain string and succeeds, forwarding invalid JSON insideoutputwithsuccess=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
- Register direct
tool_handlersonclient.beta.agents.sessions.stream(...)(sync or async) returningb"hello"(orbytearray/memoryview) and{"score": float("nan")}(orfloat("inf")/-float("inf")). - Attach an
on_tool_errorcallback and consume the stream. - Observe that
on_tool_erroris never called (count: 0) and both tool results are posted withsuccess=Trueand 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
Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de openai/openai-python
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
openai/openai-python#4338 ·
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 65/100
openai/openai-python#4337 ·
Los mantenedores suelen responder en 1 día
-
`BaseClient._prepare_url()` corrupts relative endpoint URLs when `base_url` contains query parametersPosiblemente ocupada @Rewaskc02-lang la tomó hace 1 día. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
openai/openai-python#4311 · 4 comentarios ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
openai/openai-python#4310 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
openai/openai-python#4309 · 1 comentario ·
Los mantenedores suelen responder en 1 día
Todos los issues de openai/openai-python
Issues similares
-
triage
Dificultad 1/5 1-3 horas Aptitud para principiantes 88/100
kornia/kornia-rs#1416 · 1 comentario ·
Los mantenedores suelen responder en 2 días
-
ui
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
PolicyEngine/ai-inequality#64 ·
Los mantenedores suelen responder en 1 día
-
LinearGaussianStateSpace.dist splits states and observations wrongly when the transition varies over timePosiblemente ocupada @PabloRoque la tomó hoy. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 88/100
pymc-devs/pymc-extras#839 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
Los mantenedores suelen responder en 1 día