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

# Python 与 Node.js SDK 接入

> 通过 OpenAI SDK 在服务端调用 APIONE。

使用 OpenAI SDK 调用 APIONE 时，配置基础地址、APIONE API Key 和模型 ID 即可。以下示例在服务端运行。

## 运行前准备

按[快速开始](https://apione.ai/docs/quickstart.md)设置 `APIONE_API_KEY` 和 `APIONE_MODEL`。模型 ID 从[可用模型列表](https://apione.ai/docs/models/catalog.md)复制；未设置变量时，示例会停止，不会回退到固定型号。

| 配置 | 值 |
| - | - |
| Python `base_url` / Node.js `baseURL` | `https://api.apione.ai/v1` |
| API Key | 环境变量 `APIONE_API_KEY` |
| 模型 | 环境变量 `APIONE_MODEL` |

不要把完整的 `/chat/completions` 端点填进 SDK 的基础地址；SDK 会自行拼接接口路径。

## Python

安装依赖：

```bash theme={null}
python -m pip install openai
```

保存为 `app.py`：

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

try:
    with OpenAI(
        base_url="https://api.apione.ai/v1",
        api_key=os.environ["APIONE_API_KEY"],
        timeout=60.0,
        max_retries=0,
    ) as client:
        raw = client.chat.completions.with_raw_response.create(
            model=os.environ["APIONE_MODEL"],
            messages=[{"role": "user", "content": "列出 API 文档的三个基本部分。"}],
        )
        request_ids = {name: raw.headers[name] for name in
                       ("X-Request-ID", "X-Maxx-Trace-Id", "X-Maxx-Request-ID")
                       if name in raw.headers}
        print("request identifiers:", request_ids)
        response = raw.parse()
        if response.choices:
            print(response.choices[0].message.content)
        print(response.usage)
except APIStatusError as error:
    print("HTTP status:", error.status_code)
    headers = error.response.headers
    print("request identifiers:", {name: headers[name] for name in
          ("X-Request-ID", "X-Maxx-Trace-Id", "X-Maxx-Request-ID") if name in headers})
    raise SystemExit(1) from None
except APIConnectionError:
    print("Connection failed: no HTTP response or server request ID received.")
    raise SystemExit(1) from None
```

运行 `python app.py`。正常返回时，正文位于 `choices[0].message.content`，`usage` 用于观察 Token 用量；最终费用到控制台核对。

## Node.js

安装依赖：

```bash theme={null}
npm install openai
```

保存为 `app.mjs`：

```javascript theme={null}
import OpenAI from "openai";

const apiKey = process.env.APIONE_API_KEY;
const model = process.env.APIONE_MODEL;
if (!apiKey || !model) {
  throw new Error("请先设置 APIONE_API_KEY 和 APIONE_MODEL");
}
const client = new OpenAI({
  baseURL: "https://api.apione.ai/v1",
  apiKey,
  timeout: 60_000,
  maxRetries: 0,
});
try {
  const { data: response, response: httpResponse } = await client.chat.completions.create({
    model,
    messages: [{ role: "user", content: "列出 API 文档的三个基本部分。" }],
  }).withResponse();
  console.log("request identifiers:", Object.fromEntries(
    ["X-Request-ID", "X-Maxx-Trace-Id", "X-Maxx-Request-ID"]
      .map(name => [name, httpResponse.headers.get(name)])
      .filter(([, value]) => value)
  ));
  console.log(response.choices[0]?.message?.content);
  console.log(response.usage);
} catch (error) {
  if (error instanceof OpenAI.APIError) {
    console.error("HTTP status:", error.status ?? "No HTTP response");
    console.error("request identifiers:", Object.fromEntries(
      ["X-Request-ID", "X-Maxx-Trace-Id", "X-Maxx-Request-ID"]
        .map(name => [name, error.headers?.get(name)])
        .filter(([, value]) => value)
    ));
  } else {
    console.error("Local configuration or unexpected error; no server response confirmed.");
  }
  process.exitCode = 1;
}
```

运行 `node app.mjs`。使用当前 SDK 支持的 Node.js 版本，并在项目中锁定依赖版本。

### 设置环境变量并启动

在同一终端设置密钥和实际模型 ID，再运行保存的文件：

```bash theme={null}
export APIONE_API_KEY="YOUR_APIONE_KEY"
export APIONE_MODEL="YOUR_APIONE_MODEL_ID"
node app.mjs
```

```powershell theme={null}
$env:APIONE_API_KEY = "YOUR_APIONE_KEY"
$env:APIONE_MODEL = "YOUR_APIONE_MODEL_ID"
node app.mjs
```

## 超时、重试与排查

示例使用 60 秒 SDK 超时并关闭 SDK 自动重试，便于观察单次请求；这不是平台的固定时限。生产环境按业务需求设置，核对 SDK 默认重试行为，避免与应用自己的重试叠加。

记录状态码、请求 ID 与耗时，日志中的敏感字段要脱敏。调用失败先核对基础地址、Key 和模型 ID，再查看[错误码与排查](https://apione.ai/docs/support/errors.md)。流式接收见[流式输出](https://apione.ai/docs/models/streaming.md)。

接入依据：[APIONE OpenAI SDK 文档](https://apione.ai/zh/api-docs/sdk/sdk-openai)。


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