Skip to content

SDK and Code Examples ​

We recommend using the official OpenAI SDK or a compatible SDK, and explicitly configuring the Base URL. If the SDK still sends requests to the official address, the configuration field name is usually incorrect, an environment variable is overriding it, or the SDK version is outdated.

OpenAI Python SDK ​

python
from openai import OpenAI

client = OpenAI(api_key="sk-your-token", base_url="https://api.cloudaikit.com/v1")

completion = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "解释一下渠道路由"}],
)
print(completion.choices[0].message.content)

OpenAI Node.js SDK ​

js
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.OPEN01_API_KEY,
  baseURL: "https://api.cloudaikit.com/v1",
});

const stream = await client.chat.completions.create({
  model: "gpt-4o-mini",
  stream: true,
  messages: [{ role: "user", content: "分三点说明 API 网关的作用" }],
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content || "");
}

Multi-turn Conversations ​

For multi-turn conversations, the client must save the historical messages and send them with the next request. The longer the history, the more input tokens are required, and the more likely the context limit is to be reached.

Development Recommendations ​

  • Store tokens on the server; do not expose long-lived keys in the browser frontend.
  • Use separate tokens for each environment, such as development, testing, and production.
  • Log the Request ID, model, duration, and errors to facilitate comparison with console logs.
  • Use exponential backoff retries for 429 errors, timeouts, and upstream 5xx errors.
  • Configure a fallback model or backup channel for important tasks.