> ## 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.

# Optimization SDK quickstart

<View title="Developer" />

<View title="Federal docs" />

<View title="EU docs" />

This topic explains how to configure the SDK to use agent optimization. After you enable agent optimization, you can start tuning AI agent prompts, models, and parameters.

## Install agent optimization

Agent optimization is available for the Python AI SDK.

Here's how to install it:

<CodeGroup>
  ```bash title="pip" lines wrap theme={null}
  pip install launchdarkly-server-sdk launchdarkly-server-sdk-ai launchdarkly-ai-optimizer
  ```

  ```bash title="uv" lines wrap theme={null}
  uv add launchdarkly-server-sdk launchdarkly-server-sdk-ai launchdarkly-ai-optimizer
  ```
</CodeGroup>

### Add your LaunchDarkly API key

If you want to pull configurations from LaunchDarkly or commit variations, metrics, and scores back to LaunchDarkly, you must provide your `LAUNCHDARKLY_API_KEY` as an environment variable. The agent optimization SDK automatically ingests the API key if you include it.

To learn how to get your LaunchDarkly API token, read [API access tokens](/docs/home/account/api).

## Running your first optimization

There are two ways to run an optimization:

* [Use a LaunchDarkly config object](#use-a-launchdarkly-config-object): Judges, model choices, and evaluation parameters are managed in LaunchDarkly and pulled automatically at runtime.
* [Do it in your code](#do-it-in-your-code): Define everything inline. No LaunchDarkly config is required.

Regardless of which option you use, the same data is emitted and returned. To learn more, read [Output](#output).

### Use a LaunchDarkly config object

`optimize_from_config` pulls judges, model choices, and evaluation parameters from a LaunchDarkly configuration. First, you create an optimization config in the LaunchDarkly UI. Then you point your code at the config to bring its specifications into the run.

To learn how to create the config, read [Performing optimization runs](/docs/home/agentcontrol/optimization-runs).

Here's how to pull in the config:

<CodeGroup>
  ```python title="Python" expandable lines wrap theme={null}
  # LD imports
  from ldai_optimization import (
      OptimizationClient,
      OptimizationFromConfigOptions,
      OptimizationResponse,
      LLMCallConfig,
      LLMCallContext,
  )
  from ldai import LDAIClient
  from ldai.tracker import TokenUsage

  # anthropic imports
  from claude_agent_sdk import query, ClaudeAgentOptions
  from claude_agent_sdk.types import ResultMessage

  default_fallback_model = "claude-opus-4-5-20251101"

  async def run_optimization(ld_ai_client: LDAIClient):
      async def handle_agent_call(
          key: str,
          config: LLMCallConfig,
          context: LLMCallContext,
          is_evaluation: bool = False,
      ) -> OptimizationResponse:
          model = config.model.name if config.model else default_fallback_model
          final_message = None
          async for message in query(
              prompt=context.user_input or "",
              options=ClaudeAgentOptions(
                  system_prompt=config.instructions or "",
                  model=model,
              ),
          ):
              final_message = message

          if not isinstance(final_message, ResultMessage):
              raise ValueError(f"Unexpected final message type: {type(final_message)}")

          u = final_message.usage or {}
          input_tokens = u.get("input_tokens", 0)
          output_tokens = u.get("output_tokens", 0)

          return OptimizationResponse(
              output=final_message.result or "",
              usage=TokenUsage(
                  total=input_tokens + output_tokens,
                  input=input_tokens,
                  output=output_tokens,
              ),
          )

      options = OptimizationFromConfigOptions(
          project_key="default",
          handle_agent_call=handle_agent_call,
          handle_judge_call=handle_agent_call,
      )

      client = OptimizationClient(ld_ai_client)
      result = await client.optimize_from_config("my-optimization-key", options)
  ```
</CodeGroup>

### Do it in your code

`optimize_from_options` lets you define all judges, model choices, and evaluation parameters directly in code without a LaunchDarkly configuration object.

To learn more about `optimize_from_options`, read [Optimization runs without a config](/docs/home/agentcontrol/optimize-without-config).

## Output

This call returns an `OptimizationContext` representing the final output of the optimization. You can access `OptimizationContext.history` to get all of the historical `OptimizationContext`s generated during the run.

To learn more, read the [OptimizationContext reference](/docs/home/agentcontrol/optimization-context).

## Wrapping up

These are the two core ways to run an optimization, but there is even more optimization functionality. Read these other resources to get more information:

* [optimize\_from\_options in depth](/docs/home/agentcontrol/optimize-without-config): Full explanation of every option available when defining your optimization in code.
* [optimize\_from\_config in depth](/docs/home/agentcontrol/optimization-runs): Full explanation of the config-driven approach and how to set it up in LaunchDarkly.
* [Expected output](/docs/home/agentcontrol/ground-truth-optimization): Optimize against known input/output pairs instead of randomly sampled inputs.
* [Exploratory and expected output modes](/docs/home/agentcontrol/optimization#exploratory-and-expected-output-modes): Guidance on which optimization mode to use and when.
* [OptimizationContext reference](/docs/home/agentcontrol/optimization-context): Full field reference for the object returned by all optimization methods.
* [Using tools in agent optimization](/docs/home/agentcontrol/optimization-tools): How to pass tools through to your agent and judge calls.
* [Other framework examples for agent optimization](/docs/home/agentcontrol/optimization-framework-examples): Code examples for OpenAI Agents SDK, LangChain, Strands, and the Claude Agent SDK.
* [Collecting data into LaunchDarkly](/docs/home/agentcontrol/optimization#optimization-results): How metrics, scores, and variation data are reported back to LaunchDarkly.
