aiconfig-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
    aiconfig-create
    skill)
  • 已启用AI Config的LaunchDarkly账户
  • 具备写入权限的API访问令牌
  • 项目密钥和环境密钥
  • 已创建包含变体的AI Config(可使用
    aiconfig-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%)
  • 子句逻辑:多个子句为AND关系,多个值为OR关系
  • 空属性:包含空/缺失属性的规则会被跳过

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:
    """AI Config定向规则管理器"""

    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]:
        """获取当前定向配置及变体ID。"""
        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]:
        """通过密钥或名称查找变体UUID。"""
        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]:
        """发送语义补丁指令。"""
        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:
        """
        通过将兜底规则设置为启用的变体来激活AI Config。

        注意:turnTargetingOn不适用于AI Config。请将兜底规则从禁用变体(索引0)切换为启用的变体。
        """
        variation_id = self.get_variation_id(config_key, variation_key)
        if not variation_id:
            print(f"[ERROR] 未找到变体'{variation_key}'")
            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:
        """添加定向规则,指向特定变体索引。"""
        instruction = {
            "kind": "addRule",
            "clauses": clauses,
            "variation": variation
        }
        if description:
            instruction["description"] = description

        result = self.update_targeting(config_key, environment,
            [instruction], f"添加规则: {description}")
        if result:
            print(f"[OK] 规则已添加")
            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:
        """
        添加百分比灰度发布规则。

        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
            }
        }], "添加百分比灰度发布")
        if result:
            print(f"[OK] 灰度发布规则已添加")
            return True
        return False

    def set_fallthrough(self, config_key: str, environment: str,
                        variation_id: str) -> bool:
        """通过UUID设置默认(兜底)变体。"""
        result = self.update_targeting(config_key, environment, [{
            "kind": "updateFallthroughVariationOrRollout",
            "variationId": variation_id
        }], "设置兜底规则")
        if result:
            print(f"[OK] 兜底规则已设置")
            return True
        return False

    def target_individuals(self, config_key: str, environment: str,
                          context_keys: List[str], variation: int,
                          context_kind: str = "user") -> bool:
        """定向特定上下文密钥。"""
        result = self.update_targeting(config_key, environment, [{
            "kind": "addTargets",
            "variation": variation,
            "contextKind": context_kind,
            "values": context_keys
        }], f"定向{len(context_keys)}个个体用户")
        if result:
            print(f"[OK] 个体定向已添加")
            return True
        return False

    def target_segment(self, config_key: str, environment: str,
                      segment_keys: List[str], variation: int) -> bool:
        """定向用户分群。"""
        result = self.update_targeting(config_key, environment, [{
            "kind": "addRule",
            "clauses": [{
                "attribute": "segmentMatch",
                "contextKind": "",  # 分群定向需留空
                "op": "segmentMatch",
                "values": segment_keys,
                "negate": false
            }],
            "variation": variation
        }], f"定向分群: {segment_keys}")
        if result:
            print(f"[OK] 分群定向已添加")
            return True
        return False

    def clear_rules(self, config_key: str, environment: str) -> bool:
        """移除所有定向规则。"""
        result = self.update_targeting(config_key, environment,
            [{"kind": "replaceRules", "rules": []}], "清除所有规则")
        if result:
            print(f"[OK] 所有规则已清除")
            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
}
  • 多个子句为AND关系(所有条件必须满足)
  • 多个值为OR关系(任意一个值满足即可)
  • 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="路由Sonnet模型请求" )
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
    aiconfig-ai-metrics
  3. Attach judges with
    aiconfig-online-evals
  4. Set up guarded rollouts for automatic regression detection
配置完成后:
  1. 提供配置URL:
    https://app.launchdarkly.com/projects/{projectKey}/ai-configs/{configKey}
  2. 使用
    aiconfig-ai-metrics
    监控性能
  3. 使用
    aiconfig-online-evals
    关联评测机制
  4. 设置受控发布以实现自动回归检测

Related Skills

相关技能

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

References

参考文档