Skip to content

feat(responses): add retrieve_parsed() for background response polling - #2909

Open
shouryamaanjain wants to merge 1 commit into
openai:mainfrom
shouryamaanjain:feat/retrieve-parsed-responses
Open

shouryamaanjain wants to merge 1 commit into
openai:mainfrom
shouryamaanjain:feat/retrieve-parsed-responses

Conversation

@shouryamaanjain

Copy link
Copy Markdown

Summary

  • Adds retrieve_parsed() method to both Responses and AsyncResponses clients
  • Enables parsing of background responses created with responses.parse(background=True)
  • Supports text_format for structured output parsing and tools for function tool call argument parsing
  • Mirrors the existing parse() pattern using post_parser to transform Response into ParsedResponse

Problem

When using responses.parse() with background=True, the initial call returns a ParsedResponse. However, polling with responses.retrieve() returns a plain Response without output_parsed, forcing users to manually parse via model_validate_json().

Usage

# Start background request with structured output
response = client.responses.parse(
    model="gpt-4o",
    input="Generate a name and value",
    text_format=MySchema,
    background=True,
)

# Poll with parsing support
while response.status != "completed":
    time.sleep(0.5)
    response = client.responses.retrieve_parsed(
        response.id,
        text_format=MySchema,
    )

# Now works as expected
print(response.output_parsed)

Fixes #2830

Test plan

  • Sync retrieve_parsed() with text_format parsing
  • Async retrieve_parsed() with text_format parsing
  • retrieve_parsed() with function tool argument parsing
  • Ruff lint passes

@shouryamaanjain
shouryamaanjain requested a review from a team as a code owner March 1, 2026 02:49

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7712c2a41d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

stream_cls=Stream[ResponseStreamEvent],
)

def retrieve_parsed(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Add retrieve_parsed to raw-response wrappers

retrieve_parsed() is added as a new HTTP helper, but ResponsesWithRawResponse/AsyncResponsesWithRawResponse are not updated to bind this method, so client.responses.with_raw_response.retrieve_parsed(...) and its async equivalent will raise AttributeError even though with_raw_response is documented as supporting HTTP method calls. This is a user-facing regression for anyone relying on raw-response access patterns for the new endpoint helper.

Useful? React with 👍 / 👎.

When using `responses.parse()` with `background=True`, the subsequent
`responses.retrieve()` call returns a plain `Response` object without
parsed output. This adds `retrieve_parsed()` to both sync and async
clients, allowing users to retrieve and parse background responses with
`text_format` and `tools` support.

Fixes openai#2830
@shouryamaanjain
shouryamaanjain force-pushed the feat/retrieve-parsed-responses branch from 7712c2a to 72ed678 Compare March 1, 2026 03:17
@jnohclee-rgb

Copy link
Copy Markdown

AI-assisted independent offline check at 72ed678c75cea131231e9128de1931f270062d51, compared with pinned main 919b6236382f3f9f76d8453efb9f9ad03cff1126.

A 12-case observation matrix through public retrieve_parsed (sync/async, local MockTransport) confirms the completed valid parse and its fail-closed ValidationError control. It also highlights a documentation/readiness boundary: a constructed in_progress or incomplete response containing truncated JSON raises ValidationError before the caller receives a Response whose status it can inspect. A queued empty response returns status=queued with output_parsed=None. Valid JSON is parsed even at in_progress. Main has no retrieve_parsed method, so this is feature-scope evidence, not a baseline fix-pass score.

For a helper described as useful for background polling, would you document that callers should retrieve/inspect readiness before parsing, or define status-aware parsing behavior and add these status controls?

Scope: Public methods with in-process MockTransport only. These response shapes are constructed; no assertion that a live background response currently exposes partial text with these statuses or that status-aware parsing is an existing API promise. No network/real API calls. The reproducer records observations rather than assigning a speculative provider contract. Python 3.14.7 / Pydantic 2.13.5 and shared local dependencies; this is a bounded matrix, not a full SDK suite or historical dependency matrix. Network denied by the sandbox.

Standalone reproducer (run separately with each source tree on PYTHONPATH)
import json,asyncio,pydantic,importlib
from openai import OpenAI,AsyncOpenAI
http=importlib.import_module('httpx')
class Answer(pydantic.BaseModel):n:int
async def main():
 rows=[]
 for async_ in [False,True]:
  for status,text in [('completed','{"n":3}'),('completed','{"n":'),('in_progress','{"n":3}'),('in_progress','{"n":'),('incomplete','{"n":'),('queued',None)]:
   requests=[]
   data={'id':'fictional','object':'response','created_at':0,'model':'fictional','parallel_tool_calls':True,'tool_choice':'auto','tools':[],'status':status,'output':[] if text is None else [{'type':'message','id':'fictional','role':'assistant','status':'completed' if status=='completed' else 'in_progress','content':[{'type':'output_text','annotations':[],'text':text}]}]}
   def handle(request):requests.append({'method':request.method,'path':request.url.path});return http.Response(200,json=data)
   transport=http.MockTransport(handle);h=(http.AsyncClient if async_ else http.Client)(transport=transport)
   client=(AsyncOpenAI if async_ else OpenAI)(api_key='fictional',base_url='https://example.invalid/v1',http_client=h,max_retries=0)
   kind=None;actual=None
   try:
    result=await client.responses.retrieve_parsed('fictional',text_format=Answer) if async_ else client.responses.retrieve_parsed('fictional',text_format=Answer)
    actual={'status':result.status,'output_parsed':result.output_parsed.model_dump() if result.output_parsed else None}
   except Exception as exc:kind=type(exc).__name__
   rows.append({'async':async_,'status':status,'text':text,'exception':kind,'actual':actual,'requests':requests})
   if async_:await client.close()
   else:client.close()
 print(json.dumps({'cases':rows,'scope':'Public retrieve_parsed with local MockTransport and constructed response statuses; observed behavior, not live background-response sequence or proposed readiness contract.'}))
asyncio.run(main())

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

responses.parse() with background=True returns unparseable Response from retrieve() - missing ParsedResponse support for background mode

2 participants