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

# Python SDK

> 配置兼容地址，调用 Chat Completions 和 Responses。

使用官方 OpenAI Python SDK。先设置[环境变量](/zh/guides/api-basics.md)，以下代码只在服务端或终端运行。

## 安装

需要 Python 3.10+。

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

版本为本轮示例验证版本；生产项目按自己的依赖策略升级并复测。

## Chat Completions

保存为 `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

保存为 `responses.py`。 请先选择支持 Responses 的模型。

```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.")
```

## 运行与处理结果

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

两个命令会分别发起真实请求，按需选择一个运行。示例把超时设为 60 秒，并关闭 SDK 自动重试，避免示例在失败时隐式重复请求。生产环境需设计自己的超时、重试和并发策略。

Chat Completions 的文本可能为空（例如工具调用）；Responses 示例只接受 `completed` 状态。`output_text` 是 SDK 汇总文本的属性，工具调用等非文本输出需要单独处理。

[流式输出](/zh/guides/streaming.md) · [错误处理](/zh/guides/errors.md)

参考：[OpenAI Python SDK 官方说明](https://developers.openai.com/api/reference/python)。

Responses 纯文本示例会拒绝空文本、拒答、工具调用及未完成输出。进一步接入见[多轮对话](/zh/guides/conversations.md)、[工具调用](/zh/guides/tool-calling.md)和[结构化输出](/zh/guides/structured-output.md)中的 Responses 完整示例。

[Read in English](/en/guides/python.md)


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