On this page

For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.

Experiment Python SDK

Amplitude体験のサーバー側Python SDK実装に関する公式ドキュメントです。

このドキュメントでは、リモート評価とローカル評価について別々のセクションで説明しています。

リモート評価

リモート評価を使用してユーザーのバリアントを取得する機能を実装しています。

インストール

Pythonバージョンの互換性

Python Server SDKはPython 3.6以降で動作します。

pip を使用して Python Server SDK をインストールします。

bash
pip install amplitude-experiment

クイックスタート

  1. 実験用クライアントを初期化する
  2. ユーザーのバリアントを取得
  3. フラグのバリアントにアクセスする
python
from amplitude_experiment import Experiment, RemoteEvaluationConfig, RemoteEvaluationClient, User
# (1) Initialize the experiment client
experiment = Experiment.initialize_remote('<DEPLOYMENT_KEY>')
# (2) Fetch variants for a user
user = User(
    device_id="abcdefg",
    user_id="user@company.com",
    user_properties={
        'premium': True
    }
)
variants = experiment.fetch_v2(user)
# (3) Access a flag's variant
variant = variants['YOUR-FLAG-KEY']
if variant:
    if variant.value == 'on':
        # Flag is on
    else:
        # Flag is off

初期化する

スタートアップ時にサーバーでSDKクライアントを初期化します。api_keyパラメーターに渡すデプロイメントキー引数は、アナリティクスイベントの送信先となるプロジェクトと同じプロジェクト内に存在する必要があります。

python
Experiment.initialize_remote(api_key, config = None) : RemoteEvaluationClient

タイムアウトと再試行の設定

パフォーマンス要件に最適なタイムアウトと再試行のオプションを設定できます。

python
experiment = Experiment.initialize_remote('<DEPLOYMENT_KEY>', Config())

設定

SDKクライアントは初期化時に設定できます。

EUデータセンター

AmplitudeのEUデータセンターを使用する場合は、初期化時にserver_zoneオプションを設定してください。

取得

ユーザーのバリアントを取得し、結果を返します。 この関数は、SDKクライアントの初期化に使用されたデプロイメントに関連付けられているフラグについて、ユーザーを リモートで評価します

python
fetch_v2(user: User, fetch_options: FetchOptions = None) : Variants

FetchOptions

python
user = User(
    device_id="abcdefg",
    user_id="user@company.com",
    user_properties={
        'premium': True
    }
)
variants = experiment.fetch_v2(user)

ユーザーのバリアントを取得した後、特定のフラグのバリアントにアクセスできます。

python
variant = variants['YOUR-FLAG-KEY']
if variant:
    if variant.value == 'on':
        # Flag is on
    else:
        # Flag is off

非同期で取得

フェッチメソッドは同期処理です。非同期的に取得するには、fetch_asyncメソッドを使用できます

python
fetch_async_v2(user: User, callback)
python
def fetch_callback(user, variants):
  variant = variants['YOUR-FLAG-KEY']
  if variant:
    if variant.value == 'on':
      # Flag is on
    else:
      # Flag is off
experiment.fetch_async_v2(user, fetch_callback)

ローカル評価

ローカル評価を使用して、ユーザーのバリアント評価を実装します。 ローカル評価を使用する予定がある場合は、そのトレードオフを理解しておく必要があります。

インストール

Python Server SDKのローカル評価をインストールします。

オペレーティングシステムとアーキテクチャのサポート

ローカル評価パッケージは、次のOSとアーキテクチャをサポートしています(OS/ARCH)。

対応済み

  • darwin/amd64
  • darwin/arm64
  • Linux/AMD64
  • linux/arm64

ローカル評価パッケージは、Alpine Linuxをサポートしていません。

サポートされている別のOS/Archが必要な場合は、githubで問題を送信するか、experiment@amplitude.comにメールしてください。

pip を使用して Python Server SDK をインストールします。

bash
pip install amplitude-experiment

クイックスタート

  1. ローカル評価クライアントを初期化します。
  2. ローカル評価クライアントを起動します。
  3. ユーザーを評価します。
python
# (1) Initialize the local evaluation client with a server deployment key.
experiment = Experiment.initialize_local("DEPLOYMENT_KEY", LocalEvaluationConfig(
  # (Recommended) Enable local evaluation cohort targeting.
  cohort_sync_config=CohortSyncConfig(api_key="API_KEY", secret_key="SECRET_KEY")
))
# (2) Start the local evaluation client.
experiment.start()
# (3) Evaluate a user.
user = User(
    device_id="abcdefg",
    user_id="user@company.com",
    user_properties={
        'premium': True
    }
)
variants = experiment.evaluate_v2(user)

初期化する

ローカル評価クライアントを初期化します。

サーバーデプロイメントキー

ローカル評価フラグ設定にアクセスするには、サーバーデプロイメントキーを使用してローカル評価クライアントを初期化する必要があります。

python
Experiment.initialize_local(api_key, config = None) : LocalEvaluationClient

フラグポーリング間隔

flag_config_polling_interval_millis設定を使用して、フラグ設定を変更した後更新されるまでにかかる時間を決定します(デフォルトは30秒)。

設定

SDKクライアントは初期化時に設定できます。

EUデータセンター

AmplitudeのEUデータセンターを使用する場合は、初期化時にserver_zoneオプションを設定してください。

LocalEvaluationConfig

AssignmentConfig

ExposureConfig

CohortSyncConfig

スタート

ローカル評価クライアントを起動し、評価用のローカル評価モードのフラグ設定を事前に取得し、設定された間隔でフラグ設定ポーラーを開始します。

python
start()

evaluate_v2()を呼び出す前に、start()の結果が得られるまで待機し、フラグ設定が使用できる状態であることを確認してください

python
experiment.start()

評価する

start()で事前に取得されたフラグを使用して評価ロジックを実行します。ユーザーオブジェクト引数にevaluateを指定する必要があります。フラグバリアントの特定のサブセットのみが必要な場合は、オプションでフラグキーの配列を渡すことができます。

自動割り当て追跡

evaluate_v2()が呼び出されたときに、Amplitudeへの割り当てイベントを自動的に追跡するようにassignment_configを設定します。

露出の追跡

露出の追跡を有効にするためにexposure_configを設定します。次に、evaluate_v2()を呼び出す際に、EvaluateOptionsの内のtracks_exposureTrueに設定します。

python
evaluate_v2(self, user: User, flag_keys: List[str], options: EvaluateOptions) : Dict[str, Variant]
python
# The user to evaluate
user = User(user_id='test_user')
# Evaluate all flag variants
all_variants = experiment.evaluate_v2(user)
# Evaluate a specific subset of flag variants
specific_variants = experiment.evaluate_v2(user, ["<FLAG_KEY_1>", "<FLAG_KEY_2>"])
# Access a variant
variant = all_variants["<FLAG_KEY>"]
if variant.value == 'on':
    # Flag is on
else:
    # Flag is off

EvaluateOptions

ローカル評価コホートターゲティング

1.4.0バージョン以降、ローカル評価SDKクライアントは、ローカル評価ターゲット設定用のコホートのダウンロードをサポートしています。このサポートを有効にするには、初期化時にアナリティクスapi_keyおよびsecret_keycohort_sync_configオプションを設定する必要があります。

python
experiment = Experiment.initialize_local("DEPLOYMENT_KEY", LocalEvaluationConfig(
  # (Recommended) Enable local evaluation cohort targeting.
  cohort_sync_config=CohortSyncConfig(api_key="API_KEY", secret_key="SECRET_KEY")
))

カスタムログ記録

ログの動作を制御するには、カスタムlogging.Loggerインスタンスを渡します。

カスタムロガー

カスタムlogging.LoggerインスタンスをRemoteEvaluationConfigまたはLocalEvaluationConfigに渡します。

python
import logging
from amplitude_experiment import Experiment, RemoteEvaluationConfig, LocalEvaluationConfig
# Create a custom logger
custom_logger = logging.getLogger('MyAppLogger')
custom_logger.setLevel(logging.WARN)
handler = logging.FileHandler('experiment.log')
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
custom_logger.addHandler(handler)
# Remote evaluation with custom logger
remote_config = RemoteEvaluationConfig(
    logger=custom_logger
)
experiment = Experiment.initialize_remote('DEPLOYMENT_KEY', remote_config)
# Local evaluation with custom logger
local_config = LocalEvaluationConfig(
    logger=custom_logger
)
experiment = Experiment.initialize_local('DEPLOYMENT_KEY', local_config)

デフォルトのロガーを使用したデバッグフラグ

カスタムロガーがない場合、debugフラグはデフォルトのロガーのレベルを制御します:

python
# Without custom logger, debug=False uses WARNING level
config = RemoteEvaluationConfig(
    debug=False
)
# Default logger level is WARNING
# Without custom logger, debug=True uses DEBUG level
config = RemoteEvaluationConfig(
    debug=True
)
# Default logger level is DEBUG

カスタムロガーを使用すると、SDKはこのフラグを無視し、ロガーは設定済みのdebugレベルを維持します:

python
import logging
from amplitude_experiment import Experiment, RemoteEvaluationConfig
custom_logger = logging.getLogger('MyAppLogger')
custom_logger.setLevel(logging.WARN)
# Custom logger maintains its WARN level regardless of debug flag
config = RemoteEvaluationConfig(
    logger=custom_logger,
    debug=True
)
# Logger level stays WARN (debug flag is ignored)

Amplitudeのクッキーへのアクセス

クライアント側でAmplitude Analytics SDKを使用する場合、Python server SDKから、Amplitudeの識別クッキーを解析および操作するための便利な関数を備えたAmplitudeCookieクラスが提供されます。これは、特にクライアントがデバイスIDをまだ生成していない場合に、サーバー上のデバイスIDがクライアントに設定されているデバイスIDと一致していることを確認するのに役立ちます。

python
import uuid
from amplitude_experiment import AmplitudeCookie
# Get the cookie name for the Amplitude API key
# For Browser SDK 2.0 cookies, use new_format=True:
# amp_cookie_name = AmplitudeCookie.cookie_name('amplitude-api-key', new_format=True)
amp_cookie_name = AmplitudeCookie.cookie_name('amplitude-api-key')
device_id = None
# Try to get device ID from existing cookie
if request.cookies.get(amp_cookie_name):
  device_id = AmplitudeCookie.parse(request.cookies.get(amp_cookie_name)).device_id
  # For Browser SDK 2.0: AmplitudeCookie.parse(request.cookies.get(amp_cookie_name), new_format=True).device_id
# If no device ID found, generate a new one and set the cookie
if device_id is None:
  device_id = str(uuid.uuid4())
  amp_cookie_value = AmplitudeCookie.generate(device_id)
  # For Browser SDK 2.0: AmplitudeCookie.generate(device_id, new_format=True)
  response.set_cookie(amp_cookie_name, amp_cookie_value,
    domain='.your-domain.com',  # this should be the same domain used by the Amplitude JS SDK
    httponly=False,
    secure=False
  )

Was this helpful?