Skip to content
Bedrock Managed Agents: OpenAI Agents Inside Your AWS — ContentBuffer guide

Bedrock Managed Agents: OpenAI Agents Inside Your AWS

K
Kodetra Technologies··9 min read Intermediate

Summary

Call OpenAI's agent loop from AWS with SigV4 in Python: create a session, send a turn, read items.

On September 29 OpenAI shipped its Agents API in public beta at DevDay, and AWS put a customized version of it into Amazon Bedrock the same week as Bedrock Managed Agents powered by OpenAI. The pitch is simple: the same agent loop (reasoning, tool calls, multi-step coordination), but model inference, the harness and your tools all run inside your AWS account, authenticated with IAM instead of an OpenAI API key.

That matters if AWS is the only approved processor for AI workloads at your company. It also changes how you write the client. There is no openai SDK call to make: you sign plain REST requests with SigV4 against a new bedrock-mantle endpoint, create a session, post events, and read durable items back.

In this guide you will build a small Python client for the preview API, wire up the three IAM identities it needs, run a turn against a self-hosted execution environment, and handle the failure modes the docs warn about. One honest note up front: the service is in public preview and I have no live AWS account in the loop for this write-up. The request shapes below come from the AWS preview API reference, and I verified the client's signing, pagination and polling logic against a local mock server. Check the reference before you ship anything.

Prerequisites

  • An AWS account in us-east-1, us-west-2 or us-east-2 (the only preview regions)
  • AWS CLI v2 and credentials that can call the Bedrock Managed Agents actions
  • Python 3.10+ with pip install boto3 requests
  • Node.js 20+ and a recent Codex CLI, because the execution environment runs codex exec-server
  • The AWS example bundle (bma-examples.zip) for the self-hosted and AgentCore Runtime scripts

How the pieces fit

Three terms carry the whole design. A session is a stateful conversation that stores the model, instructions, tools, IAM role and execution environment. A turn is the work done in response to one submitted message. The execution environment is compute you provide, either a self-hosted machine or Amazon Bedrock AgentCore Runtime, where commands and tools actually run. The link between that compute and the service is the codex exec-server process.

So 'managed' covers the loop and the inference, not the sandbox. Unlike a vendor-hosted agent API, there is no AWS-run sandbox: tools execute on compute you own, with your network rules. That is the main trade you accept.

ConcernOpenAI Agents APIBedrock Managed Agents
InferenceOpenAI APIAmazon Bedrock
AuthOpenAI API keyAWS IAM, SigV4
Endpointapi.openai.combedrock-mantle.<region>.api.aws
Tools run inOpenAI or self-hosted sandboxYour host or AgentCore Runtime
SubagentsSupportedNot in preview

Step 1: Create the three IAM identities

Silent permission mismatches are the most common way to lose an hour here, so set up all three on purpose. The caller (your app) needs the Bedrock Managed Agents actions plus iam:PassRole. The session role is what the service assumes on your behalf. The execution environment has its own identity for whatever your tools touch.

The session role must trust the bedrock-mantle.amazonaws.com service principal, scoped to your account:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"Service": "bedrock-mantle.amazonaws.com"},
    "Action": "sts:AssumeRole",
    "Condition": {
      "StringEquals": {"aws:SourceAccount": "123456789012"},
      "ArnLike": {"aws:SourceArn": "arn:aws:bedrock-mantle:*:123456789012:*"}
    }
  }]
}

The caller must be allowed to pass that role, and only to this service:

{
  "Effect": "Allow",
  "Action": "iam:PassRole",
  "Resource": "arn:aws:iam::123456789012:role/BedrockManagedAgentsPreviewInferenceServiceRole",
  "Condition": {"StringEquals": {"iam:PassedToService": "bedrock-mantle.amazonaws.com"}}
}

Then grant the caller the client actions: bedrock-mantle:CreateAgentSession, GetAgentSession, ListAgentSessions, CreateAgentSessionEvent, ListAgentSessionEvents, ListAgentSessionItems and DeleteAgentSession. A self-hosted exec server additionally needs bedrock-mantle:RegisterEnvironment and bedrock-mantle:ConnectEnvironment. The AWS bundle deploys the client and session roles with CDK (npm ci, npx cdk bootstrap, npm run deploy), which is the fastest way to get a known-good baseline.

Step 2: Start the execution environment

On the machine where the agent should work, start the exec server. The example scripts use port 8765:

codex exec-server --port 8765

The bundle then walks you through 0.create-session.sh, 1.attach-exec-server.sh, 2.submit-turn.sh and 3.read-result.sh. The attach step is the one thing I am not reproducing in Python, because the preview reference I used does not document its request body. Run the bundle's attach script between creating the session and sending your first turn.

Step 3: A SigV4 client in Python

The endpoint is https://bedrock-mantle.<region>.api.aws, the SigV4 service name is bedrock-mantle, and session operations live under /openai/v1/agents/sessions. botocore can sign any request, so a thin wrapper is enough:

"""Minimal client for Amazon Bedrock Managed Agents (OpenAI), public preview."""
import json, os, time
import requests
from urllib.parse import urlencode
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.credentials import Credentials

REGION = os.environ.get("AWS_REGION", "us-east-1")
BASE = f"https://bedrock-mantle.{REGION}.api.aws"
SERVICE = "bedrock-mantle"
SESS = "/openai/v1/agents/sessions"


class BMA:
    def __init__(self, creds=None, base=BASE, region=REGION):
        if creds is None:
            import boto3
            c = boto3.Session().get_credentials().get_frozen_credentials()
            creds = Credentials(c.access_key, c.secret_key, c.token)
        self.creds, self.base, self.region = creds, base, region

    def _call(self, method, path, body=None, params=None):
        url = self.base + path
        if params:  # sign the exact URL we send, query string included
            url += "?" + urlencode(params)
        data = json.dumps(body) if body is not None else None
        req = AWSRequest(method=method, url=url, data=data,
                         headers={"Content-Type": "application/json"})
        SigV4Auth(self.creds, SERVICE, self.region).add_auth(req)
        r = requests.request(method, url, data=data,
                             headers=dict(req.headers), timeout=60)
        r.raise_for_status()
        return r.json() if r.content else {}

    def create_session(self, model, instructions, role_arn, workspace, skills=None):
        body = {
            "agent": {"model": model, "instructions": instructions},
            "environment": {
                "type": "self_hosted",
                "workspace_directory": workspace,
                "capability_directories": skills or [],
            },
            "role_arn": role_arn,
            "stream": False,
        }
        return self._call("POST", SESS, body)

    def send(self, session_id, text):
        body = {"events": [{
            "type": "agent.session.input.message",
            "input": [{"role": "user",
                       "content": [{"type": "input_text", "text": text}]}],
        }]}
        return self._call("POST", f"{SESS}/{session_id}/events", body)

    def cancel(self, session_id):
        return self._call("POST", f"{SESS}/{session_id}/events",
                          {"events": [{"type": "agent.session.input.cancel"}]})

    def get(self, session_id):
        return self._call("GET", f"{SESS}/{session_id}")

    def items(self, session_id, limit=100, order="asc"):
        out, after = [], None
        while True:
            p = {"limit": limit, "order": order}
            if after: p["after"] = after
            page = self._call("GET", f"{SESS}/{session_id}/items", params=p)
            out += page.get("data", [])
            if not page.get("has_more"): return out
            after = page["last_id"]

    def delete(self, session_id):
        return self._call("DELETE", f"{SESS}/{session_id}")

    def wait_idle(self, session_id, interval=2, timeout=300):
        t0 = time.time()
        while time.time() - t0 < timeout:
            s = self.get(session_id)
            if s["status"] in ("idle", "failed"):
                return s
            time.sleep(interval)
        raise TimeoutError("turn did not finish; consider cancel()")

Two details are worth knowing. First, the signed URL must include the query string, because the list-items call pages with limit, order and after. Signing the bare path and then appending parameters produces a signature mismatch (and in my first draft, a pagination loop that never ended against the mock). Second, a successful event submit returns an acknowledgement with a possibly empty body, which is why _call checks r.content before parsing.

Step 4: Run a turn end to end

import os, sys
from bma import BMA

ROLE = os.environ["BMA_ROLE_ARN"]
bma = BMA()
s = bma.create_session(
    model="openai.gpt-5.6-luna",
    instructions="Use the workspace tools to complete the user's task. Never delete files.",
    role_arn=ROLE, workspace="/work/demo", skills=["/work/demo/skills"])
sid = s["id"]
print("session", sid, s["status"])
# attach the exec server here (sample script 1.attach-exec-server.sh) before sending turns
bma.send(sid, "List the markdown files in the workspace and summarize the newest one.")
final = bma.wait_idle(sid)
if final["status"] == "failed":
    sys.exit(f"failed: {final.get('error')}")
for it in bma.items(sid):
    print(it.get("type"), str(it)[:120])
bma.delete(sid)

Set BMA_ROLE_ARN to the session role, then run it. The model ID in the AWS reference example is openai.gpt-5.6-luna; list what your region actually offers with a signed GET to /v1/models before hard-coding anything.

Expected shape of a successful run (item contents vary by model and task):

session sess_01H... idle
message {'type': 'message', 'role': 'user', 'content': [{'type': 'input_text', ...
reasoning {'type': 'reasoning', ...
command_output {'type': 'command_output', 'exit_code': 0, ...
message {'type': 'message', 'role': 'assistant', 'content': [{'type': 'output_text', 'text': 'Found 3 markdown files...

I am showing the output as an illustration of the structure, not a captured transcript. Item type names are not enumerated in the pages I read, so log your own and key off those.

Step 5: Add skills and read progress live

Skills are plain folders containing a SKILL.md, placed in directories you list under capability_directories (at most 32 unique paths per session). Tools come from STDIO MCP servers that run inside your execution environment, and you can restrict each with an allow list. If you have written Claude Code skills, the format will feel familiar.

For progress while a turn runs, call GET /openai/v1/agents/sessions/{id}/events with Accept: text/event-stream. It emits state changes, turn progress, generated text, command output and completion, failure or cancellation events. Polling, as in the client above, is simpler and fine for batch jobs; the sample scripts poll every 2 seconds with a 300 second timeout.

A worked example: a nightly docs audit

Say you keep runbooks in a repo on a build host and want an agent to flag stale ones. Put a skills/stale-docs/SKILL.md in the workspace describing the check (find files untouched for 180 days, list owners from the front matter, write a report to reports/stale.md). Start the exec server on the host, create a session with that directory as a capability directory, and send:

Run the stale-docs skill and write reports/stale.md. Do not modify any other file.

The call returns immediately, wait_idle blocks until the session is idle or failed, and items() gives you the durable record: the commands that ran and their exit codes. Because everything ran in your account, CloudTrail already holds the API-side audit trail, and the agent only touched what the host's own identity allows.

Cost, briefly

During preview AWS charges no service fee for Managed Agents, so you pay for tokens and for the compute you bring. Third-party analysis of the preview pricing puts in-Region token rates about 10% above OpenAI's direct rates, and says model choice moves a bill far more than runtime choice. Treat those figures as indicative and confirm on the Bedrock pricing page. If you deploy the AgentCore sample stack, it includes a NAT gateway that bills around the clock; destroy the stack when you are done.

Gotchas and pitfalls

  • 201/202 means accepted, not done. A successful event submit says nothing about the outcome. Read items and exit codes.
  • Idle is not success. A session can go idle after a failed command. Check the status for failed, then inspect output items and any external side effects.
  • Cancel does not roll back. agent.session.input.cancel stops the turn, not tool side effects that already completed.
  • Three identities. If the session role does not trust bedrock-mantle.amazonaws.com, or the caller lacks iam:PassRole, you get failures that look unrelated. Check AWS_PROFILE in each terminal.
  • No turn-list API. Correlate work through the turn_id on items.
  • Preview gaps. No subagents, no programmatic tool calling, no cross-Region inference profiles, no built-in long-term memory, no console UI, and documented input is text only.
  • Human approval is yours to build. The security guidance says to enforce authorization and review in your tool implementation. Wrap destructive tools with an approval step.
  • Prompt injection. Once the agent has a shell, text in files and web pages is untrusted input. Use the per-server allow list and a read-only workspace where you can.
  • It can change. AWS labels the API as subject to change in preview. Pin your client behind one module, as above.

Quick reference

ItemValue
Endpointhttps://bedrock-mantle.<region>.api.aws
SigV4 servicebedrock-mantle
Regions (preview)us-east-1, us-west-2, us-east-2
Create sessionPOST /openai/v1/agents/sessions
Send messagePOST .../sessions/{id}/events with agent.session.input.message
Cancel turnPOST .../events with agent.session.input.cancel
Read outputGET .../sessions/{id}/items?limit&order&after
StreamGET .../sessions/{id}/events, text/event-stream
DeleteDELETE .../sessions/{id}
Example modelopenai.gpt-5.6-luna
Max idle / lifetime on AgentCore28,800 s

Next steps

  • Run the AWS bundle once end to end, then swap its shell scripts for the Python client above.
  • Add a second skill and an STDIO MCP server with a tight allow list.
  • Put an approval gate in front of any tool that writes or deletes, since the service will not do it for you.
  • Move the exec server to AgentCore Runtime when you need managed sessions, and budget the NAT gateway.
  • Compare with your existing agent setup: if you need subagents or memory today, the preview limits may rule this out until GA.

Sources

  • AWS: Amazon Bedrock Managed Agents (OpenAI) user guide, preview REST API reference, security and IAM roles, and quotas and limitations pages (docs.aws.amazon.com/bedrock)
  • AWS Weekly Roundup, October 5, 2026
  • OpenAI developer docs: Bedrock Managed Agents guide
  • eesel.ai: Bedrock Managed Agents architecture and pricing analysis (third party)

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,605 newsletter subscribers.

Also get