Skip to content
Projects

whitecircle/whitecircle-python

View on GitHub

About

Official Python SDK for the White Circle API: check messages, tool calls, agent steps and images against your Policies

Design & Media

How these counts are measured

Measured star growth

in 24h
Collecting history
in 7 days
Collecting history
in 15 days
Collecting history
in 1 month
Collecting history

Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.

README.md

Original

White Circle Python SDK

PyPI CI

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.

Explore related projects

Loading…