> ## Documentation Index
> Fetch the complete documentation index at: https://docs.playapi.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

> Configure a compatible base URL for Chat Completions and Responses.

Use the official OpenAI Python SDK. Set the [environment variables](/en/guides/api-basics) first. Run these examples on a server or in a terminal.

## Install

Requires Python 3.10+.

```bash theme={null}
python3 -m venv .venv
source .venv/bin/activate
python -m pip install openai==3.31.0
```

These are the versions used to verify the examples. Upgrade according to your dependency policy and retest.

## Chat Completions

Save as `chat.py`.

```python theme={null}
import os
from openai import OpenAI, APIConnectionError, APIStatusError

with OpenAI(
    base_url=os.environ["API_BASE_URL"].rstrip("/"),
    api_key=os.environ["API_KEY"],
    timeout=60.0,
    max_retries=0,
) as client:
    try:
        result = client.chat.completions.create(
            model=os.environ["API_MODEL"],
            messages=[{"role": "user", "content": "Say hello in one short sentence."}],
        )
        print(result.choices[0].message.content or "")
    except APIStatusError as error:
        raise SystemExit(f"Request failed (HTTP {error.status_code}). Check the request logs.")
    except APIConnectionError:
        raise SystemExit("Connection failed. Check the API address and network.")
```

## Responses

Save as `responses.py`. Select a Responses-compatible model first.

```python theme={null}
import os
from openai import OpenAI, APIConnectionError, APIStatusError

with OpenAI(
    base_url=os.environ["API_BASE_URL"].rstrip("/"),
    api_key=os.environ["API_KEY"],
    timeout=60.0,
    max_retries=0,
) as client:
    try:
        result = client.responses.create(
            model=os.environ["API_MODEL"],
            input="Say hello in one short sentence.",
        )
        if result.status != "completed" or not result.output_text.strip():
            raise SystemExit("Response did not complete with usable text.")
        for item in result.output:
            if item.type == "reasoning":
                continue
            if (item.type != "message" or item.status != "completed"
                    or any(part.type != "output_text" for part in item.content)):
                raise SystemExit("Response did not complete with usable text.")
        print(result.output_text)
    except APIStatusError as error:
        raise SystemExit(f"Request failed (HTTP {error.status_code}). Check the request logs.")
    except APIConnectionError:
        raise SystemExit("Connection failed. Check the API address and network.")
```

## Run and handle results

```bash theme={null}
python chat.py
python responses.py
```

Each command sends a real request; run only the one you need. Examples use a 60-second timeout and disable SDK retries to avoid implicit repeated requests. Design timeout, retry, and concurrency policies for production.

Chat Completions text can be empty, for example during tool calls. The Responses example requires `completed` status. `output_text` is an SDK convenience property that joins text; handle tools and other non-text output separately.

[Streaming](/en/guides/streaming) · [Error handling](/en/guides/errors)

Reference: [Official OpenAI Python SDK documentation](https://developers.openai.com/api/reference/python)。

The text-only Responses example rejects empty text, refusals, tool calls, and incomplete output. Continue with the full Responses examples in [conversations](/en/guides/conversations), [tool calling](/en/guides/tool-calling), and [structured output](/en/guides/structured-output).

[简体中文](/zh/guides/python)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.