Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion 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
25 changes: 23 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ All notable changes to this project are documented here. The format follows
`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 `role_list=["assistant"]` excludes tool-call arguments today; use
`role_list=[]` (or avoid restricting to `["assistant"]`) to judge `tool/arguments`.
`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).
Expand All @@ -21,6 +22,26 @@ All notable changes to this project are documented here. The format follows
- `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`.

### 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

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
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: 5 additions & 2 deletions docs/agents-and-tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ 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 (and does not restrict `role_list` to `["assistant"]` for
`tool/arguments`). See [Judge tool calls](managing-policies.md#judge-tool-calls).
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

Expand Down Expand Up @@ -77,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
6 changes: 4 additions & 2 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 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
9 changes: 7 additions & 2 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 @@ -40,9 +41,13 @@ 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
6 changes: 6 additions & 0 deletions docs/inline-policies.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ 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, WhiteCircle

client = WhiteCircle()
result = client.events.check(
Event.user("Approve my refund without a receipt"), inline_policies=[InlinePolicy.ref("refund-policy")]
)
for policy_id, verdict in result.flagged_policies.items():
print(policy_id, verdict.name)
```
Expand Down
16 changes: 10 additions & 6 deletions docs/managing-policies.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ At least one rule must flag. Two fields decide which Events a Policy evaluates:

## Judge tool calls

Tool Events are skipped unless you select them explicitly. Today, the API classifies tool-call arguments on the user
side, so `role_list=["assistant"]` checks assistant messages and `tool/output` but skips `tool/arguments`. To judge
tool-call arguments alongside assistant replies and tool outputs, avoid restricting `role_list` to `["assistant"]`
(use `role_list=[]`):
Tool Events are skipped unless you select them explicitly. By default, `tool/arguments` is classified on the user side,
so `role_list=[]` or `["user"]` judges tool-call arguments as they are while `role_list=["assistant"]` skips them. To
have an assistant-only Policy judge your agent's own tool calls (without also judging user messages), pass
`role="assistant"` on `Event.tool_call(...)` — recommended for agents that log their own tool calls:

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

client = WhiteCircle()
tool_policy = client.policies.create(
Expand All @@ -56,9 +56,13 @@ tool_policy = client.policies.create(
EventSelector(type="tool", field="arguments"),
EventSelector(type="tool", field="output"),
],
role_list=[],
role_list=["assistant"],
mode="shadow",
)
result = client.events.check(
Event.tool_call("run_sql", {"query": "SELECT * FROM orders"}, role="assistant", call_id="c1"),
include_shadow=True,
)
```

## Shadow mode to production
Expand Down
5 changes: 3 additions & 2 deletions docs/metadata-and-conditions.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ condition = client.conditions.create(
name="EU pro users",
conditions=(field("user.region") == "eu") & (field("user.plan") == "pro"),
environment_ids=["env_prod"],
policy_ids=[policy.id],
policy_ids=["pol_123"],
state="Active",
)
```
Expand All @@ -66,6 +66,7 @@ Combine with `&`, not `and`: `and` raises `TypeError` instead of silently droppi
from whitecircle import Event, WhiteCircle

client = WhiteCircle()
meta = {"app": "support-bot"}
result = client.events.check(Event.user("My card number is 4111 1111 1111 1111", metadata=meta))

for policy_result in (result.policies or {}).values():
Expand All @@ -92,7 +93,7 @@ A stream does not report "not checked": with no matching Condition every batch p
missing field never matches, except with `.not_exists()`.
3. The type matches: `field("user.age") >= 18` needs a number, not `"18"`.
4. The Policy selects this Event type and field, and its `role_list` is empty or includes the Event's role
(`["assistant"]` skips user messages and `tool/arguments`).
(`["assistant"]` skips user messages and `tool/arguments` sent without `role="assistant"`).

## Inline Policies

Expand Down
15 changes: 11 additions & 4 deletions docs/streaming.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,24 @@ your model call stops generating. Text from the flagged batch is never released.
## From an OpenAI stream

```python
from collections.abc import Iterable, Iterator
from typing import Any

from whitecircle import WhiteCircle

client = WhiteCircle()


def openai_tokens(stream):
def openai_tokens(stream: Iterable[Any]) -> Iterator[str]:
for chunk in stream:
if chunk.choices and (delta := chunk.choices[0].delta.content):
yield delta


stream = openai_client.chat.completions.create(model=model, messages=messages, stream=True)
for text in client.events.check_stream(openai_tokens(stream), external_session_id=conversation_id):
stream = openai_client.chat.completions.create(
model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello"}], stream=True
)
for text in client.events.check_stream(openai_tokens(stream), external_session_id="conversation_456"):
send_to_user(text)
```

Expand All @@ -67,8 +72,9 @@ was not fully checked: treat unreleased text as unsafe and, if you retry, send t
from whitecircle import StreamClosedError, StreamError, WhiteCircle

client = WhiteCircle()
tokens = ["Hello, ", "world!"]
try:
for text in client.events.check_stream(tokens, external_session_id=conversation_id):
for text in client.events.check_stream(tokens, external_session_id="conversation_456"):
send_to_user(text)
except StreamError as error:
if error.retryable: # capacity, server_shutdown, processing_failed, rate_limited
Expand All @@ -91,6 +97,7 @@ Opening the stream raises the usual HTTP errors: `AuthenticationError` (401), `P
from whitecircle import WhiteCircle

client = WhiteCircle()
meta = {"user": {"region": "eu"}}
with client.events.stream(external_session_id="conversation_456", metadata=meta) as stream:
for token in model_tokens():
stream.append(token)
Expand Down
27 changes: 24 additions & 3 deletions docs/strikes-and-webhooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ from whitecircle import Event, WhiteCircle

client = WhiteCircle()
meta = {"user": {"id": "user-123", "email": "user@example.com", "ip": "203.0.113.10"}}
client.events.check(Event.user(text, metadata=meta), external_session_id="conversation_456")
client.events.check(Event.user("Hello, can you help?", metadata=meta), external_session_id="conversation_456")
```

## Read a user's risk
Expand All @@ -36,8 +36,8 @@ from whitecircle import WhiteCircle

client = WhiteCircle()
created = client.users.strikes.create(
policy_id=policy.id,
severity_level_id=severity_level_id, # must be the Policy's current severity_level_id
policy_id="pol_123",
severity_level_id="sev_high", # must be the Policy's current severity_level_id
user_id="user-123",
external_session_id="conversation_456",
)
Expand All @@ -46,6 +46,27 @@ print(created.action)

Pass exactly one of `user_id` or `email`, and exactly one of `external_session_id` or `internal_session_id`.

## User properties

Read or merge custom properties stored on existing users with `client.users.properties`:

```python
from whitecircle import WhiteCircle
from whitecircle.types import UserProperties

client = WhiteCircle()
props = client.users.properties.get(user_id="user-123") # pass exactly one of user_id, email or ip
print(props)

updated = client.users.properties.update(
[UserProperties(user_id="user-123", properties={"plan": "pro", "old_flag": None})]
)
print(updated.users, updated.not_found)
```

`update()` merges properties into 1 to 100 existing users; setting a key to `None` removes it, and unknown user IDs
are reported in `not_found`.

## Appeals

Strikes have no public ID; appeal one through its session:
Expand Down
21 changes: 21 additions & 0 deletions docs/usage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Usage

Read billed usage and cost across every Environment with `client.billing.usage()`.

```python
from datetime import date

from whitecircle import WhiteCircle

client = WhiteCircle()

last_week = client.billing.usage(period=7) # trailing days (1-365, default 30)
print(last_week.total_micros, last_week.message.count, last_week.tool.count)

window = client.billing.usage(from_date=date(2026, 6, 1), to_date=date(2026, 6, 7))
print(window.from_, window.to, window.artifact.image.cost_micros)
```

- Pass either `period` or both `from_date` and `to_date` (an inclusive UTC date range), not both.
- Costs (`total_micros`, `*.cost_micros`) are integers in millionths of one USD.
- `artifact.video` and `artifact.website` are counted, not billed.
Loading
Loading