Building a Real-World AI Agent on AWS · Part 2: Honest Model Evaluation and an Agent with MCP, Bedrock and a Guardrail

Part 2 evaluates the vision model once on an untouched test split, reproduces it in a SageMaker pipeline, and builds the agent: a LangGraph workflow, an MCP server, two Bedrock models that choose their own tools, a Knowledge Base on Aurora and a Guardrail.

November 24, 2026  ·  19 min read
Building a Real-World AI Agent on AWS  |  NovaNutri  |  Part 2 of 4
DINOv2 SageMaker Pipelines Model Registry LangGraph MCP Amazon Bedrock RAG Guardrails

Part 2  ·  One Test, Proven Lineage, Numbers in Code and Tool Choice for the Models


Chapter 1

Honest Model Evaluation and a SageMaker Pipeline

What you will build

  • A training table built from the pipeline output (dataset v2), with lineage you can prove.
  • A vision model evaluated once on an untouched test split.
  • A SageMaker pipeline that reproduces the local model, checks the result, and registers it for approval.

Lineage first: dataset v2 from the pipeline

Run the Airflow DAG again over all 94 capture days with the cleansing rules (one backfill). Every day's manifest records the SHA-256 of the rule file. Then build the label table from the landed files only, after checking each file and each of the 3,228 photos against its manifest by SHA-256. Keep the same 61 food classes, the same validation split and the same test dishes as the first version, so the two datasets can be compared.

Result: dataset v2 equals v1 plus one training dish (brought back by fix rule R4), now with review flags. A small dataset record stores the source, the rule hash and the SHA-256 of the label table. That record is what makes the model auditable.

Dataset v2 lineage: from the pipeline's landed files to the label table, checked by SHA-256.
Figure 1. Dataset v2 lineage: from the pipeline's landed files to the label table, checked by SHA-256.

Avoid leakage before you train

Nutrition5k plates were built one ingredient at a time, so near copies of a plate appear as separate dishes. A random validation split would leak. Group dishes by plate and split by group:

  • Validation: 5-fold group cross validation on the training split only.
  • Test: the official test split (498 dishes), evaluated exactly once at the end.

The model

  • Image features: DINOv2-small at a pinned revision (facebook/dinov2-small, a fixed commit hash), so features never drift.
  • Heads: per-food presence (logistic regression) and grams (regression), blended with a k-nearest-neighbour estimate.
  • Nutrition: calculated by code from the predicted foods and grams with reference tables.

Results on the 498 test dishes, evaluated once:

Metric Dataset v1 Dataset v2
Calorie error (blend) 26.2 percent, 67.0 kcal 25.9 percent, 66.1 kcal
Simple / multi / mixed plates 30.0 / 22.8 / 26.0 28.9 / 22.6 / 26.9
Leak-free test dishes (363) 25.9 25.8
Ingredient macro F1 0.511 0.511

Read the table honestly: a 0.3 point difference is noise. The gain of dataset v2 is lineage, not accuracy. Flagged dishes were reported separately (fish dishes 31.5 percent, dishes with unusual amounts 30.4 percent, the rest 25.6 percent).

Why reproduce in SageMaker instead of training there

Full training ran locally on CPU, which was cheap and fast enough. SageMaker's job here is to prove the lifecycle: the same code, in managed jobs, producing the same model, registered with its lineage and approved by a person. Keep the job code in a normal Python package (NovaNutri used ml/jobs/, not a folder named sagemaker, so it never shadows the SDK) and test it locally on a small sample before the first cloud run.

The pipeline

Step Type What it does
Features Processing Photos from S3 to DINOv2 features, cached for reruns
Train Training Final model on train plus validation with fixed settings
Evaluate Processing Test predictions compared with the local predictions
MatchesLocalResult Condition Register only if the cloud result matches local
Register RegisterModel New version in the model package group, pending manual approval

Define the pipeline as JSON and let Terraform render and create it, so it lives with the rest of the infrastructure:

resource "aws_sagemaker_pipeline" "train" {
  pipeline_name       = "your-train-pipeline"
  role_arn            = aws_iam_role.sagemaker.arn   # an execution role with S3, ECR and registry rights
  pipeline_definition = templatefile("${path.module}/../../../pipelines/nutriscan_train.json.tftpl", { ... })
}

The condition step reads a property file written by the evaluation job:

{
  "Name": "MatchesLocalResult",
  "Type": "Condition",
  "Arguments": {
    "Conditions": [
      {"Type": "LessThanOrEqualTo",
       "LeftValue": {"Std:JsonGet": {"PropertyFile": {"Get": "Steps.Evaluate.PropertyFiles.Evaluation"},
                                     "Path": "calorie_error_gap"}},
       "RightValue": 0.005},
      {"Type": "GreaterThanOrEqualTo",
       "LeftValue": {"Std:JsonGet": {"PropertyFile": {"Get": "Steps.Evaluate.PropertyFiles.Evaluation"},
                                     "Path": "share_within_1kcal_of_local"}},
       "RightValue": 0.98}
    ],
    "IfSteps": [{"Name": "Register", "Type": "RegisterModel",
                 "Arguments": {"ModelApprovalStatus": "PendingManualApproval", "...": "..."}}],
    "ElseSteps": [{"Name": "DoesNotMatchLocal", "Type": "Fail", "...": "..."}]
  }
}

Attach the dataset hash, the rule hash and the model hash as metadata on the registered version, then approve it in SageMaker Studio.

SageMaker pipeline run 5: Features, Train, Evaluate, the condition step and Register.
Figure 2. SageMaker pipeline run 5: Features, Train, Evaluate, the condition step and Register.

What happened on the way (and how to avoid it)

Run Problem Fix
1 Zero quota for every ml.m5 type in a new account Use types with quota (ml.t3 for processing, ml.g6.xlarge for training) or request a quota increase early
2 Training ran out of memory: a bug copied the feature array per dish (about 16 GB) Fixed the copy; peak memory 0.18 GB
3 A strict per-dish equality check failed on 8 threshold dishes Judge reproduction by metrics, not exact equality
4, 5 A missing registry permission; a character the metadata refused Fixed; run 5 succeeded

About exact equality: logistic regression stops at a slightly different point on another CPU and math library, and 8 test dishes sat within 0.001 of a class threshold, so they flipped. Run 5 reproduced the local result by metrics (25.85 against 25.86 percent, 98.8 percent of dishes within 1 kcal) and registered version 1.

Tip: check your SageMaker service quotas the day you start the project. A new account often has zero for common types.

Model version 1 in the Model Registry, approved by a person.
Figure 3. Model version 1 in the Model Registry, approved by a person.

Cost and teardown

About $0.45 for five runs, storage and requests. Teardown removed the bucket, roles, pipeline, registry entries, the Studio domain and its storage, and the job log groups. Look for leftover log groups from earlier parts too; NovaNutri found three from Glue.

Lessons

  • Lineage beats a small accuracy gain: prove where every training row came from.
  • Evaluate on the test split once and publish the number, with its breakdown.
  • Reproduce in the cloud with the same code; judge reproduction by metrics with a written tolerance.
  • Put a condition step in front of registration, and keep a person in the approval.

Chapter 2

An Agent with an MCP Server, Bedrock, a Knowledge Base and a Guardrail

What you will build

photo -> analyze (vision model) -> wait for the person's confirmation
      -> nutrition (code) -> retrieve guidelines -> find past corrections
      -> suggest: two Bedrock models, each choosing tools on the NovaNutri MCP server
      -> check rules (code) -> retry once with the problems named -> finish
      -> (on AWS) Guardrail contextual grounding score per sentence

Code controls the order and every number. The models control one thing: which tools to call before they write.

The LangGraph workflow and the NovaNutri MCP server.
Figure 4. The LangGraph workflow and the NovaNutri MCP server.

Decide where the model is allowed to act

Write it down as a table before coding:

Step Controlled by Why
Food and gram prediction Vision model Its job
Correction A person (or measured data) Wrong guesses must be fixable
Nutrition math Code A language model must never invent numbers
Which tools to call, how to phrase advice Each language model The useful agentic step
Rule check and retry Code Every sentence is checked against the plate and the cited passages

The workflow in LangGraph

graph.add_node("analyze", analyze)
graph.add_node("wait", wait)                    # interrupt(): pause for the person's action
graph.add_node("nutrition", calculate_nutrition)
graph.add_node("retrieve", retrieve)
graph.add_node("suggest", ask_models)
graph.add_node("find_corrections", find_corrections)
graph.add_node("check_rules", check_rules)
graph.add_node("retry", retry)
graph.add_node("finish", finish)
graph.add_edge(START, "analyze")
graph.add_edge("analyze", "wait")
graph.add_conditional_edges("wait", route_action, ["nutrition", "retrieve", "suggest"])
graph.add_conditional_edges("suggest", route_after_suggest, ["check_rules", "wait"])
graph.add_conditional_edges("check_rules", route_after_check, ["retry", "finish"])
graph.add_edge("retry", "check_rules")

interrupt() lets the API return after analysis and resume when the person confirms the plate.

The NovaNutri MCP server: the agent's only path to data

Five read-only tools, served over Streamable HTTP with the official Python MCP SDK:

Tool Returns
lookup_nutrition Nutrition computed by code for given foods and grams
search_guidelines Guideline passages for one question, with ids to cite (G1, G2, ...)
past_corrections Sentences people corrected before, closest to a draft
meal_history Recent meals of a fictional demo user
reference_dishes Typical grams of foods in the cleaned dataset (from the pipeline)
@server.tool(description="Passages from the Dietary Guidelines for Americans 2025-2030 and FDA label pages that answer one "
                         "question. Cite them by id (G1, G2, ...) when a sentence relies on them.")
@logged
def search_guidelines(question: str, k: int = 3) -> Passages:
    if config.on_aws():
        return Passages(question=question, passages=[Passage(id=f"G{i}", **p)
                        for i, p in enumerate(cloud.kb_passages(question, k), 1)])
    # locally: pgvector cosine search on guideline_chunks
    ...

Rules for a safe tool server:

  • Connect to the database as a role with SELECT only and default_transaction_read_only on.
  • Log every call (tool, arguments, rows, milliseconds) so you can see what each model actually used.
  • Write tool descriptions for the model: say what it returns and how to cite it.

Two models that choose their tools (Bedrock Converse)

Both gpt-oss-120b and Amazon Nova 2 Lite run through the Bedrock Converse API with the same tool list plus one final tool (write_suggestion) whose schema is the answer format. Each model may call at most four tools; after that, the final tool is forced:

resp = converse(system=[{"text": system}], messages=messages,
                inferenceConfig={"maxTokens": MAX_OUTPUT_TOKENS},
                toolConfig={"tools": [final_spec] if force else specs,
                            "toolChoice": {"tool": {"name": FINAL_TOOL}} if force else {"auto": {}}})
uses = [c["toolUse"] for c in resp["output"]["message"]["content"] if "toolUse" in c]
final = next((u for u in uses if u["name"] == FINAL_TOOL), None)
if final:
    return final["input"]                  # structured answer
# otherwise run each requested MCP tool, append toolResult blocks, and loop

Two details that mattered:

  • If a model answers in plain text instead of calling the final tool, ask once more with the final tool forced.
  • Track which passage ids each model actually saw. The rule check must accept a citation only if that model was shown that passage; otherwise a model can cite a passage only the other model found.

Measured on four demo plates: both models used tools on every plate (14 and 16 calls), and the rule check removed 2 parts against 6 in the earlier fixed workflow, for $0.037 instead of $0.018.

The rule check (code) and one retry

Every sentence is checked against the plate's computed numbers, the fictional profile and the cited passages. A sentence with a number that is not there, or a citation the model never saw, is removed. If anything was removed, the model gets one retry with the problems named. The page shows what was removed.

Moving the agent's data to AWS

Piece As built Note
Guideline search Bedrock Knowledge Base: 42 passages from S3, Titan Text Embeddings V2, vectors in Aurora Use hybrid search
Meal history, corrections, dataset Aurora PostgreSQL Serverless v2 with pgvector min_capacity = 0, auto pause after 10 minutes
Sign-in to Aurora IAM database authentication 15-minute tokens instead of passwords
Grounding Bedrock Guardrail, contextual grounding Called with ApplyGuardrail after the rule check

Hybrid search was a measured choice: vector-only search ranked the right passage third on two of four test questions, hybrid ranked it first on all four.

resp = client("bedrock-agent-runtime").retrieve(
    knowledgeBaseId=kb_id(), retrievalQuery={"text": question},
    retrievalConfiguration={"vectorSearchConfiguration": {"numberOfResults": k, "overrideSearchType": "HYBRID"}})

Aurora Serverless v2 can now scale to zero:

serverlessv2_scaling_configuration {
  min_capacity             = 0
  max_capacity             = 2
  seconds_until_auto_pause = 600
}
iam_database_authentication_enabled = true
The agent's AWS side: two Bedrock models, the Knowledge Base on Aurora and the Guardrail.
Figure 5. The agent's AWS side: two Bedrock models, the Knowledge Base on Aurora and the Guardrail.
The Bedrock Knowledge Base with Aurora PostgreSQL as its vector store.
Figure 6. The Bedrock Knowledge Base with Aurora PostgreSQL as its vector store.
Testing hybrid search with a sodium question.
Figure 7. Testing hybrid search with a sodium question.

What the Guardrail caught

The Guardrail scores each kept sentence for grounding (0 to 1) against a source made of the cited passages plus the plate numbers computed by code. In the AWS run, 30 sentences passed the rule check and two scored under 0.5:

  • A real error: "Saturated fat is under 20 percent of the daily limit" when the code value was 20 percent. The rule check read the words low, moderate and high and missed a stated limit.
  • A false alarm: a true statement that something was missing from the plate.

Relevance scores were too scattered to use for this style of question. Lesson: use grounding per sentence, keep a person's judgment for the rest, and log what the Guardrail flags. Cost note: the Guardrail cost about 70 percent of the model cost because the whole source is sent for every sentence; sending each sentence only the passages it cites would cut that.

A Guardrail trace with the contextual grounding score.
Figure 8. A Guardrail trace with the contextual grounding score.

Cost and teardown

The four-plate AWS run cost $0.0425 in model calls plus $0.0304 for the Guardrail. The part stayed under $1. Teardown removed 104 resources; delete any access key you created for testing first.

Lessons

  • Give the model one clear agentic job and keep numbers in code.
  • Make the MCP server the only door to data, read-only and logged.
  • Measure retrieval choices (hybrid versus vector) on real questions.
  • Use a grounding check as a second opinion after your own rules, not instead of them.

Next: Part 3 runs the API and the MCP server as containers on ECS Fargate behind API Gateway and Cognito.

See it running

Live demo: novanutri.novapunkai.com

Case study and 2-minute video: novapunkai.com/projects/novanutri

Building a Real-World AI Agent on AWS · NovaNutri

Part 1 Project Design and a Data Pipeline from Airflow to Iceberg
Part 2 Honest Model Evaluation and an Agent with MCP, Bedrock and a Guardrail
Part 3 Deploying the Agent on ECS Fargate with CI/CD and a Public Web Demo
Part 4 The Same Services on Amazon EKS, and a Demo Video Made by Code

NovaNutri is a portfolio technology demo, not a commercial product. Nothing it produces is medical or nutrition advice. Data: Nutrition5k (Google Research, CC BY 4.0), USDA FoodData Central (CC0), Dietary Guidelines for Americans 2025-2030.

AWS, Amazon Bedrock and other product names are trademarks of their owners. This series is independent and not endorsed by Amazon Web Services.