diff --git a/README.md b/README.md index 07a281a..4b51117 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,10 @@ Send up to 50 Events in one request, in the order they happened. Each is checked gets its own result. ```python +from whitecircle import Event, WhiteCircle + +client = WhiteCircle() + batch = client.events.check_many( [ Event.user("Refund order 4815, please", event_id="evt_user_1"), @@ -101,6 +105,10 @@ Metadata does not carry over between Events: put `metadata` on every Event a Con Check an assistant reply while your model generates it, and show your user only text that passed: ```python +from whitecircle import WhiteCircle + +client = WhiteCircle() + reply = client.events.check_stream( model_tokens(), # your iterator of generated text external_session_id="conversation_456", @@ -121,7 +129,9 @@ Stream assistant output only, and check user messages and tool calls with `event ## Policies and Conditions ```python -from whitecircle import Rule, field +from whitecircle import Rule, WhiteCircle, field + +client = WhiteCircle() policy = client.policies.create( name="No medical advice", @@ -171,6 +181,9 @@ def receive(): ```python import whitecircle +from whitecircle import Event, WhiteCircle + +client = WhiteCircle() try: client.events.check(Event.user("hello")) diff --git a/docs/README.md b/docs/README.md index 8393d04..5668982 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,7 +7,7 @@ live at https://whitecircle.com/docs. 1. Skim "The model" below: it is everything the SDK assumes you know. 2. Read [Getting started](getting-started.md) for configuration and how to read a result. -3. Jump to the page for your task in the table. Pages are independent and assume a configured `client`. +3. Jump to the page for your task in the table. Pages are independent. 4. If a check returns no verdict (`result.checked` is `False`), read [Metadata and Conditions](metadata-and-conditions.md). | Page | Task | diff --git a/docs/agents-and-tools.md b/docs/agents-and-tools.md index 67e6053..d4bdf16 100644 --- a/docs/agents-and-tools.md +++ b/docs/agents-and-tools.md @@ -23,6 +23,9 @@ Event.tool_result("send_email", {"status": "sent"}, call_id="call_1") Send the same `call_id` on both, or set the result's `parent_event_id` to the call's `event_id`: ```python +from whitecircle import Event, WhiteCircle + +client = WhiteCircle() client.events.check_many( [ Event.tool_call("lookup_order", {"order_id": "4815"}, event_id="lookup_args"), @@ -39,8 +42,9 @@ client.events.check_many( - `links` are outputs the Event consumed, from this run or another run in the Environment, up to 50. ```python -from whitecircle import EventLink +from whitecircle import Event, EventLink, WhiteCircle +client = WhiteCircle() run = "run_pr_1234" client.events.check(Event.agent("Review this PR", field="input", event_id="main", name="orchestrator"), run_id=run) client.events.check( @@ -66,6 +70,9 @@ Record how long a step took with timezone-aware datetimes (the API needs RFC 333 ```python from datetime import UTC, datetime +from whitecircle import Event, WhiteCircle + +client = WhiteCircle() started = datetime.now(UTC) output = run_search() client.events.check( @@ -76,6 +83,9 @@ client.events.check( ## Load the run graph ```python +from whitecircle import WhiteCircle + +client = WhiteCircle() for page in client.runs.iter_graph("run_pr_1234"): for node in page.nodes: print(node.event_id, node.type, node.status, node.effective_violation) diff --git a/docs/chatbot.md b/docs/chatbot.md index cd8c0c3..2fc7106 100644 --- a/docs/chatbot.md +++ b/docs/chatbot.md @@ -7,7 +7,7 @@ checked text, and checks its tool calls. Every call sends only the new Event; ea ```python from typing import Any -from whitecircle import AsyncWhiteCircle, Event +from whitecircle import AsyncWhiteCircle wc = AsyncWhiteCircle() # WHITECIRCLE_API_KEY, WHITECIRCLE_ENVIRONMENT_ID @@ -20,6 +20,11 @@ def metadata_for(user: User) -> dict[str, Any]: ## 1. Check the user's message ```python +from whitecircle import AsyncWhiteCircle, Event + +wc = AsyncWhiteCircle() + + async def handle_message(user: User, conversation_id: str, text: str) -> None: meta = metadata_for(user) check = await wc.events.check(Event.user(text, metadata=meta), external_session_id=conversation_id) @@ -32,6 +37,13 @@ async def handle_message(user: User, conversation_id: str, text: str) -> None: ## 2. Stream the reply ```python +from typing import Any + +from whitecircle import AsyncWhiteCircle + +wc = AsyncWhiteCircle() + + async def answer(conversation_id: str, meta: dict[str, Any]) -> None: reply = wc.events.check_stream( llm_tokens(conversation_id), # AsyncIterator[str] from your model @@ -54,6 +66,13 @@ Tool output is a common source of leaked data. Check arguments before running th sees it; the same `call_id` pairs them. ```python +from typing import Any + +from whitecircle import AsyncWhiteCircle, Event + +wc = AsyncWhiteCircle() + + async def lookup_order(conversation_id: str, meta: dict[str, Any], order_id: str) -> dict[str, Any]: call_id = f"call-{order_id}" call = await wc.events.check( diff --git a/docs/context.md b/docs/context.md index 13916bd..a762aff 100644 --- a/docs/context.md +++ b/docs/context.md @@ -11,8 +11,9 @@ the Event you sent. | neither | none: the Event is checked alone | ```python -from whitecircle import Event +from whitecircle import Event, WhiteCircle +client = WhiteCircle() session = "conversation_456" client.events.check(Event.user("My account number is 4471"), external_session_id=session) client.events.check(Event.tool_result("lookup_account", {"holder": "A. Rivera"}), external_session_id=session) @@ -25,6 +26,9 @@ with the `system` role. In a `check_many()` batch, list order is context order. ## Start the context over ```python +from whitecircle import Event, WhiteCircle + +client = WhiteCircle() 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) ``` @@ -39,6 +43,9 @@ Store history from before you integrated as context, without checking it, with ` replaces anything stored before: ```python +from whitecircle import Event, WhiteCircle + +client = WhiteCircle() events = [Event.reset()] + [Event.message(m.text, role=m.role) for m 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) diff --git a/docs/errors-and-testing.md b/docs/errors-and-testing.md index de30c6a..2dad371 100644 --- a/docs/errors-and-testing.md +++ b/docs/errors-and-testing.md @@ -7,8 +7,9 @@ such as a missing `environment_id` or two user identifiers at once, raise `Value ```python import whitecircle -from whitecircle import Event, WhiteCircle +from whitecircle import WhiteCircle +client = WhiteCircle() try: result = client.events.check(event) except whitecircle.AuthenticationError: # 401 @@ -35,6 +36,12 @@ in `note`. ## Fail open or closed ```python +import whitecircle +from whitecircle import Event, WhiteCircle + +client = WhiteCircle() + + def is_allowed(text: str) -> bool: try: result = client.events.check(Event.user(text, metadata=meta)) @@ -48,6 +55,8 @@ def is_allowed(text: str) -> bool: ## Retries and timeouts ```python +from whitecircle import WhiteCircle + client = WhiteCircle(timeout=10.0, max_retries=3) quick = client.with_options(timeout=2.0, max_retries=0) ``` @@ -143,6 +152,9 @@ fake.events.check.return_value = EventCheckResult.model_validate( ## Endpoints the SDK does not wrap ```python +from whitecircle import WhiteCircle + +client = WhiteCircle() client.request("GET", "/api/some/new/endpoint", params={"x": 1}) client.request("POST", "/api/some/new/endpoint", body={"field": "value"}) ``` diff --git a/docs/getting-started.md b/docs/getting-started.md index 2463745..0bbfeea 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -36,19 +36,27 @@ Events and run-graph calls need an Environment. Pass `environment_id=` to overri with neither, the call raises `ValueError`: ```python +from whitecircle import WhiteCircle + +client = WhiteCircle() client.events.check(event, environment_id="env_staging") ``` For several settings at once, make a copy that shares the connection pool: ```python +from whitecircle import WhiteCircle + +client = WhiteCircle() fast = client.with_options(timeout=5.0, max_retries=0) ``` ## Check and read the result ```python -from whitecircle import Event +from whitecircle import Event, WhiteCircle + +client = WhiteCircle() result = client.events.check( Event.user("Hello, can you help me prescribe antibiotics?"), @@ -76,6 +84,9 @@ else: Fetch a stored result later: ```python +from whitecircle import WhiteCircle + +client = WhiteCircle() client.events.get(internal_event_id) client.events.get_latest(run_id="run_1", event_id="evt_user_1") ``` diff --git a/docs/images.md b/docs/images.md index 33f564a..24eabde 100644 --- a/docs/images.md +++ b/docs/images.md @@ -20,6 +20,9 @@ inline = ArtifactContent.from_bytes(Path("upload.jpg").read_bytes()) # sent as ## Standalone images ```python +from whitecircle import WhiteCircle + +client = WhiteCircle() result = client.artifacts.check(by_url, role="user", external_artifact_id="upload_123") if result.flagged: reject_upload() @@ -37,8 +40,9 @@ result is stored. ## Images in a conversation ```python -from whitecircle import Event +from whitecircle import Event, WhiteCircle +client = WhiteCircle() session = "conversation_456" client.events.check(Event.user("Is this rash serious?", metadata=meta), external_session_id=session) client.events.check( diff --git a/docs/inline-policies.md b/docs/inline-policies.md index 285f62b..7752768 100644 --- a/docs/inline-policies.md +++ b/docs/inline-policies.md @@ -5,8 +5,9 @@ Policies run on `events.check()` and `events.check_many()` in addition to the Po they need no Condition. Streams do not take them (see [Streaming replies](streaming.md)). ```python -from whitecircle import Event, InlinePolicy, Rule +from whitecircle import Event, InlinePolicy, Rule, WhiteCircle +client = WhiteCircle() refund_policy = InlinePolicy( external_id="refund-policy", name="Refund policy", @@ -28,6 +29,9 @@ for policy_id, verdict in result.flagged_policies.items(): ## Reference a stored definition ```python +from whitecircle import Event, InlinePolicy, WhiteCircle + +client = WhiteCircle() result = client.events.check(Event.user("Can I get a refund?"), inline_policies=[InlinePolicy.ref("refund-policy")]) ``` diff --git a/docs/managing-policies.md b/docs/managing-policies.md index d08ac65..aa2b0c6 100644 --- a/docs/managing-policies.md +++ b/docs/managing-policies.md @@ -5,8 +5,9 @@ Keep Policies, Metrics and Conditions in your repo and sync them from a script o ## Create a Policy ```python -from whitecircle import EventSelector, Rule +from whitecircle import EventSelector, Rule, WhiteCircle +client = WhiteCircle() policy = client.policies.create( name="No medical advice", rules=[ @@ -28,8 +29,9 @@ At least one rule must flag. `event_selector_list` picks Event types and fields, A shadow Policy is evaluated but never changes `flagged`. Ask for its results with `include_shadow=True`: ```python -from whitecircle import Event +from whitecircle import Event, WhiteCircle +client = WhiteCircle() result = client.events.check(Event.user(sample_prompt, metadata=meta), include_shadow=True) for policy_result in (result.policies or {}).values(): if policy_result.shadow: @@ -44,6 +46,9 @@ Only the fields you pass change; `None` means "keep". `rules` replaces the whole (they carry their IDs) and add to them: ```python +from whitecircle import Rule, WhiteCircle + +client = WhiteCircle() policy = client.policies.get(policy.id) client.policies.update(policy.id, rules=[*policy.rules, Rule.allow("Store opening hours")]) client.policies.update(policy.id, severity_level_id=None) # the one field None clears @@ -55,8 +60,9 @@ and `client.policies.list()` returns active Policies only. ## Attach it with a Condition ```python -from whitecircle import field +from whitecircle import WhiteCircle, field +client = WhiteCircle() condition = client.conditions.create( name="Pharmacy bot", conditions=field("app") == "pharmacy-bot", @@ -78,6 +84,9 @@ On update, leaving `policy_ids`, `metric_ids` or `environment_ids` out keeps the results appear only in the dashboard. ```python +from whitecircle import Rule, WhiteCircle + +client = WhiteCircle() metric = client.metrics.create(name="Escalation risk", rules=[Rule.flag("The user threatens to churn or escalate")]) client.conditions.update(condition.id, metric_ids=[metric.id]) ``` @@ -88,6 +97,9 @@ client.conditions.update(condition.id, metric_ids=[metric.id]) import json from pathlib import Path +from whitecircle import Rule, WhiteCircle + +client = WhiteCircle() desired = json.loads(Path("policies.json").read_text()) # [{"name": ..., "flag": [...], "allow": [...]}] existing = {policy.name: policy for policy in client.policies.list()} diff --git a/docs/metadata-and-conditions.md b/docs/metadata-and-conditions.md index fae9010..3e0ec1a 100644 --- a/docs/metadata-and-conditions.md +++ b/docs/metadata-and-conditions.md @@ -8,8 +8,9 @@ A dashboard Policy runs on an Event only when an active Condition on the Event's `metadata` is any JSON object (up to 256 KiB) and goes on each Event; it does not carry over to the next one. ```python -from whitecircle import Event +from whitecircle import Event, WhiteCircle +client = WhiteCircle() meta = {"app": "support-bot", "user": {"id": "user-123", "region": "eu", "plan": "pro", "age": 34}} session = "conversation_456" @@ -31,8 +32,9 @@ system](strikes-and-webhooks.md). ## Match it with a Condition ```python -from whitecircle import field +from whitecircle import WhiteCircle, field +client = WhiteCircle() condition = client.conditions.create( name="EU pro users", conditions=(field("user.region") == "eu") & (field("user.plan") == "pro"), @@ -61,6 +63,9 @@ Combine with `&`, not `and`: `and` raises `TypeError` instead of silently droppi ## See which Condition selected a Policy ```python +from whitecircle import Event, WhiteCircle + +client = WhiteCircle() result = client.events.check(Event.user("My card number is 4111 1111 1111 1111", metadata=meta)) for policy_result in (result.policies or {}).values(): @@ -71,6 +76,9 @@ for policy_result in (result.policies or {}).values(): ## When nothing runs ```python +from whitecircle import Event, WhiteCircle + +client = WhiteCircle() result = client.events.check(Event.user("hello")) # no metadata result.checked # False result.note # "No policies or metrics were selected for this Event" diff --git a/docs/streaming.md b/docs/streaming.md index a4d1975..f84c536 100644 --- a/docs/streaming.md +++ b/docs/streaming.md @@ -6,6 +6,9 @@ output only; check user messages and tool calls with `events.check()` under the ## `check_stream` ```python +from whitecircle import WhiteCircle + +client = WhiteCircle() reply = client.events.check_stream( model_tokens(), # any iterable of strings external_session_id="conversation_456", @@ -39,6 +42,11 @@ your model call stops generating. Text from the flagged batch is never released. ## From an OpenAI stream ```python +from whitecircle import WhiteCircle + +client = WhiteCircle() + + def openai_tokens(stream): for chunk in stream: if chunk.choices and (delta := chunk.choices[0].delta.content): @@ -56,8 +64,9 @@ for text in client.events.check_stream(openai_tokens(stream), external_session_i was not fully checked: treat unreleased text as unsafe and, if you retry, send the whole reply in a new stream. ```python -from whitecircle import StreamClosedError, StreamError +from whitecircle import StreamClosedError, StreamError, WhiteCircle +client = WhiteCircle() try: for text in client.events.check_stream(tokens, external_session_id=conversation_id): send_to_user(text) @@ -79,6 +88,9 @@ Opening the stream raises the usual HTTP errors: `AuthenticationError` (401), `P ## Full control: `stream()` ```python +from whitecircle import WhiteCircle + +client = WhiteCircle() with client.events.stream(external_session_id="conversation_456", metadata=meta) as stream: for token in model_tokens(): stream.append(token) diff --git a/docs/strikes-and-webhooks.md b/docs/strikes-and-webhooks.md index e833a06..b5b2e5e 100644 --- a/docs/strikes-and-webhooks.md +++ b/docs/strikes-and-webhooks.md @@ -6,8 +6,9 @@ configured in the dashboard. White Circle does not restrict accounts itself; you ## Identify the user on each Event ```python -from whitecircle import Event +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") ``` @@ -15,6 +16,9 @@ client.events.check(Event.user(text, metadata=meta), external_session_id="conver ## Read a user's risk ```python +from whitecircle import WhiteCircle + +client = WhiteCircle() risk = client.users.risk(user_id="user-123") # or email="user@example.com" if risk.action is not None: # the action's title as configured for your team, e.g. "Suspend" @@ -28,6 +32,9 @@ a strike that never expires. ## Record a strike yourself ```python +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 @@ -44,6 +51,9 @@ Pass exactly one of `user_id` or `email`, and exactly one of `external_session_i Strikes have no public ID; appeal one through its session: ```python +from whitecircle import WhiteCircle + +client = WhiteCircle() strike = client.users.risk(user_id="user-123").strikes[0] appeal = client.users.appeals.create(reason="I was quoting a news article", session_id=strike.internal_session_id) status = client.users.appeals.get(appeal_id=appeal.appeal_id) @@ -97,6 +107,9 @@ With FastAPI, pass `await request.body()` and `request.headers` to `unwrap()`. import json import time +from whitecircle import Webhooks + +webhooks = Webhooks() body = json.dumps( { "event_type": "session.violated",