首页 > 其他分享 >实现一个撸代码版chatgpt聊天窗

实现一个撸代码版chatgpt聊天窗

时间:2023-03-17 11:55:22浏览次数:32  
标签:markdown false 代码 marked content 聊天 chatgpt

最近在学习chatgpt和react,想做个东西练练手。刚好看到vscode上面有个chatgpt插件,可以在聊天对话框中输出markdown格式的代码块,哎呦不错哦,就它了。由于时间有限直接去github上找了个react版的gpt3聊天项目https://github.com/Vuizur/react-gpt3-chatbot,发现用的还是达摩院的chatui组件,哈哈,英雄所见略同啊。

改造前是这样滴!

改造后

实现思路就是,你也可以想一想。1分钟后。。

  1. 先让chatgpt返回带markdown格式的代码,这里要用到chatgpt的黑科技prompt.
  2. 接下来就简单了,使用marked将chatgpt返回的内容解析成html,然后直接放到div里面
    闲言少叙,直接开撸吧,先介绍第一步怎么实现
    "max_tokens": 1024,
    "model": "gpt-3.5-turbo",
    "temperature": 0.8,
    "top_p": 1.0,
    "messages": [
        {
            "role": "user",
            "content": "帮我实现一段golang代码打印hello"
        },
        {
            "role": "system",
            "content": "You are ChatGPT helping the User with coding.\n\t You are intelligent, helpful and an expert developer, who always gives the correct answer and only does what instructed. You always answer truthfully and don't make things up. When responding to the following prompt, please make sure to properly style your response using Github Flavored Markdown. Use markdown syntax for things like headings, lists, colored text, code blocks, highlights etc. Make sure not to mention markdown or styling in your actual response"
        }
    ],
    "stream": false
}

如果你看到这个一脸懵逼,那么我建议你研究一下这个接口的参数,https://platform.openai.com/docs/api-reference/chat/create
ok,如你所见,黑科技就是那一大段英文,可以让chatgpt返回markdown格式的内容。当然调这个接口须要两个条件:
1.openai api key
2.合适的梯子,你懂的
好了搞定了上面两个条件,就可以继续玩耍了。剩下的就简单了,直接上代码

import {marked} from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark.css'

function renderMessageContent(msg: any) {
        marked.setOptions({
            renderer: new marked.Renderer(),
            highlight: function (code, _lang) {
                return hljs.highlightAuto(code).value;
            },
            langPrefix: 'hljs language-',
            pedantic: false,
            gfm: true,
            breaks: false,
            sanitize: false,
            smartypants: false,
            xhtml: false
          })
        const { content } = msg;

         let html = marked(content.text)
         return <div className="show-html" dangerouslySetInnerHTML={{ __html: html }}></div>

    }

总结一下

  • 对chatgpt来说prompt很重要,那么啥是prompt呢,通过上面那一段你可以大概知道就是一个解决问题的思路。就是说一个事情你得知道怎么解决,然后翻译成chatgpt能听懂得话,接下来就是见证奇迹得时刻了。比如上面那一大段让chatgpt输出markdown格式的内容是设置在role=system的消息里面的,官方文档叫system message,文档里面有句话就说明了它就是用来格式化输出用的。
    Typically, a conversation is formatted with a system message first, followed by alternating user and assistant messages.详见https://platform.openai.com/docs/guides/chat/introduction
  • 我们知道chatgpt是支持上下文的,但是在撸代码的场景,我感觉这个有点太费钱了,但是暂时也没想到好的办法。
  • 这个代码还很简陋,有兴趣可以自己动手改进一下,代码完整链接:https://github.com/rotk2022/react-gpt3-chatbot

标签:markdown,false,代码,marked,content,聊天,chatgpt
From: https://www.cnblogs.com/rotk2022/p/17223591.html

相关文章