Source: https://wiki.niceai.dev/guide/clients/openai-sdk

# OpenAI SDK 接入自定义 API

在 OpenAI 官方 SDK 中把 `base_url`（Python）或 `baseURL`（Node.js）设为 `https://api.niceai.dev/v1`，`api_key` 填 NiceAI 密钥，其余代码无需改动。

## 准备工作

1. 在 NiceAI 控制台「[API 密钥](https://niceai.dev/keys)」页面创建密钥，分组选择 **OpenAI**（或支持 Chat Completions 的其他分组）。
2. 把密钥存到环境变量 `NICEAI_API_KEY`，不要写死在代码里，见 [API 密钥安全最佳实践](https://wiki.niceai.dev/guide/key-security)。

## 安装

**-group**

```bash [Python]
pip install openai
```

```bash [Node.js]
npm install openai
```



## Chat Completions

**-group**

```python [Python]
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.niceai.dev/v1",
    api_key=os.environ["NICEAI_API_KEY"],
)

resp = client.chat.completions.create(
    model="<模型名，见模型广场>",
    messages=[{"role": "user", "content": "你好"}],
)
print(resp.choices[0].message.content)
```

```js [Node.js]
import OpenAI from 'openai'

const client = new OpenAI({
  baseURL: 'https://api.niceai.dev/v1',
  apiKey: process.env.NICEAI_API_KEY,
})

const resp = await client.chat.completions.create({
  model: '<模型名，见模型广场>',
  messages: [{ role: 'user', content: '你好' }],
})
console.log(resp.choices[0].message.content)
```



## Responses

**-group**

```python [Python]
r = client.responses.create(model="<模型名，见模型广场>", input="你好")
print(r.output_text)
```

```js [Node.js]
const r = await client.responses.create({ model: '<模型名，见模型广场>', input: '你好' })
console.log(r.output_text)
```



## 用环境变量切换

OpenAI SDK 也会读取环境变量，不改代码就能切换地址：

**-group**

```bash [macOS / Linux]
export OPENAI_BASE_URL="https://api.niceai.dev/v1"
export OPENAI_API_KEY="你的 NiceAI 密钥"
```

```powershell [Windows PowerShell]
$env:OPENAI_BASE_URL = "https://api.niceai.dev/v1"
$env:OPENAI_API_KEY = "你的 NiceAI 密钥"
```



## 更多用法

- 流式输出：加 `stream=True`（Node.js 为 `stream: true`），见 [流式输出（SSE）](https://wiki.niceai.dev/guide/api/streaming)。
- 工具调用：见 [工具调用（Function Calling）](https://wiki.niceai.dev/guide/api/tools)。
- 图片输入：见 [图片输入（Vision）](https://wiki.niceai.dev/guide/api/vision)。
- 重试与超时：见 [限流、超时与重试](https://wiki.niceai.dev/guide/api/rate-limits)。

## 常见问题

### 404？

`base_url` 必须带 `/v1`。详见 [接口地址要不要加 /v1](https://wiki.niceai.dev/guide/v1-404)。

### Responses 接口报错？

确认所选模型和分组支持 Responses 接口，不支持时改用 Chat Completions。两者的区别见 [Chat Completions 与 Responses API 的区别](https://wiki.niceai.dev/guide/tech/responses-vs-chat-completions)。

## 下一步

- [Anthropic SDK 接入](https://wiki.niceai.dev/guide/clients/anthropic-sdk)
- [从官方 API 迁移](https://wiki.niceai.dev/guide/migrate-from-official-api)
