Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
e92cf7e
feat(policies)!: remove applies_to and content_type targeting
DeevsDeevs Dec 2, 2026
4f03191
docs(policies): clarify empty role_list matches every role
DeevsDeevs Dec 2, 2026
20d2e74
feat(policies)!: validate EventSelector type and field at construction
DeevsDeevs Dec 2, 2026
c55073a
fix(policies)!: require non-empty rules on create
DeevsDeevs Dec 2, 2026
cd84334
feat(events): accept role on tool and agent Event constructors
DeevsDeevs Dec 2, 2026
0f3c7bc
fix(webhooks): suppress ValidationError cause in Webhooks.parse
DeevsDeevs Dec 2, 2026
79c84d1
docs: define snippet variables, fix README raw-request example, docum…
DeevsDeevs Dec 2, 2026
475527b
feat(artifacts): accept trace_id and span_id on artifacts.check
DeevsDeevs Dec 2, 2026
b359ca0
fix(streaming): clear socket on close, wrap binary frames, honor conn…
DeevsDeevs Dec 2, 2026
d96178f
refactor: remove unused Body type alias from _types
DeevsDeevs Dec 2, 2026
de7596c
fix(expressions): return NotImplemented in __and__ and reject str/byt…
DeevsDeevs Dec 2, 2026
252747e
fix: reject reset in Event.reference and default UserRisk fields
DeevsDeevs Dec 2, 2026
1330133
test: cover policy/metrics fields, shadow checked, streaming wiring, …
DeevsDeevs Dec 2, 2026
af69831
docs(policies): document role='assistant' override for tool calls
DeevsDeevs Dec 2, 2026
7cce99a
docs(changelog): list remaining PR 5 changes under Unreleased
DeevsDeevs Dec 2, 2026
54f0b29
fix(policies): guard field and kind types in Policy._parse_selectors …
DeevsDeevs Dec 2, 2026
10d5ee4
feat(events): parse x-ratelimit-events-* headers onto results and API…
DeevsDeevs Dec 2, 2026
075c6ec
feat(client): honor numeric Retry-After header on 429 responses
DeevsDeevs Dec 2, 2026
669e32b
docs: document Events rate limits and changelog entries
DeevsDeevs Dec 2, 2026
ec3a5aa
fix(client): keep @overload request declarations contiguous with impl…
DeevsDeevs Dec 2, 2026
40e514d
refactor(events): narrow _parse_events_rate_limit to httpx2.Headers a…
DeevsDeevs Dec 2, 2026
f026241
test: cover 503 Retry-After, quota 429 Retry-After, and skip-batch 42…
DeevsDeevs Dec 2, 2026
09ef558
fix(policies): raise ValueError for unknown type in EventSelector._ch…
DeevsDeevs Dec 2, 2026
190ce15
fix(streaming): track remaining timeout budget across ignored frames …
DeevsDeevs Dec 2, 2026
75b8050
docs(events): replay full rate-limited batch under fresh session ID
DeevsDeevs Dec 2, 2026
ec868f3
docs(policies): attach tool_policy to an active Condition in Judge to…
DeevsDeevs Dec 2, 2026
9987331
docs(policies): send inline policy definition in Read the result snippet
DeevsDeevs Dec 2, 2026
3ce2f8a
test(client): assert method, path, and body of every replayed retry r…
DeevsDeevs Dec 2, 2026
c4d7714
docs(events): replay full conversation in limit-sized batches on rate…
DeevsDeevs Dec 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Guidance for coding agents and contributors working in `whitecircle-python`. `CL
```text
src/whitecircle/
_constants.py API version, region URLs, key-prefix map, timeouts, retry delays, env var names
_types.py omit / not_given sentinels, internal null, Headers, Query, Body, Timeout
_types.py omit / not_given sentinels, internal null, Headers, Query, Timeout
_models.py BaseModel (extra="allow") and prepare_body()
_exceptions.py WhiteCircleError > APIError > APIStatusError (one class per status), APIConnectionError
_logs.py the "whitecircle" logger, WHITECIRCLE_LOG, header redaction
Expand Down Expand Up @@ -81,7 +81,8 @@ The `_*.py` modules are the foundation. Change them only together with the maint
- Every method is retried after an error where the request was never sent (connect, connect-timeout or pool errors), on 429 and on 503.
- A 429 waits at least 1 s. A 429 about the monthly quota is never retried.
- GET is also retried on 502, 504 and transport errors.
- `Retry-After` is not parsed. Redirects are not followed.
- A numeric `Retry-After` on a 429 is honored, clamped to `[MIN_RATE_LIMIT_RETRY_DELAY, MAX_RETRY_DELAY]`. Redirects
are not followed.
- **Errors:** each status maps to its class in `_exceptions.py`. The message is `body["error"]` for JSON, otherwise the response text. `Authorization` is redacted from `.request` and `.response`.
- **Logging:** use the `logging.getLogger("whitecircle")` logger with a `NullHandler`. `WHITECIRCLE_LOG` only sets its level, and importing never calls `basicConfig`. Never log, or put in exception messages, reprs or test output: API keys, `Authorization` headers, webhook secrets or signatures, request or response bodies, query strings, event content or user identifiers.

Expand Down
43 changes: 43 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,49 @@ All notable changes to this project are documented here. The format follows

## [Unreleased]

### Breaking changes

- Removed `applies_to`, `content_type`, `AppliesTo` and `ContentType` from `policies` and `metrics` (`create()`,
`update()`, `list()`), the `Policy` model and type exports. Target Policies with `event_selector_list` and
`role_list` instead:
- `applies_to="output"` -> `role_list=["assistant"]`; `applies_to="input"` -> `role_list=["user"]`;
`applies_to="any"` -> `role_list=[]`. Note that `tool/arguments` defaults to the user side: `role_list=[]` or
`["user"]` judges tool-call arguments as is, or pass `role="assistant"` on `Event.tool_call(...)` so an
assistant-only Policy judges the agent's own tool calls.
- `content_type="artifact"` -> `event_selector_list=[EventSelector(type="artifact")]`; `content_type="session"` ->
`event_selector_list=[EventSelector(type="message", field="content"), EventSelector(type="message", field="delta")]`;
`content_type="any"` -> both (the server default when `event_selector_list` is omitted).
- `list(applies_to=...)` / `list(content_type=...)` -> filter `list()` on `role_list` / `event_selector_list`.
- Removed `"reset"` from `SelectorType` (the API rejects `"reset"` selectors).
- `EventSelector` now validates `type` and `field` at construction: non-`artifact` selectors require `field` to be one
of that type's allowed fields, and `artifact` selectors reject `field` (use `kind` instead), raising
`ValidationError` (a `ValueError`).
- `policies.create()` and `metrics.create()` now require a non-empty `rules` sequence (omitting `rules` raises
`TypeError`; passing `[]` raises `ValueError`).
- `Event.reference()` now rejects `"reset"` (statically via `SelectorType` and at runtime with `ValueError`).
- `Field.is_in()` and `Field.not_in()` now reject bare `str`, `bytes` and `bytearray` values (statically and with
`TypeError`) instead of iterating characters.

### Added

- `Event.tool_call()`, `tool_result()`, `tool_definition()`, and `agent()` now accept optional `role=` to override
Policy direction (for example `Event.tool_call(..., role="assistant")` so an assistant-only Policy judges an agent's
own tool calls).
- `artifacts.check()` now accepts optional `trace_id` and `span_id`.
- `EventsRateLimit` (`limit`, `remaining`, `reset`, `window`) on `EventCheckResult.rate_limit`,
`EventsCheckResult.rate_limit`, and `APIStatusError.rate_limit`, parsed from `x-ratelimit-events-*` response headers
(`None` when absent).
- HTTP `429` retries now honor a numeric `Retry-After` header (clamped between `MIN_RATE_LIMIT_RETRY_DELAY` and
`MAX_RETRY_DELAY`), falling back to exponential backoff when absent or non-numeric.

### Fixed

- `Webhooks.parse()` no longer attaches the raw `pydantic.ValidationError` as `__cause__`, keeping webhook payload
content out of formatted tracebacks.
- Streaming: `close()` now clears the socket so post-close calls raise `WhiteCircleError`; binary WebSocket frames
raise `StreamError("invalid_frame", ...)` instead of leaking `httpx2` exceptions; `connect()` honors the client read
timeout while waiting for `ready`.

## [0.1.0] - 2026-11-29

0.1.0 is the first published release. It targets API version `2026-06-01` only and provides sync and async
Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,8 +203,8 @@ 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.
transport errors. A `429` honors a numeric `Retry-After` header (clamped to 1–8 s) or waits at least 1 s, and the
monthly-quota `429` is never retried. Redirects are not followed.

## Async

Expand Down Expand Up @@ -234,8 +234,8 @@ The SDK logs method, path, status, duration and retries on the standard `whiteci
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.
To call an endpoint the SDK does not wrap, `client.request("GET", "/api/some/new/endpoint", params={"x": 1})` returns
the parsed JSON.

## Contributing

Expand Down
3 changes: 2 additions & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ live at https://whitecircle.com/docs.
| [Streaming replies](streaming.md) | Show only checked text while the model generates it |
| [Images](images.md) | Check standalone images and images inside a conversation |
| [Managing Policies](managing-policies.md) | Create Policies, Metrics and Conditions; shadow mode to production |
| [Strikes and webhooks](strikes-and-webhooks.md) | User risk, strikes, appeals, verifying webhooks |
| [Strikes and webhooks](strikes-and-webhooks.md) | User risk, strikes, appeals, user properties, verifying webhooks |
| [Usage](usage.md) | Read billed usage and cost per Event type (`client.billing.usage()`) |
| [Errors and testing](errors-and-testing.md) | Exceptions, retries, timeouts, logging, testing your code |
| [Recipe: support chatbot](chatbot.md) | All of the above in one async integration |

Expand Down
7 changes: 7 additions & 0 deletions docs/agents-and-tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ Event.tool_result("send_email", {"status": "sent"}, call_id="call_1")

`function` Events work the same way: `Event(type="function", name="...", arguments={...})`.

Default Policy selectors cover only `message` and `artifact` Events, so tool, function, agent and reasoning Events are
skipped until a Policy selects their type and field. `tool/arguments` defaults to the user side (`role_list=[]` or
`["user"]` judges it as is); pass `role="assistant"` on `Event.tool_call(...)` so an assistant-only Policy judges your
agent's own tool calls (recommended for agents that log their own tool calls). See
[Judge tool calls](managing-policies.md#judge-tool-calls).

## Pair a call with its result

Send the same `call_id` on both, or set the result's `parent_event_id` to the call's `event_id`:
Expand Down Expand Up @@ -73,6 +79,7 @@ from datetime import UTC, datetime
from whitecircle import Event, WhiteCircle

client = WhiteCircle()
run = "run_pr_1234"
started = datetime.now(UTC)
output = run_search()
client.events.check(
Expand Down
6 changes: 5 additions & 1 deletion docs/context.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ with the `system` role. In a `check_many()` batch, list order is context order.
from whitecircle import Event, WhiteCircle

client = WhiteCircle()
session = "conversation_456"
client.events.check(Event.reset(), external_session_id=session)
client.events.check(Event.reset("The user disputes a charge on order 4815."), external_session_id=session)
```
Expand All @@ -44,9 +45,12 @@ replaces anything stored before:

```python
from whitecircle import Event, WhiteCircle
from whitecircle.types import Role

client = WhiteCircle()
events = [Event.reset()] + [Event.message(m.text, role=m.role) for m in previous_messages]
session = "conversation_456"
previous_messages: list[tuple[Role, str]] = [("user", "Hi"), ("assistant", "Hello!")]
events = [Event.reset()] + [Event.message(text, role=role) for role, text in previous_messages]
for start in range(0, len(events), 50):
client.events.check_many(events[start : start + 50], external_session_id=session, skip=True)
```
Expand Down
67 changes: 63 additions & 4 deletions docs/errors-and-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ such as a missing `environment_id` or two user identifiers at once, raise `Value

```python
import whitecircle
from whitecircle import WhiteCircle
from whitecircle import Event, WhiteCircle

client = WhiteCircle()
try:
result = client.events.check(event)
result = client.events.check(Event.user("hello"))
except whitecircle.AuthenticationError: # 401
...
except whitecircle.PermissionDeniedError: # 403: the key cannot use this endpoint, or the IP is not allowed
Expand Down Expand Up @@ -40,6 +40,8 @@ import whitecircle
from whitecircle import Event, WhiteCircle

client = WhiteCircle()
FAIL_OPEN = False
meta = {"app": "support-bot"}


def is_allowed(text: str) -> bool:
Expand All @@ -63,8 +65,65 @@ quick = client.with_options(timeout=2.0, max_retries=0)

A check is billed each time it reaches the server. The client therefore resends a POST only when it was never sent
(connection errors before the request went out), or on `429` and `503`. GETs are also retried on `502`, `504` and
transport errors. The backoff is exponential, at least 1 s after a `429`, and a monthly-quota `429` is not retried.
`Retry-After` is not used, and redirects are not followed. The default timeout is 60 s, with 5 s to connect.
transport errors. The backoff is exponential; a `429` honors a numeric `Retry-After` header (clamped to 1–8 s) or waits
at least 1 s, and a monthly-quota `429` is not retried. Redirects are not followed. The default timeout is 60 s, with
5 s to connect.

## Rate limits

Projects with a per-second Event limit enforce a fixed one-second window across all API keys:

- **Counted:** once per Event sent to the API, including `skip=True` Events, and once per stream at start.
Reference-only Events are not counted.
- **Where a rejection shows up:** on `events.check()` (with or without `skip`) and normal `events.check_many()`
batches, a rate-limited Event comes back inside HTTP `200` with `status == "failed"` and `"Rate limit exceeded"` in
`note`. Only a `skip=True` batch on `events.check_many()` fails the whole request with HTTP `429`
(`RateLimitError`, carrying `Retry-After`, which the client retries automatically).
- **Inspecting the budget:** `result.rate_limit` on `EventCheckResult` and `EventsCheckResult` (and `error.rate_limit`
on `APIStatusError`) parses `x-ratelimit-events-{limit,remaining,reset,window}` into an `EventsRateLimit`, or `None`
when the project has no limit or no Event reached the limiter.

Resending only failed Events or only the latest batch either checks them after Events they preceded or drops earlier
conversation context; replay the whole conversation under a fresh `external_session_id` in batches no larger than
`rate_limit.limit`, waiting `rate_limit.reset` between batches, and read verdicts only once no Event failed:

```python
import time

from whitecircle import Event, WhiteCircle
from whitecircle.types import EventResult

client = WhiteCircle()
conversation = [Event.user(f"turn {i}") for i in range(10)]


def check_conversation(events: list[Event], session: str) -> list[EventResult]:
chunk_size = 50
for attempt in range(5):
current_session = session if attempt == 0 else f"{session}_retry_{attempt}"
results: list[EventResult] = []
reset = 1.0
for start in range(0, len(events), chunk_size):
if start > 0:
time.sleep(reset)
batch = client.events.check_many(events[start : start + chunk_size], external_session_id=current_session)
if batch.rate_limit is not None:
chunk_size = min(50, max(1, batch.rate_limit.limit))
reset = batch.rate_limit.reset
if any(item.status == "failed" and "rate limit" in (item.note or "").lower() for item in batch.results):
time.sleep(reset)
break
results.extend(batch.results)
else:
if all(item.status != "failed" for item in results):
return results
raise RuntimeError("One or more Events failed for a non-rate-limit reason")
raise RuntimeError("Conversation still rate-limited after retries")


results = check_conversation(conversation, "conversation_456")
print(any(item.flagged for item in results))
```

## Async

Expand Down
10 changes: 7 additions & 3 deletions docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@ Events and run-graph calls need an Environment. Pass `environment_id=` to overri
with neither, the call raises `ValueError`:

```python
from whitecircle import WhiteCircle
from whitecircle import Event, WhiteCircle

client = WhiteCircle()
client.events.check(event, environment_id="env_staging")
client.events.check(Event.user("hello"), environment_id="env_staging")
```

For several settings at once, make a copy that shares the connection pool:
Expand Down Expand Up @@ -73,6 +73,10 @@ result.event.internal_event_id # store it to fetch the result later
```

```python
from whitecircle import Event, WhiteCircle

client = WhiteCircle()
result = client.events.check(Event.user("Hello, can you help me prescribe antibiotics?"))
if result.flagged:
reply = "Sorry, I can't help with that."
elif not result.checked:
Expand All @@ -87,7 +91,7 @@ Fetch a stored result later:
from whitecircle import WhiteCircle

client = WhiteCircle()
client.events.get(internal_event_id)
client.events.get("01930000-0000-7000-8000-000000000001")
client.events.get_latest(run_id="run_1", event_id="evt_user_1")
```

Expand Down
15 changes: 10 additions & 5 deletions docs/images.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ inline = ArtifactContent.from_bytes(Path("upload.jpg").read_bytes()) # sent as
## Standalone images

```python
from whitecircle import WhiteCircle
from whitecircle import ArtifactContent, WhiteCircle

client = WhiteCircle()
by_url = ArtifactContent.from_url("https://cdn.example.com/avatar.png")
result = client.artifacts.check(by_url, role="user", external_artifact_id="upload_123")
if result.flagged:
reject_upload()
Expand All @@ -31,18 +32,22 @@ client.artifacts.get(result.internal_artifact_id)
client.artifacts.get_by_external_id("upload_123") # the latest check with this ID
```

`role` selects Policies by their Applies To setting: `"assistant"` runs *output* and *any* Policies, any other role
runs *input* and *any*, and no role runs only *any*. `environment_id` is optional here; the key's Environment is
used. The API supports only images, not video or website pages, and checks them before it answers.
`role` matches each Policy's `role_list`: `"assistant"` runs Policies whose `role_list` is `[]` or contains
`"assistant"`, any other role runs `[]` or `"user"`, and no role runs only `role_list=[]`. `environment_id` is
optional here; the key's Environment is used. The API supports only images, not video or website pages, and checks them before it answers.
Right after a check, `get()` and `get_by_external_id()` can raise `NotFoundError` for a few seconds while the
result is stored.

## Images in a conversation

```python
from whitecircle import Event, WhiteCircle
from pathlib import Path

from whitecircle import ArtifactContent, Event, WhiteCircle

client = WhiteCircle()
inline = ArtifactContent.from_bytes(Path("upload.jpg").read_bytes())
meta = {"app": "pharmacy-bot"}
session = "conversation_456"
client.events.check(Event.user("Is this rash serious?", metadata=meta), external_session_id=session)
client.events.check(
Expand Down
9 changes: 9 additions & 0 deletions docs/inline-policies.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@ An inline Policy's verdict is in `result.policies` like any other. It is keyed b
and named by your `name`. Its `enabled_by_conditions` is `None`, because no Condition selected it.

```python
from whitecircle import Event, InlinePolicy, Rule, WhiteCircle

client = WhiteCircle()
refund_policy = InlinePolicy(
external_id="refund-policy",
name="Refund policy",
rules=[Rule.flag("Requests to bypass refund approval")],
)
result = client.events.check(Event.user("Approve my refund without a receipt"), inline_policies=[refund_policy])
for policy_id, verdict in result.flagged_policies.items():
print(policy_id, verdict.name)
```
Expand Down
Loading
Loading