如需查看完整的文档索引,请参阅 llms.txt。在文档页面的 URL 末尾加上 .md 即可查看该页面的 Markdown 版本。
主导航
主题

提示词生成

在 Playground 中生成提示词和模式。

使用生成按钮时,您只需在 Playground 中描述任务,即可生成提示词、函数和模式。本指南将详细介绍其工作原理。

概述

从头编写提示词和模式可能很耗时,自动生成可以帮助您快速上手。“生成”按钮主要采用两种方法:

  1. 提示词:我们使用融入最佳实践的元提示词来生成或改进提示词。
  2. 模式:我们使用元模式来生成语法有效的 JSON 和函数定义。

目前我们使用元提示词和元模式,未来可能会引入更先进的技术,例如 DSPy 和“梯度下降”。

提示词

元提示词指导模型根据您的任务描述编写优质提示词,或改进已有的提示词。Playground 中的元提示词结合了我们的提示词工程最佳实践,以及我们与用户合作积累的实际经验。

我们针对音频等不同输出类型使用专门的元提示词,确保生成的提示词符合预期格式。

元提示词

文本输出的元提示词
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: string) {
  const completion = await client.chat.completions.create({
    model: "gpt-6.2-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.")
);

编辑提示词

编辑提示词时,我们会对元提示词稍作调整。如果修改要求明确,模型很容易照做;如果要求比较开放,判断哪些地方需要修改就比较困难。为此,我们让模型在回复开头写一段推理过程。在这一部分,模型会评估现有提示词是否清晰、思维链中各步骤的顺序是否合理、整体结构如何、表述是否具体等,据此判断需要做哪些修改并提出改进建议。我们在解析回复时会移除这一部分,再返回最终回复。

用于编辑文本输出提示词的元提示词
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: string) {
  const completion = await client.chat.completions.create({
    model: "gpt-6.2-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.")
);

模式

结构化输出模式和函数模式本身都是 JSON 对象,因此我们可以用结构化输出来生成它们。 使用结构化输出时,需要先定义一个模式来描述所需的输出。在这里,要生成的输出本身也是模式,因此我们使用一种能够描述自身的模式,即元模式。

函数模式中的 parameters 字段本身也是一个模式,因此我们使用同一个元模式来生成函数。

定义受约束的元模式

结构化输出支持两种运行模式:strict=true 和 strict=false。两者使用同一个模型,该模型经过训练,能够遵循给定的模式,但只有“严格模式”通过约束采样保证输出完全符合给定的模式。

我们的目标是在严格模式下生成符合其约束的模式。然而,JSON Schema 规范提供的官方元模式依赖严格模式目前尚不支持的特性。这给输入模式和输出模式都带来了限制。

  1. 输入模式:我们无法在输入模式中使用不受支持的特性来描述输出模式。
  2. 输出模式:生成的模式不得包含不受支持的特性。

由于需要在输出模式中生成新的键,输入的元模式必须使用 additionalProperties。因此,我们目前无法在严格模式下生成模式,但仍希望生成的模式符合严格模式的约束。

为克服这一限制,我们定义了伪元模式。这种元模式在定义中使用严格模式不支持的特性,但它所描述的特性仅限于严格模式支持的范围。这样,元模式的定义可以超出严格模式的限制,同时仍能确保生成的模式符合严格模式的约束。

深入解析
我们如何设计伪元模式

清理输出

严格模式可以保证输出完全符合给定的模式。但由于生成时无法使用严格模式,我们需要在生成后验证并转换输出。

生成模式后,我们会执行以下步骤:

  1. 将 additionalProperties 设为 false,对所有对象都执行此操作。
  2. 将所有属性标记为必填项。
  3. 对于结构化输出模式,将其封装在 json_schema 对象中。
  4. 对于函数,将其封装在 function 对象中。

Realtime API 的函数对象与 Chat Completions API 的函数对象略有不同,但两者使用相同的模式。

元模式

每个元模式都有一个对应的提示词,其中包含少样本示例。结合这些提示词和结构化输出本身的可靠性,即使不启用严格模式,我们也能生成模式。

结构化输出元模式
import OpenAI from "openai";

const client = new OpenAI();

const schemaDefinition = {
  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" },
    enum: { type: "array", minItems: 1, uniqueItems: true },
    $ref: { type: "string" },
    $defs: {
      type: "object",
      additionalProperties: { $ref: "#/$defs/schema_definition" },
    },
    anyOf: {
      type: "array",
      minItems: 1,
      items: { $ref: "#/$defs/schema_definition" },
    },
  },
  additionalProperties: false,
  if: { required: ["type"], properties: { type: { const: "object" } } },
  then: { required: ["properties"] },
};

const metaSchema = {
  name: "metaschema",
  schema: {
    ...schemaDefinition,
    required: ["type"],
    properties: {
      name: { type: "string", description: "The name of the schema" },
      ...schemaDefinition.properties,
    },
    $defs: {
      schema_definition: {
        ...schemaDefinition,
        anyOf: [
          { required: ["type"] },
          { required: ["$ref"] },
          { required: ["anyOf"] },
        ],
      },
    },
  },
};

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: string) {
  const completion = await client.chat.completions.create({
    model: "gpt-6.1-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)
);