SDK 与示例
SDK 与多语言接入指南
更新于 2026-12-03
讯蒙智能云所有能力均采用标准开放协议:Tengri 大模型、向量嵌入与内容审核可直接复用主流官方 SDK;翻译、文档识别、语音、文字转换与穹盾全量能力采用标准 HTTP JSON / Multipart / WebSocket 协议,零专有 SDK 锁定。
兼容官方 SDK 对照表
| 目标场景 | 推荐 SDK | base_url 配置 | 说明 |
|---|---|---|---|
| Tengri 大模型(OpenAI 协议) | Python openai / Node.js openai / Go openai-go | https://cloud.heimori.cn/v1 | 支持 chat.completions、responses、embeddings、models、moderations |
| Tengri 大模型(DashScope 兼容) | OpenAI SDK(DashScope 兼容配置) | https://cloud.heimori.cn/compatible-mode/v1 | 兼容阿里云百炼路径前缀 |
| Tengri 大模型(Anthropic 协议) | Python anthropic / Node.js @anthropic-ai/sdk | https://cloud.heimori.cn | SDK 自动拼接 /v1/messages 与 /v1/messages/count_tokens |
| 翻译 / OCR / TTS / ASR / 穹盾 | Python httpx / requests、Node fetch、Go net/http、Java HttpClient | https://cloud.heimori.cn/v1 | 标准 RESTful JSON 与 multipart/form-data |
| 实时语音识别与语音翻译 | Python websockets、Node ws、Go gorilla/websocket | wss://cloud.heimori.cn | 文本 JSON 控制帧 + 16kHz/16-bit 单声道 PCM 二进制帧 |
Python 生产接入模板(连接池 + 流式 + 多 SDK)
1. 标准 HTTP 连接池客户端(httpx)
Python
import os
import httpx
class HeimoriClient:
def __init__(self, api_key: str | None = None, timeout: float = 30.0):
self.client = httpx.Client(
base_url="https://cloud.heimori.cn/v1",
headers={"Authorization": f"Bearer {api_key or os.environ['XM_API_KEY']}"},
timeout=httpx.Timeout(timeout, connect=5.0),
limits=httpx.Limits(max_connections=50, max_keepalive_connections=20),
)
def translate(self, text: str, target_lang: str = "mw", mode: str = "standard") -> dict:
resp = self.client.post(
"/translate/text",
json={"text": text, "targetLang": target_lang, "mode": mode},
)
resp.raise_for_status()
return resp.json()
def guard_text(self, text: str, policy: str = "general-ugc") -> dict:
resp = self.client.post("/guard/text", json={"input": text, "policy": policy})
resp.raise_for_status()
return resp.json()
def __enter__(self) -> "HeimoriClient":
return self
def __exit__(self, *exc) -> None:
self.close()
def close(self) -> None:
self.client.close()
with HeimoriClient() as hm:
print(hm.translate("欢迎使用讯蒙智能云", target_lang="mw"))2. Anthropic SDK 接入 Tengri 大模型
Python
import os
import anthropic
claude_client = anthropic.Anthropic(
api_key=os.environ["XM_API_KEY"],
base_url="https://cloud.heimori.cn",
)
msg = claude_client.messages.create(
model="tengri-2",
max_tokens=512,
messages=[{"role": "user", "content": "简述传统蒙古文与西里尔蒙古文的区别"}],
)
print(msg.content[0].text)Node.js / TypeScript 接入模板(SSE 流式消费 + 实时 WebSocket)
1. 原生 fetch 消费 SSE 流式对话
TypeScript
const resp = await fetch("https://cloud.heimori.cn/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.XM_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "tengri-2",
stream: true,
stream_options: { include_usage: true },
messages: [{ role: "user", content: "介绍一下呼和浩特" }],
}),
});
if (!resp.ok || !resp.body) {
throw new Error(`HTTP ${resp.status} requestId=${resp.headers.get("x-request-id")}`);
}
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
if (!line.startsWith("data: ")) continue;
const payload = line.slice(6).trim();
if (payload === "[DONE]") break;
const chunk = JSON.parse(payload);
const delta = chunk.choices?.[0]?.delta?.content;
if (delta) process.stdout.write(delta);
}
}2. WebSocket 实时语音识别与翻译客户端(ws)
JavaScript
import fs from "node:fs";
import WebSocket from "ws";
const ws = new WebSocket("wss://cloud.heimori.cn/v1/translate/speech/realtime", {
headers: { Authorization: `Bearer ${process.env.XM_API_KEY}` },
});
ws.on("open", () => {
ws.send(JSON.stringify({
type: "start",
language: "xle_mw",
targetLang: "zh",
sampleRate: 16000,
format: "pcm",
}));
});
ws.on("message", (raw) => {
const frame = JSON.parse(raw.toString());
if (frame.type === "started") {
const stream = fs.createReadStream("meeting.pcm", { highWaterMark: 6400 });
stream.on("data", (buf) => ws.send(buf));
stream.on("end", () => ws.send(JSON.stringify({ type: "end" })));
} else if (frame.type === "translation") {
console.log(`[#${frame.segmentId}] ${frame.text} -> ${frame.translation}`);
} else if (frame.type === "done") {
console.log("计费时长(秒):", frame.durationSeconds);
}
});Go 与 Java 标准 HTTP 接入示例
Go(net/http 连接池复用)
Go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
var httpClient = &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 20,
IdleConnTimeout: 90 * time.Second,
},
}
func main() {
body, _ := json.Marshal(map[string]any{
"text": "欢迎使用讯蒙智能云",
"targetLang": "mw",
"mode": "standard",
})
req, _ := http.NewRequest("POST", "https://cloud.heimori.cn/v1/translate/text", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("XM_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body)
fmt.Println("X-Request-Id:", resp.Header.Get("X-Request-Id"))
fmt.Println(string(raw))
}Java 11+(java.net.http.HttpClient)
Java
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
public class HeimoriDemo {
private static final HttpClient CLIENT = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
public static void main(String[] args) throws Exception {
String json = "{\"text\":\"欢迎使用讯蒙智能云\",\"targetLang\":\"mw\",\"mode\":\"standard\"}";
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://cloud.heimori.cn/v1/translate/text"))
.timeout(Duration.ofSeconds(30))
.header("Authorization", "Bearer " + System.getenv("XM_API_KEY"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> resp = CLIENT.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println("X-Request-Id: " + resp.headers().firstValue("X-Request-Id").orElse(""));
System.out.println(resp.body());
}
}Webhook HMAC-SHA256 回调验签
接收讯蒙穹盾异步任务、人工复核或申诉回调时,使用原始请求字节流校验 X-Guard-Signature 并拒绝时间戳偏差超过 300 秒的重放请求(完整事件格式见回调与签名);接收 Heimori-ASR 长音频后台任务回调时,校验 X-Heimori-Signature: sha256=<hex>(完整事件格式见长音频后台任务与 Webhook 签名校验):
Python
import hashlib
import hmac
import time
def verify_guard_webhook(secret: str, signature_header: str, raw_body: bytes) -> bool:
parts = dict(item.split("=", 1) for item in signature_header.split(",") if "=" in item)
ts = parts.get("t", "")
v1 = parts.get("v1", "")
if not ts.isdigit() or abs(time.time() - int(ts)) > 300:
return False
expected = hmac.new(
secret.encode("utf-8"),
f"{ts}.".encode("utf-8") + raw_body,
hashlib.sha256,
).hexdigest()
return hmac.compare_digest(expected, v1)
def verify_asr_webhook(
secret: str,
timestamp_header: str,
signature_header: str,
raw_body: bytes,
) -> bool:
if not timestamp_header.isdigit() or abs(time.time() - int(timestamp_header)) > 300:
return False
if not signature_header.startswith("sha256="):
return False
expected = hmac.new(
secret.encode("utf-8"),
f"{timestamp_header}.".encode("utf-8") + raw_body,
hashlib.sha256,
).hexdigest()
return hmac.compare_digest(expected, signature_header.split("=", 1)[1].strip())