◉GEMINI LABJP
●ARGON — gemini-4-argon is generally available as of 10/13, aimed at complex coding, agents, math and science●DEEP RES — deep-research-pro-preview-12-2025 shuts down 10/23, 6 days left. Move to deep-research-preview-04-2026●NANO — gemini-nano-banana-2.1 is GA (10/06). gemini-3.1-flash-image is deprecated with no shutdown date yet●MCP — One write-up cut an 85,000-token tool result to 310 tokens by wrapping it in an ADK FunctionTool●FLASH — gemini-3.7-flash and 3.5-flash now route automatically to newer Flash models (10/08)●NEW — Stop Re-Reading Every Crash Report: Gre…●ARGON — gemini-4-argon is generally available as of 10/13, aimed at complex coding, agents, math and science●DEEP RES — deep-research-pro-preview-12-2025 shuts down 10/23, 6 days left. Move to deep-research-preview-04-2026●NANO — gemini-nano-banana-2.1 is GA (10/06). gemini-3.1-flash-image is deprecated with no shutdown date yet●MCP — One write-up cut an 85,000-token tool result to 310 tokens by wrapping it in an ADK FunctionTool●FLASH — gemini-3.7-flash and 3.5-flash now route automatically to newer Flash models (10/08)●NEW — Stop Re-Reading Every Crash Report: Gre…
Articles/API / SDK
◈ API / SDK/2026-04-26Intermediate

Gemini API Temperature Best Practices by Task — Translation, Summarization, Code, Chat, and More

The `temperature` parameter is one of the highest-leverage knobs in the Gemini API, yet most implementations ship with the default. This guide walks through the value I actually use for each task type — translation, summarization, code generation, chat, classification — and explains why.

Gemini API249TemperaturePrompt Engineering5TranslationCode GenerationChatbot

import { Callout } from '@/components/ui/callout';

When you start using the Gemini API, the temperature parameter is one of the first things you notice changes outputs dramatically. The same prompt feels completely different at 0.0 versus 1.0. What is harder to find is concrete guidance on which value to actually use for which task. Most implementations I see ship with temperature=0.7 simply because that is the default.

After running Gemini in production across several services, I have built up a working sense of the right value per task. This article distills that into something reproducible. Code samples are in both Python and TypeScript.

What Temperature Controls

Technically, temperature scales the sharpness of the next-token probability distribution.

  • temperature=0.0 — pick the most likely token every time (deterministic)
  • temperature=1.0 — sample from the model's learned distribution as-is
  • temperature>1.0 — flatten the distribution; low-probability tokens become more likely

Translated to practical terms: low values mean stable but potentially repetitive, high values mean creative but volatile. The temperature design problem is figuring out where on that axis a given task should sit.

Per-Task Recommendations

These are starting points, not absolutes. Adjust based on your evaluation criteria.

Translation: temperature=0.1–0.3

Translation prioritizes faithful meaning reproduction. I use 0.2 as a default.

from google import genai
 
client = genai.Client()
 
def translate_to_japanese(text: str) -> str:
    response = client.models.generate_content(
        model="gemini-2.5-pro",
        contents=f"Translate the following English text into natural Japanese.\n\n{text}",
        config={"temperature": 0.2},
    )
    return response.text

At 0.0 the output drifts toward word-for-word literalism, losing context-aware vocabulary choice. Around 0.2 you hit the sweet spot of accurate and natural. Above 0.5 the model starts inventing nuance that was not in the original.

Summarization: temperature=0.2–0.4

For long-form summarization I center around 0.3. Summarization is fundamentally compression, so you want low temperature, with just a sliver of room for natural phrasing.

import { GoogleGenAI } from '@google/genai';
 
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
 
async function summarizeArticle(article: string): Promise<string> {
  const response = await ai.models.generateContent({
    model: 'gemini-2.5-pro',
    contents: `Summarize the following article in 200 words or fewer.\n\n${article}`,
    config: { temperature: 0.3 },
  });
  return response.text ?? '';
}

Automated summarization pipelines stay low for consistency. For social media caption generation, 0.5–0.7 is more useful — you actually want stylistic variety.

Code Generation: temperature=0.0–0.2

Reproducibility is everything in code generation. The same spec should produce the same code on every call.

def generate_function(spec: str) -> str:
    response = client.models.generate_content(
        model="gemini-2.5-pro",
        contents=f"Implement a Python function from the following spec. Type hints required.\n\n{spec}",
        config={"temperature": 0.0},
    )
    return response.text

When generating code samples for the Dolice Labs sites I run, I default to temperature=0.0. People sometimes call this "boring." Code does not need to be interesting. It needs to run, pass tests, and stay maintainable.

The exception is initial UI design exploration — when you genuinely want to see multiple options, push it to 0.5–0.7, generate three to five candidates, and let a human choose.

Chat / Conversational Agents: temperature=0.7–0.9

In a chatbot, identical answers to the same question feel robotic. I center around 0.8, which gives enough variation to feel natural without sliding into incoherence.

def chat_response(user_message: str, history: list) -> str:
    response = client.models.generate_content(
        model="gemini-2.5-pro",
        contents=[*history, {"role": "user", "parts": [{"text": user_message}]}],
        config={
            "temperature": 0.8,
            "top_p": 0.95,
        },
    )
    return response.text

Pair high temperature with top_p=0.95. The top_p cap keeps you on the high-probability tail even when temperature is generous, preserving quality.

Creative Writing / Brainstorming: temperature=0.9–1.2

For poems, stories, and ad copy, push to around 1.0. When you want to maximize idea diversity for human curation, 1.2 works well.

Above 1.5, you start getting outputs where meaning collapses. With Gemini 2.5, I treat 1.0 as the safe ceiling.

Classification / Extraction: temperature=0.0

For sentiment classification, named entity extraction, or structured data generation, there is no reason to leave 0.0. Reproducibility is the quality criterion here.

Quick Reference Table

TaskRecommended Temperaturetop_p
Classification / Extraction0.01.0
Code Generation0.0–0.21.0
Translation0.1–0.30.95
Summarization0.2–0.40.95
General Q&A0.4–0.60.95
Chat / Dialogue0.7–0.90.95
Creative / Brainstorm0.9–1.20.95

Build a Habit of Measuring

The numbers above are starting points. The actual best value for your prompt and data has to be measured. When I set up a new pipeline, I run a quick evaluation script:

import statistics
 
def evaluate_temperature_stability(prompt: str, target_temp: float, n_trials: int = 5):
    """Call the same prompt n times and observe length/uniqueness."""
    responses = []
    for _ in range(n_trials):
        r = client.models.generate_content(
            model="gemini-2.5-pro",
            contents=prompt,
            config={"temperature": target_temp},
        )
        responses.append(r.text)
    
    lengths = [len(r) for r in responses]
    print(f"Temperature: {target_temp}")
    print(f"  Length: mean={statistics.mean(lengths):.0f}, stdev={statistics.stdev(lengths):.0f}")
    print(f"  Unique responses: {len(set(responses))} / {n_trials}")
    return responses

Run it at 0.0, 0.3, 0.7, 1.0 and watch how length variance and unique-response counts change. After a few minutes you have an intuitive feel for the temperature zone that fits your task.

Two Common Misconceptions

Misconception 1: Lower temperature always means higher accuracy.

0.0 is reproducible, but on multi-step reasoning tasks, the model can lock into the first plausible path and miss the right answer. For hard math or multi-hop reasoning, 0.3–0.5 often beats 0.0 on accuracy.

Misconception 2: Temperature is the only knob that matters.

top_p (nucleus sampling), top_k, max_output_tokens, and your system prompt all interact. Temperature is important, but it is not the whole story.

Next Step

Open your current Gemini integration and check what value temperature is set to. If it is the default, it is probably 1.0. Pick the row in the table that matches your task and try it. The resulting jump in output stability is usually obvious within five test runs.

Share

Thank You for Reading

Gemini Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

◈ API / SDK2026-10-14
When Your config Raises "Extra inputs are not permitted", Check the Spelling of Every Key
If a google-genai call fails with a pydantic ValidationError (extra_forbidden) the moment you pass a config, it is almost always a one-letter typo. Here is the output I reproduced, a small function that checks keys before the call, and how to tell why response.text came back as None.
◈ API / SDK2026-10-08
When a Deprecation Has No Shutdown Date: Re-Picking an Image Model on Three Conditions
gemini-nano-banana-2.1 went GA on October 6, and gemini-3.1-flash-image was deprecated with no shutdown date. Here is a table and a short script for choosing a replacement by resolution, reference images, and search grounding.
◈ API / SDK2026-09-29
The Size Column Said 'F6' and 'About A4' — I Let Gemini Read It, and Let a Table Do the Math
An artist's spreadsheet mixed 'F6', '41×31.8cm', and 'about A4' in one size column. Here is the small tool I built: Gemini reads each cell, a lookup table converts to centimeters, and the artwork image decides the orientation. Working code, step by step.