Grafana Cloud

Monitor agents on Amazon Bedrock AgentCore

Instrument a LangChain agent that runs in Amazon Bedrock AgentCore Runtime so that Agent Observability records what the agent does. After you complete this guide, each AgentCore session appears in Agent Observability as a conversation. The conversation shows the model generations, tool calls, token usage, and estimated cost of each invocation, and links to the OpenTelemetry trace.

This guide uses Python and LangChain, but AgentCore Runtime can host agents built with other frameworks. Agent Observability has integrations for other frameworks, such as Strands Agents, LangGraph, and OpenAI Agents. With another framework, the steps that record generations change, and tool content capture can differ. The OpenTelemetry setup and the AgentCore steps stay the same. For the supported frameworks, refer to Instrument agents with framework integrations. To see a working agent before you change your own, refer to Try the examples.

How the integration works

Your app’s OpenTelemetry providers export traces, including tool execution spans, and metrics to the Grafana Cloud OpenTelemetry Protocol (OTLP) endpoint. Every setup in this guide uses this export path.

To record model generations, choose one of these options:

  • OpenTelemetry spans: Your instrumentation writes generation spans with generative AI attributes. Agent Observability reads the generations from the traces that you send to the OTLP endpoint.
  • Agent Observability SDK: A LangChain callback records each generation and tool call. The SDK sends the generations to the Agent Observability API.

For a comparison, refer to Choose how to record generations.

The AgentCore session ID becomes the conversation ID, so all invocations in one session appear in one conversation.

By default, AgentCore applies an AWS Distro for OpenTelemetry (ADOT) configuration that sends telemetry to Amazon CloudWatch. The integration turns that configuration off so that it doesn’t replace your Grafana Cloud OTLP settings.

Before you begin

Make sure you have these tools, permissions, and credentials:

  • An AgentCore project with a Python LangChain agent, and the AgentCore CLI. To install the CLI, follow the AgentCore CLI installation instructions.
  • Node.js 20 or later, Python 3.10 or later, and uv.
  • AWS credentials with permission to invoke your model or inference profile in Amazon Bedrock. The model must be available to your account in the AWS Region that you use.
  • A Grafana Cloud stack with Agent Observability enabled, and an account with permission to read conversations.
  • The OTLP endpoint and instance ID, and a stack access policy token with the traces:write and metrics:write scopes. To record generations with the SDK, you also need the Agent Observability API URL and instance ID, and the sigil:write scope on the token. To find these values, refer to Set up Agent Observability in Grafana Cloud.

Install the OpenTelemetry packages

In the directory that holds your agent’s pyproject.toml, add the OpenTelemetry SDK and HTTP exporters. This directory is the codeLocation of your runtime in agentcore/agentcore.json.

Bash
uv add opentelemetry-sdk opentelemetry-exporter-otlp-proto-http

AgentCore installs the dependencies from pyproject.toml when it builds the runtime.

Configure OpenTelemetry export

The OpenTelemetry exporters read their settings from environment variables. Set these variables for your agent:

VariableValueSecret
OTEL_EXPORTER_OTLP_ENDPOINTThe OTLP endpoint, ending in /otlp.No
OTEL_EXPORTER_OTLP_HEADERSAuthorization=Basic%20<BASE64_CREDENTIALS>Yes
OTEL_SERVICE_NAMEThe service name for your traces and metrics.No
DISABLE_ADOT_OBSERVABILITYtrueNo

Keep %20 for the space after Basic. To get <BASE64_CREDENTIALS>, Base64-encode the OTLP instance ID and access policy token joined by a colon. Use the instance ID from the OpenTelemetry card because it can differ from the Agent Observability instance ID. For the encoding command, refer to Send directly to Grafana Cloud.

If you record generations with the SDK, you also set the variables in Configure the SDK. Where you set all these variables depends on where the agent runs:

  • Local development: Add the variables to agentcore/.env.local in your project. AgentCore loads this file when you run the agent locally. Make sure that Git ignores the file.
  • AgentCore Runtime: The hosted runtime doesn’t receive agentcore/.env.local. Refer to Deploy to AgentCore Runtime.

Set up OpenTelemetry

In your entrypoint file, set up the OpenTelemetry tracer and meter providers. Run this code once, when the module loads, before AgentCore handles requests.

Python
# Add the imports for atexit and the OpenTelemetry classes in this code.

resource = Resource.create()

tracer_provider = TracerProvider(resource=resource)
tracer_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(tracer_provider)

meter_provider = MeterProvider(
    resource=resource,
    metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter())],
)
metrics.set_meter_provider(meter_provider)


def shutdown() -> None:
    tracer_provider.shutdown()
    meter_provider.shutdown()


atexit.register(shutdown)

The OTLP exporters read OTEL_EXPORTER_OTLP_ENDPOINT and OTEL_EXPORTER_OTLP_HEADERS, and the resource reads OTEL_SERVICE_NAME. The shutdown function exports buffered telemetry before the process exits.

Choose how to record generations

Record each model call with one option only. If the SDK and OpenTelemetry spans both export the same call, Agent Observability can show duplicate generations.

ConsiderationOpenTelemetry spansAgent Observability SDK
Generation pathYour traces, through the OTLP endpointThe Agent Observability API, through the SDK
Access policy token scopestraces:write and metrics:writesigil:write, traces:write, and metrics:write
LangChain instrumentationGenerative AI instrumentation that you chooseThe Agent Observability LangChain callback
gen_ai_client metricsOnly if your instrumentation emits themAlways, from the SDK
Content captureYour instrumentation’s settingsAGENTO11Y_CONTENT_CAPTURE_MODE

Use OpenTelemetry spans if your agent already exports spans with generative AI attributes, or if you can’t add the SDK to your app. Use the SDK if you want one LangChain callback that records generations and tool calls and emits the gen_ai_client metrics that the Agent Observability dashboards use.

Record generations with OpenTelemetry spans

Complete these steps to record generations with OpenTelemetry spans. You don’t need the SDK packages or the AGENTO11Y_* variables. To record generations with the SDK instead, skip to Record generations with the SDK.

  1. Add generative AI instrumentation to your model calls. Each generation span needs the gen_ai.operation.name, gen_ai.provider.name, and gen_ai.request.model attributes. To show prompts and responses in conversations, the instrumentation must also write the gen_ai.input.messages and gen_ai.output.messages attributes. For the full requirements, refer to Instrument agents with OpenTelemetry.

  2. In the function that handles AgentCore requests, read the AgentCore session ID from context.session_id and use it as the conversation ID. Some local invocations have no session ID, so generate a conversation ID in that case. On each generation span, set gen_ai.conversation.id to the conversation ID and gen_ai.agent.name to your agent name. With the same conversation ID, all invocations in one session appear in one conversation.

  3. Set agento11y.record=true on each generation span and each tool execution span.

    Don’t set the attribute on the resource. A resource-level marker selects every span that has a gen_ai.operation.name attribute, including spans from other generative AI instrumentation in the process. Those spans can create duplicate generations.

  4. Check which content your instrumentation writes to the spans. Prompts, responses, and tool calls often carry customer data. In Grafana Cloud, the tool step details show Not recorded for Arguments and Result, because Grafana Cloud removes those attributes from the traces that it stores.

After you complete these steps, skip to Run the agent locally.

Record generations with the SDK

Complete the steps in this section to record generations with the Agent Observability SDK and its LangChain callback, instead of OpenTelemetry spans.

Install the SDK packages

In the same directory as the OpenTelemetry packages, add the Agent Observability SDK and its LangChain integration.

Bash
uv add agento11y agento11y-langchain

Configure the SDK

The SDK client reads its settings from environment variables. Set these variables in the same place as the OpenTelemetry variables:

VariableValueSecret
AGENTO11Y_ENDPOINTThe Agent Observability API URL.No
AGENTO11Y_PROTOCOLhttpNo
AGENTO11Y_AUTH_MODEbasicNo
AGENTO11Y_AUTH_TENANT_IDThe Agent Observability instance ID.No
AGENTO11Y_AUTH_TOKENThe access policy token.Yes
AGENTO11Y_AGENT_NAMEThe agent name to show in Agent Observability.No
AGENTO11Y_CONTENT_CAPTURE_MODEno_tool_content, full, or metadata_only. Refer to Choose a content capture mode.No

Create the SDK client

In your entrypoint file, after the OpenTelemetry setup, create the SDK client. Replace the shutdown function and the atexit.register call from the OpenTelemetry setup with this code, which also shuts down the client.

Python
from agento11y import Client

agento11y = Client()


def shutdown() -> None:
    agento11y.shutdown()
    tracer_provider.shutdown()
    meter_provider.shutdown()


atexit.register(shutdown)

This code does the following:

  • Client() reads the AGENTO11Y_* variables. Because you create the client after the global providers, the spans and metrics that the SDK emits use them. Without configured providers, the SDK drops its spans and metrics.
  • The shutdown function shuts down the client before the providers, so that the client exports its buffered data while the providers still run.

Instrument the entrypoint

In the same file, in the function that handles AgentCore requests, use the session ID as the conversation ID, start an invocation span, and attach the LangChain callbacks to the agent call.

Python
from uuid import uuid4

from agento11y_langchain import with_agento11y_langchain_callbacks
from bedrock_agentcore.runtime import BedrockAgentCoreApp

app = BedrockAgentCoreApp()
tracer = trace.get_tracer(__name__)


@app.entrypoint
def handler(request, context):
    conversation_id = getattr(context, "session_id", None) or f"conv-{uuid4().hex[:12]}"
    with tracer.start_as_current_span("agent.invoke") as span:
        span.set_attribute("gen_ai.conversation.id", conversation_id)
        config = with_agento11y_langchain_callbacks(
            {"metadata": {"conversation_id": conversation_id}},
            client=agento11y,
            provider="bedrock",
        )
        result = agent.invoke(
            {"messages": [{"role": "user", "content": request["prompt"]}]},
            config=config,
        )
    return {"conversation_id": conversation_id, "reply": result["messages"][-1].content}

In this example, agent is your LangChain agent, created once when the module loads. The handler does the following:

  • Reads the AgentCore session ID from the request context. Some local invocations have no session ID, so the handler generates a conversation ID in that case.
  • Starts an invocation span and sets gen_ai.conversation.id to the conversation ID. This attribute links the trace to the conversation.
  • Adds the Agent Observability callback to the LangChain run configuration. If the configuration already has callbacks, with_agento11y_langchain_callbacks keeps them. The provider argument sets the provider that Agent Observability records for each generation. Use bedrock for models that you call through Amazon Bedrock.

Choose a content capture mode

AGENTO11Y_CONTENT_CAPTURE_MODE controls how much content the SDK exports:

  • no_tool_content: The SDK exports full generation messages, which include tool arguments and results. By default, tool execution spans omit the arguments and results. The LangChain callback opts in to tool span content, so with LangChain this mode also exports tool arguments and results on tool execution spans.
  • full: The SDK exports all content, including tool arguments and results on tool execution spans.
  • metadata_only: The SDK exports structure, such as roles, tool names, models, token usage, and timing. It removes message text, tool arguments, and tool results.

In Grafana Cloud, the conversation shows tool arguments and results from the generation messages. The tool step details show Not recorded for Arguments and Result, because Grafana Cloud removes those attributes from the traces that it stores.

Tool calls often carry customer data. With the LangChain callback, only metadata_only keeps tool arguments and results out of the export. Review your capture mode before you send production traffic. For details, refer to Content capture modes.

Run the agent locally

Run the agent in AgentCore local development mode to check the integration before you deploy.

  1. From your AgentCore project directory, build the project.

    Bash
    agentcore build
  2. Start the local runtime.

    Bash
    agentcore dev --no-traces

    The --no-traces flag turns off the local trace collector of the AgentCore CLI, so that your agent exports traces and metrics directly to Grafana Cloud. Leave the server running.

  3. In a second terminal, from the same directory, invoke the agent. Replace <RUNTIME_NAME> with the name of your runtime in the runtimes list of agentcore/agentcore.json.

    Bash
    agentcore invoke --runtime <RUNTIME_NAME> --local \
      --payload '{"prompt":"<PROMPT>"}'

    If you start the server on a custom port, pass the same --port value to both commands.

Verify the data in Grafana Cloud

After you invoke the agent locally, check that its conversation, trace, and metrics arrive in Grafana Cloud. Complete these checks before you deploy, then repeat them for the deployed agent.

  1. In the main menu, select Observability > Agent Observability > Conversations.

  2. Set a time range that includes your request and filter by your agent name. Open the matching conversation, click Copy conversation ID, and compare the ID with the conversation ID that your handler used.

  3. Inspect a generation for its model response, token usage, and tool calls. If pricing data is available for the model, the conversation also shows an estimated cost. If you pay a negotiated Amazon Bedrock rate, configure your model prices so that new generations use your rate.

  4. Click the trace link of the generation. Inspect the child spans to find tool execution durations. With OpenTelemetry spans, span names depend on your instrumentation. With the SDK handler in this guide, look for the agent.invoke span and check that gen_ai.conversation.id matches the conversation ID.

  5. In Explore or Drilldown > Metrics, select your Grafana Cloud metrics data source and search for gen_ai_client. Grafana Cloud stores OpenTelemetry metric names with underscores instead of dots and adds unit suffixes. For example, look for gen_ai_client_operation_duration_seconds and gen_ai_client_token_usage. Metrics are exported periodically, so recent invocations can take up to a minute to appear.

    With OpenTelemetry spans, these metrics appear only if your instrumentation emits them. The Agent Observability dashboards use these metrics, so without them the dashboards stay empty.

Deploy to AgentCore Runtime

Deploy the agent after you verify its local telemetry. AgentCore resources can incur AWS charges.

  1. In agentcore/aws-targets.json, check that the account ID is your AWS account ID and that the AWS Region matches the Region of your model.

  2. Configure the runtime environment.

    • Set the non-secret variables from Configure OpenTelemetry export and, if you use the SDK, Configure the SDK in the envVars configuration of the runtime. Include DISABLE_ADOT_OBSERVABILITY=true.
    • Supply OTEL_EXPORTER_OTLP_HEADERS through your approved AWS secret delivery mechanism. If you use the SDK, supply AGENTO11Y_AUTH_TOKEN the same way.
    • Don’t put tokens or authorization headers in agentcore/agentcore.json, which Git tracks.

    For details about the ADOT settings, refer to the AgentCore observability configuration.

  3. Build the project, then deploy it.

    Bash
    agentcore build
    agentcore deploy

    If your AWS account doesn’t have the AWS Cloud Development Kit (AWS CDK) bootstrap resources, an AWS administrator might need to add them first. Each account and Region needs this setup only once. For the required AWS permissions, refer to AgentCore Runtime permissions.

  4. Invoke the deployed agent with a session ID. Replace <RUNTIME_NAME> with the same runtime name that you used locally, and <SESSION_ID> with an ID of at least 33 characters. The session ID becomes the conversation ID in Agent Observability.

    Bash
    agentcore invoke --runtime <RUNTIME_NAME> --session-id <SESSION_ID> \
      --payload '{"prompt":"<PROMPT>"}'

    To continue the same conversation, invoke the agent again with the same session ID.

  5. Repeat the checks in Verify the data in Grafana Cloud for the deployed agent. The conversation ID matches the session ID that you used.

Troubleshoot missing data

If telemetry is missing after a successful invocation, check the export path for the affected signal:

  • Missing conversation: With OpenTelemetry spans, check that each generation span has agento11y.record=true and the attributes in Record generations with OpenTelemetry spans. With the SDK, check the Agent Observability endpoint, instance ID, and sigil:write scope, and check that the agent call passes the configuration from with_agento11y_langchain_callbacks.
  • Each invocation creates a new conversation: Check that the handler uses the AgentCore session ID, and that you invoke the agent with the same session ID.
  • Missing traces or metrics: Check the OTLP endpoint, the instance ID in the authorization header, and the traces:write and metrics:write scopes. If you use the SDK, check that the providers are set up before you create the SDK client.
  • Failed to export metrics batch code: 404, reason: Not Found in the runtime output: Stop the runtime and restart it with agentcore dev --no-traces. In AgentCore CLI 1.1.0, without the flag, the CLI replaces OTEL_EXPORTER_OTLP_ENDPOINT with the address of its local trace collector, which doesn’t accept metrics. DISABLE_ADOT_OBSERVABILITY=true doesn’t prevent this replacement.
  • Missing tool calls or attributes with a collector: If you send OTLP data through Grafana Alloy or an OpenTelemetry Collector, check that the collector doesn’t sample out spans, drop gen_ai.* attributes, or truncate long attribute values.

Try the examples

The Agent Observability SDK repository has an AgentCore example for each way to record generations. Both examples run the same LangChain service-operations agent with synthetic inventory and order data, and call a Claude model through Amazon Bedrock. Use them to check your Grafana Cloud credentials, or to compare against your own agent.

ExampleRecords generations withRuntime nameAgent name
bedrock-agentcore-otlpOpenTelemetry spansAgentCoreOtlpDemoagentcore-otlp-demo
bedrock-agentcoreThe SDKAgentCoreObsDemoagentcore-operations-demo

In the following steps, replace <EXAMPLE>, <RUNTIME_NAME>, and <AGENT_NAME> with the values from the table. To run an example locally, complete these steps:

  1. Clone the repository and copy the environment template.

    Bash
    git clone https://github.com/grafana/agento11y.git
    cd agento11y/examples/<EXAMPLE>
    cp .env.example agentcore/.env.local
  2. In agentcore/.env.local, set BEDROCK_MODEL_ID to a Claude model ID or inference profile ID that your credentials can invoke, and set BEDROCK_REGION to its AWS Region. Replace the Grafana Cloud placeholders with the values for your stack. Keep the other values from the template.

  3. Build the project, start the local runtime, and leave it running.

    Bash
    agentcore build
    agentcore dev --no-traces
  4. In a second terminal, from the same directory, invoke the agent.

    Bash
    agentcore invoke --runtime <RUNTIME_NAME> --local \
      --payload '{"prompt":"Check inventory for ENV-100 and order DEMO-1007."}'
  5. In Agent Observability, filter conversations by <AGENT_NAME>. Check that the agent called the lookup_inventory and check_order_status tools. Both examples also emit custom metrics with the agentcore_demo prefix.

For deployment and clean-up commands, refer to the ONBOARDING.md file in each example directory.