小程序引入deepseek

首先需要申请key: 地址

deepseek文档地址

使用wx.request获取数据

js 复制代码
    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).content
              that.setState({ deepSeekData: data })
              if (index === infoList.length - 1) {
                that.setState({
                  disabled: false
                })
              }
            }
          }
        }
      }
    })
    let bl = true
    task.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) return
        regList.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插件

js 复制代码
npm install markdown-it@12.3.2
js 复制代码
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
js 复制代码
// 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);
}
标签处理
js 复制代码
// 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 解码
js 复制代码
// 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 解码
}
样式处理
css 复制代码
  .h1 {
    font-size: 40px;
  }
  .h3 {
    font-size: 32px;
    line-height: 50px;
  }
  .ul, .ol {
    padding-left: 36px;
  }
  .strong {
    font-weight: normal;
  }
相关推荐
じòぴé南冸じょうげん3 小时前
小程序的project.private.config.json是无依赖文件,那可以删除吗?
前端·小程序·json
2501_916013744 小时前
HTTPS 抓包难点分析,从端口到工具的实战应对
网络协议·http·ios·小程序·https·uni-app·iphone
2501_915918416 小时前
uni-app 项目 iOS 上架效率优化 从工具选择到流程改进的实战经验
android·ios·小程序·uni-app·cocoa·iphone·webview
00后程序员张6 小时前
如何在不同 iOS 设备上测试和上架 uni-app 应用 实战全流程解析
android·ios·小程序·https·uni-app·iphone·webview
微三云-轩7 小时前
区块链:重构企业数字化的信任核心与创新动力
人工智能·小程序·区块链·生活·我店
2501_915918411 天前
iOS 开发全流程实战 基于 uni-app 的 iOS 应用开发、打包、测试与上架流程详解
android·ios·小程序·https·uni-app·iphone·webview
黑马源码库miui520861 天前
JAVA同城打车小程序APP打车顺风车滴滴车跑腿源码微信小程序打车源码
java·微信·微信小程序·小程序·uni-app
一口十个小甜虾1 天前
微信小程序体验版,当打开调试模式正常访问,关闭之后无法访问
微信小程序·小程序
悟空码字1 天前
微信开放平台第三方平台,可以管理多个微信小程序
微信·小程序·开放平台
じòぴé南冸じょうげん1 天前
微信小程序如何进行分包处理?
前端·小程序