> ## Documentation Index
> Fetch the complete documentation index at: https://arize-ax.mintlify.site/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Amazon Bedrock Agents JS

> Trace AWS Bedrock Agents invoke_agent runs in TypeScript with OpenInference and send spans to Arize AX for LLM observability.

[Amazon Bedrock Agents](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html) are managed agents you define, prepare, and deploy on AWS. Arize AX captures every Bedrock Agent invocation — the agent's reasoning steps, action-group (tool) calls, knowledge-base lookups, and the underlying LLM calls — via the [`@arizeai/openinference-instrumentation-bedrock-agent-runtime`](https://github.com/Arize-ai/openinference/tree/main/js/packages/openinference-instrumentation-bedrock-agent-runtime) package.

<Note>
  This is the TypeScript / JavaScript guide. For the Python instrumentor, see [Amazon Bedrock Agents](/ax/integrations/llm-providers/amazon-bedrock/amazon-bedrock-agents-tracing).
</Note>

## Prerequisites

* Node.js 18+
* An Arize AX account ([sign up](https://arize.com/sign-up/))
* An AWS account with:
  * [Bedrock model access](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) enabled for the foundation model your agent uses
  * **A deployed Bedrock Agent in the `PREPARED` state, with a callable agent alias.** Create one from the [Bedrock console](https://console.aws.amazon.com/bedrock/home#/agents) or via the `bedrock-agent` (control-plane) API — see [Create an agent](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-create.html). You'll need the **agent ID** (e.g. `WYHKWZQCFM`) and the **agent alias ID** (e.g. `TSTALIASID` for the auto-generated draft, or a custom alias) to invoke it.

## Launch Arize AX

1. Sign in to your [Arize AX account](https://app.arize.com/).
2. From **Space Settings**, copy your **Space ID** and **API Key**. You will set them as `ARIZE_SPACE_ID` and `ARIZE_API_KEY` below.

## Install

```bash theme={null}
npm install @aws-sdk/client-bedrock-agent-runtime \
  @arizeai/openinference-instrumentation-bedrock-agent-runtime \
  @arizeai/openinference-semantic-conventions \
  @opentelemetry/api \
  @opentelemetry/exporter-trace-otlp-proto \
  @opentelemetry/instrumentation \
  @opentelemetry/resources \
  @opentelemetry/sdk-trace-base \
  @opentelemetry/sdk-trace-node \
  @opentelemetry/semantic-conventions
```

## Configure credentials

```bash theme={null}
export ARIZE_SPACE_ID="<your-space-id>"
export ARIZE_API_KEY="<your-api-key>"
export ARIZE_PROJECT_NAME="amazon-bedrock-agents-js-tracing-example"

# AWS credentials — long-lived or SSO/STS temporary.
export AWS_ACCESS_KEY_ID="<your-aws-access-key-id>"
export AWS_SECRET_ACCESS_KEY="<your-aws-secret-access-key>"
export AWS_REGION="us-east-1"
export AWS_SESSION_TOKEN=""  # optional — only for SSO / STS / federated logins

# The Bedrock Agent to invoke. Both must already exist in your AWS
# account and the agent must be in `PREPARED` state.
export BEDROCK_AGENT_ID="<your-agent-id>"
export BEDROCK_AGENT_ALIAS_ID="<your-agent-alias-id>"
```

## Setup tracing

```typescript theme={null}
// instrumentation.ts
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
import { registerInstrumentations } from "@opentelemetry/instrumentation";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";
import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
import {
  SEMRESATTRS_PROJECT_NAME,
} from "@arizeai/openinference-semantic-conventions";
import {
  BedrockAgentInstrumentation,
} from "@arizeai/openinference-instrumentation-bedrock-agent-runtime";

const projectName =
  process.env.ARIZE_PROJECT_NAME ?? "amazon-bedrock-agents-js-tracing-example";

export const provider = new NodeTracerProvider({
  resource: resourceFromAttributes({
    [ATTR_SERVICE_NAME]: projectName,
    [SEMRESATTRS_PROJECT_NAME]: projectName,
  }),
  spanProcessors: [
    new SimpleSpanProcessor(
      new OTLPTraceExporter({
        url: "https://otlp.arize.com/v1/traces",
        headers: {
          "arize-space-id": process.env.ARIZE_SPACE_ID ?? "",
          "arize-api-key": process.env.ARIZE_API_KEY ?? "",
        },
      }),
    ),
  ],
});

provider.register();

registerInstrumentations({
  instrumentations: [new BedrockAgentInstrumentation()],
  tracerProvider: provider,
});

console.log("Arize AX tracing initialized for Amazon Bedrock Agents.");
```

## Run Amazon Bedrock Agents

```typescript theme={null}
// example.ts

// Importing instrumentation first ensures BedrockAgentInstrumentation
// patches the AWS SDK before the bedrock-agent-runtime client is created.
import { provider } from "./instrumentation";

import {
  BedrockAgentRuntimeClient,
  InvokeAgentCommand,
} from "@aws-sdk/client-bedrock-agent-runtime";

// Agents use the `bedrock-agent-runtime` service. The client reads AWS
// credentials and AWS_REGION from the environment.
const client = new BedrockAgentRuntimeClient({
  region: process.env.AWS_REGION ?? "us-east-1",
});

// `enableTrace: true` tells Bedrock to include the agent's internal
// reasoning steps in the response stream — the instrumentor folds those
// into the span tree.
const response = await client.send(
  new InvokeAgentCommand({
    agentId: process.env.BEDROCK_AGENT_ID,
    agentAliasId: process.env.BEDROCK_AGENT_ALIAS_ID,
    sessionId: `arize-example-${Math.floor(Date.now() / 1000)}`,
    inputText: "Why is the ocean salty? Answer in two sentences.",
    enableTrace: true,
  }),
);

// invoke_agent returns a streaming completion — iterate to assemble the
// final answer.
let text = "";
if (response.completion) {
  for await (const event of response.completion) {
    if (event.chunk?.bytes) {
      text += Buffer.from(event.chunk.bytes).toString("utf8");
    }
  }
}
console.log(text);

// Flush any pending spans before the process exits.
await provider.forceFlush();
```

### Expected output

```text wrap theme={null}
Arize AX tracing initialized for Amazon Bedrock Agents.
The ocean is salty because rivers continuously dissolve mineral salts from rocks and soil and carry them to the sea, where they accumulate over millions of years. Water leaves the ocean through evaporation but the salts remain, steadily concentrating until reaching today's roughly 3.5% salinity.
```

## Verify in Arize AX

1. Open your Arize AX space and select project **`amazon-bedrock-agents-js-tracing-example`**.
2. You should see a new trace within \~30 seconds containing a `bedrock.invoke_agent` parent span (AGENT) wrapping per-step orchestration spans, any action-group (TOOL) or knowledge-base (RETRIEVER) spans your agent uses, and an LLM span (with the prompt, response, and token usage attached).
3. If no traces appear, see [Troubleshooting](#troubleshooting).

### Check from the skill, CLI, or SDK

Confirm spans are actually reaching your Arize AX project. Use whichever fits your workflow — the skill and CLI work for any framework; the SDK check is shown for each language.

<Tabs>
  <Tab title="Arize skill (agent)">
    Install the [Arize Skills](https://github.com/Arize-ai/arize-skills) plugin and let your coding agent check for you:

    ```bash theme={null}
    npx skills add Arize-ai/arize-skills
    ```

    Then prompt your agent:

    > Use the `arize-trace` skill to export and analyze recent traces from my project. Confirm spans are arriving, and summarize any errors or latency issues.
  </Tab>

  <Tab title="AX CLI">
    Export recent spans for your project — any rows mean traces are landing:

    ```bash theme={null}
    ax spans export "$ARIZE_PROJECT_NAME" --space "$ARIZE_SPACE_ID" \
      --limit 5 --stdout | jq 'length'
    ```

    A non-zero count confirms spans reached Arize AX. Run `ax auth login` first if you have not authenticated. See the [`ax spans` reference](/api-clients/cli/spans).
  </Tab>

  <Tab title="SDK">
    Query the project's spans and check that at least one came back.

    <CodeGroup>
      ```python Python theme={null}
      import os
      from arize import ArizeClient

      client = ArizeClient(api_key=os.environ["ARIZE_API_KEY"])
      resp = client.spans.list(
          project=os.environ["ARIZE_PROJECT_NAME"],
          space=os.environ["ARIZE_SPACE_ID"],
          limit=5,
      )
      count = len(resp.spans)
      print(
          f"{count} span(s) found" if count else "No spans yet — recheck setup"
      )
      ```

      ```typescript TypeScript theme={null}
      // Reads ARIZE_API_KEY from the environment.
      import { listSpans } from "@arizeai/ax-client";

      const { data: spans } = await listSpans({
        project: process.env.ARIZE_PROJECT_NAME!,
        space: process.env.ARIZE_SPACE_ID!,
        limit: 5,
      });
      const count = spans.length;
      console.log(
        count ? `${count} span(s) found` : "No spans yet — recheck setup",
      );
      ```

      ```go Go theme={null}
      client, err := arize.NewClient(
          arize.Config{APIKey: os.Getenv("ARIZE_API_KEY")},
      )
      if err != nil {
          log.Fatal(err)
      }
      resp, err := client.Spans.List(ctx, spans.ListRequest{
          Project: os.Getenv("ARIZE_PROJECT_NAME"),
          Space:   os.Getenv("ARIZE_SPACE_ID"),
          Limit:   5,
      })
      if err != nil {
          log.Fatal(err)
      }
      fmt.Printf("%d span(s) found\n", len(resp.Spans))
      ```
    </CodeGroup>

    SDK span references: [Python](/api-clients/python/version-8/client-resources/spans) · [TypeScript](/api-clients/typescript/version-1/client-resources/spans) · [Go](/api-clients/go/version-2/client-resources/spans).
  </Tab>
</Tabs>

## Troubleshooting

* **No traces in Arize AX.** Confirm `ARIZE_SPACE_ID` and `ARIZE_API_KEY` are set in the same shell that runs `example.ts`. Enable OpenTelemetry debug logs with `export OTEL_LOG_LEVEL=debug` and re-run.
* **Agent spans missing.** `registerInstrumentations(...)` must run before the `bedrock-agent-runtime` client is created. Make sure `instrumentation.ts` is imported first in your entry point.
* **`ValidationException: Agent <agent_id> is not in PREPARED state`.** A newly-created agent stays in `NOT_PREPARED` until you click **Prepare** in the console (or call `bedrock-agent prepare_agent`) and it finishes building. Agents must be re-prepared after any change to instructions, action groups, or knowledge bases.
* **`ResourceNotFoundException: ... agent alias ...`.** A "draft" agent has no callable alias by default — the auto-generated test alias `TSTALIASID` only works once the agent is prepared. Create an alias via the **Aliases** tab in the Bedrock console or `bedrock-agent create_agent_alias`.
* **`AccessDeniedException`.** Your IAM principal needs `bedrock:InvokeAgent` (different from `bedrock:InvokeModel`) plus model access for the underlying foundation model.
* **Only LLM spans, no agent-reasoning spans.** Make sure `enableTrace: true` is in the `InvokeAgentCommand` — without it, Bedrock returns only the final answer chunks and the instrumentor has no orchestration data to build the span tree.
* **Process exits before spans flush.** Always `await provider.forceFlush()` (or `provider.shutdown()`) before the process exits, otherwise trailing spans are dropped.

## Resources

<CardGroup>
  <Card icon="book-open" href="https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html" title="Amazon Bedrock Agents Documentation" horizontal />

  <Card icon="terminal" href="https://github.com/Arize-ai/openinference/tree/main/js/packages/openinference-instrumentation-bedrock-agent-runtime" title="OpenInference Bedrock Agent Runtime Instrumentor (JavaScript / TypeScript)" horizontal />

  <Card icon="github" href="https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-bedrock-agent-runtime" title="AWS SDK for JavaScript — Bedrock Agent Runtime" horizontal />

  <Card icon="book-open" href="/ax/integrations/llm-providers/amazon-bedrock/amazon-bedrock-agents-tracing" title="Amazon Bedrock Agents (Python) tracing" horizontal />
</CardGroup>
