---
title: "Max Output Tokens and Truncation Strategies for ADK Agents"
date: "2026-11-25T08:48:00+07:00"
description: "Choosing max_output_tokens per task, recognizing and handling truncated generations, and the prompt and config patterns that keep agent outputs complete and bounded."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-max-output-tokens-truncation-strategies.jpg"
alt: "Text field cut off at a token boundary representing output truncation"
tags: ['google-adk', 'max-output-tokens', 'truncation', 'generatecontentconfig', 'python']
---

An unbounded generation is a liability wearing a slider. Every extra token costs money, adds latency, occupies a sequence slot on self-hosted hardware, and — worst of all — a generation cut off at the wrong moment produces output that *looks* complete but isn't: JSON missing its closing brace, a summary ending mid-word, a tool argument silently amputated.

`max_output_tokens` solves the first three problems; getting the fourth right is a design problem. This post covers both: how to size the cap per task, and what to do about truncation when it happens.

## Where the cap lives

Two layers, and they compose:

1. **`GenerateContentConfig.max_output_tokens`** on the agent — the per-agent generation ceiling:
   ```python
   from google.adk.agents import Agent
   from google.genai.types import GenerateContentConfig

   agent = Agent(
       model="gemini-flash-latest",
       name="summarizer",
       instruction=SUMMARIZE_INSTRUCTION,
       generate_content_config=GenerateContentConfig(max_output_tokens=1024),
   )
   ```
   Remember the ADK constraint: `generate_content_config` holds generation parameters (`max_output_tokens`, `temperature`, `top_p`, `top_k`, `seed`) — not `tools`, `system_instruction`, `response_schema`, or `http_options.base_url`, which raise `ValueError` if set there.
2. **Model/provider ceiling** — the hard maximum for the model (context window minus input, or a fixed output limit). Your cap must fit inside it; `input + output ≤ context window`.

**`max_output_tokens` counts output only** — it's not a budget for prompt + response together. A long prompt doesn't leave less room for output *within this parameter*, but it does reduce the provider-side headroom, which is where the second constraint bites.

## Sizing the cap per task class

There's no universal number; there's a per-task answer:

| Task class | Typical cap | Rationale |
|---|---|---|
| Classification / routing | 16–64 | A label or enum value |
| Tool call arguments | 64–512 | Depends on argument payload |
| Structured JSON (`output_schema`) | 256–2044 | Sized to the schema, field by field |
| Chat reply | 512–2048 | Conversational turns are short |
| Summary | 1–2k tokens | Roughly proportional to source, capped |
| Long-form generation | 4k–8k+ | Rare in agents; consider chunking instead |

Two methods for getting this right rather than guessing:

- **Schema arithmetic.** For structured output, sum your field budget: a 200-word summary field ≈ 300 tokens, five short enums ≈ 50, etc. Cap at ~1.5× your estimate — headroom for the model's verbosity, not for infinity.
- **Measure, don't guess.** Log output token counts per task for a week; set the cap at p99 + margin. You'll often discover your 8000-token cap is serving 400-token generations — pure risk with no upside.

**The failure modes at each extreme:**

- **Too low:** truncation (below).
- **Too high:** a runaway generation (hallucinated loop, ignoring stop conditions) burns money and latency before anything stops it. The cap is also a [reliability backstop](/blog/adk-global-timeouts-execution-deadlines) — the last line of defense against unbounded work.

## Recognizing truncation

Truncation is dangerous because it's *quiet*. The signals to instrument:

- **`finish_reason` — `STOP` vs. `LENGTH`.** This is the definitive marker. `LENGTH` means the cap hit before natural completion; log it, alert on it, and never treat such output as valid.
- **JSON parse failures on structured output** — the classic truncation symptom: `Unterminated string` at the end.
- **Odd ending behavior** — summaries that stop mid-sentence, lists missing their last item.

```python
async def generate_bounded(agent, request):
    response = await agent.model.aio.generate_content(
        model=agent.model, contents=request, config=agent.generate_content_config
    )
    if response.candidates and response.candidates[0].finish_reason == "LENGTH":
        metrics.incr("agent.output_truncated", tags={"agent": agent.name})
        raise OutputTruncated("generation hit max_output_tokens")   # don't ship it
    return response
```

**Never pass truncated output downstream.** A half-filled `output_schema` that silently becomes a default value is exactly the kind of data corruption agents excel at producing.

## Strategies when you need more output

If `finish_reason == LENGTH` is frequent for a legitimately long task, four options in order of preference:

1. **Prompt for concision.** Most overruns are the model padding — "no preamble, bullet points, ≤150 words" reclaims more tokens than raising the cap.
2. **Split the task.** Generate the outline, then each section in its own call. Smaller caps per call, complete outputs, parallelizable — the [pipeline pattern](/blog/adk-design-patterns-single-pipeline-swarm).
3. **Iterative continuation.** Feed the tail back ("continue from X") for genuinely long artifacts. Handle deduplication at the seam.
4. **Raise the cap** — last, because it only moves the cliff; you still need detection at the new height.

## Interaction with other generation knobs

- **Sampling:** low `temperature` tends toward more predictable lengths; high temperature can ramble — worth remembering when [tuning `GenerateContentConfig`](/blog/generatecontentconfig-temperature-top-p-top-k-seed).
- **Stop sequences:** the *surgical* way to end generation early — covered in [stop sequences and early termination](/blog/adk-stop-sequences-early-generation-termination).
- **Thinking budgets:** for reasoning models, thinking tokens often consume part of the output allowance — a large [thinking budget](/blog/adk-thinking-models-reasoning-budgets) plus a tight `max_output_tokens` can starve the actual answer. Size them together.
- **Self-hosted:** on [vLLM](/blog/adk-vllm-endpoints-low-latency-self-hosted-inference), output length directly occupies a sequence slot — tight caps improve *everyone's* latency, not just the bill.

## A practical policy

```python
CAPS = {
    "classify": 32,
    "tool_args": 256,
    "chat": 1024,
    "summary": 1500,
    "longform": 4096,
}

def config_for(task: str) -> GenerateContentConfig:
    return GenerateContentConfig(
        max_output_tokens=CAPS[task],
        temperature=0.2 if task in {"classify", "tool_args"} else 0.7,
        top_p=0.95,
    )
```

Per-task caps in one table, applied by the [agent factory](/blog/adk-dynamic-model-routing-task-complexity) — reviewable in a diff, testable, and impossible to forget on a new agent.

## Checklist

- [ ] Every agent has an explicit `max_output_tokens` (no silent defaults)
- [ ] `finish_reason == LENGTH` logged and alerted, never passed downstream
- [ ] Structured outputs validated after generation; truncation → retry or failure
- [ ] Caps sized from measured output distributions, not guesses
- [ ] Thinking budgets (if used) sized jointly with the cap
- [ ] Long tasks split into bounded calls rather than one giant generation

## Where to go next

Caps bound *how much*; [stop sequences](/blog/adk-stop-sequences-early-generation-termination) end generation at the right moment, and [thinking budgets](/blog/adk-thinking-models-reasoning-budgets) allocate the reasoning allowance inside the cap. The bigger reliability frame is [timeouts and deadlines](/blog/adk-global-timeouts-execution-deadlines), and structured consumers of bounded output are covered in [Pydantic `output_schema`](/blog/adk-pydantic-response-schema-structured-outputs).

## References

- [Simple agents with `LlmAgent`](https://adk.dev/agents/llm-agents/)
- [Google Gemini models for ADK agents](https://adk.dev/agents/models/google-gemini/)
- [googleapis/python-genai](https://github.com/googleapis/python-genai)
- [google/adk-python](https://github.com/google/adk-python)
