Skip to content

Commit a4bb700

Browse files
committed
[feat] providers: add Zhipu BigModel GLM chat support
- Register the Zhipu BigModel provider preset with its canonical URL, the Z.ai brand logo and the GLM agent model catalog. - Map the shared thinking levels to GLM reasoning_effort in the shared chat payload. GLM accepts only low, high and max, auto omits the parameter and unknown levels fall back as in the DeepSeek branch. - Cover the preset shape, bilingual labels, saved connection identity and effort mapping with tests, and the provider form and assistant picker with an isolated browser case. - .venv/bin/python -m pytest tests -q: 1083 passed, 6 skipped - npm test: 678 passed - npm run build - npm run check:i18n - CREATION_API_URL=http://127.0.0.1:8019 CREATION_WEB_URL=http://127.0.0.1:5179 node tests/browser/zhipu_provider.mjs - Real credential acceptance: streaming conversation, tool call execution and both display languages verified against open.bigmodel.cn with screenshots. Refs: #236
1 parent f06e22f commit a4bb700

6 files changed

Lines changed: 316 additions & 2 deletions

File tree

‎docs/development/validation.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,17 @@ CREATION_API_URL=http://127.0.0.1:8019 CREATION_WEB_URL=http://127.0.0.1:5179 no
206206

207207
Python 用例使用模拟 HTTP 服务及真实 PNG、MP3,检查请求字段、音色、执行快照、文件探测、工程重开和下载恢复不重复生成。通用错误分类和安全提示由现有错误测试负责。浏览器用例检查两种语言下的提供商及型号列表、获取模型失败的具体原因、音色必填、保存重开和实际音频播放;播放器使用隔离服务的 WAV 替身,不代表 MOSS 已生成语音。真实验收另需有效 MOSS 凭证和音色 ID,并保留实际音频、模型标识及播放器截图。
208208

209+
Zhipu BigModel chat access uses the following checks. Browser commands connect to the isolated API and Vite described earlier in this document. Environment variables can override the ports.
210+
211+
```sh
212+
.venv/bin/python -m pytest tests/test_zhipu.py tests/test_model_configs.py -q
213+
node --test tests/providerPresets.test.ts
214+
CREATION_API_URL=http://127.0.0.1:8019 CREATION_WEB_URL=http://127.0.0.1:5179 node tests/browser/zhipu_provider.mjs
215+
```
216+
217+
The Python cases check how the shared thinking levels map to GLM reasoning_effort. GLM accepts only low, high and max for reasoning_effort. The auto level omits the parameter so the provider default applies, and an unknown level falls back to high as in the DeepSeek branch. Other hosts and the DeepSeek behavior stay unchanged.
218+
219+
The browser case checks both display languages for the provider list and names, canonical URL prefill, GLM model preselection without remote discovery, manual addition of other model IDs, the saved connection reuse hint, save and reopen, key privacy in public model responses, and the assistant agent picker listing and keeping the selected Zhipu model. The browser never contacts open.bigmodel.cn and the API key is always a fixture value. Real streaming conversations, tool call execution and thinking level effects additionally require valid Zhipu credentials. Keep the conversation transcript, tool receipts and screenshots as evidence.
209220

210221
### Voice library / 音色库
211222

‎packages/core/src/opendirector/integrations/chat_completions.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""Chat Completions streaming, including DeepSeek's thinking parameters."""
1+
"""Chat Completions streaming, including provider-specific thinking parameters."""
22

33
import json
44
from urllib.parse import urlsplit
@@ -14,8 +14,14 @@
1414
def chat_payload(config: dict, messages: list[dict], thinking: str) -> dict:
1515
value = {"model": config["modelId"], "messages": messages, "stream": True, "max_tokens": 8192}
1616
thinking_map = {"auto": "high", "low": "low", "medium": "high", "high": "max"}
17-
if urlsplit(config["url"]).hostname == "api.deepseek.com":
17+
hostname = urlsplit(config["url"]).hostname
18+
if hostname == "api.deepseek.com":
1819
value.update(thinking={"type": "enabled"}, reasoning_effort=thinking_map.get(thinking, thinking_map["auto"]))
20+
elif hostname == "open.bigmodel.cn":
21+
# GLM reasoning_effort accepts only low, high and max. Omit the parameter for
22+
# auto so the provider default applies, and fall back to high for unknown levels.
23+
if thinking != "auto":
24+
value["reasoning_effort"] = thinking_map.get(thinking, thinking_map["auto"])
1925
elif thinking != "auto":
2026
value["reasoning_effort"] = thinking
2127
if len(json.dumps(value, ensure_ascii=False).encode()) > 48 * 1024 * 1024:

‎src/canvas/providerPresets.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { getActiveLocale } from "../i18n/messages.ts";
66
const EN_NAMES: Record<string, string> = {
77
"OpenAI 兼容": "OpenAI compatible",
88
"MiniMax 官方视频": "MiniMax official video",
9+
"智谱 BigModel": "Zhipu BigModel",
910
"MOSS 开放平台": "MOSS Open Platform",
1011
"火山方舟 / Agent Plan": "Volcano Ark / Agent Plan",
1112
"vLLM-Omni 图片接口": "vLLM-Omni image API",
@@ -106,6 +107,19 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
106107
connectionType: "api",
107108
authMode: "bearer",
108109
},
110+
{
111+
id: "zhipu",
112+
logoOrganization: "zai-org",
113+
name: "智谱 BigModel",
114+
kinds: ["agent"],
115+
url: "https://open.bigmodel.cn/api/paas/v4",
116+
protocol: "openai",
117+
connectionType: "api",
118+
authMode: "bearer",
119+
modelsByKind: {
120+
agent: ["glm-5.3", "glm-5.3-flash", "glm-5.2"],
121+
},
122+
},
109123
{
110124
id: "moss",
111125
logoOrganization: "OpenMOSS-Team",

‎tests/browser/zhipu_provider.mjs‎

Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
/** Isolated Zhipu BigModel provider UI proof. Saves a fixture key and never calls a model service.
2+
* Start creation_server.py on 8029 and Vite on 5189 with its API proxy on 8029.
3+
* CREATION_WEB_URL, CREATION_API_URL and ZHIPU_SCREENSHOT_DIR override defaults.
4+
*/
5+
import assert from "node:assert/strict";
6+
import { mkdir } from "node:fs/promises";
7+
import { join } from "node:path";
8+
import { launchBrowser } from "./engine.mjs";
9+
10+
const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5189";
11+
const api = process.env.CREATION_API_URL ?? "http://127.0.0.1:8029";
12+
const output = process.env.ZHIPU_SCREENSHOT_DIR ?? "/tmp/opendirector-zhipu-evidence";
13+
const modelIds = ["glm-5.3", "glm-5.3-flash", "glm-5.2"];
14+
const canonicalURL = "https://open.bigmodel.cn/api/paas/v4";
15+
const fixtureKey = "zhipu-browser-fixture-only-no-real-service";
16+
const headers = { "X-OpenDirector-Request": "1", "Content-Type": "application/json" };
17+
async function call(path, { method = "GET", body } = {}) {
18+
const response = await fetch(api + path, {
19+
method,
20+
headers,
21+
...(body ? { body: JSON.stringify(body) } : {}),
22+
});
23+
assert.ok(response.ok, `Fixture API ${method} ${path}: ${response.status}`);
24+
return response.status === 204 ? null : response.json();
25+
}
26+
const health = await call("/api/creation-test-health");
27+
assert.equal(health.isolated, true, "Run only against creation_server.py");
28+
assert.equal(health.provider, "fixture");
29+
const webHealth = await (await fetch(base + "/api/creation-test-health", { headers })).json();
30+
assert.equal(webHealth.root, health.root, "Web proxy must use the same isolated API");
31+
const removedServices = new Set();
32+
for (const config of await call("/api/model-configs")) {
33+
const serviceId = config.providerId ?? config.id;
34+
if (config.url.replace(/\/+$/, "") === canonicalURL && modelIds.includes(config.modelId) && !removedServices.has(serviceId)) {
35+
await call(`/api/model-services/${config.id}`, { method: "DELETE" });
36+
removedServices.add(serviceId);
37+
}
38+
}
39+
await mkdir(output, { recursive: true });
40+
const projectId = crypto.randomUUID();
41+
await call(`/api/creation/projects/${projectId}/commands`, {
42+
method: "POST",
43+
body: { commandId: crypto.randomUUID(), projectId, type: "project.create",
44+
payload: { name: `Zhipu provider UI fixture ${projectId.slice(0, 8)}` } },
45+
});
46+
47+
const copy = {
48+
"zh-CN": {
49+
settings: "设置", models: "模型接入", agentOverview: "文本模型", chat: "对话",
50+
add: "添加服务", provider: "提供商", zhipu: "智谱 BigModel", url: "服务地址(Base URL)",
51+
reload: "载入支持的模型", save: "保存服务", cancel: "取消", manage: "管理", close: "关闭设置",
52+
chatEntry: "与 AI 对话", manual: "手动添加", manualAdd: "添加", manualId: "Model ID(服务的 served-model-name)",
53+
},
54+
"en-US": {
55+
settings: "Settings", models: "Model connections", agentOverview: "Text model", chat: "Chat",
56+
add: "Add service", provider: "Provider", zhipu: "Zhipu BigModel", url: "Service URL (Base URL)",
57+
reload: "Load supported models", save: "Save service", cancel: "Cancel", manage: "Manage", close: "Close settings",
58+
chatEntry: "Chat with AI", manual: "Add manually", manualAdd: "Add", manualId: "Model ID (the service's served-model-name)",
59+
},
60+
};
61+
const browser = await launchBrowser();
62+
const page = await browser.newPage({ viewport: { width: 1500, height: 1000 } });
63+
page.setDefaultTimeout(15000);
64+
await page.addInitScript(() => {
65+
localStorage.setItem("opendirector.modelSetup.v1", "dismissed");
66+
localStorage.setItem("opendirector.locale.v1", "zh-CN");
67+
});
68+
const requests = [];
69+
const errors = [];
70+
page.on("request", request => requests.push(request.url()));
71+
page.on("pageerror", error => errors.push(error.message));
72+
const shot = name => page.screenshot({ path: join(output, name), fullPage: true });
73+
const provider = labels => page.getByRole("combobox", { name: labels.provider, exact: true });
74+
// Filter an option card by its checkbox so glm-5.3 does not substring-match glm-5.3-flash.
75+
const optionRow = modelId =>
76+
page.locator(".cw-model-option").filter({ has: page.getByRole("checkbox", { name: modelId, exact: true }) });
77+
const pickerRow = page.getByRole("menuitemradio", { name: "glm-5.3", exact: true });
78+
async function brandLogo(image) {
79+
await image.waitFor();
80+
await image.evaluate(element => element.decode());
81+
assert.ok(await image.evaluate(element => element.naturalWidth > 0));
82+
const source = await image.getAttribute("src");
83+
assert.ok(source.startsWith("data:image/svg+xml") || new URL(source, base).origin === new URL(base).origin);
84+
}
85+
async function openAgentCategory(labels) {
86+
await page.locator(".cw-model-setup-row")
87+
.filter({ has: page.locator("strong", { hasText: new RegExp(`^${labels.agentOverview}$`) }) })
88+
.getByRole("button").click();
89+
}
90+
async function provePreset(labels, locale) {
91+
await page.getByRole("button", { name: labels.add, exact: true }).click();
92+
const start = requests.length;
93+
await provider(labels).click();
94+
const option = page.getByRole("option", { name: labels.zhipu, exact: true });
95+
await brandLogo(option.locator("img.cw-model-logo"));
96+
await option.click();
97+
assert.equal(await provider(labels).innerText(), labels.zhipu);
98+
assert.equal(await page.getByLabel(labels.url, { exact: true }).inputValue(), canonicalURL);
99+
assert.equal(await page.locator(".cw-model-option").count(), modelIds.length);
100+
await brandLogo(provider(labels).locator("img.cw-model-logo"));
101+
for (const modelId of modelIds) {
102+
assert.equal(await page.getByRole("checkbox", { name: modelId, exact: true }).isChecked(), true);
103+
await brandLogo(optionRow(modelId).locator("img.cw-model-logo"));
104+
}
105+
await page.getByLabel("API Key", { exact: true }).fill(fixtureKey);
106+
await page.getByRole("button", { name: labels.reload, exact: true }).click();
107+
for (const modelId of modelIds)
108+
assert.equal(await page.getByRole("checkbox", { name: modelId, exact: true }).isChecked(), true);
109+
assert.ok(!requests.slice(start).some(url => url.includes("/model-configs/discover")), "Preset selection or reload must not discover remote models");
110+
await shot(`${locale}-mock-zhipu-provider.png`);
111+
}
112+
async function proveReopen(labels, locale) {
113+
const service = page.locator(".cw-model-service").filter({ hasText: canonicalURL });
114+
assert.equal(await service.count(), 1);
115+
assert.ok((await service.innerText()).includes(labels.zhipu));
116+
for (const logo of await service.locator("img.cw-model-logo").all())
117+
await brandLogo(logo);
118+
await service.getByRole("button", { name: labels.manage, exact: true }).click();
119+
assert.equal(await provider(labels).innerText(), labels.zhipu);
120+
for (const modelId of modelIds)
121+
assert.equal(await page.getByRole("checkbox", { name: modelId, exact: true }).isChecked(), true);
122+
assert.equal(await page.getByLabel("API Key", { exact: true }).inputValue(), "", "Saved key stays private");
123+
await brandLogo(provider(labels).locator("img.cw-model-logo"));
124+
await shot(`${locale}-mock-zhipu-reopened.png`);
125+
await page.getByRole("button", { name: labels.cancel, exact: true }).click();
126+
}
127+
async function proveManualAdd(labels, locale) {
128+
// The preset ships a curated list, but manual model IDs stay available like DeepSeek.
129+
await page.getByRole("button", { name: labels.add, exact: true }).click();
130+
await provider(labels).click();
131+
await page.getByRole("option", { name: labels.zhipu, exact: true }).click();
132+
const start = requests.length;
133+
await page.getByRole("button", { name: labels.manual, exact: true }).click();
134+
await page.getByLabel(labels.manualId, { exact: true }).fill("glm-4.7");
135+
await page.locator(".cw-model-manual").getByRole("button", { name: labels.manualAdd, exact: true }).click();
136+
assert.equal(await page.locator(".cw-model-option").count(), modelIds.length + 1);
137+
assert.equal(await page.getByRole("checkbox", { name: "glm-4.7", exact: true }).isChecked(), true);
138+
assert.ok(!requests.slice(start).some(url => url.includes("/model-configs/discover")), "Manual add must not discover remote models");
139+
await shot(`${locale}-mock-zhipu-manual-add.png`);
140+
await page.getByRole("button", { name: labels.cancel, exact: true }).click();
141+
await page.getByRole("button", { name: labels.add, exact: true }).waitFor();
142+
}
143+
async function proveAgentPicker() {
144+
// The picker runtime inventory is a response fixture. The Default group lists the
145+
// saved agent model configs from the real API, so no provider endpoint is contacted.
146+
await page.route(/\/assistant\/runtimes$/, route => route.fulfill({
147+
json: [{
148+
id: "default", label: "Default", group: "default", modelSource: "settings",
149+
available: true, status: "ready", modelOverride: false,
150+
}],
151+
}));
152+
await page.getByRole("button", { name: copy["zh-CN"].chatEntry, exact: true }).click();
153+
await page.getByRole("button", { name: /^Agent:/ }).click();
154+
await brandLogo(pickerRow.locator("img.cw-model-logo"));
155+
await pickerRow.click();
156+
await page.getByRole("button", { name: /^Agent:/ }).click();
157+
assert.equal(
158+
await pickerRow.getAttribute("aria-checked"),
159+
"true", "Saved Zhipu model stays selected in the assistant picker",
160+
);
161+
await shot("zh-CN-mock-zhipu-agent-picker.png");
162+
await page.keyboard.press("Escape");
163+
}
164+
165+
try {
166+
await page.goto(`${base}/ai-tool/ai-canvas/${projectId}?creation=unified`);
167+
const zh = copy["zh-CN"];
168+
await page.getByRole("button", { name: zh.settings, exact: true }).click();
169+
await page.getByRole("button", { name: zh.models, exact: true }).click();
170+
await openAgentCategory(zh);
171+
await provePreset(zh, "zh-CN");
172+
await page.getByRole("button", { name: zh.save, exact: true }).click();
173+
await page.getByRole("button", { name: zh.add, exact: true }).waitFor();
174+
const saved = (await call("/api/model-configs")).filter(config => config.url === canonicalURL);
175+
assert.deepEqual(saved.map(config => config.modelId).sort(), [...modelIds].sort());
176+
assert.equal(new Set(saved.map(config => config.providerId)).size, 1);
177+
for (const model of saved) {
178+
assert.equal(model.kind, "agent");
179+
assert.ok(!JSON.stringify(model).includes(fixtureKey));
180+
assert.equal(Object.hasOwn(model, "apiKey"), false);
181+
}
182+
await proveReopen(zh, "zh-CN");
183+
await proveManualAdd(zh, "zh-CN");
184+
await page.getByRole("button", { name: zh.close, exact: true }).click();
185+
await proveAgentPicker();
186+
187+
await page.getByRole("button", { name: zh.settings, exact: true }).click();
188+
await page.getByRole("button", { name: zh.models, exact: true }).click();
189+
await page.getByRole("button", { name: "通用", exact: true }).click();
190+
await page.locator("#settings-language").selectOption("en-US");
191+
const en = copy["en-US"];
192+
await page.getByRole("button", { name: en.models, exact: true }).click();
193+
await openAgentCategory(en);
194+
await provePreset(en, "en-US");
195+
await page.getByRole("button", { name: en.cancel, exact: true }).click();
196+
await proveReopen(en, "en-US");
197+
await proveManualAdd(en, "en-US");
198+
assert.ok(!requests.some(url => new URL(url).hostname === "open.bigmodel.cn"), "Browser must not contact the model provider");
199+
assert.deepEqual(errors, []);
200+
console.log(JSON.stringify({ passed: true, fixture: true, generation: "not submitted", base, api,
201+
projectURL: `${base}/ai-tool/ai-canvas/${projectId}?creation=unified`, screenshotDirectory: output,
202+
modelConfigIds: saved.map(config => config.id), checks: ["Chinese and English", "Z.ai brand logo",
203+
"canonical URL", "GLM models preselected without discovery", "save and reopen", "public models have no key",
204+
"manual model IDs stay available", "assistant picker lists and keeps the Zhipu model", "no provider request from the browser"] }));
205+
} catch (error) {
206+
await shot("mock-zhipu-provider-failure.png").catch(() => {});
207+
throw error;
208+
} finally {
209+
await browser.close();
210+
}

‎tests/providerPresets.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,48 @@ test("MOSS provider labels follow the display language", () => {
4949
}
5050
});
5151

52+
test("Zhipu BigModel preset offers agent chat models by kind", () => {
53+
const preset = PROVIDER_PRESETS.find((item) => item.id === "zhipu");
54+
assert.ok(preset);
55+
assert.equal(preset.url, "https://open.bigmodel.cn/api/paas/v4");
56+
assert.equal(preset.protocol, "openai");
57+
assert.equal(preset.connectionType, "api");
58+
assert.equal(preset.authMode, "bearer");
59+
assert.equal(preset.logoOrganization, "zai-org");
60+
assert.deepEqual(preset.kinds, ["agent"]);
61+
assert.deepEqual(preset.modelsByKind, {
62+
agent: ["glm-5.3", "glm-5.3-flash", "glm-5.2"],
63+
});
64+
assert.ok(providerOptions("agent").some((item) => item.id === "zhipu"));
65+
for (const kind of ["image", "video", "audio", "vision"] as const)
66+
assert.ok(!providerOptions(kind).some((item) => item.id === "zhipu"));
67+
});
68+
69+
test("Zhipu provider labels follow the display language", () => {
70+
const previous = getActiveLocale();
71+
try {
72+
setActiveLocale("zh-CN");
73+
assert.equal(providerOptions("agent").find((item) => item.id === "zhipu")?.name, "智谱 BigModel");
74+
setActiveLocale("en-US");
75+
assert.equal(providerOptions("agent").find((item) => item.id === "zhipu")?.name, "Zhipu BigModel");
76+
} finally {
77+
setActiveLocale(previous);
78+
}
79+
});
80+
81+
test("a saved Zhipu agent connection reopens with its provider identity", () => {
82+
const preset = PROVIDER_PRESETS.find((item) => item.id === "zhipu")!;
83+
for (const modelId of preset.modelsByKind?.agent ?? []) {
84+
const model: ModelConfig = {
85+
...preset, id: "saved-zhipu", kind: "agent", modelId,
86+
url: `${preset.url}/`,
87+
inputRules: { profile: "agent", allowedKinds: [], maxImages: 0, maxVideos: 0, maxAudios: 0, videoModes: [] },
88+
};
89+
assert.equal(providerPresetFor(model), "zhipu");
90+
assert.equal(providerPresetFor({ ...model, url: "https://other.test/v1" }), "custom");
91+
}
92+
});
93+
5294
test("a saved MOSS image connection reopens with its provider identity", () => {
5395
const preset = PROVIDER_PRESETS.find((item) => item.id === "moss");
5496
assert.ok(preset);

‎tests/test_zhipu.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""Zhipu BigModel chat requests map the shared thinking setting to GLM reasoning_effort."""
2+
from opendirector.integrations.chat_completions import chat_payload
3+
4+
5+
ZHIPU = {"modelId": "glm-5.3", "url": "https://open.bigmodel.cn/api/paas/v4"}
6+
7+
8+
def test_zhipu_reasoning_effort_accepts_only_glm_levels():
9+
assert chat_payload(ZHIPU, [], "low")["reasoning_effort"] == "low"
10+
assert chat_payload(ZHIPU, [], "medium")["reasoning_effort"] == "high"
11+
assert chat_payload(ZHIPU, [], "high")["reasoning_effort"] == "max"
12+
assert chat_payload(ZHIPU, [], "xhigh")["reasoning_effort"] == "high"
13+
14+
15+
def test_zhipu_auto_keeps_provider_default():
16+
payload = chat_payload(ZHIPU, [], "auto")
17+
assert "reasoning_effort" not in payload
18+
assert "thinking" not in payload
19+
20+
21+
def test_zhipu_base_fields_and_other_hosts_unchanged():
22+
payload = chat_payload(ZHIPU, [{"role": "user", "content": "hi"}], "high")
23+
assert payload["model"] == "glm-5.3"
24+
assert payload["stream"] is True
25+
assert payload["max_tokens"] == 8192
26+
assert payload["messages"] == [{"role": "user", "content": "hi"}]
27+
other = chat_payload({"modelId": "x", "url": "https://api.example.com/v1"}, [], "medium")
28+
assert other["reasoning_effort"] == "medium"
29+
deepseek = chat_payload({"modelId": "x", "url": "https://api.deepseek.com/v1"}, [], "high")
30+
assert deepseek["thinking"] == {"type": "enabled"}
31+
assert deepseek["reasoning_effort"] == "max"

0 commit comments

Comments
 (0)