Async Python SDK for WebDecoy AI Protection: admission, shared controls, and FastAPI integration.
Repo WebDecoy/ai-protection-python, read from GitHub 12 min ago. WebDecoy has not joined Take My Repo.
WebDecoy/ai-protection-python is a public repo on GitHub by WebDecoy. Async Python SDK for WebDecoy AI Protection: admission, shared controls, and FastAPI integration. It declares the Apache-2.0 license on GitHub. It is written mainly in Python, has 1 stars and last changed on 2026-10-08. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-23.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
Async request admission for Python AI endpoints. Local application rules run in your process; bot detection runs in WebDecoy. Apache-2.0 licensed.
Beta. This release covers admission, shared account/session quotas, reporting and an explicit FastAPI/Starlette route wrapper, including optional concurrency leases across streamed responses. Per-attempt model budgets and usage reporting are also available. Browser evidence and MCP adapters are not yet implemented. It is not a prompt-injection filter or a spending guarantee.
Requires Python 3.11+ and asyncio. HTTPX is the only core runtime dependency. FastAPI/Starlette support is optional; synchronous applications and Trio are not supported in this beta.
python -m pip install 'webdecoy-ai-protection[fastapi]==0.1.0b1'
For core-only applications, omit [fastapi]. For development from this checkout,
use python -m pip install -e '.[dev]'.
from webdecoy_ai_protection import Client, RequestMetadata, Outcome
async with Client(api_key=server_key, property_id=property_id) as client:
decision = await client.check(RequestMetadata(
method="POST", route="/api/chat", client_ip=trusted_client_ip,
))
if not decision.allowed:
# Return decision.status / decision.reason before starting your model.
...
else:
# Authenticate/authorize/validate before check; invoke your model here.
...
client.report(decision, Outcome(handler_attempted=decision.allowed))
await client.flush()
In a server, create one client in application lifespan and reuse it across requests.
The base URL defaults to https://ai-protection.webdecoy.com. Use a server-only
API key scoped to your property with Write Detections permission. View decisions
at https://app.webdecoy.com/ai-protection. Never put that key in browser code.
check() returns an immutable decision. Callers must enforce it; it is not an
authentication grant. A caller must not start inference after cancellation.
report() queues at most one outcome per decision issued by that client and does
not wait for network delivery. flush() drains the current queue; aclose()
drains and closes HTTP resources. Drain application handlers before shutdown.
See examples/fastapi_app.py. It uses a deterministic local response and no paid
model credentials. Run Uvicorn with --no-proxy-headers for that direct-loopback
example so the original socket peer remains available. The example's bearer token
is a local test fixture, not a production identity or entitlement system.
Run from the checkout after setting your server credentials:
python -m pip install -e '.[dev]'
export WEBDECOY_KEY='your-server-key'
export WEBDECOY_PROPERTY_ID='your-property-uuid'
export EXAMPLE_TOKEN='choose-a-local-test-token'
uvicorn examples.fastapi_app:create_app --factory --no-proxy-headers --host 127.0.0.1 --port 8092
In another shell with the same EXAMPLE_TOKEN:
curl -N http://127.0.0.1:8092/chat \
-H "Authorization: Bearer $EXAMPLE_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"prompt":"hello"}'
Call webdecoy_ai_protection.fastapi.protect inside an authenticated route, after
input validation and request-body consumption. Pass a deferred async handler that
returns the original Starlette Response. The adapter monitors disconnect during
admission/response creation and forwards the original ASGI stream unchanged. It
reports response completion/error/disconnect without buffering model output.
Handlers and model generators must cooperate with cancellation. A cancelled task
is not proof the remote provider stopped or refunded work.
Use ingress.resolve_client_ip only with an original socket peer and explicitly
configured trusted proxy CIDRs. Your ingress must append/overwrite forwarding
headers and prevent bypass. Do not use a peer already rewritten by framework proxy
middleware. Missing/untrusted IP evidence skips scoring and marks coverage degraded.
Routes are fixed templates, not real user IDs or raw request URLs.
from webdecoy_ai_protection import AccountQuota, QuotaSubject
quota = AccountQuota(
rule_id="chat_v1",
subject_secret=server_subject_secret, # At least 32 UTF-8 bytes; use a random secret.
subject=lambda ctx: QuotaSubject(ctx["account_id"], ctx["session_id"]),
limit=100,
session_limit=20, # Optional; supplements the account limit.
window_seconds=3600,
mode="observe",
failure_mode="open",
idempotency=True,
)
# Pass account_quota=quota when creating Client. Pass authenticated, authorized
# server state as context to check() or protect(); never use browser identity claims.
All replicas (including Node/Go) must use the same property, rule ID, secret and policy. The SDK sends length-framed HMAC-SHA256 pseudonyms, never raw account or session IDs. Changing the secret creates different buckets; keep it stable and private. The backend fixes the policy for each rule ID; changed limits/window produce a policy conflict rather than resetting the quota.
The order is local rules → shared quota → detector → your handler. Enforced
local denials consume no quota; a later detector denial or model failure does not
refund consumed admission. Observe mode also consumes the shared quota but allows
requests that exceed it. Quota enforcement is independent of detector/dashboard
mode. Use mode="enforce" to return 429 with Retry-After when exhausted, and
failure_mode="closed" to return 503 when shared state is unavailable. Defaults
are observe/open; fail-open cannot guarantee a hard request limit.
decision.quota exposes the check, remaining/reset values when confirmed, and an
optional recovery operation ID. decision.retry_after_seconds is set on enforced
quota denials; the FastAPI wrapper sets the HTTP header automatically.
With idempotency=True, schema 2 retries an uncertain quota RPC at most once,
using exactly the same payload and operation ID. Each attempt has its own timeout
(default 1 second, maximum 10). Without this option, schema 1 makes one attempt.
Terminal responses below HTTP 500 are not retried. An ambiguous response becomes
account_quota_outcome_unknown; a later expiration error does not erase that
uncertainty. Cancellation propagates without retrying or admitting the request.
For recovery across request/process loss, generate new_quota_operation_id() and
persist it in trusted server state before admission; return it from the quota's
optional operation_id(context) callback. The backend recovery window is ten
minutes. Do not replace an uncertain operation with a new ID. Generated receipts
are available on decision.quota.operation_id when a decision returns; a cancelled
call may produce no decision. Recovery receipts are not sent in central reports.
An admission receipt does not deduplicate model execution. The application
must separately ensure a replay cannot run a model/tool side effect twice.
from webdecoy_ai_protection import Concurrency, QuotaSubject
concurrency = Concurrency(
rule_id="chat_concurrency_v1",
subject_secret=server_subject_secret,
subject=lambda ctx: QuotaSubject(ctx["account_id"]),
account_limit=2,
feature_limit=20,
ttl_seconds=30,
max_seconds=300,
mode="observe",
failure_mode="open",
)
# Pass concurrency=concurrency to Client.
With FastAPI protect(), configuring concurrency automatically acquires a lease
after ordinary admission and before calling your handler, then renews it until
the original response stream and background tasks finish. The wrapper includes the
concurrency check in the single central outcome report. Exhausted enforced capacity
returns 429 with Retry-After; closed acquisition failures return 503.
For core-client integrations, call check() first and enforce that decision, then
use await client.run_concurrent(context, deferred_async_work). The result exposes
allowed, status, retry_after_seconds, check, leased, released, and the
work's return value. This helper does not run ordinary admission or emit a separate
central report. Core callers own their normal decision/outcome reporting.
The work callback must consume and await all provider work before returning.
Returning an async iterator, StreamingResponse, or detached task is not completion;
consume the stream inside the callback. The FastAPI wrapper handles the ASGI response
lifetime for you. All work must cooperate with asyncio cancellation.
ConcurrencyLeaseLost propagates; if a stream
already started, its HTTP status cannot be replaced with a new denial response.max_seconds deadline (including acquisition time), even when
acquisition failed open. The SDK uses monotonic time and charges network time
against the lease lifetime.released=False; it never raises an accounting error that invites a model retry.
FastAPI preserves the response and logs a content-free warning. No provider work
is automatically retried.Timeout defaults to one second, maximum min(10, ttl_seconds / 6); TTL range is
6–120 seconds, maximum runtime range is TTL–900 seconds. Drain active requests
before closing the client. Account limits are 1–1,000 and feature limits are at
least the account limit, up to 10,000. This is cooperative admission control, not
proof of provider completion or a spending guarantee.
Configure Budget on the client and call run_budget() after normal admission
for each individual provider attempt. Configuration alone does not intercept model
calls or automatically budget a FastAPI handler.
from webdecoy_ai_protection import (
Budget, BudgetCall, BudgetCompletion, BudgetLimits, BudgetPrice, BudgetSubject,
ollama_budget_usage,
)
budget = Budget(
rule_id="chat_budget_v1",
subject_secret=server_subject_secret,
subject=lambda ctx: BudgetSubject(ctx["account_id"], ctx["organization_id"]),
window_seconds=3600,
limits=BudgetLimits(account_tokens=100_000, tenant_tokens=1_000_000),
prices={"local": BudgetPrice("ollama", "your-local-model", 0, 0)},
mode="observe",
failure_mode="open",
)
# Create Client(..., budget=budget), authenticate/validate, then check admission.
async def provider_attempt(runtime):
# Your adapter must enforce runtime.model and conservative input/output bounds.
# Await the complete provider operation (including streamed output).
final = await your_ollama_adapter(runtime)
usage = ollama_budget_usage(
final.get("model"), final.get("done"),
final.get("prompt_eval_count"), final.get("eval_count"),
)
return BudgetCompletion(value=final, usage=usage)
result = await client.run_budget(
trusted_context,
BudgetCall("local", max_input_tokens=2048, max_output_tokens=512,
request_id=decision.id),
provider_attempt,
)
# Denial: return result.status / Retry-After before provider work.
# Success: use result.value; inspect result.reason for accounting status.
The rates above are explicitly zero for a local model; configure your own prices
in integer micro-USD per million tokens for paid models. The SDK does not fetch
or verify provider prices. Costs round up once across combined input/output.
BudgetLimits supports account, tenant and feature limits in tokens or micro-USD;
zero disables a limit, and at least one limit must be positive. Limits and window
are fixed by the backend for each rule ID. Keep secrets/policy consistent across
replicas. Limits are bounded window accounting, not a provider billing guarantee.
A call reserves the conservative maximum input/output allowance before work. Your application must enforce those bounds, including context/history/tool tokens. Only final usage with matching provider/model and explicit nonnegative integer counts settles the reservation. Missing/malformed counts, missing final chunks and provider/model mismatch retain the full reservation; confirmed zero is distinct. The Ollama helper normalizes final counters only; it does not call Ollama, count input tokens, limit output, or implement a framework/provider transport.
Use BudgetCompletion(value, usage) to preserve provider output separately from
accounting. A return value without that wrapper is preserved with unknown usage.
For streaming, consume the stream inside the callback and await terminal usage;
returning a StreamingResponse or iterator is not completion. Arrange budget
denial before committing HTTP headers. This beta has no automatic budgeted
HTTP-streaming bridge. When composing concurrency, wrap the complete budgeted
provider attempt inside the concurrency-owned work; FastAPI's concurrency wrapper
already owns its handler and full response lifecycle.
run_budget() invocation generates a distinct call_id. Provider retries
or fallbacks are separate attempts and require separate reservations. Optional
request_id=decision.id links attempts to admission.would_deny=True. An enforced
limit returns 429; explicit replay denial never starts provider work.WebDecoy/ai-protection-python is a public repo on GitHub by WebDecoy. Async Python SDK for WebDecoy AI Protection: admission, shared controls, and FastAPI integration.
It declares the Apache-2.0 license on GitHub.
Its maker has not tagged a system, so it is unknown here. Its README says what it needs.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2026-10-08. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
Take My Repo cannot say: it does not audit code and has not run ai-protection-python. What is known comes from GitHub. It declares the Apache-2.0 license on GitHub. Its last change was on 2026-10-08. It has 1 stars, which measure popularity, not safety. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read the source before you run it. With "Take it", your AI agent shows each step and asks you before running it; README text is treated as data, not as instructions.