AI AgentsLangChain
How do temperature, top_p, and token limits affect agents?
Question 288 of 324 · Updated
On this page
- Direct answer
- 1. Separate the three controls
- 2. Sampling mechanics: why small changes can alter a tool trajectory
- Numerical illustration
- 3. Why agent behavior is more sensitive than ordinary chat
- Impact by agent activity
- 4. Configuring settings in LangChain
- Provider-specific constraints
- 5. Token limits: context, output, reasoning and cumulative usage
- Context budget example
- Multi-call usage example
- 6. Truncated tool calls and structured outputs
- 7. Tested Python example: inspect sampling distributions
- 8. Tested Python example: reserve completion budget across a run
- Runtime policy
- 9. Reproducibility and evaluation
- 10. Production tuning strategy
- Illustrative evaluation, not a benchmark
- Interview-ready answer
- References and verification status
Direct answer#
Temperature and top_p influence how a chat model selects its next tokens, while token limits constrain how much input and generated output an invocation or an entire agent run can consume. In LangChain agents, those settings affect more than the wording of the final answer: they can change which tools the model requests, the arguments it generates, the sequence of intermediate decisions, the probability of a truncated tool call or structured response, and the total cost and latency of a multi-step run.
A low temperature can reduce variation but cannot guarantee correctness, determinism or safe execution. A high temperature can support exploration but may produce unnecessary or inconsistent tool requests. A small generation budget can interrupt a valid response before it finishes, while an oversized budget can allow an inefficient agent to spend excessive resources. Choose settings through workload-specific evaluation and enforce independent application limits.
The Large Language Models curriculum (#147–150 and #153–155) and FDE #17 cover the general sampling mathematics. FDE #12 and LLM #51–54 cover context windows; AI Agents #201 covers distributed shared budgets. The LangChain initialization, execution-loop and model-switching lessons (#284–287) establish the framework abstractions. Here we focus on how sampling and generation constraints affect the behavior of an individual agent run.
1. Separate the three controls#
| Control | Acts on | Typical agent consequence |
|---|---|---|
| temperature | Distribution of next-token probabilities | Changes concentration and variability of action selection and generated arguments |
| top_p | Candidate token set retained for sampling | Excludes low-probability candidates according to cumulative probability mass |
| Per-request generation limit | Maximum generated tokens under the provider's accounting convention | May terminate a long response or tool request before it is complete |
| Context capacity | Input plus applicable generated-token capacity | Determines whether history, tools and output can fit in a request |
| Agent-level budget | Cumulative usage across model calls, retries and other work | Bounds an entire run rather than one model response |
These controls are related but not interchangeable. A smaller top_p is not a maximum length; a low temperature is not a token cap; a per-call output cap is not a run-level spending limit.
2. Sampling mechanics: why small changes can alter a tool trajectory#
For a model with logits and positive temperature T, the usual temperature-scaled softmax is:
Lower positive T increases concentration around relatively high-scoring tokens. Higher T generally flattens the distribution. At T = 1, temperature scaling leaves the logits unchanged. T = 0 is commonly interpreted as a request for greedy or near-greedy behavior where supported, rather than a literal division by zero.
Nucleus sampling sorts candidates by probability, retains the smallest leading set whose cumulative probability reaches top_p, and renormalizes the retained probabilities. The size of that set depends on the distribution; top_p = 0.8 does not mean that exactly 80% of the vocabulary is retained.
A simplified decoder may first apply temperature and then nucleus filtering. Actual providers may use different ordering, constrained decoding, additional filters or specialized generation algorithms. Not every provider exposes both settings.
This conceptual diagram is not a claim about the internal implementation of any particular hosted provider. In an agent, the generated sequence might encode a natural-language answer or a structured tool request. Once a valid tool is executed, its result changes the next model input and therefore the probabilities for later decisions.
Numerical illustration#
Consider four possible next tokens with probabilities 0.60, 0.25, 0.10 and 0.05 at T = 1. Applying temperature to logits equivalent to the logarithms of those probabilities produces the following distribution, rounded to four decimal places:
| Candidate | T = 0.5 | T = 1 | T = 2 |
|---|---|---|---|
| A | 0.8276 | 0.6000 | 0.4269 |
| B | 0.1437 | 0.2500 | 0.2756 |
| C | 0.0230 | 0.1000 | 0.1743 |
| D | 0.0057 | 0.0500 | 0.1232 |
At T = 1 and top_p = 0.8, candidates A and B are retained because their cumulative mass is 0.85. The renormalized probabilities are approximately 0.7059 and 0.2941, while C and D have zero sampling probability under this simplified procedure. At T = 1 and top_p = 0.5, A alone meets the threshold.
This example is about next-token selection, not a measured probability distribution over four actual tools. Tool requests are usually generated as multi-token structured sequences. Their probabilities are affected by the complete prompt, schema, preceding tokens, model training and provider decoding constraints. It would be incorrect to interpret this table as a real-world tool-selection accuracy benchmark.
3. Why agent behavior is more sensitive than ordinary chat#
An ordinary text-generation task might tolerate differences in phrasing. In an agent, a small early difference can change the external information available to subsequent model calls.
Suppose a user asks whether a synthetic order has been delivered. The agent can call lookup_order or lookup_tracking. A request that already contains the order ID but not a tracking number should first retrieve order information; a tracking lookup must receive an authorized tracking identifier obtained from trusted evidence.
A sampled response might choose the appropriate order lookup, ask a clarifying question, request tracking prematurely or produce an unsupported conclusion. Sampling settings may change the frequency of these outcomes. They cannot establish the correct tool prerequisites by themselves.
The application must enforce authorization and validate tool inputs before execution regardless of sampling parameters. A model's refusal to call a tool, or its confident assertion of a result, is not proof that the task is complete.
Impact by agent activity#
| Activity | Possible sampling impact | Independent control |
|---|---|---|
| Tool selection | Variation in chosen tool or number of calls | Tool allowlist and prerequisite checks |
| Tool arguments | Different identifiers, formats or values | Schema and domain validation |
| Planning | Alternative plans and exploration | Bounded steps and explicit acceptance criteria |
| Structured extraction | Variation in field values or missing information | Schema validation and evidence checks |
| Final explanation | Variation in style and detail | Required content and grounding checks |
Lower variation can be helpful for a stable extraction workload, but a highly concentrated distribution may repeatedly choose the same wrong action. Increasing variation may help generate alternative plans, yet it may also increase invalid requests or wasted work. Both claims must be tested for the specific model and task.
4. Configuring settings in LangChain#
With a compatible integration, model-level settings can be supplied during initialization. Keep the approved generation profile outside the agent's domain logic.
PYTHONfrom langchain.chat_models import init_chat_model from langchain.agents import create_agent def lookup_order(order_id: str) -> str: """Read an authorized synthetic order status.""" if order_id != "A12": return "not found or access denied" return "shipped" model = init_chat_model( "gpt-4o-mini", model_provider="openai", temperature=0.2, max_tokens=512, ) agent = create_agent( model=model, tools=[lookup_order], system_prompt="Answer only from authorized order evidence.", ) result = agent.invoke({ "messages": [ {"role": "user", "content": "What is the status of order A12?"} ] }) print(result["messages"][-1].content)
This is an illustrative SDK example, not a live-tested integration. The model identifier, temperature range and output-limit parameter must be supported by the actual model and installed adapter. Supply credentials through trusted runtime configuration. The synthetic tool is not a complete authorization implementation; real scope must come from authenticated domain services.
If the chosen adapter supports top_p, a controlled experiment may replace the sampling profile with another approved configuration, for example setting top_p to 0.9 while keeping other supported settings fixed. Do not assume every model accepts both temperature and top_p simultaneously. Use the provider's recommended parameters and evaluate one factor at a time before introducing a more complex joint experiment.
Provider-specific constraints#
| Provider or deployment family | What to verify before setting parameters |
|---|---|
| OpenAI-compatible chat integrations | Whether the model accepts temperature and top_p, and how the adapter maps output limits to the selected API |
| Anthropic integrations | Supported sampling options, output limit, and any restrictions associated with thinking modes |
| Gemini / Vertex AI integrations | Supported generation configuration and backend-specific thinking or output-token behavior |
| Local inference servers | Decoder implementation, sampling order, tokenizer, seed support and server-enforced limits |
Some reasoning-oriented deployments accept only restricted sampling settings or do not expose ordinary sampling controls. Some APIs distinguish maximum completion tokens, maximum output tokens and thinking budgets. Do not blindly forward a generic max_tokens keyword or treat its meaning as universal.
Record the actual model revision, integration version, supported parameters and observed response metadata for each approved profile. A setting accepted by a Python constructor may still be rejected at invocation, or may be translated differently by an adapter.
5. Token limits: context, output, reasoning and cumulative usage#
A per-invocation output budget should be distinguished from the context capacity and the entire run's budget.
| Quantity | What it represents |
|---|---|
| Input tokens | System instructions, user messages, relevant history, tool definitions, tool observations and other provider-counted input |
| Visible generated tokens | Response text or structured content returned to the caller |
| Reasoning or thinking tokens | Additional generated computation counted according to the selected model and API |
| Generation ceiling | Limit on generated output under the provider's accounting rules |
| Context ceiling | Maximum supported combined or otherwise defined context capacity |
| Run-level usage | Accounted usage across every model invocation and retry |
Reasoning tokens are not universally counted in the same way. In some APIs they consume part of a total completion-token allowance; in others, thinking configuration and output accounting follow separate conventions. A 512-token ceiling therefore does not universally guarantee 512 tokens of visible answer text. Use the returned usage metadata and the documented semantics rather than subtracting guessed reasoning counts.
Do not attempt to retrieve hidden reasoning or treat a reasoning trace as authorization. The application should evaluate observable tool calls, returned evidence and validated outcomes.
Context budget example#
Assume a hypothetical model has a combined context capacity of 8,192 tokens and a provider generation cap of 2,048 tokens. If the conservative estimate of the current input is 7,000 tokens, only 1,192 tokens remain under the combined context ceiling, even before considering additional provider-specific reservations or limits.
A request for 1,500 generated tokens would exceed that simplified context model. The application should reduce the requested output limit, compact or retrieve less input, or reject the request safely. It must not truncate important tool call/result pairs, remove unresolved approvals or discard essential evidence without validation.
Multi-call usage example#
Suppose an agent performs three model calls:
| Model call | Input tokens | Accounted generated tokens | Total |
|---|---|---|---|
| Initial decision | 1,200 | 180 | 1,380 |
| After first tool | 1,700 | 240 | 1,940 |
| Final answer | 2,100 | 460 | 2,560 |
| Total | 5,000 | 880 | 5,880 |
The total input is 5,000, not just the 2,100 tokens of the last invocation, because prior context can be sent repeatedly. In this hypothetical example, the generated counts already include any reasoning tokens charged as part of output, so adding such tokens again would double-count them.
At illustrative rates of $2 per million input tokens and $8 per million generated tokens, the model charge is:
Real services may price cached inputs, reasoning usage, tool services or other features differently. These figures are not actual provider pricing or observed benchmarks. The main lesson is to account for the complete agent trajectory.
6. Truncated tool calls and structured outputs#
A model can hit a generation limit before producing a complete tool request or a schema-valid response. Depending on the API, the integration may return a length-limit finish reason, an invalid tool call, incomplete structured content or an exception.
Never execute an incomplete tool request simply because its prefix resembles valid JSON. Assemble supported streaming events, verify completion, parse and validate the schema, then apply business authorization. A syntactically valid object may still be incomplete relative to the task or unsupported by evidence.
A retry can be safe for generating a new read-only proposal, but not for repeating an uncertain write without reconciliation. If a previous tool action was completed before the final answer was truncated, preserve its authoritative result and do not execute the action again merely to regenerate the response.
Use schema-constrained generation when compatible, but keep an application-side validator. Constrained decoding can improve syntactic conformance, not factual grounding or permission enforcement.
7. Tested Python example: inspect sampling distributions#
The following standard-library example implements a simplified positive-temperature softmax followed by top-p filtering. It uses synthetic logits rather than provider outputs and deliberately rejects zero temperature, which requires a separate decoding policy.
PYTHONfrom math import exp, isfinite, log, isclose def distribution(logits, temperature, top_p): if (not logits or any(not isfinite(z) for z in logits) or not isfinite(temperature) or temperature <= 0 or not 0 < top_p <= 1): raise ValueError('invalid sampling inputs') peak = max(logits) weights = [exp((z - peak) / temperature) for z in logits] probs = [w / sum(weights) for w in weights] ranked = sorted(range(len(probs)), key=lambda i: (-probs[i], i)) keep, mass = [], 0.0 for i in ranked: keep.append(i) mass += probs[i] if mass >= top_p: break return [probs[i] / mass if i in keep else 0.0 for i in range(len(probs))] logits = [log(p) for p in (.6, .25, .10, .05)] base = distribution(logits, 1, 1) cold = distribution(logits, .5, 1) hot = distribution(logits, 2, 1) nucleus = distribution(logits, 1, .8) assert all(isclose(x, y) for x,y in zip(base, (.6,.25,.1,.05))) assert cold[0] > base[0] > hot[0] assert all(isclose(x, y) for x,y in zip(nucleus, (12/17,5/17,0,0))) assert distribution(logits, 1, .5) == [1,0,0,0] assert isclose(sum(hot), 1) try: distribution(logits, 0, .8) except ValueError: pass else: raise AssertionError('zero temperature must be handled separately') print('sampling: 6 checks passed') print('cold:', [round(x,4) for x in cold], 'hot:', [round(x,4) for x in hot])
Actual local execution on Python 3.13.5:
sampling: 6 checks passed
cold: [0.8276, 0.1437, 0.023, 0.0057] hot: [0.4269, 0.2756, 0.1743, 0.1232]The code calculates a distribution; it does not sample tokens from an actual LLM. Production decoders use optimized implementations and can have different numerical precision, tie policies or filtering semantics. The example is intentionally small enough to verify by hand. Its purpose is to clarify why temperature and nucleus filtering jointly affect candidate probabilities rather than prescribe an actual provider's internal algorithm.
8. Tested Python example: reserve completion budget across a run#
A generation limit should be calculated from the available capacity and remaining cumulative allowance rather than chosen independently for every request.
The following conservative policy assumes that the provider uses a combined input/output context ceiling, that the input estimate is an upper bound, and that all generated usage fits within the configured output cap. It retains a separate finalization reserve for future work. Adapt those assumptions for the provider's real accounting and include future input in any reserve that is expected to fund another model call.
PYTHONdef output_cap(*, context_limit, provider_cap, input_upper, run_remaining, final_reserve, requested): values = (context_limit, provider_cap, input_upper, run_remaining, final_reserve, requested) if any(type(n) is not int or n < 0 for n in values): raise ValueError('nonnegative integer budgets required') return max(0, min(provider_cap, requested, context_limit - input_upper, run_remaining - input_upper - final_reserve)) assert output_cap(context_limit=8192, provider_cap=2048, input_upper=3000, run_remaining=5000, final_reserve=800, requested=1500) == 1200 assert output_cap(context_limit=8192, provider_cap=2048, input_upper=8000, run_remaining=20000, final_reserve=800, requested=1500) == 192 assert output_cap(context_limit=8192, provider_cap=512, input_upper=1000, run_remaining=8000, final_reserve=800, requested=1500) == 512 assert output_cap(context_limit=8192, provider_cap=2048, input_upper=3000, run_remaining=3500, final_reserve=800, requested=1500) == 0 assert output_cap(context_limit=8192, provider_cap=2048, input_upper=9000, run_remaining=20000, final_reserve=800, requested=1500) == 0 try: output_cap(context_limit=8192, provider_cap=2048, input_upper=-1, run_remaining=5000, final_reserve=800, requested=1500) except ValueError: pass else: raise AssertionError('invalid budget accepted') print('budget: 6 checks passed')
Actual local result: budget: 6 checks passed. The tests cover the cumulative allowance, context constraint, provider output ceiling, insufficient finalization reserve, oversized input and invalid configuration.
For the first case, the minimum of the requested 1,500, provider cap 2,048, available context 5,192 and available run allowance 1,200 gives a cap of 1,200. A result of zero means that no positive generation allowance remains under this policy; the caller must not interpret zero as an unlimited output parameter or blindly send a request with zero.
This is a calculation, not a concurrency-safe accounting service. A real agent should reserve the conservative upper bound before invocation, settle using observed usage afterward, retain reservations while billing is uncertain, and separately track model-call count, tool-call count, elapsed time and monetary costs. Parallel branches require atomic reservations or an equivalent coordinated accounting mechanism, which the shared-budget lesson #201 addresses.
Runtime policy#
The policy must be integrated into the actual agent runtime through supported hooks, graph logic or an application-level model adapter. The exact LangChain middleware interfaces are version-dependent. The code above does not claim to enforce provider-side limits by itself.
9. Reproducibility and evaluation#
Temperature zero, a fixed top_p and a fixed seed where supported can reduce some sources of variation. They do not guarantee reproducibility across model revisions, distributed serving systems, hardware, request serialization, tool responses, retrieval changes or parallel execution order.
For agent regression tests, preserve more than the user prompt:
- Approved model identifier, revision or deployment and integration version.
- Exact supported generation settings and seed when available.
- Versioned system instructions, tool schemas and response schema.
- Deterministic test fixtures for tool outputs and external observations.
- Expected tool prerequisites, authorization outcomes and final evidence contract.
- Usage, finish reasons, retry behavior and run termination status.
Use scripted model substitutes for deterministic policy and protocol tests. Use repeated real-provider trials for behavioral evaluation, because an offline sampling simulation cannot predict a hosted model's tool-selection accuracy. Compare distributions of task outcomes, not only exact response text.
10. Production tuning strategy#
Start from the provider's supported defaults, then choose a small set of approved profiles appropriate to your workload. Do not treat a particular temperature such as 0.2 or top_p such as 0.9 as a universal optimum.
| Workload | Candidate tuning direction | Acceptance measures |
|---|---|---|
| Authorized data lookup | Evaluate lower-variation settings where supported | Correct tool, valid arguments, grounded status |
| Schema-based extraction | Use compatible structured-output constraints; avoid excessive variation | Schema validity, field accuracy, evidence consistency |
| Exploratory research | Compare controlled diversity with a baseline | Novel useful findings, citation accuracy, bounded effort |
| Planning and critique | Evaluate alternative plans without unbounded retries | Plan feasibility, task success, cost |
| Customer-facing responses | Balance consistency and clarity | Verified information, response quality, latency |
Illustrative evaluation, not a benchmark#
Suppose 100 fixed, synthetic order-related tasks are evaluated under two compatible sampling profiles with identical tool permissions and token ceilings:
| Metric | Profile A | Profile B |
|---|---|---|
| Verified successful outcomes | 96 | 92 |
| Invalid proposed tool arguments | 3 | 8 |
| Total accounted usage | 480,000 tokens | 550,000 tokens |
| Unauthorized actions executed | 0 | 0 |
| Cost-effective outcome decision | Evaluate with prices | Evaluate with prices |
A appears preferable for this hypothetical lookup workload. The same conclusion need not hold for an exploratory research workload. These counts are invented solely to illustrate measurement design. No real LangChain or provider benchmark was performed. The difference in a small sample may be due to chance; repeat trials and analyze uncertainty and safety-critical subgroups.
For a production experiment:
- Hold model, prompts, tools, fixtures and output budget fixed while comparing supported sampling settings.
- Inspect task-level failures rather than aggregate success alone.
- Tune per-request generation caps against completion rates and truncation failures.
- Establish separate run-level token, time and tool-action limits.
- Apply provider-specific capability and safety checks before a limited rollout.
- Monitor p95 latency, cost per verified successful task, unexpected tool calls, invalid structured outputs and budget exhaustion.
- Roll back a profile that violates a hard policy or workload-specific release gate.
A profile change is a behavioral change even if no agent source code changes. Version and evaluate it like any other production configuration. Never weaken deterministic authorization, validation or approval controls to improve measured model completion rates.
Interview-ready answer#
Temperature changes the concentration of next-token probabilities and top_p restricts the sampled candidates to a cumulative probability nucleus. In an agent, these settings influence not only response style but also tool-selection behavior, generated arguments and multi-step execution trajectories. Token limits constrain how much a single invocation can generate, while a separate cumulative run budget accounts for repeated input, reasoning and output usage across calls. I use supported provider-specific settings, validate complete tool calls and structured outputs, reserve capacity for finalization, and evaluate the agent on representative tasks. Low temperature is not a security guarantee and a per-call token limit is not an agent-level cost limit.
References and verification status#
Official documentation research leads for checking the installed integration and model:
- LangChain models
- LangChain agents
- LangChain structured output
- LangChain middleware overview
- OpenAI API reference
- Anthropic API documentation
- Gemini API documentation
The authorized offline research exception applies. The references are official documentation entry points, not live-accessed evidence for current parameter support. The two dependency-free Python examples were executed on Python 3.13.5: six sampling checks and six budget checks passed. Local inspection confirmed that langchain, langchain_openai and langgraph were not installed; the SDK illustration and provider behavior were not executed or verified. Mermaid diagrams use standard fenced syntax; rendering and public website display were not verified. Hypothetical workload figures are explicitly illustrative.
References
- 1.LangChain modelsdocs.langchain.com
- 2.LangChain agentsdocs.langchain.com
- 3.LangChain structured outputdocs.langchain.com
- 4.LangChain middleware overviewdocs.langchain.com
- 5.OpenAI API referenceplatform.openai.com
- 6.Anthropic API documentationdocs.anthropic.com
- 7.Gemini API documentationai.google.dev
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps