
Day 12: Stop Guessing If Your AI Agent Works
Build an automated regression-testing system for an AI agent deployed on AWS Lambda.
Series: 30 Days of AI Engineering on AWS (17 articles)
- …
- 13Day 12: Stop Guessing If Your AI Agent Works This article
Over the past eleven days, we've built several components of an AI engineering system.
We started with foundation-model calls, explored embeddings and RAG, deployed agents using Strands and AWS Lambda, built multi-agent workflows, and introduced human approval.
But we have not addressed one important question:
How do we know whether a change actually improves our AI application?
Imagine you modify your agent's system prompt.
The agent still runs. Amazon Bedrock still returns responses. Lambda reports successful executions.
But something has changed.
The agent that previously calculated percentages correctly now occasionally returns incorrect numbers.
An AWS explanation has become less accurate.
A request that should be rejected now produces a normal response.
Nothing necessarily crashed.
Yet the application is less reliable.
Traditional software engineers solve similar problems using automated tests.
AI engineers need that discipline too.
Today, we'll build a lightweight evaluation pipeline for the agent from Day 8.
Instead of relying on a few manual conversations, we'll run repeatable test cases and record their outcomes.
1. What is AI evaluation?
AI evaluation, often shortened to AI evals, is the process of measuring an AI application's behavior against defined expectations.
These expectations depend on what the system is supposed to accomplish.
For example, an AWS learning assistant might need to:
- Answer technical questions correctly.
- Perform calculations accurately.
- Return errors for invalid requests.
- Avoid claiming it performed actions it did not execute.
- Use appropriate tools when required.
- Return responses within an acceptable latency range.
These requirements are different.
Some are easy to measure automatically. Others require semantic evaluation, human review, or inspection of the agent's tool execution.
There are several useful evaluation approaches.
Evaluation type | What it measures |
|---|---|
Deterministic evaluation | Exact values, JSON structures, response codes, required or prohibited patterns |
Model-as-a-judge | Another model assesses response quality against defined criteria |
Human evaluation | Reviewers assess correctness, usefulness, and other qualitative properties |
Trace-based agent evaluation | Whether the agent selected and executed tools appropriately |
Regression evaluation | Whether a new version performs worse than a previous baseline |
For today's exercise, we'll start with deterministic regression checks against a deployed Lambda agent.
This provides a useful foundation before introducing more advanced evaluation methods.
AWS also offers managed evaluation features through Amazon Bedrock and Amazon Bedrock AgentCore.
2. Our evaluation architecture
We'll reuse the AI assistant from Day 8.
That application uses:
- AWS Lambda for execution.
- Strands Agents SDK for orchestration.
- Amazon Bedrock for model inference.
- Amazon Nova Lite as the foundation model.
- A Python calculator tool for deterministic arithmetic.
Today's testing application runs separately from the agent.
GOLDEN DATASET cases.jsonl | v Evaluation Runner Python | v AWS Lambda Invoke | v Strands AI Agent | v Amazon Bedrock | v Agent Response | v Evaluation Rules | +------+------+ | | v v PASS FAIL | | +------+------+ | v JSON REPORT | v Regression DecisionThe evaluation runner does not need to reimplement the agent.
It sends test events to the deployed function and checks the returned results.
This is an example of black-box testing: evaluating an application's externally observable behavior without depending on its internal implementation.
AWS recommends black-box and cloud integration testing for serverless applications because local tests alone cannot fully reproduce AWS service behavior, IAM permissions, and deployment configuration.
3. Define what a successful agent looks like
Before writing evaluation code, we need measurable expectations.
For our Day 8 assistant, we'll define five initial test cases.
Test | Input | Expected result |
|---|---|---|
Arithmetic 1 | Calculate 18% of 1250 | 225 |
Arithmetic 2 | Calculate 7% of 5000 | 350 |
AWS terminology | Expand IAM | Identity and Access Management |
AWS knowledge | Explain Amazon S3 | Identifies object storage |
Input validation | Empty request | Application returns HTTP-style status 400 |
This is intentionally a small starting dataset.
A proper evaluation suite should eventually contain many more examples, especially cases that previously failed.
For now, we want to understand the evaluation pipeline rather than create a massive benchmark.
4. Prepare the project
We'll use the same AWS Region as the earlier exercises:
ap-south-1Our Lambda function is:
strands-serverless-agentThis is the function created in Day 8.
If your deployment uses a different name, replace it in the commands.
Create a project directory:
mkdir aws-agent-evaluationcd aws-agent-evaluationCreate a Python virtual environment:
py -3.12 -m venv .venv
.venv\Scripts\Activate.ps1Install Boto3:
python -m pip install --upgrade boto3Verify your AWS identity:
aws sts get-caller-identityMake sure the credentials used by your evaluation runner can invoke the Lambda function.
The runner requires:
lambda:InvokeFunctionScope that permission to your evaluation target.
For example, replace the account ID in this policy:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "lambda:InvokeFunction", "Resource": "arn:aws:lambda:ap-south-1:123456789012:function:strands-serverless-agent" } ]}The agent's Lambda execution role must separately retain its Amazon Bedrock permissions.
Do not give the evaluation runner unnecessary infrastructure modification permissions.
5. Create the golden evaluation dataset
Create:
cases.jsonlJSON Lines stores one valid JSON object per line.
For our project, every object describes a test case.
Each test includes:
- A unique test identifier.
- A category.
- The Lambda event to invoke.
- The expected application status.
- Regular-expression patterns that must appear in the response.
- Optional patterns that must not appear.
Paste these five lines into
cases.jsonl :{"id":"calc-18","category":"tool_result","event":{"prompt":"Use the calculate_percentage tool to calculate 18 percent of 1250. State the numeric result."},"expected_status":200,"must_match":["(?<!\\d)225(?:\\.0+)?(?!\\d)"]}{"id":"calc-7","category":"tool_result","event":{"prompt":"Use the calculate_percentage tool to calculate 7 percent of 5000. State the numeric result."},"expected_status":200,"must_match":["(?<!\\d)350(?:\\.0+)?(?!\\d)"]}{"id":"iam","category":"factual","event":{"prompt":"What does IAM stand for in AWS? Answer in one sentence."},"expected_status":200,"must_match":["(?i)identity\\s+and\\s+access\\s+management"]}{"id":"s3","category":"factual","event":{"prompt":"What is Amazon S3? Answer in one sentence."},"expected_status":200,"must_match":["(?i)object\\s+storage"]}{"id":"invalid-input","category":"input_validation","event":{},"expected_status":400,"must_match":["(?i)non-empty prompt"]}Let's understand the first example.
{ "id": "calc-18", "category": "tool_result", "event": { "prompt": "Use the calculate_percentage tool to calculate 18 percent of 1250. State the numeric result." }, "expected_status": 200, "must_match": [ "(?<!\\d)225(?:\\.0+)?(?!\\d)" ]}This test invokes the agent with an arithmetic question and checks whether the response contains
225 as a numeric result, allowing forms such as 225.0 .It should not pass when the answer contains
2250 .The test does not require the entire response to be an exact string. That would be unnecessarily fragile for a generative application.
For example, both of these responses can satisfy the required numeric pattern:
18% of 1250 is 225.The calculated result is 225.However, there is an important limitation.
A matching number does not prove the agent actually used the calculator tool.
For that, we would also need to inspect the agent's tool-use trace.
Today's suite validates the observable answer. We'll discuss deeper agent-level evaluation later.
6. Build the evaluation runner
Create:
eval_runner.pyThis script will:
- Load the evaluation dataset.
- Invoke the Lambda function synchronously.
- Decode the Lambda handler's response.
- Evaluate status codes and response patterns.
- Measure end-to-end invocation latency.
- Save results to a JSON report.
- Return a nonzero process exit code if any test fails.
The script is designed for the Day 8 Lambda handler, which returns an application-level
statusCode and a JSON-encoded body .Complete Python implementation
"""Day 12: black-box regression tests for a deployed AWS Lambda AI assistant."""
import argparsefrom datetime import datetime, timezoneimport jsonfrom pathlib import Pathimport reimport statisticsimport sysfrom time import perf_counter
import boto3from botocore.config import Config
def load_cases(path): items = [] seen = set()
for line_number, line in enumerate( Path(path).read_text( encoding="utf-8" ).splitlines(), 1 ): if not line.strip(): continue
case = json.loads(line)
if not isinstance(case, dict): raise ValueError( f"Case {line_number} is not an object" )
case_id = case.get("id")
if ( not isinstance(case_id, str) or not case_id or case_id in seen ): raise ValueError( f"Missing or duplicate case ID at line {line_number}" )
if not isinstance(case.get("event"), dict): raise ValueError( f"Case {case_id} has no event object" )
if case.get("expected_status") not in (200, 400): raise ValueError( f"Case {case_id} has an unexpected status target" )
for field in ("must_match", "must_not_match"): patterns = case.get(field, [])
if ( not isinstance(patterns, list) or not all( isinstance(x, str) for x in patterns ) ): raise ValueError( f"Case {case_id}: {field} must be a string list" )
for pattern in patterns: re.compile(pattern)
seen.add(case_id) items.append(case)
if not items: raise ValueError( "The evaluation dataset is empty" )
return items
def decode_lambda_response(response):
if ( response.get("StatusCode") != 200 or response.get("FunctionError") ): raise ValueError( "Lambda invocation or handler failed" )
envelope = json.loads( response["Payload"].read() )
if not isinstance(envelope, dict): raise ValueError( "Unexpected Lambda result" )
status = envelope.get("statusCode") body = envelope.get("body", {})
if isinstance(body, str): body = json.loads(body)
if not isinstance(body, dict): raise ValueError( "Expected a JSON object in the handler body" )
field = ( "answer" if status == 200 else "error" )
text = body.get(field, "")
if not isinstance(text, str): raise ValueError( "Expected textual answer or error" )
return status, text
def score_case( case, status, text, latency_ms): issues = []
if status != case["expected_status"]: issues.append( "Unexpected application status" )
for pattern in case.get("must_match", []): if re.search(pattern, text) is None: issues.append( "Missing required pattern: " + pattern )
for pattern in case.get("must_not_match", []): if re.search(pattern, text) is not None: issues.append( "Matched forbidden pattern: " + pattern )
maximum = case.get("max_latency_ms")
if ( maximum is not None and latency_ms > maximum ): issues.append( "Exceeded configured latency budget" )
return issues
def main():
parser = argparse.ArgumentParser()
parser.add_argument( "--function", required=True )
parser.add_argument( "--region", default="ap-south-1" )
parser.add_argument( "--dataset", default="cases.jsonl" )
parser.add_argument( "--output", default="eval-report.json" )
args = parser.parse_args()
cases = load_cases(args.dataset)
client = boto3.client( "lambda", region_name=args.region, config=Config( connect_timeout=10, read_timeout=180, retries={ "mode": "standard", "max_attempts": 3 } ) )
results = []
for case in cases:
start = perf_counter()
try:
result = client.invoke( FunctionName=args.function, InvocationType="RequestResponse", Payload=json.dumps( case["event"] ).encode("utf-8") )
status, text = ( decode_lambda_response(result) )
latency_ms = round( (perf_counter() - start) * 1000 )
issues = score_case( case, status, text, latency_ms )
except Exception as exc:
latency_ms = round( (perf_counter() - start) * 1000 )
status = None
issues = [ "Invocation or response error: " + type(exc).__name__ ]
passed = not issues
results.append({ "id": case["id"], "category": case.get( "category", "general" ), "passed": passed, "application_status": status, "latency_ms": latency_ms, "issues": issues })
print( f"{'PASS' if passed else 'FAIL'} " f"{case['id']} " f"{latency_ms}ms" )
passed_count = sum( item["passed"] for item in results )
report = { "created_at": datetime.now( timezone.utc ).isoformat(),
"function": args.function, "region": args.region, "total": len(results), "passed": passed_count,
"pass_rate": round( passed_count / len(results), 4 ),
"mean_latency_ms": round( statistics.mean( r["latency_ms"] for r in results ) ),
"results": results }
Path(args.output).write_text( json.dumps( report, indent=2 ), encoding="utf-8" )
print( f"\nPassed {passed_count}/{len(results)}. " f"Report: {args.output}" )
return ( 0 if passed_count == len(results) else 1 )
if __name__ == "__main__": sys.exit(main())The important part is that the test runner uses the real AWS Lambda API.
client.invoke( FunctionName=args.function, InvocationType="RequestResponse", Payload=json.dumps( case["event"] ).encode("utf-8"))RequestResponse invokes the function synchronously and returns its result.A subtle Lambda behavior
The top-level Lambda
StatusCode is not the same as the status code returned by your application handler.For a successful synchronous Lambda API invocation, AWS normally returns:
StatusCode = 200Even if the function's code fails, the API-level status can still be 200.
AWS exposes handler execution failures through:
FunctionErrorand the returned payload.
Our evaluation runner checks both the Lambda invocation and the handler's application-level status.
This distinction matters. Otherwise, a test framework could incorrectly treat a failed Lambda execution as a successful application response.
7. Run your first evaluation
Make sure your files are in the same directory:
aws-agent-evaluation/|+-- cases.jsonl|+-- eval_runner.py|+-- .venv/Run:
python eval_runner.py ` --function strands-serverless-agent ` --region ap-south-1 ` --dataset cases.jsonl ` --output eval-report.jsonThe script invokes the actual Lambda function five times, once per test case.
Each valid request can trigger one or more Bedrock inference calls, depending on the agent's execution path.
This is not a simulated test.
It invokes your real deployed application and can incur AWS charges.
Example output
If all the expected conditions are met, the output will resemble:
PASS calc-18 3200msPASS calc-7 2890msPASS iam 2150msPASS s3 2310msPASS invalid-input 180ms
Passed 5/5. Report: eval-report.jsonThese numbers are illustrative.
Actual latency and pass/fail outcomes will depend on the deployed function, model responses, network conditions, and AWS configuration.
If a test fails, the runner displays
FAIL and records the issue.For example:
FAIL calc-18 3100msA failure could mean:
- The response was incorrect.
- The expected text was missing.
- The handler returned an unexpected status.
- Lambda reported a function error.
- The invocation could not complete.
- The result did not match the expected schema.
The report distinguishes these outcomes where the runner has enough information.
8. Read the evaluation report
After the run, open:
eval-report.jsonThe report will contain structured results similar to:
{ "function": "strands-serverless-agent", "region": "ap-south-1", "total": 5, "passed": 5, "pass_rate": 1.0, "mean_latency_ms": 2146, "results": [ { "id": "calc-18", "category": "tool_result", "passed": true, "application_status": 200, "latency_ms": 3200, "issues": [] } ]}This is only an example of the report structure, with illustrative measurements.
The real report includes results for every test.
What does pass rate mean?
The pass rate is:
[
\text{Pass rate} =
\frac{\text{Passed test cases}}
{\text{Total test cases}}\times100
]
For example, if four out of five test cases pass:
Pass rate = 80%This number is useful for tracking a fixed evaluation dataset over time.
But it does not represent an application's overall accuracy across every possible user question.
Five passing tests mean five defined checks passed.
Nothing more.
9. Use the evaluation as a regression gate
Here's where the workflow becomes more useful.
Imagine you update the Strands agent's system prompt.
Before:
Always use the calculator tool for percentage calculations.After:
Answer questions as efficiently as possible.The second instruction might lead the agent to use different behavior.
We should not assume the new instruction is better simply because it is shorter.
Instead, run the same test dataset against the updated function.
Our evaluation runner returns:
Exit code 0: All cases passed.
Exit code 1: One or more cases failed.This allows a deployment pipeline to treat failed evaluations as a blocking condition.
For example, in PowerShell:
python eval_runner.py ` --function strands-serverless-agent ` --region ap-south-1
if ($LASTEXITCODE -ne 0) { throw "AI evaluation failed. Stop deployment."}For a production release process, run this against a staging version or alias first, not the production agent.
AWS Lambda supports invoking a specific function version or alias.
This lets you compare the current release with a proposed replacement.
A full CI/CD implementation should authenticate to AWS using temporary credentials and least-privilege permissions, rather than storing long-lived AWS access keys.
10. Extend the tests to include latency
Correctness is important, but it is not the only consideration.
Suppose one version of your agent produces an answer in three seconds.
Another version produces an answer in fifteen seconds.
Both may be correct, but the second might be unsuitable for an interactive application.
Our runner already measures elapsed time using:
start = perf_counter()and:
latency_ms = round( (perf_counter() - start) * 1000)This measures client-observed elapsed time, including network and Lambda invocation overhead.
It is not a direct measurement of model inference latency alone.
You can optionally add a limit to a test case:
{ "id": "iam", "category": "factual", "event": { "prompt": "What does IAM stand for in AWS?" }, "expected_status": 200, "must_match": [ "(?i)identity\\s+and\\s+access\\s+management" ], "max_latency_ms": 30000}The test will fail if its measured elapsed time exceeds 30,000 milliseconds.
However, AI latency can vary due to cold starts, model load, retries, request size, and service conditions.
Do not select a production latency limit from a single successful run.
Collect a representative sample first.
For larger datasets, compare metrics such as median and 95th-percentile latency, rather than relying entirely on the mean.
11. Understand what deterministic evaluations cannot prove
Our current evaluation framework has several limitations.
A matching answer might still be misleading.
For example, a response saying:
The answer is not 225.could still satisfy a simplistic numeric matching rule.
A more comprehensive evaluator must inspect the meaning of the response.
Correct arithmetic does not prove correct tool selection.
The model might calculate the result itself instead of invoking
calculate_percentage .To validate tool-use behavior, inspect actual tool execution traces or instrument the agent.
Passing factual tests does not guarantee safety.
A few AWS terminology questions do not establish that the model resists prompt injection, protects confidential information, or follows authorization boundaries.
A five-case dataset is not a production benchmark.
It is the beginning of an evaluation suite.
As your application develops, add cases for known failures, ambiguous requests, invalid data, tool errors, and unexpected model behavior.
Evaluation quality depends heavily on the quality of the dataset and the assertions.
12. Explore managed evaluations with Amazon Bedrock
So far, we've built a custom evaluation runner.
AWS also provides managed evaluation capabilities.
Amazon Bedrock Model Evaluations
Amazon Bedrock can evaluate foundation-model responses using several approaches, including model-as-a-judge and human-based evaluation.
With model-as-a-judge, another language model assesses responses according to selected criteria.
Depending on the evaluation type, these can include:
- Correctness.
- Completeness.
- Helpfulness.
- Harmfulness.
- Other configured quality metrics.
AWS also supports bringing your own generated responses to appropriate evaluation jobs.
This can help when the application is not simply a direct Bedrock model invocation.
For custom RAG applications, Bedrock RAG Evaluations can assess retrieval and generated responses, including faithfulness, which concerns whether an answer is supported by its source context.
This is particularly relevant to the RAG system we built on Day 5.
References:
Our
cases.jsonl file is a custom format for today's Python runner. It is not automatically a valid Bedrock managed-evaluation dataset. Managed jobs require their documented dataset schemas, S3 input locations, supported judge models, and service-role permissions.Amazon Bedrock AgentCore Evaluations
There is another option particularly relevant to our Day 9 multi-agent application.
Amazon Bedrock AgentCore Evaluations became generally available on March 31, 2026.
It supports automated assessment of AI agents, including on-demand evaluations and online evaluation of production traces.
AWS announced built-in evaluators covering response quality, safety, task completion, and tool usage, as well as support for ground-truth expectations and custom evaluation logic.
This is closer to the type of evaluation we need when an agent performs multiple tool calls rather than generating a single text response.
For example, a specialist-agent system may produce an accurate final answer but execute an unnecessary tool along the way.
A text-only test might miss that behavior.
A trace-aware evaluation can inspect more of the execution.
AgentCore Evaluations supports frameworks such as Strands through supported telemetry instrumentation.
There is one important prerequisite: the evaluation service needs compatible agent traces.
The on-demand workflow described by AWS uses CloudWatch telemetry and requires configuration such as CloudWatch Transaction Search.
Our Day 8 Lambda application does not automatically satisfy those prerequisites just because it uses Strands.
If you migrate or instrument the agent appropriately, AgentCore Evaluations becomes a natural next step.
Official references:
Before using managed LLM-based evaluations with sensitive data, check the applicable inference-routing behavior and data-processing Regions. This is particularly important if an evaluator uses cross-Region inference.
13. How today's task connects to the previous days
We are not building another unrelated AI demonstration.
We are introducing a testing layer that can eventually cover the systems built throughout this series.
Previous work | Future evaluation opportunity |
|---|---|
Day 4 — Embeddings | Measure retrieval relevance |
Day 5 — RAG | Evaluate correctness and groundedness |
Day 7 — Guardrails | Measure safety-filter outcomes |
Day 8 — Lambda agent | Test answers, validation, and latency |
Day 9 — Multi-agent system | Evaluate specialist selection and tool execution |
Day 10 — Mission Control | Validate synthesis results and workflow execution |
Day 11 — Human approval | Verify approval, rejection, timeout, and authorization behavior |
Today, we implemented the Day 8 evaluation path.
The same ideas can be adapted to the other components, although different systems require different test adapters and assertions.
For instance, testing Day 11 must verify the Step Functions execution and authorization behavior. Merely checking the text of an AI answer would not prove its approval mechanism is secure.
14. Production considerations
There are several practical improvements to make before using this approach as a deployment gate.
Store your golden dataset in version control
Keep the test cases alongside your application source code.
When a production failure reveals a new problem, add a regression test that reproduces it.
That way, future changes can be checked against the failures you've already encountered.
Keep the evaluation environment isolated
Avoid testing agent behavior against production customer data or resources that the agent can modify.
Use a staging Lambda alias, synthetic test prompts, and restricted tool permissions.
If your agent can execute real actions, ensure the evaluation environment cannot accidentally perform destructive operations.
Don't make the dataset too easy
A test suite containing only simple AWS definitions will not provide meaningful confidence in a complicated multi-agent application.
Include ordinary cases, edge cases, invalid inputs, and historical failures.
Measure results separately for different categories.
A high aggregate score should not conceal a critical failure in security-sensitive behavior.
Treat model-as-a-judge scores carefully
Judge models can make mistakes.
They may be inconsistent, share biases with the evaluated model, or misunderstand technical requirements.
Use ground-truth answers, deterministic checks, and human review where they provide stronger evidence.
No single evaluation metric should determine whether a high-impact agent is safe to deploy.
Track cost and execution context
Every live Lambda invocation can incur Lambda and downstream Bedrock costs.
For reproducibility, record the model or inference profile, deployed function version, prompt version, dataset version, and run timestamp.
Our basic JSON report identifies the function, Region, test IDs, results, and observed latency. For a production benchmark, extend it with immutable deployment and dataset identifiers.
Your Day 12 task
Build and run the evaluation framework against the Day 8 agent.
Your objectives:
- Create the five-case golden dataset.
- Execute the Python evaluation runner against AWS Lambda.
- Generate
eval-report.json.
- Introduce a deliberate test failure and verify the runner returns a nonzero exit code.
- Restore the test and compare the results.
Then add at least two new cases relevant to your own agent.
For example, test a past calculation failure or an input that previously produced an incorrect technical explanation.
The goal is not to achieve a perfect score on five easy questions.
The goal is to create a repeatable method for identifying when your AI application changes behavior unexpectedly.
What you learned today
You built an automated evaluation pipeline for an Amazon Bedrock-powered agent running on AWS Lambda.
You learned how to create golden test datasets, invoke a real deployed agent, validate responses, record latency, generate reports, and use exit codes to block regressions.
You also explored the difference between deterministic checks, managed model evaluations, and trace-based agent evaluations.
The most important lesson:
An AI application is not reliable because it answered one question correctly. Reliability requires repeatable evidence across the behaviors that matter.
Day 12 complete.
30 Days. 30 Tasks. Real AI Building.
Series: 30 Days of AI Engineering on AWS (17 articles)
- …
- 13Day 12: Stop Guessing If Your AI Agent Works This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article