chatGPT 如何用结构化输出:如直接要求它以HTML或者JSON格式输出?

40 min read

chatGPT是一个自然语言处理模型,无法直接输出HTML或JSON格式的结果。但是,可以使用编程语言或工具来将chatGPT模型的输出转换为所需的格式。

以下是基于Python的示例代码,将chatGPT模型的输出转换为HTML格式:

import openai
import json
from html import escape

openai.api_key = "YOUR_API_KEY"  # 替换为您的OpenAI API密钥
model_engine = "text-davinci-002"  # 替换为您要使用的GPT模型引擎

def generate_response(prompt):
    response = openai.Completion.create(
        engine=model_engine,
        prompt=prompt,
        max_tokens=1024,
        n=1,
        stop=None,
        temperature=0.7,
    )
    return response.choices[0].text.strip()

prompt = "聊天内容"
response_text = generate_response(prompt)

html_output = f"<p>{escape(prompt)}</p>\n"  # 将prompt作为HTML的段落输出
html_output += f"<p>{escape(response_text)}</p>"  # 将GPT生成的回复作为HTML的段落输出

# 将HTML格式保存到文件
with open("output.html", "w") as f:
    f.write(html_output)

要将chatGPT模型的输出转换为JSON格式,可以使用Python内置的json模块。

import openai
import json

openai.api_key = "YOUR_API_KEY"  # 替换为您的OpenAI API密钥
model_engine = "text-davinci-002"  # 替换为您要使用的GPT模型引擎

def generate_response(prompt):
    response = openai.Completion.create(
        engine=model_engine,
        prompt=prompt,
        max_tokens=1024,
        n=1,
        stop=None,
        temperature=0.7,
    )
    return response.choices[0].text.strip()

prompt = "聊天内容"
response_text = generate_response(prompt)

json_output = {
    "prompt": prompt,
    "response": response_text,
}

# 将JSON格式保存到文件
with open("output.json", "w") as f:
    json.dump(json_output, f)

这里将GPT生成的回复作为JSON对象的一个属性,其它属性可以根据需要添加。