Temperature vs. top_p for Deterministic Code Generation
Both temperature and top_p control how an LLM chooses the next token, but they work differently and play different roles when you want deterministic code:
- Temperature reshapes token probabilities: It scales the model’s raw scores (logits) before converting them into probabilities. Lowering temperature makes the highest-probability tokens much more dominant; setting
temperature = 0pushes the model toward greedy decoding (always picking the top token). top_p(nucleus sampling) trims the token pool: It keeps only the smallest set of top tokens whose probabilities add up totop_p(for example,0.1or0.9), and samples from that subset. Even with a lowtop_p(like0.1), the model still samples randomly among the remaining tokens in that pool rather than strictly forcing greedy selection.- Best practice for deterministic code: Set
temperature = 0(or very low, like0to0.2) and leavetop_pat its default (1.0/ omitted) rather than tuning both at the same time. Also keep in mind that even withtemperature = 0, slight variations can still happen in hosted APIs due to GPU batching or routing.
Key Differences at a Glance
| Aspect | temperature |
top_p |
|---|---|---|
| What it changes | Sharpness or flatness of the entire probability curve | Size of the candidate token shortlist based on cumulative probability |
Setting 0 (or near 0) |
Closest to deterministic (greedy top-token choice) | Still samples within the narrow top-probability set |
| Recommended for code | 0 (or 0–0.2 for low variance) |
Leave at default (1.0 / unset) while tuning temperature |
JavaScript Example Using temperature: 0 for Code
import OpenAI from "openai";
const openai = new OpenAI();
async function generateDeterministicCode(prompt) {
const response = await openai.chat.completions.create({
model: "gpt-4o-mini",
temperature: 0,
// Keep top_p at default rather than changing both parameters at once
messages: [
{
role: "system",
content:
"You are a precise software engineer. Return clean, well-typed code with no extra explanation.",
},
{
role: "user",
content: prompt,
},
],
});
return response.choices[0].message.content ?? "";
}
const code = await generateDeterministicCode(
"Write a TypeScript function that retries an async operation with exponential backoff."
);
console.log(code);
Helpful Tips for Consistent Code Outputs
- Tune one sampling knob at a time: Changing both
temperatureandtop_ptogether makes behavior harder to predict. - Be clear in your prompt and types: Even with
temperature = 0, vague prompts can lead to inconsistent structure—specify language version, function signatures, and edge cases clearly. - Use structured outputs when needed: When code or data must follow a strict schema or format, pair low temperature with schema enforcement or tests/linters in your pipeline.
You must log in or register to comment.
