ChatGPT接口返回代码高亮显示的实现逻辑

官方API:POST https://api.openai.com/v1/chat/completions

我们在使用openai提供的接口时,返回的数据如果包含代码,会发现代码是没有样式的,它们一般是用```包含的一段文本。

如图:

 怎么样才能做到和官方一样的美观呢:

 需要使用渲染器,直接上package.json配置:

"dependencies": {
    //其他无关依赖省略
    "@traptitech/markdown-it-katex": "^3.6.0",
    "markdown-it": "^13.0.1",
    "highlight.js": "^11.7.0",
  },
  "devDependencies": {
    //其他无关依赖省略
    "@types/markdown-it": "^12.2.3"
  }

依赖下载命令:

npm i markdown-it

npm i @traptitech/markdown-it-katex

npm i -D @types/markdown-it

npm i highlight.js
 

插件文档:

markdown-it | markdown-it 中文文档

highlight.js 中文文档

在需要使用的文件中引入:

<script setup>
import { reactive, onMounted } from 'vue';
import MarkdownIt from 'markdown-it'
import mdKatex from '@traptitech/markdown-it-katex'
import hljs from 'highlight.js';

const mdi = new MarkdownIt({
  linkify: true,
  highlight(code, language) {
    const validLang = !!(language && hljs.getLanguage(language))
    if (validLang) {
      const lang = language ?? ''
      return highlightBlock(hljs.highlight(lang, code, true).value, lang)
    }
    return highlightBlock(hljs.highlightAuto(code).value, '')
  }
})
mdi.use(mdKatex, { blockClass: 'katexmath-block rounded-md p-[10px]', errorColor: ' #cc0000' })

function highlightBlock(str, lang) {
  return `<pre class="pre-code-box"><div class="pre-code-header"><span class="code-block-header__lang">${lang}</span><span class="code-block-header__copy">复制代码</span></div><div class="pre-code"><code class="hljs code-block-body ${lang}">${str}</code></div></pre>`
}

const getMdiText = (value) => {
    return mdi.render(value)
}

const state = reactive({
    htmlStr: '' 
})

onMounted(() => {
    state.htmlStr = getMdiText("包含代码的文本") //htmlStr就是已经包含html样式的文本
});


<script>

<template>
    <div v-html="state.htmlStr"></div>
</template>

猜你喜欢

转载自blog.csdn.net/weixin_39823006/article/details/131001677