Build a ChatGPT Powered Markdown Documentation in No Time(chatgpt markdown support)

ChatGPT and Markdown Support

ChatGPT is a powerful language model developed by OpenAI that can generate human-like text in conversation format. Markdown, on the other hand, is a lightweight markup language that allows for easy formatting of text. In this blog post, we will explore the integration of ChatGPT with Markdown formats and discuss the various benefits and use cases of this combination.

ChatGPT to Markdown

One of the main advantages of using Markdown with ChatGPT is the ability to generate conversations in a structured and easily editable format. With Markdown, users can add headings, bullet points, and other formatting elements to their ChatGPT conversations, making them more organized and visually appealing. For example, a user can provide the ChatGPT model with an input in Markdown format:

User: Could you provide a step-by-step guide on how to use the new feature?

In response, ChatGPT can generate the following answer in Markdown format:

ChatGPT: Sure! Here’s a guide on how to use the new feature:

  1. First, go to the settings menu
  2. Click on the “Advanced” tab
  3. Scroll down to find the new feature option
  4. Toggle the switch to enable the feature
  5. Click on “Save” to apply the changes

By utilizing Markdown, ChatGPT can provide more structured and organized responses, making it easier for users to follow instructions or digest information.

Add Markdown Support to Input Bar – ChatGPT

Another important aspect of integrating Markdown with ChatGPT is to add Markdown support to the input bar. This allows users to directly input Markdown-formatted text instead of plain text. By doing so, users can leverage the power of formatting options available in Markdown to enhance their communication with ChatGPT. For example, a user can input a question using Markdown:

User: How can I **bold** certain words in the generated text?

In response, ChatGPT can understand and respect the Markdown formatting and generate the following answer:

ChatGPT: To **bold** certain words in the generated text, you can use Markdown syntax by surrounding the words with double asterisks (**). For example, “**bold**”.

This integration provides users with more flexibility in expressing their queries and receiving formatted responses from ChatGPT.

ChatGPT with Markdown – IntelliJ IDEs Plugin

The benefits of using ChatGPT with Markdown are not limited to standalone applications. There are also plugins available for integrated development environments (IDEs) such as IntelliJ IDEA. The ChatGPT with Markdown plugin enhances the developer experience by enabling communication with ChatGPT directly from Markdown files. Some key features of this plugin include:

  • GPT functions support with JSON Schema completion
  • OpenAI API integration for seamless interaction
  • Convenient generation of ChatGPT responses within Markdown files

This plugin allows developers to seamlessly integrate ChatGPT capabilities into their workflow, making it easier to generate and communicate with the language model without leaving their preferred IDE.

ChatGPT Conversations to Markdown

Converting ChatGPT conversations to Markdown format is a useful process that enables easy sharing, editing, and archiving of generated text. Fortunately, there are Python scripts available that facilitate this conversion. The ChatGPT Conversations to Markdown script takes exported ChatGPT conversations and converts them into readable and well-formatted Markdown files. This conversion process ensures that the generated text remains readable and accessible for future reference.

Conclusion

The integration of ChatGPT with Markdown formats offers numerous benefits, including structured conversations, improved communication with the model, enhanced editing capabilities, and seamless integration with IDEs. Whether you are a developer looking to communicate with ChatGPT from a Markdown file or a user seeking more organized responses, leveraging Markdown with ChatGPT can significantly enhance your experience with the language model. As we continue to explore the potential of natural language processing, the combination of ChatGPT and Markdown provides a powerful approach to generating and working with human-like text.

chatgpt markdown support的进一步展开说明

以 ChatGPT 为基础快速构建 Markdown 文档

在这篇文章中,我们将学习如何构建一个系统,使用 ChatGPT 来问问题并取得关于你的文档的准确答案。

我们将使用 OpenAI 和 Embedbase。

我们要构建的全部项目在这里可以找到。你也能够在https://docs.embedbase.xyz上尝试交互版本。

## 概述

我们在这里要涵盖一些内容,但整体来讲:

我们需要将我们的内容存储在数据库中
我们要求用户输入一个查询
我们在数据库中搜索与用户查询最类似的结果(后面会详细介绍)
我们根据查询匹配的前五个最类似结果创建一个“上下文”,然后向 ChatGPT 发问:

根据下面的上下文回答问题,如果没法根据上下文回答问题,则回答“我不知道”

上下文:

[上下文]

问题:

[问题]

答案:

深入实现细节

好的,让我们开始吧

下面是本教程所需的内容

Embedbase API 密钥:一个允许你查找“最类似结果”的数据库。并不是所有的数据库都适用于这类工作。今天我们将使用 Embedbase,它可让你做到这一点。Embedbase 可让你在搜索查询和存储内容之间找到“语义类似性”。

OpenAI API 密钥:用于 ChatGPT 部份。

Nextra:已安装的 Node.js。

在 .env 文件中写入 Embedbase 和 OpenAI API 密钥:

“`plaintext
OPENAI_API_KEY=”<你的密钥>”
EMBEDBASE_API_KEY=”<你的密钥>”
“`

提示一下,我们将使用 ChatGPT 提供动力的 QA 文档,使用了使人惊叹的文档框架 Nextra,它允许你使用 NextJS、tailwindcss 和 MDX(Markdown + React)编写文档。我们还将使用 Embedbase 作为数据库,并使用 OpenAI 来使用 ChatGPT。

创建一个 Nextra 文档

在这里你可以找到并使用官方的 Nextra 文档模板。创建完文档后,用你喜欢的编辑器打开它。

“`plaintext
# 这里我们不使用 “pnpm”,而是传统的 “npm”

rm pnpm-lock.yaml

npm i

npm run dev
“`

现在只需转到 https://localhost:3000。

尝试编辑一些 .mdx 文档并查看内容的变化。

准备并存储文档

第一步要求我们将文档存储在 Embedbase 中。但是,这里有一个小问题,如果我们在数据库中存储相对较小的块,效果会更好。我们将按句子来分块。我们先在 scripts 文件夹中编写一个名为 sync.js 的脚本。

你需要使用 glob 库来列出文件 npm i [email protected] (我们将使用 8.1.0 版本)。

“`javascript
const glob = require(“glob”);

const fs = require(“fs”);

const sync = async () => {

// 1. read all files under pages/* with .mdx extension

// for each file, read the content

const documents = glob.sync(“pages/**/*.mdx”).map((path) => ({

// we use as id /{pagename} which could be useful to

// provide links in the UI

id: path.replace(“pages/”, “/”).replace(“index.mdx”, “”).replace(“.mdx”, “”),

// content of the file

data: fs.readFileSync(path, “utf⑻″)

}));

// 2. here we split the documents in chunks, you can do it in many different ways, pick the one you prefer

// split documents into chunks of 100 lines

const chunks = [];

documents.forEach((document) => {

const lines = document.data.split(”

“);

const chunkSize = 100;

for (let i = 0; i < lines.length; i += chunkSize) { const chunk = lines.slice(i, i + chunkSize).join(" "); chunks.push({ data: chunk }); } }); } sync(); ``` 现在我们拥有了块,我们需要将它们存储到数据库中,我们将扩展我们的脚本,以便将块添加到 Embedbase。 要查询 Embedbase,我们需要安装 node-fetch 的版本 2.6.9,运行 npm i [email protected]。 ```javascript const fetch = require("node-fetch"); // your Embedbase api key const apiKey = process.env.EMBEDBASE_API_KEY; const sync = async () => {

// …

// 3. we then insert the data in Embedbase

const response = await fetch(“https://api.embedbase.xyz/v1/documentation”, { // “documentation” is your dataset ID

method: “POST”,

headers: {

“Authorization”: “Bearer ” + apiKey,

“Content-Type”: “application/json”

},

body: JSON.stringify({

documents: chunks

})

});

const data = await response.json();

console.log(data);

}

sync();
“`

好了,你现在可以运行它了:

EMBEDBASE_API_KEY=”<你的 API KEY>” node scripts/sync.js

如果运行成功,你应当可以看到:

获得用户的查询

现在,我们将修改 Nextra 文档主题,用 ChatGPT 动力的内置搜索栏替换它。

我们将在 theme.config.tsx 中添加 Modal 组件,内容以下:

“`javascript
// update the imports

import { DocsThemeConfig, useTheme } from ‘nextra-theme-docs’

const Modal = ({ children, open, onClose }) => {

const theme = useTheme();

if (!open) return null;

return (

e.stopPropagation()}>

{children}

);

};
“`

现在我们要创建搜索栏:

“`javascript
// update the imports

import React, { useState } from ‘react’

// we create a Search component

const Search = () => {

const [open, setOpen] = useState(false);

const [question, setQuestion] = useState(“”);

// …

// All the logic that we will see later

const answerQuestion = () => { }

// …

return (

<>

setOpen(true)}

type=”text”

/>

setOpen(false)}>

setQuestion(e.target.value)}

/>

);

}
“`

最后,更新 config 以设置我们创建的搜索栏:

“`javascript
const config: DocsThemeConfig = {

logo: My Project,

project: {

link: ‘https://github.com/shuding/nextra-docs-template’,

},

chat: {

link: ‘https://discord.com’,

},

docsRepositoryBase: ‘https://github.com/shuding/nextra-docs-template’,

footer: {

text: ‘Nextra Docs Template’,

},

// add this to use our Search component

search: {

component:

}

}
“`

构建上下文

在这里,你需要使用 OpenAI 的 token-counting 库 tiktoken 运行 npm i @dqbd/tiktoken。

现在我们要构建一个上下文化 ChatGPT 的提示,在 NextJS API 端点中。创建一个名为 pages/api/buildPrompt.ts 的文件,代码以下:

“`javascript
// pages/api/buildPrompt.ts

import { get_encoding } from “@dqbd/tiktoken”;

// Load the tokenizer which is designed to work with the embedding model

const enc = get_encoding(‘cl100k_base’);

const apiKey = process.env.EMBEDBASE_API_KEY;

// this is how you search Embedbase with a string query

const search = async (query: string) => {

return fetch(“https://api.embedbase.xyz/v1/documentation/search”, {

method: “POST”,

headers: {

Authorization: “Bearer ” + apiKey,

“Content-Type”: “application/json”

},

body: JSON.stringify({

query: query

})

}).then(response => response.json());

};

const createContext = async (question: string, maxLen = 1800) => {

// get the similar data to our query from the database

const searchResponse = await search(question);

let curLen = 0;

const returns = [];

// We want to add context to some limit of length (tokens)

// because usually LLM have limited input size

for (const similarity of searchResponse[“similarities”]) {

const sentence = similarity[“data”];

// count the tokens

const nTokens = enc.encode(sentence).length;

// a token is roughly 4 characters, to learn more

// https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them

curLen += nTokens + 4;

if (curLen > maxLen) {

break;

}

returns.push(sentence);

}

// we join the entries we found with a separator to show it’s different

return returns.join(”

###

“);

}

// this is the endpoint that returns an answer to the client

export default async function buildPrompt(req, res) {

const prompt = req.body.prompt;

const context = await createContext(prompt);

const newPrompt = `Answer the question based on the context below, and if the question can’t be answered based on the context, say “I don’t know”

Context: ${context}

Question: ${prompt}

Answer:`;

res.status(200).json({ prompt: newPrompt });

}
“`

调用 ChatGPT

首先,在 utils/OpenAIStream.ts 文件中添加一些用于进行 OpenAI 流式调用的实用函数,你需要运行 npm i eventsource-parser 安装 eventsource-parser。

“`javascript
import {

createParser,

ParsedEvent,

ReconnectInterval,

} from “eventsource-parser”;

export interface OpenAIStreamPayload {

model: string;

// this is a list of messages to give ChatGPT

messages: { role: “user”; content: string }[];

stream: boolean;

}

export async function OpenAIStream(payload: OpenAIStreamPayload) {

const encoder = new TextEncoder();

const decoder = new TextDecoder();

let counter = 0;

const res = await fetch(“https://api.openai.com/v1/chat/completions”, {

headers: {

“Content-Type”: “application/json”,

“Authorization”: `Bearer ${process.env.OPENAI_API_KEY ?? “”}`,

},

method: “POST”,

body: JSON.stringify(payload),

});

const stream = new ReadableStream({

async start(controller) {

// callback

function onParse(event: ParsedEvent | ReconnectInterval) {

if (event.type === “event”) {

const data = event.data;

// https://beta.openai.com/docs/api-reference/completions/create#completions/create-stream

if (data === “[DONE]”) {

controller.close();

return;

}

try {

const json = JSON.parse(data);

// get the text response from ChatGPT

const text = json.choices[0]?.delta?.content;

if (!text) return;

if (counter < 2 && (text.match(/ /) || []).length) { // this is a prefix character (i.e., " "), do nothing return; } const queue = encoder.encode(text); controller.enqueue(queue); counter++; } catch (e) { // maybe parse error controller.error(e); } } } // stream response (SSE) from OpenAI may be fragmented into multiple chunks // this ensures we properly read chunks and invoke an event for each SSE event stream const parser = createParser(onParse); // https://web.dev/streams/#asynchronous-iteration for await (const chunk of res.body as any) { parser.feed(decoder.decode(chunk)); } }, }); return stream; } ``` 然后,在 pages/api/qa.ts 文件中创建一个简单的端点,只需对 ChatGPT 进行流式调用。 ```javascript // pages/api/qa.ts import { OpenAIStream, OpenAIStreamPayload } from "../../utils/OpenAIStream"; export const config = { // We are using Vercel edge function for this endpoint runtime: "edge", }; interface RequestPayload { prompt: string; } const handler = async (req: Request, res: Response): Promise => {

const { prompt } = (await req.json()) as RequestPayload;

if (!prompt) {

return new Response(“No prompt in the request”, { status: 400 });

}

const payload: OpenAIStreamPayload = {

model: “gpt⑶.5-turbo”,

messages: [{ role: “user”, content: prompt }],

stream: true,

};

const stream = await OpenAIStream(payload);

return new Response(stream);

};

export default handler;
“`

连接一切并发问

现在是通过 API 调用发问的时候了。编辑 theme.config.tsx 文件,向 Search 组件添加功能:

“`javascript
// theme.config.tsx

const Search = () => {

const [open, setOpen] = useState(false);

const [question, setQuestion] = useState(“”);

const [answer, setAnswer] = useState(“”);

const answerQuestion = async (e: any) => {

e.preventDefault();

setAnswer(“”);

// build the contextualized prompt

const promptResponse = await fetch(“/api/buildPrompt”, {

method: “POST”,

headers: {

“Content-Type”: “application/json”,

},

body: JSON.stringify({

prompt: question,

}),

});

const promptData = await promptResponse.json();

// send it to ChatGPT

const response = await fetch(“/api/qa”, {

method: “POST”,

headers: {

“Content-Type”: “application/json”,

},

body: JSON.stringify({

prompt: promptData.prompt,

}),

});

if (!response.ok) {

throw new Error(response.statusText);

}

const data = response.body;

if (!data) {

return;

}

const reader = data.getReader();

const decoder = new TextDecoder();

let done = false;

// read the streaming ChatGPT answer

while (!done) {

const { value, done: doneReading } = await reader.read();

done = doneReading;

const chunkValue = decoder.decode(value);

// update our interface with the answer

setAnswer((prev) => prev + chunkValue);

}

};

return (

<>

setOpen(true)}

type=”text”

/>

setOpen(false)}>

setQuestion(e.target.value)}

/>

{answer}

);

}
“`

你现在应当有这个:

固然,随时可以改进样式。

总结思路

总之,我们:

创建了一个 Nextra 文档

准备并存储了我们的文档在 Embedbase 中

建立了一个获得用户查询的接口

在我们的数据库中搜索问题的上下文以提供给 ChatGPT

通过这个上下文构建提示并调用 ChatGPT

让用户通过连接一切来发问

感谢浏览这篇文章,这里有一个开源模板可以创建这类类型的文档。

如果你喜欢这篇博客文章,给 https://github.com/another-ai/embedbase 加一个星星,我们也非常期待反馈。如果你想自己托管,可以预约一个演示。

进一步浏览

嵌入是一种机器学习的概念,它允许你将数据的语义表示为一个数字,从而可以创建以下特点:

语义搜索(例如,“牛吃草”和“猴子吃香蕉”之间的类似度是多少,这也适用于比较图象等)

推荐系统(如果你喜欢电影《阿凡达》,你可能会喜欢《星球大战》)

分类(“这部电影很棒”是一个肯定的句子,“这部电影糟透了”是一个否定的句子)

生成搜索(聊天机器人回答关于 PDF、网站、YouTube 视频等的问题)

嵌入其实不是一项新技术,但最近由于 OpenAI 提供的嵌入端点变得更加流行、更加通用和更加易用。我们不会深入探讨嵌入的技术细节,由于互联网上有很多关于它们的信息。

AI 嵌入可以被看做是“哈利·波特”的分院帽。就像分院帽根据学生的特点为他们分配院系一样,AI 嵌入根据特点为类似的内容分配嵌入。当我们想要找到类似的项目时,我们可以要求 AI 为我们提供项目的嵌入,然后计算它们之间的距离。嵌入之间的距离越近,项目越类似。这个进程类似于分院帽根据每一个学生的特点来肯定他们最合适的学院的进程。通过使用 AI 嵌入,我们可以快速、简便地根据特点比较项目,从而做出更明智的决策和更高效的搜索结果。

上述方法仅仅是为了嵌入单词,但是现在,句子、图象、句子+图象和许多其他东西都是可能的。

当你想在生产软件中使用嵌入时,要注意一些问题:

存储嵌入的所有基础设施

本钱优化(例如,避免重复计算数据)

用户嵌入的分段(你不希望搜索功能显示其他用户的数据)

处理模型输入尺寸限制

与流行利用的基础设施集成(supabase、firebase、google cloud 等)

在 GitHub Actions 中不断准备数据

嵌入的目的是能够对任何类型的非结构化数据进行索引,我们希望我们的文档在每次修改时都能被索引,对吧?这是一个 GitHub action,当在主分支上进行 git push 时,将索引每一个 markdown 文件:

“`yaml
# .github/workflows/index.yaml

name: Index documentation

on:

push:

branches:

– main

jobs:

index:

runs-on: ubuntu-latest

steps:

– uses: actions/checkout@v2

– uses: actions/setup-node@v2

with:

node-version: 14

– run: npm install

– run: node scripts/sync.js

env:

EMBEDBASE_API_KEY: ${{ secrets.EMBEDBASE_API_KEY }}

“`

chatgpt markdown support的常见问答Q&A

问题1:甚么是ChatGPT和Markdown格式?

答案:ChatGPT是一种基于人工智能的对话模型,它可以与人类用户进行自然语言交换。Markdown是一种轻量级标记语言,用于简单且易于浏览的文本格式化。

  • ChatGPT:ChatGPT可以通过文本输入与用户进行对话交互。它可以理解用户的问题并生成相应的回答。ChatGPT可以利用于多种场景,如编写文档、编程辅助和在线客服。
  • Markdown格式:Markdown格式是一种简单而直观的文本标记语言,可以用于快速编写格式化的文档。使用Markdown格式,用户可以轻松地添加标题、列表、链接和粗体字等内容。

问题2:怎么将ChatGPT转换为Markdown格式?

答案:将ChatGPT转换为Markdown格式可以通过以下步骤实现:

  1. 生成对话:使用ChatGPT与用户进行交互,并记录对话内容。
  2. 提取文本:从ChatGPT生成的对话中提取文本内容。
  3. 利用Markdown格式:将提取到的文本利用Markdown格式标记,添加标题、列表、粗体字等。
  4. 保存为Markdown文件:将利用Markdown格式后的对话内容保存为Markdown文件。

问题3:怎样在ChatGPT中添加Markdown支持?

答案:要在ChatGPT中添加Markdown支持,可以斟酌以下方法:

  • 扩大输入框:修改ChatGPT的界面,使其支持Markdown格式的输入。
  • 解析Markdown:在ChatGPT中添加Markdown解析器,以解析并理解Markdown格式的输入。
  • 生成Markdown回答:在ChatGPT的回答中,将文本生成为Markdown格式,以便用户能够直接复制和粘贴。

问题4:ChatGPT和Markdown的IntelliJ IDEs插件有哪几种功能支持?

答案:ChatGPT和Markdown的IntelliJ IDEs插件提供以下功能支持:

  • 从Markdown文件中与ChatGPT进行对话:用户可以通过从Markdown文件当选择对话进行交互。
  • 使用JSON模式完成ChatGPT函数:插件提供了JSON模式完成功能,可以帮助用户更快地编写ChatGPT函数。
  • 支持GPT函数:插件支持GPT函数,用户可以在Markdown文件中直接使用GPT函数并获得对应的回答。

问题5:怎么将ChatGPT对话转换为Markdown格式的文件?

答案:要将ChatGPT对话转换为Markdown格式的文件,可使用Python脚本来实现,具体步骤以下:

  1. 导出对话:将ChatGPT对话导出为文本文件,保存对话中的时间戳和发言者信息。
  2. 解析对话:使用Python脚本解析导出的对话文件,提取出每一个发言者的发言内容。
  3. 生成Markdown文件:将解析后的对话内容依照Markdown格式进行整理和排版,并保存为Markdown文件。

问题6:怎么让ChatGPT输出原始Markdown格式的答案?

答案:目前ChatGPT默许输出的答案不是原始的Markdown格式,但可以通过以下方法获得原始Markdown格式的答案:

  • 自定义转换:将ChatGPT生成的文本答案进行自定义的转换,将其转换为符合Markdown格式的文本。可使用Python脚本来实现这个转换进程。
  • 拼接片断:ChatGPT生成的文本答案常常是原始Markdown格式的一个片断,可以将多个这样的片断拼接起来,组成完全的Markdown文件。

问题7:怎么用ChatGPT构建一个基于Markdown的文档系统?

答案:要构建一个基于Markdown的文档系统,可以依照以下步骤进行:

  1. 搜集文档内容:将文档内容整理为Markdown格式,并存储在文本文件或数据库中。
  2. 搭建ChatGPT服务:使用ChatGPT的API或搭建自己的ChatGPT服务器。
  3. 设计用户界面:设计一个用户友好的界面,使用户能够在界面中提出问题。
  4. 查询匹配文档:当用户提出问题时,将问题与Markdown格式的文档进行匹配,找到与问题相关的文档内容。
  5. 生成答案:根据匹配到的文档内容,使用ChatGPT生成准确的答案,并将答案转换为Markdown格式。

ChatGPT相关资讯

ChatGPT热门资讯

X

截屏,微信识别二维码

微信号:muhuanidc

(点击微信号复制,添加好友)

打开微信

微信号已复制,请打开微信添加咨询详情!