zanii-campus
The firm SDK for Zanii Campus (Python). Your company declares its AI agents and where they run, counts outcomes on
your own servers and sends DIFC one signed batch of counts per deployment every five minutes. Records are signed
byte for byte like the TypeScript SDK (@zanii/campus-sdk).
What is sent
Counts only, signed with your company key:
- Your agents: DID, a short product name, a kind (chatbot, voice, workflow, ...).
- Your deployments: an id, the agent, a client pseudonym you choose (never a client name), sector, country, channel, start and end dates.
- Outcome batches: per deployment and period, the number of sessions and queries, how many were resolved, escalated, failed or refused, and p50/p95 latency in milliseconds.
What is never sent
Prompts, answers, documents, customer names, phone numbers, IDs, emails or any other text from a conversation. Every
record is a closed shape and sign_record refuses any unknown field before a request is made. The server rejects
any content too, so even a modified client cannot send it.
Quickstart (10 minutes)
pip install zanii-campus
- Create your company key once and keep it in a secret store (vault, KMS, sealed file). It never leaves your company.
from zanii_campus import new_company_key
key, did = new_company_key() # save key.hex() to your secret store
- Join with the invite DIFC sent you. The token is shown once: store it like a password.
import os
from zanii_campus import CampusClient
campus = CampusClient("https://campus.zanii.agency", company_key=os.environ["CAMPUS_KEY"], state_dir="./var/campus")
token = campus.join("inv_...", "7574")["token"] # your DIFC registration number
Afterwards construct the client with token=os.environ["CAMPUS_TOKEN"].
- Register each agent and each deployment.
Any kind of agent works the same way: a chat assistant, a trading agent, a document reviewer, a voice line, a
back-office workflow, a data pipeline. Each deployment says what one counted item is (unit: conversation, task,
request, document, transaction, call, job, other) and every item ends one of four ways:
resolved (completed by the agent), escalated (handed to a person), failed, or refused (blocked by a rule).
# Example: a trading agent deployed for a brokerage, reached through an API
campus.register_agent("did:key:z6Mk...", "Order execution agent", "trading")
campus.deploy("dep-broker-01", "did:key:z6Mk...", {"ref": "client-7f3a", "sector": "finance", "country": "AE"}, "api", unit="transaction")
- Count outcomes around your agent's work (sync or async functions).
track = campus.tracker("dep-broker-01")
@track.wrap
async def execute(order): ... # resolved on return, failed on exception
execute2 = track.wrap(my_agent.execute, lambda result, error: "failed" if error else "escalated" if result.needs_approval else "resolved")
track.record("refused", new_session=True) # or count by hand
campus.close() # on shutdown: sends the open period
API
CampusClient(base_url, token=None, *, company_key, opener=None, state_dir=None, auto_flush=True, max_queued=10000, on_reject=None, on_error=None)join(invite, reg_no)returns{"company", "token"};me();register_agent(agent_did, name, kind);deploy(id, agent_did, client, channel, started=None, ended=None)(send again withendedto end it).tracker(deployment_id, period_ms=300000)returns a tracker withrecord(outcome, latency_ms=None, new_session=False),wrap(fn, classify=None)andflush().flush(),close(),pending,new_company_key(),CampusError(status, reasons, retry_after), and the contract checks (sign_record,verify_record,record_hash,check_*,ContractError).
Framework adapters (zanii_campus.adapters)
Count an existing agent with one line. The adapters are duck-typed (no framework is imported) and see only success
or failure, timing and your own optional classify(result, error); prompts, answers and tool arguments pass through
unread. Streams are counted once, when they end. Thread and asyncio safe.
from zanii_campus.adapters import (track_openai, track_anthropic, CampusCallbackHandler, CampusSpanProcessor,
track_call, track)
# A support chatbot on OpenAI or AsyncOpenAI (streaming or not)
openai = track_openai(OpenAI(), campus.tracker("dep-support-01"), new_session=True)
# A contract reviewer on Claude; a "refusal" stop reason counts as refused
anthropic = track_anthropic(Anthropic(), campus.tracker("dep-legal-01"))
# A LangGraph claims workflow: one item per top-level run (per="tool" or per="llm" also possible)
graph.invoke(state, config={"callbacks": [CampusCallbackHandler(campus.tracker("dep-claims-01"))]})
# Already on OpenTelemetry: finished spans become items (attribute campus.outcome, else ERROR status is failed)
provider.add_span_processor(CampusSpanProcessor(campus.tracker("dep-kyc-01"), filter=lambda s: s.name == "agent.run"))
# A nightly reconciliation job, as a decorator
@track_call(tracker=campus.tracker("dep-recon-01"), classify=lambda r, e: "escalated" if r and r.handed_off else None)
def reconcile(batch): ...
# A voice call, as a context manager
with track(campus.tracker("dep-voice-01"), new_session=True) as item:
if caller_asked_for_human():
item.outcome = "escalated"
Blackbox link (0.5.0)
If you run Zanii Blackbox, send Campus the head of each session chain: hashes and counts only, never events.
t = client.tracker("dep-trading-02")
t.blackbox_head("sess-01", chain_head, chain_length,
guard={"allowed": 412, "blocked": {"injection": 3, "exfiltration": 0, "secrets": 1, "personal_data": 2}},
disclosure_roots=[envelope["root"]]) # optional: lets you release one field later
client.send_blackbox_heads([...]) # many at once, 100 per request
client.head_proof(head_hash) # after the hourly checkpoint; check with verify_campus_proof
# On a consent request you agreed to: one field, checked against a root Campus already holds. The value is not stored.
client.submit_disclosure(42, disclosure, envelope)
# An erasure you carried out: a subject commitment, never the subject.
client.register_erasure(subject_commitment, "gdpr-erasure", "2026-11-06T09:00:00.000Z")
Blackbox gateways (0.6.0)
Let your Blackbox gateway sign and send heads itself, with a token that can do nothing else.
# Company side: register the gateway's log key (did:key). The token is shown once.
token = client.register_gateway(gateway_did, "Blackbox gateway eu-1")["token"]
client.gateways() # {"gateways": [{gateway, name, added_at, revoked_at}]}
client.revoke_gateway(gateway_did) # key and token stop now; heads already sent stay valid
# Gateway side: only heads and erasures, signed by the gateway key (company is still the company DID).
gw = CampusClient.from_gateway_token("https://campus.example", token)
head = sign_record({"v": 1, "type": "campus.blackbox_head", "company": company_did, "deployment": "dep-1",
"session": "s-1", "head": chain_head, "events": chain_length, "period": period, "nonce": nonce},
gateway_key)
gw.send_blackbox_heads([head])
Reliability
Counting is in memory; one batch per deployment per period; up to 100 batches per request. On 429, 503 or a network
error the SDK backs off with exponential jitter (never sooner than Retry-After), keeps counting and resends the same
signed batches later (same nonce, so a resend is a duplicate, never a double count). With state_dir, unsent batches
are kept on disk (append-only JSON lines, up to max_disk_bytes) and resent after a restart. A batch the server rejects is dropped and
reported to on_reject. Empty periods are not sent.
Auto-flush runs every 30 to 60 s, jittered so firms do not hit Campus in step, and flushes never overlap. Single calls
retry only 429/503, at most 5 attempts and 60 s per wait; a longer Retry-After and any other 4xx are raised at once. Standard library HTTP only; the one dependency is zanii.
Apache-2.0.
Operations (0.7.0)
from zanii_campus import CampusClient
campus = CampusClient(
"https://campus.zanii.agency", os.environ["CAMPUS_TOKEN"],
signer=kms_signer, # instead of company_key: any object with sign(bytes) and did or public_key
state_dir="/var/lib/campus", # append-only outbox, locked to this process
instance=os.environ.get("HOSTNAME"),
on_drop=lambda count, reason: log.error("campus batches dropped: %s (%s)", count, reason),
meter=metrics.get_meter("campus"), # optional OpenTelemetry Meter (no dependency)
)
print(campus.doctor()) # {"ok": ..., "checks": [{"name", "ok", "detail"}]}
print(campus.stats()) # {queued, on_disk, dropped, sent, failed, last_ok_at, last_error}
- Never a silent drop. Without
state_dir, pastmax_queued(10,000) the oldest batches are dropped andon_drop(count, "max_queued")is called. Withstate_dir, batches pastmax_queuedwait on disk; only pastmax_disk_bytes(512 MB) are new batches dropped ("max_disk_bytes"). - Crash-safe outbox. One appended (and fsynced) line per batch; rewritten only after a send, when it empties or when sent lines outweigh live ones. A torn last line is cut on load. After a crash a batch may be resent; the server answers duplicate.
- One process per state_dir. A lock file holds pid and host; a dead process's lock on the same host is taken over. A second live process gets a clear error unless it sets
instance(usesstate_dir/<instance>/). - Remote signer.
signerreplacescompany_key(zaniiRemoteSignercompatible); signatures are checked before use; outcome batches are signed at send time. doctor()checkstoken,identity,campus_key,clock,outbox,last_send,sdk_version.- Metrics.
meterregisterscampus.sdk.queue(observable gauge) and counterscampus.sdk.sent,campus.sdk.failed,campus.sdk.dropped. - Compatibility and clock.
x-campus-min-sdkandx-campus-deprecationare reported once each throughon_warning(defaultwarnings.warn). Clock skew is the median of the last 5Dateheaders; periods use the corrected time; a skew above 30 s is reported once. - Short-lived runtimes. With
auto_flush=Falseno thread starts and withoutstate_dirno file is written. Before exit:tracker.flush(); campus.close().
Firm features (0.8.0)
Regulation 10 purposes (zanii_campus.reg10), signed growth documents (zanii_campus.growth) and the shared threat feed (zanii_campus.community).
from zanii_campus.reg10 import sign_purpose, send_purpose
from zanii_campus.growth import growth_figures, verify_growth_document
from zanii_campus.community import threats
# Sign a human-approved purpose for one deployment with the company key (Regulation 10.3.2(a)).
record = sign_purpose(company_did, "support-web", "Answer questions about retail accounts", False, "Head of Operations", company_key)
send_purpose("https://campus.zanii.agency", os.environ["CAMPUS_TOKEN"], record)
# Verify an investor pack offline: campus signature and Ledger anchors of its checkpoints.
if verify_growth_document(pack, campus_did)["ok"]:
print(growth_figures(pack)) # activity_coverage, p95_worst_hour_ms; also for packs signed before 0.8.0
# Follow the threat feed: each page is verified against the campus key and chained from the last trusted head.
page = threats(campus, campus_did, after=None)
head = page["head"]
Assistance only: the Regulation 10 pack is a draft, not legal advice or a certification; licence evidence is not a DFSA decision.
Changelog
- 0.9.0:
company_api.declare_category(client, category)andcompany_api.CATEGORIES, same as @zanii/campus-sdk 0.9.0; the fake Campus serves it and addsset_category_by_difc(reg_no, category). Existing records, signed bytes and APIs unchanged. - 0.8.0: firm features, same as @zanii/campus-sdk 0.8.0:
zanii_campus.reg10(sign_purpose,verify_purpose,send_purpose),zanii_campus.growth(verify_growth_document,growth_figuresfor either figure field set) andzanii_campus.community(verify_threat_feed,threats,submit_threat, jobs, people in the loop, benchmarks, lessons, regulatory changes). Existing records, signed bytes and APIs unchanged. - 0.7.0: reliability and operations, same as @zanii/campus-sdk 0.7.0:
on_dropandstats(); overflow waits on disk up tomax_disk_bytes; append-only crash-safe outbox; state_dir lock withinstance; remotesigner;doctor(); optional OpenTelemetrymeter; min-SDK and deprecation warnings; clock skew correction. Records, signed bytes and existing APIs unchanged. Still pins zanii 0.40.2. - 0.6.0: Registered Blackbox gateways:
register_gateway,revoke_gateway,gateways,CampusClient.from_gateway_token;send_blackbox_headssends already-signed heads as they are;verify_recordtakes extra allowed signers. New record typecampus.gateway. Earlier records unchanged. Still pins zanii 0.40.2. - 0.5.0: Blackbox link:
send_blackbox_heads,Tracker.blackbox_head,sign_blackbox_head,head_proof,submit_disclosure,register_erasure,erasures. New record typecampus.blackbox_head(hashes, counts, optional guard verdict counts). Earlier records unchanged. - 0.4.0: framework adapters in
zanii_campus.adapters: OpenAI, Anthropic, LangChain/LangGraph callback handler, OpenTelemetry span processor,track_calldecorator andtrackcontext manager. Duck-typed, no new dependencies, never read content, streams counted once at the end. - 0.3.0:
proof(batch_hash)andverify_campus_proof(proof, campus_did): fetch the inclusion proof for one of your batches after the hourly checkpoint and check it offline against the campus key (the campus publishes its key at/api/public/campus-key). - 0.2.0: deployments can say what one counted item is (
unit: conversation, task, request, document, transaction, call, job, other); the counts are documented for any kind of agent, not only chat. Optional, so 0.1.0 code keeps working. - 0.1.0: first release.
Metadata
Release files for zanii-campus 0.9.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| zanii_campus-0.9.0.tar.gz | 71.7 kB | Without provenance | Details for zanii_campus-0.9.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| zanii_campus-0.9.0-py3-none-any.whl | Python 3 | none | any | Details for zanii_campus-0.9.0-py3-none-any.whl |
Total release size: 127.2 kB
Release files / zanii_campus-0.9.0.tar.gz
| Download URL | zanii_campus-0.9.0.tar.gz |
|---|---|
| Size | 71.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
1294df5c7b66ad0ae305df377f7422126ac90571d186ab2bdd9f9bcf079a2619
|
|
BLAKE2b-256 checksum How to use checksums |
9cebbfb385ae62c415e6a212febb3fae4dbe668ca9a4d6beedd9d95a79e142e0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.10
|
Release files / zanii_campus-0.9.0-py3-none-any.whl
| Download URL | zanii_campus-0.9.0-py3-none-any.whl |
|---|---|
| Size | 55.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6de6b6e37b5bddfc6212cfee23e993d43e437aeac6f73f6d512f94872a3035eb
|
|
BLAKE2b-256 checksum How to use checksums |
4ef9d560cc2bf30379b2a18c5cf110b1da9162755045c357f3cf72e9ef0778a4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.10
|
Security for zanii-campus 0.9.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.