Production-grade guide to agent testing patterns covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Agent Testing Patterns collect the repeatable, automated checks engineers write to validate that an AI agent behaves within expected bounds before it reaches production. They matter because agents are non‑deterministic by default: the same prompt can yield different tool calls, token usage, or error handling across runs, and a single unchecked regression can corrupt data, leak credentials, or leave tools in an inconsistent state. This page is organized by the specific question the test is trying to answer—not by framework, vendor, or taxonomy—so you can locate the pattern that matches the problem you’re facing today.
When an agent is expected to call Tool A before Tool B, the test must inspect the intermediate JSON the agent returns, not just the final answer. A concrete way to do this with a locally running agent API is:
curl -s -X POST http://agent-local:8080/run \
-H "Content-Type: application/json" \
-d '{"prompt":"summarize the log file and then archive it","temperature":0}'
The response body typically contains a tool_calls array. To extract just the names and assert the order:
response=$(curl -s -X POST http://agent-local:8080/run \
-H "Content-Type: application/json" \
-d '{"prompt":"summarize the log file and then archive it","temperature":0}')
echo "$response" | jq -r '.tool_calls[] | .name'
If the agent first calls summarize then archive, the output will be those two names in order. If the order is reversed or a call is missing, the sequence assertion fails. A typical error text from a badly‑configured registry looks like:
{"error":"tool_not_found","message":"Tool "archive" not registered in the current session"}
In CI you can fold this into a single check:
expected='["summarize","archive"]'
actual=$(echo "$response" | jq -c '.tool_calls | map(.name)')
[ "$actual" = "$expected" ] || { echo "Tool-sequence mismatch"; exit 1; }
temperature=0 does not guarantee a deterministic tool sequence. Models may still vary their calls when retrieval, dynamic planning, or multi‑step reasoning is involved. A test that only checks the final output will miss a reordered or skipped tool call. Always inspect tool_calls directly, and if your agent uses optional tools, include a “tool not called” guard in your assertion.
When you need to know whether the agent stabilizes across repeated invocations, run the same prompt multiple times with temperature=0 and compare the tool‑call sets. The following script runs ten iterations and reports unique call patterns:
for i in $(seq 1 10); do
curl -s -X POST http://agent-local:8080/run \
-H "Content-Type: application/json" \
-d '{"prompt":"extract the due date from this contract","temperature":0}' \
> /tmp/run_$i.json
done
for f in /tmp/run_*.json; do
jq -S '.tool_calls | map(.name)' "$f"
done | sort -u
If the output contains more than one distinct sorted list, the agent is non‑deterministic even at temperature=0—common when the model invokes a search tool or a code‑execution step whose outcome influences later calls.
Agents that cache tool results between runs can make repeated invocations appear deterministic when they are not. Flush any tool‑state caches before starting a variance test, or explicitly version‑pin the agent binary and note the commit SHA in your test report.
Many agent pipelines emit a JSON payload that downstream systems consume. Validating the shape of that payload early prevents silent data‑corruption bugs. A real‑world pattern uses the jsonschema CLI:
First, define the contract in discount-contract.json:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["item", "original_price", "discounted_price", "currency"],
"properties": {
"item": {"type": "string"},
"original_price": {"type": "number"},
"discounted_price": {"type": "number"},
"currency": {"type": "string", "enum": ["USD","EUR","GBP"]}
}
}
Then, from a shell script, pipe the agent’s output into the validator:
curl -s -X POST http://agent-local:8080/run \
-H "Content-Type: application/json" \
-d '{"prompt":"compute a 15% discount on the following item set","temperature":0}' | \
jq -c '.' > /tmp/agent_output.json
jsonschema -i /tmp/agent_output.json discount-contract.json
If the output omits currency or sends a string where a number is expected, jsonschema exits with a ValidationError such as:
ValidationError: "currency" is missing from the required object
You can capture the exit code in a Makefile or CI step:
jsonschema -i /tmp/agent_output.json discount-contract.json || {
echo "Output does not conform to contract"
exit 1
}
Agents sometimes emit additional fields that are valid JSON but not described in the schema. If you add additionalProperties: false to your schema, a new field from the agent will cause the validation to fail even though the new field is harmless. Use additionalProperties: true during early contract stabilization, then tighten once the set of fields is frozen.
Knowing where an agent stops processing a long prompt helps you avoid silent truncation of system instructions or critical user data. Generate a deliberately long prompt and watch the stop_reason field:
long_prompt=$(python -c "print('X'*100000)")
curl -s -X POST http://agent-local:8080/run \
-H "Content-Type: application/json" \
-d "{\"prompt\":\"$long_prompt\",\"temperature\":0}" | jq '.stop_reason'
Typical values for stop_reason are:
end_of_text – the model finished its turn normallylength_limit – the agent hit the context‑window ceiling and cut offtool_use – the agent decided to call a tool and pausedIf you see length_limit, the agent silently dropped the latter portion of the prompt, which may include a system‑level instruction or a multi‑part question.
length_limit does not always mean the agent lost the user’s prompt; some implementations trim from the *beginning* (the system prompt) rather than the *end* (the user message). Verify which end is being truncated by checking conversation.length or the usage.prompt_tokens field in the response, if your agent API exposes it.
Agents that receive an API key as an environment variable should never log or return that key in plaintext. A sandboxed test using Docker can confirm this:
docker run --rm \
-e AGENT_API_KEY=sk-live-test12345 \
-v "$(pwd)/agent:/app" \
agent-image \
/app/run.sh "use the key to list buckets"
After the container exits, inspect the captured logs:
docker logs <container_id> | grep -i "sk-live-test12345"
If the raw key string appears, the agent or its underlying runtime leaked credentials. A clean run produces no match.
Some agents echo environment variables into error messages when a tool fails. A tool‑call error such as AuthenticationError: invalid key may deliberately or inadvertently surface the key prefix. Always test with both a valid and an intentionally malformed key, and assert that the error message contains a generic phrase like “invalid credentials” rather than the key value itself.
| Pattern | What Silently Fails | What You Learn Too Late |
|---|---|---|
| Tool‑sequence checks | Agent skips a tool when a previous tool returns an non‑fatal error, but the test only asserts the final answer. | A downstream consumer receives incomplete data; the bug appears as a “missing field” ticket weeks later. |
| Iteration variance | temperature=0 is assumed to force determinism; retrieval or dynamic planning steps are omitted from the count. | Two consecutive runs produce different tool sets, causing flaky CI and merged‑conflict‑like confusion. |
| JSON contract assertion | New fields are added by the agent in production but are not in the CI schema; additionalProperties: false is set. | Production payloads are rejected by the downstream API, and the agent team is paged at 2 am. |
| Context‑window stress | Truncation happens at the system‑prompt end, but the test only measures token count at the user‑prompt end. | The agent begins responding as if it has no system instructions, producing off‑topic or unsafe outputs. |
| Credential isolation | Environment variables are forwarded to tool processes that the agent did not explicitly request. | Secret scanning tools flag the container image; a rotation incident forces a full‑scale key revocation. |
Key takeaway: Every pattern on this page is a concrete, runnable check. Use the exact commands and flags shown, inspect the exact error text your own agent API returns, and treat the “sharp edges” as required reading before you merge any agent‑related change to production. Map these patterns to the specific framework or platform you’re using; the mechanics—HTTP POST bodies, JSON extraction with jq, schema validation with jsonschema, container‑isolated env‑var checks—are universal across the agents you’ll encounter.
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