In-Context Learning & Inference Parameters
Generative & Agentic AI · Working with LLMs · Basics · 18 min
Structure prompts, teach a model with examples instead of training, and set temperature, top-k, top-p, max tokens and stop sequences on purpose.
A model holding a bag of word-tiles, each tile sized by how likely it is. Temperature puffs the small tiles up or shrinks them; top-k and top-p throw tiles out of the bag before you reach in and pick one.
The idea in everyday words
Briefing a new temp worker. You do not send them on a training course; you hand them a note: what to do (instruction), some background (context), the actual task (input), two finished examples (shots) and the format you want back. They copy the pattern immediately. That is in-context learning. The sampling dials are how adventurous you tell them to be when filling in blanks.
A prompt has four parts
Good prompts are built, not improvised. Most have these parts:
| Part | Job | Example |
|---|---|---|
| Instruction | what to do | "Classify the review's sentiment." |
| Context | background, rules, role | "You are a support analyst. Labels: positive, negative, mixed." |
| Input | the data for this request | "Review: Fast delivery but the box was crushed." |
| Output format | the exact shape of the answer | "Reply with only the label, in lowercase." |
You are a support analyst. Labels: positive, negative, mixed.
Classify the review's sentiment. Reply with only the label, in lowercase.
Review: Fast delivery but the box was crushed.
Label:
Why the output format matters most for engineers: your code has to parse the answer. "Only the label" or "valid JSON with keys x and y" turns a chatty reply into something a program can use. Ending the prompt with Label: also nudges the model to answer right away.
Zero-shot, one-shot, few-shot
In-context learning = the model picks up a task from examples inside the prompt, with no change to its weights. Remove the examples and the "learning" is gone.
- Zero-shot: instruction only. Works for common tasks on strong models.
- One-shot: one worked example. Mostly teaches the format.
- Few-shot: 2 to 5 (sometimes more) examples. Teaches format and the edge of the task.
Review: Loved it, works perfectly. Label: positive
Review: Broke after one day. Label: negative
Review: Great screen, awful battery. Label: mixed
Review: Fast delivery but the box was crushed.
Label:
When few-shot goes wrong:
- Label imbalance: if 4 of 5 examples are "positive", the model leans positive.
- Recency bias: the last example has extra pull; shuffle the order.
- Copying surface features: if every example is short, long inputs confuse it.
- Cost: every example is resent with every request, so you pay for those tokens each time and use up the context window.
- Small models follow examples less reliably. If 5-10 good examples still do not work, that is the signal to try RAG or fine-tuning.
Best practices: diverse examples, balanced labels, identical formatting, and examples that look like real traffic.
Chain-of-thought: let it show its work
For multi-step problems, ask the model to reason step by step before answering. Each generated token becomes extra "scratch paper" the next tokens can build on.
Q: A bakery has 15 muffins, sells 8, then bakes 12 more. How many now?
A: Let's think step by step. 15 - 8 = 7 left. 7 + 12 = 19. Answer: 19
- Zero-shot CoT: add "Think step by step" to the instruction.
- Few-shot CoT: include examples whose answers show the reasoning.
- Separate reasoning from the answer (for example
<thinking>…</thinking><answer>…</answer>) so your code can extract just the answer. - Trade-off: more output tokens means more latency and cost. Use it for maths, logic and planning, not for simple lookups.
Many newer models (including some Claude models on Bedrock) have a built-in extended thinking / reasoning mode that does this for you with a separate token budget. Check the model's docs for how to switch it on.
The sampling dials: temperature, top-k, top-p
At every step the model outputs a probability for every possible next token. Sampling picks one. Three dials control that pick:
- Temperature: divide the raw scores (logits) by T before softmax. T < 1 sharpens the distribution (the favourite gets more likely). T > 1 flattens it (long shots get a chance). T near 0 ≈ always the top token (greedy).
- Top-k: keep only the k most likely tokens. k = 1 is greedy.
- Top-p (nucleus sampling): keep the smallest set of top tokens whose probabilities add up to at least p (for example 90%). Adapts to the situation: when the model is sure, few tokens survive; when unsure, many do.
import math
def softmax(logits, T=1.0):
exps = [math.exp(l / T) for l in logits]
total = sum(exps)
return [round(100 * e / total) for e in exps]
logits = [3.2, 2.6, 2.1, -0.8] # chocolate, popcorn, fruit, glue
for T in [0.2, 1.0, 1.5]:
print("T =", T, "->", softmax(logits, T), "%")
Two more dials that are not about randomness:
- Max tokens: hard cap on output length. Protects cost and latency. If it is hit, the answer is cut off (the API tells you via the stop reason).
- Stop sequences: strings that end generation as soon as they appear (for example
</answer>or\n\nUser:). Great for stopping the model from rambling past the part you need.
Important: temperature 0 is close to deterministic, but not guaranteed identical every time. Never build a system that relies on byte-identical outputs.
Setting the dials on Amazon Bedrock
With the Bedrock Converse API, the common dials share one format across models:
inferenceConfig = {"maxTokens": 300, "temperature": 0.2, "topP": 0.9, "stopSequences": ["</answer>"]}
Top-k is not in inferenceConfig. Models that support it take it through additionalModelRequestFields (for example {"top_k": 50} for Anthropic Claude models). Names and ranges differ per model, so check the model's parameter page in the Bedrock docs. Some providers also advise changing temperature or top-p, not both.
| Task | Temperature | Why |
|---|---|---|
| Extraction, classification, SQL | 0 to 0.2 | you want the same right answer every time |
| Q&A over documents (RAG) | 0 to 0.3 | stick to the sources |
| Chat, explanations | 0.5 to 0.8 | natural but still focused |
| Brainstorming, stories | 0.8 to 1.0+ | variety is the goal |
Same idea elsewhere: OpenAI, Gemini and open-source servers like vLLM expose the same temperature, top-p and max-token knobs, sometimes with different names.
Step by step
- Distribution:
After "My favourite snack is": chocolate 50%, popcorn 30%, fruit 15%, glue 5% (already sorted).
- Top-k = 3:
Keep the top 3: chocolate, popcorn, fruit. "glue" is cut by rank.
- Top-p = 80%:
Running total: chocolate 50% (< 80, keep going), popcorn 80% (≥ 80, stop). Survivors: chocolate, popcorn.
- Both filters:
Using the original percentages, each filter keeps a prefix of the ranking. The survivors are the SHORTER prefix: [chocolate, popcorn].
- Renormalise:
50 / 80 = 62.5% chocolate, 30 / 80 = 37.5% popcorn. Sample from these.
- Temperature:
A low enough temperature would sharpen the distribution until chocolate alone is above 80%, and then top-p 80% would keep only chocolate.
Code example
# Build a few-shot prompt and estimate what the examples cost you.
def build_prompt(instruction, examples, text):
lines = [instruction, ""]
for review, label in examples:
lines.append("Review: " + review + "\nLabel: " + label)
lines.append("Review: " + text + "\nLabel:")
return "\n".join(lines)
examples = [("Loved it, works perfectly.", "positive"),
("Broke after one day.", "negative"),
("Great screen, awful battery.", "mixed")]
instruction = "Classify each review as positive, negative or mixed. Reply with the label only."
zero = build_prompt(instruction, [], "Fast delivery but the box was crushed.")
few = build_prompt(instruction, examples, "Fast delivery but the box was crushed.")
print(few)
print("---")
# Rule of thumb for English: about 4 characters per token.
print("zero-shot tokens ~", len(zero) // 4, "| few-shot tokens ~", len(few) // 4)
print("extra input tokens per 1M requests ~", (len(few) - len(zero)) // 4 * 1_000_000)Complexity
- Time: O(V log V) to sort V candidate tokens, then O(V) for the filters
- Space: O(V) for the sorted list
Interview tips
Explain in-context learning: the model infers the task from examples in the prompt, without any weight updates.
Compare temperature, top-k and top-p, and say which settings you would use for extraction versus creative writing.
Know when few-shot fails (imbalanced labels, recency bias, small models, cost) and what you would try next (better examples, RAG, fine-tuning).
Chain-of-thought: why it helps multi-step reasoning, and its cost in output tokens and latency.
On Bedrock: Converse inferenceConfig takes maxTokens, temperature, topP and stopSequences; model-specific settings such as top_k go in additionalModelRequestFields.
Challenge: Which Tokens Survive?
Write surviving_tokens(dist, top_k, top_p) that returns the tokens a sampler is allowed to pick from.
distis a list of[token, percent]with integer percentages, in any order.- Sort by percent, highest first. Ties keep their input order.
- top_k: if
top_k > 0, keep only the firsttop_ktokens (0 means off). - top_p: walk the list adding percentages and keep tokens until the running total is ≥ top_p (100 means keep everything). Always keep at least one token.
- Use the original percentages for both filters (real libraries renormalise between steps; we keep integers to stay exact).
Return the surviving tokens, most likely first.
Example:
surviving_tokens([["cat", 50], ["dog", 30], ["fish", 15], ["cow", 5]], 0, 80) → ["cat", "dog"]
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Amazon Bedrock: inference request parameters
- Amazon Bedrock: prompt engineering concepts
- Chain-of-Thought Prompting paper (Wei et al.)
- The Curious Case of Neural Text Degeneration (top-p paper)
More in Working with LLMs
- Prompt Engineering
- Decoding: Greedy, Beam Search, Sampling & Structured Output
- Building With LLM APIs
- Context Engineering & Prompt Caching
- Embeddings & Vector Search
Previous: Prompt Engineering · Next: Decoding: Greedy, Beam Search, Sampling & Structured Output