beta.agents: direct tool handlers returning bytes or Mapping with NaN/Infinity bypass output validation and submit success=True
Les mainteneurs répondent en général sous 1 jour
Personne n'a encore pris cette issue.
Évaluation
- Difficulté
- 3/5
- Temps estimé
- 1-2 jours
- Accessibilité débutants
- 62/100
- Type d'issue
- Bug
- Clarté
- Clairement spécifiée
- Activité
- Active
- Stack technique
- python
- Domaine
- backend-api-design
Piste de recherche
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.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Description
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)
- Langage dominant
- Python
- Étoiles
- 32.2k
- Forks
- 5.8k
- Merge moyen
- 12 h 29 min
- PR mergées (30 j)
- 112
Préparer son environnement
Lance le conteneur de développement du projet dans votre navigateur, avec votre propre compte GitHub.
- Aucun Dockerfile ni fichier Docker Compose
- Propose un modèle de pull request
- Lire le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Autres issues de openai/openai-python
-
Difficulté 2/5 1-3 heures Accessibilité débutants 76/100
openai/openai-python#4338 ·
Les mainteneurs répondent en général sous 1 jour
-
bug
Difficulté 2/5 1-3 heures Accessibilité débutants 65/100
openai/openai-python#4337 ·
Les mainteneurs répondent en général sous 1 jour
-
`BaseClient._prepare_url()` corrupts relative endpoint URLs when `base_url` contains query parametersPeut-être pris @Rewaskc02-lang l’a pris il y a 1 jour. Ouverte
Difficulté 2/5 1-3 heures Accessibilité débutants 78/100
openai/openai-python#4311 · 4 commentaires ·
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 78/100
openai/openai-python#4310 · 1 commentaire ·
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 82/100
openai/openai-python#4309 · 1 commentaire ·
Les mainteneurs répondent en général sous 1 jour
Toutes les issues de openai/openai-python
Issues similaires
-
triage
Difficulté 1/5 1-3 heures Accessibilité débutants 88/100
kornia/kornia-rs#1416 · 1 commentaire ·
Les mainteneurs répondent en général sous 2 jours
-
ui
Difficulté 2/5 1-3 heures Accessibilité débutants 78/100
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 76/100
PolicyEngine/ai-inequality#64 ·
Les mainteneurs répondent en général sous 1 jour
-
LinearGaussianStateSpace.dist splits states and observations wrongly when the transition varies over timePeut-être pris @PabloRoque l’a pris aujourd’hui. Ouverte
Difficulté 2/5 1-3 heures Accessibilité débutants 88/100
pymc-devs/pymc-extras#839 ·
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 76/100
Les mainteneurs répondent en général sous 1 jour