

# Self-hosted compute

When your agent runs outside AgentCore and sends telemetry to AgentCore Observability, you want the full instrumentation and attribute steps, so its spans still carry cost identity. The console then shows the agent’s model cost plus the cost of the AgentCore tools it calls, under the agent’s own name, the same as an agent on AgentCore Runtime.

Because Runtime is not in the path, **Runtime compute is not attributed** for a self-hosted agent. The model calls and the AgentCore tools you call (Gateway, Memory, Browser, Code Interpreter) are.

## Step 1: Turn on Transaction Search
<a name="_step_1_turn_on_transaction_search"></a>

Turn on CloudWatch Transaction Search for the account and Region. It is not on by default; it is where the spans are stored.

 **To turn on CloudWatch Transaction Search (console)** 

1. Open the [CloudWatch](https://console.aws.amazon.com/cloudwatch) console.

1. In the navigation pane, expand **Application Signals (APM)** and choose **Transaction search**.

1. Choose **Enable Transaction Search**.

1. Select the checkbox to ingest spans as structured logs.

1. Choose **Save**.

The status can stay `PENDING` for more than 5 minutes; per-resource tracing fails until it is `ACTIVE`. For the API path, see [Turn on CloudWatch Transaction Search](acv-see-your-first-agent-cost.md#acv-turn-on-transaction-search).

## Step 2: Turn on tracing for each AgentCore resource
<a name="_step_2_turn_on_tracing_for_each_agentcore_resource"></a>

For each AgentCore resource the agent uses (Gateway, Memory, Code Interpreter, Browser), turn on tracing in the AgentCore console.

 **To turn on tracing for a resource (console)** 

1. Open the resource’s page in the [AgentCore](https://console.aws.amazon.com/bedrock-agentcore) console.

1. Choose the **Observability** tab, then choose **Manage observability configuration**.

1. In the **Tracing** section, choose **Edit** to enable trace delivery to CloudWatch.

For the per-resource details, see [Configure tracing delivery to CloudWatch using the console](observability-configure.md#observability-configure-tracing).

## Step 3: Send the agent’s traces to AWS X-Ray
<a name="step_3_send_the_agent_8217_s_traces_to_shared_aws_x_ray"></a>

The recommended way is the AWS Distro for OpenTelemetry (ADOT). Any OpenTelemetry setup also works if it sends to `https://xray.<region>.amazonaws.com/v1/traces` with AWS request signing (SigV4).

**Note**  
Accurate cost attribution is guaranteed when ADOT produces the telemetry. For a self-hosted agent, a non-ADOT OpenTelemetry setup also works, as long as it produces the correct model-call span (Step 5) and signs its export to the X-Ray endpoint.

### Option A: ADOT
<a name="_option_a_adot"></a>

Follow the AWS setup for agents hosted outside AgentCore in [Enabling observability for agents hosted outside of AgentCore](observability-configure.md#observability-configure-3p). On AWS Lambda, use the ADOT Lambda layer and set `AWS_LAMBDA_EXEC_WRAPPER=/opt/otel-instrument`. The minimum is `aws-opentelemetry-distro>=0.18.0` (0.22.0 to price cache tokens). Start the agent with `opentelemetry-instrument python my_agent.py`.

Set these environment variables:

```
AGENT_OBSERVABILITY_ENABLED=true
OTEL_PYTHON_DISTRO=aws_distro
OTEL_PYTHON_CONFIGURATOR=aws_configurator
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_TRACES_EXPORTER=otlp
OTEL_EXPORTER_OTLP_LOGS_HEADERS=x-aws-log-group=<agent log group>,x-aws-log-stream=runtime-logs,x-aws-metric-namespace=bedrock-agentcore
# cost identity: set this once, with all keys (see Step 4)
OTEL_RESOURCE_ATTRIBUTES=cloud.resource_id=<a stable ID such as the Amazon EKS, Amazon ECS, or AWS Lambda ARN; not containing :runtime/>,service.name=<agent name>,service.version=<version>,aws.log.group.names=<agent log group>
```

ADOT copies `session.id` onto spans and signs the export for you.

### Option B: A self-managed OpenTelemetry Collector
<a name="_option_b_a_self_managed_opentelemetry_collector"></a>

Run an OpenTelemetry Collector next to the agent and export OTLP to it. The collector signs the export and sends it to X-Ray:

```yaml
receivers:
  otlp:
    protocols:
      http:
        endpoint: 0.0.0.0:4318

exporters:
  otlphttp/traces:
    compression: gzip
    traces_endpoint: https://xray.us-east-1.amazonaws.com/v1/traces
    auth:
      authenticator: sigv4auth/traces
    sending_queue:
      enabled: false      # send synchronously; keep the default (true) on ECS, EKS, EC2

extensions:
  sigv4auth/traces:
    region: "us-east-1"
    service: "xray"

service:
  extensions: [sigv4auth/traces]
  pipelines:
    traces:
      receivers: [otlp]
      exporters: [otlphttp/traces]
```

Replace `us-east-1` with your Region in both places. On a host that is frozen between requests (for example, AWS Lambda), turn off the exporter’s `sending_queue` so each export finishes before the host freezes; keep the default queue on long-running hosts (Amazon ECS, Amazon EKS, Amazon EC2). Without a collector (SDK only), call `tracer_provider.force_flush()` at the end of each Lambda invocation, or let the ADOT Lambda layer flush.

The credentials that sign the export need permission to send trace segments:

```json
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["xray:PutTraceSegments", "xray:PutTelemetryRecords"],
    "Resource": "*"
  }]
}
```

The managed policy `AWSXrayWriteOnlyAccess` covers both actions.

### Instrumentation libraries
<a name="_instrumentation_libraries"></a>

Your framework and its instrumentation (ADOT’s instrumentors, or OpenInference, Traceloop, or OpenLIT) must produce a model-call span (Step 5). OpenInference’s in-process session helpers alone are not enough, because only values carried in baggage reach the AgentCore tools.

## Step 4: Give the agent an identity
<a name="_step_4_give_the_agent_an_identity"></a>

Set the agent’s identity in the same single `OTEL_RESOURCE_ATTRIBUTES` variable shown in the Step 3 Option A block. Set it once, with all of its keys together, rather than as a second, separate assignment:

```
OTEL_RESOURCE_ATTRIBUTES=cloud.resource_id=<a stable ID such as the Amazon EKS, Amazon ECS, or AWS Lambda ARN; not containing :runtime/>,service.name=<agent name>,service.version=<version>,aws.log.group.names=<agent log group>
```

For example:

```
OTEL_RESOURCE_ATTRIBUTES=cloud.resource_id=arn:aws:eks:us-west-2:111122223333:cluster/my-agent,service.name=my_agent-AbCdEf1234,service.version=1,aws.log.group.names=<agent log group>
```

The `cloud.resource_id` **must not contain `:runtime/` **, because that marks an agent hosted on AgentCore Runtime. A model call whose span has no `cloud.resource_id` still counts in the total, but under no agent.

## Step 5: Record each model call
<a name="_step_5_record_each_model_call"></a>

Each model call needs a span that:
+ is marked as an outgoing call (`CLIENT`),
+ sets `gen_ai.operation.name` to `chat` (or `text_completion`, `generate_content`, or `embeddings`),
+ names the model with `gen_ai.request.model`,
+ carries `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`.

Agent frameworks and their tracing libraries produce this span. If you call a model from your own code, create the span yourself. Some models are not priced; see [Model pricing caveats](acv-model-pricing-caveats.md).

## Step 6: Pass four values in baggage on every request
<a name="_step_6_pass_four_values_in_baggage_on_every_request"></a>

Put these in OpenTelemetry baggage so they travel with each call the agent makes to Gateway, Memory, Code Interpreter, or Browser:
+  `aws.client.cloud.resource_id` — the agent’s ID from Step 4, so those calls are charged to the agent.
+  `session.id` — the conversation id (the agent picks it).
+  `aws.tenant.id` and `user.id` — for the Tenant and User ID filters.

Every call to an AgentCore tool must happen while these values are set. Calls made outside that are charged to no agent.

## Step 7: Copy the same values onto the agent’s own spans
<a name="_step_7_copy_the_same_values_onto_the_agents_own_spans"></a>

Values that are only passed along do not appear on the agent’s own spans by themselves. Copy `session.id`, `aws.tenant.id`, and `user.id` onto the agent’s spans, at least its model-call spans. A small span processor does it for every span:

```python
from opentelemetry import baggage, context
from opentelemetry.sdk.trace import SpanProcessor

class BaggageToAttributes(SpanProcessor):
    """Copy session, tenant, and user from baggage onto every span the agent creates."""
    KEYS = ("session.id", "aws.tenant.id", "user.id")
    def on_start(self, span, parent_context=None):
        for k in self.KEYS:
            v = baggage.get_baggage(k, parent_context)
            if v is not None:
                span.set_attribute(k, v)

# tracer_provider.add_span_processor(BaggageToAttributes())

def handle(request):
    ctx = baggage.set_baggage("aws.client.cloud.resource_id", AGENT_ID)   # the cloud.resource_id from Step 4
    ctx = baggage.set_baggage("session.id", request.session_id, ctx)
    ctx = baggage.set_baggage("aws.tenant.id", request.tenant_id, ctx)
    ctx = baggage.set_baggage("user.id", request.user_id, ctx)
    token = context.attach(ctx)
    try:
        run_turn(request)      # all model calls and AgentCore tool calls happen in here
    finally:
        context.detach(token)
```

## What is not available for a self-hosted agent
<a name="_what_is_not_available_for_a_self_hosted_agent"></a>
+  **The Tag filter**, because it reads the tags on the AgentCore Runtime resource, which a self-hosted agent does not have.
+  **Runtime compute cost**, because Runtime is not in the path.
+  **The Spans, Traces, latency, and error views beyond model-call spans** — these show only the agent’s model-call spans.

## An agent on AgentCore Runtime that does not use ADOT
<a name="_an_agent_on_agentcore_runtime_that_does_not_use_adot"></a>

If you run on AgentCore Runtime but use plain OpenTelemetry instead of ADOT, follow Steps 5 to 7 with these differences:
+ AgentCore Runtime already sets the agent’s identity (Step 4 is done for you).
+ Use the session id AgentCore Runtime gives each request. Read it from `BedrockAgentCoreContext.get_session_id()` if your agent uses the AgentCore Python SDK app, or from the `X-Amzn-Bedrock-AgentCore-Runtime-Session-Id` request header. A sub-agent uses the session id its caller passed along.
+ Include the AWS X-Ray trace format in your propagators (`tracecontext,xray,baggage`), or the agent’s spans are not linked to the Runtime trace.

## Other clouds and on-premises
<a name="_other_clouds_and_on_premises"></a>

An agent on another cloud or on-premises follows the same steps: send signed OTLP to the X-Ray endpoint in your Region, give the agent an identity, record the model-call span, and pass the four values in baggage.

From compute outside AWS, the agent needs:
+  **Network:** outbound HTTPS (port 443) to the public X-Ray OTLP endpoint `https://xray.<region>.amazonaws.com/v1/traces`, and to the AgentCore endpoints it calls (Gateway, Memory, Code Interpreter, Browser). No VPC peering or private link is required from another cloud.
+  **Credentials:** the export must be authenticated. Use either SigV4 with AWS credentials (for example, IAM Roles Anywhere or an IAM user’s keys) that allow `xray:PutTraceSegments`, or a bearer token (API key), which the CloudWatch OTLP traces endpoint supports for workloads outside AWS. The AgentCore tool calls need AWS credentials (SigV4) or the Gateway’s configured inbound auth.
+ Transaction Search must be on in the Region the spans are sent to (Step 1).

## Per-provider detail
<a name="_per_provider_detail"></a>

Only Amazon Bedrock models are priced, from the public price list. A call to a non-AWS provider (for example, OpenAI, the Anthropic API, or Gemini) shows its tokens when the model-call span records them, but no cost. If you keep a per-provider setup, it only needs to emit the model-call span from Step 5 (most provider instrumentations do); expect no cost for a non-Bedrock call. For a non-Bedrock provider, install the matching GenAI instrumentation package so token counts are recorded; see [Third-party frameworks on AgentCore Runtime](acv-third-party-frameworks-on-runtime.md).

## Confirm
<a name="_confirm"></a>

See [Check your setup is ready for cost](acv-check-your-setup-is-ready.md).