HarmonyOS鸿蒙Next开发者技术支持-集成DeepSeekR1模型遇到的问题
HarmonyOS鸿蒙Next开发者技术支持-集成DeepSeekR1模型遇到的问题
1、问题说明
在代码中集成deepseek模型并实现流式输出的demo中遇到的一些问题:明文硬编码 api_url、 token(高风险)
SSE 请求参数不规范,可能造成不返回或中断。只发送当前一句,无对话上下文,回答易“断层”。
2、原因分析
安全方面密钥与 API放在客户端,任何人均可抓包获取。
协议方面:fetch event source 一般使用 headers 和 body(USON字符串),而不是 header/extraData;method 需用POST字符串。
3、解决思路
安全:使用后端代理请求(隐藏密钥),前端只调用代理;若必须前端直连也应把 token 抽离到本地安全存储并做最小化权限。
APl:按 fetch event source 标准使用 headers 和 body:JsoN.stringify(payload), method:‘PosT’。
流处理:保留换行;识别并在“[DONE]”时结束;健壮的JSON 解析与错误提示
4、解决方案
重写promptdeepseek方法
async promptDeepSeek() {
const payload = {
model: this.show ? 'DeepSeek-R1' : 'DeepSeek-V3',
max_tokens: 500,
messages: this.buildContextMessages(),
stream: true,
stream_options: { include_usage: true },
temperature: this.show ? 1.0 : 0.7
};
// 占位的 assistant 条目,后续增量拼接
this.listAA.push({ role: 'assistant', content: '' });
try {
await fetchEventSource(this.api_url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.token}`
},
body: JSON.stringify(payload),
onopen: async () => {
// 可在此做 UI 状态更新,如禁用发送按钮等
},
onmessage: (ev) => {
const data = ev?.data;
if (!data) return;
if (data === '[DONE]') {
// 流结束
return;
}
try {
const json = JSON.parse(data) as ResponseQ;
const chunk = json?.choices?.[0]?.delta?.content ?? '';
this.appendAssistantDelta(chunk);
} catch {
}
},
onclose: () => {
// 可在此恢复 UI 状态
},
onerror: (err) => {
promptAction.showToast({ message: '生成失败,请稍后再试' });
throw err;
}
});
} catch (_) {
}
}
前端改为自建代理
import express from 'express';
import fetch from 'node-fetch';
const app = express();
app.use(express.json());
const API_URL = 'https://maas-cn-southwest-2.modelarts-maas.com/v1/infers/8a062fd4-7367-4ab4-a936-5eeb8fb821c4/v1/chat/completions';
app.post('/api/chat', async (req, res) => {
const resp = await fetch(API_URL, {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.DEEPSEEK_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(req.body)
});
// 透传流式响应
res.status(resp.status);
resp.body.pipe(res);
});
app.listen(3000, () => console.log('proxy on :3000'));
更多关于HarmonyOS鸿蒙Next开发者技术支持-集成DeepSeekR1模型遇到的问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html
关注
更多关于HarmonyOS鸿蒙Next开发者技术支持-集成DeepSeekR1模型遇到的问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS Next中集成DeepSeekR1模型时,需确保使用鸿蒙AI框架进行适配。请检查模型格式是否为鸿蒙支持的.om或.nn模型,并通过ArkUI调用NPU推理接口。验证模型转换工具链是否匹配鸿蒙Next版本,并确认运行时权限与硬件加速配置正确。
在HarmonyOS Next中集成DeepSeek模型时,您提出的安全性和协议规范问题确实需要重点关注。针对前端直连方案,建议使用HarmonyOS的安全存储能力(如@ohos.security.huks)管理token,避免硬编码。同时,确保SSE请求符合标准,使用正确的headers和body格式。
对于代理方案,后端代码示例基本可行,但需注意HarmonyOS的网络权限配置和跨域处理。建议在代理层增加请求验证和错误处理机制,提升稳定性。整体方案符合HarmonyOS的安全开发规范,可有效解决密钥泄露和协议兼容性问题。