TranscriptGrouper / AsyncTranscriptGrouper: unvalidated additional_acknowledgments splits bare str and raises TypeError/AttributeError instead of OpenAIError

未關閉 適合新手
#4,307 1 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

維護者通常 1 天內回覆

還沒有人認領這個 Issue。

評估

難度
2/5
預估耗時
1-3 小時
新手友好度
72/100
Issue 類型
缺陷
描述清晰度
描述清楚
活躍度
活躍
技術堆疊
python
領域
backend

研究方向

從 src/openai/lib/live/_transcript_state.py 開始,查看 validated_options() 跳過 additional_acknowledgments 欄位的位置;再看 src/openai/lib/live/_transcript_grouper.py 第 76 行附近,_options() 執行 tuple(additional_acknowledgments or ()) 的位置。使用 TranscriptGrouper(additional_acknowledgments="cool") 以及 issue 中的錯誤輸入進行重現。當單一 str、bytes 或非字串元素會拋出 OpenAIError,而有效的字串列表仍能正常運作時,即視為完成。

由索引模型根據 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 openai.lib.live, TranscriptGrouper and AsyncTranscriptGrouper validate all timing options in validated_options() (src/openai/lib/live/_transcript_state.py:19-26), raising OpenAIError for invalid values. However, additional_acknowledgments is skipped (if field.name == "additional_acknowledgments": continue) and _options() (src/openai/lib/live/_transcript_grouper.py:76) blindly runs tuple(additional_acknowledgments or ()).

This causes three problems:

  1. Silent character splitting on bare str (even passes static typing): Because additional_acknowledgments is typed as Sequence[str] | None, passing a bare string like TranscriptGrouper(additional_acknowledgments="cool") passes type checkers and silently splits into ('c', 'o', 'o', 'l'). Overlapping assistant turns with "c", "o", or "l" are silently dropped while "cool" is not suppressed.
  2. Silent acceptance of falsy non-sequence values: additional_acknowledgments or () silently turns "", b"", 0, False, or {} into () instead of rejecting invalid types.
  3. Inconsistent error types: Passing b"cool", 123, [123], or [None] leaks raw TypeError or AttributeError: 'int' object has no attribute 'lower' inside _normalize_acknowledgment() instead of raising OpenAIError like all other invalid options.

(Optional static-typing follow-up: switching the parameter annotation from Sequence[str] | None to SequenceNotStr[str] | None, matching _vector_stores.py and _chat_completion_resources.py, would also catch bare str at type-check time.)

To Reproduce
  1. Construct TranscriptGrouper(additional_acknowledgments="cool") and push a user turn overlapped by an assistant utterance "c" vs "cool".
  2. Observe that "c" is dropped as an acknowledgment while "cool" is emitted.
  3. Construct TranscriptGrouper(additional_acknowledgments=b"cool"), 123, or [123], and observe raw AttributeError/TypeError instead of OpenAIError.
Code snippets
from openai.lib.live import TranscriptGrouper
from openai.types.live import InputTranscriptDeltaEvent, OutputTranscriptDeltaEvent

for assistant_text in ("c", "cool"):
    closed = []
    g = TranscriptGrouper(additional_acknowledgments="cool")
    g.on("segment.closed", lambda e, out=closed: out.append((e.segment.speaker, e.segment.text)))
    g.push(InputTranscriptDeltaEvent(type="session.input_transcript.delta", event_id="u1", delta="Here is my question", start_ms=0, end_ms=500))
    g.push(OutputTranscriptDeltaEvent(type="session.output_transcript.delta", event_id="a1", delta=assistant_text, start_ms=300, end_ms=500))
    g.push(InputTranscriptDeltaEvent(type="session.input_transcript.delta", event_id="u2", delta="about the API.", start_ms=600, end_ms=1200))
    g.close()
    print(f"assistant={assistant_text!r} -> {closed}")

# Output on openai v3.57.0:
# assistant='c' -> [('user', 'Here is my question about the API.')]         <-- 'c' silently dropped!
# assistant='cool' -> [('user', 'Here is my question about the API.'), ('assistant', 'cool')]  <-- 'cool' NOT dropped!

for bad in (b"cool", 123, [123], [None]):
    try:
        TranscriptGrouper(additional_acknowledgments=bad)  # type: ignore[arg-type]
    except Exception as exc:
        print(f"{bad!r} -> {type(exc).__name__}: {exc}")

# Output:
# b'cool' -> AttributeError: 'int' object has no attribute 'lower'
# 123 -> TypeError: 'int' object is not iterable
# [123] -> AttributeError: 'int' object has no attribute 'lower'
# [None] -> AttributeError: 'NoneType' object has no attribute 'lower'

Suggested fix in src/openai/lib/live/_transcript_state.py and src/openai/lib/live/_transcript_grouper.py:

--- a/src/openai/lib/live/_transcript_state.py
+++ b/src/openai/lib/live/_transcript_state.py
@@ -4,6 +4,7 @@
 from typing import Callable
 from dataclasses import fields, dataclass
+from collections.abc import Sequence
 from typing_extensions import Literal, TypeGuard
@@ -16,9 +17,21 @@
+def validated_additional_acknowledgments(value: object) -> tuple[str, ...]:
+    if isinstance(value, (str, bytes, bytearray, memoryview)) or not isinstance(value, Sequence):
+        raise OpenAIError("additional_acknowledgments must be a sequence of strings")
+    phrases: list[str] = []
+    for phrase in value:
+        if not isinstance(phrase, str):
+            raise OpenAIError("additional_acknowledgments must be a sequence of strings")
+        phrases.append(phrase)
+    return tuple(phrases)
+
+
 def validated_options(options: TranscriptGrouperOptions) -> TranscriptGrouperOptions:
     for field in fields(options):
         if field.name == "additional_acknowledgments":
+            validated_additional_acknowledgments(options.additional_acknowledgments)
             continue
--- a/src/openai/lib/live/_transcript_grouper.py
+++ b/src/openai/lib/live/_transcript_grouper.py
@@ -73,7 +73,7 @@
         2000 if assistant_silence_ms is None else assistant_silence_ms,
         1000 if backchannel_max_duration_ms is None else backchannel_max_duration_ms,
         2000 if backchannel_isolation_ms is None else backchannel_isolation_ms,
-        tuple(additional_acknowledgments or ()),
+        () if additional_acknowledgments is None else validated_additional_acknowledgments(additional_acknowledgments),
     )
OS

macOS

Python version

Python 3.14

Library version

openai v3.57.0 (main@f63f14b)

主要語言
Python
星號
32.2k
分支
5.8k
平均合併
12 小時 29 分鐘
30 天內合併 PR
112

環境準備

在 Codespaces 中開啟

在瀏覽器裡用你自己的 GitHub 帳號啟動這個專案的開發容器。

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

openai/openai-python 的其他 Issue

查看 openai/openai-python 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。