# 用 OpenAI SDK（Python / Node.js）调用 BigModel.io

> 在官方 OpenAI Python 和 Node.js SDK 中把 base_url 设为 https://bigmodel.io/v1，即可调用 GLM、Kimi、DeepSeek、MiniMax 等模型，含流式、工具调用和排查。

网页版: https://bigmodel.io/zh-cn/docs/openai-sdk-langchain · 更新于 2026-10-18

BigModel.io 兼容 OpenAI Chat Completions 协议，官方 OpenAI SDK 只需改两个值：Base URL 和 API Key。

| 配置项 | 值 |
|---|---|
| Base URL | `https://bigmodel.io/v1` |
| API Key | 你的 BigModel.io Key（`sk-...`），从环境变量读取 |
| 模型 | [模型目录](https://bigmodel.io/zh-cn/models)中的模型 ID，例如 `glm-5.3` |

Key 能调用哪些模型取决于它所在的分组。以下示例都从 `BIGMODEL_API_KEY` 读取 Key：

```bash
export BIGMODEL_API_KEY="sk-..."
```

## 安装

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

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

## 最小调用

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

client = OpenAI(
    base_url="https://bigmodel.io/v1",
    api_key=os.environ["BIGMODEL_API_KEY"],
)

completion = client.chat.completions.create(
    model="glm-5.3",
    messages=[{"role": "user", "content": "用三句话解释什么是向量数据库。"}],
)
print(completion.choices[0].message.content)
```

```js [Node.js]
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://bigmodel.io/v1",
  apiKey: process.env.BIGMODEL_API_KEY,
});

const completion = await client.chat.completions.create({
  model: "glm-5.3",
  messages: [{ role: "user", content: "用三句话解释什么是向量数据库。" }],
});
console.log(completion.choices[0].message.content);
```

不传参数时，两个 SDK 都会读取 `OPENAI_BASE_URL` 和 `OPENAI_API_KEY`。这样不改代码就能切换，但同一进程里的其他 OpenAI 客户端也会被一起改到 BigModel.io。

## 流式输出

```python [Python]
stream = client.chat.completions.create(
    model="glm-5.3",
    messages=[{"role": "user", "content": "写一首关于延迟的俳句。"}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
```

```js [Node.js]
const stream = await client.chat.completions.create({
  model: "glm-5.3",
  messages: [{ role: "user", content: "写一首关于延迟的俳句。" }],
  stream: true,
});
for await (const part of stream) {
  process.stdout.write(part.choices[0]?.delta?.content || "");
}
```

GLM、DeepSeek 分组会自动开启 `stream_options.include_usage`，最后一个 chunk 带 `usage`，`choices` 为空列表，代码里要像上面一样做判断。流开始后出现的错误以 SSE `error` 事件返回。

## 工具调用

`tools` 和 `tool_choice` 会原样转给模型。模型是否返回工具调用取决于模型本身，正式使用前先测一下。完整循环见[工具调用](https://bigmodel.io/zh-cn/docs/tool-calling)。

```python [Python]
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "查询城市当前天气",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]

completion = client.chat.completions.create(
    model="glm-5.3",
    messages=[{"role": "user", "content": "杭州现在天气怎么样？"}],
    tools=tools,
)
print(completion.choices[0].message.tool_calls)
```

```js [Node.js]
const tools = [{
  type: "function",
  function: {
    name: "get_weather",
    description: "查询城市当前天气",
    parameters: {
      type: "object",
      properties: { city: { type: "string" } },
      required: ["city"],
    },
  },
}];

const completion = await client.chat.completions.create({
  model: "glm-5.3",
  messages: [{ role: "user", content: "杭州现在天气怎么样？" }],
  tools,
});
console.log(completion.choices[0].message.tool_calls);
```

## 推理内容

GLM、DeepSeek 分组的响应原样透传，思考模型返回的 `reasoning_content` 字段会到达 SDK。它不是类型化属性，按额外字段读取：

```python [Python]
message = completion.choices[0].message
print(getattr(message, "reasoning_content", None))
```

```js [Node.js]
console.log(completion.choices[0].message.reasoning_content);
```

控制思考的参数见[推理与思考](https://bigmodel.io/zh-cn/docs/reasoning)。

## Responses API

`client.responses.create(...)` 调用的是 `https://bigmodel.io/v1/responses`。只有部分分组提供该接口，GLM、DeepSeek 分组会返回 404。Chat Completions 对所有文本模型都可用。HTTP 方式下 `previous_response_id` 会返回 400，每次请发送完整 input。

```python [Python]
response = client.responses.create(model="YOUR_MODEL_ID", input="ping")
print(response.output_text)
```

```js [Node.js]
const response = await client.responses.create({ model: "YOUR_MODEL_ID", input: "ping" });
console.log(response.output_text);
```

## 验证配置

列出 Key 可调用的模型。能返回列表（哪怕很短）就说明 Base URL 和 Key 都对：

```python [Python]
for model in client.models.list():
    print(model.id)
```

```js [Node.js]
for await (const model of client.models.list()) {
  console.log(model.id);
}
```

再发一次请求，确认它出现在[用量](https://bigmodel.io/usage)页面。

## LangChain

LangChain 的 `ChatOpenAI` 使用同一个 Base URL：

```python
import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="glm-5.3", base_url="https://bigmodel.io/v1", api_key=os.environ["BIGMODEL_API_KEY"])
```

流式用量统计、`ChatAnthropic` 以及 `reasoning_content` 的限制见 [LangChain](https://bigmodel.io/zh-cn/docs/langchain)。

## OpenRouter 风格请求

同样的接口也接受 `z-ai/glm-5.3` 这类 `provider/model` 名称、`models` 备选数组，以及 `HTTP-Referer` / `X-Title` 请求头。额外的 body 字段在 Python 里用 `extra_body` 传，Node.js 里直接作为属性传。详见 [OpenRouter 兼容](https://bigmodel.io/zh-cn/docs/openrouter-compat)和[从 OpenRouter 迁移](https://bigmodel.io/zh-cn/docs/migrate-from-openrouter)。

## 常见问题排查

**所有请求都 404。** Base URL 少了 `/v1`，或者多写了 `/chat/completions`。只填 `https://bigmodel.io/v1`，路径由 SDK 自己拼。

**401 `INVALID_API_KEY` 或 `API_KEY_REQUIRED`。** 运行代码的进程里环境变量是空的。打印 Key 的前几位确认，不要打印完整 Key。

**503 `No available accounts: no available accounts supporting model: ...`。** 模型 ID 拼错了，或者 Key 所在分组不提供该模型。模型 ID 全小写并保留点号，从 `client.models.list()` 或[模型目录](https://bigmodel.io/zh-cn/models)复制。

**404 `... only supports /v1/chat/completions`。** 用只支持 Chat Completions 的分组 Key 调了 Responses API。改用 `chat.completions.create`。

**`response_format` 好像没生效。** 非 GLM、DeepSeek 分组的 Chat Completions 请求会被转换，`response_format`、`n`、`seed`、`user`、`logprobs` 会被丢弃。见[结构化输出](https://bigmodel.io/zh-cn/docs/structured-output)。

**403 `INSUFFICIENT_BALANCE`。** 余额小于等于 0，到[充值](https://bigmodel.io/purchase)页面充值。`models.list()` 同样需要余额大于 0。

**429 `API_KEY_QUOTA_EXHAUSTED` 或 `rate_limit_exceeded`。** Key 的额度或 5 小时/1 天/7 天消费上限已用完，或触发了每分钟请求数限制。见[限额与速率](https://bigmodel.io/zh-cn/docs/rate-limits)。普通 429 保留 SDK 自带的重试即可。

**长输出超时。** 改用流式，或调大客户端超时（Python 用 `timeout=`，Node.js 用 `timeout:`）。

## 相关文档

- [LangChain](https://bigmodel.io/zh-cn/docs/langchain)、[LlamaIndex](https://bigmodel.io/zh-cn/docs/llamaindex)、[Vercel AI SDK](https://bigmodel.io/zh-cn/docs/vercel-ai-sdk)
- [Anthropic SDK](https://bigmodel.io/zh-cn/docs/anthropic-sdk)：调用 Messages API
- [OpenAI SDK 兼容 API：Base URL、模型 ID 与错误](https://bigmodel.io/zh-cn/blog/openai-sdk-compatible-api)
- [快速开始](https://bigmodel.io/zh-cn/docs/quickstart)和[错误码](https://bigmodel.io/zh-cn/docs/errors)
