Lesson 3 of 4 Selecting and Configuring Foundation Models

Configuring Inference Parameters for Each Use Case

This lesson explains how inference parameters control how a model turns probabilities into text, how random it is, how long the response can be and when it stops, and how to set them through the Converse API.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain how tokens are generated from probabilities.
  • Set temperature, top-p and top-k for a use case.
  • Control length and stopping with maximum tokens and stop sequences.
  • Pass common and model-specific parameters in the Converse API.

How generation works

A foundation model generates text one token at a time, where a token is a word or part of a word. At each step, the model calculates a probability for every token in its vocabulary, given all the text so far, and then chooses the next token from that probability distribution. The chosen token is appended to the text, and the process repeats.

Inference parameters act on this choice. Sampling parameters such as temperature, top-p and top-k reshape or restrict the distribution before a token is chosen, which determines how predictable or varied the output is: always choosing among the most likely tokens gives consistent, conservative text, while allowing less likely tokens gives more varied and creative text. Other parameters control when generation ends. It stops when the model produces its end-of-sequence token, when the maximum number of output tokens is reached, or when the output contains one of the configured stop sequences. Because each output token requires another step, the length of the response largely determines latency and output cost.

Temperature, top-p and top-k

Temperature scales the probability distribution. Low values (near 0) make the most likely tokens dominate, producing focused, repeatable output suited to extraction, classification, code and factual question answering. High values flatten the distribution, producing more varied and creative output suited to brainstorming and marketing copy, at a higher risk of errors.

Top-p (nucleus sampling) keeps only the smallest set of tokens whose cumulative probability reaches p, for example 0.9, and samples from that set. Top-k keeps only the k most probable tokens. Both remove unlikely tokens from consideration. Provider guidance usually recommends adjusting temperature or top-p, not both, and top-k is not supported by every model.

The following diagram shows which candidate tokens top-k and top-p keep.

How top-k and top-p restrict the next-token choice. Top-k of 3 keeps the three most probable tokens. Top-p of 0.9 keeps the smallest set whose cumulative probability reaches 0.9, here four tokens. Temperature reshapes the probabilities before the cut: low values sharpen them, high values flatten them.
The tokens and probabilities are illustrative.
Sort into groups

High or low temperature?

Exam skills 1.2.1 · 4.2.4

Decide whether each task needs a low or a higher temperature.

Log in to try this activity Interactive activities are free with an account.

Length and stopping

Maximum tokens (maxTokens in the Converse API) caps the response length. It controls cost and latency, because output tokens are generated one at a time and are usually priced higher than input tokens. If the cap is reached, the response is cut off and the stopReason is max_tokens. Stop sequences end generation when a given string appears, which is useful to stop after one item in a list or before the model invents the next turn of a dialogue.

Fix the problem

Responses that end badly

Exam skills 1.2.1 · 5.2.1

Find the setting that explains each problem with response length.

Log in to try this activity Interactive activities are free with an account.

Setting parameters with the Converse API

The Converse API takes common parameters in inferenceConfig. Parameters that only some models support, such as top-k for some providers or reasoning budgets, go in additionalModelRequestFields. The following request sets a low temperature for a deterministic extraction task, leaves top-p at its default, passes top-k in the Amazon Nova request format and stops generation at the closing tag the prompt asks for.

import boto3
brt = boto3.client("bedrock-runtime")
response = brt.converse(
    modelId="us.amazon.nova-lite-v1:0",
    system=[{"text": "Extract the invoice number and total as JSON with keys invoice_number and total. "
                     "Wrap the JSON in <json></json> tags."}],
    messages=[{"role": "user", "content": [{"text": "Invoice INV-2291 ... Total due: EUR 1,240.50"}]}],
    inferenceConfig={"temperature": 0, "maxTokens": 200, "stopSequences": ["</json>"]},
    additionalModelRequestFields={"inferenceConfig": {"topK": 20}},
)
print(response["output"]["message"]["content"][0]["text"], response["stopReason"], response["usage"])

The following table gives starting values by use case, to be refined with evaluation and A/B tests.

Use caseTemperatureOther settings
Extraction, classification, SQL generation0 to 0.2Tight maxTokens; schema or stop sequences
Question answering over retrieved context0 to 0.3maxTokens sized to the expected answer
Conversational assistant0.3 to 0.7Moderate maxTokens; streaming
Creative writing and ideation0.7 to 1.0Higher maxTokens; top-p around 0.9

The following diagram compares the original inference settings of a ticket classifier with the corrected ones that make its output consistent.

Fixing inconsistent classification outputs with inference parameters. A temperature of 0.8 inherited from a chat template let the same ticket receive different categories, and free-text answers broke the parser. Temperature 0, a small maxTokens and a label-only answer, or tool use with an enum, make outputs consistent and parseable.
Tool use with an enum constrains the output to the allowed categories.
Worked example

Inconsistent outputs

A classification prompt assigns support tickets to one of eight categories. The same ticket sometimes receives different categories, and some responses add explanations that break the parser.

The parameters are the first suspect: a temperature of 0.8 inherited from a chat template introduces randomness. Setting temperature to 0, limiting maxTokens to a few tokens and asking for the category label only (or using tool use with an enum) make outputs consistent and parseable. If inconsistency remains, the prompt's category definitions need clarifying, which is a prompt engineering problem rather than a parameter one.

Check yourself

A response ends mid-sentence and the stopReason is max_tokens. What happened?

Show answer

The output reached the maxTokens limit and was truncated. Raise maxTokens or ask for a shorter answer.

Exam Tips

Remember for the exam

  • Low temperature for deterministic tasks; higher temperature or top-p for creative tasks.
  • Adjust temperature or top-p, usually not both.
  • stopReason max_tokens means the response was truncated.
  • Model-specific parameters go in additionalModelRequestFields.