This release is a pre-release and may not be stable for production use.
AISquare Explainability SDK
Lightweight Python SDK for tracing, graphing, and policy auditing of AI agents. Captures execution traces from any Python agent (Agno, LangChain, plain Python) and delivers them to the AISquare Explainability Gateway.
Installation
pip install aisquare
That is everything init() needs, including its default OTLP transport. The
explainability and otlp extras still resolve and add nothing.
For the recording proxy (aisquare-proxy), which also needs FastAPI and uvicorn:
pip install "aisquare[claude]"
For Agno auto-instrumentation:
pip install "aisquare[agno]"
For Google ADK auto-instrumentation:
pip install "aisquare[adk]"
For the OpenAI Agents SDK (the openai_agents extra carries the SDK runtime, so it
installs alone; it also installs beside the gateway extra, whose openai pin admits
the openai 3 that openai-agents needs):
pip install "aisquare[openai_agents]"
To check a signed AISquare receipt yourself with aisquare-verify (it needs only the
cryptography library, which this extra installs; see docs/reference/check-a-receipt.md
in the repository):
pip install "aisquare[verify]"
aisquare-verify receipt.json --public-key key.json
A receipt someone made on request (a workspace on on-demand receipts) is checked against the fingerprint of AISquare's root key, which you take from AISquare out of band, never from the file:
aisquare-verify receipt.aisq.json --root <root key fingerprint> # offline
aisquare-verify receipt.aisq.json --root <fingerprint> --gateway https://... # and ask online
The online check adds what only AISquare can say now: whether the receipt was withdrawn, erased or has expired, and whether its issuance is anchored.
Quick start
Every trace needs an agent identity on its root span — agent_name is the key
the gateway routes traces by. Name your agent explicitly and pre-register it:
# .env: EXPLAINABILITY_GATEWAY_URL, EXPLAINABILITY_API_KEY,
# EXPLAINABILITY_AGENTS=support-bot <- pre-registers; must equal agent_name below
import aisquare.explainability as sdk
sdk.init_from_env()
with sdk.AgentRunTracer(agent_name="support-bot"):
with sdk.LLMCallTracer(model="gpt-4o", provider="openai") as llm:
... # your agent logic — nested spans inherit the run's routing identity
# IMPORTANT for short-lived scripts: flush ensures traces reach the gateway
# before the process exits. Long-running services don't need this.
sdk.flush()
Using a framework instead of manual tracers? The identity contract is the
same — the agent's explicit name becomes agent.name on the root span: Agno
Agent(name="support-bot"), LangChain metadata={"agent_name": "support-bot"},
or AgentRunTracer(agent_name="support-bot") around code with no framework. The tools a LangChain model is
bound to (create_agent, LangGraph, bind_tools) are recorded without being
passed.
Automatic governance
Enable governance through the same initialization as tracing:
sdk.init_from_env(auto_instrument="agno", governance=True)
# Run ordinary framework agents and tools; no wrapper is needed.
That snippet runs on the .env from the quick start above, and the
EXPLAINABILITY_AGENTS=support-bot line there is doing more than
pre-registration: a roster of exactly one name is also the process's
default agent identity. governance=True builds a policy client inside
init(), and without an identity it raises before installing anything, so the
process exits 1:
GovernanceConfigError: PolicyClient needs a studio to check against, and nothing in this process resolved one.
The message continues with a line per setting that resolves an identity, any
one of which is enough. Set AISQUARE_AGENT_NAME=support-bot to state it
outright rather than lean on the roster, because a roster of two or more
names supplies no default identity and governance=True exits 1 there too.
init(agent_name=...) also satisfies it. EXPLAINABILITY_STUDIO_ID lets
init() start, but it pins the rule book, not the trace identity: with no name
set, trace roots carry no agent.name and the gateway refuses them with a 409,
and each check is filed under the framework's name. Set a name beside it.
Governance defaults off. Supported adapters are Agno, Google ADK, LangChain,
the OpenAI Agents SDK and Pydantic AI, and init(governance=True, auto_instrument=...) is what arms
them. Code with no framework passes auto_instrument=False: the same setup line then checks its
@check_tool (and @trace_tool) calls before they run, the reply a @check_reply() function
returns before it is sent, and the person's message given to check_message(text) before the
model reads it, each under the enclosing AgentRunTracer's agent. See
Lifecycle and compatibility.
Upgrading from 1.3.0
GovernedAgent is removed. One way connects an agent:
init(governance=True, auto_instrument=...), naming the framework, or auto_instrument=False for
code with no framework, whose tool calls, replies, messages, retrievals and file writes
check_tool, check_reply, check_message, check_retrieval and check_file_write then
check. Importing GovernedAgent raises ImportError saying so. Praxis lessons
(AISQUARE_PRAXIS_INJECT=true) now need init(governance=True); a tracing-only process gets
none. Its
rule_book= argument goes with it: rule books are set up in the AISquare platform and attached to
an agent there. The pre-adapter governance modules adapters.agno_governance and
adapters.openai_agents_governance are removed, so is adapters.langchain_governance (its span
enrichment is now internal to the LangChain adapter), and governance.runtime keeps only
record_on_span.
Governance defaults off. The Agno, Google ADK and LangChain adapters
defaulted to governance=True in 1.3.0, which installed each framework's
legacy governance module. They default to off now, so a process that
configured studio credentials and called init(auto_instrument=...) with no
governance= argument traces and makes no policy call at all. What that costs
is not the same for each framework.
Google ADK loses enforcement, not just telemetry. 1.3.0 attached a plugin
to every ADK Runner that gated each tool call before it ran (a block
replaced the tool's result with {"status": "blocked_by_policy", ...} and the
tool never executed) and checked the run's final output once. Neither is
installed now.
What 1.3.0 actually delivered depends on the shape, so measure yours before you
read this line as a loss. Measured on google-adk 2.9.1, with the wrapper built
around the same Agent object the Runner is given, 1.3.0's pre-tool gate
never fired: the plugin attached and its hook ran, but ADK hands the run a copy
of the agent while the plugin routes on object identity, so the denied tool RAN
and the one policy call the run made was the legacy observe-only output check.
In that shape an upgrade loses an observe-only check, not a working gate. One
line restores the gate and goes past what 1.3.0 did:
sdk.init_from_env(auto_instrument="adk", governance=True)
A denied tool call raises PolicyDenied out of runner.run_async instead of
feeding a dict back to the model, and the run's events are held until the
output check passes instead of being checked after delivery.
Before assuming 1.3.0 was enforcing for you: that plugin found its kernel by the
identity of the object you wrapped, and google-adk 2.x hands the callback a
per-invocation clone of your agent. Measured on google-adk 2.9.1, the lookup
missed, the pre-execution gate returned no verdict and the tool ran. The
init(governance=True) path does not depend on that lookup.
Google ADK traces route by the root agent's name. The trace root carries
the root Agent(name=...) as agent.name (each agent span carries its own
agent's name), and the gateway routes the trace by it (#958). In 1.3.0 the root span carried the default
identity (AISQUARE_AGENT_NAME or init(agent_name=...)) instead. A process
whose default identity differs from its ADK agent's name now files its traces,
and its governance checks, under the agent's name; on a workspace key that
name is registered as an agent of the same workspace on first sight. Set the
two equal to keep one identity.
Google ADK code executors are gated as a tool call. With governance armed,
the code a client-side BaseCodeExecutor (UnsafeLocalCodeExecutor,
container, Vertex AI, GKE, Agent Engine, or your own subclass) is handed is
checked in the tool_call scope before it runs, under the tool name
code_execution (_adk_hooks._CODE_EXECUTION_TOOL) with the code as its one
parameter ({"code": ...}). A policy with a tool allowlist must list that name, or
every executor run is denied. A skill script costs two checks (the skill tool
call, then its code), ADK's own data-file exploration code is checked once per
file, and on google-adk 1.x the check runs on the event loop, because ADK 1.x
calls the executor inline there.
Google ADK answer tools are output, not tool calls. A call to
finish_task (a mode="task" agent's answer) or set_model_response (an
output_schema agent's answer when it also has tools) is graded in its agent's
llm_output check, and ADK's own classes for them are exempt from the tool
gate, so an allowlist does not list them. Their names are read from the
installed ADK when governance arms, under the same missing-name rule as every
patched boundary: an ADK with task mode but no FinishTaskTool refuses
init(governance=True) naming it, and google-adk 2.7.0, which does not export
the finish-task wrapper key, reads it as result, the value it hardcodes. An
agent driven with agent.run_async(ctx) and no Runner is held and graded
like a Runner's run.
LangChain loses one telemetry signal and a billable call, and no
enforcement. Tracing-only init used to make one policy.scope="llm_output"
call per chain end and stamp the policy.* span attributes; it now makes none.
That is deliberate: a tracing-only install should not make a billable
enforcement call, 1.3.0 documented no way to switch it off, and it withheld
nothing in any case, because the legacy check ran with raise_on_block=False
and discarded its verdict. It affects every init(auto_instrument="langchain")
process, not only code that built the callback handler by hand.
governance=True brings the checks back as real gates. The same applies to an
adapter built by hand, on all five: AgnoAdapter, ADKAdapter,
LangChainAdapter, OpenAIAgentsAdapter or PydanticAIAdapter with governance=True arms the real
gates, so instrument() raises GovernanceConfigError unless gateway
credentials resolve. In 1.3.0 governance=True was the default on the first
three and installed the observe-only patches.
adapters.adk_governance.install_governance_patches() raises. That module
shipped in the 1.2.0 wheel under a public name and its own docstring taught the
import. The implementation is gone: the call raises RuntimeError naming
init(governance=True, auto_instrument="adk") as what installs ADK governance
instead, because an empty patch list would read as "nothing to install here"
and leave the caller believing ADK is governed. Its
uninstall_governance_patches() is a no-op.
Agno loses its observe-only output check and two enrichers. 1.3.0's default
install added a post-hook to every Agent and Team that made one
llm_output check per run with raise_on_block=False, so it withheld nothing,
and stamped policy.decision on the span. Tracing-only init now makes no policy
call and stamps no policy.* attribute. That install also registered the
team_routing and tool_selection span enrichers; init(auto_instrument="agno")
does not. The agent span's
system prompt is read from the agent's own fields (system_message, else
description, role, instructions, expected_output and
additional_context) and not from agno's get_system_message(), so the
sections agno adds at run time (tool instructions, the
<additional_information> block, a Team's member list) are not in it.
Structured answers are graded as the values the caller reads. On every
adapter, a structured answer (an agno output_schema result, a Pydantic AI
structured result.output, an ADK answer-tool call, a LangChain tool call, or
JSON the model wrote for a declared schema) is graded as its keys and string
values, raw, then their JSON (adapters/_answer.py), not as its str() or
json.dumps, which escape every newline and quote the model wrote, and not
through its serializer: a pydantic model is read field by field, so
Field(exclude=True), SecretStr, a masking serializer or a subset
model_serializer hide nothing from the gate, and a RootModel[str] is graded
as the string itself. A leaf the renderer cannot read as the caller reads it
refuses the answer with a GovernanceConfigError naming it: a computed field
that raises, or a value of a class the author wrote, whose str() shows
whatever that class chose rather than the value. The same reading renders a
Pydantic AI tool call's validated arguments for the tool gate. A rule written for text
answers matches the same record in a structured one. The trade-off: a keyword a
schema key contains matches, and a threshold rule on output_length reads a
structured answer at about twice its JSON length, so a rule sized on text
answers can deny a structured answer it allowed (measured: a four-field
pydantic model with a 228-character repr and 234-character JSON is graded as
444 characters).
One default agent name. init(agent_name=...) owns the process default
agent identity. A governance_config agent_name is a second spelling of it,
in init() or in get_adapter(..., governance_config=...): equal, or given
alone, it becomes the default for traces and governance alike, and two
different names raise ValueError (identity.one_default_agent_name). That
rule also runs under init(governance=False) when a governed adapter armed
outside init() disagrees. A blank or whitespace-only name is absent: the
default applies. A governed init() or init_from_env() that names no agent
raises ValueError when the environment's name (AISQUARE_AGENT_NAME,
EXPLAINABILITY_AGENT_NAME or a one-entry roster) differs from a name an
adapter armed outside init() holds. A repeated governed init() refuses a
changed EXPLAINABILITY_STUDIO_ID the way it refuses a rotated key.
The SQLite inbox is gone; OTLP is the one transport. init() and
init_from_env() send every span as OTLP/HTTP protobuf to /v1/traces. A
bundle the gateway does not take is kept in a per-process outbox,
explainability_outbox.<pid>-<uuid8>.db in EXPLAINABILITY_OUTBOX_DIR, else in
the directory of inbox_path / EXPLAINABILITY_INBOX_PATH (the working
directory by default), and a retrier thread posts it again. A later process
adopts the outbox file of a process that exited. EXPLAINABILITY_TRANSPORT=inbox
or transport="inbox" logs one WARNING and runs OTLP; any other value but
otlp raises ValueError. sweep_interval and max_retry are accepted and
ignored. These variables are no longer read: EXPLAINABILITY_OUTBOX,
EXPLAINABILITY_OTLP_INBOX_FALLBACK, EXPLAINABILITY_INBOX_QUEUE_MAX,
EXPLAINABILITY_INBOX_QUEUE_MAX_BYTES, EXPLAINABILITY_INBOX_BATCH_SIZE,
EXPLAINABILITY_INBOX_STAGING_MAX_BYTES, EXPLAINABILITY_INBOX_SPILL_PATH,
EXPLAINABILITY_INBOX_SPILL_MAX_BYTES, EXPLAINABILITY_FINAL_SWEEP_CONCURRENCY,
the EXPLAINABILITY_EXPORTER_* flush windows and EXPLAINABILITY_OTEL_PROCESSOR.
An old inbox file left at inbox_path is delivered once: the first init() after
the upgrade posts its pending rows (each under its own key, or the configured key)
to /v1/traces/ingest off the calling thread, then renames the file
explainability_inbox.db.migrated. A gateway that is down leaves the file for the
next start.
shutdown(timeout=...) bounds the outbox drain. It tries every pending
outbox bundle once inside the timeout; bundles it did not send stay in the
outbox file for the next process that adopts it.
selfcheck probes OTLP. It sends its probe over the SDK's one transport.
--transport is gone; --endpoint names a full traces URL.
OTLP float knobs are range-checked. A float knob built in code
(OTLPTransportConfig(...), or an override passed to from_env(...) or
span_processors(...)) outside the range in otlp_transport._FLOAT_KNOBS
raises ValueError. The same value from the environment (EXPLAINABILITY_OTLP_*)
falls back to the default with a WARNING when it is not finite or is above
threading.TIMEOUT_MAX, where 1.3.0 took an infinite or oversized value as
given and every export then failed with OverflowError.
Agno's direct model streams refuse under governance. With agno governed,
Model.response_stream() or Model.aresponse_stream() called by hand outside a
run raises GovernanceConfigError, as Pydantic AI's
direct.model_request_stream() does, because the reply would reach the caller
before any check. Model.response() and Model.aresponse() are gated; a run
streams as before.
The adk extra takes google-adk from its instrumentor, below 2.12. It
depends on openinference-instrumentation-google-adk[instruments], whose
releases each carry the google-adk range they instrument, and caps google-adk
below 2.12, which opens its agent spans in a way the newest instrumentor
(1.0.4) does not handle yet. One pairing still installs and fails,
instrumentor 0.1.x with google-adk 2.10 or later: the instrumentor raises, the
SDK refuses it for the rest of the process rather than stacking its wrappers on
every init(), and init(governance=True) raises GovernanceConfigError.
CI's newest leg installs the newest google-adk below 2.12 with the
instrumentor pip pairs it with. A google-adk of 2.12 or later installed outside
the extra still arms, and init() warns once that its own agent spans (scope
gcp.vertex.agent) join each run's trace beside the SDK's.
The extra also requires
opentelemetry-semantic-conventions>=0.58b0, whose names google-adk imports,
which lifts OpenTelemetry to 1.37 or later.
pip can quietly install 1.3.0. The agno and pydantic_ai extras require
agno 3.0.11 and pydantic-ai-slim 2.52 or later. A project that pins an older
release of either and asks for aisquare[agno] or aisquare[pydantic_ai] with
no version of aisquare gets 1.3.0 from pip, with no error. The same happens
to aisquare[gateway] beside an idna pin other than 3.20, and to
aisquare[adk] beside openinference-instrumentation-google-adk below 0.1.11,
under pip and uv alike. Require aisquare>=2 to turn that into a resolver
error.
Pydantic AI: PydanticAIAdapter has no translate= option. It always
registers its pre-export translation processor, because untranslated spans
carry no root agent.name and a workspace-keyed ingest rejects them; passing
translate= raises TypeError.
Pydantic AI hands its instrumentation back on shutdown(). 1.3.0 switched
Pydantic AI's own instrumentation off for every agent when the adapter came
down (Agent.instrument_all(False)). Now shutdown() restores the setting the
host had before init(), so a host that instruments Pydantic AI itself keeps
its instrumentation.
Pydantic AI tool definitions are capped like every other adapter's.
llm.tools, read from gen_ai.tool.definitions, is capped at 8,000
characters: past that the attribute is the {"_truncated": true, ...} marker
the other adapters send, not the whole list. About 30 ordinary tools reach it.
A LangChain model or tool at a trace root routes by its own metadata. A chat
model, LLM or tool invoked directly is the root of its trace, and its
metadata["agent_name"] is now stamped as the root's agent.name, as a chain
root's already was. The gateway routes that trace by it, where 1.3.0 routed it
by the default identity.
AISQUARE_PROXY_FILE_OP_MAX_CHARS has a floor. The proxy sends the first
this many characters of a Write or Edit's content to the file-op check
(default 32,768). A value below 1,024, 0 included, logs a warning and uses
1,024, so a check always carries content.
GovernanceBinding.gate() refuses a call that grades nothing. A gate call
carrying nothing its scope's handler reads raises GovernanceConfigError, where 1.3.0 returned
Decision(outcome="allow"). Two of those shapes come from runtime data rather
than from a programmer error, so guard them in your own loop: a tool-only model
turn whose content is None, passed as gate(scope="llm_output", text=message.content), and a retrieval that found nothing, passed as
gate(scope="retrieval", args={"documents": []}) with no text. An empty
string is a subject (text="" is graded), and passing the query as text=
keeps a zero-hit retrieval gradable. See Lifecycle and
compatibility
for the full table.
Governance refuses a framework release that lacks a patched name.
init(governance=True) raises GovernanceConfigError naming every missing
name when the installed framework predates one a governance patch set needs,
before any gate is written; tracing still installs on those releases and skips
only the missing run wrappers. This is one rule for every adapter
(_PatchSet's missing-target rule), and it reads names, not version numbers.
Measured, the first releases that arm: Agno 2.9.0 (with fastapi installed,
because agno.workflow imports it), Pydantic AI 2.52.0 (the first with
pydantic_ai.workspaces) and langchain-core 1.4.0 (the first with
BaseChatModel._should_use_protocol_streaming); Google ADK arms from the
floor its adk extra declares in pyproject.toml.
The agno extra requires openinference-instrumentation-agno 1.0 or
later. 0.1.x cannot instrument agno 3, so an environment that kept it
through pip install -U "aisquare[agno]" lost every agno span and
init(governance=True) refused. The upgrade now moves both.
Do not pin openinference-instrumentation-agno on older agno. Its 0.1.18
and older _uninstrument writes the saved Agent._run back over Agent.run,
so a 1.3.0 shutdown() (or a governed init() that rolled back) left the
process's own agent.run() raising TypeError on the agno releases those
versions instrument. That is an upstream bug, fixed in 0.1.19. The SDK reads
the installed instrumentor's version and, below 0.1.19, leaves it armed at
shutdown() instead of calling that _uninstrument, so no pin is needed:
measured on agno 2.2.0 with oi-agno 0.1.18, Agent.run is still run after
shutdown(). Pinning >=0.1.19 instead removes agno tracing on the releases
it would address, because that range no longer has one: on agno 1.7.0 it
resolves oi-agno 1.0.10, which instruments agno >= 2.5.0 only, so the SDK
reports the adapter armed and every agno span is lost.
Forked children. Nothing is logged because of a fork, in either process. A
child that inherited a governed adapter refuses every governed call with a
RuntimeError naming the adapter and telling it to call
init(governance=True) in the child; a successful bare init() or a
shutdown() in the child takes the inherited hooks off instead, leaving that
framework ungoverned there. An init() that raises in the child leaves them
installed and refusing, including a governed init() whose own install fails.
An adapter the host re-arms in the child itself (uninstrument(), then
instrument(tracer)) is the host's again, and the child's bare init() and
shutdown() leave it armed.
Tracing is a separate question from governance here. A forked child keeps
exporting through the path it inherited, so a worker a preloading server forks
(gunicorn --preload, uWSGI, a multiprocessing pool) ships its spans without
calling init() again. The child's own init() replaces that path rather than
adding to it, so each span is sent once. The child never delivers its parent's
outbox: it runs no retrier until it calls init() itself.
An unreadable failure mode refuses every policy client.
EXPLAINABILITY_POLICY_FAILURE_MODE accepts FAIL_OPEN and
FAIL_CLOSED, and the shorter open and closed (case and surrounding
whitespace ignored; blank is unset). Any
other value raises GovernanceConfigError, naming the variable and the value,
wherever a policy client is built from it, where 1.3.0 read it as FAIL_OPEN:
PolicyClient() fails at construction, and init(governance=True) fails before
any adapter is armed. governance_config={"failure_mode": ...} is read the
same way.
An unusable policy timeout refuses every policy client.
EXPLAINABILITY_POLICY_TIMEOUT takes a positive number of seconds, at most
threading.TIMEOUT_MAX (blank is unset, 30). Any other value (0, -1,
nan, inf, a word, 1e10) raises
GovernanceConfigError, naming the variable and the value, wherever a policy
client is built from it, where 1.3.0 used 30 for a word and failed every check
for the others: init(governance=True) fails before any adapter is
armed. Under gateway governance aisquare-proxy refuses to start on such a
value; a process serving claude_proxy:app without run_proxy reads it as 30
and logs it at ERROR.
PolicyClient(timeout=...), when given, is used instead of the variable; in
1.3.0 the variable won.
PolicyGate(timeout=...) and EXPLAINABILITY_GATE_TIMEOUT are gone. They
never bounded a check. The policy client's timeout bounds each read of a check
and how late a resend may start; a check's wait for a pooled connection has no
limit. Passing timeout= to PolicyGate raises TypeError naming
EXPLAINABILITY_POLICY_TIMEOUT.
PolicyClient.sync_rewrite_output returns a pair. It returns (text, None)
for a rewrite and (None, reason) when there is none, where 1.3.0 returned the
text or None. Read the first item: the pair itself is always truthy. A client
you inject that still returns the text alone keeps working behind the proxy.
When no verdict can be obtained (gateway outage, 5xx, circuit breaker open) the
default posture is FAIL_CLOSED: the action is held with a plain reason and the
decision is flagged as degraded. Pass
governance_config={"failure_mode": "FAIL_OPEN"} to let it through, flagged,
with a WARNING logged, instead. A check waiting for a pooled connection is
neither released nor refused: it waits, with no time limit, until a connection
frees.
See Python adapter governance for execution boundaries, streaming restrictions, outage behaviour, lifecycle, and configuration.
Business keys: your own ids on a run
Put your own identifier on a run, such as a claim id or an order number:
with sdk.AgentRunTracer(agent_name="claims-bot"):
sdk.set_business_key("claim_id", "CL-77")
...
It is recorded as aisquare.key.claim_id and sealed when the run arrives, so a receipt
for many runs can later be made for "every run about claim CL-77", and its reader can check
that no run AISquare recorded with a matching label was left out. A name is 1 to 64 of
a-z, 0-9, _ and .; a value is a string or an integer of at most 256 bytes (UTF-8). A bad name or value raises ValueError
where you set it; a value that is not a str or int raises TypeError. Outside a traced run it sets nothing and returns False.
Policy checks name the run they judge
Every policy check the SDK sends (PolicyClient, the governance adapters, the setup line's
checks for code with no framework, and the recording proxy) carries the run's trace id, and a tool check carries the
framework's tool call id. AISquare records them with the check, so a receipt of the run lists
the check. PolicyClient sends a step's span id only when you pass one (span_id=) and does
not fill it in from the current span, because AISquare counts violations and model-judged
checks per run until per-step counting is decided; the governance adapters and the recording
proxy pass the span of the step they judge. Nothing to configure; a check made outside a
traced run carries none.
What the SDK captures
The SDK collects two layers of signal:
Auto-instrumentation (zero tracing code): The AgnoAdapter installs openinference-instrumentation-agno, which automatically wraps every Agno agent run, LLM call, and tool invocation as an OTel span. The Agno Agent(name=...) becomes the trace's routing identity — always name your agents.
Manual tracers (governance-grade): Nine context-manager tracers you can add to any Python code — framework-agnostic:
| Tracer | Purpose |
|---|---|
AgentRunTracer |
Wraps a full agent run as the root span |
LLMCallTracer |
Records an LLM inference call with I/O and token counts |
ToolCallTracer |
Records a tool invocation with parameters, result, and errors |
RetrievalTracer |
Records a RAG retrieval with documents and scores |
HumanInterventionTracer |
Records a human-in-the-loop review or correction |
RoutingTracer |
Records a routing/delegation decision with selected and rejected paths |
DecisionTracer |
Records a general decision point with options, selected, and rejected paths |
PolicyGateTracer |
Records a policy-gate evaluation with the policies checked and the allow/deny outcome |
MemoryTracer |
Records memory read/write operations |
Decorators are also available: @trace_tool and @trace_retrieval.
Manual instrumentation (any framework)
Leaf tracers (LLM, tool, routing, ...) always run nested inside an
AgentRunTracer — its agent_name is stamped as agent.name on the root
span, the attribute the gateway routes the trace by. A trace with no agent
identity is rejected at ingest (409 no_agent_identity).
import aisquare.explainability as sdk
sdk.init_from_env()
with sdk.AgentRunTracer(agent_name="MyAgent", run_id="abc-123") as run:
run.set_input("User query")
with sdk.LLMCallTracer(model="gpt-4o-mini", provider="openai") as llm:
response = call_openai(...)
llm.set_input_messages([{"role": "user", "content": "..."}])
llm.set_output_messages([{"role": "assistant", "content": response}])
llm.set_token_counts(prompt=100, completion=50)
with sdk.RoutingTracer(decision_type="tool_selection") as rt:
rt.set_selected("web_search", reason="Query requires fresh data")
rt.set_rejected([{"name": "cached_search", "reason": "Cache is stale"}])
run.set_output("Agent final answer")
sdk.flush()
Add the Check contract to your own loop
If you run your own loop in any language, ask AISquare before and after each step. The thin Python client is
aisquare.explainability.check. It sends one call and returns one verdict (allow, warn, improve, block or
not_checked); the page is docs/guides/check-contract.md, and a runnable example is
examples/check_contract/check_client.py.
from aisquare.explainability.check import CheckClient
check = CheckClient() # reads EXPLAINABILITY_GATEWAY_URL, EXPLAINABILITY_API_KEY, AISQUARE_AGENT_NAME
before = check.before({"type": "tool_call", "name": "reverse_fee", "arguments": {"amount": 150}}, run_id="run-7f3a")
if before.proceed:
... # run the tool, then check.after({"type": "tool_result", "name": "reverse_fee", "result": result}, run_id="run-7f3a")
AsyncCheckClient is the same with await. It never raises for an outage: with no verdict it answers not_checked,
and failure_mode decides whether the step goes on or is held.
Environment variables
| Variable | Description |
|---|---|
EXPLAINABILITY_GATEWAY_URL |
Gateway base URL for trace ingest |
EXPLAINABILITY_API_KEY |
API key for trace ingest |
EXPLAINABILITY_AGENTS |
Comma-separated agent names registered at init; must match your AgentRunTracer / framework agent names |
AISQUARE_AGENT_NAME |
The SDK's default agent identity, in two roles: the identity used for policy checks, and (since 1.0.6) the fallback trace identity stamped on spans that would otherwise be rootless so the trace still routes. Keep it equal to your agent_name. |
EXPLAINABILITY_TRANSPORT |
otlp (default and only value: OTLP/HTTP protobuf to /v1/traces, retries honouring Retry-After, partialSuccess logged, the local outbox as durable store; the encoder is a base dependency), read when no transport argument is passed. The retired value inbox logs one WARNING and runs OTLP. Tuning: EXPLAINABILITY_OTLP_*, see docs/reference/sdk-api.md |
EXPLAINABILITY_OUTBOX_DIR |
Directory of the per-process outbox files. Default: the directory of EXPLAINABILITY_INBOX_PATH, which defaults to explainability_inbox.db (so the working directory) |
AISQUARE_DOCTOR |
Set to off to silence the start check. At every start the SDK checks its key, the gateway, its adapters and the proxy in a background thread and, when something is wrong, prints the problem and its fix once. A healthy start prints nothing. |
Multiple agents: name each agent in code (AgentRunTracer(agent_name=...)
or the framework equivalent) — that per-run name is what routes each trace.
AISQUARE_AGENT_NAME holds a single name and is a single-agent convenience
only; it cannot distinguish between agents in the same process.
Diagnostics
The SDK ships a built-in health checker:
explainability-doctor
It exits 1 when a check says this process cannot send runs: no gateway URL, no key, httpx
missing, or any check in error. A CI step that runs it fails then; an optional part that is
missing, such as a framework you do not use, does not fail it.
Its agent_identity check warns when no agent identity is configured (the
classic precondition for 409 no_agent_identity ingest rejections). Its
outbox check, read by aisquare.explainability.doctor.run_doctor() inside the
traced process, reports the outbox's pending and dead-lettered bundles and the
spans it lost.
To prove an integration end to end, send one probe trace and read it back:
python -m aisquare.explainability.selfcheck # over OTLP
It prints the resolved agent name, studio, workspace and span count and exits
2 on a rejected key, 3 when the gateway could not route the probe, 4 on a
mismatch, 5 when the gateway is unreachable.
License
MIT
Metadata
Release files for aisquare 2.1.0rc1
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 |
|---|---|---|---|---|
| aisquare-2.1.0rc1.tar.gz | 8.5 MB | Without provenance | Details for aisquare-2.1.0rc1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| aisquare-2.1.0rc1-py3-none-any.whl | Python 3 | none | any | Details for aisquare-2.1.0rc1-py3-none-any.whl |
Total release size: 9.6 MB
Release files / aisquare-2.1.0rc1.tar.gz
| Download URL | aisquare-2.1.0rc1.tar.gz |
|---|---|
| Size | 8.5 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
0b4b68dffa87bc4e3bcfb752616bee9637f03b4acfae386dc7058c9645e45bae
|
|
BLAKE2b-256 checksum How to use checksums |
294cea78a042b6c7ae8f6ece8950a5f98f830ae5739830e741aaa2154b6a319c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Release files / aisquare-2.1.0rc1-py3-none-any.whl
| Download URL | aisquare-2.1.0rc1-py3-none-any.whl |
|---|---|
| Size | 1.0 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6bcc380d1fda73a2824a6b576c7e0460e61a2abb21532f826c37b5cfb29ebbd4
|
|
BLAKE2b-256 checksum How to use checksums |
31b332bb0c293a580ab708808ff168fc6bb157fc380a85a532eb3df8012d11d4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Security for aisquare 2.1.0rc1
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.