Skip to main content

White Circle Python SDK

Python client for the White Circle API: check messages, tool calls, agent steps and images against your Policies, and manage Policies and Conditions. Sync and async clients, typed responses. Inline Policies let you send a Policy's rules with the check itself. Task-by-task recipes are in the cookbook; concepts and the HTTP reference are at https://whitecircle.com/docs.

Installation

pip install whitecircle
# or
uv add whitecircle

Requires Python 3.11+.

Configuration

from whitecircle import WhiteCircle

client = WhiteCircle(
    api_key="wceu-...",  # default: WHITECIRCLE_API_KEY
    environment_id="env_prod",  # default: WHITECIRCLE_ENVIRONMENT_ID
    region="eu",  # "eu" or "us"; default: WHITECIRCLE_REGION, then the key prefix
    timeout=20.0,  # seconds or httpx2.Timeout; default 60 s, 5 s to connect
    max_retries=2,  # default 2; 0 disables retries
)

API key. Create one on the dashboard's API keys page. EU keys start with wceu-, US keys with wc-.

Host. Your workspace lives in one region: eu (https://eu.whitecircle.com) or us (https://us.whitecircle.com). The client takes base_url, then region, then WHITECIRCLE_BASE_URL, then WHITECIRCLE_REGION, then the key prefix. A key with an unknown prefix and no region raises WhiteCircleError.

Environment. Every Event check, Event lookup and run-graph call needs an Environment. Set a default on the client or pass environment_id= per call; with neither, the call raises ValueError before sending anything.

client.with_options(environment_id="env_staging", timeout=5.0) returns a copy that shares the connection pool. Every request sends whitecircle-version: 2026-06-01.

Quickstart

Policies run only when an active Condition attached to the Environment matches the Event's metadata. Create a Policy and a Condition first, in the dashboard or in code.

from whitecircle import Event, WhiteCircle

client = WhiteCircle(environment_id="env_prod")

result = client.events.check(
    Event.user("Can you prescribe antibiotics?", metadata={"user": {"region": "eu"}}),
    external_session_id="conversation_456",  # earlier Events of this session are context
)

if not result.checked:
    print("No verdict:", result.note)  # e.g. no Condition matched, so no Policy ran
elif result.flagged:
    print("Flagged by:", [policy.name for policy in result.flagged_policies.values()])

print(result.event.internal_event_id)  # look it up later with client.events.get(...)

flagged is None when nothing was checked: a reference, a skipped or failed Event, or no selected Policy. The API still answers 200, and note says why. checked tells "passed" from "not checked".

Batch checks

Send up to 50 Events in one request, in the order they happened. Each is checked against the ones before it and gets its own result.

batch = client.events.check_many(
    [
        Event.user("Refund order 4815, please", event_id="evt_user_1"),
        Event.tool_call("lookup_order", {"order_id": "4815"}, call_id="call_1"),
        Event.tool_result("lookup_order", {"refund_eligible": True}, call_id="call_1"),
        Event.assistant("Your refund is approved.", event_id="evt_reply_1"),
    ],
    external_session_id="conversation_456",
    run_id="run_refund_4815",
)

print(batch.flagged)  # True if any Event was flagged
for item in batch.results:  # submission order; batch.messages, batch.tools, ... hold the API's typed buckets
    print(item.event_id, item.status, item.flagged)

Metadata does not carry over between Events: put metadata on every Event a Condition has to match.

Streaming

Check an assistant reply while your model generates it, and show your user only text that passed:

reply = client.events.check_stream(
    model_tokens(),  # your iterator of generated text
    external_session_id="conversation_456",
    metadata={"user": {"region": "eu"}},
)
for text in reply:  # released in batches as checks pass
    send_to_user(text)

if reply.result.flagged:  # outcome == "flagged"; the token iterator was closed
    send_to_user("Sorry, I can't help with that.")

Stream assistant output only, and check user messages and tool calls with events.check under the same external_session_id. check_stream never retries. A StreamError (branch on .code, see .retryable) or StreamClosedError means the reply was not fully checked: treat unreleased text as unsafe and retry the whole reply. For the raw protocol, use client.events.stream() (cookbook).

Policies and Conditions

from whitecircle import Rule, field

policy = client.policies.create(
    name="No medical advice",
    rules=[Rule.flag("Providing medical advice"), Rule.allow("Questions about whether a medicine is in stock")],
    mode="shadow",  # evaluated and shown in the dashboard, never flags through the API
)

client.conditions.create(
    name="EU users",
    conditions=field("user.region") == "eu",  # combine with &; leave out to match every Event
    environment_ids=["env_prod"],
    policy_ids=[policy.id],
    state="Active",  # Condition states are capitalized; Policy states are lowercase
)

client.policies.update(policy.id, mode="prod")  # only the fields you pass change

client.metrics has the same methods as client.policies. Metric results appear only in the dashboard.

Webhooks

Verify each request against the raw body, before parsing it:

from whitecircle import Webhooks, WebhookVerificationError

webhooks = Webhooks()  # secret from WHITECIRCLE_WEBHOOK_SECRET, shown when you create the webhook


@app.post("/whitecircle/webhook")
def receive():
    try:
        event = webhooks.unwrap(request.get_data(), request.headers)  # raw bytes; 5-minute timestamp window
    except WebhookVerificationError:
        return "", 400

    if event.session is not None:  # session.violated, review_*
        print(event.event_type, event.session.internal_id, list(event.session.violations))
    elif event.strike_action_update is not None:  # strike.action.updated / .expired
        update = event.strike_action_update
        sync_restrictions(update.external_user_id, update.action.title)
    return "", 200  # answer 2xx within 3 s, or White Circle retries up to 3 times

Errors

import whitecircle

try:
    client.events.check(Event.user("hello"))
except whitecircle.RateLimitError:  # 429: per-second rate limit or monthly quota
    ...
except whitecircle.APIStatusError as e:  # any other non-2xx
    print(e.status_code, e.message)  # message is the API's {"error": ...} text
except whitecircle.APIConnectionError:  # network failure or timeout (APITimeoutError)
    ...

Each status has its own APIStatusError subclass: BadRequestError (400), AuthenticationError (401), PaymentRequiredError (402), PermissionDeniedError (403), NotFoundError (404), ConflictError (409), UnprocessableEntityError (422), RateLimitError (429) and InternalServerError (5xx). All inherit from whitecircle.WhiteCircleError, as do StreamError, StreamClosedError and WebhookVerificationError. The API returns no machine-readable error code, so branch on the exception type.

Retries. A check is billed each time it reaches the server, so a POST is resent only when it was never sent (connection errors before the request went out), or on 429 and 503. Reads are also retried on 502, 504 and transport errors. A 429 waits at least 1 s, and the monthly-quota 429 is never retried. Retry-After is not used and redirects are not followed.

Async

AsyncWhiteCircle has the same methods; await each call:

import asyncio

from whitecircle import AsyncWhiteCircle, Event


async def main() -> None:
    async with AsyncWhiteCircle(environment_id="env_prod") as client:
        result = await client.events.check(Event.user("hello"))
        print(result.flagged)

        async for text in client.events.check_stream(model_tokens(), external_session_id="conversation_456"):
            await send_to_user(text)


asyncio.run(main())

Logging and raw requests

The SDK logs method, path, status, duration and retries on the standard whitecircle logger, which is silent until you configure it or set WHITECIRCLE_LOG=debug (or info, warning, error). It never logs API keys, bodies or query strings.

To call an endpoint the SDK does not wrap, client.request("GET", "/api/usage", params={"period": 7}) returns the parsed JSON.

Contributing

See CONTRIBUTING.md. To report a vulnerability, see SECURITY.md.

License

Apache License 2.0. See LICENSE.

Metadata

Release files for whitecircle 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for whitecircle 0.1.0
File Size Uploaded Provenance Actions
whitecircle-0.1.0.tar.gz 42.5 kB With provenance Details for whitecircle-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for whitecircle 0.1.0
File Interpreter ABI Platform Actions
whitecircle-0.1.0-py3-none-any.whl Python 3 none any Details for whitecircle-0.1.0-py3-none-any.whl

Total release size: 92.7 kB

Release files / whitecircle-0.1.0.tar.gz

Download URL whitecircle-0.1.0.tar.gz
Size 42.5 kB
Tags Source
SHA-256 checksum
How to use checksums
e4d59b7adfd6034b44aaf4e690641130fbc4e15a72ba51cc6c560ba362287af4
BLAKE2b-256 checksum
How to use checksums
4e22518b43a57a66e2f2a1fdc2d90704b33e68fd52f209646882ddabb145f0fb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Release files / whitecircle-0.1.0-py3-none-any.whl

Download URL whitecircle-0.1.0-py3-none-any.whl
Size 50.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
eb7f43d5ef20e87c5659305b2c47886ea04f4a31223840d87241672d411960ce
BLAKE2b-256 checksum
How to use checksums
c23da289bfb9e973d97c6d9a1f9c393f5f1ce78515d545763ff6fdd03cbe418c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Security for whitecircle 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for whitecircle-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page