> ## 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 Anthropic Claude and AgentControl configs

This guide shows how to connect an Anthropic Claude-powered application to LaunchDarkly AgentControl. Claude is well-suited for complex reasoning, code generation, and long-context tasks. 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. Both completion mode and agent mode support 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 Anthropic API key. Create one at [console.anthropic.com](https://console.anthropic.com/).
* 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 Anthropic 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 Anthropic 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 "anthropic>=0.39.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 @anthropic-ai/sdk
  npm install dotenv
  ```
</CodeGroup>

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

```bash lines wrap theme={null}
# .env
LAUNCHDARKLY_SDK_KEY=<your-launchdarkly-sdk-key>
ANTHROPIC_API_KEY=<your-anthropic-api-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 Anthropic client. Store your API keys in environment variables.

Here is the initialization code:

<CodeGroup>
  ```python title="Python" expandable lines wrap theme={null}
  import os
  import ldclient
  from ldclient import Context
  from ldclient.config import Config
  from ldai import LDAIClient
  from ldai.providers.types import LDAIMetrics
  from ldai.tracker import TokenUsage
  from anthropic import Anthropic
  from dotenv import load_dotenv

  load_dotenv()

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

  anthropic_client = Anthropic(api_key=ANTHROPIC_API_KEY)
  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,
    type LDAIMetrics,
  } from '@launchdarkly/server-sdk-ai';
  import Anthropic from '@anthropic-ai/sdk';

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

  const anthropicClient = new Anthropic({ apiKey: ANTHROPIC_API_KEY });
  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 Anthropic 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 'Anthropic assistant' with a 'Claude Sonnet 4' variation using the claude-sonnet-4-20250514 model, temperature 0.7, maxTokens 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 "Anthropic 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 the `claude-sonnet-4-20250514` Anthropic model.
3. Click **Parameters** and set `temperature` to `0.7` and `maxTokens` 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 so your application fails gracefully if 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": "claude-opus-4-7"},
  #       provider={"name": "anthropic"},
  #       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: 'claude-opus-4-7' },
  //     provider: { name: 'anthropic' },
  //     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>

Check the `enabled` property and handle the disabled case in your application. When you pass a fallback configuration, the SDK uses it if LaunchDarkly is unreachable.

<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 Anthropic and track metrics

Anthropic's Messages API expects a specific format. The system message goes in a top-level `system` parameter, separate from the user/assistant messages.

To track metrics, define an `anthropic_metrics` (Python) / `anthropicMetrics` (TypeScript) converter function that maps an Anthropic response to an `LDAIMetrics` object. Then pass it to `tracker.track_metrics_of` / `tracker.trackMetricsOf` along with a callable that performs the Anthropic API call. The tracker handles duration, success, and error tracking automatically.

Define the metrics converter:

<CodeGroup>
  ```python title="Python" lines wrap theme={null}
  def anthropic_metrics(response) -> LDAIMetrics:
      """Convert an Anthropic Messages response into LDAIMetrics. Passed to
      tracker.track_metrics_of, which handles duration + success/error itself."""
      usage = response.usage
      return LDAIMetrics(
          success=True,
          tokens=TokenUsage(
              total=usage.input_tokens + usage.output_tokens,
              input=usage.input_tokens,
              output=usage.output_tokens,
          ),
      )
  ```

  ```typescript title="Node.js (TypeScript)" lines wrap theme={null}
  // Convert an Anthropic Messages response into LDAIMetrics. Passed to
  // tracker.trackMetricsOf, which handles duration + success/error itself.
  function anthropicMetrics(response: Anthropic.Messages.Message): LDAIMetrics {
    return {
      success: true,
      tokens: {
        input: response.usage.input_tokens,
        output: response.usage.output_tokens,
        total: response.usage.input_tokens + response.usage.output_tokens,
      },
    };
  }
  ```
</CodeGroup>

Then call Anthropic with the config using `tracker.track_metrics_of` / `tracker.trackMetricsOf`. Variation parameters are stored in the same snake\_case shape Anthropic's SDK expects (`max_tokens`, `top_p`, ...), so they pass through directly:

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

      # Anthropic uses a top-level `system` parameter, not a system role in messages
      system = next((m.content for m in messages if m.role == "system"), None)
      chat_messages = [{"role": m.role, "content": m.content} for m in messages if m.role != "system"]
      chat_messages.append({"role": "user", "content": "How do I read a file in Python?"})

      params = dict((config.model.to_dict().get("parameters") if config.model else None) or {})
      params.setdefault("max_tokens", 1024)

      response = tracker.track_metrics_of(
          anthropic_metrics,
          lambda: anthropic_client.messages.create(
              model=config.model.name,
              system=system or "",
              messages=chat_messages,
              **params,
          ),
      )
  ```

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

    // Anthropic uses a top-level `system` parameter, not a system role in messages
    let systemMessage: string | undefined;
    const chatMessages: Array<{ role: 'user' | 'assistant'; content: string }> = [];

    for (const msg of messages) {
      if (msg.role === 'system') systemMessage = msg.content;
      else if (msg.role === 'user' || msg.role === 'assistant') {
        chatMessages.push({ role: msg.role, content: msg.content });
      }
    }

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

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

    await tracker.trackMetricsOf(anthropicMetrics, () =>
      anthropicClient.messages.create({
        model: aiConfig.model!.name,
        system: systemMessage,
        messages: chatMessages,
        ...params,
      } as any),
    );
  }
  ```
</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 Anthropic, the instructions map to the top-level `system` parameter and tools pass through on the top-level `tools` 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 **AgentControl 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}
  Anthropic 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 `claude-sonnet-4-20250514`.
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 the attached tools under `parameters.tools` in OpenAI's `type=function` shape, so convert them to Anthropic's `{name, description, input_schema}` shape and pass them on the top-level `tools=` argument. 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}
  # Same fallback pattern as completion — omit the default for a disabled fallback.
  agent = ai_client.agent_config(AGENT_CONFIG_KEY, context)

  if agent.enabled:
      tracker = agent.create_tracker()
      params = dict((agent.model.to_dict().get("parameters") if agent.model else None) or {})
      params.setdefault("max_tokens", 1024)

      # LaunchDarkly returns attached tools under `parameters.tools` in OpenAI's type=function
      # shape: [{type:"function", name, description, parameters:{...schema}}].
      # Anthropic expects {name, description, input_schema}. Convert and move them
      # out of params (they go on the top-level `tools=` argument).
      ld_tools = params.pop("tools", []) or []
      tools = [
          {
              "name": t["name"],
              "description": t.get("description", ""),
              "input_schema": t.get("parameters", {"type": "object", "properties": {}}),
          }
          for t in ld_tools
      ]

      # Handlers stay in application code — LaunchDarkly stores the schema, the app owns the behavior.
      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}

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

      # Agent loop: call Anthropic, handle tool_use blocks, repeat
      MAX_STEPS = 5
      for _ in range(MAX_STEPS):
          response = tracker.track_metrics_of(
              anthropic_metrics,
              lambda: anthropic_client.messages.create(
                  model=agent.model.name,
                  system=agent.instructions,
                  messages=messages,
                  tools=tools,
                  **params,
              ),
          )

          if response.stop_reason != "tool_use":
              break

          # Append assistant turn (preserves tool_use blocks)
          messages.append({"role": "assistant", "content": response.content})

          # Build a single tool_result user turn covering every tool_use block
          tool_results = []
          for block in response.content:
              if block.type != "tool_use":
                  continue
              if block.name not in tool_handlers:
                  raise ValueError(f"Unknown tool: {block.name}")
              result = tool_handlers[block.name](**block.input)
              tracker.track_tool_call(block.name)
              tool_results.append({
                  "type": "tool_result",
                  "tool_use_id": block.id,
                  "content": result,
              })
          messages.append({"role": "user", "content": tool_results})
  ```

  ```typescript title="Node.js (TypeScript)" expandable lines wrap theme={null}
  // Same fallback pattern as completion — omit the default for a disabled fallback.
  const agentConfig: LDAIAgentConfig = await aiClient.agentConfig(AGENT_CONFIG_KEY, context);

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

    // LaunchDarkly returns attached tools in OpenAI type=function shape; Anthropic wants
    // {name, description, input_schema}. Convert and pop from params.
    const ldTools = (params.tools as any[] | undefined) ?? [];
    delete params.tools;
    const tools = ldTools.map((t) => ({
      name: t.name as string,
      description: (t.description as string) ?? '',
      input_schema: (t.parameters as any) ?? { type: 'object' as const, properties: {} },
    }));

    // Handlers stay in application code — LaunchDarkly stores the schema, the app owns the behavior.
    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 messages: any[] = [
      { role: 'user', content: "What's the status of order ORD-123?" },
    ];

    // Agent loop: call Anthropic, handle tool_use blocks, repeat
    const MAX_STEPS = 5;
    for (let i = 0; i < MAX_STEPS; i++) {
      const response = await tracker.trackMetricsOf(anthropicMetrics, () =>
        anthropicClient.messages.create({
          model: agentConfig.model!.name,
          system: agentConfig.instructions,
          messages,
          tools,
          ...params,
        } as any),
      );

      if (response.stop_reason !== 'tool_use') {
        break;
      }

      // Append assistant turn (preserves tool_use blocks)
      messages.push({ role: 'assistant', content: response.content });

      // Build a single tool_result user turn covering every tool_use block
      const toolResults: any[] = [];
      for (const block of response.content) {
        if (block.type !== 'tool_use') continue;
        if (!toolHandlers[block.name]) throw new Error(`Unknown tool: ${block.name}`);
        const result = toolHandlers[block.name](block.input);
        toolResults.push({
          type: 'tool_result',
          tool_use_id: block.id,
          content: result,
        });
      }
      messages.push({ role: 'user', content: toolResults });
    }
  }
  ```
</CodeGroup>

You can attach judges to variations in the LaunchDarkly UI for automatic evaluation in both completion mode and agent mode. You can also 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 Anthropic AgentControl configs.">
  <img src="https://mintcdn.com/launchdarkly/Y_qcqLWSC5ccm6eB/images/__LD_UI_no_test/guide-ai-config-anthropic-insights.png?fit=max&auto=format&n=Y_qcqLWSC5ccm6eB&q=85&s=313c1b2c898167db61a2efbae2e2bb17" alt="The Insights overview page showing cost, latency, error rate, and invocation metrics for Anthropic AgentControl configs." width="2897" height="1629" data-path="images/__LD_UI_no_test/guide-ai-config-anthropic-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().close()
  ```

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

Always flush events before closing. Trailing events are at risk of being lost otherwise, in short-lived scripts and long-running services alike.

Here is how to flush events:

<CodeGroup>
  ```python title="Python" lines wrap theme={null}
  # Always flush events before closing — trailing events are at risk of being
  # lost otherwise, in short-lived scripts and long-running services alike.
  ldclient.get().flush()
  ldclient.get().close()
  ```

  ```typescript title="Node.js (TypeScript)" lines wrap theme={null}
  // Always flush events before closing — trailing events are at risk of being
  // lost otherwise, in short-lived scripts and long-running services alike.
  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 ldclient
    from ldclient import Context
    from ldclient.config import Config
    from ldai import LDAIClient
    from ldai.providers.types import LDAIMetrics
    from ldai.tracker import TokenUsage
    from anthropic import Anthropic
    from dotenv import load_dotenv

    load_dotenv()

    ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY")
    SDK_KEY = os.environ.get("LAUNCHDARKLY_SDK_KEY_ANTHROPIC")

    CONFIG_KEY = "anthropic-assistant"
    AGENT_CONFIG_KEY = "anthropic-agent"


    def anthropic_metrics(response) -> LDAIMetrics:
        """Convert an Anthropic Messages response into LDAIMetrics. Passed to
        tracker.track_metrics_of, which handles duration + success/error itself."""
        usage = response.usage
        return LDAIMetrics(
            success=True,
            tokens=TokenUsage(
                total=usage.input_tokens + usage.output_tokens,
                input=usage.input_tokens,
                output=usage.output_tokens,
            ),
        )


    def main():
        anthropic_client = Anthropic(api_key=ANTHROPIC_API_KEY)
        ldclient.set_config(Config(SDK_KEY))
        if not ldclient.get().is_initialized():
            return

        ai_client = LDAIClient(ldclient.get())

        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:
        #   from ldai import AICompletionConfigDefault
        #   default = AICompletionConfigDefault(
        #       enabled=True,
        #       model={"name": "claude-opus-4-7"},
        #       provider={"name": "anthropic"},
        #       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 []

            # Anthropic uses a top-level `system` parameter, not a system role in messages
            system = next((m.content for m in messages if m.role == "system"), None)
            chat_messages = [{"role": m.role, "content": m.content} for m in messages if m.role != "system"]
            chat_messages.append({"role": "user", "content": "How do I read a file in Python?"})

            params = dict((config.model.to_dict().get("parameters") if config.model else None) or {})
            params.setdefault("max_tokens", 1024)

            tracker.track_metrics_of(
                anthropic_metrics,
                lambda: anthropic_client.messages.create(
                    model=config.model.name,
                    system=system or "",
                    messages=chat_messages,
                    **params,
                ),
            )

        # ===================
        # AGENT MODE
        # ===================

        # Same fallback pattern as completion — omit the default for a disabled fallback.
        agent = ai_client.agent_config(AGENT_CONFIG_KEY, context)

        if agent.enabled:
            tracker = agent.create_tracker()
            params = dict((agent.model.to_dict().get("parameters") if agent.model else None) or {})
            params.setdefault("max_tokens", 1024)

            # LaunchDarkly returns attached tools under `parameters.tools` in OpenAI's type=function
            # shape: [{type:"function", name, description, parameters:{...schema}}].
            # Anthropic expects {name, description, input_schema}. Convert and move them
            # out of params (they go on the top-level `tools=` argument).
            ld_tools = params.pop("tools", []) or []
            tools = [
                {
                    "name": t["name"],
                    "description": t.get("description", ""),
                    "input_schema": t.get("parameters", {"type": "object", "properties": {}}),
                }
                for t in ld_tools
            ]

            # Handlers stay in application code — LaunchDarkly stores the schema, the app owns the behavior.
            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}

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

            # Agent loop: call Anthropic, handle tool_use blocks, repeat
            MAX_STEPS = 5
            for _ in range(MAX_STEPS):
                response = tracker.track_metrics_of(
                    anthropic_metrics,
                    lambda: anthropic_client.messages.create(
                        model=agent.model.name,
                        system=agent.instructions,
                        messages=messages,
                        tools=tools,
                        **params,
                    ),
                )

                if response.stop_reason != "tool_use":
                    break

                # Append assistant turn (preserves tool_use blocks)
                messages.append({"role": "assistant", "content": response.content})

                # Build a single tool_result user turn covering every tool_use block
                tool_results = []
                for block in response.content:
                    if block.type != "tool_use":
                        continue
                    if block.name not in tool_handlers:
                        raise ValueError(f"Unknown tool: {block.name}")
                    result = tool_handlers[block.name](**block.input)
                    tracker.track_tool_call(block.name)
                    tool_results.append({
                        "type": "tool_result",
                        "tool_use_id": block.id,
                        "content": result,
                    })
                messages.append({"role": "user", "content": tool_results})

        # Always flush events before closing — trailing events are at risk of being
        # lost otherwise, in short-lived scripts and long-running services alike.
        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,
      type LDAIMetrics,
    } from '@launchdarkly/server-sdk-ai';
    import Anthropic from '@anthropic-ai/sdk';

    const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY as string;
    const SDK_KEY = process.env.LAUNCHDARKLY_SDK_KEY_ANTHROPIC as string;
    const CONFIG_KEY = 'anthropic-assistant';
    const AGENT_CONFIG_KEY = 'anthropic-agent';

    // Convert an Anthropic Messages response into LDAIMetrics. Passed to
    // tracker.trackMetricsOf, which handles duration + success/error itself.
    function anthropicMetrics(response: Anthropic.Messages.Message): LDAIMetrics {
      return {
        success: true,
        tokens: {
          input: response.usage.input_tokens,
          output: response.usage.output_tokens,
          total: response.usage.input_tokens + response.usage.output_tokens,
        },
      };
    }

    async function main() {
      const anthropicClient = new Anthropic({ apiKey: ANTHROPIC_API_KEY });
      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: 'claude-opus-4-7' },
      //     provider: { name: 'anthropic' },
      //     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 || [];

        // Anthropic uses a top-level `system` parameter, not a system role in messages
        let systemMessage: string | undefined;
        const chatMessages: Array<{ role: 'user' | 'assistant'; content: string }> = [];

        for (const msg of messages) {
          if (msg.role === 'system') systemMessage = msg.content;
          else if (msg.role === 'user' || msg.role === 'assistant') {
            chatMessages.push({ role: msg.role, content: msg.content });
          }
        }

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

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

        await tracker.trackMetricsOf(anthropicMetrics, () =>
          anthropicClient.messages.create({
            model: aiConfig.model!.name,
            system: systemMessage,
            messages: chatMessages,
            ...params,
          } as any),
        );
      }

      // ===================
      // AGENT MODE
      // ===================

      // Same fallback pattern as completion — omit the default for a disabled fallback.
      const agentConfig: LDAIAgentConfig = await aiClient.agentConfig(AGENT_CONFIG_KEY, context);

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

        // LaunchDarkly returns attached tools in OpenAI type=function shape; Anthropic wants
        // {name, description, input_schema}. Convert and pop from params.
        const ldTools = (params.tools as any[] | undefined) ?? [];
        delete params.tools;
        const tools = ldTools.map((t) => ({
          name: t.name as string,
          description: (t.description as string) ?? '',
          input_schema: (t.parameters as any) ?? { type: 'object' as const, properties: {} },
        }));

        // Handlers stay in application code — LaunchDarkly stores the schema, the app owns the behavior.
        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 messages: any[] = [
          { role: 'user', content: "What's the status of order ORD-123?" },
        ];

        // Agent loop: call Anthropic, handle tool_use blocks, repeat
        const MAX_STEPS = 5;
        for (let i = 0; i < MAX_STEPS; i++) {
          const response = await tracker.trackMetricsOf(anthropicMetrics, () =>
            anthropicClient.messages.create({
              model: agentConfig.model!.name,
              system: agentConfig.instructions,
              messages,
              tools,
              ...params,
            } as any),
          );

          if (response.stop_reason !== 'tool_use') {
            break;
          }

          // Append assistant turn (preserves tool_use blocks)
          messages.push({ role: 'assistant', content: response.content });

          // Build a single tool_result user turn covering every tool_use block
          const toolResults: any[] = [];
          for (const block of response.content) {
            if (block.type !== 'tool_use') continue;
            if (!toolHandlers[block.name]) throw new Error(`Unknown tool: ${block.name}`);
            const result = toolHandlers[block.name](block.input);
            toolResults.push({
              type: 'tool_result',
              tool_use_id: block.id,
              content: result,
            });
          }
          messages.push({ role: 'user', content: toolResults });
        }
      }

      // Always flush events before closing — trailing events are at risk of being
      // lost otherwise, in short-lived scripts and long-running services alike.
      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 `tracker.track_metrics_of()` (Python) or `tracker.trackMetricsOf()` (Node.js) with the correct metrics converter.
* 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.

### Anthropic API errors

If you receive Anthropic API errors:

* Verify your ANTHROPIC\_API\_KEY is set correctly.
* Check that your API key has sufficient permissions.
* Ensure the model name in your AgentControl config matches an available Anthropic model.

## Conclusion

In this guide, you connected an Anthropic Claude-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" />
