Responses create spends CPU proportional to the body size transforming a body it returns unchanged

オープン
#4,021 コメント 2 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
52/100
issue の種類
バグ
明瞭さ
おおむね明確
活発さ
活発
技術スタック
python
領域
performance

調査の方向性

Start in _utils/_transform.py and trace async_maybe_transform from AsyncResponses.create and Responses.create. Use the reproduction script in the issue to compare transformation time and output equality for large plain-dict bodies. Done means unchanged bodies avoid the recursive walk while aliased, formatted, and file inputs still transform correctly.

索引モデルが issue の本文から書いたものです。

説明

bug
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

AsyncResponses.create runs async_maybe_transform over the whole request body before every request. With a long input and many tools, that transform costs tens of milliseconds of CPU per request, and the cost grows linearly with the body size. For a body of plain dicts (no aliased keys, no format fields, no file inputs) the transform returns a body equal to its input, so the CPU time does not change the request.

The transform runs on the event loop. In an asyncio app that shares the loop with latency-sensitive work, such as streaming audio, each request blocks that work for the whole transform. A chat app sends the full history on every turn, so the block grows as the conversation gets longer. Responses.create (sync) runs the same transform.

Median of 11 runs, from the script under Code snippets:

input items tools transform (ms) output == input
30 10 4.6 True
90 40 14.5 True
180 86 29.7 True
360 86 54.0 True

cProfile of one request with 180 input items and 86 tools: 21,068 calls to _utils/_transform.py:_async_transform_recursive, 7,857 calls to _async_transform_typeddict, and about 74,000 calls to typing.get_origin. The time goes to the walk over every nested dict and list, not to any field the transform rewrites.

A possible direction: decide once per type, and cache, whether its annotations contain any PropertyInfo (alias, format, discriminator). When a type contains none, return the data without walking it.

To Reproduce
  1. Build a Responses request body of plain dicts with a long input (user messages, function_call and function_call_output items) and 86 function tools.
  2. Time async_maybe_transform(body, ResponseCreateParamsStreaming), the call AsyncResponses.create makes before it sends the request.
  3. Compare the transformed body with the input.

The script under Code snippets does this with synthetic data and makes no network call. Its output:

input_items  tools  transform_ms  output_equals_input
         30     10           4.6  True
         90     40          14.5  True
        180     86          29.7  True
        360     86          54.0  True
Code snippets
import asyncio
import time

from openai._utils import async_maybe_transform
from openai.types.responses import response_create_params


def build_body(turns: int, n_tools: int) -> dict:
    items = []
    for i in range(turns):
        items.append({"role": "user", "content": [{"type": "input_text", "text": "lorem ipsum " * 100}]})
        items.append({"type": "function_call", "call_id": f"call_{i}", "name": "lookup", "arguments": '{"q": "x"}'})
        items.append({"type": "function_call_output", "call_id": f"call_{i}", "output": "result " * 200})
    tools = [
        {
            "type": "function",
            "name": f"tool_{i}",
            "description": "does a thing " * 10,
            "strict": False,
            "parameters": {
                "type": "object",
                "properties": {f"arg_{j}": {"type": "string", "description": "an argument"} for j in range(8)},
                "required": ["arg_0"],
            },
        }
        for i in range(n_tools)
    ]
    return {"model": "gpt-4.1", "input": items, "tools": tools, "stream": True}


async def median_ms(body: dict) -> tuple[float, bool]:
    # The same call AsyncResponses.create makes before sending the request.
    for _ in range(3):
        out = await async_maybe_transform(body, response_create_params.ResponseCreateParamsStreaming)
    runs = []
    for _ in range(11):
        start = time.perf_counter()
        out = await async_maybe_transform(body, response_create_params.ResponseCreateParamsStreaming)
        runs.append((time.perf_counter() - start) * 1000)
    return sorted(runs)[5], out == body


async def main() -> None:
    print("input_items  tools  transform_ms  output_equals_input")
    for turns, n_tools in [(10, 10), (30, 40), (60, 86), (120, 86)]:
        body = build_body(turns, n_tools)
        ms, same = await median_ms(body)
        print(f"{len(body['input']):>11}  {n_tools:>5}  {ms:>12.1f}  {same}")


asyncio.run(main())
OS

macOS 26.5 (arm64)

Python version

Python v3.14.3

Library version

openai v3.24.0

主要言語
Python
スター
32.2k
フォーク
5.8k
平均マージ
12時間 29分
マージ済み PR(30日)
112

環境構築

Codespaces で開く

このプロジェクトの開発コンテナを、あなたの GitHub アカウントでブラウザ上に起動します。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

openai/openai-python のほかの issue

openai/openai-python の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。