Contents
  1. Inputs and instructions
    1. Changing inputs, keeping weights fixed
    2. Specify the intended task
  2. Demonstrations and their origins
    1. Learning from examples in context
    2. From continuation cues to instructions
  3. Choosing and presenting examples
    1. Select examples for useful coverage
    2. Order and formatting can change behavior
  4. Testing prompt changes
    1. Separate development from assessment
    2. Interpret controlled comparisons
    3. Evaluate requests for intermediate steps
  5. Transfer and next decisions
    1. Bound the transfer claim
    2. Choose the next intervention
  6. Check understanding
  7. Open questions
  8. Selected talks
  9. References
  10. Talk library
← All topics

Prompting and In-Context Learning

Prompting gives a general language model a particular job. An instruction describes the operation; examples can clarify the distinctions or response conventions that matter. The engineering challenge is to make that intended behavior clear, then establish whether the resulting prompt works beyond the cases used to develop it.

Inputs and instructions

Changing inputs, keeping weights fixed

A prompt supplies a language model with the task and information it should use to respond. The model predicts text using numerical values learned during training, called parameters or weights. Using those learned values to produce an output is inference; changing the prompt changes the input to that process, not the weights. Parameters and modeling assumptions explains their role.

The model processes text as tokens, encoded units that can represent words, fragments or punctuation; Tokenization explains that representation. Predictions depend on the supplied input, a relationship called conditioning. Different instructions or examples can therefore guide different responses through the same weights. The computation produces temporary state, including any cached intermediate results, but that state is separate from the learned parameters. Following a convention in one request does not by itself make that convention available in a later request.

Different inputs, shared parameters

Request information changes the computation without updating the shared weights.

Each inference uses its own input and the same learned parameters to produce a response. Arrows show dependencies, not timing or concurrent execution. No training update is depicted.
Read the diagram as text
  • Prompt A. Instructions and context for one request.
  • Prompt B. Different request information.
  • Fixed learned weights.
  • Inference A.
  • Inference B.
  • Response A.
  • Response B.
  • Prompt AInference A: Request input.
  • Prompt BInference B: Request input.
  • Fixed learned weightsInference A: Shared parameters.
  • Fixed learned weightsInference B: Shared parameters.
  • Inference AResponse A: Generates.
  • Inference BResponse B: Generates.

This separation makes prompting useful: behavior can be adapted without a training run. This chapter concerns the instructions and demonstrations that guide a call. Context Engineering covers the broader application responsibility of selecting and maintaining everything supplied across calls, including history, external information and tools.

Specify the intended task

An instruction describes an operation and expectations for its response. Specify the input, relevant constraints, intended use and treatment of uncertainty. Output style matters when it serves that use, but it cannot resolve an undefined decision rule. For example, requiring a short answer says little about which category the answer should name. Anthropic's prompting guidance recommends explicit requirements and explanations of their purpose.

Consider a constructed specification for classifying messages. The purpose is to identify whether the sender requests an action, rather than merely detecting question marks or imperative verbs. Each clause below removes a different ambiguity.

Instruction clauseWhat it specifies
Classify the supplied message by its communicative purpose.The operation and unit of input.
Use REQUEST when it asks the recipient to act, including polite questions.The category meaning; grammatical form alone does not decide it.
Use REPORT when it describes a condition without asking for action.The contrasting category boundary.
If a message both reports a condition and requests action, use REQUEST. If its purpose is insufficiently clear, use UNCLEAR.A policy for mixed messages and uncertainty.
Return exactly one of REQUEST, REPORT or UNCLEAR.The requested response format.

A prompt template keeps reusable instructions separate from request-specific variables, such as the message to classify. For a repeated API task, revise that reusable template when a failure exposes a missing rule. Correcting one answer later in a chat does not improve the independently invoked template.

Before blaming the model, check that the requirements agree and the necessary facts are present. Demanding exactly one bullet and several bullets is contradictory. In the Prompt Doctor workshop, an apparent scheduling failure became acceptable uncertainty once the participants established that service availability had deliberately been omitted.

Chat APIs label contributions with roles such as user and assistant. A model-specific chat template serializes these messages into the sequence the model expects; incompatible markers can impair behavior. Chat templates explains that interface. Within it, a format instruction remains a request. Schema-constrained generation adds structural enforcement, but valid structure can still contain wrong values. Structured Outputs and Tool Calling develops that distinction.

Demonstrations and their origins

Learning from examples in context

A demonstration pairs an input with its desired response inside the prompt. Zero-shot supplies none; one-shot supplies one; few-shot supplies several. These counts concern the request, not training exposure. Demonstrations show how to respond, whereas background facts supply information to use. Training examples participate in an operation that updates parameters; prompt demonstrations condition inference with fixed weights.

In-context learning describes adapting behavior from information or patterns in the current input without a parameter update. The practical objective is generalization: useful behavior on inputs not shown in the demonstrations. Fit, select, and assess explains the broader distinction between fitting examples and succeeding beyond them.

Examples guide a new response

Example

Demonstrations and the unanswered query have different roles in the same request.

Constructed example: dax denotes requests and wug denotes reports. The expected answer for the new query is dax; no model result is reported.
Read the diagram as text
  • Classify by communicative purpose. Use the demonstrated label convention.
  • Demonstration pairs. Send the log. → dax The log is attached. → wug
  • New query. Could you send the log?
  • Inference with fixed weights.
  • Expected response: dax. A polite question requests an action.
  • Classify by communicative purposeInference with fixed weights: Task instruction.
  • Demonstration pairsInference with fixed weights: Demonstrated associations.
  • New queryInference with fixed weights: Unanswered input.
  • Inference with fixed weightsExpected response: dax: Target response for query.

Demonstrations can communicate response conventions that are awkward to describe fully. A coding example can show the required component syntax and styling convention; paired writing briefs and finished pieces can show a client's tone. In both cases, the example supplies a pattern to apply to a new input. Whether the model follows it still needs testing.

For the classification illustration below, replace familiar category names with dax for requests and wug for reports. Unfamiliar labels make the supplied association matter. Research using unrelated label names found that some tested models followed these mappings more successfully than others. Correctly answering one new message would establish local success, not a particular internal learning algorithm.

From continuation cues to instructions

The distinction between training a model and adapting through its inputs predates language-model prompting. In 2001, Hochreiter, Younger and Conwell investigated learning to learn, also called meta-learning: training a system to acquire a procedure for learning related tasks. Their recurrent network carried information from successive inputs and previous target values in its internal state while predicting changing numerical functions. Training shaped its ability to adapt; new examples supplied information for that adaptation. This provides a conceptual precedent involving numerical tasks rather than language instructions.

GPT-2's 2019 experiments communicated tasks through continuation cues: a summary cue followed an article, while translation used sentence pairs and an unfinished pair. These formats directed completion, although generated summaries still confused details.

GPT-3's 2020 study made inference-time demonstration counts an explicit comparison: task descriptions alone, one demonstration and several demonstrations, all without task-specific weight updates. This helped distinguish adaptation through a request from adaptation through training.

A complementary problem was making models more responsive to direct instructions. Instruction tuning updates a pretrained model's weights using tasks expressed as instructions and examples of desired responses. FLAN, first reported in September 2021, studied this approach. Its evaluation withheld entire groups of task types from instruction tuning and compared the resulting model with its untuned counterpart. The tuned model performed better on those unseen task types, although their exclusion from instruction tuning did not establish their absence from pretraining.

The BigScience T0 project, first reported in October 2021, trained on multiple tasks expressed through varied prompts. More prompt formulations per dataset improved median held-out performance and reduced prompt variability in its experiments. This was a training intervention; adding paraphrased instructions to one request is a different operation.

Training for instruction following and supplying completion cues address different parts of the interaction. A base model—a pretrained model before instruction tuning—may continue a coding request with descriptive prose, while a function definition and docstring elicit code, as illustrated in Decoding Mistral AI's Large Language Models. The example shows how an unhelpful response can reflect the interaction format rather than missing coding capability. Training changes the model's responsiveness; instructions and demonstrations still specify what it should do in a particular call. Post-training and Alignment explains parameter adaptation.

Choosing and presenting examples

Select examples for useful coverage

Choose demonstrations for the distinction they communicate. First verify that their desired responses follow the task specification. Then consider relevance and coverage: which important cases the set represents. Repeated direct requests may leave polite questions unexplained. A contrasting example can clarify that boundary more directly than another near-duplicate. Negative examples are useful when their explanation identifies a misconception, rather than merely declaring an answer bad.

When different requests need different examples, dynamic few-shot selection chooses demonstrations for each query from a larger collection. It can use explicit rules, such as matching a category, or search for example inputs similar in meaning to the query. Search and Retrieval explains how to find such candidates. The selection procedure must still choose a set that demonstrates the intended behavior together.

Repetition and added coverage

Example

A different surface form can add coverage that another direct request does not.

Constructed demonstrations all have label REQUEST. Two repeat imperative wording; the third demonstrates a polite question. Coverage makes the third worth testing, not a guaranteed performance improvement.
Read the diagram as text
  • Send the log.. Desired label: REQUEST
  • Restart the application.. Desired label: REQUEST
  • Could you restart the application?. Desired label: REQUEST
  • Imperative wording can request action.
  • Question wording can request action.
  • Send the log.Imperative wording can request action: Demonstrates.
  • Restart the application.Imperative wording can request action: Demonstrates.
  • Could you restart the application?Question wording can request action: Demonstrates.

KATE tested similarity selection for sentiment classification: deciding whether text is positive or negative. It prompted GPT-3 with three labeled sentences from SST-2, a sentiment dataset, and assessed predictions on IMDB movie reviews, keeping the generation setting fixed at temperature zero. Random selection averaged 87.95% accuracy, with a 2.74-point standard deviation across five runs. Similarity selection using an unchanged RoBERTa-large encoder, which represents text numerically for comparison, achieved 91.99%. Selection also determined example order, so the result compares selection procedures rather than isolating similarity alone.

Selecting each example independently can nevertheless produce a redundant set. Coverage-based selection research found its strongest benefits on compositional semantic parsing—turning language into programs or queries that combine operations. The method did not consistently improve ordinary classification or numerical reasoning. Useful diversity depends on the task.

Examples also compete for capacity. The context window bounds the tokenized sequence available to a request. When input and output share that allowance, adding demonstrations leaves less room for the query or response. Count the complete input, including instructions and template overhead, and reserve output space while respecting any separate input and output limits. For models that generate internal reasoning tokens, that reservation must cover them as well as the visible answer. Counting complete requests covers the accounting. Caching reuses processing of an unchanged input prefix; it can lower processing cost but does not free context capacity.

More available space does not imply steadily improving results. Many-Shot In-Context Learning tested the original February 2024 Gemini 1.5 Pro using smaller demonstration sets nested inside larger ones and repeated selections. On 150 test articles from the XSum news-summary dataset, scores improved through roughly 50 examples and then declined. Using XSum demonstrations to summarize articles from another dataset, XLSum, generally improved with more examples. Scores used ROUGE-L, a measure of overlap with reference summaries; fabricated dates and times still occurred. These different curves give no universal shot count, and overlap scores do not establish factual accuracy.

Order and formatting can change behavior

Prompt sensitivity is behavioral variation associated with changes in wording, examples, order or presentation. Some edits change the task. Others intend to preserve its meaning but change the sequence the model receives. These require different interpretations.

EditWhat remains fixedWhat the comparison tests
Reorder demonstrationsExample identities and intended taskOrder sensitivity
Change separators or label capitalizationExample identities, order and intended meaningPresentation sensitivity
Redefine mixed messages as REPORTThe input messagesA changed task specification

A controlled order study evaluated all 24 permutations of four fixed, balanced SST-2 sentiment demonstrations across GPT-2 and GPT-3 sizes. Accuracy varied substantially, and effective orderings correlated weakly across models. Increasing example counts did not reliably remove the variation. These historical results establish order as a variable worth testing, not a preferred permutation for current models.

Label bias is a preference for an answer label that need not follow the current input's meaning. Experiments found preferences for frequent demonstration labels, recently shown labels and familiar answer tokens. Balanced examples expose each class, but do not necessarily reproduce deployment prevalence or remove other biases. Choose the class mix against the intended workload and consequences of errors.

Formatting can also change token boundaries, although tokenization alone does not explain every sensitivity result. Consistent separators help distinguish instructions, examples and query. The Prompt Doctor workshop's useful clarification was that clear separation mattered more than XML itself. Such markers do not enforce a security boundary: external text can still be interpreted as instructions. Context Engineering covers handling that untrusted input.

Testing prompt changes

Separate development from assessment

Define success before selecting a prompt. For the message classifier, distinguish a correct category from a correctly formatted response, and identify consequential mistakes such as overlooking a request embedded in a report. Establish a baseline, the reference configuration: a clear instruction-only prompt and, when one exists, the prompt already in use. Include conventional code when it is a meaningful alternative.

Start by saving baseline responses on concrete cases and rerunning those cases after a change. The Prompt Doctor workshop demonstrates why this helps: improved formatting did not automatically resolve the remaining behavioral failures. This establishes a useful development practice, but the cases that guide revisions are not independent evidence about the selected result.

Keep final assessment outside selection

Development feedback changes the prompt; held-out results assess the frozen choice.

One revision is unrolled. Final assessment has no feedback edge into selection. Reusing its results to revise the prompt requires a new independent assessment.
Read the diagram as text
  • Demonstration pool.
  • Development cases.
  • Evaluate candidate.
  • Revise and re-evaluate.
  • Frozen choice.
  • Baseline.
  • Held-out cases.
  • Final paired assessment.
  • Demonstration poolEvaluate candidate: Available examples.
  • Development casesEvaluate candidate: Development inputs.
  • Evaluate candidateRevise and re-evaluate: Selection feedback.
  • Demonstration poolRevise and re-evaluate: Available examples.
  • Development casesRevise and re-evaluate: Re-evaluation inputs.
  • Revise and re-evaluateFrozen choice: Select after development.
  • Frozen choiceFinal paired assessment: Candidate configuration.
  • BaselineFinal paired assessment: Reference configuration.
  • Held-out casesFinal paired assessment: Shared assessment inputs.

Separate three uses of examples. The demonstration pool supplies material that may enter prompts. Development cases provide feedback for choosing instructions, examples and presentation. A held-out assessment evaluates the frozen choice without guiding its selection. The True Few-Shot Learning study showed why visible shot count understates development effort: selecting a prompt can require many more labeled examples than appear inside it.

Leakage occurs when assessment information crosses that boundary. Putting a test answer into a demonstration is an obvious route; splitting near-duplicates or related messages across pools can also weaken the intended test. Adaptive overfitting occurs when repeated test feedback guides prompt selection. The weights can remain unchanged while the prompt becomes specialized to the repeatedly consulted cases. Keep assessment independent explains these routes.

Record the full comparison configuration: model version, surrounding input, chat template, demonstration identities and order, generation settings, attempt limits, output allowance and scoring procedure. Preserve relevant conversation turns, not just the instruction template. A workshop reproduction of a JSON reviewer needed upstream tests that had arrived through conversation history; changing that history or the model changed the experiment.

Use shared cases and explicit budgets throughout development. Once the candidate is frozen, compare it with the baseline on held-out cases. If those results drive another revision, they have become development feedback; a fresh independent assessment is needed for the revised choice.

Interpret controlled comparisons

A paired comparison evaluates alternatives on the same cases, making it possible to see which answers changed from wrong to right and which regressed. An ablation removes or changes a component to investigate its contribution. Decide whether the experiment compares complete prompt packages or isolates a narrower change. Holding other conditions fixed makes that distinction interpretable.

Use these contrasts during development; each supports a different explanation.
ComparisonHold fixedInterpretation
Instruction-only versus demonstrationsInstruction, model and assessment protocolEffect of adding this demonstration package, including its length
Two example setsExample count, formatting and ordering ruleEffect of set composition; equal counts need not have equal token lengths
Permutations of one setExample identities and formattingOrder sensitivity
Alternative presentationExample identities, order and intended meaningSensitivity to the tested formatting choices

FormatSpread held demonstration identity and order fixed while varying separators, capitalization and option numbering. Across 53 tasks and the tested model and demonstration-count settings, the median gap between the best and worst of ten sampled formats was 7.5 accuracy percentage points. The study used Llama-2 and Falcon variants; its principal scoring method chose answers by their model-assigned probabilities. This measured sensitivity within the tested format choices. It does not predict a gain of 7.5 points from reformatting a current application's freely generated responses.

Every assessed case in a binary correctness comparison belongs to one of four outcomes. This is bookkeeping, not a measured dataset.
BaselineCandidateContribution to the change
CorrectCorrectPreserved success
WrongCorrectImprovement
CorrectWrongRegression
WrongWrongUnresolved failure

For equally weighted cases, subtract regressions from improvements and divide by the number of assessed pairs to obtain the accuracy difference. Then inspect task slices, relevant subsets such as mixed messages or polite requests. A positive total can conceal unacceptable regressions on a consequential slice. Repeatable evaluations expose these tradeoffs more reliably than choosing whichever response looks most impressive.

Record complete input length, output usage and measured latency separately from correctness and format compliance. Prespecify repeated trials when output variation matters, and retain the same attempt policy for alternatives. If several components changed, the result belongs to the bundle. It does not establish which component caused the gain.

Finally, assess uncertainty in the difference, not only the two headline scores. A small apparent gain can remain inconclusive, particularly on rare but important cases. The independent comparison supports the frozen candidate under the tested conditions; it does not establish superiority on other tasks or models.

Evaluate requests for intermediate steps

Chain-of-thought prompting asks for, or demonstrates, intermediate reasoning before an answer. The 2022 demonstrated method added worked steps to input-answer examples and reported gains on tested arithmetic, commonsense and symbolic tasks. It changed both the information supplied and the generated work, so those gains do not establish equal-cost superiority.

A zero-shot request asks for intermediate steps without worked demonstrations. The published 2022 zero-shot protocol used two stages: generate reasoning, then append an answer-extraction instruction and generate the final answer. Reproducing that result requires retaining the additional stage; it was not simply a one-call wording change.

Compare such a protocol with direct answering under explicit call and output limits, and measure actual usage and latency. Score the answer independently of the explanation's fluency. Experiments on GPT-3.5 and Claude 1.0 found that answer suggestions and demonstration positions influenced predictions while explanations often omitted those influences or rationalized mistakes. Plausible explanatory text therefore need not faithfully account for what changed the answer.

Deliberation is additional work toward a solution; verification checks a proposed result against independent criteria. Reasoning and Test-Time Compute develops those mechanisms. Here, requesting intermediate steps is another prompt choice to evaluate for the particular model and task.

Transfer and next decisions

Bound the transfer claim

Finite demonstrations can support several interpretations. A model may recognize a familiar task, copy its response conventions or apply a newly demonstrated mapping. In classification and multiple-choice experiments, randomized demonstration labels often retained much of the benefit; label vocabulary, input distribution and formatting each contributed. Thus, improved output alone need not show that the intended input-label rule was learned.

Unfamiliar-label experiments probe a different ability: following associations supplied locally. Some models succeeded, while others relied more on familiar label meanings. Instruction-tuned PaLM variants improved at unrelated labels but resisted demonstrations reversing familiar meanings. These contrasting results show why a single account of what demonstrations teach is insufficient.

Compositional generalization means applying operations in combinations absent from demonstrations. Coverage-based selection helped particular compositional parsing splits more than ordinary classification. That is a narrower achievement than general transfer. Likewise, order preferences differed across tested models, and many-shot summarization gains changed with the evaluation dataset.

Design the test around the condition that changes. Distribution shift means that input–outcome conditions differ from those used to establish performance. Merely calling every assessment input new does not specify how demanding a transfer claim is.

These are proposed checks, not claims that transfer has been established.
ClaimWithhold from prompt developmentWhat remains fixed
Fresh inputs in the same taskAssessment cases and related duplicatesInstructions, demonstrations, order and format
New combinations or task familiesThe relevant combinations or whole familiesThe selected prompting procedure
Another domain or languageTarget-domain or target-language feedbackThe source prompt; translation or target examples constitute adaptation
Another model or versionTarget-model selection feedbackPrompt content and declared protocol; document required serialization changes

For dynamic selection, freeze the selector and example pool while allowing the query to determine the selected examples. The claim then concerns transfer of a procedure, not identical demonstration text. If target results guide revisions, describe the outcome as target adaptation and assess the revised procedure independently.

Choose the next intervention

When prompt revisions stop helping, several explanations remain possible. The task may be unclear, demonstrations may miss a boundary, necessary information may be absent, or the model may struggle with the required operation. A plateau does not distinguish these causes. Investigate a specific hypothesis instead of accumulating more instructions.

Use each observation to propose a comparison, not to declare a diagnosis.
Observed limitationCompeting explanationsUseful next comparison
Errors near a category boundaryAn ambiguous rule or inadequate demonstrationsClarify the rule; separately test demonstrations covering that boundary
Uncertainty about a required factMissing information or failure to use supplied informationInspect the actual input, then test with sufficient verified information
Malformed machine-readable outputAn unclear format request or insufficient structural controlCompare supported structural enforcement while checking values independently
Persistent semantic errorsPoor elicitation, unsuitable examples or limited capabilityCompare a targeted prompt revision, another model or parameter adaptation under the same task criteria

These interventions change different parts of the system. Context Engineering changes which information reaches an invocation. Post-training and Alignment changes learned parameters using training data and objectives. Prompting still specifies the task for the adapted model, so the two approaches can coexist. Neither a new training procedure nor a new source of context guarantees improvement.

Apply the acceptance criteria established before selection: task quality, consequential slices, output requirements and resource limits. Retain a prompt that meets them with adequate independent evidence. Revise a demonstrated weakness when a plausible input change addresses it. Narrow supported use when evidence covers only part of the workload, or investigate another intervention when the remaining failures warrant it. Every revised choice needs evidence appropriate to its new claim.

Open questions

  1. Predicting which demonstrations add useful coverage remains difficult: similarity can retrieve redundancy, while coverage depends on the chosen representation. Progress would predict marginal usefulness across tasks before extensive prompt search.

  2. Prompt portability needs stronger evidence across model versions and languages. Presentation preferences can change across models; useful progress would establish performance ranges under declared changes without target-specific retuning.

  3. Demonstration-following still leaves ambiguity about what was acquired. Distinguishing format imitation, familiar-task recognition and new mapping use matters for transfer; progress requires interventions that separate those explanations.

  4. Efficient prompt selection must preserve assessment independence despite limited labeled data. Progress would reduce search and labeling costs while maintaining reliable estimates on cases excluded from selection.

Follow the curated reading path through the speakers and demonstrations behind this entry.

121 min

AI Engineer World's Fair 2025 · 2025

Prompt Engineering & AI Red Teaming

Sander Schulhoff

Cited in this entry

Provides a broad practitioner discussion of example order, label quality and the difference between correcting a conversation and improving a reusable prompt.

Watch talk

Explore more talks

The rest of the library, beyond the curated path. Cited talks support this entry; reviewed transcripts were processed in full. Metadata candidates have not been reviewed as sources or verified as topic members.

10 matching talks

TalkSpeakerEventYear
Aparna DhinakaranAI Engineer Code 20252025
Christopher Harrison, John PeckAI Engineer World's Fair 20252025
Nick HeinerAI Engineer World's Fair 20262026
Dan ClearyAI Engineer Summit 20252025
Devendra Chaplot, Devendra Singh ChaplotAI Engineer World's Fair 20242024
AI Engineering 101

Cited in this entry

Noah HeinAI Engineer Summit 20232023
Skills are the New SDKs

Transcript reviewed

Elvin AghammadzadaAI Engineer World's Fair 20262026
Ishan AnandAI Engineer World's Fair 20262026
Charles FryeAI Engineer Summit 20232023
Lukas BiewaldAI Engineer World's Fair 20242024

References

Coverage and source review
Processed transcripts
14 processed in full · 4 in the curated path
Automated source review
Passed
Metadata candidates
0 unreviewed; not verified topic membership
Corpus version
1bd8e407b26a07b33815594e1b2db5f41827119a2b3cb6fbf240f9fc571fc767

Automated review checks source support; it is not publication approval.

A synthesis of selected conference talks and technical references. Citations link to the source material; they do not imply that every talk on this subject is included.

  1. Language Models are Unsupervised Multitask Learners

    GPT-2 represents text using byte-level byte-pair encoding: frequent byte sequences become vocabulary tokens, so a token need not equal a word. Autoregressive modeling factorizes sequence probability as pθ(t1,…,tn)=∏i pθ(ti|t1,…,t(i−1)). Generation repeatedly computes a next-token distribution, selects a token, and extends the context. Training estimates parameters θ from text; the paper's zero-shot task execution changes the supplied sequence without modifying parameters or architecture. Instructions, examples, and source text can therefore change the conditional output distribution without constituting a training update.

  2. Optimizing LLMs for Speed and Memory

    Model parameters are numerical weight matrices and vectors loaded from a checkpoint; text inputs are represented separately as sequences of vectors. In ordinary inference, request inputs pass through those weights without a training update. Applied to RAG, instructions, conversation history, the question and retrieved text belong to request context when included in the input. Changing that text changes the computation without rewriting the checkpoint. Request-specific cached attention keys and values are intermediate computation state, not newly learned model parameters.

  3. Effective context engineering for AI agents

    Context engineering selects and maintains the information supplied at each model invocation, including instructions, tools, external data, and conversation history. Instead of loading every possible document, an agent can retain references such as paths or queries and retrieve details when needed; this trades smaller working context for additional exploration latency. Compaction summarizes an existing conversation into a new context, while external notes preserve selected information across calls. Compression can discard details needed later, so shorter context is not automatically better context.

  4. Prompting best practices — Claude Platform Docs

    Anthropic recommends stating desired outputs and constraints explicitly, explaining the purpose behind instructions, and specifying sequence when order matters. Its demonstration guidance emphasizes examples relevant to the actual use case, varied enough to cover edge cases without teaching accidental patterns, and visibly separated from instructions. The guide treats examples as a way to communicate output format, tone, and structure.

  5. Writing Principles for Task-Tuned Prompt Engineering

    Contrasting conceptual distinctions can clarify the intended granularity and meaning of categories when ordinary instructions miss nuance.

  6. The LLM Triangle: Engineering Principles for Robust AI Applications

    Prompt templates provide a reusable instruction structure whose variables supply the data for each invocation.

  7. Prompt Engineering & AI Red Teaming

    For a reusable API task, improve the original prompt rather than relying on corrections later in a chat.

  8. When Will The Benchmaxxing Plague End?

    Contradictory instructions make success impossible, while arbitrary constraints require evidence that performance transfers to real user requests.

  9. Building with Anthropic's Claude - The Prompt Doctor is In

    Check what information the prompt actually supplies before treating an uncertainty response as a failure.

  10. Transformers: model-specific chat serialization

    A chat template converts ordered role/content messages into the token sequence a causal model continues, inserting model-specific role markers, message boundaries and special tokens. Models fine-tuned from the same base can require different formats: Mistral-Instruct brackets user messages with instruction delimiters, while Zephyr uses explicit speaker markers. The guide warns that incompatible control tokens degrade performance. Where the format requires it, add_generation_prompt=True appends the assistant-start marker; omitting it can cause continuation of the user's message instead of a reply. Some templates need no such marker. Templates already supply required special tokens: use apply_chat_template(tokenize=True), or tokenize the rendered string with add_special_tokens=False to avoid duplicated beginning/end tokens.

  11. Introducing Structured Outputs in the API

    OpenAI describes schema-constrained generation that restricts which tokens may be produced as an output is generated. This adds a mechanism beyond requesting a format in natural language. The report explicitly warns that schema-conforming JSON values can still contain mistakes, such as an incorrect mathematical step, and identifies refusal and incomplete generation as separate outcomes.

  12. Language Models are Few-Shot Learners

    Few-shot inference supplies demonstrations as input conditioning while keeping model weights fixed; fine-tuning changes pretrained weights through training. Examples consume bounded context and influence subsequent predictions without becoming parameter updates. Separately, benchmark contamination means evaluation material overlaps training data, weakening claims of generalization to unseen examples. GPT-3's study compares original scores with subsets lacking detected n-gram overlap, but acknowledges false positives and possible distribution differences between clean and original subsets. Conceptually, contamination concerns exposure to evaluation data; optimizing a proxy concerns objective mismatch, while biased reviewer labels concern measurement. Those problems can occur independently.

  13. Language Models are Few-Shot Learners

    The paper distinguishes zero-shot prompting, with a task description but no demonstrations; one-shot prompting, with one demonstration; and few-shot prompting, with several. A demonstration pairs an input with its desired completion, followed by an unanswered input. These categories count examples supplied for inference, not examples encountered during pretraining.

  14. AI Engineering 101

    Few-shot prompting can demonstrate output conventions that subsequent requests need not restate.

  15. The Model Isn’t Wrong—You’re Just Bad at Prompting

    Few-shot prompting can convey desired content and style through paired briefs and completed content.

  16. Larger language models do in-context learning differently

    This study separates prior label meanings from mappings supplied in the prompt. Replacing sentiment labels with unrelated names such as Foo and Bar requires using the demonstrated association rather than the words' familiar meanings. Some tested models successfully used these mappings, while others relied more heavily on prior semantics. Instruction-tuned PaLM variants improved at unrelated-label mappings but became less willing to follow demonstrations that reversed familiar label meanings.

  17. Learning to Learn Using Gradient Descent

    Hochreiter, Younger, and Conwell investigated learning to learn: training a system to acquire a procedure for learning related tasks. Their recurrent network received successive function inputs and previous target values, allowing its internal state to incorporate examples. Experiments tested adaptation to changing Boolean, semilinear, and quadratic functions. The motivation was to make learning-algorithm discovery practical with more adjustable parameters than earlier evolutionary approaches.

  18. Language Models are Unsupervised Multitask Learners

    GPT-2's summarization experiment appended a summary cue to an article; removing that cue reduced its reported summarization score. Translation supplied example sentence pairs followed by an unfinished pair. These experiments used continuation formats to communicate the intended operation, while the summaries still confused details.

  19. Finetuned Language Models Are Zero-Shot Learners

    FLAN addressed weak instruction-only performance by fine-tuning a pretrained language model on tasks expressed through natural-language instructions. Evaluation withheld entire task-type clusters, such as natural-language inference, from instruction tuning. The resulting model improved over its untuned counterpart on unseen task types. Training for instruction responsiveness and supplying an instruction during inference are therefore distinct interventions that can work together.

  20. Multitask Prompted Training Enables Zero-Shot Task Generalization

    The BigScience T0 project explicitly trained an encoder-decoder model on multiple supervised tasks rendered through varied natural-language prompts. It investigated whether this could produce generalization to held-out tasks rather than relying solely on implicit multitask exposure during language-model pretraining. Training with more prompt formulations per dataset improved median held-out performance and reduced variability across prompts; adding more datasets did not consistently reduce that variability.

  21. Decoding Mistral AI's Large Language Models

    A next-token pretrained model can possess the needed capability while responding in a format that does not satisfy a human instruction.

  22. Prompt Engineering & AI Red Teaming

    Verify demonstration labels despite reports that some models can perform with incorrect examples.

  23. The LLM Triangle: Engineering Principles for Robust AI Applications

    Select a small set of relevant demonstrations for each request instead of including the entire example collection.

  24. What Makes Good In-Context Examples for GPT-3?

    KATE selects demonstrations by finding training inputs similar to the current query. In a sentiment-transfer experiment, three demonstrations came from SST-2 and predictions were evaluated on IMDB. With temperature zero, random selection averaged 87.95% accuracy with a 2.74-point standard deviation across five runs; selection using an unchanged RoBERTa-large encoder achieved 91.99%. Task-matched encoder training improved results further, whereas other encoder training objectives were less helpful.

  25. Coverage-based Example Selection for In-Context Learning

    Selecting examples independently by similarity can fill a prompt with paraphrases while omitting a needed operation. The paper's meeting-scheduling illustration contrasts redundant appointment examples with an example demonstrating how to find someone's manager. Its set-selection method rewards covering different relevant aspects of the query. Eight-shot experiments found the strongest benefits on compositional semantic-parsing splits, which test combining learned operations. The same method did not consistently improve ordinary classification and numerical-reasoning splits.

  26. Conversation state: managing the context window — OpenAI

    The context window limits tokens used in one request, including supplied input and generated output; applicable reasoning tokens also consume capacity. Instructions, conversation history, retrieved material and tool results supplied to that invocation therefore share its input budget. A simple worked design reserves generated-token capacity before allocating remaining space to input, while also respecting the model's separate output limit. For a reasoning model, reserve space for hidden reasoning as well as the visible answer without counting the same output tokens twice. Persisting a conversation does not make its usable context unbounded.

  27. Claude context windows and cached-token accounting

    Cached prefixes still occupy the context window. System instructions, tool definitions, messages and tool results consume capacity, and generated output also occupies the window. A useful planning constraint is I + O <= W, where I is counted input, O is generated output and W is the model's context capacity. Caching changes processing cost, not this capacity requirement. Inputs exceeding the window are rejected; generation at the limit follows model-specific overflow behavior.

  28. Many-Shot In-Context Learning

    Expanded context windows enabled testing hundreds or thousands of demonstrations. Using the original February 2024 Gemini 1.5 Pro, the study nested smaller demonstration sets inside larger ones and repeated selections across seeds. News-summary performance on XSum improved through roughly 50 examples and then declined, while transfer from XSum demonstrations to XLSum generally improved with more examples. Summaries sometimes fabricated dates or times. More available context therefore enabled useful adaptation without guaranteeing monotonic gains or faithful output.

  29. Prompt Engineering & AI Red Teaming

    Example order and example formatting can affect results, so neither should be assumed behaviorally neutral.

  30. Fantastically Ordered Prompts and Where to Find Them: Overcoming Few-Shot Prompt Order Sensitivity

    The study held a balanced set of four SST-2 demonstrations fixed and evaluated all 24 orderings across GPT-2 and GPT-3 model sizes. Accuracy varied substantially despite unchanged examples and task. Rankings of effective permutations correlated weakly across models. Increasing demonstration counts improved performance in some settings but did not reliably remove ordering variance. Additional randomly selected demonstration sets were tested to check that the phenomenon was not confined to one set.

  31. Quantifying Language Models’ Sensitivity to Spurious Features in Prompt Design

    The authors varied meaning-preserving formatting choices such as separators, descriptor capitalization, and option numbering while fixing demonstration identity and order. Across 53 classification and multiple-choice tasks, ten sampled formats produced a reported median spread of 7.5 accuracy points across model and shot settings. Formats that worked well for one model could work poorly for another. The study evaluated shared cases and kept demonstrations out of evaluation.

  32. Calibrate Before Use: Improving Few-Shot Performance of Language Models

    Experiments identified biases toward labels occurring frequently in demonstrations, labels appearing near the prompt's end, and familiar answer tokens. On balanced SST-2 sentiment data, these biases could make a one-example prompt worse than a zero-example prompt by encouraging repetition of the demonstrated class. The proposed contextual calibration estimates answer preferences with a content-free query and adjusts output scores.

  33. Prompt Engineering & AI Red Teaming

    Balanced examples are the speaker's default, but matching a known deployment distribution may be appropriate and introduces bias trade-offs.

  34. Building with Anthropic's Claude - The Prompt Doctor is In

    Use XML tags to distinguish prompt sections, but treat clear separation as the essential mechanism rather than XML itself.

  35. Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection

    Indirect prompt injection places attacker instructions in material an application is likely to retrieve, rather than in a direct user request. The paper demonstrates how applications can confuse external data with instructions, allowing retrieved text to redirect behavior or influence subsequent API calls. This makes the provenance and trust level of a context item separate from its relevance to a query: useful retrieved material can still be adversarial.

  36. Building with Anthropic's Claude - The Prompt Doctor is In

    Capture a baseline on concrete failure cases before editing, then rerun those same cases against the revised prompt.

  37. True Few-Shot Learning with Language Models

    The paper distinguishes the examples placed in a prompt from additional labeled examples used to choose that prompt. When prompt selection was restricted to very few examples, cross-validation and minimum-description-length criteria only slightly outperformed random selection on average and substantially underperformed selection using larger held-out sets. A prompt containing few demonstrations can therefore depend on considerable task-specific development data.

  38. Building with Anthropic's Claude - The Prompt Doctor is In

    A downstream agent's output-format problem may depend on earlier conversation turns, so its instruction template alone is an incomplete reproduction.

  39. OpenTelemetry GenAI model and tool spans

    GenAI spans describe logical operations through completion, error, or cancellation and can include automatic retries. Diagnostic attributes include provider, requested and returned model, prompt version, sampling parameters, token usage, finish reasons, and errors. Tool execution spans identify tool names and call IDs, enabling correlation with model requests. Instructions and messages should not be captured by default; instrumentation should offer opt-in. Tool arguments and results are explicitly opt-in and potentially sensitive. External content storage can separate content access controls from operational telemetry.

  40. NIST randomized blocks: applying controlled comparisons to RAG evidence

    NIST describes holding nuisance factors constant within blocks and randomizing remaining variation. Proposed RAG application: for each fixed query, compare the recorded baseline with a candidate-boundary intervention replacing candidates with independently verified sufficient source passages, then run the unchanged reranker, assembler and generator. Separately replace only the final evidence block with sufficient passages, bypassing retrieval and assembly. Keep corpus/ACL/time snapshot, question, prompt template, model/version, decoding settings, token budgets and evaluator fixed; record passage identities, order and every resulting context. For assembly diagnosis, replay the same candidates through original versus evidence-preserving assembly. Match evidence length and position where feasible; otherwise the treatment changes those too. Compare boundary coverage and answer support, not answer wording alone.

  41. Rethinking the Role of Demonstrations: What Makes In-Context Learning Work?

    The authors compared no demonstrations, correctly labeled demonstrations, and demonstrations with randomized labels. Across their classification and multiple-choice experiments, randomizing labels often retained much of the benefit of demonstrations. Further ablations identified contributions from the available label names, the input distribution, and the input-output format. In the reported example-count ablation, gains became small beyond eight examples. Demonstration-following performance therefore need not imply that a model inferred the intended input-label rule.

  42. Productionizing GenAI Models – Lessons from the world's best AI teams

    Informal testing can expose obvious failures, but repeatable evaluations are needed to assess changes that improve some cases and regress others.

  43. Chain-of-Thought Prompting Elicits Reasoning in Large Language Models

    Chain-of-thought prompting augments input-answer demonstrations with intermediate natural-language steps. The paper compares this with demonstrations that give answers directly and reports gains on tested arithmetic, commonsense, and symbolic tasks. Its arithmetic experiments reused one set of eight worked examples across several benchmarks, with a separate four-example setup for multiple-choice AQuA.

  44. Large Language Models are Zero-Shot Reasoners

    The proposed zero-shot chain-of-thought method requests intermediate steps without worked demonstrations. Its actual experimental procedure has two stages: generate reasoning, then append an answer-extraction instruction and generate the final answer. Experiments used greedy decoding.

  45. Language Models Don't Always Say What They Think: Unfaithful Explanations in Chain-of-Thought Prompting

    The authors manipulated answer suggestions and demonstration answer positions while testing GPT-3.5 and Claude 1.0. These changes influenced predictions, yet generated explanations generally omitted the influential cues and sometimes rationalized incorrect answers. The experiment separates an explanation's plausibility from whether it accounts for factors that changed the prediction.

  46. Training language models to follow instructions with human feedback

    InstructGPT begins with a pretrained language model. Supervised fine-tuning updates it using demonstrations of desired responses to prompts. Preference training then fits a reward model to human comparisons of candidate responses; PPO updates the response policy to increase predicted reward, with a penalty for departing from the supervised policy. These stages optimize learned parameters using datasets and objectives. Supplying an instruction or tool observation during ordinary inference instead changes the current input to that trained policy. A favorable preference score represents the learned comparison objective, not a proof of factual or program correctness.

  47. Optimization in DSPy

    DSPy's optimization guide starts from a working program and an evaluation procedure, then separates data for optimization, validation, and held-out testing from earlier exploratory development. It warns that prompt optimizers can overfit small datasets. When results remain unsatisfactory, it recommends revisiting task definition, data, metrics, program structure, and optimization choices rather than assuming that another prompt edit will resolve the problem.

  48. The LLM Triangle: Engineering Principles for Robust AI Applications

    Few-shot demonstrations can communicate the intended category vocabulary when an instruction admits several correct interpretations.