API reference
Everything the zyonix package exports, for SDK version 0.1.13. Anything whose name starts with an
underscore (zyonix._core, zyonix._config...) is internal and may change without notice.
import zyonix
| Name | Kind | Purpose |
|---|---|---|
init | function | start the SDK, once per process |
run | decorator / context manager | one document = one run |
step | decorator | a named stage inside a run |
tool | decorator | a function that acts on the outside world |
output | function | the run's final result, the one that is checked |
check | function | a check your application evaluated itself |
flag | function | a problem your application noticed itself |
feedback | function | a person's correction or verdict |
flush | function | wait until queued data is sent |
shutdown | function | flush and stop the SDK |
current_trace_id | function | the id of the active run |
ReplayBlocked | exception | a tool with side effects was called during a replay |
__version__ | string | the installed SDK version |
guard, observe, RepairHint, GuardHold, GuardReport, last_guard_report | runtime repair; not available in customer installations |
Guarantees that apply to every call
- Never raises into your code. An error inside the SDK is caught, counted and logged at debug
level (logger
zyonix), and your function runs as it would without Zyonix. The only exceptions the SDK raises on purpose areReplayBlocked, and only whilezyonix testorzyonix replayre-runs a step, andGuardHold, which customer installations never raise. - Your exceptions pass through unchanged. An exception raised by your function is recorded and re-raised as the same object, with the same traceback.
- Pass-through when off. Without
init(), with tracing off, or outside a run, every decorator simply calls your function and every function returns at once. - Cheap on your thread. Your thread redacts and serialises the payloads and puts them on a bounded queue. Sending happens on a background thread. If the queue is full or Zyonix is unreachable, data is dropped and counted, never retried forever, never allowed to block you.
- Content leaves only with full capture, after redaction on your machine. See Configuration.
zyonix.init
zyonix.init(
api_key: str | None = None,
service: str | None = None,
release: str | None = None,
*,
endpoint: str | None = None,
mode: str | None = None,
config_file: str | None = None,
**options,
) -> None
Starts the SDK. Call it once per process, at start-up, before the first document is handled.
| Parameter | Default | Meaning |
|---|---|---|
api_key | ZYONIX_API_KEY | An sdk key. Leave it out and set the environment variable instead, so no secret is in your code. |
service | ZYONIX_SERVICE, then service in zyonix.yaml, then "unknown-service" | Short, stable name of the application. |
release | ZYONIX_RELEASE | The deployed version (git commit, build id). Used to detect releases and link problems to recent changes. |
endpoint | ZYONIX_ENDPOINT, then endpoint in zyonix.yaml, then http://localhost:8000 | Your Zyonix address, https://zyonix.example.com. A trailing / is removed. |
mode | ZYONIX_MODE, then mode in zyonix.yaml, then "remote" with a key or "off" without | "remote", "local", "console" or "off". See Modes. |
config_file | ZYONIX_CONFIG, then ./zyonix.yaml | Path of the configuration file. |
Keyword options (**options). Each overrides the same setting from the environment and the
file:
| Option | Type | Default | Meaning |
|---|---|---|---|
capture | "full" or "hash_only" | "hash_only" | "full" sends redacted content. Any other value means "hash_only". |
ca_file | path | ZYONIX_CA_FILE | PEM file of a private certificate authority to trust for the endpoint. |
local_only | bool | True | Send only to a local address or one listed in egress_allow. |
egress_allow | list of host names, or one comma-separated string | [] | Public hosts you allow, such as ["zyonix.example.com"]. Replaces the file's list. |
otel_provider | "private" or "shared" | "private" | "shared" joins your application's own OpenTelemetry provider. |
instrument | "auto", "none" or a list such as ["openai"] | "auto" | Which LLM libraries to record automatically. |
local_path | path | "zyonix-traces.jsonl" | The file mode="local" writes. |
max_payload_bytes | int | 524288 (512 KB) | A larger input, output, record or attribute is cut and marked truncated. |
redaction_presets | list of str | ["email", "phone", "iban", "card_number"] | Built-in masks. Also "national_id". |
custom_patterns | list of tuples | [] | Your own masks: (name, regex), (name, regex, context, window) or (name, regex, context, window, unless). See Redaction. |
queue_size | int | 2048 | Spans the export queue holds. |
queue_max_bytes | int | 268435456 (256 MB) | Bytes the export queue holds. |
batch_size | int | 256 | Spans per export batch. |
schedule_delay_s | float | 1.0 | Seconds between export batches. |
export_timeout_s | float | 5.0 | Timeout of one export request. |
max_batch_bytes | int | 4194304 (4 MB) | Bytes of one export request, before compression. |
export_compression | "gzip" or "none" | "gzip" | Compression of export requests. |
The file zyonix.yaml validates its values; init options are applied as given. Prefer the file
for anything beyond capture and the connection settings, and run zyonix doctor after a change.
An unknown option is ignored with a warning.
Returns None.
Behaviour:
- Settings come from, in order of precedence:
initarguments,ZYONIX_*environment variables,zyonix.yaml, built-in defaults. Details: Configuration. - Without a key and without
mode="local"or"console", tracing is off: the SDK logszyonix: tracing is offat info level and every decorator becomes a pass-through. - If
zyonix.yamlexists but is invalid, tracing is off until it is fixed. - If the endpoint is a public host that is not in
egress_allow, or plainhttp://to a public host, remote tracing is off, with a warning. - A second call in the same process logs
init() called twice; ignoring the second calland does nothing. To start again with other settings, callshutdown()first. - Registers a handler that flushes for up to 2 seconds when the interpreter exits.
- Detects installed LLM libraries and records their calls (see LLM libraries).
- Never raises. If start-up fails, it logs
zyonix: init failed, tracing disabledand tracing stays off.
import os
import zyonix
# Typical: everything else from the environment
zyonix.init(service="invoice-extractor", release=os.getenv("GIT_SHA"))
# Local development: write to a file, send nothing
zyonix.init(service="invoice-extractor", mode="local", local_path="zyonix-dev.jsonl")
# Full capture chosen in code (after agreeing what may be sent)
zyonix.init(service="invoice-extractor", capture="full")
zyonix.run
class zyonix.run(doc_id=None, source=None, *, doc_name=None)
One document, from start to end: a new trace in Zyonix, shown as one document on the website. Use
it as a decorator (def or async def) or as a context manager (with or async with).
| Parameter | Type | Meaning |
|---|---|---|
doc_id | value or callable | The document's own stable id. Converted to str. Sent in clear in every capture mode. |
source | value or callable | Where the document came from ("email", "api"). Converted to str. Sent in clear. |
doc_name | value or callable | The document's real file name. Content: sent only with full capture; shown to administrators only. |
Callables. As a decorator, a callable receives the decorated function's arguments:
@zyonix.run(doc_id=lambda message, config: message["id"])
def process(message: dict, config: dict) -> dict: ...
If calling it with all arguments raises TypeError, it is called again with the first positional
argument only, so lambda message: message["id"] also works for process(message, config). On a
method the first argument is self: write lambda self, job: job.id. If the callable fails, the
run is recorded without that value (the run itself is never lost because of it).
In the with form there are no arguments to pass: give values.
Attribute trace_id: str | None: the run's id (32 hexadecimal characters) inside a with
block; None before the block, after it, and when tracing is off.
Behaviour:
- Every run starts a new trace, even when it is called inside another span of your own application (it is linked to that span instead).
- An exception that leaves the function or block is recorded on the run (its type; its message only with full capture) and re-raised unchanged. The context manager never suppresses exceptions.
- Steps, tools, checks,
outputand automatically recorded LLM calls made inside the run belong to it, including inasynciotasks it starts. Threads you start do not inherit it (see threads). - Not meant for generator functions: the run ends when the function returns.
@zyonix.run(doc_id=lambda doc_id, path: doc_id, source="upload-folder",
doc_name=lambda doc_id, path: Path(path).name)
def process(doc_id: str, path: str) -> dict: ...
async def handle(message):
async with zyonix.run(doc_id=message.id, source="queue") as run:
log.info("zyonix run %s", run.trace_id)
...
zyonix.step
zyonix.step(
name: str,
*,
kind: str | None = None,
replayable: bool = False,
version: str | None = None,
capture_input: bool = True,
capture_output: bool = True,
) -> decorator
A named stage of a run. Works on def and async def functions.
| Parameter | Default | Meaning |
|---|---|---|
name | required | The step's name, shown on the website and used to group problems by step. Keep it stable. |
kind | from the name | One of INGEST, PARSE, RETRIEVE, LLM, TOOL, TRANSFORM, DELIVER (any case). An unknown kind is logged and replaced by TRANSFORM. |
replayable | False | Marks the one step zyonix test / zyonix replay may call again with recorded arguments. See the rules. |
version | None | Your own version label of this step (for example a prompt version), recorded with it. |
capture_input | True | False records the step without its arguments. |
capture_output | True | False records the step without its return value. |
Kind from the name, when kind is not given:
| Name (any case) | Kind |
|---|---|
ingest, receive | INGEST |
ocr, parse | PARSE |
retrieve | RETRIEVE |
extract | LLM |
postprocess, transform | TRANSFORM |
deliver | DELIVER |
| anything else | TRANSFORM |
Returns a decorator; the decorated function keeps its signature, name and docstring, and returns exactly what your function returns.
Behaviour:
- The input is the function's arguments, bound to their parameter names (without
selfandcls), as a JSON object. The output is the return value. Both are redacted, then cut tomax_payload_bytes, then hashed; under full capture the redacted text is sent too. - Values are converted to JSON as follows: pydantic models through
model_dump, dataclasses as dicts, sets and tuples as lists, dates as ISO text,Decimalas text, enums as their value,bytesas{"__bytes__": <length>, "sha256": "<hash>"}(never the bytes), and any other object as itsrepr(up to 200 characters). - An exception passing through the step is recorded on it and re-raised unchanged.
- Outside a run, or with tracing off, the step just calls your function.
- With
replayable=True, a plaindefstep is marked so the replay commands may call it; anasync defstep is never called by a replay. If a replayable step's input is cut bymax_payload_bytes, the SDK warns once for that step.
@zyonix.step("ocr")
def ocr(image_path: str) -> str: ...
@zyonix.step("extract", replayable=True, version="invoice-v3")
def extract(document_text: str, config: dict) -> dict: ...
@zyonix.step("upload", kind="DELIVER", capture_input=False)
def upload(blob: bytes, url: str) -> None: ...
zyonix.tool
zyonix.tool(
name: str | None = None,
*,
side_effects: bool = True,
capture_input: bool = True,
capture_output: bool = True,
) -> decorator
A function that acts on the outside world or that the AI calls: a database write, a message, a
search, an external API. Recorded as a step of kind TOOL, so a failing tool is reported as that
tool's failure. Works on def and async def. Also usable bare: @zyonix.tool takes the
function's name.
| Parameter | Default | Meaning |
|---|---|---|
name | the function's name | The tool's name. |
side_effects | True | True: the call changes something outside the process, so replays never run it. False: it only reads, so replays may call it. |
capture_input | True | False keeps its arguments off the record (a recipient, a file). |
capture_output | True | False keeps its result off the record. |
Raises zyonix.ReplayBlocked when side_effects=True and the call
happens while zyonix test or zyonix replay is re-running a step. In normal operation it never
raises anything of its own.
@zyonix.tool("save_invoice")
def save_invoice(doc_id: str, invoice: dict) -> int: ...
@zyonix.tool("send_reply", capture_input=False)
def send_reply(chat_id: str, text: str) -> None: ...
@zyonix.tool("lookup_vendor", side_effects=False)
def lookup_vendor(name: str) -> dict | None: ...
@zyonix.tool
def geocode(address: str) -> dict: ...
zyonix.output
zyonix.output(result, schema=None, *, schema_version=None) -> result
Registers the run's final structured result: the output record that Zyonix checks.
| Parameter | Meaning |
|---|---|
result | The result: a dict, a pydantic model, a dataclass, a list. Converted to JSON like step outputs. |
schema | What kind of result it is: a class (its __name__), a string, or a JSON-schema dict (its title, else "schema"). Zyonix uses the name to choose the checks for this kind of document. |
schema_version | Optional version of that schema. Without it, a __version__ attribute on schema is used, if present. |
Returns result itself, unchanged, so return zyonix.output(record, schema="Invoice") works.
Behaviour: call it once per run, inside the run. Outside a run, or with tracing off, it only
returns result. A record larger than max_payload_bytes is cut and marked truncated; Zyonix then
cannot check that document.
zyonix.check
zyonix.check(name: str, passed, detail: str | None = None, *, severity: str = "medium") -> bool
Reports a check your application evaluated itself. A failed check becomes a problem in Zyonix under its own name; a passed one counts as evidence that the check ran.
| Parameter | Meaning |
|---|---|
name | The check's name. Lower-cased; characters other than a-z, 0-9, _, ., - become _; at most 64 characters. Empty becomes "unnamed". |
passed | Any value; its truthiness decides (bool(passed)). |
detail | Optional explanation, up to 500 characters. Redacted; sent as text only with full capture, as a hash otherwise. |
severity | "low", "medium" or "high". Another value is logged and replaced by "medium". |
Returns bool(passed), so it can wrap a condition: if not zyonix.check("saved", row is not None): ....
Behaviour: outside a run, or with tracing off, it only returns bool(passed).
zyonix.flag
zyonix.flag(name: str, detail: str | None = None, *, severity: str = "medium") -> None
Reports a problem your application noticed and handled itself: a duplicate it refused, a hand-off
to a person, a fallback it had to take. The same as zyonix.check(name, False, detail, severity=severity).
zyonix.flag("duplicate_message", "already processed", severity="low")
zyonix.flag("handed_to_person", "confidence below threshold")
zyonix.feedback
zyonix.feedback(doc_id, corrected=None, verdict: str | None = None, *, reviewer: str | None = None) -> None
Sends ground truth from your own correction or review flow: a person said a result was wrong (and what it should have been), or that it was correct.
| Parameter | Meaning |
|---|---|
doc_id | The document's id, the same value its run used. Converted to str. |
corrected | Optional corrected record (dict, pydantic model...). Redacted; sent as content only with full capture, as a hash otherwise. |
verdict | "wrong" or "correct". Zyonix accepts no other value: anything else is refused and dropped. |
reviewer | Optional reviewer label, sent as given in every capture mode. Use a team or role name or an internal id, not an email address. |
Returns None.
Behaviour: does not need to be inside a run, but needs init(); with tracing off it does
nothing. It is sent through the same background queue as runs, with an idempotency key so a
resend never counts twice. A correction is matched to the document's runs by doc_id, so it can
arrive long after the run.
zyonix.feedback("INV-2026-0042", corrected=fixed_invoice, verdict="wrong", reviewer="ap-team")
zyonix.feedback("INV-2026-0043", verdict="correct")
zyonix.flush
zyonix.flush(timeout_s: float = 5.0) -> bool
Blocks until everything queued so far has been sent, or until timeout_s seconds have passed.
Returns True when the queue is empty (also when tracing is off), False on timeout or error.
Call it at the end of a script or batch job: zyonix.flush(10). A long-running server does not
need it.
zyonix.shutdown
zyonix.shutdown() -> None
Flushes (for up to 2 seconds), stops the background exporter and removes the automatic LLM
instrumentation. After it, the decorators are pass-throughs again and init() may be called
again, for example with other settings. Use it in a web application's shutdown hook, or in tests
that start the SDK.
zyonix.current_trace_id
zyonix.current_trace_id() -> str | None
The id of the active run (32 hexadecimal characters), or None outside a run or with tracing off.
Useful to put the Zyonix id into your own logs or error reports.
@zyonix.run(doc_id=lambda job: job.id)
def handle(job):
log.info("job %s is zyonix run %s", job.id, zyonix.current_trace_id())
zyonix.ReplayBlocked
class zyonix.ReplayBlocked(RuntimeError):
tool: str # the name of the tool that was not run
Raised by a @zyonix.tool with side_effects=True when it is called while zyonix test or
zyonix replay is re-running a recorded step. The tool did not run. The replay reports that case
as not executed, and that it verified nothing, even if your code catches the exception. Mark a
tool that only reads with side_effects=False so replays may call it.
It never occurs in normal operation of your application.
zyonix.__version__
>>> zyonix.__version__
'0.1.13'
Runtime repair (Guard)
zyonix.guard, zyonix.observe, zyonix.RepairHint, zyonix.GuardHold, zyonix.GuardReport and
zyonix.last_guard_report belong to runtime repair: checking a model's answer while the
application runs and repairing it before it is used.
Runtime repair needs the Zyonix detection engine, which runs on the Zyonix server and is not part of
the SDK you install. In your installation these names exist so that code using them keeps working,
but they do nothing: a function decorated with @zyonix.guard returns exactly what your code
returns, and if your agent's settings turn a repair strategy on, the SDK says once in your log that
the Guard cannot run here. Do not build on them; ask Zyonix if you need runtime repair.
For completeness, their signatures:
| Name | Signature | In a customer installation |
|---|---|---|
guard | zyonix.guard(step="extract", *, source=None, schema=None), a decorator placed under @zyonix.step | calls your function unchanged; async def functions are left unguarded with a warning |
observe | zyonix.observe(response=None, *, text=None, finish_reason=None, completion_tokens=None) -> None | does nothing |
RepairHint | dataclass: strategy, attempt, message, max_tokens, failed_checks; method as_message() | never passed to your function |
GuardReport | dataclass describing what the Guard did for one call (outcome, delivered, strategies...) | not produced |
last_guard_report | zyonix.last_guard_report() -> GuardReport | None | returns None |
GuardHold | exception with a report attribute | never raised |
Turn the Guard off for good with guard: {enabled: false} in zyonix.yaml.