All guides
OpenAI

提示工程

Checked 09/11/2026View original

AI translation, not an official translation. Refer to the original for technical details.

On this page

完整文档索引请参见 llms.txt。在页面 URL 后附加 .md 即可获取文档页面的 Markdown 版本。

使用 OpenAI API,您可以利用大型语言模型从提示生成文本,就像使用 ChatGPT 一样。模型几乎可以生成任何类型的文本响应——例如代码、数学方程式、结构化 JSON 数据或类似人类写作的散文。

以下是一个使用 Responses API 的简单示例。

从简单提示生成文本

import OpenAI from "openai";
const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-6-astra",
  input: "Write a one-sentence bedtime story about a unicorn.",
});

console.log(response.output_text);
from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    input="Write a one-sentence bedtime story about a unicorn.",
)

print(response.output_text)
package main

import (
	"context"
	"fmt"

	"github.com/openai/openai-go/v3"
	"github.com/openai/openai-go/v3/responses"
)

func main() {
	client := openai.NewClient()

	resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{
		Model: "gpt-6-astra",
		Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},
	})
	if err != nil {
		panic(err.Error())
	}

	fmt.Println(resp.OutputText())
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

public class Main {
  public static void main(String[] args) {
    OpenAIClient client = OpenAIOkHttpClient.fromEnv();

    ResponseCreateParams params =
        ResponseCreateParams.builder().input("Say this is a test").model("gpt-6-astra").build();

    Response response = client.responses().create(params);
    response.output().stream()
        .flatMap(item -> item.message().stream())
        .flatMap(message -> message.content().stream())
        .flatMap(content -> content.outputText().stream())
        .forEach(outputText -> System.out.println(outputText.text()));
  }
}
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);

ResponseResult response = await client.CreateResponseAsync(
    "gpt-6-astra",
    "Say 'this is a test.'"
);

Console.WriteLine($"[ASSISTANT]: {response.GetOutputText()}");
require "openai"

openai = OpenAI::Client.new

response = openai.responses.create(
  model: "gpt-6-astra",
  input: "Write a one-sentence bedtime story about a unicorn."
)

puts(response.output_text)
openai responses create \
  --model "gpt-6-astra" \
  --input "Write a one-sentence bedtime story about a unicorn." \
  --raw-output \
  --transform 'output.#(type=="message").content.0.text'
curl "https://api.openai.com/v1/responses" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -d '{
        "model": "gpt-6-astra",
        "input": "Write a one-sentence bedtime story about a unicorn."
    }'

模型生成的内容数组位于响应的 output 属性中。在这个简单示例中,我们只有一个输出,如下所示:

[
  {
    "id": "msg_67b73f697ba4819183a15cc17d011509",
    "type": "message",
    "role": "assistant",
    "content": [
      {
        "type": "output_text",
        "text": "Under the soft glow of the moon, Luna the unicorn danced through fields of twinkling stardust, leaving trails of dreams for every child asleep.",
        "annotations": []
      }
    ]
  }
]

output 数组中通常包含不止一个条目! 它可以包含工具调用、推理模型生成的推理令牌相关数据以及其他条目。因此,不能假定模型的文本输出一定位于 output[0].content[0].text

我们的部分官方 SDK 为方便起见,在模型响应中提供了 output_text 属性,它会将模型的所有文本输出汇总为一个字符串。这可以作为访问模型文本输出的快捷方式。

除纯文本外,您还可以让模型以 JSON 格式返回结构化数据——此功能称为结构化输出

选择模型

通过 API 生成内容时,一个关键选择是使用哪个模型——即上述代码示例中的 model 参数。您可以在此处查看所有可用模型的完整列表。以下是选择文本生成模型时需要考虑的几个因素。

  • 推理模型 会生成内部思维链来分析输入提示,擅长理解复杂任务和多步骤规划。但与 GPT 模型相比,它们通常速度更慢、使用成本更高。
  • GPT 模型 速度快、成本效益高且高度智能,但需要更明确的指令来说明如何完成任务。
  • 大型和小型(mini 或 nano)模型 在速度、成本和智能方面各有权衡。大型模型在理解提示和跨领域解决问题方面更为有效,而小型模型通常速度更快、成本更低。

如有疑问,gpt-6-astra 是通用文本生成和提示迭代的有力默认选择。

提示工程

提示工程是为模型编写有效指令的过程,使其能够持续生成满足您需求的内容。

由于模型生成的内容具有不确定性,要通过提示获得理想输出,既需要技巧,也需要经验。不过,您可以应用一定的技术和最佳实践来持续获得良好结果。

某些提示工程技术适用于所有模型,例如使用消息角色。但不同类型的模型(如推理模型与 GPT 模型)可能需要采用不同的提示方式才能产生最佳结果。即使是同一系列模型的不同快照版本,也可能产生不同的结果。因此,在构建更复杂的应用程序时,我们强烈建议:

  • 将您的生产应用程序固定到特定的模型快照(例如 gpt-4.1-2025-04-14),以确保行为的一致性
  • 构建测试和评估套件,用于衡量提示行为,以便在迭代或更换、升级模型版本时监控性能

现在,让我们来了解一些可用于构建提示的工具和技术。

消息角色与指令遵循

您可以通过 instructions API 参数或消息角色,以不同级别的权限向模型提供指令。

instructions 参数为模型提供关于其生成响应时应如何行为的高层级指令,包括语气、目标以及正确响应示例。以此方式提供的任何指令都将优先于 input 参数中的提示。

使用指令生成文本

import OpenAI from "openai";
const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-6-astra",
  reasoning: { effort: "low" },
  instructions: "Talk like a pirate.",
  input: "Are semicolons optional in JavaScript?",
});

console.log(response.output_text);
from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    reasoning={"effort": "low"},
    instructions="Talk like a pirate.",
    input="Are semicolons optional in JavaScript?",
)

print(response.output_text)
package main

import (
	"context"
	"fmt"

	"github.com/openai/openai-go/v3"
	"github.com/openai/openai-go/v3/responses"
)

func main() {
	client := openai.NewClient()

	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
		Model:        "gpt-6-astra",
		Instructions: openai.String("Talk like a pirate."),
		Reasoning: responses.ReasoningParam{
			Effort: responses.ReasoningEffortLow,
		},
		Input: responses.ResponseNewParamsInputUnion{
			OfString: openai.String("Are semicolons optional in JavaScript?"),
		},
	})
	if err != nil {
		panic(err)
	}

	fmt.Println(response.OutputText())
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.Reasoning;
import com.openai.models.ReasoningEffort;
import com.openai.models.responses.ResponseCreateParams;

String semicolonsDevMsg = "Talk like a pirate.";

String semicolonsPrompt = "Are semicolons optional in JavaScript?";

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input(semicolonsPrompt)
        .instructions(semicolonsDevMsg)
        .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())
        .build();

client.responses().create(params).output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);

CreateResponseOptions options = new()
{
    Model = "gpt-6-astra",
    Instructions = "Talk like a pirate.",
    ReasoningOptions = new ResponseReasoningOptions
    {
        ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,
    },
};
options.InputItems.Add(
    ResponseItem.CreateUserMessageItem("Are semicolons optional in JavaScript?")
);

ResponseResult response = await client.CreateResponseAsync(options);

Console.WriteLine(response.GetOutputText());
require "openai"

client = OpenAI::Client.new
response = client.responses.create(
  model: "gpt-6-astra",
  instructions: "Talk like a pirate.",
  reasoning: {effort: :low},
  input: "Are semicolons optional in JavaScript?"
)

puts(response.output_text)
curl "https://api.openai.com/v1/responses" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -d '{
        "model": "gpt-6-astra",
        "reasoning": {"effort": "low"},
        "instructions": "Talk like a pirate.",
        "input": "Are semicolons optional in JavaScript?"
    }'

上述示例大致等同于在 input 数组中使用以下不同角色的输入消息:

使用不同角色的消息生成文本

import OpenAI from "openai";
const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-6-astra",
  reasoning: { effort: "low" },
  input: [
    {
      role: "developer",
      content: "Talk like a pirate.",
    },
    {
      role: "user",
      content: "Are semicolons optional in JavaScript?",
    },
  ],
});

console.log(response.output_text);
from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    reasoning={"effort": "low"},
    input=[
        {"role": "developer", "content": "Talk like a pirate."},
        {"role": "user", "content": "Are semicolons optional in JavaScript?"},
    ],
)

print(response.output_text)
package main

import (
	"context"
	"fmt"

	"github.com/openai/openai-go/v3"
	"github.com/openai/openai-go/v3/responses"
)

func main() {
	client := openai.NewClient()

	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
		Model: "gpt-6-astra",
		Reasoning: responses.ReasoningParam{
			Effort: responses.ReasoningEffortLow,
		},
		Input: responses.ResponseNewParamsInputUnion{
			OfInputItemList: responses.ResponseInputParam{
				responses.ResponseInputItemParamOfMessage(
					"Talk like a pirate.",
					responses.EasyInputMessageRoleDeveloper,
				),
				responses.ResponseInputItemParamOfMessage(
					"Are semicolons optional in JavaScript?",
					responses.EasyInputMessageRoleUser,
				),
			},
		},
	})
	if err != nil {
		panic(err)
	}

	fmt.Println(response.OutputText())
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.Reasoning;
import com.openai.models.ReasoningEffort;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;

String semicolonsDevMsg = "Talk like a pirate.";

String semicolonsPrompt = "Are semicolons optional in JavaScript?";

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input(
            ResponseCreateParams.Input.ofResponse(
                List.of(
                    ResponseInputItem.ofEasyInputMessage(
                        EasyInputMessage.builder()
                            .role(EasyInputMessage.Role.DEVELOPER)
                            .content(semicolonsDevMsg)
                            .build()),
                    ResponseInputItem.ofEasyInputMessage(
                        EasyInputMessage.builder()
                            .role(EasyInputMessage.Role.USER)
                            .content(semicolonsPrompt)
                            .build()))))
        .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())
        .build();

client.responses().create(params).output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);

CreateResponseOptions options = new()
{
    Model = "gpt-6-astra",
    ReasoningOptions = new ResponseReasoningOptions
    {
        ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,
    },
};
options.InputItems.Add(
    ResponseItem.CreateDeveloperMessageItem("Talk like a pirate.")
);
options.InputItems.Add(
    ResponseItem.CreateUserMessageItem("Are semicolons optional in JavaScript?")
);

ResponseResult response = await client.CreateResponseAsync(options);

Console.WriteLine(response.GetOutputText());
require "openai"

client = OpenAI::Client.new
response = client.responses.create(
  model: "gpt-6-astra",
  reasoning: {effort: :low},
  input: [
    {role: :developer, content: "Talk like a pirate."},
    {role: :user, content: "Are semicolons optional in JavaScript?"}
  ]
)

puts(response.output_text)
curl "https://api.openai.com/v1/responses" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -d '{
        "model": "gpt-6-astra",
        "reasoning": {"effort": "low"},
        "input": [
            {
                "role": "developer",
                "content": "Talk like a pirate."
            },
            {
                "role": "user",
                "content": "Are semicolons optional in JavaScript?"
            }
        ]
    }'

请注意,instructions 参数仅适用于当前的响应生成请求。如果您正在使用 previous_response_id 参数管理对话状态,则在先前轮次中使用的 instructions 将不会出现在上下文中。

OpenAI 模型规范描述了我们的模型如何对不同角色的消息赋予不同级别的优先权。

developeruserassistant
developer 消息是由应用程序开发者提供的指令,其优先级高于 user 消息。user 消息是由最终用户提供的指令,其优先级低于 developer 消息。由模型生成的消息具有 assistant 角色。

多轮对话可能由这些类型的多条消息以及由您和模型提供的其他内容类型组成。在此处了解更多关于管理对话状态的内容。

您可以将 developer 消息和 user 消息理解为编程语言中的函数及其参数。

  • developer 消息提供系统的规则和业务逻辑,类似于函数定义。
  • user 消息提供输入和配置,developer 消息的指令将应用于这些内容,类似于传递给函数的参数。

在代码中管理提示词版本

将生产环境的提示词存储在应用代码中,而不是创建可复用的提示词对象。通过代码管理提示词,您可以使用类型化输入、代码审查、测试以及常规部署流程来更改模型行为。

OpenAI 正在废弃 API 中的可复用提示词对象。从 2026 年 6 月 3 日起,提示词创建功能将被逐步淡化,v1/prompts 计划于 2026 年 11 月 30 日关闭。请参阅废弃说明页面了解当前时间表。

对于新的提示词工程工作:

  • 将提示词构建器保存在靠近其所支持功能的小模块中。
  • 对客户数据、文件或任务选项等动态值使用类型化函数参数或 Schema。
  • 将生成的 instructionsinput 直接传递给 Responses API
  • 在修改生产提示词之前,添加具有代表性的测试夹具、测试用例和评估检查。
  • 通过您的部署系统推出提示词变更,在需要分阶段发布时使用功能标志或配置项。

如果您的集成已通过提示词 ID 或版本调用已保存的提示词,请使用提示词对象迁移指南将该提示词迁移到代码中。

使用 Markdown 和 XML 格式化消息

在编写 developeruser 消息时,您可以结合使用 Markdown 格式和 XML 标签,帮助模型理解提示词和上下文数据的逻辑边界。

Markdown 标题和列表有助于标记提示词的不同部分,并向模型传达层级关系,同时也可以使您的提示词在开发过程中更易于阅读。XML 标签可以帮助界定某段内容(如用于参考的辅助文档)的起止位置。XML 属性还可用于定义提示词中内容的元数据,以便在指令中引用。

通常,开发者消息将包含以下几个部分,一般按以下顺序排列(不过,确切的最优内容和顺序可能因您使用的模型而有所不同):

  • 身份: 描述助手的用途、沟通风格和高层目标。
  • 指令: 为模型提供生成所需响应的指导。它应遵循哪些规则?模型应该做什么,绝对不应该做什么?该部分可根据您的使用场景包含多个子部分,例如模型应如何调用自定义函数
  • 示例: 提供可能的输入示例,以及模型期望输出的对应结果。
  • 上下文: 为模型提供生成响应可能需要的任何额外信息,例如训练数据之外的私有/专有数据,或您已知特别相关的任何数据。此类内容通常最好放在提示词末尾,因为不同的生成请求可能需要包含不同的上下文。

以下是一个使用 Markdown 和 XML 标签构建 developer 消息的示例,该消息包含不同的分区和辅助示例。

示例提示词

A developer message for code generation
# Identity

You are coding assistant that helps enforce the use of snake case
variables in JavaScript code, and writing code that will run in
Internet Explorer version 6.

# Instructions

* When defining variables, use snake case names (e.g. my_variable)
  instead of camel case names (e.g. myVariable).
* To support old browsers, declare variables using the older
  "var" keyword.
* Do not give responses with Markdown formatting, just return
  the code as requested.

# Examples

<user_query>
How do I declare a string variable for a first name?
</user_query>

<assistant_response>
var first_name = "Anna";
</assistant_response>

API 请求

Send a prompt to generate code through the API
import fs from "fs/promises";
import OpenAI from "openai";
const client = new OpenAI();

const instructions = await fs.readFile("fixtures/prompt.txt", "utf-8");

const response = await client.responses.create({
  model: "gpt-6-astra",
  instructions,
  input: "How would I declare a variable for a last name?",
});

console.log(response.output_text);
from openai import OpenAI

client = OpenAI()

with open("prompt.txt", "r", encoding="utf-8") as f:
    instructions = f.read()

response = client.responses.create(
    model="gpt-6-astra",
    instructions=instructions,
    input="How would I declare a variable for a last name?",
)

print(response.output_text)
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/openai/openai-go/v3"
	"github.com/openai/openai-go/v3/responses"
)

func main() {
	client := openai.NewClient()

	instructions, err := os.ReadFile("prompt.txt")
	if err != nil {
		panic(err)
	}

	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
		Model:        "gpt-6-astra",
		Instructions: openai.String(string(instructions)),
		Input: responses.ResponseNewParamsInputUnion{
			OfString: openai.String("How would I declare a variable for a last name?"),
		},
	})
	if err != nil {
		panic(err)
	}

	fmt.Println(response.OutputText())
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .instructions(
            "You are a coding assistant. Answer with concise JavaScript examples and use semicolons.")
        .input("How would I declare a variable for a last name?")
        .build();

client.responses().create(params).output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);

string instructions = await File.ReadAllTextAsync("prompt.txt");
CreateResponseOptions options = new()
{
    Model = "gpt-6-astra",
    Instructions = instructions,
};
options.InputItems.Add(
    ResponseItem.CreateUserMessageItem("How would I declare a variable for a last name?")
);

ResponseResult response = await client.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
require "openai"

client = OpenAI::Client.new
instructions = File.read(File.join(__dir__, "prompt.txt"))
response = client.responses.create(
  model: "gpt-6-astra",
  instructions: instructions,
  input: "How would I declare a variable for a last name?"
)

puts(response.output_text)
curl https://api.openai.com/v1/responses \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-6-astra",
    "instructions": "'"$(< prompt.txt)"'",
    "input": "How would I declare a variable for a last name?"
  }'

通过提示词缓存降低成本和延迟

在构建消息时,应尽量将您预期在 API 请求中反复使用的内容放在提示词开头,并且放在您向 Chat CompletionsResponses JSON 请求体传入的最前面的 API 参数中。这样可以最大化利用提示词缓存带来的成本和延迟节省效果。

少样本学习

少样本学习允许您通过在提示词中包含少量输入/输出示例,将大语言模型引导至新任务,而无需对模型进行微调。模型会从这些示例中隐式"学习"规律,并将其应用于提示词。在提供示例时,请尽量展示多样化的可能输入及其期望输出。

通常,您会在 API 请求的 developer 消息中提供示例。以下是一个包含示例的 developer 消息示例,展示如何指导模型对正面或负面的客户服务评论进行分类。

# Identity

You are a helpful assistant that labels short product reviews as
Positive, Negative, or Neutral.

# Instructions

* Only output a single word in your response with no additional formatting
  or commentary.
* Your response should only be one of the words "Positive", "Negative", or
  "Neutral" depending on the sentiment of the product review you are given.

# Examples

<product_review id="example-1">
I absolutely love this headphones — sound quality is amazing!
</product_review>

<assistant_response id="example-1">
Positive
</assistant_response>

<product_review id="example-2">
Battery life is okay, but the ear pads feel cheap.
</product_review>

<assistant_response id="example-2">
Neutral
</assistant_response>

<product_review id="example-3">
Terrible customer service, I'll never buy from them again.
</product_review>

<assistant_response id="example-3">
Negative
</assistant_response>

包含相关上下文信息

在提示词中加入模型可用于生成响应的额外上下文信息通常很有帮助。您可能这样做的常见原因有以下几点:

  • 为模型提供专有数据,或模型训练数据集之外的其他任何数据。
  • 将模型的响应限定在您认为最有价值的特定资源范围内。

这种在模型生成请求中添加额外相关上下文的技术有时被称为检索增强生成(RAG)。您可以通过多种方式向提示词添加额外上下文,例如查询向量数据库并将返回的文本加入提示词,或使用 OpenAI 内置的文件搜索工具基于上传的文档生成内容。

规划上下文窗口

模型在生成请求时所能处理的数据量是有限的。这一内存限制被称为上下文窗口,以 token(您传入的数据块,从文本到图像)为单位定义。

不同模型的上下文窗口大小各不相同,从低端的 10 万 token 级别到较新的 GPT-4.1 模型的百万 token 级别不等。请参阅模型文档了解各模型具体的上下文窗口大小。

对当前模型进行提示词工程

gpt-6-astra 等 GPT 模型受益于精确的指令,这些指令能在提示词中明确提供完成任务所需的逻辑和数据。要充分发挥最新模型的潜力,请从当前的提示词指南开始。

[

  Get the most out of prompting the latest model with current guidance,
practical examples, and migration notes.](https://developers.openai.com/api/docs/guides/latest-model)

最新模型的提示词最佳实践

如需完整的最新说明,请参阅最新模型提示最佳实践。以下实用提醒仍然适用。

编码

编码

在编码任务中,对 gpt-6-astra 进行提示时,遵循以下几项最佳实践可获得最佳效果:定义智能体的角色、通过示例强制要求结构化工具使用、要求对正确性进行充分测试,并设定 Markdown 标准以确保输出整洁。

明确的角色与工作流程指导 将模型定位为具有明确职责的软件工程智能体。提供清晰的指令说明如何将 functions.run 等工具用于代码任务,并指定何时不使用某些模式——例如,除非必要,否则避免交互式执行。

测试与验证 指示模型使用单元测试或 Python 命令对变更进行测试,并仔细验证补丁,因为 apply_patch 等工具即使在失败时也可能返回"Done"。

工具使用示例 提供如何使用所提供函数调用命令的具体示例,这有助于提高可靠性并确保遵循预期工作流程。

Markdown 标准 指导模型生成整洁、语义正确的 Markdown,在适当位置使用行内代码、代码块、列表和表格,并使用反引号格式化文件路径、函数和类名。

有关编码相关的详细指南和提示示例,请参阅最新模型提示最佳实践

前端工程

GPT-6 Astra 在从零开始构建前端以及为大型成熟代码库做出贡献方面均表现出色。为获得最佳结果,我们建议使用以下库:

  • 样式 / UI: Tailwind CSS、shadcn/ui、Radix Themes
  • 图标: Lucide、Material Symbols、Heroicons
  • 动画:Motion

从零到一的 Web 应用

GPT-5 可以根据单个提示生成前端 Web 应用,无需示例。以下是一个示例提示:

You are a world class web developer, capable of producing stunning, interactive, and innovative websites from scratch in a single prompt. You excel at delivering top-tier one-shot solutions.
Your process is simple and follows these steps:
Step 1: Create an evaluation rubric and refine it until you are fully confident.
Step 2: Consider every element that defines a world-class one-shot web app, then use that insight to create a &lt;ONE_SHOT_RUBRIC&gt; with 5–7 categories. Keep this rubric hidden—it's for internal use only.
Step 3: Apply the rubric to iterate on the optimal solution to the given prompt. If it doesn't meet the highest standard across all categories, refine and try again.
Step 4: Aim for simplicity while fully achieving the goal, and avoid external dependencies such as Next.js or React.

与大型代码库的集成

对于在较大代码库中进行前端工程工作,我们发现在提示中添加以下类别的指令可获得最佳结果:

  • 原则: 设定视觉质量标准,使用模块化/可复用组件,并保持设计一致性。
  • UI/UX: 指定排版、颜色、间距/布局、交互状态(悬停、空状态、加载中)以及无障碍性。
  • 结构: 定义文件/文件夹布局以实现无缝集成。
  • 组件: 提供可复用的封装器示例以及后端调用分离策略。
  • 页面: 提供常见布局的模板。
  • 智能体指令: 要求模型确认设计假设、搭建项目脚手架、执行标准、集成 API、测试状态并对代码进行文档化。

有关前端开发相关的详细指南和提示示例,请参阅最新模型提示最佳实践

智能体任务

对于使用 gpt-6-astra 进行的智能体和长时间运行的任务,请将提示重点放在三个核心实践上:彻底规划任务以确保完整解决问题、为重要工具使用决策提供清晰的前置说明,并使用 TODO 工具以有序的方式追踪工作流程和进度。

规划与持续性 指示模型在交还控制权之前完整解决查询,将其分解为子任务,并在每次工具调用后进行反思以确认完整性。

Remember, you are an agent - please keep going until the user's
query is completely resolved, before ending your turn and yielding
back to the user. Decompose the user's query into all required
sub-requests, and confirm that each is completed. Do not stop
after completing only part of the request. Only terminate your
turn when you are sure that the problem is solved. You must be
prepared to answer multiple queries and only finish the call once
the user has confirmed they're done.

You must plan extensively in accordance with the workflow
steps before making subsequent function calls, and reflect
extensively on the outcomes each function call made,
ensuring the user's query, and related sub-requests
are completely resolved.

透明度的前置说明

要求模型解释其调用工具的原因,但仅在关键步骤处执行此操作。

Before you call a tool explain why you are calling it

使用评分标准和 TODO 跟踪进度

使用 TODO 列表工具或评分标准来强制执行结构化规划,避免遗漏步骤。

有关构建智能体相关的详细指南和提示示例,请参阅最新模型提示最佳实践

提示推理模型

在提示推理模型与提示 GPT 模型时,有一些差异需要考虑。一般而言,推理模型在仅提供高层次指导的任务中会提供更好的结果。这与 GPT 模型不同,后者受益于非常精确的指令。

您可以这样理解推理模型与 GPT 模型之间的差异:

  • 推理模型就像一位资深同事。您可以给他们一个需要实现的目标,并相信他们能够自行处理细节。
  • GPT 模型就像一位初级同事。他们在获得明确指令以创建特定输出时表现最佳。

有关使用推理模型时最佳实践的更多信息,请参阅本指南

后续步骤

现在您已了解文本输入和输出的基础知识,接下来可以查阅以下资源之一。

[在 Playground 中构建提示

  Use the Playground to develop and iterate on prompts.](https://platform.openai.com/chat/edit)

[使用结构化输出生成 JSON 数据

  Ensure JSON data emitted from a model conforms to a JSON schema.](https://developers.openai.com/api/docs/guides/structured-outputs)

[完整 API 参考

  Check out all the options for text generation in the API reference.](https://developers.openai.com/api/reference/resources/responses)

其他资源

如需更多灵感,请访问 OpenAI Cookbook,其中包含示例代码以及指向第三方资源的链接,例如: