Skip to main content
Zimei TechnologyEnterprise AI · Development and delivery
EnglishEN
Discuss a project

Enterprise AI Project Wiki · Data, knowledge, and models

Prompt

Also calledPrompt · Model prompt · Input prompt · Prompt template · System prompt · 系统提示词 · 提示词

Definition

A prompt is the input structure an application constructs and submits for one generative-model call to express what the model should do, what it may rely on, which boundaries it must observe, how to handle missing or conflicting information, and what verifiable form to return. A governed prompt version fixes at least its purpose and owner, model/API and message roles, template text, variable names and types, interpolation and escaping rules, context and tool insertion points, output contract, inference-parameter reference, test set, approval state, release time, and rollback version.

A prompt is an input contract for one model call, not a magic incantation

Prompts are easily mistaken for prose polished by intuition: change a few words, add “follow these rules strictly,” and the result may appear better. An enterprise project has to govern the complete input contract instead—who supplied the task, what the model can see, how gaps are handled, and what form the result must take.

“Organise this procurement request” does not say what the result is, which fields are evidence, what to do when data is missing or conflicting, or whether inference or action is allowed. It can express user intent, but it is not yet a deliverable prompt contract. The project must encode objective, inputs, boundaries, output, and failure states in a structure the model and application can execute and test.

Modern chat and multimodal APIs can accept role-bearing messages, multiple content blocks, system instructions, tool schemas, and runtime variables. A provider can serialise them through another model-specific template, so one text fragment visible in source code is not necessarily the complete token sequence the model receives.

Prompts influence an output distribution; they cannot create missing model capability or replace current facts, access control, business validation, and security enforcement. The same template can behave differently after a model, version, language, context, parameter, or tool change. Even an identical combination can yield variable sampled output.

Establish a replayable prompt-version contract first

When an answer goes wrong, the team needs the exact template, variables, model, and parameters used at the time, not a similar sentence reconstructed from memory. A version contract brings those conditions into one object that can be compared, retested, and rolled back.

Stable identity

Record prompt ID, name, purpose, owner, caller, task risk, languages, and status. A display name can change; a stable ID must not be silently reused for different semantics.

Exact template

Store every message role, content block, order, delimiter, and exact text, including system, task, fallback, citation, tool, and output rules. A UI screenshot is not the source artifact.

Variable schema

For every placeholder, define name, type, required state, source, length, allowed values, sensitivity, default, and missing-value behaviour. User data must not land accidentally inside a high-trust instruction slot.

Assembly rules

Fix interpolation, encoding, escaping, Unicode, markup delimiters, attachments, context, history, examples, and tool-schema insertion points and order; emit a final-render hash and token count.

Runtime combination

Link provider, model/deployment and exact version, API, tokeniser, temperature/top-p, max output, seed or other parameters, tool version, retrieval/context selector, and safety configuration.

Output contract

Define prose, JSON/schema, class labels, citations, tool calls, forbidden fields, insufficient/refused/error states, and downstream validators. Format instructions never replace parsing and schema validation.

Testing and approval

Link representative inputs, expected and prohibited results, automated and human metrics, adversarial cases, baseline, reviewers, approval date, known weaknesses, and release gates.

Release and fallback

Track draft, candidate, approved, active, and retired states, rollout scope, effective time, traffic, monitoring, rollback target, and old-version retention.

Message roles express source and priority relationships, not an impenetrable security layer

Placing content in a system, user, or tool role helps a model interpret its place in the exchange. It does not automatically make a fact true or a rule enforceable. Roles organise model input; authority and security still belong to controls outside the model.

Layer or objectTypical responsibility and limitation
System instructionDefines cross-task role, broad boundaries, insufficiency, and safety behaviour under application-owner control. APIs differ in priority and persistence, and compliance is not guaranteed.
Developer/application instructionExpresses product workflow, task policy, tools, and output contract. Some APIs support it separately and others require another role, so validate against the target interface.
User messagePreserves the user's request and material. It is input data and gains no authority to rewrite policy, access secrets, or expand tools merely from its role.
Assistant historySupplies earlier model output for continuity. It can be wrong, stale, or superseded and is not an approved fact or instruction.
Tool descriptionDescribes a tool, schema, and purpose. The application controls allowlists, credentials, access, invocation, confirmation, and side effects.
Tool resultReturns data or error for one invocation. External content may contain injection; preserve ID, source, time, and trust and never recast it as system policy.
Context blockHolds knowledge, records, and state needed by this task. Separate sources and define their use; commands found inside documents do not become prompt policy.

Final behaviour depends on the target model and API. Do not treat one vendor's roles or precedence as a cross-model standard. During migration, verify serialisation, role support, system instructions, tool loops, modality order, and token accounting.

Template variables are a data interface, not arbitrary string substitution

One placeholder might receive a user's words, authenticated identity, retrieved evidence, or a tool result. All are rendered as content, but they have different trust and permitted uses, so each variable needs interface-like provenance, typing, validation, and missing-value behaviour.

Type the slots

Separate original user query, trusted identity/state, retrieved evidence, tool results, examples, locale, and output options. Do not overload one `{input}` placeholder with every trust class.

Fix provenance

Declare whether each value comes from UI, authenticated session, business API, retrieval, configuration, or approval. Never let a model infer tenant, access, price, or approval state from prose and feed it back as trusted state.

Validate ranges

Apply deterministic checks for length, type, enums, dates, amounts, IDs, MIME, encoding, language, and nulls. High-risk fields require authoritative lookup and separate confirmation.

Retain raw and rendered values

Store raw input, normalised value, escaped/rendered value, and final position so cleaning does not silently alter negation, quotes, line breaks, code, tables, or multilingual text.

A delimiter is not a sandbox

XML tags, Markdown fences, quotes, and delimiters can aid structure but cannot prevent enclosed text from influencing behaviour. Still enforce trust, access, minimal tools, and output validation.

Missing and overflow states

For absent required variables, insufficient context, unsupported files, or token overflow, clarify, degrade, or stop under an explicit state. Do not insert an empty string and invite guessing.

Secrets are not variables

API keys, connection strings, raw credentials, and other users' data never enter a template. Tools use server-side identity and return only task-required fields.

Instructions should be clear, decidable, non-conflicting, and explicit about uncertainty

“Be accurate” and “sound professional” are sensible aspirations but weak acceptance conditions. An operational instruction tells the model what completion means and tells the surrounding application when to clarify, refuse, or stop because the evidence is insufficient.

Objective

Name a recognisable result, such as extracting fields from one request and identifying missing evidence, rather than asking for a “professional analysis.”

Scope

Bound objects, sources, time, language, and excluded work. Persona and tone serve the task but cannot replace scope.

Steps and decisions

Break complex work into externally checkable stages such as inspect, extract, compare, validate, and return. Do not require hidden chain-of-thought; request explicit evidence, calculations, and reason codes that need audit.

Priority and conflicts

“Be concise” can conflict with “be complete,” and “use only sources” with “always answer.” Define priority and handling for source conflicts, user corrections, and rule exceptions.

Insufficiency and ambiguity

Define triggers for clarify, unknown, insufficient, access denied, tool failed, and refusal so the model does not invent facts to satisfy a demand to answer.

Prohibited outcomes

List disclosure, inference, automatic approval, execution, and treatment of model output as fact that are disallowed. Critical prohibitions also require code, access, and human gates.

Verifiable output

Connect conclusions to source or field, distinguish observation from inference, and return statuses or schemas so validators and reviewers can decide rather than merely demanding accuracy.

Few-shot examples define task shape and can also carry bias and leakage

Examples can communicate label boundaries and output shape more readily than abstract rules, but they also carry wording, class balance, and even concrete values into the live task. Whether a small set truly helps is an evaluation question, not something a successful demonstration settles.

Purpose

Examples clarify label boundaries, input–output mapping, format, exceptions, and insufficiency. The original GPT-3 study demonstrated in-context few-shot use through text task descriptions and demonstrations, not equal success for every task or model.

Representative coverage

Include normal, boundary, exceptional, insufficient, conflicting, and multilingual cases rather than only easy positives. Let incremental evaluation and token cost determine count.

Paired input and output

Mark example input, expected output, and explanation clearly. Facts, IDs, and tool calls inside example output must never leak into the live task.

Order and label distribution

Example order, class ratio, wording, names, and the most recent label can influence output. Regress permutations and paraphrases rather than treating one arrangement as truth.

Real-data risk

Examples are sent and logged with the prompt. Prefer synthetic or authorised low-risk material, remove secrets and personal data, and consider rare-combination reidentification.

Prevent test leakage

Do not turn acceptance cases and answers into few-shot examples and report gains on that same set. Separate prompt tuning, validation, and final test sets.

Examples are not a rules engine

Amounts, access, tax, eligibility, and approval belong in code or authoritative services. Examples demonstrate a task; they cannot enumerate all combinations.

Schemas and validators must enforce the output contract together

Telling a model to “return JSON only” expresses an expectation; it does not prove that fields are complete, amounts are plausible, or the caller may access an object. The contract must cover shape, parse failure, business validation, and safe downstream handling before a result can advance.

Output formBoundary of use
Natural languageUseful for explanation, summary, and dialogue. Define citations, insufficiency, and forbidden assertions; never use it directly as a database field or execution instruction.
Fixed labelsUseful for classification and routing. Define the complete label set, unknown/other, multilabel rules, confidence or evidence, and reject out-of-set output.
JSON/schemaUseful for application parsing. Prefer native structured-output or tool-schema support, then validate parsing, types, enums, required fields, and business rules. “Return JSON only” still fails.
Tool callLets a model propose a tool and arguments. A proposal is not authorisation; the application validates schema, identity, scope, idempotency, and human approval before execution.
Cited answerConnects each claim to source ID and location. Verify the cited content supports the text, not merely that a URL exists.
Decidable non-completionUse structured statuses for insufficient, ambiguous, access_denied, unsupported, tool_error, and refused so the system can clarify, retry, hand off, or stop.

Parse-failure path

Set repair retries, whether an independent repair step is allowed, preservation of raw output, and the stop point. Do not feed invalid output back indefinitely.

Content and shape gates

Schema validity proves shape only; facts, access, amounts, business state, and safety still need validation. Correct content also needs safe encoding before HTML, SQL, shell, or other sinks.

Prompts define how to use context; they do not retrieve the right evidence

An unsupported answer can begin with failed retrieval or with poor use of evidence that was retrieved. Check whether the right material reached final context before judging the instruction, otherwise repeated wording changes merely hide a recall problem.

Separate the parts

A RAG prompt commonly separates stable system message, scenario instruction, context block, user query, and optional examples. Each has an owner and version.

Preserve the original need

Query rewrites, summaries, and routing are derived items; retain user wording, identity, time, and task. A prompt must not silently alter negation or target.

Source boundaries

Label chunks with source ID, version, location, and validity and define citation rules. Retrieved content is data even when it says to ignore earlier instructions.

Meaning of source-only

Require verifiable claims to be supported by context and stop on insufficiency. This neither proves that parameter knowledge was unused nor makes a wrong source correct.

Diagnose retrieval and prompt separately

First check whether correct evidence entered candidates and final context, then whether the prompt led to proper use. Wording changes rarely repair missing recall.

Conflict and insufficiency

State how to present conflicting sources or apply authorised precedence without fluent merging. Missing evidence triggers clarification, re-retrieval, tools, or humans.

Shared context budget

Instructions, query, evidence, history, tool schemas, and output share tokens. More rules or examples can evict decisive evidence, so count the full combination.

Prompts and inference parameters form one runtime combination but remain separately diagnosable

The same prompt can behave differently with another model, temperature, or output limit, while identical parameters do not erase template differences. Bind both in a release and record them separately so a change can be attributed rather than guessed.

Model dependency

Role following, formatting, and safety differ by provider, model family, snapshot, language, and modality. Migration requires a new combination evaluation, not just a model-name replacement.

Temperature and top-p

They influence sampling distributions, not factual correctness, and semantics differ by API/model. Do not change several parameters and attribute the result to prompt wording.

Maximum output

Too little truncates JSON, citations, or conditions; too much adds cost and unbounded-generation risk. Derive it from the output contract and monitor finish reasons.

Seed and determinism

Some APIs expose seeds or more stable modes without guaranteeing identical output across infrastructure and versions. Acceptance uses ranges, repeated samples, and prohibited events.

Stop sequences

They can bound output but can also occur in user content, code, or another language. Test with the target tokeniser, schema, and streaming behaviour.

Tokeniser and wrapper

Providers can transform messages into model-specific templates. Retain API requests and usage; source character count or home-grown concatenation is not the actual prompt.

One main variable

When comparing prompt variants, hold model, parameters, context, tools, data, and evaluator fixed. When comparing models, document unavoidable interface adaptations.

Agent prompts describe decisions and tools but cannot grant tool authority

In an agent workflow, a prompt can describe available tools, selection guidance, and stopping conditions. It should never serve as the credential. Whether a write occurs still depends on the current principal, validated arguments, risk confirmation, and authorisation at the tool boundary.

Task and stopping

Define objective, acceptable completion, maximum steps/cost/time, clarification, human handoff, and stopping. “Continue until successful” is not authorisation for an infinite loop.

Tool selection

Expose the minimum set with clear names, descriptions, typed inputs/outputs, prerequisites, and error states. Similar tools need decidable routing boundaries.

Observe and replan

The original ReAct work demonstrated interleaved reasoning, action, and environment observations. Production retains externally auditable plans/actions/results rather than depending on hidden reasoning text.

Confirm parameters

Separate user-stated, trusted-state, and model-inferred values. Re-display and risk-confirm payees, amounts, addresses, publication scope, and destructive options.

Access at the tool

Every invocation uses current subject and minimum scope, with authorisation repeated by the service. “Only access my data” in a prompt is not object-level permission.

Side effects

Separate read and write tools; writes have dry run, idempotency keys, approvals, timeout/unknown handling, and receipts. No receipt means the model cannot claim success.

External observations

Pages, mail, files, tool results, and memory can contain injection. Separate, minimise, and inspect them as data; they cannot expand the tool list or rewrite objectives.

Delegation

Define which instructions, context, credentials, budgets, and audit data a sub-agent inherits. A parent prompt cannot assume an untransmitted policy is understood.

System prompts can reduce risk but cannot hold secrets, access, or the security boundary

Writing prohibitions into a system prompt is useful, but it remains behavioural guidance. Once a model can read external content or invoke tools, the project must assume untrusted data may influence it and keep real secrets, permissions, and high-risk action controls in deterministic systems.

Direct prompt injection

User input tries to change higher-trust instructions, bypass restrictions, extract prompts, or widen tools. NIST classifies this as adversarial attack; scope, minimal capability, detection, and independent enforcement reduce impact.

Indirect prompt injection

Instructions hide in retrieved documents, pages, mail, images, or tool results. RAG, fine-tuning, and delimiters do not eliminate it; trust layering and end-to-end red teaming remain necessary.

System-prompt leakage

OWASP notes that secrets, credentials, and actual access logic do not belong in system prompts. Even if undisclosed, session and authorisation cannot be delegated to an LLM.

Input minimisation

Accept only task-required data, allowlist and inspect attachments, URLs, MIME, sizes, encodings, and sources, and exclude other tenants, secrets, and internal chains.

Untrusted output

Before model output enters HTML, Markdown, SQL, shell, paths, mail, APIs, or memory, apply sink-specific validation and encoding. A prompt prohibition is not output safety.

Minimum agency

Limit tools, scope, frequency, amounts, network, and egress and require human approval for high-risk actions. Impact depends on application capability, not only whether the model emits disallowed text.

Prompt-log privacy

Prompts, variables, and traces can contain personal, contractual, policy, and attack data. Encrypt by classification, restrict access and retention, and separate test artifacts from production logs.

Continuous adversarial testing

Cover languages, encodings, misspellings, split payloads, long conversations, role confusion, few-shot poisoning, tool echo, memory poisoning, and hidden multimodal instructions after model or prompt updates.

Review, release, roll back, and retire prompts like production configuration

Changing one word can shift a class boundary, refusal rate, or tool argument, so editing a prompt in a remote console is still a production change. Versioning is not just numbering copy; it identifies what changed, what it can affect, and which approved state remains available.

Make the source of truth findable

Keep templates, schemas, variables, and metadata in a controlled repository or prompt registry so reviewers can see the semantic change. If the only copy lives as an unexported console draft, the team cannot reproduce it reliably or know which version to restore during an incident.

Semantic versions

Text, role, order, examples, fallback, schema, tool descriptions, and parameter references can all change behaviour. Assign an immutable version and intended effect.

Variant experiments

Products such as Amazon Bedrock support variants and versions. Regardless of tooling, fix traffic, test sets, metrics, sample size, and stop rules; a variant name is not evidence.

Review responsibilities

Business owners confirm tasks/rules, domain reviewers evidence/terms, engineering assembly/parsers, security/privacy data and agency, and QA coverage/statistics.

Release binding

Bind the active prompt version to application release, model, retrieval/context, tool, schema, and safety configuration. Editing a remote prompt is still a production change.

Canary and monitoring

Release first to low-risk, internal, or small traffic and compare quality, safety, latency, cost, and handoff by task and language. Record the actual version for every request.

Rollback

Retain a prior approved version and compatible schemas/tools with triggers and ownership. If a bad action already occurred, reverting the prompt is not business recovery.

Retirement

Stop traffic, revoke caches and references, process sensitive test/log material, preserve necessary audit evidence, and verify old clients cannot invoke a retired version.

Evaluate fixed combinations on representative tasks and counterexamples, not selected good answers

A polished answer chosen for a demonstration proves only that the system can sometimes do well. Acceptance fixes the model, context, and tools, then runs normal, boundary, insufficient, conflicting, and adversarial cases together to expose gains and regressions.

Fixed baseline

Hold model/API, context, retrieval, tools, parameters, and evaluator fixed against the approved prompt, or hold prompt fixed for model comparison while documenting interface adaptation.

Representative set

Cover normal, boundary, exceptional, ambiguous, insufficient, conflicting, historical, unauthorised, multilingual, long-input, format-noise, and high-risk-action cases rather than author-written easy examples.

Task metrics

Use precision/recall and confusion for classification, exact/normalised field match for extraction, relevance/groundedness/citation for RAG, and tool choice/arguments/task success for agents.

Prohibited events

Leakage, unauthorised access, wrong submission, fabricated sources, missed negation, invalid schema, infinite loops, and confident insufficiency each have gates and are not offset by averages.

Repetition and perturbation

Resample cases and vary paraphrase, spelling, whitespace, order, example permutations, context length, and parameters. PromptBench highlights dynamic and adversarial evaluation.

Automated and human

Prefer deterministic validators for schema, IDs, calculations, and citations. An LLM judge can assist semantics but needs bias validation; authorised people adjudicate business correctness and risk.

Statistics and slices

Report counts, intervals, and per-case wins/losses, slicing by task, language, user group, source quality, risk, and input length rather than one overall pass rate.

Prevent overfitting

Separate prompt-tuning, validation, final test, and production-shadow sets. Do not append a special instruction for every failure without comparing maintainability and new regressions.

Operate quality, tokens, latency, cost, and drift together

Passing a test set does not make a prompt maintenance-free. Real requests change in length, language, and evidence quality, and model providers may update behaviour, so quality, latency, and cost need one continuing operational view.

Token breakdown

Record system/task, variables, history, context, examples, tool schemas, input, and output tokens separately to identify rule and schema growth.

Latency

Measure P50/P95/P99 for assembly, token counting, provider queue, prefill/time-to-first-token, generation, tool loops, validators, and retries, separating streaming first byte from completion.

Cost

Attribute input/output, cache, retrieval, tool, retry, and human review to a successful task. A larger variant must demonstrate quality or risk benefit.

Quality drift

Monitor structured parsing, fallback, insufficiency, citations, tool errors, corrections, and handoffs and sample real inputs. Model/provider updates and query-mix changes can age a prompt.

Security signals

Track injection detections, access attempts, secret patterns, anomalous calls, output blocks, and repeated attacks while restricting payload-log access.

Degradation

For registry, model, retrieval, tool, or schema failure, define approved fallback, read-only mode, fixed form, human handoff, or stop. Never invent an untested production prompt.

Handover

Transfer source templates, variable schemas, renderer, version registry, combination dependencies, tests/evaluators, dashboards, runbooks, rollback, provider limits, and known failures.

Prompt contract for procurement-request extraction

This example illustrates a prompt contract rather than providing a production-ready template. Fields, rules, models, thresholds, access, and outcomes are constructed.

Purpose

Extract candidate fields and flag missing or conflicting material from a procurement note and authorised attachments for employee review. Do not approve, decide compliance, or write to ERP.

Controlled instruction

Extract only from labelled user material and source context, separate quoted, normalised, and inferred values, return `insufficient` for unknowns, and never copy example values as facts.

Typed variables

Separate `request_text`, `attachment_text`, `current_user`, `organisation`, `locale`, and `allowed_field_schema`. Identity comes from session and schema from approved configuration; material remains untrusted data.

Examples

Use synthetic normal, missing-amount, currency-conflict, multi-supplier, and malicious-attachment examples with expected fields/status/citations. Keep tuning examples separate from final tests.

Output

Native structured output constrains requestId, supplierCandidate, amount, currency, neededEvidence, conflicts, status, and sourceLocator. Parsers then validate types, values, IDs, and access.

Stop

Unreadable attachments, unauthorised sources, decisive conflicts, incompatible schema, invalid output, and unknown tool states must not create a submittable record; return a typed error and hand off.

Version

Prompt P1 binds model M1, schema S1, parser V1, test set T1, parameters C1, and release R1. Any change creates a new combination with rendered hash and request trace.

Acceptance

Report field correctness, omission, unsupported completion, citations, schema, access/injection, safety, P95, and cost per successful task by scenario, with zero-tolerance failures separate.

Prompt compared with adjacent concepts

A prompt touches context, tools, business rules, and output schemas, which makes it easy to mistake for the whole AI system. Separating these objects gives content design, factual authority, execution rights, and validation to the right owners.

ConceptBoundary from a prompt
User inputThe user's question or material, used as a lower-trust variable or message. The complete prompt also includes application instructions, context, tools, and output contract.
System promptThe higher-trust application's cross-task instruction layer. It is one component, not the complete input or a security boundary.
Prompt templateA reusable structure with typed placeholders. A concrete call becomes an actual prompt after variables, context, history, and tools are rendered.
ContextRuntime information selected for this task. The prompt presents and governs use, but context has separate provenance, access, time, and selection responsibilities.
Few-shot promptingA method placing a small number of input–output demonstrations in a prompt. It is optional rather than required for all prompts.
Prompt engineeringThe process of designing, experimenting, evaluating, and iterating. A prompt is the concrete input artifact managed by that process.
Inference parametersTemperature, top-p, maximum output, and related generation configuration. They are not natural-language prompt text but belong to the runtime combination.
Structured outputAPI or schema constraints on output shape. Prompts can describe semantics, while the application must still parse and validate business meaning.
GuardrailAn independent policy, filter, or control around inputs or outputs. A system message can supplement but not replace guardrails and deterministic controls.
Business ruleAn authoritative obligation deciding business conditions and outcomes, managed in controlled logic and formal sources. A prompt only guides how a model cites or proposes application.
Fine-tuningTraining that updates model parameters. A prompt is supplied at inference and does not change weights; their versions and evaluations remain separate.
Agent workflowThe complete system of decision loops, tools, state, access, retries, and human control. A prompt is one artifact guiding some model steps.

Sources and scope

This entry explains a prompt in an enterprise generative-AI, RAG, or agent project: the versioned input structure an application submits in one model call to express the objective, instructions, constraints, input variables, context boundaries, examples, tool descriptions, insufficiency behaviour, and output contract. A prompt can comprise system, developer, user, assistant, and tool messages and text, image, audio, or document content blocks; actual roles and capabilities depend on the model API. A prompt is not synonymous with the user's wording, context, a system prompt, a few-shot example, output schema, inference parameters, model training or fine-tuning, guardrails, business rules, code validation, retrieval, a tool, model output, or a complete agent workflow. Those can be components, external controls, or adjacent objects. Length, politeness, the word “must,” or a hidden system prompt cannot guarantee compliance, security, factual correctness, or repeatability. No universal prompt, template, temperature, or example count is best across models, versions, languages, tasks, and risks. This entry does not fully define every prompt-engineering technique, linguistics, model architecture, chain-of-thought research, fine-tuning, RAG, agent protocols, content safety, or vendor APIs. Review a production prompt with its model, context, tools, parameters, test data, and application controls.