Production-grade guide to agent context engineering covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Agent Context Engineering is the practice of designing, controlling, and persisting the information an AI agent references across turns, sessions, and tool invocations. It matters whenever an agent’s behavior depends on what it has seen before—conversation history, retrieved documents, configuration state, or cached query results. When context is mismanaged, agents repeat themselves, act on stale data, or fail silently because the context window overflows or the prompt sent to the model diverges from the engineer’s intent. This reference page maps the concrete engineering tasks required to keep agent context reliable, observable, and resilient.
An engineer typically begins a new agent session by constructing a deterministic prompt payload rather than relying on implicit state. This means selecting which roles appear first, which system instructions are immutable, and which user-supplied data is injected per-request.
A common pattern uses a curl call to a chat‑completion endpoint with a structured JSON body:
curl -s -X POST \
-H "Content-Type: application/json" \
-d '{
"model": "default",
"messages": [
{"role": "system", "content": "You are a logistics coordinator. Use the provided tracking IDs only."},
{"role": "user", "content": "Session 42: track parcel 94u‑kp1."}
],
"max_tokens": 4096
}' https://api.example.com/v1/chat/completions
The system message establishes a baseline that should not be overwritten by later user turns. The max_tokens flag caps the total tokens the endpoint will accept; exceeding it typically returns an error rather than silently truncating. Engineers should treat max_tokens as a hard ceiling for the combined prompt + completion, not as a soft limit the model enforces.
When launching an agent as a containerized service, docker run can inject the session context root via an environment variable:
docker run \
--restart policy=unless-stopped \
-e CONTEXT_ROOT=session-42 \
-v /var/lib/agent/context:/data/context \
my-agent-image:2024.09
In Kubernetes, a equivalent rollout can be triggered with kubectl:
kubectl set env deployment/agent CONTEXT_ROOT=session-42
kubectl rollout restart deployment/agent
These commands ensure the same context root is available to every agent instance in the pod, avoiding divergent state across replicas.
Agents often need to remember facts, tool outputs, or user preferences from earlier turns, possibly across process restarts or cluster migrations. The engineering pattern is to externalize this state into a durable store—typically a relational database—before each LLM call and reload it afterward.
A practical schema in PostgreSQL might look like:
CREATE TABLE agent_context (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
session_id UUID NOT NULL,
turn_number INTEGER NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
tokens INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
To record a turn after the agent returns a tool result:
INSERT INTO agent_context (session_id, turn_number, role, content, tokens)
VALUES ('sess-9c3e', 7, 'assistant', 'Used carrier lookup API; found status "in transit".', 142);
To retrieve the full history before the next LLM call:
SELECT role, content
FROM agent_context
WHERE session_id = 'sess-9c3e'
ORDER BY turn_number ASC;
The tokens column lets the engineer approximate the contribution of each row toward the context window. When the total approaches the limit, the engineer can selectively prune rows—often the oldest user or assistant messages that carry low‑information density—before sending the payload to the model.
If the agent runs as a stateful service, a Docker volume or persistent volume claim can back the context store, and kubectl get pvc can verify that the volume is bound and available across pod reschedules.
Context windows are finite, and the total token count of the payload sent to the LLM frequently exceeds the model’s advertised limit. Engineers must implement a reshaping strategy before the final curl payload is constructed.
A common approach is priority‑ordered truncation: system and role‑definition messages are kept intact, while older conversation turns are removed from the tail until the token budget is satisfied. The engineer can use jq to filter and reorder the JSON payload programmatically:
echo "$PAYLOAD" | jq '
[ .[] | select(.role == "system") ] +
[ .[] | select(.role == "user" and .importance == "high") ] +
[ .[] | select(.role == "assistant" and .turn_number > 5) ]
' > trimmed_payload.json
The select() expressions promote high‑importance user messages and discard assistant turns beyond a configurable threshold. The resulting file is then fed into the same curl command shown earlier, now with a token count well under the max_tokens ceiling.
A silent failure mode occurs when the client‑side token counter (often based on tiktoken or a similar BPE tokenizer) reports 3,800 tokens, but the server rejects the request with “context length must be between 0 and 4096 tokens.” The discrepancy arises because some SDKs count role and content delimiters differently, or because the model’s internal tokenizer applies slightly different byte‑pair encoding. Engineers should always validate the server‑reported limit by sending a probe request with a known‑size payload and reading the exact error text returned.
Context drift happens when the information an agent uses to make decisions diverges from the engineer’s intended state. Drift can be silent: the agent continues to operate, but its choices are based on stale or corrupted entries.
One sharp edge is the mismatch between the engineer’s mental model of “what the agent knows” and the actual payload sent. For example, a system message meant to enforce a policy may be pushed down the message list by repeated user turns, effectively silencing it. Another edge is retrieval‑augmented generation where the vector store returns embeddings from a previous domain, and the agent incorporates those as if they were current.
To surface drift, engineers can pipe the final prompt through a diff tool or log the exact JSON body before the curl POST. A reproducible pattern:
# Capture the payload sent to the LLM
curl -s -X POST \
-H "Content-Type: application/json" \
-d "$(cat prompt.json)" \
https://api.example.com/v1/chat/completions \
-o /dev/null \
-w "HTTP %{http_code}, effective_tokens %{size_download}\n"
The %{size_download} flag reports the byte size of the response body, but when combined with -w format strings that capture the request, it can be adapted to log the exact request payload size. Comparing that size against the expected token budget reveals unexpected additions.
In production, kubectl logs <agent-pod> --previous often contains the full prompt sent in the most recent request, especially if the agent runtime logs at DEBUG level. If the agent is restarted without persisting context, the agent_context table will show a gap in turn_number sequences, which a simple query exposes:
SELECT session_id, turn_number,
LAG(turn_number) OVER (PARTITION BY session_id ORDER BY turn_number) AS prev_turn
FROM agent_context
ORDER BY session_id, turn_number;
Rows where prev_turn is not exactly one less than the current turn_number indicate lost or out‑of‑order context, a condition that often precedes the agent asking the same question twice or refusing a tool call it previously handled.
When an agent hallucinates, loops, or returns a tool error that seems unrelated to the user’s request, the first troubleshooting step is to inspect the exact prompt that left the agent process.
messages array at INFO or DEBUG level. Capture the line that contains "role": "system" through the last "role": "assistant" entry.system messages, duplicated user turns, or content that references a previous session’s ID.400 Bad Request: context length exceeded, but the client logged 3,900 tokens against a 4,096 limit, the 196‑token gap may include header fields, role strings, or whitespace that the counter omitted.agent_context table. Run the LAG query shown earlier, then SELECT content FROM agent_context WHERE turn_number BETWEEN 1 AND 3; to verify that the stored text matches what the agent should have seen.kubectl rollout undo deployment/agent restores the previous image and context‑handling logic, allowing you to determine whether a new config key or env var introduced the drift.A frequent root cause is an env var that changes the context‑root prefix mid‑run. If CONTEXT_ROOT is set to session-42 for the first half of a conversation and then silently overridden to session-99 by a orchestrator restart, the agent_context table will contain rows avouched under two different session IDs. The agent, pulling the wrong prefix, will appear to “forget” earlier instructions. Verifying that CONTEXT_ROOT is immutable for the duration of a session—often by reading it once at startup and never again—prevents this class of failures.
system message placed after the first user turn is treated as a second‑class instruction and may be ignored by the model. Keep system messages first in the array.usage object in the response (if present) and comparing prompt_tokens against your own counter.session_id column—or when it’s populated inconsistently—one agent’s context can bleed into another’s. Always scope context by a globally unique session identifier, never by a short‑lived request ID.Engineering agent context is not a one‑time setup; it is a recurring discipline of schema design, payload shaping, token accounting, and production observability. The commands, SQL, and patterns above are concrete starting points that map onto virtually any AI‑agent platform, without locking you into a vendor’s internal knobs or undocumented flags.
This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy