beta.agents: direct tool handlers returning bytes or Mapping with NaN/Infinity bypass output validation and submit success=True
メンテナーはふだん 1 日以内に返信
まだ誰も着手していません。
評価
- 難易度
- 3/5
- 見積もり時間
- 1〜2日
- 初心者へのやさしさ
- 62/100
- issue の種類
- バグ
- 明瞭さ
- 明確に書かれている
- 活発さ
- 活発
- 技術スタック
- python
調査の方向性
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.
索引モデルが issue の本文から書いたものです。
説明
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)
- 主要言語
- Python
- スター
- 32.2k
- フォーク
- 5.8k
- 平均マージ
- 12時間 29分
- マージ済み PR(30日)
- 112
環境構築
このプロジェクトの開発コンテナを、あなたの GitHub アカウントでブラウザ上に起動します。
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートあり
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
openai/openai-python のほかの issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
openai/openai-python#4338 ·
メンテナーはふだん 1 日以内に返信
-
bug
難易度 2/5 1〜3時間 初心者へのやさしさ 65/100
openai/openai-python#4337 ·
メンテナーはふだん 1 日以内に返信
-
`BaseClient._prepare_url()` corrupts relative endpoint URLs when `base_url` contains query parameters対応中かも @Rewaskc02-lang が 1 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
openai/openai-python#4311 · コメント 4 件 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
openai/openai-python#4310 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 82/100
openai/openai-python#4309 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
openai/openai-python の issue をすべて見る
似ている issue
-
triage
難易度 1/5 1〜3時間 初心者へのやさしさ 88/100
kornia/kornia-rs#1416 · コメント 1 件 ·
メンテナーはふだん 2 日以内に返信
-
ui
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
PolicyEngine/ai-inequality#64 ·
メンテナーはふだん 1 日以内に返信
-
LinearGaussianStateSpace.dist splits states and observations wrongly when the transition varies over time対応中かも @PabloRoque が今日担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 88/100
pymc-devs/pymc-extras#839 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
メンテナーはふだん 1 日以内に返信