OpenAI 提示词生成
Playground的 Generate 按钮可根据任务描述生成提示词、函数及Schema。本页解释其方法。这里描述生成过程;提示词对象和部分评测功能的生命周期另见提示词概览。
<a id="overview"></a>
概览
从零写提示词和Schema耗时,生成可帮助快速起步。主要方法为:用包含最佳实践的元提示词生成或改进提示,用元Schema生成有效JSON与函数语法。原文说明未来可能整合DSPy及“梯度下降”提示优化等更高级技术,这是可能方向,不是已经提供的功能。
<a id="prompts"></a>
提示词
元提示词指导模型根据任务描述创建良好提示,或改善现有提示。Playground结合提示词工程实践与用户经验,并针对音频等输出类型采用不同元提示,确保格式适当。
<a id="meta-prompts"></a>
元提示词
文本输出:程序内元提示词中文译文
根据任务描述或现有提示,生成详细系统提示,引导语言模型有效完成任务。
# 指南
- 理解任务:把握主要目的、目标、要求、约束和预期输出。
- 最小修改:提供现有提示时,简单提示可直接改进;复杂提示只改善清晰度、补缺,不改变原结构。
- 先推理后结论:鼓励在得结论前推理。注意,用户示例若先结论后推理,必须反转!示例绝不以结论开头。指出推理部分和结论部分的具体字段名,确定各自顺序及是否要反转。结论、分类或结果始终最后出现。
- 示例:有帮助时给高质量示例,复杂元素用[方括号占位符]。考虑应给何种示例、数量,以及复杂程度是否需要占位符。
- 清楚简洁:用清楚具体语言,避免不必要指令和空泛说法。
- 格式:用Markdown便于阅读。除非明确要求,不使用三个反引号的代码块。
- 保留用户内容:任务或提示含大量指南、示例时,完整或尽可能接近原样保留;模糊时考虑拆为子步骤。保留所有细节、指南、示例、变量及占位符。
- 常量:务必在提示中包含指南、评分标准、示例等常量;原提示给出的理由是它们不易受提示注入影响。
- 输出格式:明确、详细规定最适合的格式,包括长度、语法,例如短句、段落、JSON。对分类、JSON等定义明确或结构化数据,优先JSON。未经明确要求,JSON绝不包在代码围栏中。
最终提示遵循以下结构,只输出完成的系统提示,不加评论,开头末尾都不加其他消息,例如不加“---”。
[简洁任务指令,必须为首行,不设小节标题]
[按需补充细节]
[可选:以标题或要点列出详细步骤]
# Steps [可选]
[完成任务所需步骤的详细拆解]
# Output Format
[明确输出长度、结构,如JSON、Markdown等]
# Examples [可选]
[1—3个定义清楚的示例,必要时用占位符,标明起止及输入输出]
[示例短于真实案例时,用圆括号说明真实案例应更长/更短/有何不同,并使用占位符]
# Notes [可选]
[边界情况、细节,以及需特别指出或重复的重要事项]
下列各语言实现保留原英文程序字符串;用户输入以“Task, Goal, or Current Prompt”(任务、目标或当前提示)为前缀,再插入实际任务变量;输出用于后续应用。元提示中关于常量和注入的表述属于原示例,不代表常量能绝对免疫提示注入。
本组调用任务逐项对应:“Write a concise product launch announcement.”为“撰写一则简洁的产品发布公告”;Go和C#的“Help a customer resolve a billing issue.”为“帮助客户解决账单问题”;Python示例接收调用方传入的任务变量,不预设相同任务。
元提示词(来源示例1,javascript)
// [中文] 将文本元提示作为system消息,用户消息拼入任务、目标或当前提示。
// [中文] 发送Chat Completions并读取生成的提示词;长字符串中的标题是提示词正文,不是程序注释。
import OpenAI from "openai";
const client = new OpenAI();
const metaPrompt = `Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.
## Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!
- Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.
- Conclusion, classifications, or results should ALWAYS appear last.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Formatting: Use markdown features for readability. DO NOT USE \`\`\` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
- For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
- JSON should never be wrapped in code blocks (\`\`\`) unless explicitly requested.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
## Steps [optional]
[optional: a detailed breakdown of the steps necessary to accomplish the task]
## Output Format
[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]
## Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
## Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]`;
async function generatePrompt(taskOrPrompt) {
const completion = await client.chat.completions.create({
model: "gpt-6-astra",
messages: [
{ role: "system", content: metaPrompt },
{
role: "user",
content: "Task, Goal, or Current Prompt:\n" + taskOrPrompt,
},
],
});
return completion.choices[0].message.content;
}
console.log(
await generatePrompt("Write a concise product launch announcement.")
);
元提示词(来源示例2,python)
## [中文] 将文本元提示作为system消息,用户消息拼入任务、目标或当前提示。
## [中文] 发送Chat Completions并读取生成的提示词;长字符串中的标题是提示词正文,不是程序注释。
from openai import OpenAI
client = OpenAI()
META_PROMPT = """
Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.
## Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!
- Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.
- Conclusion, classifications, or results should ALWAYS appear last.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
- For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
- JSON should never be wrapped in code blocks (```) unless explicitly requested.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
## Steps [optional]
[optional: a detailed breakdown of the steps necessary to accomplish the task]
## Output Format
[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]
## Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
## Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
""".strip()
def generate_prompt(task_or_prompt: str):
completion = client.chat.completions.create(
model="gpt-6-astra",
messages=[
{
"role": "system",
"content": META_PROMPT,
},
{
"role": "user",
"content": "Task, Goal, or Current Prompt:\n" + task_or_prompt,
},
],
)
return completion.choices[0].message.content
元提示词(来源示例3,go)
// [中文] 将文本元提示作为system消息,用户消息拼入任务、目标或当前提示。
// [中文] 发送Chat Completions并读取生成的提示词;长字符串中的标题是提示词正文,不是程序注释。
import (
"context"
"fmt"
"log"
"github.com/openai/openai-go/v3"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
client := openai.NewClient()
metaPrompt := "Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.\n" +
"\n" +
"# Guidelines\n" +
"\n" +
"- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.\n" +
"- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.\n" +
"- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!\n" +
" - Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.\n" +
" - Conclusion, classifications, or results should ALWAYS appear last.\n" +
"- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.\n" +
" - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.\n" +
"- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.\n" +
"- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.\n" +
"- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.\n" +
"- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.\n" +
"- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)\n" +
" - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.\n" +
" - JSON should never be wrapped in code blocks (```) unless explicitly requested.\n" +
"\n" +
"The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no \"---\")\n" +
"\n" +
"[Concise instruction describing the task - this should be the first line in the prompt, no section header]\n" +
"\n" +
"[Additional details as needed.]\n" +
"\n" +
"[Optional sections with headings or bullet points for detailed steps.]\n" +
"\n" +
"# Steps [optional]\n" +
"\n" +
"[optional: a detailed breakdown of the steps necessary to accomplish the task]\n" +
"\n" +
"# Output Format\n" +
"\n" +
"[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]\n" +
"\n" +
"# Examples [optional]\n" +
"\n" +
"[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]\n" +
"[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]\n" +
"\n" +
"# Notes [optional]\n" +
"\n" +
"[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n"
completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
Model: "gpt-6-astra",
Messages: []openai.ChatCompletionMessageParamUnion{
openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),
}})
if err != nil {
return err
}
fmt.Println(completion.Choices[0].Message.Content)
return nil
}
元提示词(来源示例4,java)
// [中文] 将文本元提示作为system消息,用户消息拼入任务、目标或当前提示。
// [中文] 发送Chat Completions并读取生成的提示词;长字符串中的标题是提示词正文,不是程序注释。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
String metaPrompt =
"""
Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.
# Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!
- Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.
- Conclusion, classifications, or results should ALWAYS appear last.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
- For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
- JSON should never be wrapped in code blocks (```) unless explicitly requested.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
# Steps [optional]
[optional: a detailed breakdown of the steps necessary to accomplish the task]
# Output Format
[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]
# Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
# Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
"""
.strip();
ChatCompletionCreateParams params =
ChatCompletionCreateParams.builder()
.model("gpt-6-astra")
.addSystemMessage(metaPrompt)
.addUserMessage(
"Task, Goal, or Current Prompt:\nWrite a concise product launch announcement.")
.build();
client.chat().completions().create(params).choices().stream()
.flatMap(choice -> choice.message().content().stream())
.forEach(System.out::println);
元提示词(来源示例5,csharp)
// [中文] 将文本元提示作为system消息,用户消息拼入任务、目标或当前提示。
// [中文] 发送Chat Completions并读取生成的提示词;长字符串中的标题是提示词正文,不是程序注释。
using OpenAI.Chat;
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-6-astra";
ChatClient client = new(model, key);
string metaPrompt = """"
Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.
# Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!
- Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.
- Conclusion, classifications, or results should ALWAYS appear last.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
- For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
- JSON should never be wrapped in code blocks (```) unless explicitly requested.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
# Steps [optional]
[optional: a detailed breakdown of the steps necessary to accomplish the task]
# Output Format
[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]
# Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
# Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
"""";
ChatCompletionOptions options = new();
ChatCompletion result = await client.CompleteChatAsync([new SystemChatMessage(metaPrompt), new UserChatMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue.")], options);
Console.WriteLine(result.Content[0].Text);
元提示词(来源示例6,ruby)
## [中文] 将文本元提示作为system消息,用户消息拼入任务、目标或当前提示。
## [中文] 发送Chat Completions并读取生成的提示词;长字符串中的标题是提示词正文,不是程序注释。
require "openai"
client = OpenAI::Client.new
meta_prompt = <<~PROMPT
Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.
# Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!
- Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.
- Conclusion, classifications, or results should ALWAYS appear last.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
- For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
- JSON should never be wrapped in code blocks (```) unless explicitly requested.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
# Steps [optional]
[optional: a detailed breakdown of the steps necessary to accomplish the task]
# Output Format
[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]
# Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
# Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
PROMPT
def generate_prompt(client, meta_prompt, task_or_prompt)
completion = client.chat.completions.create(
model: "gpt-6-astra",
messages: [
{
role: :system,
content: meta_prompt
},
{
role: :user,
content: "Task, Goal, or Current Prompt:\n#{task_or_prompt}"
}
]
)
completion.choices.fetch(0).message.content
end
puts(generate_prompt(client, meta_prompt, "Write a concise product launch announcement."))
音频输出:程序内元提示词中文译文
根据任务描述或现有提示,生成详细系统提示,引导实时音频输出语言模型有效完成任务。
# 指南
- 理解任务:把握主要目的、目标、要求、约束和预期输出。
- 语气:明确指出语气。默认富有情感、友好,语速较快,避免让用户等待。
- 音频输出约束:回复简短、适合对话。
- 最小修改:已有提示简单时可改进;复杂提示只改善清晰度、补缺,不改变原结构。
- 示例:有帮助时给高质量示例,复杂元素用[方括号占位符];考虑类型、数量及是否复杂到需要占位符。示例必须体现简短对话输出。默认句子很短,不让助手连续说3句,而是拆成与用户来回互动。默认每句约5—20个词;用户明确要求“短”时,示例回复最多1—10个词。示例必须多轮,每例至少4次来回互动,而非单次问答,体现自然对话。
- 清楚简洁:清楚、具体,不加多余指令或空泛说法。
- 保留用户内容:大量指南和示例应完整或尽可能接近原样保留;模糊时考虑拆步骤,保留全部细节、指南、示例、变量与占位符。
- 常量:务必纳入指南、评分标准、示例;原提示给出的理由是它们不易受提示注入影响。
最终提示只输出完成的系统提示,不加评论,开头末尾不加额外消息,如“---”,结构为:
[简洁任务指令作为首行,无小节标题]
[按需补充细节]
[可选:详细步骤的标题或要点]
# Examples [可选]
[1—3个定义明确的示例,必要时用占位符,标明起止、输入与输出]
[示例短于真实预期时,用圆括号说明真实案例应更长/更短/如何不同,并使用占位符]
# Notes [可选]
[边界情况、细节及需要特别指出或重复的重要事项]
本组JavaScript、Java、Ruby任务“Create a friendly voice assistant for a bike shop.”译为“为自行车商店创建一个友好的语音助手”;Go和C#仍使用“帮助客户解决账单问题”,Python接收任务变量。
元提示词(来源示例7,javascript)
// [中文] 使用音频输出专用元提示,把语音表达、节奏及输出约束交给提示生成器。
// [中文] 任务仍作为独立user消息提交,返回文本用于后续音频任务。
import OpenAI from "openai";
const client = new OpenAI();
const metaPrompt = `Given a task description or existing prompt, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.
## Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.
- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- It is very important that any examples included reflect the short, conversational output responses of the model.
Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.
- By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.
- Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
## Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
## Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]`;
async function generatePrompt(taskOrPrompt) {
const completion = await client.chat.completions.create({
model: "gpt-6-astra",
messages: [
{ role: "system", content: metaPrompt },
{
role: "user",
content: "Task, Goal, or Current Prompt:\n" + taskOrPrompt,
},
],
});
return completion.choices[0].message.content;
}
console.log(
await generatePrompt("Create a friendly voice assistant for a bike shop.")
);
元提示词(来源示例8,python)
## [中文] 使用音频输出专用元提示,把语音表达、节奏及输出约束交给提示生成器。
## [中文] 任务仍作为独立user消息提交,返回文本用于后续音频任务。
from openai import OpenAI
client = OpenAI()
META_PROMPT = """
Given a task description or existing prompt, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.
## Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.
- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- It is very important that any examples included reflect the short, conversational output responses of the model.
Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.
- By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.
- Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
## Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
## Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
""".strip()
def generate_prompt(task_or_prompt: str):
completion = client.chat.completions.create(
model="gpt-6-astra",
messages=[
{
"role": "system",
"content": META_PROMPT,
},
{
"role": "user",
"content": "Task, Goal, or Current Prompt:\n" + task_or_prompt,
},
],
)
return completion.choices[0].message.content
元提示词(来源示例9,go)
// [中文] 使用音频输出专用元提示,把语音表达、节奏及输出约束交给提示生成器。
// [中文] 任务仍作为独立user消息提交,返回文本用于后续音频任务。
import (
"context"
"fmt"
"log"
"github.com/openai/openai-go/v3"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
client := openai.NewClient()
metaPrompt := "Given a task description or existing prompt, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.\n" +
"\n" +
"# Guidelines\n" +
"\n" +
"- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.\n" +
"- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.\n" +
"- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.\n" +
"- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.\n" +
"- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.\n" +
" - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.\n" +
" - It is very important that any examples included reflect the short, conversational output responses of the model.\n" +
"Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.\n" +
" - By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for \"short\" responses, then the examples should truly have 1-10 word responses max.\n" +
" - Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.\n" +
"- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.\n" +
"- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.\n" +
"- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.\n" +
"\n" +
"The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no \"---\")\n" +
"\n" +
"[Concise instruction describing the task - this should be the first line in the prompt, no section header]\n" +
"\n" +
"[Additional details as needed.]\n" +
"\n" +
"[Optional sections with headings or bullet points for detailed steps.]\n" +
"\n" +
"# Examples [optional]\n" +
"\n" +
"[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]\n" +
"[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]\n" +
"\n" +
"# Notes [optional]\n" +
"\n" +
"[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n"
completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
Model: "gpt-6-astra",
Messages: []openai.ChatCompletionMessageParamUnion{
openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),
}})
if err != nil {
return err
}
fmt.Println(completion.Choices[0].Message.Content)
return nil
}
元提示词(来源示例10,java)
// [中文] 使用音频输出专用元提示,把语音表达、节奏及输出约束交给提示生成器。
// [中文] 任务仍作为独立user消息提交,返回文本用于后续音频任务。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
String metaPrompt =
"""
Given a task description or existing prompt, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.
# Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.
- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- It is very important that any examples included reflect the short, conversational output responses of the model.
Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.
- By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.
- Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
# Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
# Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
"""
.strip();
ChatCompletionCreateParams params =
ChatCompletionCreateParams.builder()
.model("gpt-6-astra")
.addSystemMessage(metaPrompt)
.addUserMessage(
"Task, Goal, or Current Prompt:\n"
+ "Create a friendly voice assistant for a bike shop.")
.build();
client.chat().completions().create(params).choices().stream()
.flatMap(choice -> choice.message().content().stream())
.forEach(System.out::println);
元提示词(来源示例11,csharp)
// [中文] 使用音频输出专用元提示,把语音表达、节奏及输出约束交给提示生成器。
// [中文] 任务仍作为独立user消息提交,返回文本用于后续音频任务。
using OpenAI.Chat;
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-6-astra";
ChatClient client = new(model, key);
string metaPrompt = """"
Given a task description or existing prompt, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.
# Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.
- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- It is very important that any examples included reflect the short, conversational output responses of the model.
Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.
- By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.
- Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
# Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
# Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
"""";
ChatCompletionOptions options = new();
ChatCompletion result = await client.CompleteChatAsync([new SystemChatMessage(metaPrompt), new UserChatMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue.")], options);
Console.WriteLine(result.Content[0].Text);
元提示词(来源示例12,ruby)
## [中文] 使用音频输出专用元提示,把语音表达、节奏及输出约束交给提示生成器。
## [中文] 任务仍作为独立user消息提交,返回文本用于后续音频任务。
require "openai"
client = OpenAI::Client.new
meta_prompt = <<~PROMPT
Given a task description or existing prompt, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.
# Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.
- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- It is very important that any examples included reflect the short, conversational output responses of the model.
Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.
- By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.
- Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
# Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
# Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
PROMPT
def generate_prompt(client, meta_prompt, task_or_prompt)
completion = client.chat.completions.create(
model: "gpt-6-astra",
messages: [
{
role: :system,
content: meta_prompt
},
{
role: :user,
content: "Task, Goal, or Current Prompt:\n#{task_or_prompt}"
}
]
)
completion.choices.fetch(0).message.content
end
puts(generate_prompt(client, meta_prompt, "Create a friendly voice assistant for a bike shop."))
<a id="prompt-edits"></a>
编辑提示词
编辑时采用略改的元提示。直接修改通常容易,开放式修订较难确定改什么,因此先在响应开头加入推理小节,检查原提示的清晰度、推理与结论顺序、结构和具体程度,提出改进。该小节随后从最终响应中解析移除。
文本输出编辑版:在上述文本元提示的完整指南和结构之前,换用下面的任务与分析前缀;末尾再加“必须以reasoning小节开头,立即生成的下一个token必须为<reasoning>”。实际完整译文如下。
根据当前提示和修改描述,生成详细系统提示,引导语言模型有效完成任务。
最终输出为修改后完整提示词。但在其之前,响应最开头必须以<reasoning&标签分析并明确回答:
<reasoning&
- Simple Change:(yes/no) 修改描述是否明确、简单?是则跳过后续问题。
- Reasoning:(yes/no) 当前提示是否使用推理、分析或思维链?
- Identify:(最多10个词) 哪些小节使用推理?
- Conclusion:(yes/no) 推理是否用于确定结论?
- Ordering:(before/after) 推理位于前还是后?
- Structure:(yes/no) 输入提示是否结构明确?
- Examples:(yes/no) 是否有少样本示例?
- Representative:(1—5) 若有,代表性如何?
- Complexity:(1—5) 输入提示有多复杂?
- Task:(1—5) 隐含任务有多复杂?
- Necessity:()
- Specificity:(1—5) 提示有多详细具体?不要与长度混淆。
- Prioritization:(列表) 最重要的1—3类改进是什么?
- Conclusion:(最多30个词) 根据评估,以简洁祈使句描述改什么、如何改,不必仅限上述分类。
</reasoning&
# 指南
- 理解任务:把握主要目的、目标、要求、约束和预期输出。
- 最小修改:提供现有提示时,简单提示可直接改进;复杂提示只改善清晰度、补缺,不改变原结构。
- 先推理后结论:鼓励在得结论前推理。注意,用户示例若先结论后推理,必须反转!示例绝不以结论开头。指出推理部分和结论部分的具体字段名,确定各自顺序及是否要反转。结论、分类或结果始终最后出现。
- 示例:有帮助时给高质量示例,复杂元素用[方括号占位符]。考虑应给何种示例、数量,以及复杂程度是否需要占位符。
- 清楚简洁:用清楚具体语言,避免不必要指令和空泛说法。
- 格式:用Markdown便于阅读。除非明确要求,不使用三个反引号的代码块。
- 保留用户内容:任务或提示含大量指南、示例时,完整或尽可能接近原样保留;模糊时考虑拆为子步骤。保留所有细节、指南、示例、变量及占位符。
- 常量:务必在提示中包含指南、评分标准、示例等常量;原提示给出的理由是它们不易受提示注入影响。
- 输出格式:明确、详细规定最适合的格式,包括长度、语法,例如短句、段落、JSON。对分类、JSON等定义明确或结构化数据,优先JSON。未经明确要求,JSON绝不包在代码围栏中。
最终提示遵循以下结构,只输出完成的系统提示,不加评论,开头末尾都不加其他消息,例如不加“---”。
[简洁任务指令,必须为首行,不设小节标题]
[按需补充细节]
[可选:以标题或要点列出详细步骤]
# Steps [可选]
[完成任务所需步骤的详细拆解]
# Output Format
[明确输出长度、结构,如JSON、Markdown等]
# Examples [可选]
[1—3个定义清楚的示例,必要时用占位符,标明起止及输入输出]
[示例短于真实案例时,用圆括号说明真实案例应更长/更短/有何不同,并使用占位符]
# Notes [可选]
[边界情况、细节,以及需特别指出或重复的重要事项]
[注意:必须先输出<reasoning&小节,立即生成的下一个token必须是<reasoning&。]
本组JavaScript和Ruby任务“Make this support prompt more concise and empathetic.”为“让这个客服提示词更简洁、更有同理心”;Java任务“Make this product launch announcement clearer and more concise.”为“让这则产品发布公告更清楚、更简洁”;Go和C#仍为账单问题任务,Python接收任务变量。下列程序直接返回生成文本,并未实现前文所述分析小节移除;应用需自行补充这一步,不能把元提示的格式要求当作已完成的程序处理。
编辑提示词(来源示例13,javascript)
// [中文] 用编辑版元提示审查并改写原提示,要求先输出约定的reasoning小节。
// [中文] 这些程序返回原生成文本;应用若只需最终提示,还须实现分析小节的解析和移除。
import OpenAI from "openai";
const client = new OpenAI();
const metaPrompt = `Given a current prompt and a change description, produce a detailed system prompt to guide a language model in completing the task effectively.
Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:
<reasoning>
- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)
- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?
- Identify: (max 10 words) if so, which section(s) utilize reasoning?
- Conclusion: (yes/no) is the chain of thought used to determine a conclusion?
- Ordering: (before/after) is the chain of though located before or after
- Structure: (yes/no) does the input prompt have a well defined structure
- Examples: (yes/no) does the input prompt have few-shot examples
- Representative: (1-5) if present, how representative are the examples?
- Complexity: (1-5) how complex is the input prompt?
- Task: (1-5) how complex is the implied task?
- Necessity: ()
- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)
- Prioritization: (list) what 1-3 categories are the MOST important to address.
- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed
</reasoning>
## Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!
- Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.
- Conclusion, classifications, or results should ALWAYS appear last.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Formatting: Use markdown features for readability. DO NOT USE \`\`\` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
- For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
- JSON should never be wrapped in code blocks (\`\`\`) unless explicitly requested.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
## Steps [optional]
[optional: a detailed breakdown of the steps necessary to accomplish the task]
## Output Format
[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]
## Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
## Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]`;
async function generatePrompt(taskOrPrompt) {
const completion = await client.chat.completions.create({
model: "gpt-6-astra",
messages: [
{ role: "system", content: metaPrompt },
{
role: "user",
content: "Task, Goal, or Current Prompt:\n" + taskOrPrompt,
},
],
});
return completion.choices[0].message.content;
}
console.log(
await generatePrompt("Make this support prompt more concise and empathetic.")
);
编辑提示词(来源示例14,python)
## [中文] 用编辑版元提示审查并改写原提示,要求先输出约定的reasoning小节。
## [中文] 这些程序返回原生成文本;应用若只需最终提示,还须实现分析小节的解析和移除。
from openai import OpenAI
client = OpenAI()
META_PROMPT = """
Given a current prompt and a change description, produce a detailed system prompt to guide a language model in completing the task effectively.
Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:
<reasoning>
- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)
- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?
- Identify: (max 10 words) if so, which section(s) utilize reasoning?
- Conclusion: (yes/no) is the chain of thought used to determine a conclusion?
- Ordering: (before/after) is the chain of though located before or after
- Structure: (yes/no) does the input prompt have a well defined structure
- Examples: (yes/no) does the input prompt have few-shot examples
- Representative: (1-5) if present, how representative are the examples?
- Complexity: (1-5) how complex is the input prompt?
- Task: (1-5) how complex is the implied task?
- Necessity: ()
- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)
- Prioritization: (list) what 1-3 categories are the MOST important to address.
- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed
</reasoning>
## Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!
- Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.
- Conclusion, classifications, or results should ALWAYS appear last.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
- For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
- JSON should never be wrapped in code blocks (```) unless explicitly requested.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
## Steps [optional]
[optional: a detailed breakdown of the steps necessary to accomplish the task]
## Output Format
[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]
## Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
## Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]
""".strip()
def generate_prompt(task_or_prompt: str):
completion = client.chat.completions.create(
model="gpt-6-astra",
messages=[
{
"role": "system",
"content": META_PROMPT,
},
{
"role": "user",
"content": "Task, Goal, or Current Prompt:\n" + task_or_prompt,
},
],
)
return completion.choices[0].message.content
编辑提示词(来源示例15,go)
// [中文] 用编辑版元提示审查并改写原提示,要求先输出约定的reasoning小节。
// [中文] 这些程序返回原生成文本;应用若只需最终提示,还须实现分析小节的解析和移除。
import (
"context"
"fmt"
"log"
"github.com/openai/openai-go/v3"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
client := openai.NewClient()
metaPrompt := "Given a current prompt and a change description, produce a detailed system prompt to guide a language model in completing the task effectively.\n" +
"\n" +
"Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:\n" +
"<reasoning>\n" +
"- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)\n" +
"- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?\n" +
" - Identify: (max 10 words) if so, which section(s) utilize reasoning?\n" +
" - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?\n" +
" - Ordering: (before/after) is the chain of though located before or after\n" +
"- Structure: (yes/no) does the input prompt have a well defined structure\n" +
"- Examples: (yes/no) does the input prompt have few-shot examples\n" +
" - Representative: (1-5) if present, how representative are the examples?\n" +
"- Complexity: (1-5) how complex is the input prompt?\n" +
" - Task: (1-5) how complex is the implied task?\n" +
" - Necessity: ()\n" +
"- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)\n" +
"- Prioritization: (list) what 1-3 categories are the MOST important to address.\n" +
"- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed\n" +
"</reasoning>\n" +
"\n" +
"# Guidelines\n" +
"\n" +
"- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.\n" +
"- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.\n" +
"- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!\n" +
" - Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.\n" +
" - Conclusion, classifications, or results should ALWAYS appear last.\n" +
"- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.\n" +
" - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.\n" +
"- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.\n" +
"- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.\n" +
"- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.\n" +
"- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.\n" +
"- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)\n" +
" - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.\n" +
" - JSON should never be wrapped in code blocks (```) unless explicitly requested.\n" +
"\n" +
"The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no \"---\")\n" +
"\n" +
"[Concise instruction describing the task - this should be the first line in the prompt, no section header]\n" +
"\n" +
"[Additional details as needed.]\n" +
"\n" +
"[Optional sections with headings or bullet points for detailed steps.]\n" +
"\n" +
"# Steps [optional]\n" +
"\n" +
"[optional: a detailed breakdown of the steps necessary to accomplish the task]\n" +
"\n" +
"# Output Format\n" +
"\n" +
"[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]\n" +
"\n" +
"# Examples [optional]\n" +
"\n" +
"[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]\n" +
"[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]\n" +
"\n" +
"# Notes [optional]\n" +
"\n" +
"[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n" +
"[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]\n"
completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
Model: "gpt-6-astra",
Messages: []openai.ChatCompletionMessageParamUnion{
openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),
}})
if err != nil {
return err
}
fmt.Println(completion.Choices[0].Message.Content)
return nil
}
编辑提示词(来源示例16,java)
// [中文] 用编辑版元提示审查并改写原提示,要求先输出约定的reasoning小节。
// [中文] 这些程序返回原生成文本;应用若只需最终提示,还须实现分析小节的解析和移除。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
String metaPrompt =
"""
Given a current prompt and a change description, produce a detailed system prompt to guide a language model in completing the task effectively.
Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:
<reasoning>
- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)
- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?
- Identify: (max 10 words) if so, which section(s) utilize reasoning?
- Conclusion: (yes/no) is the chain of thought used to determine a conclusion?
- Ordering: (before/after) is the chain of though located before or after
- Structure: (yes/no) does the input prompt have a well defined structure
- Examples: (yes/no) does the input prompt have few-shot examples
- Representative: (1-5) if present, how representative are the examples?
- Complexity: (1-5) how complex is the input prompt?
- Task: (1-5) how complex is the implied task?
- Necessity: ()
- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)
- Prioritization: (list) what 1-3 categories are the MOST important to address.
- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed
</reasoning>
# Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!
- Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.
- Conclusion, classifications, or results should ALWAYS appear last.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
- For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
- JSON should never be wrapped in code blocks (```) unless explicitly requested.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
# Steps [optional]
[optional: a detailed breakdown of the steps necessary to accomplish the task]
# Output Format
[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]
# Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
# Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]
"""
.strip();
ChatCompletionCreateParams params =
ChatCompletionCreateParams.builder()
.model("gpt-6-astra")
.addSystemMessage(metaPrompt)
.addUserMessage(
"Task, Goal, or Current Prompt:\nMake this product launch announcement clearer and more concise.")
.build();
client.chat().completions().create(params).choices().stream()
.flatMap(choice -> choice.message().content().stream())
.forEach(System.out::println);
编辑提示词(来源示例17,csharp)
// [中文] 用编辑版元提示审查并改写原提示,要求先输出约定的reasoning小节。
// [中文] 这些程序返回原生成文本;应用若只需最终提示,还须实现分析小节的解析和移除。
using OpenAI.Chat;
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-6-astra";
ChatClient client = new(model, key);
string metaPrompt = """"
Given a current prompt and a change description, produce a detailed system prompt to guide a language model in completing the task effectively.
Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:
<reasoning>
- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)
- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?
- Identify: (max 10 words) if so, which section(s) utilize reasoning?
- Conclusion: (yes/no) is the chain of thought used to determine a conclusion?
- Ordering: (before/after) is the chain of though located before or after
- Structure: (yes/no) does the input prompt have a well defined structure
- Examples: (yes/no) does the input prompt have few-shot examples
- Representative: (1-5) if present, how representative are the examples?
- Complexity: (1-5) how complex is the input prompt?
- Task: (1-5) how complex is the implied task?
- Necessity: ()
- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)
- Prioritization: (list) what 1-3 categories are the MOST important to address.
- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed
</reasoning>
# Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!
- Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.
- Conclusion, classifications, or results should ALWAYS appear last.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
- For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
- JSON should never be wrapped in code blocks (```) unless explicitly requested.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
# Steps [optional]
[optional: a detailed breakdown of the steps necessary to accomplish the task]
# Output Format
[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]
# Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
# Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]
"""";
ChatCompletionOptions options = new();
ChatCompletion result = await client.CompleteChatAsync([new SystemChatMessage(metaPrompt), new UserChatMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue.")], options);
Console.WriteLine(result.Content[0].Text);
编辑提示词(来源示例18,ruby)
## [中文] 用编辑版元提示审查并改写原提示,要求先输出约定的reasoning小节。
## [中文] 这些程序返回原生成文本;应用若只需最终提示,还须实现分析小节的解析和移除。
require "openai"
client = OpenAI::Client.new
meta_prompt = <<~PROMPT
Given a current prompt and a change description, produce a detailed system prompt to guide a language model in completing the task effectively.
Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:
<reasoning>
- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)
- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?
- Identify: (max 10 words) if so, which section(s) utilize reasoning?
- Conclusion: (yes/no) is the chain of thought used to determine a conclusion?
- Ordering: (before/after) is the chain of though located before or after
- Structure: (yes/no) does the input prompt have a well defined structure
- Examples: (yes/no) does the input prompt have few-shot examples
- Representative: (1-5) if present, how representative are the examples?
- Complexity: (1-5) how complex is the input prompt?
- Task: (1-5) how complex is the implied task?
- Necessity: ()
- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)
- Prioritization: (list) what 1-3 categories are the MOST important to address.
- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed
</reasoning>
# Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!
- Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.
- Conclusion, classifications, or results should ALWAYS appear last.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
- For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
- JSON should never be wrapped in code blocks (```) unless explicitly requested.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
# Steps [optional]
[optional: a detailed breakdown of the steps necessary to accomplish the task]
# Output Format
[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]
# Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
# Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]
PROMPT
def generate_prompt(client, meta_prompt, task_or_prompt)
completion = client.chat.completions.create(
model: "gpt-6-astra",
messages: [
{
role: :system,
content: meta_prompt
},
{
role: :user,
content: "Task, Goal, or Current Prompt:\n#{task_or_prompt}"
}
]
)
completion.choices.fetch(0).message.content
end
puts(generate_prompt(client, meta_prompt, "Make this support prompt more concise and empathetic."))
音频输出编辑版完整译文
根据当前提示和修改描述,生成详细系统提示,引导实时音频输出语言模型有效完成任务。
最终输出为修改后完整提示词。但在其之前,响应最开头必须以<reasoning&标签分析并明确回答:
<reasoning&
- Simple Change:(yes/no) 修改描述是否明确、简单?是则跳过后续问题。
- Reasoning:(yes/no) 当前提示是否使用推理、分析或思维链?
- Identify:(最多10个词) 哪些小节使用推理?
- Conclusion:(yes/no) 推理是否用于确定结论?
- Ordering:(before/after) 推理位于前还是后?
- Structure:(yes/no) 输入提示是否结构明确?
- Examples:(yes/no) 是否有少样本示例?
- Representative:(1—5) 若有,代表性如何?
- Complexity:(1—5) 输入提示有多复杂?
- Task:(1—5) 隐含任务有多复杂?
- Necessity:()
- Specificity:(1—5) 提示有多详细具体?不要与长度混淆。
- Prioritization:(列表) 最重要的1—3类改进是什么?
- Conclusion:(最多30个词) 根据评估,以简洁祈使句描述改什么、如何改,不必仅限上述分类。
</reasoning&
# 指南
- 理解任务:把握主要目的、目标、要求、约束和预期输出。
- 语气:明确指出语气。默认富有情感、友好,语速较快,避免让用户等待。
- 音频输出约束:回复简短、适合对话。
- 最小修改:已有提示简单时可改进;复杂提示只改善清晰度、补缺,不改变原结构。
- 示例:有帮助时给高质量示例,复杂元素用[方括号占位符];考虑类型、数量及是否复杂到需要占位符。示例必须体现简短对话输出。默认句子很短,不让助手连续说3句,而是拆成与用户来回互动。默认每句约5—20个词;用户明确要求“短”时,示例回复最多1—10个词。示例必须多轮,每例至少4次来回互动,而非单次问答,体现自然对话。
- 清楚简洁:清楚、具体,不加多余指令或空泛说法。
- 保留用户内容:大量指南和示例应完整或尽可能接近原样保留;模糊时考虑拆步骤,保留全部细节、指南、示例、变量与占位符。
- 常量:务必纳入指南、评分标准、示例;原提示给出的理由是它们不易受提示注入影响。
最终提示只输出完成的系统提示,不加评论,开头末尾不加额外消息,如“---”,结构为:
[简洁任务指令作为首行,无小节标题]
[按需补充细节]
[可选:详细步骤的标题或要点]
# Examples [可选]
[1—3个定义明确的示例,必要时用占位符,标明起止、输入与输出]
[示例短于真实预期时,用圆括号说明真实案例应更长/更短/如何不同,并使用占位符]
# Notes [可选]
[边界情况、细节及需要特别指出或重复的重要事项]
[注意:必须先输出<reasoning&小节,立即生成的下一个token必须是<reasoning&。]
本组JavaScript、Java和Ruby任务“Make this voice assistant prompt warmer and more direct.”译为“让这个语音助手提示词更亲切、更直接”;Go和C#仍为账单问题任务,Python接收任务变量。
编辑提示词(来源示例19,javascript)
// [中文] 用编辑版元提示审查并改写原提示,要求先输出约定的reasoning小节。
// [中文] 这些程序返回原生成文本;应用若只需最终提示,还须实现分析小节的解析和移除。
import OpenAI from "openai";
const client = new OpenAI();
const metaPrompt = `Given a current prompt and a change description, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.
Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:
<reasoning>
- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)
- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?
- Identify: (max 10 words) if so, which section(s) utilize reasoning?
- Conclusion: (yes/no) is the chain of thought used to determine a conclusion?
- Ordering: (before/after) is the chain of though located before or after
- Structure: (yes/no) does the input prompt have a well defined structure
- Examples: (yes/no) does the input prompt have few-shot examples
- Representative: (1-5) if present, how representative are the examples?
- Complexity: (1-5) how complex is the input prompt?
- Task: (1-5) how complex is the implied task?
- Necessity: ()
- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)
- Prioritization: (list) what 1-3 categories are the MOST important to address.
- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed
</reasoning>
## Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.
- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- It is very important that any examples included reflect the short, conversational output responses of the model.
Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.
- By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.
- Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
## Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
## Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]`;
async function generatePrompt(taskOrPrompt) {
const completion = await client.chat.completions.create({
model: "gpt-6-astra",
messages: [
{ role: "system", content: metaPrompt },
{
role: "user",
content: "Task, Goal, or Current Prompt:\n" + taskOrPrompt,
},
],
});
return completion.choices[0].message.content;
}
console.log(
await generatePrompt(
"Make this voice assistant prompt warmer and more direct."
)
);
编辑提示词(来源示例20,python)
## [中文] 用编辑版元提示审查并改写原提示,要求先输出约定的reasoning小节。
## [中文] 这些程序返回原生成文本;应用若只需最终提示,还须实现分析小节的解析和移除。
from openai import OpenAI
client = OpenAI()
META_PROMPT = """
Given a current prompt and a change description, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.
Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:
<reasoning>
- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)
- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?
- Identify: (max 10 words) if so, which section(s) utilize reasoning?
- Conclusion: (yes/no) is the chain of thought used to determine a conclusion?
- Ordering: (before/after) is the chain of though located before or after
- Structure: (yes/no) does the input prompt have a well defined structure
- Examples: (yes/no) does the input prompt have few-shot examples
- Representative: (1-5) if present, how representative are the examples?
- Complexity: (1-5) how complex is the input prompt?
- Task: (1-5) how complex is the implied task?
- Necessity: ()
- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)
- Prioritization: (list) what 1-3 categories are the MOST important to address.
- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed
</reasoning>
## Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.
- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- It is very important that any examples included reflect the short, conversational output responses of the model.
Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.
- By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.
- Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
## Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
## Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]
""".strip()
def generate_prompt(task_or_prompt: str):
completion = client.chat.completions.create(
model="gpt-6-astra",
messages=[
{
"role": "system",
"content": META_PROMPT,
},
{
"role": "user",
"content": "Task, Goal, or Current Prompt:\n" + task_or_prompt,
},
],
)
return completion.choices[0].message.content
编辑提示词(来源示例21,go)
// [中文] 用编辑版元提示审查并改写原提示,要求先输出约定的reasoning小节。
// [中文] 这些程序返回原生成文本;应用若只需最终提示,还须实现分析小节的解析和移除。
import (
"context"
"fmt"
"log"
"github.com/openai/openai-go/v3"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
client := openai.NewClient()
metaPrompt := "Given a current prompt and a change description, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.\n" +
"\n" +
"Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:\n" +
"<reasoning>\n" +
"- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)\n" +
"- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?\n" +
" - Identify: (max 10 words) if so, which section(s) utilize reasoning?\n" +
" - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?\n" +
" - Ordering: (before/after) is the chain of though located before or after\n" +
"- Structure: (yes/no) does the input prompt have a well defined structure\n" +
"- Examples: (yes/no) does the input prompt have few-shot examples\n" +
" - Representative: (1-5) if present, how representative are the examples?\n" +
"- Complexity: (1-5) how complex is the input prompt?\n" +
" - Task: (1-5) how complex is the implied task?\n" +
" - Necessity: ()\n" +
"- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)\n" +
"- Prioritization: (list) what 1-3 categories are the MOST important to address.\n" +
"- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed\n" +
"</reasoning>\n" +
"\n" +
"# Guidelines\n" +
"\n" +
"- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.\n" +
"- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.\n" +
"- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.\n" +
"- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.\n" +
"- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.\n" +
" - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.\n" +
" - It is very important that any examples included reflect the short, conversational output responses of the model.\n" +
"Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.\n" +
" - By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for \"short\" responses, then the examples should truly have 1-10 word responses max.\n" +
" - Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.\n" +
"- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.\n" +
"- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.\n" +
"- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.\n" +
"\n" +
"The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no \"---\")\n" +
"\n" +
"[Concise instruction describing the task - this should be the first line in the prompt, no section header]\n" +
"\n" +
"[Additional details as needed.]\n" +
"\n" +
"[Optional sections with headings or bullet points for detailed steps.]\n" +
"\n" +
"# Examples [optional]\n" +
"\n" +
"[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]\n" +
"[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]\n" +
"\n" +
"# Notes [optional]\n" +
"\n" +
"[optional: edge cases, details, and an area to call or repeat out specific important considerations]\n" +
"[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]\n"
completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
Model: "gpt-6-astra",
Messages: []openai.ChatCompletionMessageParamUnion{
openai.SystemMessage(metaPrompt), openai.UserMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue."),
}})
if err != nil {
return err
}
fmt.Println(completion.Choices[0].Message.Content)
return nil
}
编辑提示词(来源示例22,java)
// [中文] 用编辑版元提示审查并改写原提示,要求先输出约定的reasoning小节。
// [中文] 这些程序返回原生成文本;应用若只需最终提示,还须实现分析小节的解析和移除。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
String metaPrompt =
"""
Given a current prompt and a change description, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.
Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:
<reasoning>
- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)
- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?
- Identify: (max 10 words) if so, which section(s) utilize reasoning?
- Conclusion: (yes/no) is the chain of thought used to determine a conclusion?
- Ordering: (before/after) is the chain of though located before or after
- Structure: (yes/no) does the input prompt have a well defined structure
- Examples: (yes/no) does the input prompt have few-shot examples
- Representative: (1-5) if present, how representative are the examples?
- Complexity: (1-5) how complex is the input prompt?
- Task: (1-5) how complex is the implied task?
- Necessity: ()
- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)
- Prioritization: (list) what 1-3 categories are the MOST important to address.
- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed
</reasoning>
# Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.
- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- It is very important that any examples included reflect the short, conversational output responses of the model.
Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.
- By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.
- Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
# Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
# Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]
"""
.strip();
ChatCompletionCreateParams params =
ChatCompletionCreateParams.builder()
.model("gpt-6-astra")
.addSystemMessage(metaPrompt)
.addUserMessage(
"Task, Goal, or Current Prompt:\nMake this voice assistant prompt warmer and more direct.")
.build();
client.chat().completions().create(params).choices().stream()
.flatMap(choice -> choice.message().content().stream())
.forEach(System.out::println);
编辑提示词(来源示例23,csharp)
// [中文] 用编辑版元提示审查并改写原提示,要求先输出约定的reasoning小节。
// [中文] 这些程序返回原生成文本;应用若只需最终提示,还须实现分析小节的解析和移除。
using OpenAI.Chat;
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-6-astra";
ChatClient client = new(model, key);
string metaPrompt = """"
Given a current prompt and a change description, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.
Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:
<reasoning>
- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)
- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?
- Identify: (max 10 words) if so, which section(s) utilize reasoning?
- Conclusion: (yes/no) is the chain of thought used to determine a conclusion?
- Ordering: (before/after) is the chain of though located before or after
- Structure: (yes/no) does the input prompt have a well defined structure
- Examples: (yes/no) does the input prompt have few-shot examples
- Representative: (1-5) if present, how representative are the examples?
- Complexity: (1-5) how complex is the input prompt?
- Task: (1-5) how complex is the implied task?
- Necessity: ()
- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)
- Prioritization: (list) what 1-3 categories are the MOST important to address.
- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed
</reasoning>
# Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.
- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- It is very important that any examples included reflect the short, conversational output responses of the model.
Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.
- By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.
- Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
# Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
# Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]
"""";
ChatCompletionOptions options = new();
ChatCompletion result = await client.CompleteChatAsync([new SystemChatMessage(metaPrompt), new UserChatMessage("Task, Goal, or Current Prompt: Help a customer resolve a billing issue.")], options);
Console.WriteLine(result.Content[0].Text);
编辑提示词(来源示例24,ruby)
## [中文] 用编辑版元提示审查并改写原提示,要求先输出约定的reasoning小节。
## [中文] 这些程序返回原生成文本;应用若只需最终提示,还须实现分析小节的解析和移除。
require "openai"
client = OpenAI::Client.new
meta_prompt = <<~PROMPT
Given a current prompt and a change description, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.
Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:
<reasoning>
- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)
- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?
- Identify: (max 10 words) if so, which section(s) utilize reasoning?
- Conclusion: (yes/no) is the chain of thought used to determine a conclusion?
- Ordering: (before/after) is the chain of though located before or after
- Structure: (yes/no) does the input prompt have a well defined structure
- Examples: (yes/no) does the input prompt have few-shot examples
- Representative: (1-5) if present, how representative are the examples?
- Complexity: (1-5) how complex is the input prompt?
- Task: (1-5) how complex is the implied task?
- Necessity: ()
- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)
- Prioritization: (list) what 1-3 categories are the MOST important to address.
- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed
</reasoning>
# Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.
- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- It is very important that any examples included reflect the short, conversational output responses of the model.
Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.
- By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.
- Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
# Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
# Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]
PROMPT
def generate_prompt(client, meta_prompt, task_or_prompt)
completion = client.chat.completions.create(
model: "gpt-6-astra",
messages: [
{
role: :system,
content: meta_prompt
},
{
role: :user,
content: "Task, Goal, or Current Prompt:\n#{task_or_prompt}"
}
]
)
completion.choices.fetch(0).message.content
end
puts(generate_prompt(client, meta_prompt, "Make this voice assistant prompt warmer and more direct."))
<a id="schemas"></a>
Schema
结构化输出Schema与函数Schema本身也是JSON对象,因此可用结构化输出生成它们。要先定义描述输出Schema的Schema,也就是自描述的元Schema。函数的parameters本身也是Schema,因此可用相同元Schema生成函数。
<a id="defining-a-constrained-meta-schema"></a>
定义受约束元Schema
结构化输出有strict=true与strict=false两种模式,同一模型都受训遵循Schema,但只有严格模式以受约束采样保证符合。目标是用严格模式生成供严格模式使用的Schema;然而JSON Schema官方元Schema依赖严格模式不支持的特性:输入Schema不能用这些特性描述输出,生成的输出Schema也不能包含它们。
生成新键需要输入元Schema使用additionalProperties,因此目前不能直接在严格模式生成这些Schema,但仍希望结果符合严格模式约束。解决办法是伪元Schema:元Schema定义本身使用严格模式不支持的特性,只描述严格模式支持的结构。即定义阶段跳出严格模式,生成结果仍约束为可用于严格模式的Schema。
构造这种元Schema并不容易。原文描述先让JSON模式的o1-preview和gpt-4o结合文档理解目标,迭代出初版;再用gpt-4o结构化输出、初版Schema、任务与文档生成更好候选,逐次以改进版生成下一版,最后人工仔细审查,清理输出后用Schema与函数评测集验证。这是来源的方法经历,不作为本教程作者亲历。
<a id="output-cleaning"></a>
清理输出
生成过程不能用严格模式,因此完成后验证、转换:全部对象设additionalProperties:false;所有属性列为required;结构化输出Schema包进json_schema对象;函数包进function对象。Realtime函数对象与Chat Completions略有不同,但共用Schema。
<a id="meta-schemas"></a>
元Schema
每个元Schema配有含少样本的提示词,结合结构化输出的可靠性,即使非严格模式也能生成Schema。
结构化输出元Schema的任务提示中文释义:返回所描述JSON的有效Schema;对象所有字段必须required(原文重复强调);所有对象设additionalProperties:false,因此通常自由扩展的attributes、metadata也应改成固定属性集;所有对象定义properties;字段顺序重要,思考/解释先于结论;$defs放在schema参数内。对象不支持unevaluatedProperties、propertyNames、minProperties、maxProperties;数组不支持unevaluatedItems、contains、minContains、maxContains、uniqueItems。支持定义和递归,只有需要引用时才加$defs等,并放在schema对象中。
程序完整保留三个少样本JSON。数学示例:生成含steps和final_answer的解题Schema;steps是解题步骤序列,每步explanation解释方法,output是该步结果,final_answer为最终答案。链表示例:linked_list是表头,$defs.linked_list_node定义单链表结点,value为存储数值,next指向下一结点,末结点为null。动态UI示例:type为组件类型(div、button、header、section、field、form),label为按钮/表单标签,children递归嵌套组件,attributes为任意元素的属性条目数组;name是属性名(如onClick、className),value是属性值。字段、引用、required与Schema完整结构见各语言代码,英文description按上述逐项理解。
元Schema自身的name.description译为“Schema的名称”。错误字符串“The model did not return a schema.”和“No schema returned”分别为“模型未返回Schema”和“未返回Schema”;“Schema generation refused:”为“Schema生成被拒绝:”。示例任务中的“Schedule a meeting with a title and start time.”译为“安排一个包含标题与开始时间的会议”,“Describe a calendar event.”译为“描述一个日历事件”;Description:表示“描述:”。数学和链表字段的完整说明分别是:“解答数学题所涉及的一系列步骤”“本步骤采用的推理或方法的描述”“本步骤的结果”“数学题的最终解或答案”“链表的头节点”“定义单链表中的节点”“此节点存储的值”“指向下一节点;若为末节点则为null”。UI各说明为:组件类型、用于按钮或表单字段的组件标签、嵌套组件、适用于任意元素的组件属性、属性名(如onClick或className)、属性值。
元Schema(来源示例25,javascript)
// [中文] 构造伪元Schema并加入数学、链表、递归UI少样本,描述待生成Schema的结构。
// [中文] 将任务描述拼入user消息,解析返回的JSON;用于严格输出前仍须验证并清理生成Schema。
import OpenAI from "openai";
const client = new OpenAI();
const metaSchema = {
name: "metaschema",
schema: {
type: "object",
properties: {
name: {
type: "string",
description: "The name of the schema",
},
type: {
type: "string",
enum: ["object", "array", "string", "number", "boolean", "null"],
},
properties: {
type: "object",
additionalProperties: {
$ref: "#/$defs/schema_definition",
},
},
items: {
anyOf: [
{
$ref: "#/$defs/schema_definition",
},
{
type: "array",
items: {
$ref: "#/$defs/schema_definition",
},
},
],
},
required: {
type: "array",
items: {
type: "string",
},
},
additionalProperties: {
type: "boolean",
},
},
required: ["type"],
additionalProperties: false,
if: {
properties: {
type: {
const: "object",
},
},
},
then: {
required: ["properties"],
},
$defs: {
schema_definition: {
type: "object",
properties: {
type: {
type: "string",
enum: ["object", "array", "string", "number", "boolean", "null"],
},
properties: {
type: "object",
additionalProperties: {
$ref: "#/$defs/schema_definition",
},
},
items: {
anyOf: [
{
$ref: "#/$defs/schema_definition",
},
{
type: "array",
items: {
$ref: "#/$defs/schema_definition",
},
},
],
},
required: {
type: "array",
items: {
type: "string",
},
},
additionalProperties: {
type: "boolean",
},
},
required: ["type"],
additionalProperties: false,
if: {
properties: {
type: {
const: "object",
},
},
},
then: {
required: ["properties"],
},
},
},
},
};
const metaPrompt = `# Instructions
Return a valid schema for the described JSON.
You must also make sure:
- all fields in an object are set as required
- I REPEAT, ALL FIELDS MUST BE MARKED AS REQUIRED
- all objects must have additionalProperties set to false
- because of this, some cases like "attributes" or "metadata" properties that would normally allow additional properties should instead have a fixed set of properties
- all objects must have properties defined
- field order matters. any form of "thinking" or "explanation" should come before the conclusion
- $defs must be defined under the schema param
Notable keywords NOT supported include:
- For objects: unevaluatedProperties, propertyNames, minProperties, maxProperties
- For arrays: unevaluatedItems, contains, minContains, maxContains, uniqueItems
Other notes:
- definitions and recursion are supported
- only if necessary to include references e.g. "$defs", it must be inside the "schema" object
## Examples
Input: Generate a math reasoning schema with steps and a final answer.
Output: {
"name": "math_reasoning",
"type": "object",
"properties": {
"steps": {
"type": "array",
"description": "A sequence of steps involved in solving the math problem.",
"items": {
"type": "object",
"properties": {
"explanation": {
"type": "string",
"description": "Description of the reasoning or method used in this step."
},
"output": {
"type": "string",
"description": "Result or outcome of this specific step."
}
},
"required": [
"explanation",
"output"
],
"additionalProperties": false
}
},
"final_answer": {
"type": "string",
"description": "The final solution or answer to the math problem."
}
},
"required": [
"steps",
"final_answer"
],
"additionalProperties": false
}
Input: Give me a linked list
Output: {
"name": "linked_list",
"type": "object",
"properties": {
"linked_list": {
"$ref": "#/$defs/linked_list_node",
"description": "The head node of the linked list."
}
},
"$defs": {
"linked_list_node": {
"type": "object",
"description": "Defines a node in a singly linked list.",
"properties": {
"value": {
"type": "number",
"description": "The value stored in this node."
},
"next": {
"anyOf": [
{
"$ref": "#/$defs/linked_list_node"
},
{
"type": "null"
}
],
"description": "Reference to the next node; null if it is the last node."
}
},
"required": [
"value",
"next"
],
"additionalProperties": false
}
},
"required": [
"linked_list"
],
"additionalProperties": false
}
Input: Dynamically generated UI
Output: {
"name": "ui",
"type": "object",
"properties": {
"type": {
"type": "string",
"description": "The type of the UI component",
"enum": [
"div",
"button",
"header",
"section",
"field",
"form"
]
},
"label": {
"type": "string",
"description": "The label of the UI component, used for buttons or form fields"
},
"children": {
"type": "array",
"description": "Nested UI components",
"items": {
"$ref": "#"
}
},
"attributes": {
"type": "array",
"description": "Arbitrary attributes for the UI component, suitable for any element",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name of the attribute, for example onClick or className"
},
"value": {
"type": "string",
"description": "The value of the attribute"
}
},
"required": [
"name",
"value"
],
"additionalProperties": false
}
}
},
"required": [
"type",
"label",
"children",
"attributes"
],
"additionalProperties": false
}`;
async function generateSchema(description) {
const completion = await client.chat.completions.create({
model: "gpt-5.6-terra",
response_format: { type: "json_schema", json_schema: metaSchema },
messages: [
{ role: "system", content: metaPrompt },
{ role: "user", content: "Description:\n" + description },
],
});
const content = completion.choices[0].message.content;
if (!content) throw new Error("The model did not return a schema.");
return JSON.parse(content);
}
console.log(
JSON.stringify(await generateSchema("Describe a calendar event."), null, 2)
);
元Schema(来源示例26,python)
## [中文] 构造伪元Schema并加入数学、链表、递归UI少样本,描述待生成Schema的结构。
## [中文] 将任务描述拼入user消息,解析返回的JSON;用于严格输出前仍须验证并清理生成Schema。
from openai import OpenAI
import json
client = OpenAI()
META_SCHEMA = {
"name": "metaschema",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string", "description": "The name of the schema"},
"type": {
"type": "string",
"enum": ["object", "array", "string", "number", "boolean", "null"],
},
"properties": {
"type": "object",
"additionalProperties": {"$ref": "#/$defs/schema_definition"},
},
"items": {
"anyOf": [
{"$ref": "#/$defs/schema_definition"},
{"type": "array", "items": {"$ref": "#/$defs/schema_definition"}},
]
},
"required": {"type": "array", "items": {"type": "string"}},
"additionalProperties": {"type": "boolean"},
},
"required": ["type"],
"additionalProperties": False,
"if": {"properties": {"type": {"const": "object"}}},
"then": {"required": ["properties"]},
"$defs": {
"schema_definition": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [
"object",
"array",
"string",
"number",
"boolean",
"null",
],
},
"properties": {
"type": "object",
"additionalProperties": {"$ref": "#/$defs/schema_definition"},
},
"items": {
"anyOf": [
{"$ref": "#/$defs/schema_definition"},
{
"type": "array",
"items": {"$ref": "#/$defs/schema_definition"},
},
]
},
"required": {"type": "array", "items": {"type": "string"}},
"additionalProperties": {"type": "boolean"},
},
"required": ["type"],
"additionalProperties": False,
"if": {"properties": {"type": {"const": "object"}}},
"then": {"required": ["properties"]},
}
},
},
}
META_PROMPT = """
## Instructions
Return a valid schema for the described JSON.
You must also make sure:
- all fields in an object are set as required
- I REPEAT, ALL FIELDS MUST BE MARKED AS REQUIRED
- all objects must have additionalProperties set to false
- because of this, some cases like "attributes" or "metadata" properties that would normally allow additional properties should instead have a fixed set of properties
- all objects must have properties defined
- field order matters. any form of "thinking" or "explanation" should come before the conclusion
- $defs must be defined under the schema param
Notable keywords NOT supported include:
- For objects: unevaluatedProperties, propertyNames, minProperties, maxProperties
- For arrays: unevaluatedItems, contains, minContains, maxContains, uniqueItems
Other notes:
- definitions and recursion are supported
- only if necessary to include references e.g. "$defs", it must be inside the "schema" object
## Examples
Input: Generate a math reasoning schema with steps and a final answer.
Output: {
"name": "math_reasoning",
"type": "object",
"properties": {
"steps": {
"type": "array",
"description": "A sequence of steps involved in solving the math problem.",
"items": {
"type": "object",
"properties": {
"explanation": {
"type": "string",
"description": "Description of the reasoning or method used in this step."
},
"output": {
"type": "string",
"description": "Result or outcome of this specific step."
}
},
"required": [
"explanation",
"output"
],
"additionalProperties": false
}
},
"final_answer": {
"type": "string",
"description": "The final solution or answer to the math problem."
}
},
"required": [
"steps",
"final_answer"
],
"additionalProperties": false
}
Input: Give me a linked list
Output: {
"name": "linked_list",
"type": "object",
"properties": {
"linked_list": {
"$ref": "#/$defs/linked_list_node",
"description": "The head node of the linked list."
}
},
"$defs": {
"linked_list_node": {
"type": "object",
"description": "Defines a node in a singly linked list.",
"properties": {
"value": {
"type": "number",
"description": "The value stored in this node."
},
"next": {
"anyOf": [
{
"$ref": "#/$defs/linked_list_node"
},
{
"type": "null"
}
],
"description": "Reference to the next node; null if it is the last node."
}
},
"required": [
"value",
"next"
],
"additionalProperties": false
}
},
"required": [
"linked_list"
],
"additionalProperties": false
}
Input: Dynamically generated UI
Output: {
"name": "ui",
"type": "object",
"properties": {
"type": {
"type": "string",
"description": "The type of the UI component",
"enum": [
"div",
"button",
"header",
"section",
"field",
"form"
]
},
"label": {
"type": "string",
"description": "The label of the UI component, used for buttons or form fields"
},
"children": {
"type": "array",
"description": "Nested UI components",
"items": {
"$ref": "#"
}
},
"attributes": {
"type": "array",
"description": "Arbitrary attributes for the UI component, suitable for any element",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name of the attribute, for example onClick or className"
},
"value": {
"type": "string",
"description": "The value of the attribute"
}
},
"required": [
"name",
"value"
],
"additionalProperties": false
}
}
},
"required": [
"type",
"label",
"children",
"attributes"
],
"additionalProperties": false
}
""".strip()
def generate_schema(description: str):
completion = client.chat.completions.create(
model="gpt-5.6-terra",
response_format={"type": "json_schema", "json_schema": META_SCHEMA},
messages=[
{
"role": "system",
"content": META_PROMPT,
},
{
"role": "user",
"content": "Description:\n" + description,
},
],
)
return json.loads(completion.choices[0].message.content)
元Schema(来源示例27,go)
// [中文] 构造伪元Schema并加入数学、链表、递归UI少样本,描述待生成Schema的结构。
// [中文] 将任务描述拼入user消息,解析返回的JSON;用于严格输出前仍须验证并清理生成Schema。
import (
"context"
"encoding/json"
"fmt"
"log"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/shared"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
client := openai.NewClient()
metaPrompt := "# Instructions\n" +
"Return a valid schema for the described JSON.\n" +
"\n" +
"You must also make sure:\n" +
"- all fields in an object are set as required\n" +
"- I REPEAT, ALL FIELDS MUST BE MARKED AS REQUIRED\n" +
"- all objects must have additionalProperties set to false\n" +
" - because of this, some cases like \"attributes\" or \"metadata\" properties that would normally allow additional properties should instead have a fixed set of properties\n" +
"- all objects must have properties defined\n" +
"- field order matters. any form of \"thinking\" or \"explanation\" should come before the conclusion\n" +
"- $defs must be defined under the schema param\n" +
"\n" +
"Notable keywords NOT supported include:\n" +
"- For objects: unevaluatedProperties, propertyNames, minProperties, maxProperties\n" +
"- For arrays: unevaluatedItems, contains, minContains, maxContains, uniqueItems\n" +
"\n" +
"Other notes:\n" +
"- definitions and recursion are supported\n" +
"- only if necessary to include references e.g. \"$defs\", it must be inside the \"schema\" object\n" +
"\n" +
"# Examples\n" +
"Input: Generate a math reasoning schema with steps and a final answer.\n" +
"Output: {\n" +
" \"name\": \"math_reasoning\",\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"steps\": {\n" +
" \"type\": \"array\",\n" +
" \"description\": \"A sequence of steps involved in solving the math problem.\",\n" +
" \"items\": {\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"explanation\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"Description of the reasoning or method used in this step.\"\n" +
" },\n" +
" \"output\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"Result or outcome of this specific step.\"\n" +
" }\n" +
" },\n" +
" \"required\": [\n" +
" \"explanation\",\n" +
" \"output\"\n" +
" ],\n" +
" \"additionalProperties\": false\n" +
" }\n" +
" },\n" +
" \"final_answer\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The final solution or answer to the math problem.\"\n" +
" }\n" +
" },\n" +
" \"required\": [\n" +
" \"steps\",\n" +
" \"final_answer\"\n" +
" ],\n" +
" \"additionalProperties\": false\n" +
"}\n" +
"\n" +
"Input: Give me a linked list\n" +
"Output: {\n" +
" \"name\": \"linked_list\",\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"linked_list\": {\n" +
" \"$ref\": \"#/$defs/linked_list_node\",\n" +
" \"description\": \"The head node of the linked list.\"\n" +
" }\n" +
" },\n" +
" \"$defs\": {\n" +
" \"linked_list_node\": {\n" +
" \"type\": \"object\",\n" +
" \"description\": \"Defines a node in a singly linked list.\",\n" +
" \"properties\": {\n" +
" \"value\": {\n" +
" \"type\": \"number\",\n" +
" \"description\": \"The value stored in this node.\"\n" +
" },\n" +
" \"next\": {\n" +
" \"anyOf\": [\n" +
" {\n" +
" \"$ref\": \"#/$defs/linked_list_node\"\n" +
" },\n" +
" {\n" +
" \"type\": \"null\"\n" +
" }\n" +
" ],\n" +
" \"description\": \"Reference to the next node; null if it is the last node.\"\n" +
" }\n" +
" },\n" +
" \"required\": [\n" +
" \"value\",\n" +
" \"next\"\n" +
" ],\n" +
" \"additionalProperties\": false\n" +
" }\n" +
" },\n" +
" \"required\": [\n" +
" \"linked_list\"\n" +
" ],\n" +
" \"additionalProperties\": false\n" +
"}\n" +
"\n" +
"Input: Dynamically generated UI\n" +
"Output: {\n" +
" \"name\": \"ui\",\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The type of the UI component\",\n" +
" \"enum\": [\n" +
" \"div\",\n" +
" \"button\",\n" +
" \"header\",\n" +
" \"section\",\n" +
" \"field\",\n" +
" \"form\"\n" +
" ]\n" +
" },\n" +
" \"label\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The label of the UI component, used for buttons or form fields\"\n" +
" },\n" +
" \"children\": {\n" +
" \"type\": \"array\",\n" +
" \"description\": \"Nested UI components\",\n" +
" \"items\": {\n" +
" \"$ref\": \"#\"\n" +
" }\n" +
" },\n" +
" \"attributes\": {\n" +
" \"type\": \"array\",\n" +
" \"description\": \"Arbitrary attributes for the UI component, suitable for any element\",\n" +
" \"items\": {\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"name\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The name of the attribute, for example onClick or className\"\n" +
" },\n" +
" \"value\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The value of the attribute\"\n" +
" }\n" +
" },\n" +
" \"required\": [\n" +
" \"name\",\n" +
" \"value\"\n" +
" ],\n" +
" \"additionalProperties\": false\n" +
" }\n" +
" }\n" +
" },\n" +
" \"required\": [\n" +
" \"type\",\n" +
" \"label\",\n" +
" \"children\",\n" +
" \"attributes\"\n" +
" ],\n" +
" \"additionalProperties\": false\n" +
"}\n"
var schema map[string]any
if err := json.Unmarshal([]byte(`{
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name of the schema"
},
"type": {
"type": "string",
"enum": [
"object",
"array",
"string",
"number",
"boolean",
"null"
]
},
"properties": {
"type": "object",
"additionalProperties": {
"$ref": "#/$defs/schema_definition"
}
},
"items": {
"anyOf": [
{
"$ref": "#/$defs/schema_definition"
},
{
"type": "array",
"items": {
"$ref": "#/$defs/schema_definition"
}
}
]
},
"required": {
"type": "array",
"items": {
"type": "string"
}
},
"additionalProperties": {
"type": "boolean"
}
},
"required": [
"type"
],
"additionalProperties": false,
"if": {
"properties": {
"type": {
"const": "object"
}
}
},
"then": {
"required": [
"properties"
]
},
"$defs": {
"schema_definition": {
"type": "object",
"properties": {
"description": {
"type": "string"
},
"type": {
"type": "string",
"enum": [
"object",
"array",
"string",
"number",
"boolean",
"null"
]
},
"properties": {
"type": "object",
"additionalProperties": {
"$ref": "#/$defs/schema_definition"
}
},
"items": {
"anyOf": [
{
"$ref": "#/$defs/schema_definition"
},
{
"type": "array",
"items": {
"$ref": "#/$defs/schema_definition"
}
}
]
},
"required": {
"type": "array",
"items": {
"type": "string"
}
},
"additionalProperties": {
"type": "boolean"
}
},
"required": [
"type"
],
"additionalProperties": false,
"if": {
"properties": {
"type": {
"const": "object"
}
}
},
"then": {
"required": [
"properties"
]
}
}
}
}`), &schema); err != nil {
return err
}
completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
Model: "gpt-5.6-terra",
Messages: []openai.ChatCompletionMessageParamUnion{
openai.SystemMessage(metaPrompt), openai.UserMessage("Description: Schedule a meeting with a title and start time."),
}, ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{OfJSONSchema: &shared.ResponseFormatJSONSchemaParam{JSONSchema: shared.ResponseFormatJSONSchemaJSONSchemaParam{Name: "metaschema", Schema: schema}}}})
if err != nil {
return err
}
var result any
if err := json.Unmarshal([]byte(completion.Choices[0].Message.Content), &result); err != nil {
return err
}
encoded, err := json.MarshalIndent(result, "", " ")
if err != nil {
return err
}
fmt.Println(string(encoded))
return nil
}
元Schema(来源示例28,java)
// [中文] 构造伪元Schema并加入数学、链表、递归UI少样本,描述待生成Schema的结构。
// [中文] 将任务描述拼入user消息,解析返回的JSON;用于严格输出前仍须验证并清理生成Schema。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import java.util.List;
import java.util.Map;
String metaPrompt =
"""
# Instructions
Return a valid schema for the described JSON.
You must also make sure:
- all fields in an object are set as required
- I REPEAT, ALL FIELDS MUST BE MARKED AS REQUIRED
- all objects must have additionalProperties set to false
- because of this, some cases like "attributes" or "metadata" properties that would normally allow additional properties should instead have a fixed set of properties
- all objects must have properties defined
- field order matters. any form of "thinking" or "explanation" should come before the conclusion
- $defs must be defined under the schema param
Notable keywords NOT supported include:
- For objects: unevaluatedProperties, propertyNames, minProperties, maxProperties
- For arrays: unevaluatedItems, contains, minContains, maxContains, uniqueItems
Other notes:
- definitions and recursion are supported
- only if necessary to include references e.g. "$defs", it must be inside the "schema" object
# Examples
Input: Generate a math reasoning schema with steps and a final answer.
Output: {
"name": "math_reasoning",
"type": "object",
"properties": {
"steps": {
"type": "array",
"description": "A sequence of steps involved in solving the math problem.",
"items": {
"type": "object",
"properties": {
"explanation": {
"type": "string",
"description": "Description of the reasoning or method used in this step."
},
"output": {
"type": "string",
"description": "Result or outcome of this specific step."
}
},
"required": [
"explanation",
"output"
],
"additionalProperties": false
}
},
"final_answer": {
"type": "string",
"description": "The final solution or answer to the math problem."
}
},
"required": [
"steps",
"final_answer"
],
"additionalProperties": false
}
Input: Give me a linked list
Output: {
"name": "linked_list",
"type": "object",
"properties": {
"linked_list": {
"$ref": "#/$defs/linked_list_node",
"description": "The head node of the linked list."
}
},
"$defs": {
"linked_list_node": {
"type": "object",
"description": "Defines a node in a singly linked list.",
"properties": {
"value": {
"type": "number",
"description": "The value stored in this node."
},
"next": {
"anyOf": [
{
"$ref": "#/$defs/linked_list_node"
},
{
"type": "null"
}
],
"description": "Reference to the next node; null if it is the last node."
}
},
"required": [
"value",
"next"
],
"additionalProperties": false
}
},
"required": [
"linked_list"
],
"additionalProperties": false
}
Input: Dynamically generated UI
Output: {
"name": "ui",
"type": "object",
"properties": {
"type": {
"type": "string",
"description": "The type of the UI component",
"enum": [
"div",
"button",
"header",
"section",
"field",
"form"
]
},
"label": {
"type": "string",
"description": "The label of the UI component, used for buttons or form fields"
},
"children": {
"type": "array",
"description": "Nested UI components",
"items": {
"$ref": "#"
}
},
"attributes": {
"type": "array",
"description": "Arbitrary attributes for the UI component, suitable for any element",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name of the attribute, for example onClick or className"
},
"value": {
"type": "string",
"description": "The value of the attribute"
}
},
"required": [
"name",
"value"
],
"additionalProperties": false
}
}
},
"required": [
"type",
"label",
"children",
"attributes"
],
"additionalProperties": false
}
"""
.strip();
Map<String, Object> metaSchema =
Map.ofEntries(
Map.entry("name", "metaschema"),
Map.entry(
"schema",
Map.ofEntries(
Map.entry("type", "object"),
Map.entry(
"properties",
Map.ofEntries(
Map.entry(
"name",
Map.ofEntries(
Map.entry("type", "string"),
Map.entry("description", "The name of the schema"))),
Map.entry(
"type",
Map.ofEntries(
Map.entry("type", "string"),
Map.entry(
"enum",
List.of(
"object", "array", "string", "number", "boolean",
"null")))),
Map.entry(
"properties",
Map.ofEntries(
Map.entry("type", "object"),
Map.entry(
"additionalProperties",
Map.ofEntries(
Map.entry("$ref", "#/$defs/schema_definition"))))),
Map.entry(
"items",
Map.ofEntries(
Map.entry(
"anyOf",
List.of(
Map.ofEntries(
Map.entry("$ref", "#/$defs/schema_definition")),
Map.ofEntries(
Map.entry("type", "array"),
Map.entry(
"items",
Map.ofEntries(
Map.entry(
"$ref",
"#/$defs/schema_definition")))))))),
Map.entry(
"required",
Map.ofEntries(
Map.entry("type", "array"),
Map.entry(
"items", Map.ofEntries(Map.entry("type", "string"))))),
Map.entry(
"additionalProperties",
Map.ofEntries(Map.entry("type", "boolean"))))),
Map.entry("required", List.of("type")),
Map.entry("additionalProperties", false),
Map.entry(
"if",
Map.ofEntries(
Map.entry(
"properties",
Map.ofEntries(
Map.entry(
"type", Map.ofEntries(Map.entry("const", "object"))))))),
Map.entry("then", Map.ofEntries(Map.entry("required", List.of("properties")))),
Map.entry(
"$defs",
Map.ofEntries(
Map.entry(
"schema_definition",
Map.ofEntries(
Map.entry("type", "object"),
Map.entry(
"properties",
Map.ofEntries(
Map.entry(
"type",
Map.ofEntries(
Map.entry("type", "string"),
Map.entry(
"enum",
List.of(
"object", "array", "string", "number",
"boolean", "null")))),
Map.entry(
"properties",
Map.ofEntries(
Map.entry("type", "object"),
Map.entry(
"additionalProperties",
Map.ofEntries(
Map.entry(
"$ref",
"#/$defs/schema_definition"))))),
Map.entry(
"items",
Map.ofEntries(
Map.entry(
"anyOf",
List.of(
Map.ofEntries(
Map.entry(
"$ref",
"#/$defs/schema_definition")),
Map.ofEntries(
Map.entry("type", "array"),
Map.entry(
"items",
Map.ofEntries(
Map.entry(
"$ref",
"#/$defs/schema_definition")))))))),
Map.entry(
"required",
Map.ofEntries(
Map.entry("type", "array"),
Map.entry(
"items",
Map.ofEntries(
Map.entry("type", "string"))))),
Map.entry(
"additionalProperties",
Map.ofEntries(Map.entry("type", "boolean"))))),
Map.entry("required", List.of("type")),
Map.entry("additionalProperties", false),
Map.entry(
"if",
Map.ofEntries(
Map.entry(
"properties",
Map.ofEntries(
Map.entry(
"type",
Map.ofEntries(
Map.entry("const", "object"))))))),
Map.entry(
"then",
Map.ofEntries(
Map.entry("required", List.of("properties")))))))))));
ChatCompletionCreateParams params =
ChatCompletionCreateParams.builder()
.model("gpt-5.6-terra")
.addSystemMessage(metaPrompt)
.addUserMessage("Description:\nDescribe a calendar event.")
.putAdditionalBodyProperty(
"response_format",
JsonValue.from(Map.of("type", "json_schema", "json_schema", metaSchema)))
.build();
client.chat().completions().create(params).choices().stream()
.flatMap(choice -> choice.message().content().stream())
.forEach(System.out::println);
元Schema(来源示例29,csharp)
// [中文] 构造伪元Schema并加入数学、链表、递归UI少样本,描述待生成Schema的结构。
// [中文] 将任务描述拼入user消息,解析返回的JSON;用于严格输出前仍须验证并清理生成Schema。
using System.Text.Json;
using OpenAI.Chat;
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-5.6-terra";
ChatClient client = new(model, key);
string metaPrompt = """"
# Instructions
Return a valid schema for the described JSON.
You must also make sure:
- all fields in an object are set as required
- I REPEAT, ALL FIELDS MUST BE MARKED AS REQUIRED
- all objects must have additionalProperties set to false
- because of this, some cases like "attributes" or "metadata" properties that would normally allow additional properties should instead have a fixed set of properties
- all objects must have properties defined
- field order matters. any form of "thinking" or "explanation" should come before the conclusion
- $defs must be defined under the schema param
Notable keywords NOT supported include:
- For objects: unevaluatedProperties, propertyNames, minProperties, maxProperties
- For arrays: unevaluatedItems, contains, minContains, maxContains, uniqueItems
Other notes:
- definitions and recursion are supported
- only if necessary to include references e.g. "$defs", it must be inside the "schema" object
# Examples
Input: Generate a math reasoning schema with steps and a final answer.
Output: {
"name": "math_reasoning",
"type": "object",
"properties": {
"steps": {
"type": "array",
"description": "A sequence of steps involved in solving the math problem.",
"items": {
"type": "object",
"properties": {
"explanation": {
"type": "string",
"description": "Description of the reasoning or method used in this step."
},
"output": {
"type": "string",
"description": "Result or outcome of this specific step."
}
},
"required": [
"explanation",
"output"
],
"additionalProperties": false
}
},
"final_answer": {
"type": "string",
"description": "The final solution or answer to the math problem."
}
},
"required": [
"steps",
"final_answer"
],
"additionalProperties": false
}
Input: Give me a linked list
Output: {
"name": "linked_list",
"type": "object",
"properties": {
"linked_list": {
"$ref": "#/$defs/linked_list_node",
"description": "The head node of the linked list."
}
},
"$defs": {
"linked_list_node": {
"type": "object",
"description": "Defines a node in a singly linked list.",
"properties": {
"value": {
"type": "number",
"description": "The value stored in this node."
},
"next": {
"anyOf": [
{
"$ref": "#/$defs/linked_list_node"
},
{
"type": "null"
}
],
"description": "Reference to the next node; null if it is the last node."
}
},
"required": [
"value",
"next"
],
"additionalProperties": false
}
},
"required": [
"linked_list"
],
"additionalProperties": false
}
Input: Dynamically generated UI
Output: {
"name": "ui",
"type": "object",
"properties": {
"type": {
"type": "string",
"description": "The type of the UI component",
"enum": [
"div",
"button",
"header",
"section",
"field",
"form"
]
},
"label": {
"type": "string",
"description": "The label of the UI component, used for buttons or form fields"
},
"children": {
"type": "array",
"description": "Nested UI components",
"items": {
"$ref": "#"
}
},
"attributes": {
"type": "array",
"description": "Arbitrary attributes for the UI component, suitable for any element",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name of the attribute, for example onClick or className"
},
"value": {
"type": "string",
"description": "The value of the attribute"
}
},
"required": [
"name",
"value"
],
"additionalProperties": false
}
}
},
"required": [
"type",
"label",
"children",
"attributes"
],
"additionalProperties": false
}
"""";
ChatCompletionOptions options = new();
options.ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat("metaschema", BinaryData.FromString("""
{
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name of the schema"
},
"type": {
"type": "string",
"enum": [
"object",
"array",
"string",
"number",
"boolean",
"null"
]
},
"properties": {
"type": "object",
"additionalProperties": {
"$ref": "#/$defs/schema_definition"
}
},
"items": {
"anyOf": [
{
"$ref": "#/$defs/schema_definition"
},
{
"type": "array",
"items": {
"$ref": "#/$defs/schema_definition"
}
}
]
},
"required": {
"type": "array",
"items": {
"type": "string"
}
},
"additionalProperties": {
"type": "boolean"
}
},
"required": [
"type"
],
"additionalProperties": false,
"if": {
"properties": {
"type": {
"const": "object"
}
}
},
"then": {
"required": [
"properties"
]
},
"$defs": {
"schema_definition": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [
"object",
"array",
"string",
"number",
"boolean",
"null"
]
},
"properties": {
"type": "object",
"additionalProperties": {
"$ref": "#/$defs/schema_definition"
}
},
"items": {
"anyOf": [
{
"$ref": "#/$defs/schema_definition"
},
{
"type": "array",
"items": {
"$ref": "#/$defs/schema_definition"
}
}
]
},
"required": {
"type": "array",
"items": {
"type": "string"
}
},
"additionalProperties": {
"type": "boolean"
}
},
"required": [
"type"
],
"additionalProperties": false,
"if": {
"properties": {
"type": {
"const": "object"
}
}
},
"then": {
"required": [
"properties"
]
}
}
}
}
"""));
ChatCompletion result = await client.CompleteChatAsync([new SystemChatMessage(metaPrompt), new UserChatMessage("Description: Schedule a meeting with a title and start time.")], options);
using JsonDocument parsed = JsonDocument.Parse(result.Content[0].Text);
Console.WriteLine(parsed.RootElement);
元Schema(来源示例30,ruby)
## [中文] 构造伪元Schema并加入数学、链表、递归UI少样本,描述待生成Schema的结构。
## [中文] 将任务描述拼入user消息,解析返回的JSON;用于严格输出前仍须验证并清理生成Schema。
require "openai"
require "json"
META_SCHEMA = {
"name" => "metaschema",
"schema" => {
"type" => "object",
"properties" => {
"name" => {
"type" => "string",
"description" => "The name of the schema"
},
"type" => {
"type" => "string",
"enum" => ["object", "array", "string", "number", "boolean", "null"]
},
"properties" => {
"type" => "object",
"additionalProperties" => {
"$ref" => "#/$defs/schema_definition"
}
},
"items" => {
"anyOf" => [
{
"$ref" => "#/$defs/schema_definition"
}, {
"type" => "array",
"items" => {
"$ref" => "#/$defs/schema_definition"
}
}
]
},
"required" => {
"type" => "array",
"items" => {
"type" => "string"
}
},
"additionalProperties" => {
"type" => "boolean"
}
},
"required" => ["type"],
"additionalProperties" => false,
"if" => {
"properties" => {
"type" => {
"const" => "object"
}
}
},
"then" => {
"required" => ["properties"]
},
"$defs" => {
"schema_definition" => {
"type" => "object",
"properties" => {
"type" => {
"type" => "string",
"enum" => ["object", "array", "string", "number", "boolean", "null"]
},
"properties" => {
"type" => "object",
"additionalProperties" => {
"$ref" => "#/$defs/schema_definition"
}
},
"items" => {
"anyOf" => [
{
"$ref" => "#/$defs/schema_definition"
}, {
"type" => "array",
"items" => {
"$ref" => "#/$defs/schema_definition"
}
}
]
},
"required" => {
"type" => "array",
"items" => {
"type" => "string"
}
},
"additionalProperties" => {
"type" => "boolean"
}
},
"required" => ["type"],
"additionalProperties" => false,
"if" => {
"properties" => {
"type" => {
"const" => "object"
}
}
},
"then" => {
"required" => ["properties"]
}
}
}
}
}
META_PROMPT = <<~PROMPT.strip
# Instructions
Return a valid schema for the described JSON.
You must also make sure:
- all fields in an object are set as required
- I REPEAT, ALL FIELDS MUST BE MARKED AS REQUIRED
- all objects must have additionalProperties set to false
- because of this, some cases like "attributes" or "metadata" properties that would normally allow additional properties should instead have a fixed set of properties
- all objects must have properties defined
- field order matters. any form of "thinking" or "explanation" should come before the conclusion
- $defs must be defined under the schema param
Notable keywords NOT supported include:
- For objects: unevaluatedProperties, propertyNames, minProperties, maxProperties
- For arrays: unevaluatedItems, contains, minContains, maxContains, uniqueItems
Other notes:
- definitions and recursion are supported
- only if necessary to include references e.g. "$defs", it must be inside the "schema" object
# Examples
Input: Generate a math reasoning schema with steps and a final answer.
Output: {
"name": "math_reasoning",
"type": "object",
"properties": {
"steps": {
"type": "array",
"description": "A sequence of steps involved in solving the math problem.",
"items": {
"type": "object",
"properties": {
"explanation": {
"type": "string",
"description": "Description of the reasoning or method used in this step."
},
"output": {
"type": "string",
"description": "Result or outcome of this specific step."
}
},
"required": [
"explanation",
"output"
],
"additionalProperties": false
}
},
"final_answer": {
"type": "string",
"description": "The final solution or answer to the math problem."
}
},
"required": [
"steps",
"final_answer"
],
"additionalProperties": false
}
Input: Give me a linked list
Output: {
"name": "linked_list",
"type": "object",
"properties": {
"linked_list": {
"$ref": "#/$defs/linked_list_node",
"description": "The head node of the linked list."
}
},
"$defs": {
"linked_list_node": {
"type": "object",
"description": "Defines a node in a singly linked list.",
"properties": {
"value": {
"type": "number",
"description": "The value stored in this node."
},
"next": {
"anyOf": [
{
"$ref": "#/$defs/linked_list_node"
},
{
"type": "null"
}
],
"description": "Reference to the next node; null if it is the last node."
}
},
"required": [
"value",
"next"
],
"additionalProperties": false
}
},
"required": [
"linked_list"
],
"additionalProperties": false
}
Input: Dynamically generated UI
Output: {
"name": "ui",
"type": "object",
"properties": {
"type": {
"type": "string",
"description": "The type of the UI component",
"enum": [
"div",
"button",
"header",
"section",
"field",
"form"
]
},
"label": {
"type": "string",
"description": "The label of the UI component, used for buttons or form fields"
},
"children": {
"type": "array",
"description": "Nested UI components",
"items": {
"$ref": "#"
}
},
"attributes": {
"type": "array",
"description": "Arbitrary attributes for the UI component, suitable for any element",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name of the attribute, for example onClick or className"
},
"value": {
"type": "string",
"description": "The value of the attribute"
}
},
"required": [
"name",
"value"
],
"additionalProperties": false
}
}
},
"required": [
"type",
"label",
"children",
"attributes"
],
"additionalProperties": false
}
PROMPT
client = OpenAI::Client.new
completion = client.chat.completions.create(
model: "gpt-5.6-terra",
response_format: {
type: :json_schema,
json_schema: META_SCHEMA
},
messages: [
{
role: :system,
content: META_PROMPT
},
{
role: :user,
content: "Description: Schedule a meeting with a title and start time."
}
]
)
message = completion.choices.fetch(0).message
raise "Schema generation refused: #{message.refusal}" if message.refusal
puts(JSON.pretty_generate(JSON.parse(message.content || raise("No schema returned"))))
函数元Schema的任务提示中文释义:为所描述函数返回有效Schema,特别确保required和type位于正确嵌套层级;required与properties同级,不能放进properties。每个属性无论多短,都必须正确包含type和description。
三个完整少样本的含义分别为:给神经网络超参数赋值,set_hyperparameters的epochs表示完整遍历数据集次数、learning_rate表示学习速度;机器人路径规划plan_motion包含起点、终点、障碍物坐标,x/y为对应位置或障碍物的坐标;技术指标计算technical_indicator包含股票代码ticker、待算指标indicators(RSI、MACD、Bollinger_Bands、Stochastic_Oscillator)及分析周期period。完整JSON及伪元Schema都保留在代码中。
函数元Schema本身的三处说明完整译为:“函数名称”“函数功能的说明”“定义函数参数的JSON Schema”。超参数示例两项description为“完整遍历数据集的次数”“模型学习的速度”;路径示例依次为终点X/Y坐标、障碍物坐标数组及每个障碍物X/Y坐标、起点X/Y坐标;技术指标示例为“待计算的技术指标列表”“技术指标”“分析的时间周期”“股票代码”。RSI为相对强弱指数,MACD为平滑异同移动平均指标,Bollinger_Bands为布林带,Stochastic_Oscillator为随机振荡指标,代码枚举不变。JavaScript示例任务“Create a function that checks the weather in a city.”完整译为“创建一个查询某城市天气的函数”;其他语言会议任务的中文同前组,不能将两者描述为同一任务。
元Schema(来源示例31,javascript)
// [中文] 元Schema描述函数名、说明和parameters;少样本示范超参数、机器人路径及技术指标。
// [中文] 提交待生成函数的描述并读取返回内容;解析JSON时仍需处理空内容或拒绝,required与properties必须同层。
import OpenAI from "openai";
const client = new OpenAI();
const metaSchema = {
name: "function-metaschema",
schema: {
type: "object",
properties: {
name: {
type: "string",
description: "The name of the function",
},
description: {
type: "string",
description: "A description of what the function does",
},
parameters: {
$ref: "#/$defs/schema_definition",
description: "A JSON schema that defines the function's parameters",
},
},
required: ["name", "description", "parameters"],
additionalProperties: false,
$defs: {
schema_definition: {
type: "object",
properties: {
type: {
type: "string",
enum: ["object", "array", "string", "number", "boolean", "null"],
},
properties: {
type: "object",
additionalProperties: {
$ref: "#/$defs/schema_definition",
},
},
items: {
anyOf: [
{
$ref: "#/$defs/schema_definition",
},
{
type: "array",
items: {
$ref: "#/$defs/schema_definition",
},
},
],
},
required: {
type: "array",
items: {
type: "string",
},
},
additionalProperties: {
type: "boolean",
},
},
required: ["type"],
additionalProperties: false,
if: {
properties: {
type: {
const: "object",
},
},
},
then: {
required: ["properties"],
},
},
},
},
};
const metaPrompt = `# Instructions
Return a valid schema for the described function.
Pay special attention to making sure that "required" and "type" are always at the correct level of nesting. For example, "required" should be at the same level as "properties", not inside it.
Make sure that every property, no matter how short, has a type and description correctly nested inside it.
## Examples
Input: Assign values to NN hyperparameters
Output: {
"name": "set_hyperparameters",
"description": "Assign values to NN hyperparameters",
"parameters": {
"type": "object",
"required": [
"learning_rate",
"epochs"
],
"properties": {
"epochs": {
"type": "number",
"description": "Number of complete passes through dataset"
},
"learning_rate": {
"type": "number",
"description": "Speed of model learning"
}
}
}
}
Input: Plans a motion path for the robot
Output: {
"name": "plan_motion",
"description": "Plans a motion path for the robot",
"parameters": {
"type": "object",
"required": [
"start_position",
"end_position"
],
"properties": {
"end_position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"description": "End X coordinate"
},
"y": {
"type": "number",
"description": "End Y coordinate"
}
}
},
"obstacles": {
"type": "array",
"description": "Array of obstacle coordinates",
"items": {
"type": "object",
"properties": {
"x": {
"type": "number",
"description": "Obstacle X coordinate"
},
"y": {
"type": "number",
"description": "Obstacle Y coordinate"
}
}
}
},
"start_position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"description": "Start X coordinate"
},
"y": {
"type": "number",
"description": "Start Y coordinate"
}
}
}
}
}
}
Input: Calculates various technical indicators
Output: {
"name": "technical_indicator",
"description": "Calculates various technical indicators",
"parameters": {
"type": "object",
"required": [
"ticker",
"indicators"
],
"properties": {
"indicators": {
"type": "array",
"description": "List of technical indicators to calculate",
"items": {
"type": "string",
"description": "Technical indicator",
"enum": [
"RSI",
"MACD",
"Bollinger_Bands",
"Stochastic_Oscillator"
]
}
},
"period": {
"type": "number",
"description": "Time period for the analysis"
},
"ticker": {
"type": "string",
"description": "Stock ticker symbol"
}
}
}
}`;
async function generateFunctionSchema(description) {
const completion = await client.chat.completions.create({
model: "gpt-5.6-terra",
response_format: { type: "json_schema", json_schema: metaSchema },
messages: [
{ role: "system", content: metaPrompt },
{ role: "user", content: "Description:\n" + description },
],
});
const content = completion.choices[0].message.content;
if (!content) throw new Error("The model did not return a schema.");
return JSON.parse(content);
}
console.log(
JSON.stringify(
await generateFunctionSchema(
"Create a function that checks the weather in a city."
),
null,
2
)
);
元Schema(来源示例32,python)
## [中文] 元Schema描述函数名、说明和parameters;少样本示范超参数、机器人路径及技术指标。
## [中文] 提交待生成函数的描述并读取返回内容;解析JSON时仍需处理空内容或拒绝,required与properties必须同层。
from openai import OpenAI
import json
client = OpenAI()
META_SCHEMA = {
"name": "function-metaschema",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string", "description": "The name of the function"},
"description": {
"type": "string",
"description": "A description of what the function does",
},
"parameters": {
"$ref": "#/$defs/schema_definition",
"description": "A JSON schema that defines the function's parameters",
},
},
"required": ["name", "description", "parameters"],
"additionalProperties": False,
"$defs": {
"schema_definition": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [
"object",
"array",
"string",
"number",
"boolean",
"null",
],
},
"properties": {
"type": "object",
"additionalProperties": {"$ref": "#/$defs/schema_definition"},
},
"items": {
"anyOf": [
{"$ref": "#/$defs/schema_definition"},
{
"type": "array",
"items": {"$ref": "#/$defs/schema_definition"},
},
]
},
"required": {"type": "array", "items": {"type": "string"}},
"additionalProperties": {"type": "boolean"},
},
"required": ["type"],
"additionalProperties": False,
"if": {"properties": {"type": {"const": "object"}}},
"then": {"required": ["properties"]},
}
},
},
}
META_PROMPT = """
## Instructions
Return a valid schema for the described function.
Pay special attention to making sure that "required" and "type" are always at the correct level of nesting. For example, "required" should be at the same level as "properties", not inside it.
Make sure that every property, no matter how short, has a type and description correctly nested inside it.
## Examples
Input: Assign values to NN hyperparameters
Output: {
"name": "set_hyperparameters",
"description": "Assign values to NN hyperparameters",
"parameters": {
"type": "object",
"required": [
"learning_rate",
"epochs"
],
"properties": {
"epochs": {
"type": "number",
"description": "Number of complete passes through dataset"
},
"learning_rate": {
"type": "number",
"description": "Speed of model learning"
}
}
}
}
Input: Plans a motion path for the robot
Output: {
"name": "plan_motion",
"description": "Plans a motion path for the robot",
"parameters": {
"type": "object",
"required": [
"start_position",
"end_position"
],
"properties": {
"end_position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"description": "End X coordinate"
},
"y": {
"type": "number",
"description": "End Y coordinate"
}
}
},
"obstacles": {
"type": "array",
"description": "Array of obstacle coordinates",
"items": {
"type": "object",
"properties": {
"x": {
"type": "number",
"description": "Obstacle X coordinate"
},
"y": {
"type": "number",
"description": "Obstacle Y coordinate"
}
}
}
},
"start_position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"description": "Start X coordinate"
},
"y": {
"type": "number",
"description": "Start Y coordinate"
}
}
}
}
}
}
Input: Calculates various technical indicators
Output: {
"name": "technical_indicator",
"description": "Calculates various technical indicators",
"parameters": {
"type": "object",
"required": [
"ticker",
"indicators"
],
"properties": {
"indicators": {
"type": "array",
"description": "List of technical indicators to calculate",
"items": {
"type": "string",
"description": "Technical indicator",
"enum": [
"RSI",
"MACD",
"Bollinger_Bands",
"Stochastic_Oscillator"
]
}
},
"period": {
"type": "number",
"description": "Time period for the analysis"
},
"ticker": {
"type": "string",
"description": "Stock ticker symbol"
}
}
}
}
""".strip()
def generate_function_schema(description: str):
completion = client.chat.completions.create(
model="gpt-5.6-terra",
response_format={"type": "json_schema", "json_schema": META_SCHEMA},
messages=[
{
"role": "system",
"content": META_PROMPT,
},
{
"role": "user",
"content": "Description:\n" + description,
},
],
)
return json.loads(completion.choices[0].message.content)
元Schema(来源示例33,go)
// [中文] 元Schema描述函数名、说明和parameters;少样本示范超参数、机器人路径及技术指标。
// [中文] 提交待生成函数的描述并读取返回内容;解析JSON时仍需处理空内容或拒绝,required与properties必须同层。
import (
"context"
"encoding/json"
"fmt"
"log"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/shared"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
client := openai.NewClient()
metaPrompt := "# Instructions\n" +
"Return a valid schema for the described function.\n" +
"\n" +
"Pay special attention to making sure that \"required\" and \"type\" are always at the correct level of nesting. For example, \"required\" should be at the same level as \"properties\", not inside it.\n" +
"Make sure that every property, no matter how short, has a type and description correctly nested inside it.\n" +
"\n" +
"# Examples\n" +
"Input: Assign values to NN hyperparameters\n" +
"Output: {\n" +
" \"name\": \"set_hyperparameters\",\n" +
" \"description\": \"Assign values to NN hyperparameters\",\n" +
" \"parameters\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"learning_rate\",\n" +
" \"epochs\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"epochs\": {\n" +
" \"type\": \"number\",\n" +
" \"description\": \"Number of complete passes through dataset\"\n" +
" },\n" +
" \"learning_rate\": {\n" +
" \"type\": \"number\",\n" +
" \"description\": \"Speed of model learning\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}\n" +
"\n" +
"Input: Plans a motion path for the robot\n" +
"Output: {\n" +
" \"name\": \"plan_motion\",\n" +
" \"description\": \"Plans a motion path for the robot\",\n" +
" \"parameters\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"start_position\",\n" +
" \"end_position\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"end_position\": {\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"x\": {\n" +
" \"type\": \"number\",\n" +
" \"description\": \"End X coordinate\"\n" +
" },\n" +
" \"y\": {\n" +
" \"type\": \"number\",\n" +
" \"description\": \"End Y coordinate\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"obstacles\": {\n" +
" \"type\": \"array\",\n" +
" \"description\": \"Array of obstacle coordinates\",\n" +
" \"items\": {\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"x\": {\n" +
" \"type\": \"number\",\n" +
" \"description\": \"Obstacle X coordinate\"\n" +
" },\n" +
" \"y\": {\n" +
" \"type\": \"number\",\n" +
" \"description\": \"Obstacle Y coordinate\"\n" +
" }\n" +
" }\n" +
" }\n" +
" },\n" +
" \"start_position\": {\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"x\": {\n" +
" \"type\": \"number\",\n" +
" \"description\": \"Start X coordinate\"\n" +
" },\n" +
" \"y\": {\n" +
" \"type\": \"number\",\n" +
" \"description\": \"Start Y coordinate\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}\n" +
"\n" +
"Input: Calculates various technical indicators\n" +
"Output: {\n" +
" \"name\": \"technical_indicator\",\n" +
" \"description\": \"Calculates various technical indicators\",\n" +
" \"parameters\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"ticker\",\n" +
" \"indicators\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"indicators\": {\n" +
" \"type\": \"array\",\n" +
" \"description\": \"List of technical indicators to calculate\",\n" +
" \"items\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"Technical indicator\",\n" +
" \"enum\": [\n" +
" \"RSI\",\n" +
" \"MACD\",\n" +
" \"Bollinger_Bands\",\n" +
" \"Stochastic_Oscillator\"\n" +
" ]\n" +
" }\n" +
" },\n" +
" \"period\": {\n" +
" \"type\": \"number\",\n" +
" \"description\": \"Time period for the analysis\"\n" +
" },\n" +
" \"ticker\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"Stock ticker symbol\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}\n"
var schema map[string]any
if err := json.Unmarshal([]byte(`{
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name of the function"
},
"description": {
"type": "string",
"description": "A description of what the function does"
},
"parameters": {
"$ref": "#/$defs/schema_definition",
"description": "A JSON schema that defines the function's parameters"
}
},
"required": [
"name",
"description",
"parameters"
],
"additionalProperties": false,
"$defs": {
"schema_definition": {
"type": "object",
"properties": {
"description": {
"type": "string"
},
"type": {
"type": "string",
"enum": [
"object",
"array",
"string",
"number",
"boolean",
"null"
]
},
"properties": {
"type": "object",
"additionalProperties": {
"$ref": "#/$defs/schema_definition"
}
},
"items": {
"anyOf": [
{
"$ref": "#/$defs/schema_definition"
},
{
"type": "array",
"items": {
"$ref": "#/$defs/schema_definition"
}
}
]
},
"required": {
"type": "array",
"items": {
"type": "string"
}
},
"additionalProperties": {
"type": "boolean"
}
},
"required": [
"type"
],
"additionalProperties": false,
"if": {
"properties": {
"type": {
"const": "object"
}
}
},
"then": {
"required": [
"properties"
]
}
}
}
}`), &schema); err != nil {
return err
}
completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
Model: "gpt-5.6-terra",
Messages: []openai.ChatCompletionMessageParamUnion{
openai.SystemMessage(metaPrompt), openai.UserMessage("Description: Schedule a meeting with a title and start time."),
}, ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{OfJSONSchema: &shared.ResponseFormatJSONSchemaParam{JSONSchema: shared.ResponseFormatJSONSchemaJSONSchemaParam{Name: "function-metaschema", Schema: schema}}}})
if err != nil {
return err
}
var result any
if err := json.Unmarshal([]byte(completion.Choices[0].Message.Content), &result); err != nil {
return err
}
encoded, err := json.MarshalIndent(result, "", " ")
if err != nil {
return err
}
fmt.Println(string(encoded))
return nil
}
元Schema(来源示例34,java)
// [中文] 元Schema描述函数名、说明和parameters;少样本示范超参数、机器人路径及技术指标。
// [中文] 提交待生成函数的描述并读取返回内容;解析JSON时仍需处理空内容或拒绝,required与properties必须同层。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import java.util.List;
import java.util.Map;
String metaPrompt =
"""
# Instructions
Return a valid schema for the described function.
Pay special attention to making sure that "required" and "type" are always at the correct level of nesting. For example, "required" should be at the same level as "properties", not inside it.
Make sure that every property, no matter how short, has a type and description correctly nested inside it.
# Examples
Input: Assign values to NN hyperparameters
Output: {
"name": "set_hyperparameters",
"description": "Assign values to NN hyperparameters",
"parameters": {
"type": "object",
"required": [
"learning_rate",
"epochs"
],
"properties": {
"epochs": {
"type": "number",
"description": "Number of complete passes through dataset"
},
"learning_rate": {
"type": "number",
"description": "Speed of model learning"
}
}
}
}
Input: Plans a motion path for the robot
Output: {
"name": "plan_motion",
"description": "Plans a motion path for the robot",
"parameters": {
"type": "object",
"required": [
"start_position",
"end_position"
],
"properties": {
"end_position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"description": "End X coordinate"
},
"y": {
"type": "number",
"description": "End Y coordinate"
}
}
},
"obstacles": {
"type": "array",
"description": "Array of obstacle coordinates",
"items": {
"type": "object",
"properties": {
"x": {
"type": "number",
"description": "Obstacle X coordinate"
},
"y": {
"type": "number",
"description": "Obstacle Y coordinate"
}
}
}
},
"start_position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"description": "Start X coordinate"
},
"y": {
"type": "number",
"description": "Start Y coordinate"
}
}
}
}
}
}
Input: Calculates various technical indicators
Output: {
"name": "technical_indicator",
"description": "Calculates various technical indicators",
"parameters": {
"type": "object",
"required": [
"ticker",
"indicators"
],
"properties": {
"indicators": {
"type": "array",
"description": "List of technical indicators to calculate",
"items": {
"type": "string",
"description": "Technical indicator",
"enum": [
"RSI",
"MACD",
"Bollinger_Bands",
"Stochastic_Oscillator"
]
}
},
"period": {
"type": "number",
"description": "Time period for the analysis"
},
"ticker": {
"type": "string",
"description": "Stock ticker symbol"
}
}
}
}
"""
.strip();
Map<String, Object> schemaDefinition =
Map.of(
"type", "object",
"properties",
Map.of(
"type",
Map.of(
"type",
"string",
"enum",
List.of("object", "array", "string", "number", "boolean", "null")),
"properties",
Map.of(
"type",
"object",
"additionalProperties",
Map.of("$ref", "#/$defs/schema_definition")),
"items",
Map.of(
"anyOf",
List.of(
Map.of("$ref", "#/$defs/schema_definition"),
Map.of(
"type",
"array",
"items",
Map.of("$ref", "#/$defs/schema_definition")))),
"required", Map.of("type", "array", "items", Map.of("type", "string")),
"additionalProperties", Map.of("type", "boolean")),
"required", List.of("type"),
"additionalProperties", false,
"if", Map.of("properties", Map.of("type", Map.of("const", "object"))),
"then", Map.of("required", List.of("properties")));
Map<String, Object> functionSchema =
Map.of(
"type", "object",
"properties",
Map.of(
"name", Map.of("type", "string", "description", "The name of the function"),
"description",
Map.of(
"type",
"string",
"description",
"A description of what the function does"),
"parameters",
Map.of(
"$ref",
"#/$defs/schema_definition",
"description",
"A JSON schema that defines the function's parameters")),
"required", List.of("name", "description", "parameters"),
"additionalProperties", false,
"$defs", Map.of("schema_definition", schemaDefinition));
ChatCompletionCreateParams params =
ChatCompletionCreateParams.builder()
.model("gpt-5.6-terra")
.addSystemMessage(metaPrompt)
.addUserMessage("Description:\nSchedule a meeting with a title and start time.")
.putAdditionalBodyProperty(
"response_format",
JsonValue.from(
Map.of(
"type",
"json_schema",
"json_schema",
Map.of("name", "function-metaschema", "schema", functionSchema))))
.build();
client.chat().completions().create(params).choices().stream()
.flatMap(choice -> choice.message().content().stream())
.forEach(System.out::println);
元Schema(来源示例35,csharp)
// [中文] 元Schema描述函数名、说明和parameters;少样本示范超参数、机器人路径及技术指标。
// [中文] 提交待生成函数的描述并读取返回内容;解析JSON时仍需处理空内容或拒绝,required与properties必须同层。
using System.Text.Json;
using OpenAI.Chat;
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-5.6-terra";
ChatClient client = new(model, key);
string metaPrompt = """"
# Instructions
Return a valid schema for the described function.
Pay special attention to making sure that "required" and "type" are always at the correct level of nesting. For example, "required" should be at the same level as "properties", not inside it.
Make sure that every property, no matter how short, has a type and description correctly nested inside it.
# Examples
Input: Assign values to NN hyperparameters
Output: {
"name": "set_hyperparameters",
"description": "Assign values to NN hyperparameters",
"parameters": {
"type": "object",
"required": [
"learning_rate",
"epochs"
],
"properties": {
"epochs": {
"type": "number",
"description": "Number of complete passes through dataset"
},
"learning_rate": {
"type": "number",
"description": "Speed of model learning"
}
}
}
}
Input: Plans a motion path for the robot
Output: {
"name": "plan_motion",
"description": "Plans a motion path for the robot",
"parameters": {
"type": "object",
"required": [
"start_position",
"end_position"
],
"properties": {
"end_position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"description": "End X coordinate"
},
"y": {
"type": "number",
"description": "End Y coordinate"
}
}
},
"obstacles": {
"type": "array",
"description": "Array of obstacle coordinates",
"items": {
"type": "object",
"properties": {
"x": {
"type": "number",
"description": "Obstacle X coordinate"
},
"y": {
"type": "number",
"description": "Obstacle Y coordinate"
}
}
}
},
"start_position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"description": "Start X coordinate"
},
"y": {
"type": "number",
"description": "Start Y coordinate"
}
}
}
}
}
}
Input: Calculates various technical indicators
Output: {
"name": "technical_indicator",
"description": "Calculates various technical indicators",
"parameters": {
"type": "object",
"required": [
"ticker",
"indicators"
],
"properties": {
"indicators": {
"type": "array",
"description": "List of technical indicators to calculate",
"items": {
"type": "string",
"description": "Technical indicator",
"enum": [
"RSI",
"MACD",
"Bollinger_Bands",
"Stochastic_Oscillator"
]
}
},
"period": {
"type": "number",
"description": "Time period for the analysis"
},
"ticker": {
"type": "string",
"description": "Stock ticker symbol"
}
}
}
}
"""";
ChatCompletionOptions options = new();
options.ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat("function-metaschema", BinaryData.FromString("""
{
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name of the function"
},
"description": {
"type": "string",
"description": "A description of what the function does"
},
"parameters": {
"$ref": "#/$defs/schema_definition",
"description": "A JSON schema that defines the function's parameters"
}
},
"required": [
"name",
"description",
"parameters"
],
"additionalProperties": false,
"$defs": {
"schema_definition": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [
"object",
"array",
"string",
"number",
"boolean",
"null"
]
},
"properties": {
"type": "object",
"additionalProperties": {
"$ref": "#/$defs/schema_definition"
}
},
"items": {
"anyOf": [
{
"$ref": "#/$defs/schema_definition"
},
{
"type": "array",
"items": {
"$ref": "#/$defs/schema_definition"
}
}
]
},
"required": {
"type": "array",
"items": {
"type": "string"
}
},
"additionalProperties": {
"type": "boolean"
}
},
"required": [
"type"
],
"additionalProperties": false,
"if": {
"properties": {
"type": {
"const": "object"
}
}
},
"then": {
"required": [
"properties"
]
}
}
}
}
"""));
ChatCompletion result = await client.CompleteChatAsync([new SystemChatMessage(metaPrompt), new UserChatMessage("Description: Schedule a meeting with a title and start time.")], options);
using JsonDocument parsed = JsonDocument.Parse(result.Content[0].Text);
Console.WriteLine(parsed.RootElement);
元Schema(来源示例36,ruby)
## [中文] 元Schema描述函数名、说明和parameters;少样本示范超参数、机器人路径及技术指标。
## [中文] 提交待生成函数的描述并读取返回内容;解析JSON时仍需处理空内容或拒绝,required与properties必须同层。
require "openai"
require "json"
META_SCHEMA = {
"name" => "function-metaschema",
"schema" => {
"type" => "object",
"properties" => {
"name" => {
"type" => "string",
"description" => "The name of the function"
},
"description" => {
"type" => "string",
"description" => "A description of what the function does"
},
"parameters" => {
"$ref" => "#/$defs/schema_definition",
"description" => "A JSON schema that defines the function's parameters"
}
},
"required" => ["name", "description", "parameters"],
"additionalProperties" => false,
"$defs" => {
"schema_definition" => {
"type" => "object",
"properties" => {
"type" => {
"type" => "string",
"enum" => ["object", "array", "string", "number", "boolean", "null"]
},
"properties" => {
"type" => "object",
"additionalProperties" => {
"$ref" => "#/$defs/schema_definition"
}
},
"items" => {
"anyOf" => [
{
"$ref" => "#/$defs/schema_definition"
}, {
"type" => "array",
"items" => {
"$ref" => "#/$defs/schema_definition"
}
}
]
},
"required" => {
"type" => "array",
"items" => {
"type" => "string"
}
},
"additionalProperties" => {
"type" => "boolean"
}
},
"required" => ["type"],
"additionalProperties" => false,
"if" => {
"properties" => {
"type" => {
"const" => "object"
}
}
},
"then" => {
"required" => ["properties"]
}
}
}
}
}
META_PROMPT = <<~PROMPT.strip
# Instructions
Return a valid schema for the described function.
Pay special attention to making sure that "required" and "type" are always at the correct level of nesting. For example, "required" should be at the same level as "properties", not inside it.
Make sure that every property, no matter how short, has a type and description correctly nested inside it.
# Examples
Input: Assign values to NN hyperparameters
Output: {
"name": "set_hyperparameters",
"description": "Assign values to NN hyperparameters",
"parameters": {
"type": "object",
"required": [
"learning_rate",
"epochs"
],
"properties": {
"epochs": {
"type": "number",
"description": "Number of complete passes through dataset"
},
"learning_rate": {
"type": "number",
"description": "Speed of model learning"
}
}
}
}
Input: Plans a motion path for the robot
Output: {
"name": "plan_motion",
"description": "Plans a motion path for the robot",
"parameters": {
"type": "object",
"required": [
"start_position",
"end_position"
],
"properties": {
"end_position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"description": "End X coordinate"
},
"y": {
"type": "number",
"description": "End Y coordinate"
}
}
},
"obstacles": {
"type": "array",
"description": "Array of obstacle coordinates",
"items": {
"type": "object",
"properties": {
"x": {
"type": "number",
"description": "Obstacle X coordinate"
},
"y": {
"type": "number",
"description": "Obstacle Y coordinate"
}
}
}
},
"start_position": {
"type": "object",
"properties": {
"x": {
"type": "number",
"description": "Start X coordinate"
},
"y": {
"type": "number",
"description": "Start Y coordinate"
}
}
}
}
}
}
Input: Calculates various technical indicators
Output: {
"name": "technical_indicator",
"description": "Calculates various technical indicators",
"parameters": {
"type": "object",
"required": [
"ticker",
"indicators"
],
"properties": {
"indicators": {
"type": "array",
"description": "List of technical indicators to calculate",
"items": {
"type": "string",
"description": "Technical indicator",
"enum": [
"RSI",
"MACD",
"Bollinger_Bands",
"Stochastic_Oscillator"
]
}
},
"period": {
"type": "number",
"description": "Time period for the analysis"
},
"ticker": {
"type": "string",
"description": "Stock ticker symbol"
}
}
}
}
PROMPT
client = OpenAI::Client.new
completion = client.chat.completions.create(
model: "gpt-5.6-terra",
response_format: {
type: :json_schema,
json_schema: META_SCHEMA
},
messages: [
{
role: :system,
content: META_PROMPT
},
{
role: :user,
content: "Description: Schedule a meeting with a title and start time."
}
]
)
message = completion.choices.fetch(0).message
raise "Schema generation refused: #{message.refusal}" if message.refusal
puts(JSON.pretty_generate(JSON.parse(message.content || raise("No schema returned"))))
TRAE-AI编程


更多建议: