---
title: "OpenAI Python SDK"
description: "Run the exact Python source exercised for non-streaming and streaming compatibility."
---

> Documentation Index
> Fetch the complete documentation index at: https://nexus.microvoid.io/llms.txt
> Use this file to discover all available pages before exploring further.

# OpenAI Python SDK

## Outcome

同一个 OpenAI Python Client 完成普通请求和 Streaming 请求，并从流末尾读取上游 Usage。

## Install


```sh title="Terminal"
python3 -m venv .venv
. .venv/bin/activate
pip install openai==2.46.0
```


## Configure


```sh title="Terminal"
export NEXUS_BASE_URL="https://gateway.nexus.microvoid.io/providers/00000000-0000-0000-0000-000000000141"
export NEXUS_API_KEY="<NEXUS_INFERENCE_KEY>"
export NEXUS_MODEL="provider/opaque-model-v9"
```


## Run


```python title="openai-python.py"
"""Public OpenAI Python SDK quickstart executed by the Nexus compatibility E2E suite."""

import json
import os

import openai
from openai import OpenAI


def required_environment(name: str) -> str:
    value = os.environ.get(name, "").strip()
    if not value:
        raise RuntimeError(f"{name} is required")
    return value


client = OpenAI(
    base_url=required_environment("NEXUS_BASE_URL"),
    api_key=required_environment("NEXUS_API_KEY"),
    max_retries=0,
    timeout=10.0,
)
model = required_environment("NEXUS_MODEL")
messages = [{"role": "user", "content": "Keep this Python request unchanged."}]

completion = client.chat.completions.create(model=model, messages=messages)
stream = client.chat.completions.create(
    model=model,
    messages=messages,
    stream=True,
    stream_options={"include_usage": True},
)
stream_text = ""
stream_usage = None
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        stream_text += chunk.choices[0].delta.content
    if chunk.usage is not None:
        stream_usage = chunk.usage.total_tokens

print(
    json.dumps(
        {
            "sdk_version": openai.__version__,
            "model": completion.model,
            "content": completion.choices[0].message.content,
            "stream_text": stream_text,
            "stream_usage": stream_usage,
        }
    )
)
```


```sh title="Terminal"
python openai-python.py
```

## Check your work

JSON 输出应包含锁定的 SDK 版本、原始模型名、普通响应正文、拼接后的 Streaming 正文和末尾 `stream_usage`。

> **Executable source**
>
> 代码块由 `tests/e2e/examples/openai-python.py` 生成，并在 Node 与 Cloudflare Gateway Composition 上使用进程内 Fake
> Provider 执行；缺少锁定 Python SDK 时 E2E 会明确失败而不是跳过。

Source: https://nexus.microvoid.io/docs/make-model-requests/openai-python/index.mdx
