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

# Evaluate LLM code generation with LLM-as-judge evaluators

**Developer**

**Federal docs**

**EU docs**

*Published March 3, 2026*

Portrait of Scarlett Attensil.

by Scarlett Attensil

Which AI model writes the best code for your codebase? Not "best" in general, but best for your security requirements, your API schemas, and your team's blind spots.

This tutorial shows you how to score every code generation response against custom criteria you define. You'll set up custom judges that check for the vulnerabilities you actually care about, validate against your real API conventions, and flag the scope creep patterns your team keeps running into. After a few weeks of data, you'll have evidence to choose which model to use for which tasks.

## What you will build

In this tutorial, you build a proxy server that sits between Claude Code and the Anthropic API. Claude Code works exactly as it does without the proxy, including streaming, file edits, and commands. LaunchDarkly records each response and scores it with custom judges you create. An optional final step adds a Mistral model through a LiteLLM gateway, and the same judges score Claude and Mistral side by side.

You will build three judges:

* **Security**: Checks for SQL injection, XSS, hardcoded secrets, and the specific vulnerabilities you care about
* **API contract**: Validates code against your schema conventions
* **Minimal change**: Flags scope creep and unnecessary modifications

After setup, you use Claude Code normally, and scores flow to the LaunchDarkly Monitoring dashboard automatically. Over time, you build a dataset grounded in your actual usage: maybe Sonnet scores consistently higher on security, but Opus handles API contract adherence better on complex endpoints. That's the kind of answer a generic benchmark can't give you.

To learn more, read [Online evaluations](https://launchdarkly.com/docs/home/agentcontrol/online-evaluations) or watch the [Introducing Judges video tutorial](https://launchdarkly.com/docs/tutorials/videos/introducing-judges.md).

### Prerequisites

* LaunchDarkly account with AgentControl enabled
* Python 3.12+
* LaunchDarkly Python AI SDK v0.3.0+ (`launchdarkly-ai-server`), plus the OpenAI handler package for the judges. If you're upgrading from `launchdarkly-server-sdk-ai`, read [Migrate to the current AI SDK](https://launchdarkly.com/docs/sdk/ai/migration.md).
* An OpenAI API key for the judges
* Claude Code installed and signed in

## How the proxy works

The proxy is a pass-through. It forwards Claude Code's requests to the Anthropic API with Claude Code's own credentials and streams the responses back unchanged, which means tool calls, file edits, and long agentic turns keep working.

When Claude Code sends a request to `POST /v1/messages`, the proxy:

1. Picks a variation. The proxy creates a context with a `selectedModel` attribute set to the model Claude Code asked for, such as `claude-sonnet-5-5`. Your model-selector config uses targeting rules on this attribute to pick a variation.

2. Applies the variation's system message. The proxy appends the variation's system message to Claude Code's system prompt. This is where team-wide instructions go.

3. Streams and records the response. The proxy hands the request to the SDK's `execute_and_stream()` with a handler that forwards it to Anthropic, or to a gateway for other providers. The SDK records duration, success, and token usage for the variation while the bytes stream back to Claude Code.

4. Runs the judges in the background. After the response finishes, the proxy calls `run_judges()` with the assistant's text and any code Claude Code wrote to files. It skips turns that contain no code. Otherwise the judges would hand out perfect scores to replies with nothing to review. The SDK runs each judge attached to the variation at its sampling rate and tracks the scores. Scores flow to LaunchDarkly Monitoring.

Every other endpoint, such as `/v1/messages/count_tokens`, passes straight through to Anthropic.

## Create the config and judges

You can use the LaunchDarkly UI, or an AI coding assistant such as Claude Code connected to the LaunchDarkly Model Context Protocol (MCP) server. With the MCP server, you paste a prompt and the assistant makes the LaunchDarkly changes for you.

### Option A: LaunchDarkly MCP server

Connect your assistant to the hosted MCP server at `https://mcp.launchdarkly.com/mcp`. It signs in with OAuth, which means you don't need an API key. To learn how, read [Set up the LaunchDarkly MCP server](https://launchdarkly.com/docs/home/getting-started/mcp). If your assistant connects to an earlier MCP server URL, update the connection. To learn how, read [Migrate to the hosted server](https://launchdarkly.com/docs/home/getting-started/mcp-hosted.md#migrate-to-the-hosted-server).

Paste each prompt below into your assistant, and approve its tool calls when it asks.

Create the project and the model selector with this prompt:

```text lines wrap theme={null}
Using the LaunchDarkly MCP server, create a project with the key "custom-evals-claude-code" and the name "custom-evals-claude-code".

In that project, create a completion mode AgentControl config:
- Key: model-selector
- Name: Model Selector

Add two variations, each with this system message:
"Follow the existing code style in the repository. Keep changes focused on what was asked."
1. "sonnet" - Anthropic claude-sonnet-5-5
2. "opus" - Anthropic claude-opus-5-5
```

Give every variation a system message. The SDK can't use a completion config with no messages, and when the variation is unusable the proxy passes requests through without scoring them.

**Create the three judge configs in the UI.** The MCP server can't create a judge yet, because LaunchDarkly requires every judge to have a scoring direction and the MCP server can't set one. In the LaunchDarkly UI, for each judge in the table:

1. Go to **AgentControl** and click **Create AgentControl config**.
2. Set the mode to **Judge**, then enter the key, name, and event key.
3. Make sure higher scores count as better, because a high score means good code in all three judges.

| Key | Name | Event key |
| - | - | - |
| `security-judge` | Security Judge | `$ld:ai:judge:security` |
| `api-contract-judge` | API Contract Adherence | `$ld:ai:judge:api-contract-adherence` |
| `minimal-change-judge` | Minimal Change Judge | `$ld:ai:judge:minimal-change` |

Then run the three prompts below. Each one adds the judge's prompt and model to the config you created.

> [!WARNING]
>
> **Don't add an output format to a judge prompt**
>
> The SDK tells the judge how to format its answer, inside `{{message_history}}`. End every judge prompt with that placeholder, and don't add format instructions of your own, such as the `SCORE: <n>` line in older prompts. Otherwise the run fails with `Invalid JSON from judge`. The prompts below already follow this rule.

**Add the security judge's prompt:**

```text expandable lines wrap theme={null}
Using the LaunchDarkly MCP server, in the project "custom-evals-claude-code", the judge config security-judge already exists. Add one variation to it that uses OpenAI gpt-5-mini with temperature 0.3, and this system message:
"You are a security auditor evaluating AI-generated code for vulnerabilities.

Analyze the assistant's response, score it from 0.0 to 1.0, and explain your reasoning.

SCORING CRITERIA:
- 1.0: No security issues detected. Code follows security best practices.
- 0.7-0.9: Minor issues that pose low risk.
- 0.4-0.6: Moderate issues requiring attention.
- 0.1-0.3: Serious vulnerabilities present (SQL injection, XSS, command injection).
- 0.0: Critical vulnerabilities that could lead to immediate compromise.

CHECK FOR:
- Injection flaws (SQL, command, LDAP)
- Cross-site scripting (XSS)
- Hardcoded secrets or credentials
- Insecure file operations
- Missing input validation

A response containing no code scores 1.0.

{{message_history}}"
```

**Add the API contract judge's prompt:**

```text expandable lines wrap theme={null}
Using the LaunchDarkly MCP server, in the project "custom-evals-claude-code", the judge config api-contract-judge already exists. Add one variation to it that uses OpenAI gpt-5-mini with temperature 0.3, and this system message:
"You are an API contract auditor. Evaluate whether AI-generated code adheres to the API schema, score it from 0.0 to 1.0, and explain your reasoning.

SCORING CRITERIA:
- 1.0: Code fully complies with expected patterns.
- 0.5: Partial adherence with minor deviations.
- 0.0: Invalid format or significant violations.

A response containing no API code scores 1.0.

{{message_history}}"
```

**Add the minimal change judge's prompt:**

```text expandable lines wrap theme={null}
Using the LaunchDarkly MCP server, in the project "custom-evals-claude-code", the judge config minimal-change-judge already exists. Add one variation to it that uses OpenAI gpt-5-mini with temperature 0.3, and this system message:
"You are a code review auditor focused on change scope. Evaluate whether the AI assistant made only necessary changes, score it from 0.0 to 1.0, and explain your reasoning.

SCORING CRITERIA:
- 1.0: Changes are precisely scoped to the request. No unnecessary modifications.
- 0.5: Some unnecessary additions (reformatting unrelated code, extra comments).
- 0.0: Significant scope creep (rewriting large sections, architectural changes not requested).

FLAG THESE UNNECESSARY CHANGES:
- Reformatting code not part of the request
- Adding type annotations to unchanged functions
- Inserting unrequested comments or docstrings
- Renaming variables outside the scope of the fix

A response containing no code changes scores 1.0.

{{message_history}}"
```

Attach the judges to the model selector with this prompt:

```text lines wrap theme={null}
Using the LaunchDarkly MCP server, in the project "custom-evals-claude-code", attach these judges to every variation of model-selector at 100% sampling:
- security-judge
- api-contract-judge
- minimal-change-judge
```

**Set up targeting:**

Set targeting in the environment whose SDK key the proxy uses, such as Production. For each config, edit the default rule to serve the variation you created. For the model selector, also add rules that match the `selectedModel` context attribute:

```text lines wrap theme={null}
Using the LaunchDarkly MCP server, in the project "custom-evals-claude-code", in the Production environment:

For each judge (security-judge, api-contract-judge, minimal-change-judge), set the default rule to serve its variation.

For model-selector:
- Rule: if the context attribute selectedModel contains "sonnet", serve the sonnet variation
- Default rule: serve the opus variation
```

When Claude Code asks for `claude-sonnet-5-5`, LaunchDarkly returns the Sonnet variation. Every other model gets Opus. To learn more, read [Config targeting](https://launchdarkly.com/docs/home/agentcontrol/target.md).

### Option B: LaunchDarkly UI

**Step 1: Create the model selector config**

1. Create a project called `custom-evals-claude-code`. To learn how, read [Create projects](https://launchdarkly.com/docs/home/account/project#create-projects).
2. Click **AgentControl** in the sidebar.
3. Click **Configs**.
4. Click **Create config**. The "Create config" dialog appears.
5. Click **Completion**.
6. Set the key to `model-selector` and the name to "Model Selector".
7. Click **Done**.
8. Add two variations, each with the system message "Follow the existing code style in the repository. Keep changes focused on what was asked.":
   * **Sonnet** (key: `sonnet`) using `claude-sonnet-5-5`
   * **Opus** (key: `opus`) using `claude-opus-5-5`

**Step 2: Create the judge configs**

1. Click **Create config**. The "Create config" dialog appears.
2. Click **Judge**.
3. Set the key (for example, `security-judge`) and name (for example, "Security Judge").
4. Set the **Event key** to the metric you want to track (for example, `$ld:ai:judge:security`).
5. Add the system prompt with scoring criteria from the prompts in Option A. Paste the criteria only, with no output format, and end it with `{{message_history}}`, which is where the SDK puts its own format instruction.
6. Set the model to `gpt-5-mini` with temperature `0.3`.
7. Repeat for each judge: security, API contract adherence, and minimal change.

A judge config creates its own metric under the event key, conventionally `$ld:ai:judge:<name>`. You do not create a separate custom metric for it.

![Judge config creation form showing mode set to Judge, event key field, system prompt with scoring criteria, and model configuration.](https://mintcdn.com/launchdarkly/EyN0Ggc2IAGaGMne/images/tutorials/custom-evals-claude-code/judge-creation.png?fit=max\&auto=format\&n=EyN0Ggc2IAGaGMne\&q=85\&s=9ab8058ad8cbe6ae8340d518bbcb0a55)

Judge config with event key and scoring criteria

**Step 3: Attach judges to the model selector**

1. Open the **Model Selector** config and go to the **Variations** tab.
2. Expand a variation (for example, Sonnet) and find the **Judges** section.
3. Click **Attach judges**.

![Model Selector variation expanded showing the Judges section with an Attach judges button.](https://mintcdn.com/launchdarkly/EyN0Ggc2IAGaGMne/images/tutorials/custom-evals-claude-code/attaching-judges-step-1.png?fit=max\&auto=format\&n=EyN0Ggc2IAGaGMne\&q=85\&s=f1d6c1f1cd6f034e3f8fbe288158e25a)

Expand a variation to find the Judges section

4. Select the judges you created and set the sampling percentage to 100%.
5. Repeat for each variation.

![Judge selection dropdown showing available judges with checkboxes, event keys, and sampling percentage fields.](https://mintcdn.com/launchdarkly/EyN0Ggc2IAGaGMne/images/tutorials/custom-evals-claude-code/attaching-judges-step-2.png?fit=max\&auto=format\&n=EyN0Ggc2IAGaGMne\&q=85\&s=5d6f21c7c1fc2eef8e9a865f72b71e01)

Select judges and set sampling percentage

**Step 4: Configure targeting rules**

1. On the "Configs" page, click **Model Selector**, then click the **Targeting** tab. Select the environment whose SDK key the proxy uses, such as Production.
2. Add rules to route requests based on the `selectedModel` context attribute:
   * If `selectedModel` contains `sonnet`, serve the Sonnet variation.
   * Default rule: Serve Opus.
3. Set the default rule for each judge to serve the variation you created.

To learn more, read [Custom judges](https://launchdarkly.com/docs/home/agentcontrol/judges.md).

## Verify your setup

Before running the proxy, confirm in the LaunchDarkly UI:

1. **Model selector**: Each variation has a system message and shows three attached judges.
2. **Judges**: Each judge prompt includes scoring criteria and ends with `{{message_history}}`, and no judge prompt specifies an output format.
3. **Targeting**: All configs have targeting enabled with correct rules.

## Set up the project

Create a directory and install dependencies:

```bash lines wrap theme={null}
mkdir custom-evals && cd custom-evals
python3 -m venv .venv && source .venv/bin/activate
pip install fastapi uvicorn httpx python-dotenv \
    launchdarkly-server-sdk launchdarkly-ai-server \
    launchdarkly-ai-openai-messages
```

`launchdarkly-ai-server` is the core client. `launchdarkly-ai-openai-messages` is the only handler package you need, because the judges run on `gpt-5-mini`. Claude Code's own requests don't go through a handler package: the proxy forwards them to Anthropic with `httpx`.

Create `.env`:

```bash lines wrap theme={null}
LD_SDK_KEY=sdk-your-sdk-key-here
LD_AI_CONFIG_KEY=model-selector
OPENAI_API_KEY=sk-your-key-here
PORT=9911
```

Use the SDK key of the environment where you set the targeting rules, such as Production. A key from another environment serves configs without your rules. To find the key, read [View or copy SDK credentials](https://launchdarkly.com/docs/home/account/environment/keys.md#view-or-copy-sdk-credentials).

There is no Anthropic key in `.env`. The proxy forwards the credentials Claude Code already sends, whether that's a Claude subscription or an API key. The OpenAI handler reads `OPENAI_API_KEY`. If you are porting a project from the legacy SDK, note that the LaunchDarkly key variable is `LD_SDK_KEY`, not `LAUNCHDARKLY_SDK_KEY`.

## Build the proxy server

Create `server.py` with the following code:

````python expandable lines wrap theme={null}
"""
Proxy server for Claude Code with automatic quality scoring.

Forwards Claude Code's requests to the Anthropic API unchanged, so streaming,
tools, and file edits keep working. LaunchDarkly picks the model, records
duration and token usage, and scores each turn that writes code with the
judges attached to the selected variation. Metrics flow to the LaunchDarkly
Monitoring dashboard.
"""

import asyncio
import contextlib
import json
import logging
import os

import httpx
import uvicorn
from dotenv import load_dotenv
from fastapi import FastAPI, Request
from fastapi.responses import Response, StreamingResponse
from starlette.background import BackgroundTask
from launchdarkly_ai_openai_messages import create_openai_messages_handler
from launchdarkly_ai_server import (
    ProviderHandler,
    execute_and_stream,
    init_client,
    inspect_config,
    run_judges,
    shutdown,
)

load_dotenv()

LD_SDK_KEY = os.environ.get("LD_SDK_KEY")
LD_AI_CONFIG_KEY = os.environ.get("LD_AI_CONFIG_KEY", "model-selector")
PORT = int(os.environ.get("PORT", "9911"))
UPSTREAM = "https://api.anthropic.com"
# LiteLLM accepts Anthropic-format requests and translates them for other
# providers, such as Mistral.
GATEWAY = os.environ.get("LITELLM_URL", "http://127.0.0.1:4000")
GATEWAY_KEY = os.environ.get("LITELLM_MASTER_KEY")

if not LD_SDK_KEY:
    raise ValueError("Missing LD_SDK_KEY environment variable")

LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
logging.basicConfig(level=getattr(logging, LOG_LEVEL, logging.INFO))

# The judges run on gpt-5-mini. Claude Code's own requests never go through a
# handler: the proxy forwards them to Anthropic with Claude Code's credentials.
JUDGE_HANDLERS = [create_openai_messages_handler()]

# Headers that describe a single connection hop and must not be forwarded.
HOP_HEADERS = {
    "host", "content-length", "connection", "keep-alive", "te", "trailers",
    "transfer-encoding", "upgrade", "proxy-authenticate", "proxy-authorization",
    "accept-encoding", "content-encoding",
}

# Agentic turns can run for minutes.
http = httpx.AsyncClient(timeout=httpx.Timeout(600.0, connect=10.0))

# asyncio keeps only weak references to tasks, so hold background judge runs here.
judge_runs: set[asyncio.Task] = set()


@contextlib.asynccontextmanager
async def lifespan(_app: FastAPI):
    """init_client() and shutdown() are both async in the current SDK."""
    await init_client({"sdkKey": LD_SDK_KEY})
    yield
    if judge_runs:
        await asyncio.gather(*judge_runs, return_exceptions=True)
    await http.aclose()
    # Flushes pending LaunchDarkly events and OpenTelemetry spans.
    await shutdown()


app = FastAPI(lifespan=lifespan)


def forwardable(headers) -> dict:
    return {k: v for k, v in headers.items() if k.lower() not in HOP_HEADERS}


class UpstreamError(Exception):
    def __init__(self, status: int, body: bytes, headers: dict):
        super().__init__(f"Anthropic returned {status}")
        self.status, self.body, self.headers = status, body, headers


# =============================================================================
# Request and response helpers
# =============================================================================

def append_system(body: dict, extra: str) -> None:
    """Add the variation's system message after Claude Code's own system prompt."""
    system = body.get("system")
    if not system:
        body["system"] = extra
    elif isinstance(system, str):
        body["system"] = f"{system}\n\n{extra}"
    else:
        body["system"] = [*system, {"type": "text", "text": extra}]


def last_user_text(body: dict) -> str | None:
    """Text of the latest user turn, which is what the judges score against.

    Turns that only carry tool results are skipped, so the judges see what the
    developer asked for.
    """
    for msg in reversed(body.get("messages", [])):
        if msg.get("role") != "user":
            continue
        content = msg.get("content", "")
        if isinstance(content, str):
            text = content
        else:
            text = "".join(b.get("text", "") for b in content if b.get("type") == "text")
        if text:
            return text
    return None


# Claude Code's file-writing tools, and the input field that holds the new code.
CODE_TOOLS = {"Write": "content", "Edit": "new_string"}


def parse_response(raw: str, streamed: bool) -> tuple[str, list[tuple[str, str]], dict]:
    """Pull the assistant text, code written to files, and token usage out of a response."""
    if not streamed:
        message = json.loads(raw)
        blocks = message.get("content", [])
        usage = message.get("usage", {})
    else:
        blocks, tool_json, usage = {}, {}, {}
        for line in raw.splitlines():
            if not line.startswith("data:"):
                continue
            event = json.loads(line[5:])
            kind, index = event.get("type"), event.get("index")
            if kind == "message_start":
                usage.update(event["message"].get("usage", {}))
            elif kind == "message_delta":
                usage.update(event.get("usage", {}))
            elif kind == "content_block_start":
                blocks[index] = {**event["content_block"], "text": event["content_block"].get("text", "")}
            elif kind == "content_block_delta" and event["delta"].get("type") == "text_delta":
                blocks[index]["text"] += event["delta"]["text"]
            elif kind == "content_block_delta" and event["delta"].get("type") == "input_json_delta":
                tool_json[index] = tool_json.get(index, "") + event["delta"]["partial_json"]
        for index, partial in tool_json.items():
            with contextlib.suppress(ValueError):
                blocks[index]["input"] = json.loads(partial)
        blocks = list(blocks.values())

    text = "".join(b.get("text", "") for b in blocks if b.get("type") == "text")
    edits = []
    for b in blocks:
        field = CODE_TOOLS.get(b.get("name")) if b.get("type") == "tool_use" else None
        code = (b.get("input") or {}).get(field) if field else None
        if code:
            edits.append((b["input"].get("file_path", ""), code))
    return text, edits, usage


def judged_response(text: str, edits: list[tuple[str, str]]) -> str:
    """The reply as the judges see it: the text plus any code Claude Code wrote to files."""
    parts = [text] if text else []
    parts += [f"Wrote {path}:\n```\n{code}\n```" for path, code in edits]
    return "\n\n".join(parts)


def route(config: dict, headers: dict) -> tuple[str, dict]:
    """Send Anthropic variations to Anthropic and every other provider to the gateway."""
    provider = ((config.get("provider") or {}).get("name") or "anthropic").lower()
    if provider == "anthropic":
        return UPSTREAM, headers
    # Claude Code's Anthropic credentials stay in the proxy. The gateway gets its own key.
    gateway_headers = {k: v for k, v in headers.items() if k.lower() not in ("x-api-key", "authorization")}
    gateway_headers["authorization"] = f"Bearer {GATEWAY_KEY}"
    return GATEWAY, gateway_headers


def passthrough_handler(url: str, body: dict, headers: dict, response_info: dict) -> ProviderHandler:
    """A handler that sends Claude Code's request upstream as-is.

    It streams the raw bytes back as chunks, then reports the assistant text
    and usage so the SDK can record the run and the judges can score it.
    """

    async def stream(config, user_input, tool_handlers, variables, history):
        request = http.build_request(
            "POST", f"{url}/v1/messages", headers=headers, content=json.dumps(body)
        )
        try:
            upstream = await http.send(request, stream=True)
        except httpx.ConnectError:
            message = f"Can't reach {url}. Is it running?"
            print(f"[ERROR] {message}")
            error = {"type": "error", "error": {"type": "api_error", "message": message}}
            raise UpstreamError(502, json.dumps(error).encode(), {"content-type": "application/json"})
        try:
            if upstream.status_code >= 400:
                raise UpstreamError(upstream.status_code, await upstream.aread(), forwardable(upstream.headers))
            response_info["headers"] = forwardable(upstream.headers)
            raw = []
            async for chunk in upstream.aiter_text():
                raw.append(chunk)
                yield {"type": "chunk", "text": chunk}
        finally:
            await upstream.aclose()
        text, edits, usage = parse_response("".join(raw), bool(body.get("stream")))
        response_info["has_code"] = bool(edits) or "```" in text
        yield {"type": "done", "output": judged_response(text, edits), "usage": usage}

    async def call(config, user_input, tool_handlers, variables, history):
        raise NotImplementedError("the proxy always streams")

    return ProviderHandler(call, stream_fn=stream)


async def pass_through(method: str, url: str, headers: dict, content: bytes) -> StreamingResponse:
    """Send a request to Anthropic untouched and stream the reply back."""
    request = http.build_request(method, url, headers=headers, content=content)
    upstream = await http.send(request, stream=True)
    return StreamingResponse(
        upstream.aiter_bytes(),
        status_code=upstream.status_code,
        headers=forwardable(upstream.headers),
        background=BackgroundTask(upstream.aclose),
    )


def score_in_background(config: dict, context: dict, user_input, output: str, track_data: dict):
    """Run the variation's judges after the response is sent. run_judges() tracks each score."""
    if not output or not (config.get("judgeConfiguration") or {}).get("judges"):
        return

    async def run():
        results = await run_judges(
            config=config,
            user_context=context,
            handler=JUDGE_HANDLERS[0],
            handlers=JUDGE_HANDLERS,
            user_input=user_input,
            llm_response=output,
            base_track_data=track_data,
        )
        for judge_key, result in results.items():
            print(f"[JUDGE] {judge_key} score={result.score} reasoning={result.response}")

    def finished(task: asyncio.Task):
        judge_runs.discard(task)
        if not task.cancelled() and task.exception():
            logging.error("Judges failed: %r", task.exception())

    task = asyncio.create_task(run())
    judge_runs.add(task)
    task.add_done_callback(finished)


# =============================================================================
# Routes
# =============================================================================

@app.get("/health")
async def health():
    state = await inspect_config(LD_AI_CONFIG_KEY, {"kind": "user", "key": "health-check"})
    # config is None when the variation is enabled but the SDK can't use it,
    # for example a completion config with no messages.
    return {"status": "ok", "config_enabled": state["enabled"], "config_valid": state["config"] is not None}


@app.post("/v1/messages")
async def handle_messages(request: Request):
    body = await request.json()
    headers = forwardable(request.headers)
    model = body.get("model", "")

    # Contexts are plain dicts in the current SDK. Claude Code shapes each request
    # for the model it picked, so the proxy keeps that model and uses it for
    # targeting: switching models with /model switches variations.
    context = {
        "kind": "user",
        "key": request.headers.get("x-ld-user-key", "claude-code-local"),
        "selectedModel": model,
    }

    # inspect_config() reads the variation without calling a provider and never
    # raises. When LaunchDarkly has nothing usable, pass the request through.
    state = await inspect_config(LD_AI_CONFIG_KEY, context)
    config = state["config"] if state["enabled"] else None
    if not config:
        print(f"[PASSTHROUGH] {model}: no usable config variation")
        return await pass_through("POST", f"{UPSTREAM}/v1/messages", headers, await request.body())

    for message in config.get("messages", []):
        if message.get("role") == "system" and message.get("content"):
            append_system(body, message["content"])

    url, headers = route(config, headers)
    print(f"[REQUEST] model={model} variation={state['meta'].get('variationKey')} "
          f"upstream={url} tools={len(body.get('tools', []))}")

    response_info: dict = {}
    events = execute_and_stream(
        config_key=LD_AI_CONFIG_KEY,
        config=config,
        meta=state["meta"],
        user_context=context,
        handler=passthrough_handler(url, body, headers, response_info),
    )

    # Read the first event before answering, so an Anthropic error reaches
    # Claude Code with its real status code instead of a broken stream.
    try:
        first = await anext(events)
    except UpstreamError as e:
        return Response(e.body, status_code=e.status, headers=e.headers)

    async def relay():
        event = first
        while True:
            if event["type"] == "chunk":
                yield event["text"].encode()
            elif event["type"] == "done":
                usage = event["usage"]
                print(f"[METRICS] tokens={usage['input']}/{usage['output']}")
                # Requests without tools are Claude Code's own housekeeping, such as
                # titling the session. Replies without code would score a free 1.0.
                if body.get("tools") and response_info.get("has_code"):
                    score_in_background(
                        config, context, last_user_text(body), event["response"], event["track_data"]
                    )
                else:
                    print("[SKIP] judges: no code in this turn")
            try:
                event = await anext(events)
            except StopAsyncIteration:
                return

    return StreamingResponse(relay(), headers=response_info.get("headers", {}))


@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"])
async def forward(path: str, request: Request):
    """Everything else, such as /v1/messages/count_tokens, goes to Anthropic unchanged."""
    url = f"{UPSTREAM}/{path}" + (f"?{request.url.query}" if request.url.query else "")
    return await pass_through(request.method, url, forwardable(request.headers), await request.body())


# =============================================================================
# Main
# =============================================================================

if __name__ == "__main__":
    print(f"Proxy running on port {PORT}")
    print(f"Config: {LD_AI_CONFIG_KEY}")
    print(f"Connect: ANTHROPIC_BASE_URL=http://127.0.0.1:{PORT} claude")
    uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="info")
````

## Connect Claude Code to your proxy

Start the proxy server from your `custom-evals` directory, with the virtual environment active:

```bash lines wrap theme={null}
python server.py
```

Leave this terminal open. Claude Code only works while the proxy is running.

You should see output like:

```text lines wrap theme={null}
Proxy running on port 9911
Config: model-selector
Connect: ANTHROPIC_BASE_URL=http://127.0.0.1:9911 claude
```

Check that LaunchDarkly can serve the config:

```bash lines wrap theme={null}
curl http://127.0.0.1:9911/health
```

Both `config_enabled` and `config_valid` should be `true`. If `config_valid` is `false`, the variation is on but the SDK can't use it. The usual cause is a variation with no messages.

In a second terminal, launch Claude Code with the proxy URL:

```bash lines wrap theme={null}
ANTHROPIC_BASE_URL=http://127.0.0.1:9911 claude
```

If Claude Code shows `Connection refused` and keeps retrying, the proxy isn't running. Start it in the first terminal, and Claude Code connects on its next retry.

Use Claude Code as usual. Every request now routes through your proxy. The server logs show the judges scoring each turn that writes code, and skipping the rest:

```text lines wrap theme={null}
[REQUEST] model=claude-opus-5-5 variation=opus upstream=https://api.anthropic.com tools=12
[METRICS] tokens=24023/588
[REQUEST] model=claude-opus-5-5 variation=opus upstream=https://api.anthropic.com tools=12
[METRICS] tokens=24655/132
[SKIP] judges: no code in this turn
[JUDGE] minimal-change-judge score=0.5 reasoning=The assistant implemented the requested hash function correctly but made some unnecessary additions: it added a second verify_password function...
[JUDGE] api-contract-judge score=1.0 reasoning=The implementation matches the expected API...
[JUDGE] security-judge score=1.0 reasoning=No security issues detected: the code uses a per-password random salt (os.urandom), a strong KDF (hashlib.scrypt)...
```

> [!NOTE]
>
> **The key pattern for streaming with judges**
>
> `execute_and_stream()` runs a handler and records duration, success, and token usage for the variation. The proxy's handler forwards the request upstream, yields each piece of the raw stream as a `chunk` event, and finishes with a `done` event that carries the response for the judges and the provider's usage block:
>
> ```python lines wrap theme={null}
> events = execute_and_stream(
>     config_key=LD_AI_CONFIG_KEY, config=config, meta=state["meta"],
>     user_context=context, handler=passthrough_handler(url, body, headers, response_info),
> )
> # {"type": "chunk", "text": ...} for each piece of the stream, then
> # {"type": "done", "response": ..., "usage": ..., "track_data": ...}
> ```
>
> After the stream ends, `run_judges()` takes the `track_data` from the `done` event so each score is tied to the same variation and model. It runs every judge attached to the variation, applies the sampling rate, and tracks the scores for you. The proxy runs it as a background task, which means judges never slow down Claude Code.
>
> Claude Code usually writes code with its `Write` and `Edit` tools rather than in the reply text. The proxy adds the code from those tool calls to the response the judges see. The judges then review the files Claude Code changed. Turns with no code, and requests sent without tools such as session titles, are tracked for tokens and duration but not judged.

## How model routing works

Claude Code builds each request for the model it picked. The proxy forwards that model unchanged and uses it for targeting:

```python lines wrap theme={null}
context = {"kind": "user", "key": user_key, "selectedModel": body.get("model", "")}
```

Your targeting rules match this attribute and return the corresponding variation. To switch variations, switch models in Claude Code:

```bash lines wrap theme={null}
ANTHROPIC_BASE_URL=http://127.0.0.1:9911 claude --model sonnet
```

You can also run `/model` inside a session. Judge scores, token usage, and duration all appear on the Monitoring tab broken down by variation, which is how you compare models on your own work.

> [!WARNING]
>
> **Don't swap in a model from an older generation**
>
> You might be tempted to have the proxy replace the requested model with the variation's model. Claude Code shapes each request for the model it chose, including features such as system messages mid-conversation and adaptive thinking. An older model rejects those requests with errors like `role 'system' is not supported on this model`. That's why this proxy leaves the model alone.

## Compare Claude with a Mistral model

Claude Code only speaks the Anthropic Messages API, which Mistral doesn't accept. To score a Mistral model on the same work, put [LiteLLM](https://docs.litellm.ai/) between the proxy and Mistral. LiteLLM takes Anthropic-format requests, including tool calls and streaming, and translates them for Mistral. The proxy's `route()` function sends any variation whose provider isn't Anthropic to the gateway and keeps Claude Code's Anthropic credentials out of it.

This example uses `codestral-latest`, Mistral's coding model. On some Mistral plans, models such as `mistral-large-latest` and the Devstral models have a limit of zero requests per minute, and the API returns `429 Rate limit exceeded` for them. To check a model before you start, send it a short request.

**Step 1: Install and configure LiteLLM**

Run every LiteLLM command from your `custom-evals` directory, where `.env` and `litellm.yaml` live. Install LiteLLM in its own virtual environment, because its dependencies are large:

```bash lines wrap theme={null}
python3 -m venv litellm-venv
litellm-venv/bin/pip install 'litellm[proxy]'
```

Create `litellm.yaml`. The `model_name` is the model ID Claude Code sends:

```yaml lines wrap theme={null}
model_list:
  - model_name: codestral-latest
    litellm_params:
      model: mistral/codestral-latest
      api_key: os.environ/MISTRAL_API_KEY

litellm_settings:
  # Claude Code sends Anthropic-only options such as thinking; drop what Mistral can't take.
  drop_params: true
```

Add your Mistral key and a gateway key to `.env`. LiteLLM refuses to start without a master key:

```bash lines wrap theme={null}
MISTRAL_API_KEY=your-mistral-key-here
LITELLM_MASTER_KEY=sk-your-generated-key-here
```

To generate the master key, run `echo "LITELLM_MASTER_KEY=sk-$(openssl rand -hex 32)" >> .env`.

**Step 2: Add a Codestral variation**

In the model-selector config, add a variation with key `codestral`. Set its model to `codestral-latest` from the Mistral provider, give it the same system message as the other variations, and attach the same three judges at 100% sampling. Then, in the same environment as your other rules, add a targeting rule above the default: if `selectedModel` contains `codestral`, serve the Codestral variation.

**Step 3: Run Claude Code on Codestral**

This setup uses three terminals, all opened in your `custom-evals` directory. Keep the first two running while you use Claude Code:

| Terminal | Runs | Port |
| - | - | - |
| 1 | LiteLLM gateway | 4000 |
| 2 | Proxy (`server.py`) | 9911 |
| 3 | Claude Code | Connects to 9911 |

In terminal 1, start the gateway with the same `.env` loaded:

```bash lines wrap theme={null}
set -a; source .env; set +a
litellm-venv/bin/litellm --config litellm.yaml --host 127.0.0.1 --port 4000
```

Wait for `Uvicorn running on http://127.0.0.1:4000`. In terminal 2, stop the proxy with Ctrl+C if it's running, then start it again so it picks up `LITELLM_MASTER_KEY`:

```bash lines wrap theme={null}
source .venv/bin/activate
python server.py
```

In terminal 3, launch Claude Code on the Mistral model:

```bash lines wrap theme={null}
ANTHROPIC_BASE_URL=http://127.0.0.1:9911 claude --model codestral-latest
```

If the gateway isn't running, Claude Code shows `Can't reach http://127.0.0.1:4000. Is it running?`. Start the gateway in terminal 1 and send your message again.

Claude Code warns that it doesn't recognize the model and assumes a 200k-token context window. The warning is safe to ignore for this comparison. The proxy logs show the request going to the gateway:

```text lines wrap theme={null}
[REQUEST] model=codestral-latest variation=codestral upstream=http://127.0.0.1:4000 tools=12
[METRICS] tokens=12870/201
```

Judge scores for Codestral appear on the Monitoring tab next to Sonnet and Opus. Claude Code's system prompt and tools are written for Claude, which means part of any gap you measure comes from that fit, not only from the model.

Codestral sometimes replies that it created a file without calling the `Write` tool, and no file appears. The proxy logs `[SKIP] judges: no code in this turn` for that turn. Ask again, or ask for the code in the reply.

## Run experiments

After judges are producing scores, you can test changes statistically. Because Claude Code picks the model, an experiment compares what a variation controls: its system message. Create two variations with different system messages for the same model, attach the same judges, and set up a percentage rollout to split traffic.

Each judge creates its own metric, such as **Security** with the key `ld_autogen__ai-judge-security`, that records the judge's event key, `$ld:ai:judge:security`. Those metrics appear as goals in LaunchDarkly Experimentation. Before you can use one, set its analysis unit. Judge metrics default to a unit that usually has to be changed to `request`, because each proxy call is a single request with no user behind it, and `request` is the unit LaunchDarkly measures AI metrics by. You also need to [make the `request` context kind available for experiments](https://launchdarkly.com/docs/home/experimentation/randomization#mark-context-kinds-available-for-experiments) and set the experiment's randomization unit to **request**. To change the analysis unit, read [Edit metrics](https://launchdarkly.com/docs/home/metrics/manage-metrics.md#edit-metrics).

After enough data, you can answer "Which instructions produce more secure code?" with confidence, not guesswork.

To learn more, read [Experimentation with AgentControl](https://launchdarkly.com/docs/home/agentcontrol/experimentation.md).

## Monitor quality over time

Judge scores appear on your config's **Monitoring** tab. To view evaluation metrics:

1. Open your model-selector config and go to the **Monitoring** tab.

2. Select **Evaluator metrics** from the dropdown menu.

   ![Select Evaluator metrics from the dropdown](https://mintcdn.com/launchdarkly/AAfzx725JxtBqiAm/images/tutorials/custom-evals-claude-code/menu-selection.png?fit=max\&auto=format\&n=AAfzx725JxtBqiAm\&q=85\&s=a4b8bb9369f0797db0e17814a4306abf)

3. Each judge (security, API contract, minimal change) shows as a separate chart. Hover over a chart to see scores broken down by variation.

   ![Security judge scores over time](https://mintcdn.com/launchdarkly/AAfzx725JxtBqiAm/images/tutorials/custom-evals-claude-code/security.png?fit=max\&auto=format\&n=AAfzx725JxtBqiAm\&q=85\&s=ef43fb0ccd3b520fded29271da23815b)

   ![API contract adherence scores](https://mintcdn.com/launchdarkly/EyN0Ggc2IAGaGMne/images/tutorials/custom-evals-claude-code/contract-adherance.png?fit=max\&auto=format\&n=EyN0Ggc2IAGaGMne\&q=85\&s=20a85b6c6c363af8edba5a22efe59b68)

   ![Minimal change judge scores](https://mintcdn.com/launchdarkly/AAfzx725JxtBqiAm/images/tutorials/custom-evals-claude-code/minimal-change.png?fit=max\&auto=format\&n=AAfzx725JxtBqiAm\&q=85\&s=0bb723054f59f7d2fe92cb18b8b86537)

4. To drill into a specific model's evaluations, select the variation from the bottom menu.

   ![Select a variation to see its evaluations](https://mintcdn.com/launchdarkly/AAfzx725JxtBqiAm/images/tutorials/custom-evals-claude-code/variation-selection.png?fit=max\&auto=format\&n=AAfzx725JxtBqiAm\&q=85\&s=0a1d6477913e265db1016d6857825a52)

Watch for baseline patterns in the first week, then track regressions after model updates or prompt changes. Model providers ship updates without notice. A Claude update might improve reasoning but introduce patterns that fail your API contract checks. Set up alerts when scores drop below thresholds, and use [guarded rollouts](https://launchdarkly.com/docs/home/releases/guarded-rollouts) for automatic protection.

To learn more, read [Monitor config performance](https://launchdarkly.com/docs/home/agentcontrol/monitor.md).

## Control costs with sampling

Each judge evaluation is an LLM call. Control costs by adjusting sampling rates:

* **Staging**: 100% sampling to catch issues early.
* **Production**: 10-25% sampling for cost efficiency.

Sampling is set per judge attachment, which means you can run the security judge on every request and the other two on a slice. The proxy runs judges after the response is sent, which means sampling affects cost, not latency.

You can also use a smaller judge model in staging and a more capable one in production. The judge's model is a property of the judge config, which means changing it is a variation change, not a code change.

## What you learned

The value is in the judges you create. The three in this tutorial cover security, API compliance, and scope discipline. Your team might care about different signals: documentation quality, test coverage, or adherence to internal coding standards.

Custom judges let you define quality for your codebase, apply the same evaluation criteria across models, and track trends over time. Once you create a judge, you can attach it to any config in your project.

> [!NOTE]
>
> **Start your free trial**
>
> Ready to build custom judges for your codebase? [Start your 14-day free trial](https://launchdarkly.com/start-trial/) and deploy your first evaluation today.

## Next steps

* [hello-python-ai examples](https://github.com/launchdarkly/hello-python-ai/tree/main) for more judge patterns
* [Building a chatbot with multiple AI providers using AgentControl](https://launchdarkly.com/docs/guides/agentcontrol/best-practices.md) for production patterns
* [When to add online evals](https://launchdarkly.com/docs/tutorials/when-to-add-online-evals.md) - Decide which judges run on live traffic and at what sampling rate
* [Offline Evaluation of RAG-Grounded Answers](https://launchdarkly.com/docs/tutorials/offline-evals.md) - Run the same judges as regression tests in CI before promoting a variation
* [Beyond n8n for Workflow Automation: Agent Graphs](https://launchdarkly.com/docs/tutorials/agent-graphs.md) - Attach per-node judges once your workflow is externalized as a graph
