configs-targeting

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AI Config Targeting

AI Config 定向配置

Configure targeting rules for AI Configs to control which variations serve to different contexts. Works the same for both completion and agent mode.
为AI Config配置定向规则,控制向不同上下文场景提供哪些变体。该功能在补全模式和Agent模式下的工作方式一致。

Prerequisites

前提条件

  • LaunchDarkly account with AI Configs enabled
  • API access token with write permissions
  • Project key and environment key
  • Existing AI Config with variations (use
    configs-create
    skill)
  • 已启用AI Config功能的LaunchDarkly账户
  • 具备写入权限的API访问令牌
  • 项目密钥和环境密钥
  • 已包含变体的现有AI Config(使用
    configs-create
    技能创建)

API Key Detection

API密钥检测

  1. Check environment variables -
    LAUNCHDARKLY_API_KEY
    ,
    LAUNCHDARKLY_API_TOKEN
    ,
    LD_API_KEY
  2. Check MCP config - Claude:
    ~/.claude/config.json
    ->
    mcpServers.launchdarkly.env.LAUNCHDARKLY_API_KEY
  3. Prompt user - Only if detection fails
  1. 检查环境变量 -
    LAUNCHDARKLY_API_KEY
    LAUNCHDARKLY_API_TOKEN
    LD_API_KEY
  2. 检查MCP配置 - Claude:
    ~/.claude/config.json
    ->
    mcpServers.launchdarkly.env.LAUNCHDARKLY_API_KEY
  3. 提示用户 - 仅当检测失败时触发

Core Concepts

核心概念

Evaluation Order

评估顺序

Targeting rules evaluate in this order (same as feature flags):
  1. Individual targets - Specific context keys (highest priority)
  2. Segment rules - Pre-defined segments
  3. Custom rules - Attribute-based conditions (evaluated in order)
  4. Default rule - Fallthrough for all others
  5. Off variation - When targeting is disabled
定向规则按以下顺序评估(与功能标志相同):
  1. 个体定向 - 特定上下文密钥(优先级最高)
  2. 分群规则 - 预定义用户分群
  3. 自定义规则 - 基于属性的条件(按顺序评估)
  4. 默认规则 - 所有其他情况的兜底规则
  5. 关闭变体 - 定向功能禁用时生效

Semantic Patch API

语义补丁API

AI Config targeting uses semantic patch instructions:
PATCH /api/v2/projects/{projectKey}/ai-configs/{configKey}/targeting
Content-Type: application/json; domain-model=launchdarkly.semanticpatch
AI Config定向使用语义补丁指令:
PATCH /api/v2/projects/{projectKey}/ai-configs/{configKey}/targeting
Content-Type: application/json; domain-model=launchdarkly.semanticpatch

Key Concepts

关键概念

  • variationId: UUIDs, not keys. Always fetch targeting first to get IDs.
  • Weights: Thousandths (50000 = 50%, 100000 = 100%)
  • Clause logic: Multiple clauses = AND, multiple values = OR
  • Null attributes: Rules with null/missing attributes are skipped
  • variationId:UUID格式,而非密钥。请始终先获取定向配置以获取ID。
  • 权重:千分比(50000 = 50%,100000 = 100%)
  • 子句逻辑:多个子句 = 逻辑与,多个值 = 逻辑或
  • 空属性:包含空/缺失属性的规则将被跳过

Workflow

工作流程

Step 1: Get Targeting (with Variation IDs)

步骤1:获取定向配置(含变体ID)

bash
curl -X GET "https://app.launchdarkly.com/api/v2/projects/{projectKey}/ai-configs/{configKey}/targeting" \
  -H "Authorization: {api_token}" \
  -H "LD-API-Version: beta"
Response includes
variations
array with
_id
(UUID) for each variation.
bash
curl -X GET "https://app.launchdarkly.com/api/v2/projects/{projectKey}/ai-configs/{configKey}/targeting" \
  -H "Authorization: {api_token}" \
  -H "LD-API-Version: beta"
响应包含
variations
数组,其中每个变体都带有
_id
(UUID)字段。

Step 2: Edit the Default Rule

步骤2:编辑默认规则

Edit the default rule to serve the variation you created.
Important: The
turnTargetingOn
instruction does not work for AI Configs. Use
updateFallthroughVariationOrRollout
instead.
bash
undefined
编辑默认规则,使其提供你创建的变体。
重要提示
turnTargetingOn
指令不适用于AI Config。请改用
updateFallthroughVariationOrRollout
bash
undefined

First, get variation IDs from Step 1 response

首先,从步骤1的响应中获取变体ID

Then set fallthrough to the enabled variation (e.g., "Default" variation)

然后将兜底规则设置为启用的变体(例如"Default"变体)

curl -X PATCH "https://app.launchdarkly.com/api/v2/projects/{projectKey}/ai-configs/{configKey}/targeting"
-H "Authorization: {api_token}"
-H "Content-Type: application/json; domain-model=launchdarkly.semanticpatch"
-H "LD-API-Version: beta"
-d '{ "environmentKey": "production", "instructions": [{ "kind": "updateFallthroughVariationOrRollout", "variationId": "your-enabled-variation-uuid" }] }'
undefined
curl -X PATCH "https://app.launchdarkly.com/api/v2/projects/{projectKey}/ai-configs/{configKey}/targeting"
-H "Authorization: {api_token}"
-H "Content-Type: application/json; domain-model=launchdarkly.semanticpatch"
-H "LD-API-Version: beta"
-d '{ "environmentKey": "production", "instructions": [{ "kind": "updateFallthroughVariationOrRollout", "variationId": "your-enabled-variation-uuid" }] }'
undefined

Step 3: Add Targeting Rules

步骤3:添加定向规则

Attribute-based rule:
bash
curl -X PATCH "https://app.launchdarkly.com/api/v2/projects/{projectKey}/ai-configs/{configKey}/targeting" \
  -H "Authorization: {api_token}" \
  -H "Content-Type: application/json; domain-model=launchdarkly.semanticpatch" \
  -H "LD-API-Version: beta" \
  -d '{
    "environmentKey": "production",
    "instructions": [{
      "kind": "addRule",
      "clauses": [{
        "contextKind": "user",
        "attribute": "selectedModel",
        "op": "contains",
        "values": ["sonnet"],
        "negate": false
      }],
      "variation": 0
    }]
  }'
Percentage rollout:
bash
curl -X PATCH "..." \
  -d '{
    "environmentKey": "production",
    "instructions": [{
      "kind": "addRule",
      "clauses": [{
        "contextKind": "user",
        "attribute": "tier",
        "op": "in",
        "values": ["premium"],
        "negate": false
      }],
      "percentageRolloutConfig": {
        "contextKind": "user",
        "bucketBy": "key",
        "variations": [
          {"variation": 0, "weight": 60000},
          {"variation": 1, "weight": 40000}
        ]
      }
    }]
  }'
Set fallthrough (default rule):
bash
curl -X PATCH "..." \
  -d '{
    "environmentKey": "production",
    "instructions": [{
      "kind": "updateFallthroughVariationOrRollout",
      "variationId": "fallback-variation-uuid"
    }]
  }'
基于属性的规则:
bash
curl -X PATCH "https://app.launchdarkly.com/api/v2/projects/{projectKey}/ai-configs/{configKey}/targeting" \
  -H "Authorization: {api_token}" \
  -H "Content-Type: application/json; domain-model=launchdarkly.semanticpatch" \
  -H "LD-API-Version: beta" \
  -d '{
    "environmentKey": "production",
    "instructions": [{
      "kind": "addRule",
      "clauses": [{
        "contextKind": "user",
        "attribute": "selectedModel",
        "op": "contains",
        "values": ["sonnet"],
        "negate": false
      }],
      "variation": 0
    }]
  }'
百分比灰度发布:
bash
curl -X PATCH "..." \
  -d '{
    "environmentKey": "production",
    "instructions": [{
      "kind": "addRule",
      "clauses": [{
        "contextKind": "user",
        "attribute": "tier",
        "op": "in",
        "values": ["premium"],
        "negate": false
      }],
      "percentageRolloutConfig": {
        "contextKind": "user",
        "bucketBy": "key",
        "variations": [
          {"variation": 0, "weight": 60000},
          {"variation": 1, "weight": 40000}
        ]
      }
    }]
  }'
设置兜底规则(默认规则):
bash
curl -X PATCH "..." \
  -d '{
    "environmentKey": "production",
    "instructions": [{
      "kind": "updateFallthroughVariationOrRollout",
      "variationId": "fallback-variation-uuid"
    }]
  }'

Python Implementation

Python实现

python
import requests
import os
from typing import Dict, List, Optional

class AIConfigTargeting:
    """Manager for AI Config targeting rules"""

    def __init__(self, api_token: str, project_key: str):
        self.api_token = api_token
        self.project_key = project_key
        self.base_url = "https://app.launchdarkly.com/api/v2"

    def get_targeting(self, config_key: str) -> Optional[Dict]:
        """Get current targeting with variation IDs."""
        url = f"{self.base_url}/projects/{self.project_key}/ai-configs/{config_key}/targeting"

        response = requests.get(url, headers={
            "Authorization": self.api_token,
            "LD-API-Version": "beta"
        })

        if response.status_code == 200:
            return response.json()
        print(f"[ERROR] {response.status_code}: {response.text}")
        return None

    def get_variation_id(self, config_key: str, variation_key: str) -> Optional[str]:
        """Look up variation UUID from key or name."""
        targeting = self.get_targeting(config_key)
        if targeting:
            for var in targeting.get("variations", []):
                if var.get("key") == variation_key or var.get("name") == variation_key:
                    return var.get("_id")
        return None

    def update_targeting(self, config_key: str, environment: str,
                         instructions: List[Dict], comment: str = "") -> Optional[Dict]:
        """Send semantic patch instructions."""
        url = f"{self.base_url}/projects/{self.project_key}/ai-configs/{config_key}/targeting"

        payload = {"environmentKey": environment, "instructions": instructions}
        if comment:
            payload["comment"] = comment

        response = requests.patch(url, headers={
            "Authorization": self.api_token,
            "Content-Type": "application/json; domain-model=launchdarkly.semanticpatch",
            "LD-API-Version": "beta"
        }, json=payload)

        if response.status_code == 200:
            return response.json()
        print(f"[ERROR] {response.status_code}: {response.text}")
        return None

    def enable_config(self, config_key: str, environment: str,
                      variation_key: str = "default") -> bool:
        """
        Enable an AI Config by setting fallthrough to an enabled variation.

        Note: turnTargetingOn doesn't work for AI Configs. Instead, set the
        fallthrough from the disabled variation (index 0) to an enabled one.
        """
        variation_id = self.get_variation_id(config_key, variation_key)
        if not variation_id:
            print(f"[ERROR] Variation '{variation_key}' not found")
            return False
        return self.set_fallthrough(config_key, environment, variation_id)

    def add_rule(self, config_key: str, environment: str,
                 clauses: List[Dict], variation: int,
                 description: str = "") -> bool:
        """Add targeting rule serving a specific variation index."""
        instruction = {
            "kind": "addRule",
            "clauses": clauses,
            "variation": variation
        }
        if description:
            instruction["description"] = description

        result = self.update_targeting(config_key, environment,
            [instruction], f"Add rule: {description}")
        if result:
            print(f"[OK] Rule added")
            return True
        return False

    def add_rollout_rule(self, config_key: str, environment: str,
                         clauses: List[Dict],
                         weights: List[Dict],
                         bucket_by: str = "key") -> bool:
        """
        Add percentage rollout rule.

        weights: [{"variation": 0, "weight": 50000}, {"variation": 1, "weight": 50000}]
        """
        result = self.update_targeting(config_key, environment, [{
            "kind": "addRule",
            "clauses": clauses,
            "percentageRolloutConfig": {
                "contextKind": "user",
                "bucketBy": bucket_by,
                "variations": weights
            }
        }], "Add percentage rollout")
        if result:
            print(f"[OK] Rollout rule added")
            return True
        return False

    def set_fallthrough(self, config_key: str, environment: str,
                        variation_id: str) -> bool:
        """Set default (fallthrough) variation by UUID."""
        result = self.update_targeting(config_key, environment, [{
            "kind": "updateFallthroughVariationOrRollout",
            "variationId": variation_id
        }], "Set fallthrough")
        if result:
            print(f"[OK] Fallthrough set")
            return True
        return False

    def target_individuals(self, config_key: str, environment: str,
                          context_keys: List[str], variation: int,
                          context_kind: str = "user") -> bool:
        """Target specific context keys."""
        result = self.update_targeting(config_key, environment, [{
            "kind": "addTargets",
            "variation": variation,
            "contextKind": context_kind,
            "values": context_keys
        }], f"Target {len(context_keys)} individuals")
        if result:
            print(f"[OK] Individual targets added")
            return True
        return False

    def target_segment(self, config_key: str, environment: str,
                      segment_keys: List[str], variation: int) -> bool:
        """Target a segment."""
        result = self.update_targeting(config_key, environment, [{
            "kind": "addRule",
            "clauses": [{
                "attribute": "segmentMatch",
                "contextKind": "",  # Leave blank for segments
                "op": "segmentMatch",
                "values": segment_keys,
                "negate": False
            }],
            "variation": variation
        }], f"Target segments: {segment_keys}")
        if result:
            print(f"[OK] Segment targeting added")
            return True
        return False

    def clear_rules(self, config_key: str, environment: str) -> bool:
        """Remove all targeting rules."""
        result = self.update_targeting(config_key, environment,
            [{"kind": "replaceRules", "rules": []}], "Clear all rules")
        if result:
            print(f"[OK] All rules cleared")
            return True
        return False
python
import requests
import os
from typing import Dict, List, Optional

class AIConfigTargeting:
    """Manager for AI Config targeting rules"""

    def __init__(self, api_token: str, project_key: str):
        self.api_token = api_token
        self.project_key = project_key
        self.base_url = "https://app.launchdarkly.com/api/v2"

    def get_targeting(self, config_key: str) -> Optional[Dict]:
        """Get current targeting with variation IDs."""
        url = f"{self.base_url}/projects/{self.project_key}/ai-configs/{config_key}/targeting"

        response = requests.get(url, headers={
            "Authorization": self.api_token,
            "LD-API-Version": "beta"
        })

        if response.status_code == 200:
            return response.json()
        print(f"[ERROR] {response.status_code}: {response.text}")
        return None

    def get_variation_id(self, config_key: str, variation_key: str) -> Optional[str]:
        """Look up variation UUID from key or name."""
        targeting = self.get_targeting(config_key)
        if targeting:
            for var in targeting.get("variations", []):
                if var.get("key") == variation_key or var.get("name") == variation_key:
                    return var.get("_id")
        return None

    def update_targeting(self, config_key: str, environment: str,
                         instructions: List[Dict], comment: str = "") -> Optional[Dict]:
        """Send semantic patch instructions."""
        url = f"{self.base_url}/projects/{self.project_key}/ai-configs/{config_key}/targeting"

        payload = {"environmentKey": environment, "instructions": instructions}
        if comment:
            payload["comment"] = comment

        response = requests.patch(url, headers={
            "Authorization": self.api_token,
            "Content-Type": "application/json; domain-model=launchdarkly.semanticpatch",
            "LD-API-Version": "beta"
        }, json=payload)

        if response.status_code == 200:
            return response.json()
        print(f"[ERROR] {response.status_code}: {response.text}")
        return None

    def enable_config(self, config_key: str, environment: str,
                      variation_key: str = "default") -> bool:
        """
        Enable an AI Config by setting fallthrough to an enabled variation.

        Note: turnTargetingOn doesn't work for AI Configs. Instead, set the
        fallthrough from the disabled variation (index 0) to an enabled one.
        """
        variation_id = self.get_variation_id(config_key, variation_key)
        if not variation_id:
            print(f"[ERROR] Variation '{variation_key}' not found")
            return False
        return self.set_fallthrough(config_key, environment, variation_id)

    def add_rule(self, config_key: str, environment: str,
                 clauses: List[Dict], variation: int,
                 description: str = "") -> bool:
        """Add targeting rule serving a specific variation index."""
        instruction = {
            "kind": "addRule",
            "clauses": clauses,
            "variation": variation
        }
        if description:
            instruction["description"] = description

        result = self.update_targeting(config_key, environment,
            [instruction], f"Add rule: {description}")
        if result:
            print(f"[OK] Rule added")
            return True
        return False

    def add_rollout_rule(self, config_key: str, environment: str,
                         clauses: List[Dict],
                         weights: List[Dict],
                         bucket_by: str = "key") -> bool:
        """
        Add percentage rollout rule.

        weights: [{"variation": 0, "weight": 50000}, {"variation": 1, "weight": 50000}]
        """
        result = self.update_targeting(config_key, environment, [{
            "kind": "addRule",
            "clauses": clauses,
            "percentageRolloutConfig": {
                "contextKind": "user",
                "bucketBy": bucket_by,
                "variations": weights
            }
        }], "Add percentage rollout")
        if result:
            print(f"[OK] Rollout rule added")
            return True
        return False

    def set_fallthrough(self, config_key: str, environment: str,
                        variation_id: str) -> bool:
        """Set default (fallthrough) variation by UUID."""
        result = self.update_targeting(config_key, environment, [{
            "kind": "updateFallthroughVariationOrRollout",
            "variationId": variation_id
        }], "Set fallthrough")
        if result:
            print(f"[OK] Fallthrough set")
            return True
        return False

    def target_individuals(self, config_key: str, environment: str,
                          context_keys: List[str], variation: int,
                          context_kind: str = "user") -> bool:
        """Target specific context keys."""
        result = self.update_targeting(config_key, environment, [{
            "kind": "addTargets",
            "variation": variation,
            "contextKind": context_kind,
            "values": context_keys
        }], f"Target {len(context_keys)} individuals")
        if result:
            print(f"[OK] Individual targets added")
            return True
        return False

    def target_segment(self, config_key: str, environment: str,
                      segment_keys: List[str], variation: int) -> bool:
        """Target a segment."""
        result = self.update_targeting(config_key, environment, [{
            "kind": "addRule",
            "clauses": [{
                "attribute": "segmentMatch",
                "contextKind": "",  # Leave blank for segments
                "op": "segmentMatch",
                "values": segment_keys,
                "negate": False
            }],
            "variation": variation
        }], f"Target segments: {segment_keys}")
        if result:
            print(f"[OK] Segment targeting added")
            return True
        return False

    def clear_rules(self, config_key: str, environment: str) -> bool:
        """Remove all targeting rules."""
        result = self.update_targeting(config_key, environment,
            [{"kind": "replaceRules", "rules": []}], "Clear all rules")
        if result:
            print(f"[OK] All rules cleared")
            return True
        return False

Instruction Reference

指令参考

Note:
turnTargetingOn
and
turnTargetingOff
do not work for AI Configs. AI Configs have targeting enabled by default. To "enable" a config, set the fallthrough to an enabled variation using
updateFallthroughVariationOrRollout
.
注意
turnTargetingOn
turnTargetingOff
不适用于AI Config。AI Config默认已启用定向功能。要"启用"配置,请使用
updateFallthroughVariationOrRollout
将兜底规则设置为启用的变体。

Rules

规则类指令

KindDescription
addRule
Add rule with clauses and variation/rollout
removeRule
Remove by ruleId
replaceRules
Replace all rules
reorderRules
Change evaluation order
updateRuleVariationOrRollout
Update what a rule serves
类型描述
addRule
添加包含子句和变体/灰度配置的规则
removeRule
通过ruleId移除规则
replaceRules
替换所有规则
reorderRules
更改规则评估顺序
updateRuleVariationOrRollout
更新规则提供的变体

Fallthrough

兜底规则类指令

KindDescription
updateFallthroughVariationOrRollout
Set default variation or rollout
类型描述
updateFallthroughVariationOrRollout
设置默认变体或灰度配置

Individual Targets

个体定向类指令

KindDescription
addTargets
Target specific context keys
removeTargets
Remove specific targets
replaceTargets
Replace all targets
类型描述
addTargets
定向特定上下文密钥
removeTargets
移除特定定向对象
replaceTargets
替换所有定向对象

Operators Reference

操作符参考

OperatorDescriptionExample
in
Value in list
["premium", "enterprise"]
contains
String contains
["sonnet"]
startsWith
String prefix
["user-"]
endsWith
String suffix
[".edu"]
matches
Regex match
["^user-\\d+$"]
greaterThan
/
lessThan
Numeric comparison
[100]
before
/
after
Date comparison
["2024-12-31T00:00:00Z"]
semVerEqual
/
semVerGreaterThan
Version comparison
["2.0.0"]
segmentMatch
Segment membership
["beta-testers"]
操作符描述示例
in
值在列表中
["premium", "enterprise"]
contains
字符串包含指定内容
["sonnet"]
startsWith
字符串以指定前缀开头
["user-"]
endsWith
字符串以指定后缀结尾
[".edu"]
matches
正则匹配
["^user-\\d+$"]
greaterThan
/
lessThan
数值比较
[100]
before
/
after
日期比较
["2024-12-31T00:00:00Z"]
semVerEqual
/
semVerGreaterThan
版本号比较
["2.0.0"]
segmentMatch
用户分群成员匹配
["beta-testers"]

Clause Structure

子句结构

json
{
  "contextKind": "user",
  "attribute": "email",
  "op": "endsWith",
  "values": [".edu"],
  "negate": false
}
  • Multiple clauses = AND (all must match)
  • Multiple values = OR (any can match)
  • negate: true
    inverts the operator
json
{
  "contextKind": "user",
  "attribute": "email",
  "op": "endsWith",
  "values": [".edu"],
  "negate": false
}
  • 多个子句 = 逻辑与(所有条件必须匹配)
  • 多个值 = 逻辑或(任一条件匹配即可)
  • negate: true
    会反转操作符的逻辑

Rollout Types

灰度发布类型

Manual Percentage Rollout

手动百分比灰度发布

json
{
  "percentageRolloutConfig": {
    "contextKind": "user",
    "bucketBy": "key",
    "variations": [
      {"variation": 0, "weight": 50000},
      {"variation": 1, "weight": 50000}
    ]
  }
}
json
{
  "percentageRolloutConfig": {
    "contextKind": "user",
    "bucketBy": "key",
    "variations": [
      {"variation": 0, "weight": 50000},
      {"variation": 1, "weight": 50000}
    ]
  }
}

Progressive Rollout

渐进式灰度发布

json
{
  "progressiveRolloutConfig": {
    "contextKind": "user",
    "controlVariation": 1,
    "endVariation": 0,
    "steps": [
      {"rolloutWeight": 1000, "duration": {"quantity": 4, "unit": "hour"}},
      {"rolloutWeight": 5000, "duration": {"quantity": 4, "unit": "hour"}},
      {"rolloutWeight": 10000, "duration": {"quantity": 4, "unit": "hour"}}
    ]
  }
}
json
{
  "progressiveRolloutConfig": {
    "contextKind": "user",
    "controlVariation": 1,
    "endVariation": 0,
    "steps": [
      {"rolloutWeight": 1000, "duration": {"quantity": 4, "unit": "hour"}},
      {"rolloutWeight": 5000, "duration": {"quantity": 4, "unit": "hour"}},
      {"rolloutWeight": 10000, "duration": {"quantity": 4, "unit": "hour"}}
    ]
  }
}

Guarded Rollout

受控灰度发布

json
{
  "guardedRolloutConfig": {
    "randomizationUnit": "user",
    "stages": [
      {"rolloutWeight": 1000, "monitoringWindowMilliseconds": 17280000},
      {"rolloutWeight": 5000, "monitoringWindowMilliseconds": 17280000}
    ],
    "metrics": [{
      "metricKey": "error-rate",
      "onRegression": {"rollback": true},
      "regressionThreshold": 0.01
    }]
  }
}
json
{
  "guardedRolloutConfig": {
    "randomizationUnit": "user",
    "stages": [
      {"rolloutWeight": 1000, "monitoringWindowMilliseconds": 172800000},
      {"rolloutWeight": 5000, "monitoringWindowMilliseconds": 172800000}
    ],
    "metrics": [{
      "metricKey": "error-rate",
      "onRegression": {"rollback": true},
      "regressionThreshold": 0.01
    }]
  }
}

Common Patterns

常见模式

Model Routing by Attribute

基于属性的模型路由

python
undefined
python
undefined

Route based on selectedModel context attribute

根据selectedModel上下文属性进行路由

targeting.add_rule( config_key="model-selector", environment="production", clauses=[{ "contextKind": "user", "attribute": "selectedModel", "op": "contains", "values": ["sonnet"], "negate": False }], variation=0, # Sonnet variation index description="Route sonnet requests" )
undefined
targeting.add_rule( config_key="model-selector", environment="production", clauses=[{ "contextKind": "user", "attribute": "selectedModel", "op": "contains", "values": ["sonnet"], "negate": False }], variation=0, # Sonnet变体索引 description="Route sonnet requests" )
undefined

Tier-Based Variation

基于用户层级的变体分配

python
targeting.add_rule(
    config_key="chat-assistant",
    environment="production",
    clauses=[{
        "contextKind": "user",
        "attribute": "tier",
        "op": "in",
        "values": ["premium", "enterprise"],
        "negate": False
    }],
    variation=0  # Premium model variation
)
python
targeting.add_rule(
    config_key="chat-assistant",
    environment="production",
    clauses=[{
        "contextKind": "user",
        "attribute": "tier",
        "op": "in",
        "values": ["premium", "enterprise"],
        "negate": False
    }],
    variation=0  # 高级模型变体
)

Segment Targeting

用户分群定向

python
targeting.target_segment(
    config_key="chat-assistant",
    environment="production",
    segment_keys=["beta-testers"],
    variation=1  # Experimental variation
)
python
targeting.target_segment(
    config_key="chat-assistant",
    environment="production",
    segment_keys=["beta-testers"],
    variation=1  # 实验性变体
)

Error Handling

错误处理

StatusCauseSolution
400Invalid semantic patchCheck instruction format, ops must be lowercase
403Insufficient permissionsCheck API token
404Config not foundVerify projectKey and configKey
422Invalid variationUse index (0, 1, 2...) or UUID from targeting response
状态码原因解决方案
400语义补丁无效检查指令格式,操作符必须为小写
403权限不足检查API令牌权限
404配置未找到验证projectKey和configKey正确性
422变体无效使用索引(0、1、2...)或定向响应中的UUID

Next Steps

后续步骤

After configuring targeting:
  1. Provide config URL:
    https://app.launchdarkly.com/projects/{projectKey}/ai-configs/{configKey}
  2. Monitor performance with
    built-in-metrics
  3. Attach judges with
    online-evals
  4. Set up guarded rollouts for automatic regression detection
配置定向规则后:
  1. 提供配置URL:
    https://app.launchdarkly.com/projects/{projectKey}/ai-configs/{configKey}
  2. 使用
    built-in-metrics
    监控性能
  3. 使用
    online-evals
    关联评估器
  4. 设置受控灰度发布以实现自动回归检测

Related Skills

相关技能

  • configs-create
    - Create AI Configs with variations
  • configs-variations
    - Manage variations
  • online-evals
    - Attach judges
  • segments
    - Create segments for targeting
  • configs-create
    - 创建包含变体的AI Config
  • configs-variations
    - 管理变体
  • online-evals
    - 关联评估器
  • segments
    - 创建用于定向的用户分群

References

参考资料