beta.agents: AgentTurnResult.parse() swallows TypeError for invalid output_type and raises AgentOutputParseError

Aperta Adatta ai principianti
#4,304 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
1/5
Tempo stimato
Meno di un'ora
Idoneità per principianti
82/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python
Ambito
backend

Direzione di ricerca

Il bug è in src/openai/lib/beta/agents/_result.py in AgentTurnResult.parse(), dove validate_output_type viene eseguito all’interno di un ampio except Exception. Inizia leggendo quel metodo e il controllo esistente in tests/lib/streaming/agents/test_output.py (test_invalid_output_model_rejected_before_request). Sposta la chiamata di validazione sopra try: e aggiungi test di regressione sincroni e asincroni che verifichino che parse(str), parse(dict) e parse(object) sollevino TypeError senza AgentOutputParseError. Fatto quando quei test passano e la suite di test degli agents passa ancora.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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/beta/agents/_result.py:32-51, AgentTurnResult.parse() invokes validate_output_type(output_type) inside the broad try: ... except Exception: block:

    def parse(self, output_type: type[ParseT]) -> AgentTurnResult[ParseT]:
        """Beta: parse a completed answer without changing its session configuration."""
        try:
            validate_output_type(output_type)
            parsed: ParseT | None = None
            ...
        except Exception:
            # Pydantic errors may include response text in their rendered message.
            raise AgentOutputParseError(self) from None

When a caller passes an unsupported output_type (such as str, dict, or object), validate_output_type(output_type) raises TypeError("Agents output_type must be a Pydantic model or a Pydantic v2 dataclass"), which is immediately caught, stripped of its cause (from None), and re-raised as AgentOutputParseError("Could not parse the completed agent output").

This disguises a caller-side programming/configuration error as a malformed model output error and is inconsistent with sessions.create(..., output_type=...) and sessions.stream(..., output_type=...), both of which propagate TypeError directly (covered by test_invalid_output_model_rejected_before_request in tests/lib/streaming/agents/test_output.py:456-477).

To Reproduce
  1. Obtain an AgentTurnResult from a completed agent turn (e.g. stream.get_final_result()).
  2. Call result.parse(str), result.parse(dict), or result.parse(object).
  3. Observe that AgentOutputParseError (__cause__=None) is raised instead of TypeError.
Code snippets
from openai.lib.beta.agents import AgentTurnResult
from openai.types.beta.agent_session_message import AgentSessionMessage
from openai.types.beta.agents.sessions.turn import Turn

turn = Turn.construct(
    id="turn_1", object="agent.session.turn", agent_id="a", session_id="s", created_at=1, status="completed"
)
msg = AgentSessionMessage.construct(
    id="msg_1",
    type="message",
    role="assistant",
    status="completed",
    turn_id="turn_1",
    content=[{"type": "output_text", "text": '{"ok": true}'}],
)
result = AgentTurnResult(turn=turn, messages=[msg])

for bad_type in (str, dict, object):
    try:
        result.parse(bad_type)
    except Exception as exc:
        print(f"result.parse({bad_type.__name__}) -> {type(exc).__name__}: {exc} (__cause__={exc.__cause__!r})")

Actual output:

result.parse(str) -> AgentOutputParseError: Could not parse the completed agent output (__cause__=None)
result.parse(dict) -> AgentOutputParseError: Could not parse the completed agent output (__cause__=None)
result.parse(object) -> AgentOutputParseError: Could not parse the completed agent output (__cause__=None)

Expected output:
TypeError: Agents output_type must be a Pydantic model or a Pydantic v2 dataclass

Suggested Fix

Move validate_output_type(output_type) immediately before try: in src/openai/lib/beta/agents/_result.py:

     def parse(self, output_type: type[ParseT]) -> AgentTurnResult[ParseT]:
         """Beta: parse a completed answer without changing its session configuration."""
+        validate_output_type(output_type)
         try:
-            validate_output_type(output_type)
             parsed: ParseT | None = None

(Verified locally with sync/async regression tests across str, dict, and object: 519 passed across tests/lib/streaming/agents/, tests/lib/beta/agents/test_tools.py, and tests/test_agents_budget_events.py, with ruff and pyright 0 errors.)

OS

macOS

Python version

Python 3.14.8

Library version

openai v3.57.0 (main@f63f14b)

Lingua principale
Python
Stelle
32.2k
Fork
5.8k
Merge medio
12h 29m
PR unite (30g)
112

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di openai/openai-python

Tutte le issue di openai/openai-python

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.