当前位置: 首页 > java >正文

小程序引入deepseek

首先需要申请key: 地址

deepseek文档地址

使用wx.request获取数据

    const task = wx.request({url: 'https://api.deepseek.com/chat/completions',method: 'POST',responseType: 'text',headers: {'Content-Type': 'application/json','Authorization': 'Bearer YOUR_API_KEY'},dataType: 'text', // 或 'json'enableChunked: true,data: {messages: [{ role: 'user', 'content'}]},success: async function(res) {const systemInfo = Taro.getSystemInfoSync()// 兼容企微小程序不能使用onChunkReceived钩子的情况if (systemInfo.environment === 'wxwork') {if (res.data) {const infoList = res.data.match(/data:\s*(\{[^}]*\})/g)let data = ''Taro.hideLoading()for (let index = 0; index < infoList.length; index++) {await new Promise(resolve => setTimeout(resolve, 80))const jsonStr = infoList[index].replace(/^data:\s*/, '')data += JSON.parse(jsonStr).contentthat.setState({ deepSeekData: data })if (index === infoList.length - 1) {that.setState({disabled: false})}}}}}})let bl = truetask.onChunkReceived((chunk) => {const chunkText = SimpleTextDecoder(chunk.data); // 解码当前分块const regList = chunkText.match(/data:\s*(\{[^}]*\})/g)let deepSeekData = ''if (chunkText.indexOf('data: [DONE]') > -1) {request.post('admin/TransferStoreDeepseek', {transfer_store_id: this.state.transferInfo.id,deepseek: this.state.deepSeekData})this.setState({disabled: false})} else {if (!regList) returnregList.forEach((item) => {if (bl) {Taro.hideLoading()bl = false}const jsonStr = item.replace(/^data:\s*/, '')try {deepSeekData += JSON.parse(jsonStr).content} catch (e) {console.error('解析JSON失败:', e, '原始数据:', jsonStr)return null}})this.setState({ deepSeekData: this.state.deepSeekData += deepSeekData });}});

渲染数据

使用markdown-it插件

npm install markdown-it@12.3.2
import { Button, View, RichText, Input } from '@tarojs/components';
import { parseMarkdownToHtml } from '@/utils/markdownParser';
import { filterHtmlForRichText } from '@/utils/htmlFilter';
import { SimpleTextDecoder} from '@/utils/SimpleTextDecoder';<RichText nodes={filterHtmlForRichText(parseMarkdownToHtml(this.state.deepSeekData))} />
配置markdown
// utils/markdownParser.js
import markdownIt from 'markdown-it'
// 初始化 markdown-it 实例
const md = new markdownIt({html: false,        // 允许解析 HTML 标签breaks: true,      // 保留换行符linkify: true,     // 自动转换 URL 为链接typographer: true  // 启用智能标点替换
});// Markdown 转 HTML
export function parseMarkdownToHtml(mdText) {return md.render(mdText);
}
标签处理
// utils/htmlFilter.js
export function filterHtmlForRichText(html) {// 转换不支持的标签(示例:表格转 div 布局)let safeHtml = html.replace(/<table>/g, '<div class="table">').replace(/<\/table>/g, '</div>').replace(/<tr>/g, '<div class="tr">').replace(/<\/tr>/g, '</div>').replace(/<td>/g, '<div class="td">').replace(/<\/td>/g, '</div>').replace(/<h1>/g, '<h1 class="h1">').replace(/<h3>/g, '<h3 class="h3">').replace(/<ul>/g, '<ul class="ul">').replace(/<li>/g, '<li class="li">').replace(/<ol>/g, '<ol class="ol">').replace(/<strong>/g, '<strong class="strong">')// 移除危险标签(如 script)safeHtml = safeHtml.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');return safeHtml;
}
UTF-8 解码
// utils/htmlFilter.js
// 
export function SimpleTextDecoder (buffer) {let str = '';const uint8Array = new Uint8Array(buffer);for (let i = 0; i < uint8Array.length; i++) {str += String.fromCharCode(uint8Array[i]);}return decodeURIComponent(escape(str)); // UTF-8 解码
}
样式处理
  .h1 {font-size: 40px;}.h3 {font-size: 32px;line-height: 50px;}.ul, .ol {padding-left: 36px;}.strong {font-weight: normal;}
http://www.xdnf.cn/news/12197.html

相关文章:

  • Web-图片上传出现的错误
  • 视频汇聚平台EasyCVR“明厨亮灶”方案筑牢旅游景区餐饮安全品质防线
  • 【HTML】HTML 与 CSS 基础教程
  • Profinet转CAN网关借助特定配置软件完成子站配置任务
  • Spring 框架之IOC容器加载重要组件
  • label-studio的使用教程(导入本地路径)
  • CppCon 2015 学习:Comparison is not simple, but it can be simpler.
  • SQL进阶之旅 Day 16:特定数据库引擎高级特性
  • Maven的生命周期
  • 【QT】显示类控件
  • 2025年上海市“星光计划”第十一届职业院校技能大赛 网络安全赛项技能操作模块样题
  • 华硕电脑,全新的超频方式,无需进入BIOS
  • PostgreSQL 技术峰会,为您打造深度交流优质平台
  • 神经网络-Day45
  • 第二十四章 流程控制_ if分支
  • day38 6月5号
  • Tensorrt python api 10.11.0笔记
  • 【新品解读】一板多能,AXRF49 定义新一代 RFSoC FPGA 开发平台
  • Devops系列---python基础篇二
  • 提示词指南 --- 提示词的基本结构
  • 51单片机基础部分——独立按键检测
  • 从零发布一个 Vue 3 Button 组件到 npm(基于 Vite)
  • 【推荐算法】WideDeep推荐模型:融合记忆与泛化的智能推荐引擎
  • Oracle杀进程注意事项
  • 力扣100题之128. 最长连续序列
  • 探秘 MyBatis:开启你的数据库操作「智能之旅」
  • 基于Qt的app开发第十三天
  • 【深尚想】TPS54618CQRTERQ1汽车级同步降压转换器电源芯片全面解析
  • 服务器中CC攻击的特点有哪些?
  • 全面解析网络端口:概念、分类与安全应用