必须服务端代理调用,禁用客户端直连;密钥存环境变量,用tencentcloud-sdk-nodejs-hunyuan初始化client,model字段严格匹配文档(如hunyuan-pro),流式响应需for await解析sse。
☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 多模态理解力帮你轻松跨越从0到1的创作门槛☜☜☜

要在Node.js项目中稳定调用腾讯混元大模型的文本生成能力,必须避开客户端直连密钥的风险,走服务端代理路径,并正确配置SDK认证与接口参数。
准备密钥和环境
登录腾讯云控制台 → 进入【访问管理 CAM】→ 【API密钥管理】→ 创建新的密钥对,勾选“Hunyuan”服务权限;【SecretId 和 SecretKey 必须保存在服务端环境变量中,绝不可写死在前端代码或Git仓库里】。
在项目根目录创建 .env 文件,写入:
HY_SECRET_ID=your_secret_id_here
HY_SECRET_KEY=your_secret_key_here
这一步漏掉会导致后续所有请求返回 401 认证失败,且错误提示非常模糊,容易卡在调试环节超过20分钟。
安装并初始化混元 Node.js SDK
执行命令安装官方 SDK:
npm install tencentcloud-sdk-nodejs-hunyuan
新建文件 src/utils/hunyuanClient.js,写入初始化代码:
const { hunyuan } = require("tencentcloud-sdk-nodejs-hunyuan");
const clientConfig = {
credential: {
secretId: process.env.HY_SECRET_ID,
secretKey: process.env.HY_SECRET_KEY,
},
region: "ap-guangzhou", // 必须指定,否则报错 RegionNotSupported
};
module.exports = new hunyuan.v20230901.Client(clientConfig);
发起单轮对话请求
方法一:使用 ChatCompletions 接口(推荐)
const hunyuanClient = require("../utils/hunyuanClient");
async function askModel(prompt) {
try {
const res = await hunyuanClient.ChatCompletions({
Model: "hunyuan-pro", // 模型名必须准确,大小写敏感
Messages: [{ Role: "user", Content: prompt }],
Temperature: 0.7,
});
return res.Choices[0].Message.Content;
} catch (err) {
console.error("混元调用失败:", err.message);
throw err;
}
}
注意:Model 字段若填错(比如写成 hunyuan-pro-v1 或 hunyuan_lite),会直接返回 400 错误且不提示具体原因,只能靠文档核对。
方法二:用 OpenAI 兼容接口(适合已有 OpenAI 适配层的项目)
安装 axios:
npm install axios
然后调用:
const axios = require("axios");
const res = await axios.post(
"https://tokenhub.tencentmaas.com/v1/chat/completions",
{
model: "hy4-preview",
messages: [{ role: "user", content: "你好" }],
},
{
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${process.env.HY_API_KEY}`
},
}
);
【HY_API_KEY 是另一套独立密钥,需在腾讯云「API密钥管理」中单独开通「TokenHub」权限后生成】。
处理流式响应(可选进阶)
第一步:修改请求参数,启用 Stream 模式
在 ChatCompletions 调用中加入:
Stream: true
第二步:监听 SSE 数据流,拼接 Delta 内容
SDK 返回的是 ReadableStream,需用 for await…of 解析:
const stream = await hunyuanClient.ChatCompletions({
Model: "hunyuan-lite",
Messages: [{ Role: "user", Content: "讲个冷笑话" }],
Stream: true,
});
let fullResponse = "";
for await (const chunk of stream) {
if (chunk.Choices?.[0]?.Delta?.Content) {
fullResponse += chunk.Choices[0].Delta.Content;
}
}
console.log(fullResponse);
这一步不能用普通 JSON.parse 处理,因为每块 chunk 是独立的 SSE event,格式为 data: {...}\n\n,直接解析会报错。











