Python and Node.js SDK

Provide the key with environment variables and call the OpenAI compatible interface on the server.

This article calls the Chat Completions of this site through the OpenAI official SDK on the server side. After installing, configuring the environment, and running in order, you should see model replies, usage, and request IDs.

Preparation before starting

Complete Quick Start first, confirm that the key can query the model, and select a model that supports Chat Completions. Python uses the Python version supported by the current SDK (the current official requirement is Python 3.10 or newer); Node.js uses the LTS version supported by the current SDK.

Configuration Fill in content
Python base_url / Node.js baseURL https://dunduntoken.com/v1
DUNDUN_API_KEY Site key created for the application
DUNDUN_MODEL The exact model ID available for the current key

The SDK will append the interface path, do not write /chat/completions into the Base URL. The following code should be run on the server side.

Step one: Set environment variables

Execute in Bash or zsh, enter the key, press Enter, and replace the model placeholder:

printf 'API Key: '
read -rs DUNDUN_API_KEY
printf '\n'
export DUNDUN_API_KEY
export DUNDUN_MODEL="MODEL_ID"

PowerShell can use hidden input to read the key and then set the process environment variables:

$credential = Get-Credential -UserName "api" -Message "在密码栏填写本站 API Key"
$env:DUNDUN_API_KEY = $credential.GetNetworkCredential().Password
$env:DUNDUN_MODEL = "MODEL_ID"
Remove-Variable credential

These settings only apply to the current terminal and its child processes. When deploying to a container or server, set the variable with the same name in the environment of the actual application process.

Step 2: Select language and install SDK

Python: Create a standalone environment

python -m venv .venv

macOS, Linux or Bash environment activation:

source .venv/bin/activate
python -m pip install openai

Windows PowerShell activation:

.\.venv\Scripts\Activate.ps1
python -m pip install openai

If the system only has the python3 command, replace python with python3 when creating the environment. After activation, use Python within the environment.

Node.js: Install dependencies

Execute in your Node.js project directory:

npm install openai

Projects using Bun can also execute bun add openai. Keep the project lock file to facilitate installation of the same version during deployment.

Step 3: Save and run the example

###Python

Save as app.py:

import os
from openai import OpenAI, APIConnectionError, APIStatusError

api_key = os.environ.get("DUNDUN_API_KEY")
model = os.environ.get("DUNDUN_MODEL")
if not api_key or not model:
    raise SystemExit("请先设置 DUNDUN_API_KEY 和 DUNDUN_MODEL")

try:
    with OpenAI(
        api_key=api_key,
        base_url="https://dunduntoken.com/v1",
        timeout=60.0,
        max_retries=0,
    ) as client:
        raw = client.chat.completions.with_raw_response.create(
            model=model,
            messages=[{"role": "user", "content": "只回复 OK"}],
        )
        print("Request ID:", raw.headers.get("X-Oneapi-Request-Id"))
        result = raw.parse()
        if result.choices:
            print(result.choices[0].message.content)
        print("Usage:", result.usage)
except APIStatusError as error:
    print("HTTP status:", error.status_code)
    print("Request ID:", error.response.headers.get("X-Oneapi-Request-Id"))
    raise SystemExit(1) from None
except APIConnectionError:
    print("连接失败或超时,请检查网络并核对调用记录")
    raise SystemExit(1) from None

Run in a terminal with environment variables set:

python app.py

Node.js

Save as app.mjs, use the .mjs suffix to directly enable ES Modules:

import OpenAI from "openai";

const apiKey = process.env.DUNDUN_API_KEY;
const model = process.env.DUNDUN_MODEL;
if (!apiKey || !model) {
  throw new Error("请先设置 DUNDUN_API_KEY 和 DUNDUN_MODEL");
}

const client = new OpenAI({
  apiKey,
  baseURL: "https://dunduntoken.com/v1",
  timeout: 60_000,
  maxRetries: 0,
});

try {
  const { data, response } = await client.chat.completions.create({
    model,
    messages: [{ role: "user", content: "只回复 OK" }],
  }).withResponse();
  console.log("Request ID:", response.headers.get("X-Oneapi-Request-Id"));
  console.log(data.choices[0]?.message?.content);
  console.log("Usage:", data.usage);
} catch (error) {
  if (error instanceof OpenAI.APIError) {
    console.error("HTTP status:", error.status ?? "未收到 HTTP 响应");
    console.error("Request ID:", error.headers?.get("X-Oneapi-Request-Id"));
  } else {
    console.error("本地配置或运行错误,请检查环境与依赖");
  }
  process.exitCode = 1;
}

Run:

node app.mjs

Step 4: Confirm that the request is successful

Under normal circumstances, the terminal will display the reply text and Usage. The request ID is displayed when the server returns the corresponding response header; it may be empty when no response header is received. Open Call Record to check the time, model, status and usage. The 60 seconds in the example is the client timeout setting, not a fixed time limit on the platform.

Verify the non-streaming text first, and then press Streaming Output and Tool Call to expand the business. The SDK exposes more methods than the interfaces actually supported by this site. It cannot be inferred from the existence of SDK methods that Files, Fine-tunes or model management are available.

FAQ

Phenomenon Inspection method
Prompt for missing environment variables Set variables in the same terminal where the script is started; IDE, container and service process need to be configured separately
ModuleNotFoundError / openai not found Confirm that the dependencies are installed to the actual Python environment or Node.js project
401 Check the key validity period, actual process variables and whether other platform keys are misused
404 Fill in the Base URL only to /v1 and check whether the model and interface match
400 or parameter error Run the minimum example of this article first, and then add parameters one by one
Timeout or connection failure Check proxy and DNS, and check the call log to see if there has been a request

The example turns off the SDK automatic retry to facilitate troubleshooting a single request. Set timeout and limited retries according to business requirements when going online to avoid repeated retries for applications and SDKs. Only the necessary status code, time consumption and request ID are recorded, and the complete request header or exception object containing credentials is not directly printed.

Continue reading

Responses Access · Request Tracking and Retry · Error Troubleshooting

SDK usage basis: OpenAI Python SDK, OpenAI Node.js SDK.