Prompt variables: define and validate changing inputs
A prompt variable is a named value passed into a fixed place in a prompt when that value changes from one request to the next. It can be a customer question, a document to use, a response language, or retrieved search results. Giving a value a name is only the start: application code should define what it means and what format, range, and source it allows.
A prompt variable is a named value passed into a fixed place in a prompt when that value changes from one request to the next. It can be a customer question, a document to use, a response language, or retrieved search results. Giving a value a name is only the start: application code should define what it means and what format, range, and source it allows.
This article explains how to design dynamic inputs sent to a model API. A separate Prompt template topic covers reusable instructions and structure; here the focus is the contract for each variable and how to validate it. Variables in OpenAI API saved Prompt objects are a product feature distinct from the general idea of variables. As of November 22, 2026, OpenAI has de-emphasized creating new Prompt objects and scheduled the /v1/prompts shutdown for November 30, 2026. The implementation example below therefore uses application-managed input values.
Which values should be variables?
Model a value as a variable when it is inserted into a prompt, changes across requests, and can be chosen by the caller. For example, a customer-support feature might take question, a server-retrieved policyExcerpt, and replyLanguage. A persistent service rule such as “do not make up information absent from the policy” should be application-managed guidance, not a caller-controlled input variable. If users can replace the role or policy text itself, the data interface can become a way to change the service rules.
Each variable needs a contract, not just a name.
| Contract item | Question to answer | Example: replyLanguage |
|---|---|---|
| Meaning | What exactly does this value select or describe? | Language to use in the reply |
| Type | Is it text, a number, an enum, or an object? | "ko" or "en" |
| Required behavior | If it is missing, should the system stop, use a default, or ask? | Required; reject values outside the allowlist |
| Size and range | What length, numeric limits, or item count is allowed? | Accept only short language codes |
| Source and permission | Who supplies it, and may they access the referenced data? | Caller may choose a language; server retrieves the policy excerpt |
| Use in prompt | Is it a request, source material, or application rule? | A response condition in the user message |
Treating every variable as a string erases its structure and meaning. For example, if a quantity is text, it is hard to handle "3", "three", and "-1" consistently. Specify whether it is an integer and its minimum and maximum; for a language, accept only supported codes. A type declaration can catch some development-time errors, but it does not validate the actual value received from a network request or form.
How do you validate values and separate them from permissions?
Input validation has three distinct checks. First, syntax validation checks whether a value has the expected shape. Second, semantic validation checks whether it makes sense for the current task. Third, authorization checks whether the caller may retrieve the data or request the action. A value should not be trusted or granted access merely because it has the right string format.
For example, the TypeScript function below restricts the reply language to an allowlist and rejects a blank question. It assumes the policy excerpt is fetched by server code after authorization rather than supplied by a browser or user. The code illustrates a structure; it is not a program claimed to have been run or integration-tested.
type ReplyLanguage = "ko" | "en";
type SupportRequest = {
question: string;
replyLanguage: ReplyLanguage;
};
function validateSupportRequest(value: unknown): SupportRequest {
if (!value || typeof value !== "object") throw new Error("Invalid request format.");
const candidate = value as Record<string, unknown>;
if (typeof candidate.question !== "string") throw new Error("Question must be text.");
const question = candidate.question.trim();
if (!question) throw new Error("Question is empty.");
if (question.length > 4000) throw new Error("Question exceeds the allowed length.");
if (candidate.replyLanguage !== "ko" && candidate.replyLanguage !== "en") {
throw new Error("Unsupported reply language.");
}
return { question, replyLanguage: candidate.replyLanguage };
}
function buildMessages(request: unknown, policyExcerpt: string) {
const checked = validateSupportRequest(request);
if (!policyExcerpt.trim()) throw new Error("Verified policy material is required.");
return [
{
role: "developer" as const,
content:
"Answer customer questions using only the supplied policy material. Do not infer procedures or exceptions that are absent from it.",
},
{
role: "user" as const,
content: `Reply language: ${checked.replyLanguage}\nCustomer question: ${checked.question}\nPolicy material:\n${policyExcerpt}`,
},
];
}In a real server, do not assume an externally supplied value already has a trusted type; validate and normalize it at the input boundary. The example accepts unknown and checks runtime field types and allowed values. A production application could also use a validation library or API schema. Check access to the customer or account before fetching policy material. Putting a value in a model prompt is not a database permission check.
Long text from an external document or search result may be riskier than a simple string variable. It can contain a sentence such as “ignore the earlier rules” that attempts to instruct the model. Mark the boundary and tell the model to treat the content as material to analyze, but do not expect delimiters or tags to stop every attack. Restrict tool permissions and external actions in the application, and use separate checks and approval for sensitive results or real changes.
What if variables are numerous or complex?
As fields grow, it is easier to manage related values in an explicit object or schema. For instance, instead of scattering dateRange across two strings, treat it as a range object whose time zone and permitted span are validated. Represent a variable with a fixed set of choices as an enum or allowlist rather than free-form text. When multiple values change together, check that changing one does not make another inconsistent.
Structured input does not guarantee that a model’s output is correct or that the input is true. Input validation checks whether the data has the shape a program expects; fact checking separately considers the source and reliability of its contents. A valid date format does not prove that the event is real. For variables whose factual accuracy matters, consider recording the source, retrieval time, owner, and refresh policy.
Adding variables indefinitely so one request can handle many tasks may obscure which inputs connect to which rules and outputs. Split tasks into separate functions or prompts when their goals, permissions, or validation rules differ. When choosing a default for a missing value, decide whether it is safe; choose among rejection, a follow-up question, or an explicit default instead of vague behavior such as “infer it if blank.”
In what order should values go into a prompt?
Keeping reusable instructions first and request-specific values later makes it easier to distinguish rules from data. OpenAI’s Responses API documentation recommends putting reusable guidance in the first developer message and building dynamic values from typed arguments or validated input objects. Message roles and input structures can differ across APIs, so follow the current documentation for the endpoint you use.
Putting variable data after a stable prompt prefix may help reuse prompt caches in some APIs. That is a possibility when the prefix actually matches and the model and request conditions qualify; it is not a guarantee of a cache hit or lower cost. Do not retain user data unnecessarily or add sensitive content to a request just to pursue caching.
Saved Prompt objects in the OpenAI API are a separate management feature that associates named variables with request-time values. A service already using saved Prompts should plan a migration according to the scheduled shutdown; the general concept of variables is not going away. The official documentation checked on November 22, 2026, gives the de-emphasis and scheduled shutdown dates, so recheck the latest notice and the SDK version in use when planning a migration.
What should you record and verify?
Versioning variable definitions alongside prompts makes changes easier to trace. Document each variable’s meaning, allowed values, limits, source, and missing-value behavior in code or developer documentation, and keep representative inputs and edge cases as evaluation fixtures. Cases might include a valid input, blank text, an overlength value, an unsupported language, an unauthorized document identifier, and quoted material that contains instructions.
Before release, check at least the following:
Does the system safely reject a missing required variable or a value in the wrong format?
Can a caller retrieve personal data or policy documents without permission?
Does the design distinguish instructions embedded in external material from application rules?
Do evaluations check the requested language and structure and guard against unsupported claims?
Do schema or prompt changes introduce regressions on existing cases?
A prompt variable marks the boundary of dynamic input used by a model. Defining types and limits can catch some errors early, but reliability also depends on runtime validation, authorization, source management, and evaluation.
References
[OpenAI API: Prompting](https://developers.openai.com/api/docs/guides/prompting)
[OpenAI API: Text generation](https://developers.openai.com/api/docs/guides/text)
[OpenAI API: Migrate from prompt objects](https://developers.openai.com/api/docs/guides/prompting/migrate-from-prompt-object)
[OpenAI Model Spec (2025-09-12)](https://model-spec.openai.com/2025-09-12.html)