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

# Getting started with Amazon Bedrock and AgentControl configs

This guide shows how to connect an Amazon Bedrock-powered application to LaunchDarkly AgentControl. Amazon Bedrock provides a single API for multiple foundation models with enterprise-grade AWS integration. By the end, you will be able to manage your model configuration and prompts outside of your application code, and track metrics automatically.

AgentControl supports two modes:

* **Completion mode** returns messages and roles (system, user, assistant). Use it for chat-style interactions and message-oriented workflows. Completion mode supports online evaluations with judges attached in the LaunchDarkly UI.
* **Agent mode** returns a single `instructions` string. Use it when your runtime or framework expects a goal/instructions input for a structured workflow. Agent mode changes the configuration shape from messages to instructions. Your application maps these instructions into your provider or framework's native input.

Both modes support tool calling. This guide walks through completion mode as the main path, with an optional agent config section. To learn more about when to use each mode, read [When to use completion mode vs agent mode](/docs/guides/agentcontrol/agent-vs-completion).

This guide provides examples in both Python and Node.js (TypeScript).

<Tip>
  **New to AgentControl?**

  If you're new to AgentControl, start with the [Quickstart](/docs/home/agentcontrol/quickstart) and return to this guide when you are ready for a more detailed example.

  To learn more about AgentControl-specific SDKs, read [AI SDKs](/docs/sdk/ai). For Python-specific details, read the [Python AI SDK reference](/docs/sdk/ai/python).
</Tip>

## Prerequisites

To complete this guide, you need the following:

* A [LaunchDarkly account](https://app.launchdarkly.com/) with an [SDK key](/docs/home/account/environment/keys#view-or-copy-sdk-credentials) for your environment and a member role that allows [AgentControl actions](/docs/home/account/roles/role-actions#agentcontrol-config-actions). To learn more about LaunchDarkly roles, read [Roles](/docs/home/account/roles).
* An AWS account with Amazon Bedrock access enabled and model access granted for the models you want to use. To learn more, read [Model access](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) in the AWS documentation.
* AWS credentials with the `bedrock-runtime:Converse` permission.
* A development environment:
  * **Python**: Python 3.10 or higher
  * **Node.js**: Node.js 20 or higher
* Familiarity with LaunchDarkly contexts. To learn more, read [Contexts and segments](/docs/home/flags/contexts).

## Concepts

Before you begin, review these key concepts.

### AgentControl configs

An AgentControl config is a LaunchDarkly resource that controls how your application uses large language models. Each AgentControl config contains one or more variations. Each variation specifies:

* A model configuration, including the model name and parameters
* Messages that define the prompt

You can update these settings in LaunchDarkly at any time without changing your application code.

### Contexts

A context represents the end user interacting with your application. LaunchDarkly uses context attributes to:

* Determine which variation to serve based on targeting rules
* Populate `{{ ldctx.* }}` placeholders in your prompts with context attribute values

Other placeholders, such as `{{ topic }}`, are populated from the `variables` argument you pass at runtime.

### The tracker

When you retrieve an AgentControl config, call `createTracker()` (Node.js) or `create_tracker()` (Python) on the returned object to mint a tracker. The tracker records metrics from your Bedrock calls, including:

* Generation count
* Input and output tokens
* Latency
* Success and error rates

These metrics appear on the **AI Insights** dashboard in LaunchDarkly.

## Step 1: Install the SDK

Install the LaunchDarkly AI SDK and the AWS Bedrock SDK in your application. AgentControl is supported by LaunchDarkly server-side SDKs only. The Node.js examples in this guide use the [server-side Node.js AI SDK](https://github.com/launchdarkly/js-core/tree/main/packages/sdk/server-ai).

Here is how to install the required packages:

<CodeGroup>
  ```bash title="Python" lines wrap theme={null}
  pip install "launchdarkly-server-sdk-ai>=0.20.0"
  pip install "boto3>=1.34.0"
  pip install "python-dotenv>=1.0.0"
  ```

  ```bash title="Node.js" lines wrap theme={null}
  npm install @launchdarkly/node-server-sdk
  npm install "@launchdarkly/server-sdk-ai@^0.20.0"
  npm install @aws-sdk/client-bedrock-runtime
  npm install dotenv
  ```
</CodeGroup>

Create a `.env` file in your project root to store your credentials:

```bash lines wrap theme={null}
# .env
LAUNCHDARKLY_SDK_KEY_BEDROCK=<your-launchdarkly-sdk-key>
AWS_REGION=<your-aws-region>
AWS_ACCESS_KEY_ID=<your-aws-access-key-id>
AWS_SECRET_ACCESS_KEY=<your-aws-secret-access-key>
```

Add `.env` to your `.gitignore` to keep credentials out of version control.

## Step 2: Initialize the clients

Initialize both the LaunchDarkly client and the Amazon Bedrock runtime client. Store your credentials in environment variables.

Here is the initialization code:

<CodeGroup>
  ```python title="Python" expandable lines wrap theme={null}
  import os
  import boto3
  import ldclient
  from ldclient import Context
  from ldclient.config import Config
  from ldai import LDAIClient, AICompletionConfigDefault, AIAgentConfigDefault
  from dotenv import load_dotenv

  load_dotenv()

  SDK_KEY = os.environ.get("LAUNCHDARKLY_SDK_KEY")
  CONFIG_KEY = "bedrock-assistant"
  AGENT_CONFIG_KEY = "bedrock-agent"

  bedrock_client = boto3.client(
      'bedrock-runtime',
      region_name=os.environ.get('AWS_REGION', 'us-west-2'),
  )
  ldclient.set_config(Config(SDK_KEY))
  if not ldclient.get().is_initialized():
      exit(1)

  ai_client = LDAIClient(ldclient.get())
  ```

  ```typescript title="Node.js (TypeScript)" expandable lines wrap theme={null}
  import dotenv from 'dotenv';
  dotenv.config();
  import { init, LDClient, LDContext } from '@launchdarkly/node-server-sdk';
  import { initAi, type LDAIClient, type LDAICompletionConfig, type LDAIAgentConfig } from '@launchdarkly/server-sdk-ai';
  import {
    BedrockRuntimeClient,
    ConverseCommand,
    type Message,
    type SystemContentBlock,
    type Tool,
  } from '@aws-sdk/client-bedrock-runtime';

  const SDK_KEY = process.env.LAUNCHDARKLY_SDK_KEY as string;
  const CONFIG_KEY = 'bedrock-assistant';
  const AGENT_CONFIG_KEY = 'bedrock-agent';

  const bedrockClient = new BedrockRuntimeClient({
    region: process.env.AWS_REGION || 'us-west-2',
  });
  const ldClient: LDClient = init(SDK_KEY);
  await ldClient.waitForInitialization({ timeout: 10 });

  const aiClient: LDAIClient = initAi(ldClient);
  ```
</CodeGroup>

## Step 3: Create an AgentControl config in LaunchDarkly

Create an AgentControl config in the LaunchDarkly UI to store your Bedrock model settings and prompts.

<Tip>
  **Using the MCP server or agent skills**

  If you have the [LaunchDarkly MCP server](https://github.com/launchdarkly/mcp-server) or [agent skills](https://github.com/launchdarkly/agent-skills) configured, prompt your coding assistant to create the AgentControl config for you. For example:

  "Create a completion mode AgentControl config called 'Bedrock assistant' with a 'Claude Sonnet 4' variation using the us.anthropic.claude-sonnet-4-20250514-v1:0 Bedrock model, temperature 0.7, max\_tokens 1024, and the system message: 'You are a helpful assistant. Answer questions about \{\{topic}}.' Enable targeting."
</Tip>

To create the AgentControl config:

1. In the left sidebar, click **Create** and select **Config**.
2. In the "Create config" dialog, select **Completion**.
3. Enter a name, such as "Bedrock assistant".
4. Click **Create**.

<Frame caption="The &#x22;Create&#x22; menu options.">
  <img src="https://mintcdn.com/launchdarkly/-b7nPh0oyigf6iW7/images/auto/create-menu.auto.png?fit=max&auto=format&n=-b7nPh0oyigf6iW7&q=85&s=5b3fe40c4dd161b2972de2334ff19c0a" alt="The &#x22;Create&#x22; menu options." width="1180" height="440" data-path="images/auto/create-menu.auto.png" />
</Frame>

To create a variation:

1. On the **Variations** tab, replace "Untitled variation" with a name, such as "Claude Sonnet 4".
2. Click **Select a model** and choose an Amazon Bedrock model such as `us.anthropic.claude-sonnet-4-20250514-v1:0`.
3. Click **Parameters** and set `temperature` to `0.7` and `max_tokens` to `1024`.
4. Add a **system** message to define your assistant's behavior:

<CodeGroup>
  ```text title="System message" lines wrap theme={null}
  You are a helpful assistant. Answer questions about {{topic}}.
  ```
</CodeGroup>

5. Click **Review and save**.

<Frame caption="A completed variation with model configuration and system message.">
  <img src="https://mintcdn.com/launchdarkly/-b7nPh0oyigf6iW7/images/auto/ai-config-variation-complete.auto.png?fit=max&auto=format&n=-b7nPh0oyigf6iW7&q=85&s=e6b80ed68d6edb05d7f31ee72e6b4974" alt="A completed variation with model configuration and system message." width="2070" height="638" data-path="images/auto/ai-config-variation-complete.auto.png" />
</Frame>

To enable targeting:

1. Select the **Targeting** tab.
2. In the "Default rule" section, click **Edit**.
3. Set the default rule to serve your variation.
4. Click **Review and save**.

<Frame caption="The default targeting rule configured to serve a variation.">
  <img src="https://mintcdn.com/launchdarkly/hutarVphEq2dY_zb/images/auto/guide-ai-config-model-config-update-default-targeting-rule.auto.png?fit=max&auto=format&n=hutarVphEq2dY_zb&q=85&s=b92bcc5a507600be0fd944fbd203113e" alt="The default targeting rule configured to serve a variation." width="2074" height="1138" data-path="images/auto/guide-ai-config-model-config-update-default-targeting-rule.auto.png" />
</Frame>

## Step 4: Get the AgentControl config in your application

Retrieve the AgentControl config from LaunchDarkly by calling the completion config function. Pass a context that represents the current user. You can also pass an optional fallback configuration that the SDK uses when LaunchDarkly is unreachable.

Here is how to get the AgentControl config:

<CodeGroup>
  ```python title="Python" expandable lines wrap theme={null}
  # Define the context for the current user
  context = Context.builder("user-123") \
      .kind("user") \
      .name("Sandy") \
      .build()

  # Pass a default for improved resiliency when the AgentControl config is unavailable
  # or LaunchDarkly is unreachable; omit for a disabled default.
  # Example:
  #   from ldai import AICompletionConfigDefault
  #   default = AICompletionConfigDefault(
  #       enabled=True,
  #       model={"name": "us.anthropic.claude-sonnet-4-20250514-v1:0"},
  #       provider={"name": "bedrock"},
  #       messages=[{"role": "system", "content": "You are a helpful assistant."}],
  #   )
  #   config = ai_client.completion_config(CONFIG_KEY, context, default, variables={"topic": "Python"})

  # Get the AgentControl config
  config = ai_client.completion_config(CONFIG_KEY, context, variables={"topic": "Python"})
  tracker = config.create_tracker()
  ```

  ```typescript title="Node.js (TypeScript)" expandable lines wrap theme={null}
  // Define the context for the current user
  const context: LDContext = {
    kind: 'user',
    key: 'user-123',
    name: 'Sandy',
  };

  // Pass a default for improved resiliency when the AgentControl config is unavailable
  // or LaunchDarkly is unreachable; omit for a disabled default.
  // Example:
  //   const fallback: LDAICompletionConfigDefault = {
  //     enabled: true,
  //     model: { name: 'us.anthropic.claude-sonnet-4-20250514-v1:0' },
  //     provider: { name: 'bedrock' },
  //     messages: [{ role: 'system', content: 'You are a helpful assistant.' }],
  //   };
  //   const aiConfig = await aiClient.completionConfig(CONFIG_KEY, context, fallback, { topic: 'Python' });

  // Get the AgentControl config
  const aiConfig: LDAICompletionConfig = await aiClient.completionConfig(
    CONFIG_KEY,
    context,
    undefined,
    { topic: 'Python' }
  );
  ```
</CodeGroup>

The SDK uses the fallback configuration when LaunchDarkly is unreachable. Check the `enabled` property and handle the disabled case in your application.

<Note>
  **Best practices**

  For production use:

  * Retrieve the AgentControl config each time you generate content so LaunchDarkly can evaluate the latest targeting rules and prompt changes.
  * Provide a fallback configuration when possible so your application can fail gracefully if LaunchDarkly is unavailable.
  * Avoid sending personally identifiable information in contexts unless you have a specific need and an approved handling pattern. To learn more, read [Privacy in AgentControl](/docs/home/agentcontrol/privacy).
</Note>

## Step 5: Call Bedrock and track metrics

The Amazon Bedrock Converse API expects a specific format. System messages go in a top-level `system` list, user and assistant messages go in the `messages` array with nested content blocks, and model parameters go in `inferenceConfig`. The tracker's `track_bedrock_converse_metrics` helper records latency, success, errors, and token usage directly from the Converse response.

Define a helper to filter AgentControl config parameters to Bedrock's `inferenceConfig` shape. Bedrock's Converse API accepts `maxTokens`, `temperature`, `topP`, and `stopSequences`. Rename LaunchDarkly's `max_tokens` key to `maxTokens`; the rest already match.

<CodeGroup>
  ```python title="Python" lines wrap theme={null}
  def inference_config_from_params(params):
      """Map AgentControl config parameters to Bedrock's Converse inferenceConfig shape.
      Rename max_tokens to maxTokens; keep temperature, topP, stopSequences as-is."""
      mapping = {"max_tokens": "maxTokens"}
      allowed = {"maxTokens", "temperature", "topP", "stopSequences"}
      renamed = {mapping.get(k, k): v for k, v in (params or {}).items()}
      return {k: v for k, v in renamed.items() if k in allowed}
  ```

  ```typescript title="Node.js (TypeScript)" lines wrap theme={null}
  function inferenceConfigFromParams(params: Record<string, unknown>): Record<string, number | string[]> {
    const mapping: Record<string, string> = { max_tokens: 'maxTokens' };
    const allowed = new Set(['maxTokens', 'temperature', 'topP', 'stopSequences']);
    const renamed = Object.fromEntries(
      Object.entries(params || {}).map(([k, v]) => [mapping[k] ?? k, v]),
    );
    return Object.fromEntries(Object.entries(renamed).filter(([k]) => allowed.has(k))) as any;
  }
  ```
</CodeGroup>

Then call Bedrock with the config and pass the response to the tracker:

<CodeGroup>
  ```python title="Python" expandable lines wrap theme={null}
  if config.enabled:
      tracker = config.create_tracker()
      messages = config.messages or []

      # Bedrock Converse: system messages are a top-level list, not a role
      system_messages = [{'text': m.content} for m in messages if m.role == 'system']
      conversation = [
          {'role': m.role, 'content': [{'text': m.content}]}
          for m in messages if m.role in ('user', 'assistant')
      ]
      conversation.append({
          'role': 'user',
          'content': [{'text': 'How do I read a file in Python?'}]
      })

      converse_params = {
          'modelId': config.model.name,
          'messages': conversation,
      }
      if system_messages:
          converse_params['system'] = system_messages
      ld_params = (config.model.to_dict().get("parameters") if config.model else None) or {}
      inference = inference_config_from_params(ld_params)
      if inference:
          converse_params['inferenceConfig'] = inference

      response = tracker.track_bedrock_converse_metrics(
          bedrock_client.converse(**converse_params)
      )
  ```

  ```typescript title="Node.js (TypeScript)" expandable lines wrap theme={null}
  if (aiConfig.enabled) {
    const tracker = aiConfig.createTracker();
    const messages = aiConfig.messages || [];

    const conversation: Message[] = [];
    const systemMessages: SystemContentBlock[] = [];
    for (const msg of messages) {
      if (msg.role === 'system') {
        systemMessages.push({ text: msg.content });
      } else if (msg.role === 'user' || msg.role === 'assistant') {
        conversation.push({ role: msg.role, content: [{ text: msg.content }] });
      }
    }

    conversation.push({
      role: 'user',
      content: [{ text: 'How do I read a file in Python?' }],
    });

    const inferenceConfig = inferenceConfigFromParams((aiConfig.model?.parameters || {}) as Record<string, unknown>);

    const response = await bedrockClient.send(
      new ConverseCommand({
        modelId: aiConfig.model!.name,
        messages: conversation,
        system: systemMessages.length ? systemMessages : undefined,
        inferenceConfig: Object.keys(inferenceConfig).length ? inferenceConfig : undefined,
      })
    );

    tracker.trackBedrockConverseMetrics(response);
  }
  ```
</CodeGroup>

## Step 6: Optional: Use agent mode with tool calling

Agent-mode AgentControl configs return a single `instructions` string instead of a message list, and they let you attach reusable tools from the LaunchDarkly tools library. With Bedrock's Converse API, the instructions map to a `system` content block and tools pass through on the `toolConfig` parameter.

### Create the tool in the tools library

First, define the tool in LaunchDarkly so the AgentControl config variation can reference it:

1. In the left sidebar, click **Library**, then select the **Tools** tab.
2. Click **Add tool**.
3. Enter `get_order_status` as the **Key**.
4. Enter "Look up the status of a customer order by order ID" as the **Description**.
5. Define the schema using the JSON editor:

```json lines wrap theme={null}
{
  "type": "object",
  "properties": {
    "order_id": {
      "type": "string",
      "description": "The order ID to look up"
    }
  },
  "required": ["order_id"]
}
```

6. Click **Save**.

<Frame caption="The Create tool dialog.">
  <img src="https://mintcdn.com/launchdarkly/WYiCaDy82H6mz_dK/images/auto/ai-configs-create-tool.auto.png?fit=max&auto=format&n=WYiCaDy82H6mz_dK&q=85&s=958a8759bedffa7e426d66ae51dbd998" alt="The Create tool dialog." width="1240" height="1468" data-path="images/auto/ai-configs-create-tool.auto.png" />
</Frame>

### Create the agent AgentControl config

1. Click **Create** and select **Config**.
2. Select **Agent** mode.

<Frame caption="The Create AgentControl config dialog with Agent mode selected.">
  <img src="https://mintcdn.com/launchdarkly/WYiCaDy82H6mz_dK/images/auto/agentcontrol-snippet-create-agent.auto.png?fit=max&auto=format&n=WYiCaDy82H6mz_dK&q=85&s=0132e925414611e4468858bce6392568" alt="The Create AgentControl config dialog with Agent mode selected." width="920" height="984" data-path="images/auto/agentcontrol-snippet-create-agent.auto.png" />
</Frame>

3. Enter a name:

<CodeGroup>
  ```text title="AgentControl config name" lines wrap theme={null}
  Bedrock agent
  ```
</CodeGroup>

4. Click **Create**.
5. On the **Variations** tab, name the variation (for example, "Claude Sonnet 4 agent").
6. Click **Select a model** and choose an Amazon Bedrock model such as `us.anthropic.claude-sonnet-4-20250514-v1:0`.
7. Click **Parameters** and set `max_tokens` to `1024`.
8. Add the agent **instructions**:

<CodeGroup>
  ```text title="Agent instructions" lines wrap theme={null}
  You are an order status assistant. Use the get_order_status tool to look up customer orders by ID. Only call the tool when the user asks about an order.
  ```
</CodeGroup>

9. Click **+ Attach tools** and select `get_order_status`.

<Frame caption="A variation editor with an attached tool.">
  <img src="https://mintcdn.com/launchdarkly/-b7nPh0oyigf6iW7/images/auto/ai-configs-variations-with-tool.auto.png?fit=max&auto=format&n=-b7nPh0oyigf6iW7&q=85&s=60dba16f862a59385da8b203cfcf7d21" alt="A variation editor with an attached tool." width="1980" height="868" data-path="images/auto/ai-configs-variations-with-tool.auto.png" />
</Frame>

10. Click **Review and save**.
11. On the **Targeting** tab, set the default rule to serve your variation and save.

To learn more about managing tools, read [Tools in AgentControl](/docs/home/agentcontrol/tools).

### Retrieve the agent config and run the tool loop

Use `agent_config()` instead of `completion_config()`. The SDK returns attached tools under `parameters.tools` in OpenAI's `type=function` shape, so convert them to Bedrock Converse's `{toolSpec: {name, description, inputSchema: {json}}}` shape and pass them on the `toolConfig` parameter. Tool handler functions stay in your application code: LaunchDarkly stores the schema, your application owns the behavior.

<CodeGroup>
  ```python title="Python" expandable lines wrap theme={null}
  agent = ai_client.agent_config(
      AGENT_CONFIG_KEY,
      context,
      AIAgentConfigDefault(enabled=False),
  )

  if agent.enabled:
      tracker = agent.create_tracker()
      ld_params = (agent.model.to_dict().get("parameters") if agent.model else None) or {}
      inference = inference_config_from_params(ld_params)

      # LaunchDarkly returns attached tools under parameters.tools in OpenAI type=function shape.
      # Bedrock Converse wants {toolSpec: {name, description, inputSchema: {json}}}.
      ld_tools = ld_params.get("tools", []) or []
      tool_config = {
          "tools": [
              {
                  "toolSpec": {
                      "name": t["name"],
                      "description": t.get("description", ""),
                      "inputSchema": {"json": t.get("parameters", {"type": "object", "properties": {}})},
                  }
              }
              for t in ld_tools
          ]
      }

      # Handlers stay in application code — LaunchDarkly governs the schema, the app owns execution.
      def get_order_status(order_id: str) -> str:
          orders = {
              "ORD-123": "Shipped — arrives Thursday",
              "ORD-456": "Processing — estimated ship date: tomorrow",
              "ORD-789": "Delivered on Monday",
          }
          return orders.get(order_id, f"No order found with ID {order_id}")

      tool_handlers = {"get_order_status": get_order_status}

      conversation = [{"role": "user", "content": [{"text": "What's the status of order ORD-123?"}]}]

      # Agent loop: call Bedrock, handle toolUse blocks, repeat
      MAX_STEPS = 5
      for _ in range(MAX_STEPS):
          converse_params = {
              "modelId": agent.model.name,
              "messages": conversation,
              "system": [{"text": agent.instructions}],
              "toolConfig": tool_config,
          }
          if inference:
              converse_params["inferenceConfig"] = inference

          response = tracker.track_bedrock_converse_metrics(
              bedrock_client.converse(**converse_params)
          )

          output_message = response.get("output", {}).get("message", {})
          stop_reason = response.get("stopReason")

          if stop_reason != "tool_use":
              break

          # Append assistant turn (preserves toolUse blocks)
          conversation.append(output_message)

          # Build a single tool-result user turn covering every toolUse block
          tool_results = []
          for block in output_message.get("content", []):
              if "toolUse" not in block:
                  continue
              tool_use = block["toolUse"]
              if tool_use["name"] not in tool_handlers:
                  raise ValueError(f"Unknown tool: {tool_use['name']}")
              result = tool_handlers[tool_use["name"]](**tool_use["input"])
              tracker.track_tool_call(tool_use["name"])
              tool_results.append({
                  "toolResult": {
                      "toolUseId": tool_use["toolUseId"],
                      "content": [{"text": result}],
                  }
              })
          conversation.append({"role": "user", "content": tool_results})
  ```

  ```typescript title="Node.js (TypeScript)" expandable lines wrap theme={null}
  const agentFallback = { enabled: false };
  const agentConfig: LDAIAgentConfig = await aiClient.agentConfig(
    AGENT_CONFIG_KEY,
    context,
    agentFallback,
  );

  if (agentConfig.enabled && agentConfig.instructions) {
    const tracker = agentConfig.createTracker();
    const ldParams = (agentConfig.model?.parameters || {}) as Record<string, unknown>;
    const inferenceConfig = inferenceConfigFromParams(ldParams);

    // LaunchDarkly returns attached tools under parameters.tools in OpenAI type=function shape.
    // Bedrock Converse wants { toolSpec: { name, description, inputSchema: { json } } }.
    const ldTools = (ldParams.tools as any[] | undefined) ?? [];
    const tools: Tool[] = ldTools.map((t) => ({
      toolSpec: {
        name: t.name as string,
        description: (t.description as string) ?? '',
        inputSchema: { json: (t.parameters as any) ?? { type: 'object', properties: {} } },
      },
    }));

    // Handlers stay in application code — LaunchDarkly governs the schema, the app owns execution.
    function getOrderStatus(orderId: string): string {
      const orders: Record<string, string> = {
        'ORD-123': 'Shipped — arrives Thursday',
        'ORD-456': 'Processing — estimated ship date: tomorrow',
        'ORD-789': 'Delivered on Monday',
      };
      return orders[orderId] || `No order found with ID ${orderId}`;
    }

    const toolHandlers: Record<string, (args: any) => string> = {
      get_order_status: (args) => getOrderStatus(args.order_id),
    };

    const conversation: Message[] = [
      { role: 'user', content: [{ text: "What's the status of order ORD-123?" }] },
    ];

    // Agent loop: call Bedrock, handle toolUse blocks, repeat
    const MAX_STEPS = 5;
    for (let i = 0; i < MAX_STEPS; i++) {
      const response = await bedrockClient.send(
        new ConverseCommand({
          modelId: agentConfig.model!.name,
          messages: conversation,
          system: [{ text: agentConfig.instructions }],
          toolConfig: { tools },
          inferenceConfig: Object.keys(inferenceConfig).length ? inferenceConfig : undefined,
        })
      );

      tracker.trackBedrockConverseMetrics(response);

      const outputMessage = response.output?.message;
      if (response.stopReason !== 'tool_use') {
        break;
      }

      // Append assistant turn (preserves toolUse blocks)
      if (outputMessage) conversation.push(outputMessage);

      // Build a single tool-result user turn covering every toolUse block
      const toolResults: any[] = [];
      for (const block of outputMessage?.content || []) {
        if (!('toolUse' in block) || !block.toolUse) continue;
        const { name, input, toolUseId } = block.toolUse;
        const handler = toolHandlers[name!];

        if (!handler) throw new Error(`Unknown tool: ${name}`);
        const result = handler(input);
        toolResults.push({
          toolResult: { toolUseId, content: [{ text: result }] },
        });
      }
      conversation.push({ role: 'user', content: toolResults });
    }
  }
  ```
</CodeGroup>

In completion mode, you can attach judges to variations in the LaunchDarkly UI for automatic evaluation. In agent mode, invoke judges programmatically through the AI SDK.

To learn more, read [When to use completion mode vs agent mode](/docs/guides/agentcontrol/agent-vs-completion) and [Agents in AgentControl](/docs/home/agentcontrol/agents).

## Step 7: Monitor your AgentControl config

Use the LaunchDarkly UI to monitor how your applications are performing across all AgentControl configs and for individual configs.

To view aggregated metrics across all your AgentControl configs, navigate to **Insights** in the left sidebar under the **AI** section. The Insights overview page displays cost, latency, error rate, invocation counts, and model distribution across your organization. To learn more, read [AI Insights](/docs/home/agentcontrol/insights).

To view metrics for a specific AgentControl config:

1. Navigate to your AgentControl config.
2. Select the **Monitoring** tab.

The dashboard displays the following metrics:

* **Generation count**: The total number of AI generation calls tracked for this config.
* **Input and output tokens**: Token consumption broken down by prompt tokens sent and completion tokens received.
* **Latency**: The time taken for each generation call, shown as percentiles (p50, p95).
* **Success and error rates**: The proportion of successful versus failed generation calls.

Metrics update approximately every minute. Use these metrics to compare variations and optimize your prompts. To learn more, read [Monitor AgentControl configs](/docs/home/agentcontrol/monitor).

<Frame caption="The Insights overview page showing cost, latency, error rate, and invocation metrics for a Bedrock AgentControl config.">
  <img src="https://mintcdn.com/launchdarkly/Y_qcqLWSC5ccm6eB/images/__LD_UI_no_test/guide-ai-config-bedrock-insights.png?fit=max&auto=format&n=Y_qcqLWSC5ccm6eB&q=85&s=903468b897684ef9ef3f8a5c57670527" alt="The Insights overview page showing cost, latency, error rate, and invocation metrics for a Bedrock AgentControl config." width="3299" height="1475" data-path="images/__LD_UI_no_test/guide-ai-config-bedrock-insights.png" />
</Frame>

<Tip>
  **Observability**

  The AI SDKs emit OpenTelemetry-compatible spans for each generation call. You can forward these spans to your existing observability stack for deeper analysis. To learn more, read [Observability](/docs/home/observability) and [LLM observability](/docs/home/observability/llm-observability).
</Tip>

## Step 8: Close the client

Close the LaunchDarkly client when your application shuts down to flush pending events.

Here is how to close the client:

<CodeGroup>
  ```python title="Python" lines wrap theme={null}
  ldclient.get().flush()
  ldclient.get().close()
  ```

  ```typescript title="Node.js (TypeScript)" lines wrap theme={null}
  await ldClient.flush();
  await ldClient.close();
  ```
</CodeGroup>

For short-lived applications such as scripts, explicitly flush events before closing.

Here is how to flush events:

<CodeGroup>
  ```python title="Python" lines wrap theme={null}
  ldclient.get().flush()
  ldclient.get().close()
  ```

  ```typescript title="Node.js (TypeScript)" lines wrap theme={null}
  await ldClient.flush();
  await ldClient.close();
  ```
</CodeGroup>

## Complete example

Here is a complete working example that combines all the steps.

<Accordion title="Click to expand full example code">
  <CodeGroup>
    ```python title="Python" expandable lines wrap theme={null}
    import os
    import boto3
    import ldclient
    from ldclient import Context
    from ldclient.config import Config
    from ldai import LDAIClient, AICompletionConfigDefault, AIAgentConfigDefault
    from dotenv import load_dotenv

    load_dotenv()

    SDK_KEY = os.environ.get("LAUNCHDARKLY_SDK_KEY_BEDROCK")

    CONFIG_KEY = "bedrock-assistant"
    AGENT_CONFIG_KEY = "bedrock-agent"


    def inference_config_from_params(params):
        """Map AgentControl config parameters to Bedrock's Converse inferenceConfig shape.
        Rename max_tokens to maxTokens; keep temperature, topP, stopSequences as-is."""
        mapping = {"max_tokens": "maxTokens"}
        allowed = {"maxTokens", "temperature", "topP", "stopSequences"}
        renamed = {mapping.get(k, k): v for k, v in (params or {}).items()}
        return {k: v for k, v in renamed.items() if k in allowed}


    def main():
        ldclient.set_config(Config(SDK_KEY))
        if not ldclient.get().is_initialized():
            return

        ai_client = LDAIClient(ldclient.get())

        bedrock_client = boto3.client(
            'bedrock-runtime',
            region_name=os.environ.get('AWS_REGION', 'us-west-2'),
        )

        context = Context.builder("user-123").kind("user").name("Sandy").build()

        # ===================
        # COMPLETION MODE
        # ===================
        # Pass a default for improved resiliency when the AgentControl config is unavailable
        # or LaunchDarkly is unreachable; omit for a disabled default.
        # Example:
        #   default = AICompletionConfigDefault(
        #       enabled=True,
        #       model={"name": "us.anthropic.claude-sonnet-4-20250514-v1:0"},
        #       provider={"name": "bedrock"},
        #       messages=[{"role": "system", "content": "You are a helpful assistant."}],
        #   )
        #   config = ai_client.completion_config(CONFIG_KEY, context, default, variables={"topic": "Python"})
        config = ai_client.completion_config(CONFIG_KEY, context, variables={"topic": "Python"})

        if config.enabled:
            tracker = config.create_tracker()
            messages = config.messages or []

            # Bedrock Converse: system messages are a top-level list, not a role
            system_messages = [{'text': m.content} for m in messages if m.role == 'system']
            conversation = [
                {'role': m.role, 'content': [{'text': m.content}]}
                for m in messages if m.role in ('user', 'assistant')
            ]
            conversation.append({
                'role': 'user',
                'content': [{'text': 'How do I read a file in Python?'}]
            })

            converse_params = {
                'modelId': config.model.name,
                'messages': conversation,
            }
            if system_messages:
                converse_params['system'] = system_messages
            ld_params = (config.model.to_dict().get("parameters") if config.model else None) or {}
            inference = inference_config_from_params(ld_params)
            if inference:
                converse_params['inferenceConfig'] = inference

            tracker.track_bedrock_converse_metrics(
                bedrock_client.converse(**converse_params)
            )

        # ===================
        # AGENT MODE
        # ===================
        agent = ai_client.agent_config(
            AGENT_CONFIG_KEY,
            context,
            AIAgentConfigDefault(enabled=False),
        )

        if agent.enabled:
            tracker = agent.create_tracker()
            ld_params = (agent.model.to_dict().get("parameters") if agent.model else None) or {}
            inference = inference_config_from_params(ld_params)

            # LaunchDarkly returns attached tools under parameters.tools in OpenAI type=function shape.
            # Bedrock Converse wants {toolSpec: {name, description, inputSchema: {json}}}.
            ld_tools = ld_params.get("tools", []) or []
            tool_config = {
                "tools": [
                    {
                        "toolSpec": {
                            "name": t["name"],
                            "description": t.get("description", ""),
                            "inputSchema": {"json": t.get("parameters", {"type": "object", "properties": {}})},
                        }
                    }
                    for t in ld_tools
                ]
            }

            # Handlers stay in application code — LaunchDarkly governs the schema, the app owns execution.
            def get_order_status(order_id: str) -> str:
                orders = {
                    "ORD-123": "Shipped — arrives Thursday",
                    "ORD-456": "Processing — estimated ship date: tomorrow",
                    "ORD-789": "Delivered on Monday",
                }
                return orders.get(order_id, f"No order found with ID {order_id}")

            tool_handlers = {"get_order_status": get_order_status}

            conversation = [{"role": "user", "content": [{"text": "What's the status of order ORD-123?"}]}]

            # Agent loop: call Bedrock, handle toolUse blocks, repeat
            MAX_STEPS = 5
            for _ in range(MAX_STEPS):
                converse_params = {
                    "modelId": agent.model.name,
                    "messages": conversation,
                    "system": [{"text": agent.instructions}],
                    "toolConfig": tool_config,
                }
                if inference:
                    converse_params["inferenceConfig"] = inference

                response = tracker.track_bedrock_converse_metrics(
                    bedrock_client.converse(**converse_params)
                )

                output_message = response.get("output", {}).get("message", {})
                stop_reason = response.get("stopReason")

                if stop_reason != "tool_use":
                    break

                # Append assistant turn (preserves toolUse blocks)
                conversation.append(output_message)

                # Build a single tool-result user turn covering every toolUse block
                tool_results = []
                for block in output_message.get("content", []):
                    if "toolUse" not in block:
                        continue
                    tool_use = block["toolUse"]
                    if tool_use["name"] not in tool_handlers:
                        raise ValueError(f"Unknown tool: {tool_use['name']}")
                    result = tool_handlers[tool_use["name"]](**tool_use["input"])
                    tracker.track_tool_call(tool_use["name"])
                    tool_results.append({
                        "toolResult": {
                            "toolUseId": tool_use["toolUseId"],
                            "content": [{"text": result}],
                        }
                    })
                conversation.append({"role": "user", "content": tool_results})

        ldclient.get().flush()
        ldclient.get().close()


    if __name__ == "__main__":
        main()
    ```

    ```typescript title="Node.js (TypeScript)" expandable lines wrap theme={null}
    import dotenv from 'dotenv';
    dotenv.config();
    import { init, LDClient, LDContext } from '@launchdarkly/node-server-sdk';
    import { initAi, type LDAIClient, type LDAICompletionConfig, type LDAIAgentConfig } from '@launchdarkly/server-sdk-ai';
    import {
      BedrockRuntimeClient,
      ConverseCommand,
      type Message,
      type SystemContentBlock,
      type Tool,
    } from '@aws-sdk/client-bedrock-runtime';

    const SDK_KEY = process.env.LAUNCHDARKLY_SDK_KEY_BEDROCK as string;
    const CONFIG_KEY = 'bedrock-assistant';
    const AGENT_CONFIG_KEY = 'bedrock-agent';

    function inferenceConfigFromParams(params: Record<string, unknown>): Record<string, number | string[]> {
      const mapping: Record<string, string> = { max_tokens: 'maxTokens' };
      const allowed = new Set(['maxTokens', 'temperature', 'topP', 'stopSequences']);
      const renamed = Object.fromEntries(
        Object.entries(params || {}).map(([k, v]) => [mapping[k] ?? k, v]),
      );
      return Object.fromEntries(Object.entries(renamed).filter(([k]) => allowed.has(k))) as any;
    }

    async function main() {
      const bedrockClient = new BedrockRuntimeClient({
        region: process.env.AWS_REGION || 'us-west-2',
      });

      const ldClient: LDClient = init(SDK_KEY);
      await ldClient.waitForInitialization({ timeout: 10 });

      const aiClient: LDAIClient = initAi(ldClient);

      const context: LDContext = {
        kind: 'user',
        key: 'user-123',
        name: 'Sandy',
      };

      // ===================
      // COMPLETION MODE
      // ===================
      // Pass a default for improved resiliency when the AgentControl config is unavailable
      // or LaunchDarkly is unreachable; omit for a disabled default.
      // Example:
      //   const fallback: LDAICompletionConfigDefault = {
      //     enabled: true,
      //     model: { name: 'us.anthropic.claude-sonnet-4-20250514-v1:0' },
      //     provider: { name: 'bedrock' },
      //     messages: [{ role: 'system', content: 'You are a helpful assistant.' }],
      //   };
      //   const aiConfig = await aiClient.completionConfig(CONFIG_KEY, context, fallback, { topic: 'Python' });
      const aiConfig: LDAICompletionConfig = await aiClient.completionConfig(
        CONFIG_KEY,
        context,
        undefined,
        { topic: 'Python' }
      );

      if (aiConfig.enabled) {
        const tracker = aiConfig.createTracker();
        const messages = aiConfig.messages || [];

        const conversation: Message[] = [];
        const systemMessages: SystemContentBlock[] = [];
        for (const msg of messages) {
          if (msg.role === 'system') {
            systemMessages.push({ text: msg.content });
          } else if (msg.role === 'user' || msg.role === 'assistant') {
            conversation.push({ role: msg.role, content: [{ text: msg.content }] });
          }
        }

        conversation.push({
          role: 'user',
          content: [{ text: 'How do I read a file in Python?' }],
        });

        const inferenceConfig = inferenceConfigFromParams((aiConfig.model?.parameters || {}) as Record<string, unknown>);

        const response = await bedrockClient.send(
          new ConverseCommand({
            modelId: aiConfig.model!.name,
            messages: conversation,
            system: systemMessages.length ? systemMessages : undefined,
            inferenceConfig: Object.keys(inferenceConfig).length ? inferenceConfig : undefined,
          })
        );

        tracker.trackBedrockConverseMetrics(response);
      }

      // ===================
      // AGENT MODE
      // ===================
      const agentFallback = { enabled: false };
      const agentConfig: LDAIAgentConfig = await aiClient.agentConfig(
        AGENT_CONFIG_KEY,
        context,
        agentFallback,
      );

      if (agentConfig.enabled && agentConfig.instructions) {
        const tracker = agentConfig.createTracker();
        const ldParams = (agentConfig.model?.parameters || {}) as Record<string, unknown>;
        const inferenceConfig = inferenceConfigFromParams(ldParams);

        // LaunchDarkly returns attached tools under parameters.tools in OpenAI type=function shape.
        // Bedrock Converse wants { toolSpec: { name, description, inputSchema: { json } } }.
        const ldTools = (ldParams.tools as any[] | undefined) ?? [];
        const tools: Tool[] = ldTools.map((t) => ({
          toolSpec: {
            name: t.name as string,
            description: (t.description as string) ?? '',
            inputSchema: { json: (t.parameters as any) ?? { type: 'object', properties: {} } },
          },
        }));

        function getOrderStatus(orderId: string): string {
          const orders: Record<string, string> = {
            'ORD-123': 'Shipped — arrives Thursday',
            'ORD-456': 'Processing — estimated ship date: tomorrow',
            'ORD-789': 'Delivered on Monday',
          };
          return orders[orderId] || `No order found with ID ${orderId}`;
        }

        const toolHandlers: Record<string, (args: any) => string> = {
          get_order_status: (args) => getOrderStatus(args.order_id),
        };

        const conversation: Message[] = [
          { role: 'user', content: [{ text: "What's the status of order ORD-123?" }] },
        ];

        const MAX_STEPS = 5;
        for (let i = 0; i < MAX_STEPS; i++) {
          const response = await bedrockClient.send(
            new ConverseCommand({
              modelId: agentConfig.model!.name,
              messages: conversation,
              system: [{ text: agentConfig.instructions }],
              toolConfig: { tools },
              inferenceConfig: Object.keys(inferenceConfig).length ? inferenceConfig : undefined,
            })
          );

          tracker.trackBedrockConverseMetrics(response);

          const outputMessage = response.output?.message;
          if (response.stopReason !== 'tool_use') {
            break;
          }

          if (outputMessage) conversation.push(outputMessage);

          const toolResults: any[] = [];
          for (const block of outputMessage?.content || []) {
            if (!('toolUse' in block) || !block.toolUse) continue;
            const { name, input, toolUseId } = block.toolUse;
            const handler = toolHandlers[name!];

            if (!handler) throw new Error(`Unknown tool: ${name}`);
            const result = handler(input);
            toolResults.push({
              toolResult: { toolUseId, content: [{ text: result }] },
            });
          }
          conversation.push({ role: 'user', content: toolResults });
        }
      }

      await ldClient.flush();
      await ldClient.close();
    }

    main();
    ```
  </CodeGroup>
</Accordion>

## What to explore next

After you have the basic integration working, you can extend it with:

* [Tools](/docs/home/agentcontrol/tools) for calling external functions from your workflows
* [Online evaluations](/docs/home/agentcontrol/online-evaluations) to score response quality automatically
* [Experiments](/docs/home/agentcontrol/experimentation) to compare AgentControl config variations statistically
* [Agents](/docs/home/agentcontrol/agents) for multi-step workflows

For more AgentControl guides, read the other guides in the [AgentControl guides](/docs/guides/agentcontrol) section.

## Troubleshooting

If you are experiencing problems with your configuration, this section lists common errors and solutions.

### Metrics not appearing

If metrics do not appear on the **AI Insights** dashboard:

* Verify that you are calling the tracker methods (`track_bedrock_converse_metrics` in Python, `trackBedrockConverseMetrics` in Node.js).
* Ensure you call `flush()` before closing the client, especially for short-lived scripts.
* Wait at least one minute for metrics to process.

### SDK initialization failures

If the LaunchDarkly SDK fails to initialize:

* Verify your SDK key is correct and matches the environment you are targeting.
* Check that your network can reach LaunchDarkly servers.
* Review the SDK logs for specific error messages.

### Config returns fallback value

If you always receive the fallback configuration:

* Verify targeting is enabled for your AgentControl config.
* Check that the AgentControl config key in your code matches the key in LaunchDarkly.
* Ensure your context matches the targeting rules.

### Amazon Bedrock errors

If you receive Amazon Bedrock API errors:

* Verify your AWS credentials are set correctly and have the `bedrock-runtime:Converse` permission.
* Confirm model access is granted for the model ID referenced in your AgentControl config.
* Ensure the model ID in your AgentControl config matches an available Amazon Bedrock model in your region.

## Conclusion

In this guide, you connected an Amazon Bedrock-powered application to LaunchDarkly AgentControl. You can now:

* Manage prompts and model settings in LaunchDarkly without code changes
* Track token usage, latency, and success rates automatically
* Use template variables to customize prompts per user

<View title="Developer">
  <Note>
    **Want to know more? Start a trial.**

    Your 14-day trial begins as soon as you sign up. Get started in minutes using the in-app Quickstart. You'll discover how easy it is to release, monitor, and optimize your software.<br /><br />

    Want to try it out? <a href="https://app.launchdarkly.com/signup">Start a trial</a>.
  </Note>
</View>

<View title="Federal docs" />

<View title="EU docs" />
