随着人工智能技术的不断发展,强大的大模型如腾讯的混元大模型(HunYuan)为开发者提供了丰富的智能服务能力。本文将详细介绍如何在 Node.js 环境中使用腾讯云提供的 SDK 调用混元大模型,构建一个简单的 API 接口来实现与模型的交互。
首先,确保你已经安装了 Node.js 环境。如果尚未安装,可以访问 Node.js 官网 下载并安装最新版本。
创建一个新的项目目录并初始化 package.json
:
mkdir hunyuan-api
cd hunyuan-api
npm init -y
安装必要的依赖包:
npm install express body-parser cors tencentcloud-sdk-nodejs-hunyuan
这些包分别是:
express
:构建服务器的流行框架。body-parser
:解析请求体的中间件。cors
:处理跨域资源共享问题。tencentcloud-sdk-nodejs-hunyuan
:腾讯云混元大模型的 Node.js SDK。新建 app.js
文件,并添加以下代码:
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const tencentcloud = require("tencentcloud-sdk-nodejs-hunyuan");
const HunyuanClient = tencentcloud.hunyuan.v20230901.Client;
const app = express();
const port = 3000;
// 使用 CORS 中间件,允许所有来源
app.use(cors());
// 解析 JSON 请求体
app.use(bodyParser.json());
// 定义 POST /hunyuan 接口
app.post("/hunyuan", async (req, res) => {
console.log("Received request body:", req.body);
const clientConfig = {
credential: {
secretId: "YOUR_SECRET_ID", // 替换为你的 SecretId
secretKey: "YOUR_SECRET_KEY", // 替换为你的 SecretKey
},
region: "your-region", // 替换为你的区域,如 "ap-guangzhou"
profile: {
httpProfile: {
endpoint: "hunyuan.tencentcloudapi.com",
},
},
};
const client = new HunyuanClient(clientConfig);
const params = {
Model: "hunyuan-pro",
Messages: req.body,
Stream: false,
};
try {
const response = await client.ChatCompletions(params);
res.json(response);
} catch (err) {
console.error("Error calling HunYuan:", err);
res.status(500).json({ error: '请求失败', details: err.message });
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
cors
允许跨域请求,避免前端请求时的跨域问题。bodyParser.json()
用于解析 JSON 格式的请求体。POST /hunyuan
接口,接收前端发送的消息体。clientConfig
,包括 secretId
和 secretKey
,请确保这些凭证信息的安全性,建议使用环境变量或配置文件管理。HunyuanClient
创建客户端实例。ChatCompletions
方法发送请求,并返回模型的响应。在终端中运行以下命令启动服务器:
node app.js
你应该会看到:
Server is running on port 3000
我们准备测试数据如下:
[
{
"Role": "user",
"Content": "今天星期几?"
}
]
在Apifox编写接口地址以及测试数据
然后我们开始执行,获取最终数据。
以下是一个简单的前端 JavaScript 示例,展示如何通过 fetch
调用上述接口:
async function sendMessage(message) {
const response = await fetch('http://localhost:3000/hunyuan', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify([{ content: message, role: "user" }])
});
const data = await response.json();
if (response.ok) {
console.log("HunYuan Response:", data.Response.Messages);
} else {
console.error("Error:", data.error);
}
}
// 示例调用
sendMessage("你好,混元大模型!");
secretId
和 secretKey
直接暴露在代码中,建议使用环境变量进行管理。例如,可以使用 dotenv 库来加载 .env
文件中的配置。region
参数设置为腾讯云混元大模型所在的区域。具体区域信息请参考 腾讯云区域列表。通过本文的介绍,你可以轻松地在 Node.js 环境中使用腾讯云 SDK 调用混元大模型,构建智能聊天 API 接口。利用大模型的强大能力,可以应用于各种场景,如客服机器人、内容生成、智能助手等。希望这篇文章对你有所帮助。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。