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

Ouverte Adaptée aux débutants
#4,307 1 commentaire 0 réactions 0 personnes assignées Voir sur GitHub

Les mainteneurs répondent en général sous 1 jour

Personne n'a encore pris cette issue.

Évaluation

Difficulté
2/5
Temps estimé
1-3 heures
Accessibilité débutants
72/100
Type d'issue
Bug
Clarté
Clairement spécifiée
Activité
Active
Stack technique
python
Domaine
backend

Piste de recherche

Commence dans src/openai/lib/live/_transcript_state.py, où validated_options() ignore le champ additional_acknowledgments, puis dans src/openai/lib/live/_transcript_grouper.py vers la ligne 76, où _options() exécute tuple(additional_acknowledgments or ()). Reproduis le problème avec TranscriptGrouper(additional_acknowledgments="cool") et les mauvaises entrées décrites dans l'issue. C'est terminé lorsqu'un str simple, des bytes ou des éléments non textuels lèvent OpenAIError et qu'une liste valide de chaînes fonctionne toujours.

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 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)

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

Ouvrir dans Codespaces

Lance le conteneur de développement du projet dans votre navigateur, avec votre propre compte GitHub.

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de openai/openai-python

Toutes les issues de openai/openai-python

Issues similaires

Plus d'issues Python

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.