Skip to main content

Integrate by hand

This page adds Zyonix to an application step by step, using a complete example: an invoice extractor that reads a file, asks an AI model for the invoice fields, validates the answer and saves it. At the end you have the whole file, plus variants for a web application (FastAPI), a batch script, async code and code without a single per-document function.

You add a handful of lines. Nothing else in your code changes, and the SDK never raises into your code: if Zyonix is slow or unreachable, your application produces exactly the same results.

What goes where​

CallWhere it goesWhat it records
zyonix.init(...)once per process, at start-upstarts the SDK
@zyonix.run(doc_id=...)the function that handles one document from start to endone run (a document on the website)
@zyonix.step("name")each stage that function calls: parse, model call, validate...one step, with its inputs, output, error and timing
replayable=Trueon exactly one step: the model callmarks the step that zyonix test and zyonix replay run again
@zyonix.tool("name")functions that act on the outside world: database writes, messages, external APIsa tool step that replays never run
zyonix.output(result, schema=...)just before the run returns its final resultthe output record Zyonix checks
zyonix.check(...) / zyonix.flag(...)where your code already validates a resultyour own problem categories
zyonix.feedback(...)where a person corrects a resultground truth for that document
zyonix.flush(10)at the end of a script that exitswaits until everything is sent

Before you start, install the SDK with the extra for your LLM library. You do not need a Zyonix server to follow this page: you can check every step in local mode (see Testing locally).

The example application, before Zyonix​

A small package invoice_extractor with three files: pipeline.py (the work), db.py (storage) and cli.py (the entry point that processes a folder of files).

# invoice_extractor/pipeline.py (before Zyonix)
import json
import os
from pathlib import Path

from openai import OpenAI
from pydantic import BaseModel
from pypdf import PdfReader

from invoice_extractor import db

PROMPTS = {
"invoice-v3": (
"Extract the invoice as JSON with the keys invoice_number, vendor_name, issue_date "
"(YYYY-MM-DD), currency, subtotal, tax_amount, total and line_items (description, "
"quantity, unit_price, amount). Use only values printed in the document."
),
}


class LineItem(BaseModel):
description: str
quantity: float
unit_price: float
amount: float


class Invoice(BaseModel):
invoice_number: str
vendor_name: str
issue_date: str
currency: str
subtotal: float
tax_amount: float
total: float
line_items: list[LineItem] = []


_client: OpenAI | None = None


def client() -> OpenAI:
global _client
if _client is None:
_client = OpenAI() # reads OPENAI_API_KEY
return _client


def current_config() -> dict:
"""What production uses for the next document."""
return {
"model": os.getenv("EXTRACTION_MODEL", "gpt-4o-mini"),
"prompt_version": "invoice-v3",
"temperature": 0,
}


def read_text(path: str) -> str:
if path.lower().endswith(".pdf"):
return "\n".join(page.extract_text() or "" for page in PdfReader(path).pages)
return Path(path).read_text(encoding="utf-8")


def extract(document_text: str, config: dict) -> dict:
response = client().chat.completions.create(
model=config["model"],
temperature=config["temperature"],
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": PROMPTS[config["prompt_version"]]},
{"role": "user", "content": document_text},
],
)
return json.loads(response.choices[0].message.content)


def validate(raw: dict) -> Invoice:
return Invoice.model_validate(raw)


def save_invoice(doc_id: str, invoice: Invoice) -> int:
return db.insert_invoice(doc_id, invoice.model_dump())


def process(doc_id: str, path: str) -> Invoice | None:
if db.already_saved(doc_id):
return None
invoice = validate(extract(read_text(path), current_config()))
save_invoice(doc_id, invoice)
return invoice

The steps below change this file and the entry point. Each change is marked with a # Zyonix: comment in the complete version at the end.

Step 1: start Zyonix once, at start-up​

Call zyonix.init once per process, before the first document is handled. In a script that is the start of main(); in a web application, its start-up code; in a worker, where the worker starts.

import os
import zyonix

zyonix.init(service="invoice-extractor", release=os.getenv("GIT_SHA"))
  • service is a short, stable name for this application. It labels every document it sends.
  • release is the version you deploy: a git commit, a build number or a tag. Zyonix uses it to notice a new release and to link problems to recent changes. Use the variable your build already sets; leave it out if there is none.
  • The address and the key are not arguments: init reads them from the environment variables ZYONIX_ENDPOINT and ZYONIX_API_KEY (see Configuration). No secret goes in your code.

Without a key (and without a local mode), init turns tracing off and every Zyonix decorator just calls your function. That is why your tests keep working unchanged.

One init per process

A second call to init in the same process is ignored with a warning. If your server starts several worker processes (gunicorn, uvicorn --workers, Celery, multiprocessing), each process must call init itself, after it has started: the SDK sends from a background thread, and threads do not survive a fork. Putting init in the code every worker runs at start-up (the app's start-up hook, the worker's init signal) does this for you.

Step 2: mark the function that handles one document​

The run is the function that takes one document from start to end. Here that is process.

@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) -> Invoice | None:
...
  • doc_id is how you find this document in Zyonix later, and how corrections are matched to it. It must be the document's own, stable id: a message id, an upload id, a database id, or a file name if file names are unique. Never a random value (uuid4(), a timestamp): the same document would appear as a new one each time.
  • A value or a function. As a function, it receives the same arguments as the decorated function and returns the id. Here lambda doc_id, path: doc_id returns the first argument.
  • source says where documents come from ("email", "whatsapp", "api", "upload-folder"). It can also be a function of the arguments.
  • doc_name (optional) is the document's real file name, shown to administrators only. It counts as content: it is sent only with full capture, never in hash_only.

Rules for the run:

  • One run per document. Never put the run around a loop over many documents; put it on the function the loop calls for each one.
  • An exception that leaves the function is recorded on the run (type, and the message under full capture) and then raised again, unchanged.
  • The decorator works on def and async def functions. It is not meant for generator functions: the run would end when the generator is created, not when it is consumed.
Methods

On a method, the function also receives self: @zyonix.run(doc_id=lambda self, job: job.id). If your function takes only one parameter, a one-argument lambda is fine. A lambda that does not accept all the arguments is called with the first positional argument only, which on a method is self, not your document.

Step 3: mark the stages as steps​

Mark each stage the run calls with @zyonix.step("name"). Two to six steps are usually right. The stage functions are called inside the run; that is how the SDK knows which document they belong to.

@zyonix.step("parse")
def read_text(path: str) -> str:
...


@zyonix.step("validate")
def validate(raw: dict) -> Invoice:
...

Each step records its named arguments (input), its return value (output), its duration, and an exception if one passes through it. Inputs and outputs are redacted on your machine before they are sent, and in hash_only mode only their hashes leave the process.

Prefer these names where they fit, because Zyonix gives them a matching kind: "ingest" or "receive", "parse" or "ocr", "retrieve", "extract" (the model call), "postprocess" or "transform", "deliver". Any other name works too (for example "validate"); it is recorded as a transform step. You can also set the kind yourself, see step.

A step called outside a run (for example from a unit test, or from a different code path) is not recorded: it simply calls your function.

Keeping large or private arguments off the record

@zyonix.step("parse", capture_input=False) records the step without its arguments. Use it for arguments that are useless as evidence, such as raw file bytes. (Bytes are never sent as content anyway: the SDK records only their length and hash.)

Step 4: make the model call the replayable step​

Mark exactly one step replayable=True: the model call that produces the result.

@zyonix.step("extract", replayable=True)
def extract(document_text: str, config: dict) -> dict:
response = client().chat.completions.create(...)
return json.loads(response.choices[0].message.content)

A replayable step's named arguments are recorded so that zyonix test and zyonix replay can call the same function again, on your machine, with the arguments of a past failure, to check whether a fix works.

When may a step be replayable​

Only when all of these are true:

RuleWhy
It is a module-level function: not nested inside another function, not a lambda, not a method.The replay imports it by its module and name.
It is a plain def, not async def.The replay calls it synchronously; an async def step is never called by a replay.
Its result depends only on its arguments: the document text and a configuration dict (model, prompt version, temperature, limits).The replay passes the recorded arguments, with a candidate fix merged into the configuration. A prompt or model read from a global or self would not change with the fix.
Its arguments are plain data: strings, numbers, lists, dicts, pydantic models, dataclasses.They are recorded as JSON. Bytes, clients, open files and other objects are recorded as placeholders and cannot be replayed.
It takes its arguments by name (no *args, no positional-only parameters).The replay calls it as extract(document_text=..., config=...).
It does not act on the outside world.It runs again for every test. Database writes, messages and other side effects belong in a @zyonix.tool.

The client object itself (client() above) may come from a global: it is plumbing, not part of the result. The replay creates it through the replay.setup hook you configure (see The replay settings).

If your model call does not meet these rules, leave replayable off. Everything else still works: documents are recorded, checked and explained. Only zyonix test and zyonix replay need a replayable step. You can make the step replayable later, by passing the prompt version and model in a config argument.

Large documents

A replayable step's input larger than max_payload_bytes (512 KB by default) is recorded cut off. Such a run cannot become a regression case, and its values cannot be found in the document. The SDK warns once per step. Raise max_payload_bytes in zyonix.yaml if your documents are larger (see Configuration).

Step 5: mark functions that act on the outside world as tools​

A function that changes something outside your process (writes a database row, sends an email or a message, calls a payment or an external API) gets @zyonix.tool instead of @zyonix.step:

@zyonix.tool("save_invoice")
def save_invoice(doc_id: str, invoice: Invoice) -> int:
return db.insert_invoice(doc_id, invoice.model_dump())

A tool is recorded like a step, and a failing tool is reported as that tool's failure. During zyonix test and zyonix replay it is never run: it raises zyonix.ReplayBlocked instead, so a replay cannot save a row or send a message a second time on a customer's behalf.

A tool that only reads (a lookup, a search) can run during replays:

@zyonix.tool("lookup_vendor", side_effects=False)
def lookup_vendor(name: str) -> dict | None:
return db.find_vendor(name)

capture_input=False and capture_output=False keep a tool's arguments or result off the record (a recipient address, a file).

Step 6: record the final result​

Just before the run returns its result, pass the result through zyonix.output:

zyonix.output(invoice, schema=Invoice)

This is the output record: the result Zyonix checks against the document and your rules. It returns the same object, so return zyonix.output(invoice, schema=Invoice) also works. Dicts, pydantic models and dataclasses are recorded as JSON.

schema names the kind of result: a class (its name is used, here "Invoice"), a string such as "Invoice", or a JSON-schema dict (its title). Zyonix uses the name to pick the output format (the checks for that kind of document), so keep it the same across releases. If the shape of your result changes in a way that matters, pass schema_version=2.

Call it once per run. Called outside a run, it does nothing.

Step 7: report your own validation (optional)​

Where your code already checks a result, report the check under its own name. A failed check becomes a problem in Zyonix under that name:

lines_total = round(sum(item.amount for item in invoice.line_items), 2)
zyonix.check(
"line_items_add_up",
abs(lines_total - invoice.subtotal) < 0.01,
detail=f"line items {lines_total}, subtotal {invoice.subtotal}",
severity="high",
)

zyonix.check returns the condition as a bool, so it can wrap an if:

if not zyonix.check("has_line_items", invoice.line_items):
log.warning("invoice %s has no line items", doc_id)

For a problem your code noticed and handled (a duplicate it skipped, a hand-off to a person, a fallback), use zyonix.flag. It is a check that failed:

if db.already_saved(doc_id):
zyonix.flag("duplicate_document", "already processed", severity="low")
return None
  • Names are lower case letters, digits, _, . and -; other characters become _.
  • severity is "low", "medium" (default) or "high".
  • detail (up to 500 characters) is redacted, and sent as text only with full capture.

Only add checks your application already performs. Zyonix's own checks of the result are configured on the server, not in your code.

Step 8: send corrections as feedback (optional)​

If a person in your process corrects results (a review screen, an approval queue, a support tool), send the correction to Zyonix. It is the most valuable evidence Zyonix gets: the correct answer.

def on_reviewer_correction(doc_id: str, corrected: dict) -> None:
db.update_invoice(doc_id, corrected)
zyonix.feedback(doc_id, corrected=corrected, verdict="wrong", reviewer="ap-team")


def on_reviewer_approval(doc_id: str) -> None:
zyonix.feedback(doc_id, verdict="correct", reviewer="ap-team")
  • doc_id is the same id the run used. That is how the correction finds its document.
  • verdict is "wrong" or "correct".
  • corrected is the corrected record. It is redacted and sent only with full capture; in hash_only mode only the verdict counts.
  • reviewer is sent as you give it, in every capture mode: use a team or role name, or an internal id, not a person's email address.

feedback does not need to run inside a run, but the process must have called zyonix.init.

Step 9: flush before a script exits​

The SDK sends in the background. A long-running server needs nothing more. A script or batch job that exits right after its work must wait for the sending to finish:

zyonix.flush(10) # wait up to 10 seconds

At normal interpreter exit the SDK also tries for 2 seconds by itself, but an explicit flush is more reliable and lets you choose the wait. It returns True when everything was sent.

The complete example​

# invoice_extractor/pipeline.py (with Zyonix)
import json
import logging
import os
from pathlib import Path

import zyonix # Zyonix
from openai import OpenAI
from pydantic import BaseModel
from pypdf import PdfReader

from invoice_extractor import db

log = logging.getLogger(__name__)

PROMPTS = {
"invoice-v3": (
"Extract the invoice as JSON with the keys invoice_number, vendor_name, issue_date "
"(YYYY-MM-DD), currency, subtotal, tax_amount, total and line_items (description, "
"quantity, unit_price, amount). Use only values printed in the document."
),
}


class LineItem(BaseModel):
description: str
quantity: float
unit_price: float
amount: float


class Invoice(BaseModel):
invoice_number: str
vendor_name: str
issue_date: str
currency: str
subtotal: float
tax_amount: float
total: float
line_items: list[LineItem] = []


_client: OpenAI | None = None


def client() -> OpenAI:
global _client
if _client is None:
_client = OpenAI() # reads OPENAI_API_KEY
return _client


def current_config() -> dict:
"""What production uses for the next document."""
return {
"model": os.getenv("EXTRACTION_MODEL", "gpt-4o-mini"),
"prompt_version": "invoice-v3",
"temperature": 0,
}


@zyonix.step("parse") # Zyonix: a stage
def read_text(path: str) -> str:
if path.lower().endswith(".pdf"):
return "\n".join(page.extract_text() or "" for page in PdfReader(path).pages)
return Path(path).read_text(encoding="utf-8")


@zyonix.step("extract", replayable=True) # Zyonix: the one replayable step, the model call
def extract(document_text: str, config: dict) -> dict:
response = client().chat.completions.create(
model=config["model"],
temperature=config["temperature"],
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": PROMPTS[config["prompt_version"]]},
{"role": "user", "content": document_text},
],
)
return json.loads(response.choices[0].message.content)


@zyonix.step("validate") # Zyonix: a stage
def validate(raw: dict) -> Invoice:
return Invoice.model_validate(raw)


@zyonix.tool("save_invoice") # Zyonix: acts on the outside world, never replayed
def save_invoice(doc_id: str, invoice: Invoice) -> int:
return db.insert_invoice(doc_id, invoice.model_dump())


@zyonix.run( # Zyonix: one run per document
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) -> Invoice | None:
if db.already_saved(doc_id):
zyonix.flag("duplicate_document", "already processed", severity="low") # Zyonix
return None
invoice = validate(extract(read_text(path), current_config()))
lines_total = round(sum(item.amount for item in invoice.line_items), 2)
zyonix.check( # Zyonix: the application's own rule
"line_items_add_up",
abs(lines_total - invoice.subtotal) < 0.01,
detail=f"line items {lines_total}, subtotal {invoice.subtotal}",
severity="high",
)
zyonix.output(invoice, schema=Invoice) # Zyonix: the result that is checked
save_invoice(doc_id, invoice)
return invoice


def on_reviewer_correction(doc_id: str, corrected: dict) -> None:
db.update_invoice(doc_id, corrected)
zyonix.feedback(doc_id, corrected=corrected, verdict="wrong", reviewer="ap-team") # Zyonix

The entry point, a script that processes every file in a folder:

# invoice_extractor/cli.py
import logging
import os
import sys
from pathlib import Path

import zyonix # Zyonix

from invoice_extractor.pipeline import process

log = logging.getLogger("invoice_extractor")


def main(folder: str) -> int:
logging.basicConfig(level=logging.INFO)
zyonix.init(service="invoice-extractor", release=os.getenv("GIT_SHA")) # Zyonix: once, first
failures = 0
for path in sorted(Path(folder).iterdir()):
if path.suffix.lower() not in (".pdf", ".txt"):
continue
try:
process(path.stem, str(path)) # one run per file
except Exception as exc:
failures += 1
log.error("%s failed: %s", path.name, exc)
zyonix.flush(10) # Zyonix: a script must flush before it exits
return 1 if failures else 0


if __name__ == "__main__":
sys.exit(main(sys.argv[1]))

Here the file name without its extension is the doc_id. That is stable as long as file names are unique. If the same name can arrive twice with different content, use an id from wherever the files come from (an upload id, a message id) instead.

Try it without a server:

ZYONIX_MODE=local ZYONIX_LOCAL_PATH=zyonix-check.jsonl python -m invoice_extractor.cli ./samples

Then read zyonix-check.jsonl as described in Testing locally. With ZYONIX_ENDPOINT and ZYONIX_API_KEY set instead, the documents appear on the website under Documents.

What happens to errors​

The SDK never changes what your code sees:

  • An exception raised by your code passes through each step and the run unchanged (same object, same traceback). On the way, each step and the run record that they failed.
  • If your code catches an exception inside the run, the step it passed through is still recorded as failed, but the run is not, because the exception did not leave it.
  • An error inside the SDK itself is caught, counted and logged at debug level. Your function runs as if Zyonix were not there.

So do not wrap Zyonix calls in try/except. They do not raise.

Variant: a web application (FastAPI)​

Start the SDK in the application's start-up code, never in a request handler. With FastAPI, use the lifespan:

# invoice_extractor/web.py
import os
import tempfile
from contextlib import asynccontextmanager

import zyonix
from fastapi import FastAPI, UploadFile

from invoice_extractor.pipeline import process


@asynccontextmanager
async def lifespan(app: FastAPI):
zyonix.init(service="invoice-extractor", release=os.getenv("GIT_SHA"))
yield
zyonix.shutdown() # sends what is still queued before the process stops


app = FastAPI(lifespan=lifespan)


@app.post("/invoices/{upload_id}")
def upload_invoice(upload_id: str, file: UploadFile) -> dict:
suffix = os.path.splitext(file.filename or "")[1] or ".pdf"
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
tmp.write(file.file.read())
invoice = process(upload_id, tmp.name) # the @zyonix.run function: one run per upload
os.unlink(tmp.name)
return {"status": "duplicate"} if invoice is None else invoice.model_dump()
  • The handler is a plain def, so FastAPI runs it in a worker thread; the run, its steps and the model call are all recorded in that thread.
  • upload_id comes from the caller and identifies the document, so it is a good doc_id. (Here doc_name records the temporary file's name; pass the upload's own file name to process if you want the real one.)
  • With uvicorn --workers 4 (or gunicorn), each worker process runs the lifespan, so each calls init once.
  • The same applies to Flask (call init in the app factory), Django (in AppConfig.ready()) and Celery (in a worker_process_init signal handler).

Work handed to FastAPI's BackgroundTasks is recorded the same way, as long as the function the task runs is the @zyonix.run function.

Variant: async code​

@zyonix.run, @zyonix.step and @zyonix.tool work on async def functions. The run follows await and tasks started with asyncio.create_task or asyncio.gather, because each task copies the current context.

import zyonix
from openai import AsyncOpenAI

aclient = AsyncOpenAI()


@zyonix.step("extract") # async: recorded, but cannot be replayable
async def extract(document_text: str, config: dict) -> dict:
response = await aclient.chat.completions.create(
model=config["model"],
response_format={"type": "json_object"},
messages=[{"role": "user", "content": document_text}],
)
return json.loads(response.choices[0].message.content)


@zyonix.run(doc_id=lambda message: message["id"], source="queue")
async def handle(message: dict) -> dict:
text = await fetch_text(message["url"])
record = await extract(text, current_config())
return zyonix.output(record, schema="Invoice")

A replay calls the replayable step synchronously, so an async def step cannot be replayable. If you need zyonix test and zyonix replay, keep the model call in a plain def function (an async application can call it with await asyncio.to_thread(extract, text, config)).

Variant: threads inside one document​

The SDK follows a document through Python's context variables. asyncio copies them to new tasks, but a thread pool does not: a step called from a ThreadPoolExecutor inside a run is not recorded, and neither are its model calls. Run each task in a copy of the context:

import contextvars
from concurrent.futures import ThreadPoolExecutor


@zyonix.run(doc_id=lambda doc: doc["id"])
def process_pages(doc: dict) -> list[dict]:
with ThreadPoolExecutor(max_workers=4) as pool:
futures = [
pool.submit(contextvars.copy_context().run, extract_page, page, current_config())
for page in doc["pages"]
]
return [f.result() for f in futures]

Use a fresh copy_context() for each task, as above: one context cannot run in two threads at once.

A pool that handles different documents, one per task, needs nothing special: each task calls the @zyonix.run function, which starts its own run in its own thread.

Variant: no single function per document​

When the per-document code is a block inside a larger function, wrap the block with the context-manager form. Pass values, not functions:

for message in inbox.fetch_new():
with zyonix.run(doc_id=message.id, source="email", doc_name=message.attachment_name):
text = read_text(message.attachment_path)
record = validate(extract(text, current_config()))
zyonix.output(record, schema="Invoice")
save_invoice(message.id, record)

The with block is one run. An exception that leaves the block is recorded and raised again. async with zyonix.run(...) works the same way in async code. The object the with statement gives you has a trace_id attribute, the run's id in Zyonix, useful in your own logs:

with zyonix.run(doc_id=message.id) as run:
log.info("processing %s (zyonix run %s)", message.id, run.trace_id)

Inside any run, zyonix.current_trace_id() returns the same id.

The replay settings​

zyonix test (a regression gate for CI) and zyonix replay --fix (checking a proposed fix) are commands of the zyonix-cli package. They import your replayable step and call it with the recorded arguments of past failures, on your machine. Tell them how to prepare your application in the replay: section of zyonix.yaml:

replay:
setup: invoice_extractor.zyonix_hooks:setup # called once before any case
config_provider: invoice_extractor.zyonix_hooks:current_config # the configuration in use now
config_arg: config # the step argument it replaces
python_path: [src] # extra import roots (default: the current folder)
# invoice_extractor/zyonix_hooks.py
from invoice_extractor import pipeline


def setup() -> None:
"""Prepare what the extraction step needs, as production does. Start no consumers."""
pipeline.client()


def current_config() -> dict:
return pipeline.current_config()

The config_provider matters: a recorded case keeps the document, but the test must use the configuration your application uses today, so that a fix you deployed is recognised. These commands need full capture. They are described with the rest of the CLI.

Next​