AWS Builder Center
How an Enterprise Can Move Its Agents to Amazon Bedrock AgentCore

How an Enterprise Can Move Its Agents to Amazon Bedrock AgentCore

How a freight team moved its four-model LangGraph agent off Amazon EKS without rewriting it, and what they stopped having to run.

Most multi-model agents I review in the field have the same shape. The agent logic is good, the model routing is clever, and the demo lands well. Then someone asks who patches the nodes, why two customers once saw each other's context, and which model burned last month's budget. There is no clear answer, because the team built an agent and accidentally became a platform team.
The workload we will go through today is a freight exception-handling agent running LangGraph on Amazon EKS, with four model backends and a pile of hand-built support code for state, credentials and tools.
We'll migrate it in three phases:
  • Lift it onto AgentCore Runtime.
  • Replace that support code with AgentCore Memory, Gateway and Identity.
  • Make it a governed workload on an enterprise agent platform.
Along the way I'll call out the multi-model traps that don't show up in single-model tutorials.

The workload: a freight exception desk with four models

Our example is a composite of engagements I've worked on, anonymized as a mid-sized freight forwarder. Its operations team handles a few thousand shipment exceptions a week. A container rolled to the next vessel, a customs hold, a damaged pallet, a missed delivery window. Each one used to need an analyst reading carrier emails, opening the transport management system (TMS), checking port status and writing to the customer.
The team built an "Exception Desk" agent in LangGraph to do the first 80% of that work. It is genuinely multi-model, and for good reasons:
Job in the graph
Model backend
Why this model
Triage: classify the exception, pull shipment and container IDs
Amazon Nova Lite on Amazon Bedrock
Cheap and fast; runs on every inbound message
Plan the remediation, draft carrier and customer messages
Anthropic Claude Sonnet on Amazon Bedrock
Best multi-step reasoning and tool use in their evals
Read scanned bills of lading and customs forms
Fine-tuned document model on an Amazon SageMaker AI endpoint
Trained on their own document layouts
Understand carrier emails in Spanish, Portuguese and Mandarin
LoRA-tuned open-weight model served by vLLM on EKS GPU nodes
Tuned on years of their carrier correspondence
Today it all runs on Amazon EKS. A FastAPI service hosts the graph, Amazon ElastiCache for Redis holds LangGraph checkpoints, PostgreSQL stores customer preferences, and a sidecar fetches carrier OAuth tokens from AWS Secrets Manager. Tools are plain Python functions calling the TMS, three carrier APIs and a port-congestion feed.
It works. It also produced five problems that pushed the team to migrate:
  1. Session data leak. An in-process cache keyed on shipment ID, not on conversation, once leaked one customer's context into another analyst's session.
  1. Long-running work breaks HTTP. A customs hold can take hours to clear. The agent polled inside a request and kept hitting load balancer idle timeouts.
  1. The GPU node group is a load to handle. Patching, driver upgrades and capacity for the vLLM pods ate a weekend every month.
  1. Credential sprawl. Every carrier integration had its own token refresh code, and the agent ran with one broad IAM role.
  1. No per-model cost view. Finance could see the EKS bill and the Bedrock bill, but not what one exception cost or which model drove it.



In the target architecture, each piece of hand-built support code on EKS maps to one AgentCore service, while the graph and the four model backends carry over unchanged.

What AgentCore changes

The first thing I tell customers: AgentCore Runtime hosts your agent, not your models. Your graph, your prompts and your routing logic move into Runtime. Your SageMaker endpoint and your vLLM server stay inference backends that the agent calls over the network, exactly as they do today. Once you get that boundary right, the migration plan almost writes itself.
Here is how the five problems map onto AgentCore services:
Problem on EKS
AgentCore capability
What stays your job
Session data leak
Runtime runs each session in its own microVM with isolated CPU, memory and filesystem, and sanitizes it when the session ends
Sending a stable session ID per conversation
Long-running work
Sessions can run up to 8 hours, with a 15-minute idle timeout by default
Designing async steps so you don't hold a request open
GPU node patching
Runtime is serverless for the agent tier
The GPU model server, until you move it to SageMaker AI or Bedrock
Credential sprawl
AgentCore Identity for inbound JWT auth and outbound OAuth to carriers; AgentCore Gateway to expose tools over MCP
Registering carriers as credential providers
No per-model cost view
Runtime emits traces to Amazon CloudWatch; you add model and tenant attributes to spans
Tagging and the attribution model
AgentCore is framework-agnostic and model-agnostic, so LangGraph stays.
What are the trade-offs?
  • If you need fine-grained control over networking, sidecars or scaling policies, a container platform you already run well is a valid home for an agent.
  • The case for Runtime gets strong when you have many agents, many tenants, or long-lived sessions, which is exactly where self-managed hosting starts to hurt.

Migration strategy: re-platform first, refactor second

What's the plan? Change where the agent runs before you change how it works. Every phase has an exit gate you can measure, and each one is reversible on its own.
Phase
Scope
Exit gate
0. Assess
Inventory graph nodes, model calls, state stores, tools, credentials and side effects. Build a golden eval set from resolved exceptions.
Every model call and tool call has an owner and a test case
1. Re-platform
Wrap the existing graph for Runtime. Keep Redis, Postgres and current tool code. Run in VPC mode and shadow production traffic.
Eval scores and p95 latency match EKS within agreed tolerance
2. Replace support code
Move state to AgentCore Memory, tools behind AgentCore Gateway, carrier OAuth into AgentCore Identity.
Redis, the token sidecar and the broad IAM role are retired
3. Govern
Land the agent in a workstream cell on the enterprise agent platform, with a governed inference gateway and evaluation gates in CI/CD.
Release, rollback and teardown are proven by the pipeline
Three questions to ask:
  • Where does each model live, and can Runtime reach it? Bedrock is an API call. A SageMaker endpoint needs an IAM permission. A vLLM server behind an internal load balancer needs Runtime's VPC network mode and a security group path.
  • What state survives a turn? LangGraph checkpoints, in-process caches and module-level globals all behave differently once every session gets a fresh microVM. Find them before production does.
  • What has side effects? Anything that emails a customer or rebooks a container needs idempotency keys before you start replaying traffic for evaluation.

Walkthrough: moving the Exception Desk onto AgentCore

The code below is trimmed to the parts that change. Model IDs, endpoint names and URLs are examples.

Step 1: Make model routing configuration, not code

Before touching hosting, pull the four backends behind one interface. On EKS the routing was scattered across graph nodes. Centralizing it gives you one place to set timeouts, fallbacks and the span attributes you'll need for cost attribution later.
# exception_desk/backends.py
import os, json, boto3, httpx
from opentelemetry import trace

tracer = trace.get_tracer("exception-desk")
bedrock = boto3.client("bedrock-runtime")
sagemaker = boto3.client("sagemaker-runtime")

BACKENDS = {
"triage": {"kind": "bedrock", "model": os.environ["TRIAGE_MODEL_ID"]}, # e.g. Amazon Nova Lite
"planner": {"kind": "bedrock", "model": os.environ["PLANNER_MODEL_ID"]}, # e.g. Claude Sonnet
"docs": {"kind": "sagemaker", "endpoint": os.environ["DOC_ENDPOINT"]},
"carrier_lang": {"kind": "openai_compat", "url": os.environ["VLLM_URL"],
"fallback": "planner"},
}

def call_model(role: str, messages: list, **kw) -> str:
cfg = BACKENDS[role]
with tracer.start_as_current_span(f"model.{role}") as span:
span.set_attribute("exception_desk.model_role", role)
span.set_attribute("exception_desk.backend", cfg["kind"])
try:
if cfg["kind"] == "bedrock":
r = bedrock.converse(modelId=cfg["model"], messages=messages, **kw)
usage = r["usage"]
span.set_attribute("gen_ai.usage.input_tokens", usage["inputTokens"])
span.set_attribute("gen_ai.usage.output_tokens", usage["outputTokens"])
return r["output"]["message"]["content"][0]["text"]
if cfg["kind"] == "sagemaker":
r = sagemaker.invoke_endpoint(EndpointName=cfg["endpoint"],
ContentType="application/json",
Body=json.dumps({"inputs": messages}))
return r["Body"].read().decode()
r = httpx.post(f"{cfg['url']}/v1/chat/completions", timeout=20,
json={"model": "carrier-lang", "messages": messages})
r.raise_for_status()
return r.json()["choices"][0]["message"]["content"]
except Exception as err:
if cfg.get("fallback"):
span.set_attribute("exception_desk.fallback", cfg["fallback"])
return call_model(cfg["fallback"], messages, **kw)
raise

Step 2: Wrap the graph for Runtime

The LangGraph graph doesn't change. You add an entrypoint, compile the graph once per microVM, and map the Runtime session to LangGraph's thread ID.
# exception_desk/main.py
from bedrock_agentcore.runtime import BedrockAgentCoreApp
from exception_desk.graph import build_graph

app = BedrockAgentCoreApp()
graph = build_graph() # same StateGraph as on EKS

@app.entrypoint
async def invoke(payload, context):
config = {"configurable": {"thread_id": context.session_id}}
state = {
"messages": [("user", payload["prompt"])],
"shipment_ref": payload.get("shipment_ref"),
"customer_id": payload["customer_id"],
}
async for update in graph.astream(state, config, stream_mode="updates"):
yield update # streamed back to the caller

if __name__ == "__main__":
app.run()
That  thread_id  line fixes the session data leak by construction. State is keyed to the conversation, and the conversation has its own microVM.

Step 3: Deploy in VPC mode with the AgentCore CLI

The vLLM server and Redis are private, so phase 1 runs in VPC mode. Scaffold a project and add the agent as bring-your-own code:
npm install -g @aws/agentcore

agentcore create --project-name exceptiondesk --no-agent --build Container \
--language Python --protocol HTTP --model-provider Bedrock --memory none

agentcore add agent --name exception_desk --type byo --build Container \
--language Python --protocol HTTP --code-location ./exception_desk \
--entrypoint main.py --model-provider Bedrock

agentcore deploy -y
Set the network mode, subnets and security groups in the project configuration before deploying; flags differ between CLI versions, so check  agentcore add agent --help . The execution role needs  bedrock:InvokeModel  on the two model IDs,  sagemaker:InvokeEndpoint  on the document endpoint, and nothing else.

Step 4: Invoke with a session ID that means something

This is the most important step in the whole migration. The session ID is the conversation. If a client generates a new one per request, every turn lands in a fresh microVM with no state. For the Exception Desk, we derive it from the exception case so a customs hold keeps its context for its whole life.
import boto3, json

client = boto3.client("bedrock-agentcore")

resp = client.invoke_agent_runtime(
agentRuntimeArn=AGENT_ARN,
runtimeSessionId=f"exception-case-{case_id}-v1-{customer_id}", # 33+ characters
payload=json.dumps({
"prompt": "Container MSKU1234567 rolled from MAERSK EDMONTON. Options?",
"shipment_ref": "SHP-88213",
"customer_id": customer_id,
}).encode(),
)

Step 5: Replace Redis and Postgres with AgentCore Memory

AgentCore Memory gives you short-term events per session and long-term records extracted by strategies. We map them like this: conversation turns become short-term events, and each customer's standing preferences become long-term preference records.
from bedrock_agentcore.memory import MemoryClient

memory = MemoryClient()

# One-time setup, usually in IaC
mem = memory.create_memory_and_wait(
name="ExceptionDeskMemory",
strategies=[{"userPreferenceMemoryStrategy": {
"name": "CustomerPreferences",
"namespaces": ["/customers/{actorId}/preferences"],
}}],
)

# Inside the graph's planner node
prefs = memory.retrieve_memories(
memory_id=MEMORY_ID,
namespace=f"/customers/{customer_id}/preferences",
query="routing and rebooking preferences",
)

# After each turn
memory.create_event(
memory_id=MEMORY_ID, actor_id=customer_id, session_id=session_id,
messages=[(user_text, "USER"), (answer_text, "ASSISTANT")],
)
Using the customer as the actor scopes long-term memory per tenant, which is the property you actually care about in a B2B agent. If you want to keep LangGraph's checkpointer API, the  langgraph-checkpoint-aws  package offers an AgentCore Memory-backed saver; check its current docs before adopting it.

Step 6: Tools behind AgentCore Gateway and carrier auth in Identity

The TMS has an OpenAPI spec, so it becomes a Gateway target directly. The three carrier integrations become AWS Lambda targets. Each outbound target uses an AgentCore Identity credential provider, so carrier client secrets and token refresh live in Identity instead of in our sidecar. The agent only ever sees an MCP endpoint.
from langchain_mcp_adapters.client import MultiServerMCPClient

mcp = MultiServerMCPClient({
"freight-tools": {
"transport": "streamable_http",
"url": GATEWAY_MCP_URL,
"headers": {"Authorization": f"Bearer {workload_token}"},
}
})
tools = await mcp.get_tools() # tms_get_shipment, carrier_rebook, port_congestion, ...
graph = build_graph(tools=tools)
The graph code that binds tools to the planner model is unchanged, because LangGraph sees ordinary tools. What changed is everything around them: one inbound authorizer, per-target credentials, and a single place to add or revoke a tool.

Step 7: Stop polling inside requests

For customs holds, the old agent polled the broker API inside a request. On Runtime, the entrypoint kicks off a background check and returns, and the next turn on the same session picks up the result. The Python SDK lets you register background work so Runtime reports the session as busy rather than idle. Combined with up to 8 hours per session, this removed every load balancer timeout we used to fight.

Prove it before you switch: observability, evaluation and cutover

A migration is done when the new path is measurably as good as the old one, not when the deploy succeeds.

Observability

Runtime sends logs, metrics and traces to Amazon CloudWatch, and the OpenTelemetry spans from Step 1 land in the same traces. Enable CloudWatch Transaction Search once per account so the agent traces are searchable. Then add three attributes to every span: the tenant (customer ID), the model role, and the exception type.

Evaluation

Replay the golden set from phase 0 against both stacks and compare them side by side. We score each run on the same dimensions on both sides:
Metric
How we measure it
Gate
Remediation quality
LLM-as-judge with a rubric per exception type, spot-checked by analysts
No regression beyond tolerance
Tool success rate
Successful tool calls over attempted, from traces
Equal or better
Triage accuracy
Exact match on exception type and IDs
Equal or better
Time to first token, p95
CloudWatch metrics
Within agreed tolerance
Cost per exception
Token usage from spans plus Runtime and endpoint cost
Known and reported
Fallback rate
Spans with the fallback attribute
Tracked, alarm on spikes
AgentCore also offers an evaluations capability you can wire into the pipeline later. Start with your own golden set anyway; it encodes what "good" means for your business, which no generic metric will.

Cutover

Runtime creates a new version each time you update the agent, and endpoints point at versions, which makes rollback a pointer change. We cut over in three steps:
  1. Shadow. Mirror production messages to Runtime, discard its outputs, compare traces.
  1. Canary by tenant. Route a handful of lower-risk customers to Runtime. Session IDs are per case, so a case never switches stacks halfway through.
  1. Full traffic, EKS warm. Keep the EKS deployment scaled down but deployable for two release cycles, then retire it.

Phase 3: A governed platform

The Exception Desk was the first of several agents this organization planned, with customs brokerage and carrier invoicing next in line. This makes the team ask: how do ten teams ship agents without ten copies of the same controls?
My recommendation is a federated model, where a central platform team owns shared, governed services and domain teams own their agents, tools and data. AWS lays out this pattern in detail in  Building an Agentic AI Platform on Amazon Bedrock AgentCore .
The unit of scale is a per-team "workstream cell" with its own Runtime, actor-scoped Memory and tool Gateway, so one team can deploy, fail or roll back without touching another. Here is what that meant for our migrated agent:
  • Model calls go through a governed inference gateway.
  • In that design, agents don't call model providers directly. The guardrails, model allow-lists, quotas and attribution are applied at the gateway.
  • Because Step 1 put every model call behind  call_model , adopting the gateway was a change to one module, not to the graph.
  • Tools are subscriptions, not imports.
  • The Exception Desk's Gateway exposes only the approved tool targets for its cell.
  • The eval gate tests the failures.
  • For every approved call, the pipeline makes an adversarial twin.
  • An unapproved model must be denied, an unsubscribed tool must be refused, and a request from another team's identity must be rejected. If an expected denial doesn't happen, the build fails.

Conclusion

Migrating a multi-model agent to Amazon Bedrock AgentCore is less about the agent and more about everything you stop running. The Exception Desk kept its LangGraph graph, its four models and its routing logic. What it lost was a Redis cluster, a token sidecar, a broad IAM role, an HTTP timeout problem and a monthly patching weekend for the agent tier.
If you're planning a similar move, start small and in order. Centralize model routing, wrap the existing agent for Runtime, prove parity on a golden set, and only then replace the support code with Memory, Gateway and Identity. When the second and third agents show up, land them in governed workstream cells so the controls you just earned don't drift.

Further reading

Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article