Skip to content

Python SDK ​

The package is preworld-guard-sdk, imported as preworld_guard. It runs on Python 3.11 and 3.12. The base package depends only on httpx, pydantic and PyYAML. Frameworks come with extras. import preworld_guard never imports a framework.

Current hosted production offers preworld-guard-sdk==0.10.0. Version 0.11.0 will use yi-guard-sdk; use that name only after it is released and appears on your private index. The preworld_guard import and CLI names stay unchanged.

Install ​

Install only from the private SDK source specified by your console, with its pinned version and hash. Do not install from public PyPI.

  • Hosted control plane: your private SDK index, reached with an SDK download token. Use the install command the console gives you. It pins the wheel's address and sha256. See Quickstart.
  • Self-hosted control plane: the wheel or private index we provide. Pin the version and its hash.
ExtraInstalls
mcpThe MCP proxy
identityJWT checks (RS256, issuer, audience, scope) for the broker and the MCP proxy
oauthPer-user OAuth to MCP upstreams, with the encrypted vault
gatewayThe HTTP broker
langchain, langgraph, claude, openai-agents, pydantic-ai, google-adk, agent-framework, llama-index, agno, dspy, crewaiOne framework adapter each; see Framework adapters

Some combinations can't be installed together. See Extras that conflict.

GuardClient ​

python
GuardClient(endpoint, token, project_id, *, agent_id="python-agent", cache_path=None, timeout=5.0,
            refresh_interval=60.0, max_stale_age=300.0, background_events=False, event_batch_size=50,
            event_flush_interval=1.0, max_outbox_bytes=8_000_000, proxy=None, ca_bundle=None)
ParameterDefaultMeaning
endpointThe control plane's address
tokenThe executor credential (PREWORLD_GUARD_TOKEN in guard.env)
project_idThe project
agent_idpython-agentThe agent this credential belongs to
cache_path.preworld-guard/policy.jsonWhere the verified policy is cached; PREWORLD_GUARD_CACHE sets it too. The event queue and approval snapshots live next to it
timeout5 sTimeout for each control-plane request
refresh_interval60 sHow often the policy is refreshed when it's used
max_stale_age300 sHow long the cached policy may be used without reaching the control plane. After that every protected action is blocked
background_eventsFalseSend events from a background thread instead of inline. Use it for agents with many calls
max_outbox_bytes8,000,000Size of the local event queue. When it is full, new actions are blocked
proxy, ca_bundleAn HTTP(S) proxy and a CA bundle for control-plane traffic; also PREWORLD_GUARD_PROXY and PREWORLD_GUARD_CA_BUNDLE

The SDK ignores HTTPS_PROXY and SSL_CERT_FILE. The proxy and CA settings cover only control-plane traffic: policy, heartbeats, events, approvals, connection-check, trial-check, siem-export and onboard. Guarded HTTP, the broker, MCP upstreams, OAuth and JWKS traffic never use the proxy, because it would bypass the address checks.

Lifecycle ​

MethodWhat it does
start(*, name="python-sdk", version=..., heartbeat_interval=15.0)Registers the executor, declares the agent as an asset, sends a heartbeat, then keeps syncing policy and sending heartbeats every 15 seconds in a background thread. Returns the client
lifecycle_statusExecutor ID, status, last error, loaded policy version and hash, and whether the policy came from the control plane or the cache
close()Sends a last stopped heartbeat, stops the background threads and sends queued events if it can. Call it on shutdown

Protecting calls ​

MethodWhat it does
@guard.tool(resource=None, *, action_type="tool.call", pending=False)Wraps a sync or async function. Decides before each call, records started and completed, runs a registered fallback for degrade rules. pending=True keeps an argument snapshot for approval resume
authorize(resource, arguments=None, *, action_type="tool.call", destination=None, data_labels=(), subject_id=None, ...)Decides one action and returns (action, decision), or raises. Use it when you run the side effect yourself
register_fallback(resource, function, *, map_arguments)Registers the fallback a degrade rule names. It can't be replaced while running
approval_status(ticket_id), cancel_approval(ticket_id)Read or withdraw an approval ticket this executor filed
pending.status(ticket_id), pending.resume(ticket_id), pending.resume_async(ticket_id), pending.cancel(ticket_id), pending.list()Approval snapshots for tools wrapped with pending=True

Context ​

FunctionWhat it does
guard_run(*, session_id=None, subject_id=None, run_id=None, trace_id=None)Context manager. Sets the trusted subject and correlation IDs for every Guard call inside it. The subject must come from your application, never from the model
guard_approval(ticket_id)Context manager. The next matching call consumes this approved ticket; any later use fails
guard_resume(*ticket_ids)Context manager for adapters. An approved ticket is consumed when the same action is proposed again; other calls are decided normally
current_run()The active guard_run context, if any

The decision ​

GuardDenied.decision and the decision returned by authorize have:

FieldMeaning
effectallow, deny, allow_with_warning, require_approval or degrade
would_effectWhat an enforcing policy would decide
rule_idThe rule that decided, or default-allow, default-deny, policy-expired
reason_codeALLOWED, RULE_DENIED, DEFAULT_DENY, APPROVAL_REQUIRED, DEGRADED, POLICY_EXPIRED, SUBJECT_REQUIRED, APPROVED…
messageThe rule's message
policy_version, policy_hashThe policy that decided
fallback_resourceFor degrade

Exceptions ​

ExceptionRaised when
GuardErrorBase class. Also raised when there is no valid policy, or the cached policy is older than max_stale_age
GuardTransportErrorThe control plane can't be reached. A verified cache may still be used
GuardRequestRejectedThe control plane refused a request with a 4xx other than 401/403; status_code says which
GuardAuthErrorThe credential is invalid. Never falls back to the cache; create a new client with a new credential
GuardDeniedThe decision is deny; decision holds it
GuardApprovalRequiredA subclass of GuardDenied: a ticket was filed. ticket_id, expires_at, status
GuardDegradeRequiredA subclass of GuardDenied: a degrade rule applies and no fallback ran on this path
GuardSubjectRequiredAn approval rule matched a call without a trusted subject
GuardFallbackUnavailableThe fallback a degrade rule names isn't registered, or can't run on this path
GuardUnavailableIn adapters (preworld_guard._adapter): Guard couldn't decide. Its payload is safe to show the model

In every case the tool must not run.

Control-plane retries ​

From 0.9.0, a control-plane request that fails at the connection level is sent once more, immediately, but only when that can't repeat a side effect. A request that never left the client is always retried. One that may have been sent is retried only if it is a read, an event upload or an approval request, which the control plane deduplicates. Consuming a ticket, registering and heartbeats are never repeated. A request can therefore take up to twice timeout.

Other modules ​

ModuleFor
preworld_guard.egressGuardedHTTPClient, GuardedAsyncHTTPClient; see HTTP egress
preworld_guard.gatewayThe HTTP broker (python -m preworld_guard.gateway --config ...)
preworld_guard.policy_dslparse_policy_document, load_policy_yaml, compile_policy, policy_json_schema
preworld_guard.langgraph, .pydantic_ai, .google_adk, .agent_framework, .llama_index, .agno, .dspy, .crewaiFramework adapters. GuardMiddleware, GuardHooks and protect_function_tool are importable from preworld_guard directly