Skip to main content

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
NameKindPurpose
initfunctionstart the SDK, once per process
rundecorator / context managerone document = one run
stepdecoratora named stage inside a run
tooldecoratora function that acts on the outside world
outputfunctionthe run's final result, the one that is checked
checkfunctiona check your application evaluated itself
flagfunctiona problem your application noticed itself
feedbackfunctiona person's correction or verdict
flushfunctionwait until queued data is sent
shutdownfunctionflush and stop the SDK
current_trace_idfunctionthe id of the active run
ReplayBlockedexceptiona tool with side effects was called during a replay
__version__stringthe installed SDK version
guard, observe, RepairHint, GuardHold, GuardReport, last_guard_reportruntime 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 are ReplayBlocked, and only while zyonix test or zyonix replay re-runs a step, and GuardHold, 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.

ParameterDefaultMeaning
api_keyZYONIX_API_KEYAn sdk key. Leave it out and set the environment variable instead, so no secret is in your code.
serviceZYONIX_SERVICE, then service in zyonix.yaml, then "unknown-service"Short, stable name of the application.
releaseZYONIX_RELEASEThe deployed version (git commit, build id). Used to detect releases and link problems to recent changes.
endpointZYONIX_ENDPOINT, then endpoint in zyonix.yaml, then http://localhost:8000Your Zyonix address, https://zyonix.example.com. A trailing / is removed.
modeZYONIX_MODE, then mode in zyonix.yaml, then "remote" with a key or "off" without"remote", "local", "console" or "off". See Modes.
config_fileZYONIX_CONFIG, then ./zyonix.yamlPath of the configuration file.

Keyword options (**options). Each overrides the same setting from the environment and the file:

OptionTypeDefaultMeaning
capture"full" or "hash_only""hash_only""full" sends redacted content. Any other value means "hash_only".
ca_filepathZYONIX_CA_FILEPEM file of a private certificate authority to trust for the endpoint.
local_onlyboolTrueSend only to a local address or one listed in egress_allow.
egress_allowlist 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_pathpath"zyonix-traces.jsonl"The file mode="local" writes.
max_payload_bytesint524288 (512 KB)A larger input, output, record or attribute is cut and marked truncated.
redaction_presetslist of str["email", "phone", "iban", "card_number"]Built-in masks. Also "national_id".
custom_patternslist of tuples[]Your own masks: (name, regex), (name, regex, context, window) or (name, regex, context, window, unless). See Redaction.
queue_sizeint2048Spans the export queue holds.
queue_max_bytesint268435456 (256 MB)Bytes the export queue holds.
batch_sizeint256Spans per export batch.
schedule_delay_sfloat1.0Seconds between export batches.
export_timeout_sfloat5.0Timeout of one export request.
max_batch_bytesint4194304 (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: init arguments, ZYONIX_* environment variables, zyonix.yaml, built-in defaults. Details: Configuration.
  • Without a key and without mode="local" or "console", tracing is off: the SDK logs zyonix: tracing is off at info level and every decorator becomes a pass-through.
  • If zyonix.yaml exists but is invalid, tracing is off until it is fixed.
  • If the endpoint is a public host that is not in egress_allow, or plain http:// 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 call and does nothing. To start again with other settings, call shutdown() 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 disabled and 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).

ParameterTypeMeaning
doc_idvalue or callableThe document's own stable id. Converted to str. Sent in clear in every capture mode.
sourcevalue or callableWhere the document came from ("email", "api"). Converted to str. Sent in clear.
doc_namevalue or callableThe 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, output and automatically recorded LLM calls made inside the run belong to it, including in asyncio tasks 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.

ParameterDefaultMeaning
namerequiredThe step's name, shown on the website and used to group problems by step. Keep it stable.
kindfrom the nameOne of INGEST, PARSE, RETRIEVE, LLM, TOOL, TRANSFORM, DELIVER (any case). An unknown kind is logged and replaced by TRANSFORM.
replayableFalseMarks the one step zyonix test / zyonix replay may call again with recorded arguments. See the rules.
versionNoneYour own version label of this step (for example a prompt version), recorded with it.
capture_inputTrueFalse records the step without its arguments.
capture_outputTrueFalse records the step without its return value.

Kind from the name, when kind is not given:

Name (any case)Kind
ingest, receiveINGEST
ocr, parsePARSE
retrieveRETRIEVE
extractLLM
postprocess, transformTRANSFORM
deliverDELIVER
anything elseTRANSFORM

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 self and cls), as a JSON object. The output is the return value. Both are redacted, then cut to max_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, Decimal as text, enums as their value, bytes as {"__bytes__": <length>, "sha256": "<hash>"} (never the bytes), and any other object as its repr (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 plain def step is marked so the replay commands may call it; an async def step is never called by a replay. If a replayable step's input is cut by max_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.

ParameterDefaultMeaning
namethe function's nameThe tool's name.
side_effectsTrueTrue: the call changes something outside the process, so replays never run it. False: it only reads, so replays may call it.
capture_inputTrueFalse keeps its arguments off the record (a recipient, a file).
capture_outputTrueFalse 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.

ParameterMeaning
resultThe result: a dict, a pydantic model, a dataclass, a list. Converted to JSON like step outputs.
schemaWhat 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_versionOptional 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.

ParameterMeaning
nameThe check's name. Lower-cased; characters other than a-z, 0-9, _, ., - become _; at most 64 characters. Empty becomes "unnamed".
passedAny value; its truthiness decides (bool(passed)).
detailOptional 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.

ParameterMeaning
doc_idThe document's id, the same value its run used. Converted to str.
correctedOptional 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.
reviewerOptional 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.

Not available in customer installations

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:

NameSignatureIn a customer installation
guardzyonix.guard(step="extract", *, source=None, schema=None), a decorator placed under @zyonix.stepcalls your function unchanged; async def functions are left unguarded with a warning
observezyonix.observe(response=None, *, text=None, finish_reason=None, completion_tokens=None) -> Nonedoes nothing
RepairHintdataclass: strategy, attempt, message, max_tokens, failed_checks; method as_message()never passed to your function
GuardReportdataclass describing what the Guard did for one call (outcome, delivered, strategies...)not produced
last_guard_reportzyonix.last_guard_report() -> GuardReport | Nonereturns None
GuardHoldexception with a report attributenever raised

Turn the Guard off for good with guard: {enabled: false} in zyonix.yaml.