LLM Integration & APIs

How to Stream OpenAI Responses API Events in a Python Agent CLI

A Python CLI that waits for a complete response before printing can feel unresponsive, especially when a request takes time. The Responses API stream instead delivers events, so your program can display text as it arrives and decide how to finish based on the final event.

This guide focuses on a small, synchronous CLI using the official OpenAI Python SDK. You’ll set up a streamed request, print each text delta as it arrives, and distinguish successful completion from failed or incomplete responses and errors.

You’ll need the SDK installed and an API key available to the process through OPENAI_API_KEY. API access and model availability may depend on your account and region, so check those before treating a request failure as a problem with the event loop.

The goal is a clear pattern for consuming the stream—not a broader agent architecture or a guarantee that every response contains text.

Digital illustration of cyberpunk cats in neon-lit urban scenes, engaged in AI-agent tasks such as coding, debugging, or analyzing data streams. The style features glowing outlines, high contrast, and a vibrant acid-color palette. No brand logos, no invented software screenshots, no legible text.: How to Stream OpenAI Responses API Events in a Python Agent CLI

Quick answer

The short version: install the official openai package, make OPENAI_API_KEY available to the CLI, then create a Responses API request with stream=True. Iterate through the returned events rather than treating the stream as one finished string.

When an event is response.output_text.delta, write its delta text to standard output and flush it so the CLI can show partial output. Other events need not contain text.

Treat response.completed as successful completion; handle response.failed, response.incomplete, and error as unsuccessful outcomes, reporting available details rather than silently counting them as success.

Keep SDK exceptions in the error-handling path too. The event reference describes stream event types, but it does not establish that every failure will arrive as an event instead of an exception.

After implementing the loop, verify both the visible behavior—text appears before the stream ends—and the process result: success on completion, nonzero status for failures or exceptions.

Step-by-step guide

Prerequisites and starting state

Before building the CLI, have a Python environment and an OpenAI API key that the process can access. Install the official Python SDK with:

pip install openai

Set OPENAI_API_KEY in the environment from which you will launch the CLI. The OpenAI client reads this variable when initialized, so make sure it is available in that same terminal or process environment.

You’ll also need API access for the account you plan to use. Model availability and API access can vary by account and region, so confirm that your account can use the model you intend to request before troubleshooting the streaming loop.

The next step uses the SDK’s synchronous client and a Responses API request with streaming enabled. You do not need to assemble the response from a single returned string: the stream is consumed as a sequence of events.

Sources: Developer quickstart; OpenAI Python API library; Responses streaming events.

Set up the Python client and streamed request

With the SDK installed and OPENAI_API_KEY available to the process, initialize the synchronous client and create a Responses API request with streaming enabled. Set model_name to a model your account can use, and prompt to the input you want to send.

from openai import OpenAI

client = OpenAI()
stream = client.responses.create(
    model=model_name,
    input=prompt,
    stream=True,
)

The call returns a stream of events, not one completed text string. Keep stream available for the event-consumption loop in the next step; the request setup alone does not print output to the terminal.

Sources: Developer quickstart; OpenAI Python API library; Responses streaming events.

Render text deltas as they arrive

The next step is to turn the event stream into visible output. OpenAI sends a sequence of typed, JSON-serialized events as Server-Sent Events over the streaming connection.

Each meaningful token arrives inside a response.output_text.delta event whose delta field holds the newly delivered text fragment. Looping through that event makes incremental terminal rendering possible instead of waiting for one returned string.

Here is how to build that loop and what to expect from it.

Sources: Developer quickstart; OpenAI Python API library; Responses streaming events.

Handle terminal events and API errors

Add terminal-event handling to the loop that prints text deltas. Only response.completed counts as success; a failed, incomplete, or error event should produce a nonzero exit status.

import sys
from openai import OpenAI


def main():
    client = OpenAI()
    completed = False

    try:
        stream = client.responses.create(
            model=model_name,
            input=prompt,
            stream=True,
        )
        for event in stream:
            if event.type == "response.output_text.delta":
                sys.stdout.write(event.delta)
                sys.stdout.flush()
            elif event.type == "response.completed":
                completed = True
                break
            elif event.type == "response.failed":
                error = getattr(getattr(event, "response", None), "error", None)
                print(f"Response failed: {error}", file=sys.stderr)
                return 1
            elif event.type == "response.incomplete":
                print("Response incomplete; it was not a successful completion.", file=sys.stderr)
                return 1
            elif event.type == "error":
                print(
                    f"Stream error ({getattr(event, 'code', None)}): "
                    f"{getattr(event, 'message', 'No message provided')}",
                    file=sys.stderr,
                )
                return 1
    except Exception as exc:
        print(f"Request or stream error: {exc}", file=sys.stderr)
        return 1

    if not completed:
        print("Stream ended without a completion event.", file=sys.stderr)
        return 1

    sys.stdout.write("\\n")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

The failed-response event can include an error object; error events provide a code and message. The code reports those details where available, catches exceptions from the request or iteration, and treats a stream ending without a completion event as unsuccessful.

Replace model_name and prompt with the values from your request setup.

Sources: Developer quickstart; OpenAI Python API library; Responses streaming events.

Verify incremental output and exit status

Run the CLI from the same environment where OPENAI_API_KEY is set, using a prompt that should produce text. Watch the terminal while the request is still running: text should appear in pieces, rather than all at once when the stream ends.

Flushing each delta makes those partial updates visible.

When the stream ends with response.completed, the CLI should exit with status 0. Check the process exit status in your terminal or test harness; don’t treat printed text alone as proof of success.

For failure checks, verify that response.failed, response.incomplete, and error events are reported to standard error and result in a nonzero status. Also check that an SDK exception during the request or iteration is reported as an error, not success.

The stream reference documents the event types and available failure details, but it does not guarantee how a particular failure will be delivered, so test event handling and exception handling separately.

If no partial text appears, confirm the loop handles response.output_text.delta and flushes standard output. If the request fails, check the error details and confirm the API key is available to the process.

Sources: Developer quickstart; OpenAI Python API library; Responses streaming events.

Troubleshoot missing output and unsuccessful streams

If output does not appear while the request is running, check that the loop handles response.output_text.delta and writes each event’s delta to standard output with a flush. The stream may not contain text for every event, so make sure the code is not waiting for one complete response string.

If the request fails, confirm OPENAI_API_KEY is available to the same process that launches the CLI. Also check that the account has API access and can use the requested model; availability can depend on account and region.

For a response.failed event, inspect the response’s error object for any available code or message. An error event can also provide a code and message; report these to standard error and return a nonzero status.

If the SDK raises an exception during the request or iteration, handle and report it separately from stream events, and do not treat it as successful completion.

Sources: Developer quickstart; OpenAI Python API library; Responses streaming events.

Next steps

For a straightforward synchronous CLI, the key decision is to treat the stream as a sequence of typed events, not as a single text value. Print and flush text deltas as they arrive, and reserve success for response.completed; failed or incomplete responses, error events, and SDK exceptions should remain visible as failures.

Before relying on the CLI, run it with a prompt expected to produce text and watch for partial output before the request ends. Then check the exit status, and separately confirm that unsuccessful outcomes are reported rather than treated as completed responses.

If the CLI fails, first check that OPENAI_API_KEY reaches the process and that your account can access the requested model. If text does not appear incrementally, check the text-delta event handling and output flush.

That gives you a practical next step without confusing a setup issue or an API error with a successful stream.