Skip to main content
Glama

BanditDB Python SDK

BanditDB의 공식 Python 클라이언트 및 Model Context Protocol(MCP) 서버 — Rust로 작성된 초고속, 락-프리(Contextual Bandit) 데이터베이스입니다.

BanditDB는 강화학습(LinUCB, Thompson Sampling)의 복잡한 선형대수를 추상화하여 매우 간단한 API 뒤에 숨깁니다. 실시간 개인화 시스템, 동적 A/B 테스트를 구축하고 LLM 에이전트에게 수학적으로 엄밀한 영구 메모리를 제공하세요.

설치

pip install banditdb-python

BanditDB Rust 서버가 실행 중이어야 합니다(기본값: http://localhost:8080).


Related MCP server: Copilot Memory Store

1. 표준 SDK 사용법

클라이언트는 자동 연결 풀링, 지수 백오프 재시도, 엄격한 타임아웃을 지원합니다.

from banditdb import Client, BanditDBError

# Connect to the BanditDB server.
# Pass api_key if BANDITDB_API_KEY is set on the server.
db = Client(
    url="http://localhost:8080",
    timeout=2.0,
    api_key="your-secret-key",   # omit if server runs without auth
)

try:
    # 1. Create a campaign (run once at startup)
    # algorithm defaults to "linucb"; use "thompson_sampling" for Bayesian exploration
    db.create_campaign(
        campaign_id="checkout_upsell",
        arms=["offer_discount", "offer_free_shipping"],
        feature_dim=3,
    )
    # or: db.create_campaign(..., algorithm="thompson_sampling")

    # 2. A user arrives — ask the database what to show them
    # Context: [is_mobile, cart_value_normalized, is_returning_user]
    arm_id, interaction_id = db.predict("checkout_upsell", [1.0, 0.8, 0.0])
    print(f"Showing: {arm_id}")  # e.g., "offer_free_shipping"

    # 3. The user clicked — send the reward
    db.reward(interaction_id, reward=1.0)

except BanditDBError as e:
    print(f"Database error: {e}")

모든 클라이언트 메서드

헬스(Health)

메서드

설명

health()

서버에 연결 가능하고 WAL 라이터가 정상이면 True를 반환합니다.

health_detail()

캠페인별 entropystatus("ok" / "warning" / "critical")를 포함한 전체 헬스 딕셔너리를 반환합니다.

캠페인(Campaigns)

메서드

설명

create_campaign(campaign_id, arms, feature_dim, alpha=1.0, algorithm="linucb", metadata=None)

새 캠페인을 등록합니다. algorithm"linucb", "thompson_sampling", NeuralLinUCBConfig 또는 ProgressiveConfig를 허용합니다. metadata는 임의의 JSON 딕셔너리입니다(≤ 64 KB).

list_campaigns()

alpha, arm_count, algorithm과 함께 모든 캠페인(활성 및 보관됨) 목록을 반환합니다.

campaign_info(campaign_id)

theta, theta_norm, 예측 및 보상 카운터 등 arm별 전체 상태를 반환합니다. 찾을 수 없으면 APIError(404)를 발생시킵니다.

report(campaign_id)

비즈니스 수준 수렴 보고서입니다. converged=True는 한 arm이 95% 신뢰구간에서 통계적으로 유의미한 우위를 가짐을 의미합니다 — 중단해도 안전합니다. converged=False는 선두이지만 신뢰구간이 여전히 겹침을 의미합니다. converged=None은 데이터가 아직 충분하지 않음을 의미합니다(arm당 30개 미만의 보상).

diagnostics(campaign_id)

운영자 진단: arm별 theta 노름, A_inv 불확실성 경계, 엔트로피 헬스(selection_entropy, entropy_status, entropy_trend, likely_cause, suggested_action), 토너먼트 트래픽, 신경망 버퍼 크기.

archive_campaign(campaign_id)

소프트 삭제: 예측/보상을 일시 중지하지만 학습된 모든 가중치는 보존합니다. restore_campaign()으로 복구 가능합니다.

restore_campaign(campaign_id)

보관된 캠페인을 모든 가중치를 유지한 채 활성 상태로 복원합니다.

delete_campaign(campaign_id)

캠페인을 영구 삭제합니다. 찾을 수 없으면 False를 반환합니다.

예측 및 보상(Predict & Reward)

메서드

설명

predict(campaign_id, context)

(arm_id, interaction_id)를 반환합니다. 루프를 닫으려면 interaction_idreward()에 전달하세요.

batch_predict(predictions)

단일 왕복으로 최대 100개의 캠페인/컨텍스트 쌍을 예측합니다. 각 항목: {"campaign_id": str, "context": List[float]}. 항목별로 {arm_id, interaction_id} 또는 {error} 목록을 반환합니다.

reward(interaction_id, reward)

결과를 기록합니다. reward[0.0, 1.0] 범위여야 합니다. 상호작용이 이미 보상되었거나 만료된 경우(기본 TTL: 24시간) APIError를 발생시킵니다.

데이터 및 내보내기(Data & Export)

메서드

설명

checkpoint()

WAL을 플러시하고, 모델을 스냅샷하고, Parquet 샤드를 쓰고, 신경망 재학습 + 토너먼트 평가를 실행하고, WAL을 순환합니다. 요약 문자열을 반환합니다.

export()

캠페인별로 그룹화된 Parquet 내보내기 샤드 목록을 반환합니다. {export_dir, shards}를 반환합니다.


2. AI "하이브 마인드" (Model Context Protocol)

표준 LLM 에이전트는 상태가 없습니다(stateless) — 작업을 잘못된 모델로 라우팅하여 실패하면 다음 날 같은 실수를 반복합니다. BanditDB의 내장 MCP 서버는 전체 에이전트 스웜에 공유 영구 메모리를 제공합니다.

MCP 서버 시작

# Set environment variables before starting
export BANDITDB_URL=http://localhost:8080
export BANDITDB_API_KEY=your-secret-key   # omit if server runs without auth

banditdb-mcp

Claude Desktop에 연결

Claude 구성 파일에 추가하세요:

  • Mac: ~/Library/Application Support/Claude/claude_desktop_config.json

  • Windows: %APPDATA%\Claude\claude_desktop_config.json

{
  "mcpServers": {
    "banditdb": {
      "command": "banditdb-mcp",
      "args": [],
      "env": {
        "BANDITDB_URL": "http://localhost:8080",
        "BANDITDB_API_KEY": "your-secret-key"
      }
    }
  }
}

이제 에이전트 스웜은 9개의 도구를 사용할 수 있습니다:

도구

기능

create_campaign

새 의사결정 캠페인을 생성합니다. algorithm("linucb" 또는 "thompson_sampling") 및 alpha를 허용합니다. 튜닝 없이 자연스러운 베이지안 탐색을 위해 Thompson Sampling을 사용하세요.

list_campaigns

모든 활성 캠페인을 나열합니다(algorithmalpha 표시) — get_intuition을 호출하기 전에 무엇이 존재하는지 확인하는 데 유용합니다.

campaign_diagnostics

arm별 학습 상태를 검사합니다: theta_norm, 예측 횟수, 보상 비율, 엔트로피 헬스. 캠페인이 학습되지 않거나 한 arm이 지배적인 것 같을 때 사용하세요.

campaign_report

비즈니스 수준 수렴 보고서입니다. 캠페인이 통계적으로 수렴했는지, 신뢰구간과 함께 어떤 arm이 이기고 있는지 알려줍니다.

get_intuition

주어진 컨텍스트에 대해 BanditDB에 어떤 arm을 선택할지 묻습니다. arm과 저장할 interaction_id를 반환합니다.

batch_get_intuition

단일 왕복으로 여러 캠페인에 대한 결정을 얻습니다. {campaign_id, context} 딕셔너리 목록을 전달하세요.

record_outcome

선택한 행동이 성공(1.0)했는지 실패(0.0)했는지 보고합니다. 공유 모델을 업데이트합니다.

archive_campaign

캠페인을 소프트 삭제합니다. 예측/보상을 일시 중지하지만 학습된 모든 가중치는 보존합니다.

restore_campaign

보관된 캠페인을 모든 가중치를 유지한 채 활성 상태로 복원합니다.

네트워크의 모든 에이전트가 내린 모든 결정은 향후 모든 에이전트의 라우팅을 개선합니다.


3. 데이터 사이언스 및 오프라인 평가

BanditDB는 모든 예측과 보상을 Write-Ahead Log(WAL)에 이벤트 소싱합니다. checkpoint()를 호출하면 완료된 예측→보상 쌍을 Polars 또는 Pandas로 오프라인 분석할 수 있도록 캠페인별로 하나씩 Snappy 압축 Parquet 파일로 컴파일합니다.

보상이 몇 시간 후에 도착하더라도 모든 예측이 Parquet 파일에 나타나는 것이 보장됩니다: BanditDB는 각 체크포인트에서 진행 중인 상호작용을 재발행하므로 지연된 보상은 항상 향후 주기에 캡처됩니다.

# Checkpoint: snapshot models, write Parquet, rotate the WAL.
# Call this on a schedule or after significant traffic.
summary = db.checkpoint()
print(summary)
# "Checkpoint written and WAL rotated: 2 campaigns, offset 4821 bytes,
#  150 interactions exported, 3 in-flight re-emitted"

# List which Parquet files are available
print(db.export())
# 'Parquet files in /data/exports: ["llm_routing.parquet"]'

# Load directly from the mounted volume into Polars.
# Flat schema: interaction_id | arm_id | reward | predicted_at | rewarded_at | propensity | feature_0 | ...
import polars as pl
df = pl.read_parquet("/data/exports/llm_routing.parquet")
print(df.head())
print(df.columns)

오프라인 정책 평가(OPE)

SDK는 banditdb.eval에 세 가지 OPE 추정기를 제공합니다. 이들은 다음 질문에 답합니다: "라이브 실험을 실행하지 않고 다른 정책 하에서 내 평균 보상이 어땠을까?"

평가 종속성을 설치하세요:

pip install "banditdb-python[eval]"

추정기

함수

작동 방식

사용 시기

Replay

replay(df)

각 상호작용을 확률 (1/K) / propensity로 수락합니다(Li et al. 2010). 균일 무작위 정책의 편향되지 않은 표본입니다.

기준선(sanity check)입니다. 낮은 커버리지가 예상됩니다 — 상호작용의 약 1/K만 사용됩니다.

IPS / SNIPS

ips(df, clip=10.0)

중요도 가중치 (1/K) / propensity로 모든 상호작용을 사용합니다. 분산을 줄이기 위해 자기 정규화됩니다. 가중치 클리핑(기본 10배)은 편향-분산 트레이드오프를 제어합니다.

기본 추정기입니다. 데이터가 충분하지만 전체 커버리지를 원할 때 사용하세요.

Doubly Robust

doubly_robust(df, clip=10.0)

선형 보상 모델을 피팅한 다음 잔차에 IPS 보정을 적용합니다. 보상 모델 또는 propensity 중 하나가 정확하면 일관성이 있습니다.

최상의 통계적 효율성입니다. 여러 정책을 비교하거나 alpha를 스윕할 때 사용하세요.

세 가지 추정기 모두:

  • BanditDB Parquet 내보내기에서 로드된 Polars 또는 pandas DataFrame 허용

  • 균일 무작위 정책을 대상으로 평가(이겨야 할 편향 없는 기준선)

  • Thompson Sampling 캠페인의 경우 ValueError 발생(성향 열이 null — TS는 성향을 기록하지 않음)

  • estimate, std_error, n_used, n_total, method를 포함한 OPEResult 반환

import polars as pl
from banditdb.eval import replay, ips, doubly_robust

df = pl.read_parquet("/data/exports/llm_routing.parquet")

# How much reward would a uniform random policy have earned?
print(replay(df))
# OPEResult(method='replay', estimate=0.4821, std_error=0.0312, coverage=22.1% [33/149])

print(ips(df))
# OPEResult(method='ips', estimate=0.5103, std_error=0.0187, coverage=100.0% [149/149])

print(doubly_robust(df))
# OPEResult(method='doubly_robust', estimate=0.5219, std_error=0.0141, coverage=100.0% [149/149])

# Compare against the observed reward of the logging policy:
print("Observed (logging policy):", df["reward"].mean())
# If observed >> estimate, the campaign has learned something real — it outperforms random.

실용적 활용: 배포 전에 alpha를 오프라인으로 스윕하세요. 실제 트래픽으로 캠페인을 훈련하고 Parquet로 체크포인트한 다음, doubly_robust()를 통해 서로 다른 alpha 값을 재생하여 최적의 탐색 수준을 찾으세요 — 라이브 실험이 필요 없습니다.

참고: OPE에는 propensity 열이 필요하며, 이 열은 LinUCB 캠페인에만 기록됩니다. Thompson Sampling 캠페인은 null 성향을 기록하는데, 이는 TS 팔 선택이 확률적이고 성향 점수 산정에는 결정적 로깅 정책이 필요하기 때문입니다.


알고리즘 선택

BanditDB는 캠페인 생성 시 선택할 수 있는 네 가지 알고리즘을 지원합니다.

알고리즘

algorithm

탐색 방식

사용 시기

LinUCB

"linucb" (기본값)

결정적 UCB 보너스: θ·x + α√(x·A⁻¹·x)

예측 가능하고 조정 가능. alpha를 오프라인으로 스윕하여 보정.

Linear Thompson Sampling

"thompson_sampling"

θ̃ ~ N(θ, α²·A⁻¹) 샘플링, θ̃·x로 점수 산정

베이지안 사후 분포 — alpha 스윕 불필요. 동시 사용자가 자동으로 선택을 다양화.

NeuralLinUCB

NeuralLinUCBConfig(...)

딥 MLP 임베딩 + 임베딩 공간에서의 LinUCB

비선형 보상 함수. N개의 보상마다 MLP를 재훈련.

Progressive

ProgressiveConfig(...)

자동 튜닝 토너먼트: 기본 + 도전자를 병렬 실행, 승자에게 트래픽 이동

제로 구성 모델 선택. 최적의 알고리즘을 자동으로 선택.

from banditdb import Client, NeuralLinUCBConfig, ProgressiveConfig

db = Client("http://localhost:8080")

# LinUCB (default)
db.create_campaign("routing", ["fast", "cheap"], feature_dim=4, alpha=1.5)

# Thompson Sampling — natural Bayesian exploration, alpha=1.0 is ideal
db.create_campaign("routing_ts", ["fast", "cheap"], feature_dim=4,
                   algorithm="thompson_sampling")

# NeuralLinUCB — learns a deep embedding of the context, then applies LinUCB
cfg = NeuralLinUCBConfig(
    context_dim=4,     # must match feature_dim
    embed_dim=32,      # arm matrix dimension (default 32)
    hidden_dim=128,    # MLP hidden layer width (default 128)
    retrain_every=200, # retrain the MLP every N cumulative rewards
)
db.create_campaign("routing_neural", ["fast", "cheap"], feature_dim=4, algorithm=cfg)

# Progressive — runs LinUCB vs NeuralLinUCB, shifts traffic to whoever wins SNIPS checkpoints
cfg = ProgressiveConfig(
    base="linucb",
    challenger=NeuralLinUCBConfig(context_dim=4, embed_dim=32),
    min_obs=100,       # minimum buffer entries per arm before any traffic shift
    required_wins=3,   # consecutive checkpoint wins to earn one traffic step
    step_bps=1000,     # traffic delta per win run, in basis points (1000 = 10%)
)
db.create_campaign("routing_prog", ["fast", "cheap"], feature_dim=4, algorithm=cfg)

네 가지 알고리즘 모두 동일한 predictreward 루프를 공유합니다.


오류 처리

예외

발생 시점

BanditDBError

기본 예외 — 모든 SDK 오류를 처리하려면 이를 포착하세요.

ConnectionError

서버가 오프라인이거나 연결할 수 없음.

TimeoutError

요청이 구성된 제한 시간을 초과함.

APIError

서버가 오류를 반환함(예: 캠페인을 찾을 수 없음, 권한 없음).


라이선스

Apache-2.0 — Copyright (C) 2026 Simeon Lukov and Dynamic Pricing Ltd. 자세한 내용은 메인 저장소를 참조하세요.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

No tool schema history has been recorded yet.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/dynamicpricing-ai/banditdb-python'

If you have feedback or need assistance with the MCP directory API, please join our Discord server