Skip to main content

OpenResponses Python SDK

A typed Python client for the OpenResponses protocol. This SDK implements the pinned 2026-04-24 wire contract, including JSON and SSE response creation, compaction, WebSocket turns and continuation, typed models, structured errors, and opaque provider extensions.

Requirements and installation

Python 3.10 or newer is required.

python -m pip install openresponses-py

For a checkout of this repository:

python -m pip install -e .

The default HTTP base URL is https://api.openai.com/v1. Supply a provider-specific URL when needed. An API key is optional for local or private providers.

Synchronous and asynchronous JSON

import os

from openresponses import OpenResponses

client = OpenResponses(
    base_url=os.environ.get("OPENRESPONSES_BASE_URL", "https://api.openai.com/v1"),
    api_key=os.environ.get("OPENRESPONSES_API_KEY"),
)
with client:
    response = client.responses.create({
        "model": os.environ["OPENRESPONSES_MODEL"],
        "input": "Give me one practical tip for testing an API.",
    })
    print(response.id)
    for item in response.output:
        print(item.root)

AsyncOpenResponses has the same responses.create(...) API; await the call and iterate asynchronous streams with async for:

import asyncio
import os

from openresponses import AsyncOpenResponses

async def main() -> None:
    async with AsyncOpenResponses(
        base_url=os.environ.get("OPENRESPONSES_BASE_URL", "https://api.openai.com/v1"),
        api_key=os.environ.get("OPENRESPONSES_API_KEY"),
    ) as client:
        response = await client.responses.create({
            "model": os.environ["OPENRESPONSES_MODEL"],
            "input": "Hello",
        })
        print(response.id)

asyncio.run(main())

Requests may be dictionaries or typed CreateResponseRequest models. Strict JSON responses are validated as ResponseResource; with response_compatibility="openai-compatible", partial provider responses are validated as OpenAICompatibleResponse. The typed model surface is re-exported from openresponses.

Streaming

Set stream=True to receive a ResponseStream; the asynchronous client returns AsyncResponseStream. Each yielded value is a typed streaming event.

from openresponses import OpenResponses

with OpenResponses() as client:
    with client.responses.create({
        "model": "your-model",
        "input": "Write a short greeting.",
        "stream": True,
    }) as stream:
        for event in stream:
            if event.type == "response.output_text.delta":
                print(event.delta, end="", flush=True)
        print()
        print(stream.final_response.id if stream.final_response else "no final response")

A valid SSE response contains exactly one terminal event—response.completed, response.failed, or response.incomplete—followed by the private [DONE] sentinel. The sentinel is not yielded as a protocol event. Sequence gaps are allowed, but supplied sequence numbers must strictly increase. See streaming semantics.

WebSockets and continuation

A connection accepts one in-flight turn at a time. A completed, failed, or errored turn releases it for the next turn. The SDK never reconnects or resends automatically: with store=False, continuation state can be local to the connection and replay may execute work twice.

from openresponses import CreateResponseRequest, OpenResponses

with OpenResponses() as client, client.websocket() as websocket:
    turn = websocket.create(CreateResponseRequest(model="your-model", input="Hello"))
    for event in turn:
        print(event.type)

    if turn.error is not None:
        print(f"turn failed: {turn.error.error.code}: {turn.error.error.message}")
    elif turn.final_response is not None:
        previous_response_id = turn.final_response.id

AsyncWebSocketConnection provides the corresponding asynchronous API. For continuation, recovery, compaction handoff, and reconnect guidance, see WebSocket semantics.

Function calls are not executed

The SDK is a protocol client, not an agent runner. It returns function_call items but never executes tools automatically. Inspect each call, run application-owned code yourself, then send a matching function_call_output item, using previous_response_id only when the provider has retained that response. See protocol models.

Compaction

responses.compact(...) posts a CompactResponseRequest to /responses/compact and returns a CompactResource. Compaction has no streaming mode. Its output can seed a new request or WebSocket turn, typically without previous_response_id.

Errors and retries

All SDK exceptions derive from OpenResponsesError. HTTP failures retain the status, raw body, headers, request URL, and parsed provider error where available. Common subclasses include BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, RateLimitError, ModelError, InternalServerError, APIConnectionError, and APITimeoutError. Invalid success payloads and malformed event streams raise validation or protocol errors. Each operation also accepts a per-call timeout override.

The SDK performs no automatic retries. Response creation can bill or execute work and the protocol has no universal idempotency key. Retry only when your application understands duplicate-work risk and provider semantics.

Provider extensions

Models preserve unknown extension fields and serialize them with model_dump(mode="json", by_alias=True). Unknown provider-prefixed streaming events become UnknownStreamingEvent records rather than being discarded. Malformed records claiming a known standard event type are rejected, not downgraded to an opaque event.

For Ollama, vLLM, llama.cpp, LM Studio, SGLang, and other partial OpenAI-compatible runtimes, see provider compatibility. Compatibility mode is explicit and preserves strict OpenResponses validation by default.

Documentation

Read the hosted documentation at openresponses-python.readthedocs or locally with python -m mkdocs serve.

The site covers the quickstart, typed protocol models, SSE streaming, WebSocket turns, and provider compatibility. Runnable examples live in examples/.

The package includes the pinned schema at openresponses/openapi/2026-04-24.json. Compatibility is for that dated release; later protocol versions require an explicit SDK/model update.

Release files for openresponses-py 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for openresponses-py 0.1.1
File Size Uploaded
openresponses_py-0.1.1.tar.gz 59.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for openresponses-py 0.1.1
File Interpreter ABI Platform
openresponses_py-0.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 114.0 kB

Release files / openresponses_py-0.1.1.tar.gz

Download URL openresponses_py-0.1.1.tar.gz
Size 59.5 kB
Tags Source
SHA-256 checksum
How to use checksums
703286216e17977064073a6fb2f97645b40bc6d38bab8872db4c8d7199cf70a0
BLAKE2b-256 checksum
How to use checksums
4ca0cc4d3d2f7f642f8047f41fe762a7698ab6892d5241a48634280eb059684a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 25, 2026.

Transparency log

Release files / openresponses_py-0.1.1-py3-none-any.whl

Download URL openresponses_py-0.1.1-py3-none-any.whl
Size 54.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e597ab5f33025e0369114acd96e6def5ae63d4ccc9a472824f165c0af02389c5
BLAKE2b-256 checksum
How to use checksums
1beaa6a6f63c85577e1078653715e19c666e015d85fa2b1e29f69ec969c4ec1d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 25, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page