SCROLL TO EXPLORE
01 · USER REQUEST
02 · AUTH / VALIDATE
03 · CONTEXT ASSEMBLY
04 · TOKENIZATION
05 · INFERENCE
06 · OUTPUT PARSING
07 · TOOL EXECUTION
08 · FEEDBACK LOOP
09 · FINAL RESPONSE
10 · TELEMETRY
Stage 01
User Request
JSON payload over TLS 1.3 / HTTP2. The conversation, tool schemas, and hyperparameters are serialized and sent to the API gateway edge.
HTTP POST /v1/messages
Stage 02
Auth & Validation
HMAC key verification, schema validation, context-window size check, and token-bucket rate limiting — all in <10 ms.
x-api-key → SHA-256
Stage 03
Context Assembly
Messages are flattened into a single token sequence using the model's conversation template. Tool schemas are injected after the system prompt.
[SYS] … [HUMAN] … [TOOL]
Stage 04
Tokenization
BPE encodes text to integer IDs. Each ID maps to a dense embedding vector via a lookup in E ∈ ℝ^(V×d). RoPE adds position information.
BPE · V≈100k · d=4096
Stage 05
Inference
Multi-layer transformer forward pass across a sharded GPU cluster. KV-cache stores prior keys/values; only new tokens require fresh compute.
Tensor · Pipeline · Expert parallel
Stage 06
Output Parsing
The serving stack detects tool_use blocks mid-stream. stop_reason: "tool_use" triggers dispatch without waiting for full response completion.
stop_reason: tool_use
Stage 07
Tool Execution
Client or server dispatches the function call in a sandboxed environment. Independent tool calls run in parallel to minimize round-trip latency.
Firecracker · seccomp-bpf
Stage 08
Feedback Loop
tool_result injected as a new user turn. Full updated context re-submitted. Context window grows by N_call + N_result tokens each iteration.
N_k ≈ N_0 + Σ(N_call + N_result)
Stage 09
Final Response
stop_reason: end_turn triggers SSE streaming. Tokens emitted as sampled — no buffering. Speculative decoding may emit k tokens per forward pass.
SSE · chunked transfer
Stage 10
Logging & Telemetry
TTFT, TPS, tool_call_count, cache_hit_ratio, and OTel spans emitted. PII scrubbed before reaching logging systems. Used for billing and capacity planning.
OpenTelemetry · trace_id
A Technical Deep-Dive

Inside Agentic
Tool Use

From the moment an API request leaves your machine to the final streamed token — every layer, every decision, every loop.

SCROLL · DRAG TO ROTATE

Modern LLM APIs are deceptively simple on the surface — you POST some JSON, you get text back. But when those APIs support tool use, what actually happens between request and response spans multiple subsystems: authentication layers, context management, GPU-accelerated autoregressive decoding, sandboxed function dispatch, and multi-turn feedback loops. This post walks through every stage of that journey, with the math and engineering that make it work.

01
User Request

The Request Leaves Your Machine

It starts with a POST. The client serializes a messages array, an optional system prompt, a tools list, and generation hyperparameters into a JSON body, then fires it over TLS 1.3 to the API gateway.

// Minimal agentic request
{
  "model": "claude-sonnet-4-20250514",
  "max_tokens": 4096,
  "system": "You are a research assistant...",
  "messages": [{ "role": "user", "content": "What is the weather in Tokyo?" }],
  "tools": [{
    "name": "get_weather",
    "description": "Returns current weather for a city.",
    "input_schema": { "type": "object", "properties": { "city": { "type": "string" } }, "required": ["city"] }
  }]
}

The wire protocol is HTTP/2, meaning the connection is multiplexed — several concurrent requests share a single TCP stream. TLS terminates at an edge load balancer, well before the request reaches compute. The plaintext JSON then travels over the internal network to the API gateway proper.

Network Latency is Non-Trivial. Even at the speed of light, a transatlantic round-trip adds ~70–90 ms. Agentic loops multiply this: a 5-turn tool-use chain experiences 5× the round-trip overhead before a single token is generated.
02
Authentication & Validation

Gatekeeping Before a Single Token is Processed

The gateway's first job is to decide whether this request should proceed. This happens in strict order and fast — it must complete in single-digit milliseconds or it degrades perceived time-to-first-token.

API Key Authentication

The x-api-key header carries a long random token, typically at least 128 bits of entropy encoded in base-64. The gateway computes a cryptographic hash of the presented key and does a constant-time comparison against stored hashes — the actual secrets are never stored plaintext. Constant-time comparison is critical because otherwise an attacker can probe which key bytes match by measuring tiny response-time differences.

Schema Validation & Input Sanitisation

The JSON body is validated against a schema before it touches downstream services. This catches malformed requests early: missing required fields, invalid tool definitions, wrong content block types, impossible sampling parameters, and messages that exceed the model's context window.

Token counting happens here too. The serialized context must fit within the model's context window $C$. If $\text{tokens}(\text{prompt}) + \text{max\_tokens} > C$, the gateway returns a 400 immediately rather than burning capacity on a request that cannot be served.

$$\text{stored} = \text{SHA-256}(k_{\text{secret}})$$ $$\text{auth} = \text{ct\_eq}\!\left(\text{SHA-256}(k_{\text{presented}}),\ \text{stored}\right)$$
Key verification — constant-time hash comparison to prevent timing side-channel attacks

Rate Limiting: Token Bucket

Limits are enforced on requests-per-minute (RPM) and tokens-per-minute (TPM) simultaneously. A common implementation uses a token bucket per API key in Redis or another low-latency shared store:

$$B_{t+\Delta t} = \min\!\left(B_{\max},\ B_t + r\cdot\Delta t\right)$$
Token bucket refill: $B$ = current tokens, $r$ = refill rate (tokens/sec), $B_{\max}$ = bucket capacity. A request consuming $n$ tokens is rejected if $B_t < n$.

If the bucket has insufficient tokens for the estimated request cost, the gateway responds 429 Too Many Requests with a Retry-After header. More sophisticated systems combine token buckets with sliding-window logs so bursty but legitimate users are treated fairly across multiple regions.

Gateway Processing — Latency Breakdown
03
Context Assembly

Assembling the Context Window

Once authenticated and validated, the request moves into context assembly. This is where the clean API abstraction gets flattened into a single linear token sequence the model can consume.

The messages array is serialized using a model-specific conversation template. A simplified version looks like:

<!-- BOS -->[BOS] [SYSTEM] You are a helpful assistant... [/SYSTEM]
[HUMAN] What is the weather in Tokyo? [/HUMAN]
[ASSISTANT] ← model generates from here

The tools array is serialized into this same token stream, usually after the system prompt, describing each tool's name, description, and JSON Schema. There is no separate router network deciding whether to call a tool; the tool decision emerges from the same autoregressive forward pass that generates normal text.

Context Window Budget — Interactive

Adjust the sliders to see how context budget is allocated across a multi-turn agentic session.

KV-Cache Priming

For long static system prompts — a common pattern in agentic deployments — providers cache the key-value state computed during prefill. On subsequent requests sharing the same prefix, cached KV state is reused, dramatically reducing compute and latency for the static portion:

$$\text{TTFT}_{\text{cached}} \approx \frac{N_{\text{dynamic}}}{N_{\text{total}}} \cdot \text{TTFT}_{\text{cold}}$$
Prompt caching speedup — only the dynamic (non-cached) tokens require fresh prefill computation. Cached tokens are typically billed at a discounted rate because prefill has already been amortized.
KV-Cache — Autoregressive State

Each cell represents one token × one layer KV state. Green = cached prefix, amber = generated in this loop, blue = active token, purple = queued/speculative positions, grey = empty future slots.

04
Tokenization

Tokenization: Text to Integer IDs

BPE starts with a vocabulary of individual bytes (256 entries), then iteratively merges the most frequent adjacent pair into a new token, repeating until the vocabulary reaches target size $V$. Common English words map to one or a few tokens; rare words and code are split into subword units.

Each integer token ID $t_i$ is mapped to a dense vector via the embedding matrix $\mathbf{E} \in \mathbb{R}^{V \times d}$, then position is encoded via RoPE:

$$\mathbf{x}_i = \mathbf{E}[t_i] + \text{PE}_{\text{RoPE}}(i)$$ $$\mathbf{q}'_i = R_{\Theta,i}^d \mathbf{q}_i, \quad \mathbf{k}'_j = R_{\Theta,j}^d \mathbf{k}_j$$
RoPE encodes position by rotating Q/K vectors by position-dependent angles in each attention head — enabling better extrapolation to unseen sequence lengths.
BPE Tokenization — Live Viewer
05
Inference

Inference: The Forward Pass at Scale

At each of $L$ layers, the model applies multi-head self-attention followed by a feedforward network. The attention mechanism computes a weighted sum over all previous token representations:

$$\text{Attention}(\mathbf{Q},\mathbf{K},\mathbf{V}) = \text{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\mathbf{V}$$ $$\text{MultiHead}(\mathbf{X}) = \text{Concat}(\text{head}_1,\ldots,\text{head}_H)\mathbf{W}^O$$
Scaled dot-product attention and multi-head attention. $d_k$ is key dimensionality; $H$ heads attend to different representation subspaces simultaneously.
Attention Pattern Explorer — Interactive

Select an attention head and hover over tokens to see what each position attends to. This simulates a tool-use prompt: the model must attend to the tool schema to decide when to call it.

KV-Cache During Generation

Autoregressive generation produces one token per forward pass. Without caching, each new token would require recomputing attention over the entire context from scratch — $O(n^2)$ per token for a sequence of length $n$. The KV-cache stores the key and value matrices for prior tokens, reducing each generation step to attend over existing state instead of rebuilding it.

$$\text{KV-cache memory} = O\!\left(n \cdot L \cdot H \cdot d_k\right)$$
$n$ tokens, $L$ layers, $H$ KV heads, and key/value width $d_k$. Long-context agentic systems spend a surprising amount of memory just remembering what has already happened.

This memory pressure is why serving stacks care about grouped-query attention, multi-query attention, cache paging, prefix reuse, and eviction policies. A long tool session can be bottlenecked by KV-cache residency before raw FLOPs become the limiting factor.

Sampling & Temperature

Each forward pass produces logits $\mathbf{z} \in \mathbb{R}^V$. Temperature $T$ controls sharpness before sampling:

$$P(t_i) = \frac{\exp(z_i/T)}{\sum_j \exp(z_j/T)}$$
Temperature scaling: $T \to 0$ approaches greedy decoding; $T = 1$ is unmodified; $T > 1$ flattens the distribution. For tool calls, low $T$ prevents malformed JSON.
Sampling Distribution — Interactive

Drag the temperature slider to see how it reshapes the next-token probability distribution. Top-p (nucleus) sampling selects from the minimal set of tokens summing to probability $p$.

Model Parallelism

TechniqueWhat is ShardedBenefit
Tensor ParallelismWeight matrices split across GPUsReduces per-GPU memory, increases parallelism
Pipeline ParallelismLayers split into stagesEnables models too deep for one node
Sequence ParallelismToken sequence split across GPUsHandles 100k+ token contexts
Expert ParallelismMoE experts distributedScales capacity without proportional compute
Time-to-First-Token vs. Input Length — Cold vs. Cached
06
Output Parsing + Tool Execution

From Tokens to Tool Calls

When the model decides a tool should be called, it emits a structured tool_use content block. The serving infrastructure detects this mid-stream — stop_reason: "tool_use" is the signal.

// Model's raw response at tool_use stop
{
  "role": "assistant",
  "content": [
    { "type": "text", "text": "I'll look up the weather in Tokyo." },
    { "type": "tool_use", "id": "toolu_01A2B3C4", "name": "get_weather", "input": { "city": "Tokyo" } }
  ],
  "stop_reason": "tool_use"
}
Constrained Decoding. Many production systems use grammar-guided sampling to guarantee syntactically valid JSON for tool calls — restricting which tokens can be sampled based on the JSON parser state. This eliminates parse errors without fine-tuning.

The Execution Model

In client-side tool use, the API returns at stop_reason: "tool_use". Your code executes the tool, then submits a new message containing a tool_result block. The model never directly calls external systems; it emits structured intent, and the host runtime decides what to run.

Sandboxing & Security

For server-side tool execution, sandboxing is non-negotiable. Common defenses include seccomp-bpf or gVisor syscall filtering, Firecracker microVM isolation, network egress allowlists, CPU and memory quotas, wall-clock timeouts, and strict secret-scoping so a tool can only access credentials it actually needs.

Parallel Execution

When multiple tool calls are independent (no data dependency), parallel dispatch gives:

$$T_{\text{parallel}} = \max_i T_{\text{exec},i} + T_{\text{overhead}}$$ $$T_{\text{sequential}} = \sum_i T_{\text{exec},i} + n \cdot T_{\text{overhead}}$$
For $n$ equal-cost tools, parallel execution reduces total latency by factor $\approx n$. Most production orchestrators detect independence by checking for cross-call input references.
Agentic Loop — Live Simulation

Step through a realistic 3-tool agentic session and watch context, token cost, and latency accumulate.

07
Feedback Loop

Feeding Results Back: The Agentic Loop

The tool result is injected as a tool_result block attributed to the original tool_use_id. The full updated messages array — the user turn, the assistant's tool call, and the tool observation — is submitted as a new API request. This is the agentic loop.

Each iteration adds tokens to the context:

$$N_k \approx N_0 + \sum_{i=1}^{k}\!\left(N_{\text{call},i} + N_{\text{result},i}\right)$$
Context growth after $k$ tool-call rounds. $N_0$ = initial prompt, $N_{\text{call}}$ = tool_use block tokens, $N_{\text{result}}$ = tool_result tokens. With prompt caching, only the delta from the previous call is freshly computed.

This growth has two practical effects. First, cost: every later inference call prices and processes the larger accumulated context. Second, reliability: if raw tool outputs are dumped into the transcript without summarization, the model may attend to stale or irrelevant details in later turns.

Loop Termination

The loop terminates when the model returns stop_reason: "end_turn", or when a guardrail fires: maximum iteration count, context-window exhaustion, repeated tool failures, or human-approval checkpoints for high-stakes actions. Good orchestrators do not merely let the model call tools forever; they bound the process and summarize failure modes back into the context.

08
Final Response & Streaming

The Final Response: Streaming to the Client

Once the model emits stop_reason: "end_turn", the response streams via Server-Sent Events. Tokens are emitted as sampled — no buffering of the full response.

Speculative Decoding

A small draft model generates $k$ candidate tokens quickly; the large target model verifies them in one batched forward pass. Accepted tokens are emitted for the cost of ~one forward pass:

$$\text{Speedup} \approx \frac{k\cdot\alpha}{1 + \alpha\cdot\mathbb{E}[k-m]}$$
$\alpha$ = token acceptance rate, $m$ = expected rejected tokens, $k$ = draft length. Real-world speedups of 2–3× for predictable text.
Throughput vs Batch Size — Standard vs Speculative Decoding
09
Logging & Telemetry

Observability: What Gets Measured

After the final response is transmitted, the infrastructure emits telemetry for billing, capacity planning, quality debugging, and safety monitoring. Agentic sessions especially need traceability because the visible answer is the product of several model calls, tool calls, retries, and branching control-flow decisions.

MetricWhat It MeasuresTypical Value
ttft_msTime from request receipt to first token200–800 ms
tpsOutput tokens per second50–200 tok/s
tool_call_countTool_use blocks in session0–50
tool_latency_p9999th-percentile tool execution50–2000 ms
cache_hit_ratioFraction of input from KV-cache0–0.95
stop_reasonWhy generation stoppedend_turn / tool_use / max_tokens

Distributed Tracing

For multi-service pipelines, OpenTelemetry-style tracing is essential. A root trace span is created at the gateway; child spans record validation, inference prefill, token generation, each tool execution, retries, and response streaming. Correlating these by a shared trace_id makes it possible to reconstruct the causal timeline of a complex agentic session and explain why one run was slow or wrong.

Privacy & Data Handling. Telemetry pipelines are a significant attack surface. Tool results may contain PII or credentials that must be scrubbed before reaching logging systems. Field-level redaction policies should treat raw conversation data as a separate, access-controlled artifact from operational metrics.
End-to-End Latency Budget — Single Tool-Use Turn

Synthesis

The Full Picture

What feels like a single API call is an orchestrated sequence of distributed systems decisions. The agentic loop multiplies this complexity: each iteration re-traverses the full stack with a growing context window and accumulated tool results. Understanding each layer — from TLS handshakes and rate-limit algorithms to KV-cache eviction and speculative decoding — is what separates someone who uses an agentic framework from someone who can build, debug, and optimise one.

The stack will continue to evolve — longer contexts, faster inference, richer tool ecosystems — but the fundamental structure of the agentic loop is likely to remain: plan, call, observe, reason, repeat. Getting the plumbing right is what makes the rest possible.