Skip to content

jaz.hooks

New to JAZ? This is generated API reference. Start with the docs and the concepts overview.

Public API of the jaz.hooks submodule (import from jaz.hooks, e.g. from jaz.hooks import ...).

The mental model in three sentences. As an agent runs, the framework fires typed events at fixed points: once around the whole invoke, and per turn around the LLM query and the REPL execution — each of those three spans walks the same four stages, Enter → Send → Complete → Exit (see jaz.hooks.events for the pipeline). A hook is a class with a method per event it cares about (LLMQueryEnter → on_llm_query_enter); each handler receives the event and returns a list of effects — the only way a hook changes anything (jaz.hooks.effects says which effect is valid at which stage). Effects from all active hooks are composed order-independently and applied by the framework; a hook that returns [] everywhere is a pure observer.

Public surface (three parts):

A complete first hook — count the turns, nudge the agent, then stop it:

from jaz import invoke
from jaz.hooks import Hook
from jaz.hooks.effects import Abort, AddMessages, Effect
from jaz.hooks.events import LLMQueryEnter
class TurnLimiter(Hook):
def on_llm_query_enter(self, event: LLMQueryEnter) -> list[Effect]:
if event.iteration >= 10:
return [Abort(error=RuntimeError("out of turns"))]
if event.iteration >= 8:
return [AddMessages([{"role": "user", "content": "Finish soon."}])]
return []
# `with` activation propagates to nested invokes:
with TurnLimiter():
result = invoke(task="...")
# Passing a hook positionally scopes it to that one invoke — nested invokes
# do NOT see it. See the Hook class for the difference.
result = invoke(TurnLimiter(), task="...")

Before writing your own, check the battery hooks — limits, budgets, logging, tracing and replay are already covered.

Base class for hooks — subclass it and override the handlers you care about.

Every event has a handler named after it (LLMQueryEnter → on_llm_query_enter). A handler observes the event and returns a list of effects; returning effects is the only way a hook influences the run, and which effects are accepted depends on the event — each event class documents its own set, and an effect outside it raises InvalidEffectError rather than being silently dropped. A cross-cutting observer (logging, tracing) overrides on_any instead, which runs in addition to the matched typed handler, so the two compose.

There are two ways to activate a hook, and they differ in whether nested invokes see it. A hook activated either way must not be activated the other way at the same time. (Snippets below assume from jaz import invoke.)

with — propagating:

with MyHook():
invoke(...) # active here AND in every invoke nested inside
with Hook1(), Hook2(): # several at once
invoke(...)

It reaches nested invokes, functions called inside the block, async code, and threads (each gets its own context copy). Across a process boundary it follows the start method (https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods): under fork the child inherits the activation, and with it the parent’s instance holding the parent’s open files, locks and spans; under spawn and forkserver the hook is simply absent. Activate hooks inside the worker.

Leading positional argument — one invoke only:

invoke(MyHook(), task=...) # active for THIS invoke, NOT for invokes it nests

A hook passed this way applies to that invoke alone — the invokes it nests never see it, so anything it accumulates or enforces (a budget, a limit, a log) covers the outer invoke’s own turns and nothing below them. Use with when sub-invokes must be included.

Re-activating one instance. A hook may be activated again after its previous scope ended — the same FileLogger or BudgetPool passed to several invokes in turn. Only overlapping activation is rejected. A hook that carries per-run state must therefore pick one of two policies, because nothing else will:

  • Clean, when everything the run produced lives in the hook’s own memory. Clear that state so each activation starts empty. Clear it in setup if a caller is meant to read the finished run after the scope ends, in teardown if promptly releasing it matters more.
  • Reject, when a second run would destroy what the first one produced — typically a file the hook rewrites from scratch each time. Cleaning memory does not un-write a file. Call forbid_reactivation at the top of setup.

Producing output outside the hook does not by itself call for rejecting: what matters is whether reuse overwrites it. A span exporter appends, so re-activating a tracing hook adds the second run’s spans beside the first’s and needs neither policy.

A hook with no per-run state, such as a validator that only inspects each event, needs neither and can be reused freely.

Declaring what you write. The reserved_* / reserves_* attributes below let a hook declare, up front, the slots it intends to write. They are entirely optional: a hook that writes a slot without declaring it works exactly as before. What a declaration buys is when a conflict surfaces — two hooks that both claim one slot are rejected at seed time, before the first event of the next jaz.invoke, instead of when their two writes happen to meet, which can be deep into a paid-for run. Declare when the slot is one only your hook should own; skip it otherwise. One caveat, because it can turn a working composition into an error: the seed-time check is stricter than the runtime one — it rejects two declarers of a slot even when they would write identical values, where runtime would have coalesced them.

For a list of hooks known only at runtime, use contextlib.ExitStack, which unwinds in reverse order and hands the in-flight exception to each hook’s __exit__ exactly as nested with blocks do:

with ExitStack() as stack:
for hook in hook_list:
stack.enter_context(hook)
invoke(...)

Examples

from jaz import invoke
from jaz.hooks import Hook
from jaz.hooks.effects import Abort, Effect
from jaz.hooks.events import LLMQueryEnter
class StopAfterFiftyTurns(Hook):
def on_llm_query_enter(self, event: LLMQueryEnter) -> list[Effect]:
if event.iteration >= 50: # iterations are 0-based
return [Abort(error=RuntimeError("Limit exceeded"))]
return []
with StopAfterFiftyTurns():
result = invoke(task="task")
on_invoke_enter(event: InvokeEnter) -> list[Effect]

An invoke is starting, before any LLM query. Default no-op.

on_invoke_send(event: InvokeSend) -> list[Effect]

An invoke’s input set has committed (post add/drop). Default no-op.

on_invoke_complete(event: InvokeComplete) -> list[Effect]

An invoke’s raw terminal result exists (transform boundary). Default no-op.

on_invoke_exit(event: InvokeExit) -> list[Effect]

An invoke’s span has closed (see event.outcome). Default no-op.

on_repl_exec_enter(event: REPLExecEnter) -> list[Effect]

REPL code is about to execute (parsed code available). Default no-op.

on_repl_exec_send(event: REPLExecSend) -> list[Effect]

An execution’s code has committed (namespace deltas applied). Default no-op.

on_repl_exec_complete(event: REPLExecComplete) -> list[Effect]

An execution’s raw result exists (transform boundary). Default no-op.

on_repl_exec_exit(event: REPLExecExit) -> list[Effect]

A REPL execution’s span has closed (see event.outcome). Default no-op.

on_llm_query_enter(event: LLMQueryEnter) -> list[Effect]

An LLM query is about to be issued. Default no-op.

on_llm_query_send(event: LLMQuerySend) -> list[Effect]

A query’s input has committed (the post-edit shown list). Default no-op.

on_llm_query_complete(event: LLMQueryComplete) -> list[Effect]

A query’s raw response exists (response control boundary). Default no-op.

on_llm_query_exit(event: LLMQueryExit) -> list[Effect]

An LLM query’s span has closed (see event.outcome). Default no-op.

on_llm_query_retry(event: LLMQueryRetry) -> list[Effect]

An LLM query is being retried after a failure. Default no-op.

on_any(event: Event) -> list[Effect]

Catch-all called for every event, in addition to the matched typed handler.

Override this for cross-cutting observers (loggers, tracing, replay) that treat all events uniformly, where N separate typed handlers would be worse than one match. It composes with the typed handlers rather than replacing them — the effects of both are collected — so a hook may implement specific on_<event> handlers and an on_any without either clobbering the other. Default no-op.

reserved_input_names: frozenset[str]

Input keys this hook reserves for its AddInputs writes.

Two active hooks reserving the same key are rejected at seed time — when the next jaz.invoke assembles the blackboard, not when the hook is activated — with REPLInputConflictError. Optional, like every declaration here: an unreserved collision still raises, but only once the two writes meet. Set it on the class, or per instance in __init__ when the key is a constructor argument.

reserved_namespace_names: frozenset[str]

REPL namespace names this hook reserves for its AddToNamespace writes.

Two active hooks reserving the same name are rejected at seed time with REPLInputConflictError. Set it on the class, or per instance in __init__ when the name is a constructor argument.

reserved_llm_response_fields: frozenset[str]

LLMResponse fields this hook reserves for its ModifyLLMResponse writes ("content", "cost_usd", …).

Authority is per field: two active hooks reserving the same field are rejected at seed time with LLMResponseConflictError, while hooks that set disjoint fields compose. Set it on the class, or per instance in __init__. Distinct from reserves_llm_response despite the name: that one is authorship of the turn at LLMQuerySend, this one is per-field editing of the response at LLMQueryComplete, and neither is checked against the other.

reserved_blackboard_keys: frozenset[str]

Blackboard keys this hook reserves for its BlackboardWrite writes.

Two active hooks reserving the same key are rejected at seed time with BlackboardWriteConflictError. Set it on the class, or per instance in __init__ when the key is a constructor argument.

Writes only — do not reserve a key you merely seed. Seeds need no reservation: they are assembled before the first event, so two hooks seeding one key with different values already raise BlackboardSeedConflictError there, at no cost. Reserving a seeded key cannot stop an undeclared writer, and against one that does declare it is actively harmful: seeding a key and writing it at a later event is legal — the later generation overwrites — but two declarers of one key are refused whatever they meant to do with it, so the invoke never starts.

reserves_llm_response: bool

Whether this hook reserves authorship of the model’s turn — whether it may emit SupplyLLMResponse.

That effect is sole-authority — one response per turn — so two active hooks both reserving it are rejected at seed time with LLMResponseConflictError. Set it on the class, or per instance in __init__.

reserves_exec_return: bool

Whether this hook reserves the return value of a REPL execution — whether it may carry a Return in a SupplyExecResult or ModifyExecResult.

NOT “may emit that effect”: several hooks carrying Continue at one boundary is normal and composes (outputs concatenate, exceptions group), and two Raise results group their exceptions. Only a Return is sole-authority, because two distinct return values cannot merge — which is why the name says return and not result. Two active hooks reserving it are rejected at seed time with ReturnValueConflictError. Set it on the class, or per instance in __init__.

reserves_invoke_return: bool

Whether this hook reserves the return value of an invoke — whether it may carry a Return in a SupplyInvokeResult or ModifyInvokeResult.

The invoke-boundary twin of reserves_exec_return, and the most expensive slot to get wrong: it is decided at InvokeComplete, after the agent has finished, so an unreserved collision kills the run with its whole cost already spent. Two active hooks reserving it are rejected at seed time with ReturnValueConflictError. Set it on the class, or per instance in __init__.

blackboard_seed: dict[str, object]

Return this hook’s contribution to the blackboard’s initial contents.

The blackboard is a small shared scratch space (a key/value store) that every hook active for an invoke can read and write, used to pass per-invoke data between hooks and the caller; “generation 0” is its initial contents, assembled from these seeds before the run starts.

Merged into the seed before InvokeEnter is dispatched, so seeded keys are visible to every event including the first. Must be a pure function of the hook’s own state (its constructor args) — it receives no invoke context (prompt/config/inputs). A value that must be computed from the invoke’s parameters is not seedable and belongs at InvokeEnter as an effect; keeping seeds own-state-only is what avoids a pre-InvokeEnter dispatch (and the generation-regress it would imply). Default: no seed.

setup() -> None

Acquire resources for this hook (open files, start providers, …).

Default no-op. Override in stateful hooks instead of overriding __enter__. This runs on whichever activation path is used:

  • the with MyHook(): context-manager path (via __enter__), and
  • the per-invoke path (a hook passed positionally to jaz.invoke), which deliberately does NOT touch the contextvar.

A given instance is active via exactly ONE path at a time — activating it via both at once raises HookActivationError — so setup() runs once per activation and a stateful hook need not make it idempotent. Separating resource lifecycle from contextvar registration is what lets per-invoke hooks run cleanup without re-introducing propagation.

setup() may run more than once on one instance, at different times: re-activating a hook whose previous scope has ended is allowed. See the class docstring for the two policies a stateful hook must choose between, and forbid_reactivation.

forbid_reactivation() -> None

Refuse a second activation of this instance. Call from setup if reuse is unsafe.

Raises HookActivationError on every activation after the first, whether or not the earlier one has ended. An activation whose setup went on to fail still counts as the first: this runs before the rest of setup and cannot know how it turns out, so a retry after a transient failure is refused too.

teardown(exc: BaseException | None = None) -> None

Release resources for this hook (flush/close files, end spans, …).

Default no-op. Override in stateful hooks instead of overriding __exit__ (and do NOT call super().__exit__ — contextvar de-registration is handled by the base __exit__). Runs on both the with and per-invoke activation paths.

exc is the exception that propagated out of the scope (or None on clean exit), mirroring the exception __exit__ would have seen.

Bases: Hook

Write the run as an ATIF trajectory JSON file.

ATIF (Agent Trajectory Interchange Format) is the standard trace format JAZ reads and writes; a trajectory records an invoke’s turns, messages, and per-call metrics.

A pure observer: it emits no effects, so it never influences the run. The file is written once, when the hook’s scope ends — a single trajectory object when the scope held one top-level invoke, an array when it held several (nested invokes appear under their parent’s subagent_trajectories, not as extra roots). The resulting trace is also the input TrajectoryReplay resumes from.

Because the write happens at scope end, nothing is on disk while the run is in progress: tail -f on output_path shows nothing until it finishes, and a process killed outright leaves no file at all. An ordinary exception does still write, and get_trajectories returns the same documents mid-run. For a trace that reaches disk as it happens, see TrajectoryDirectoryRecorder, which writes a browsable directory rather than this JSON.

Under with the trace covers invokes nested inside. Passed positionally, only that invoke is traced and its sub-invokes are absent from the output.

Document shape. ATIF-v1.7 fixes the field names and where custom data may live; what the values mean for a JAZ run is set here, and a generic ATIF reader cannot assume it.

Standard fields written:

  • schema_version — "ATIF-v1.7". trajectory_id — the invoke id.
  • agent — {"name", "version"}, plus model_name when the backend reports one (omitted when model_info.name is None, as for MockLLM). The model is recorded once per trajectory, so the per-step model_name the standard allows is never written.
  • steps — one per message, in buffer order. source is system / user / agent. On an agent step, message is the LLM’s response verbatim, as it arrived and before the protocol parses it: a response wrapped in markdown fences appears here with its fences, and is not what the REPL went on to execute. llm_call_count is 1 there and 0 elsewhere; metrics rides the same step, carrying tokens, cost_usd, and cached_tokens whenever the backend reports a count at all — 0 included, so the key’s presence says the backend tracks caching, not that this turn hit a cache.
  • final_metrics — totals for this invoke alone, excluding its subagents; sum the tree yourself for a whole-run figure. total_steps counts REPL iterations, not len(steps). The document’s top-level notes says so inside the file, for a reader holding only the JSON.
  • subagent_trajectories — one complete, independently-valid trajectory per nested invoke, recursively. A reader that walks only the top-level steps sees the root invoke and nothing else, which on a delegating run is a small minority of the turns.

Standard fields deliberately absent: session_id, continued_trajectory_ref, and the step-level reasoning_content, tool_calls, observation, is_copied_context and reasoning_effort. A REPL agent acts by writing code in message rather than by calling tools, and its observations arrive as ordinary user steps.

Everything JAZ-specific rides extra, the standard’s slot for it, and no other reader should expect it. Per trajectory: writer_records (always, so a reader need not date the document by probing for a field), then depth, parent_repl_iteration, inputs, input_edits, recursion_disabled, repl_history_withheld, scope, hooks, query_failures, retries and outcome, in that order — each omitted when empty, so a plain completed run carries few of them. The invoke’s result is inside outcome, shaped like InvokeExit.outcome field for field, rather than in flat result_* keys. Per step: provenance, position, iteration, message_edits and raw_message on a transformed agent step — the conversation-history channel this module’s own docstring specifies in full.

Example:

from jaz import invoke
from jaz.hooks import TrajectoryRecorder
with TrajectoryRecorder(output_path="./trace.atif.json"):
result = invoke(task="Do something")

Parameters

  • output_path (str | Path | None) (default: None) — Where to write the trajectory JSON when the scope ends. None (the default) writes no file — read the documents in-memory with get_trajectories instead.
  • indent (int | None) (default: 2) — Indentation for the written JSON; None writes compact single-line output.
__init__(output_path: str | Path | None = None, *, indent: int | None = 2)
on_invoke_enter(event: InvokeEnter) -> list
on_invoke_send(event: InvokeSend) -> list
on_llm_query_send(event: LLMQuerySend) -> list
on_llm_query_enter(event: LLMQueryEnter) -> list
on_llm_query_retry(event: LLMQueryRetry) -> list
on_llm_query_complete(event: LLMQueryComplete) -> list

Capture the raw response, before any Complete-stage transform runs.

on_llm_query_exit(event: LLMQueryExit) -> list
on_invoke_exit(event: InvokeExit) -> list
get_trajectories() -> list[dict[str, Any]]

Return the ATIF trajectory documents traced so far, one per top-level invoke.

Built fresh from the recorded state on each call, so it can be read mid-run or after the scope ends; nested invokes appear inside their parent’s document.

setup() -> None

Prepare for a run: with an output_path, refuse reuse; without one, start clean.

Raises HookActivationError when this instance has already been activated and output_path is set, because the second run’s file would replace the first’s.

teardown(exc: BaseException | None = None) -> None

Write the output file when the hook’s scope ends.

Bases: Hook

Write a browsable trajectory directory incrementally as a run executes.

Each message is written the moment it is seen, so a long run can be watched (tail -f <output_dir>/trace.md) while it is still going, and a run that dies keeps everything up to the failure. A pure observer: it emits no effects, so it never influences the run it records.

The two neighbours it is easily confused with: TrajectoryRecorder writes machine- readable ATIF (Agent Trajectory Interchange Format) JSON, once, at scope end, and is what TrajectoryReplay reads; the trace_to_directory utility writes this same kind of tree, but from a finished ATIF file after the run. Reach for this hook when the point is watching a run in progress.

Parameters

  • output_dir (str | Path) — Directory to stream the trajectory into, created if absent. The first top-level invoke expands directly into it; sub-agents and any further roots get their own sub-directories. It is written into as-is: a trace already at that path is overwritten file by file as the new run reaches each one, and any sub-agent directories the old run left behind survive and interleave with the new ones. Give each run its own directory.

Raises

  • OSError — If output_dir cannot be created or written to.
__init__(output_dir: str | Path)
setup() -> None

Refuse reuse: a second run would overwrite the directory this one wrote.

Raises HookActivationError when this instance has already been activated. Construct a new recorder, with its own output_dir, for each run.

TrajectoryDirectoryRecorder.on_invoke_enter

Section titled “TrajectoryDirectoryRecorder.on_invoke_enter”
on_invoke_enter(event: InvokeEnter) -> list[Effect]

TrajectoryDirectoryRecorder.on_invoke_send

Section titled “TrajectoryDirectoryRecorder.on_invoke_send”
on_invoke_send(event: InvokeSend) -> list[Effect]

TrajectoryDirectoryRecorder.on_llm_query_enter

Section titled “TrajectoryDirectoryRecorder.on_llm_query_enter”
on_llm_query_enter(event: LLMQueryEnter) -> list[Effect]

TrajectoryDirectoryRecorder.on_llm_query_send

Section titled “TrajectoryDirectoryRecorder.on_llm_query_send”
on_llm_query_send(event: LLMQuerySend) -> list[Effect]

TrajectoryDirectoryRecorder.on_llm_query_exit

Section titled “TrajectoryDirectoryRecorder.on_llm_query_exit”
on_llm_query_exit(event: LLMQueryExit) -> list[Effect]

TrajectoryDirectoryRecorder.on_invoke_exit

Section titled “TrajectoryDirectoryRecorder.on_invoke_exit”
on_invoke_exit(event: InvokeExit) -> list[Effect]

Bases: Hook

Replay saved LLM responses from an ATIF trace instead of calling the model.

ATIF (Agent Trajectory Interchange Format) is the standard trace format JAZ reads and writes — here, the saved run that responses are replayed from.

Each turn consumes the next saved response for the active invoke in order. Once an invoke’s responses run out, its live LLM calls resume.

The trace (as written by TrajectoryRecorder) is the canonical replay/cost format. Each invoke replays from its own per-invoke queue — one TrajectoryReplay covers the whole invoke tree, and a nested invoke never shifts a sibling’s or parent’s cursor. The per-call tokens and cost are the real metrics recorded in the trace (prompt_tokens / completion_tokens / cost_usd) — no reconstruction — so replayed calls report exact token totals as well as exact dollar cost.

With detect_divergence=True, replay stops for an invoke as soon as it stops matching, on any of four comparisons: before an invoke’s first query, its starting prompt is compared to the saved one; before each query, the message edits hooks composed for it are compared to the saved ones; as each query closes, the assistant turn the run is about to commit is compared to the saved one; after each REPL exec, the output is compared to the saved observation. On the first difference that invoke diverges — every LLM call from then on is live, including ones that would still have matched, and a differing prompt takes the current query live rather than answering it from the trace. Divergence is per-invoke, so a diverged invoke never desynchronizes a still-replaying sibling or parent. Use this to re-run an old trace under a change: everything before the first difference replays for free, and everything after it is paid for.

Output comparison is not byte-for-byte. The live output is abbreviated the way the original run abbreviated it, and REPL session IDs and traceback line numbers are normalized away, so edits elsewhere in the source do not read as divergence. It is not stable across a change to the truncation format: after such a change, every saved iteration whose output was truncated reports a divergence even on an otherwise identical rerun. Edit and assistant-turn comparison have no such exposure — the trace stores an added message’s role and content, and the assistant turn, verbatim, and all are compared as values.

The starting-prompt comparison covers everything the prompt shows, including each input’s rendering, so it diverges on an input whose text differs between runs, such as a fresh temp path, even when nothing else changed. It cannot see past what the prompt shows: an input too long for the prompt is shown abbreviated, and a difference only in the part left out is caught only if it changes a REPL output.

Two limits worth knowing. A trace written before message edits were recorded is detected and its edit comparison skipped entirely (the other checks are unaffected), and one written before the starting prompt was stamped skips that comparison the same way.

An invoke launched by a turn of its parent that did not replay calls the model live as well, since the code launching it is not the code that launched the recorded one. That covers a parent turn that went live, in either mode, and with detect_divergence one that was served but diverged as its query closed.

A content-changing ModifyLLMResponse is handled, but only for a trace whose writer recorded the pre-transform content — traces written by this version and later, which declare raw_message in extra.writer_records. On those, replay supplies the raw turn, the rerun’s own transform re-derives the recorded one, and a rerun under the same hook replays free with no divergence; a transform added or dropped since the recording does differ, and is reported. On an OLDER trace the saved response is the post-transform turn and there is no raw to supply, so a content-changing transform on the rerun re-applies itself to a turn that already carries it, the committed turn differs, and the invoke diverges on its FIRST turn — one free response per invoke and live calls after it, even when nothing about the run has changed. That one free turn is itself the doubly-transformed one and divergence does not undo it (detection happens as the query closes, by which point the turn is committed), so such a rerun keeps a first turn matching neither the trace nor a live run. Neither comparison sees a transform that changes only tokens or cost, on a trace of any vintage, so a re-pricing hook silently drifts the run’s cost totals away from the trace’s.

Under with the replay covers invokes nested inside. Passed positionally, only that invoke replays; this hook supplies nothing to the invokes it nests, so they call the model live unless something else replays them.

A trace of several top-level invokes, which TrajectoryRecorder writes when its scope ran more than one, replays them in the order they were recorded: each top-level invoke in the scope takes the next one. A top-level invoke beyond the recorded ones calls the model live and logs a warning. Recordings are matched to invokes by order, which assumes the scope re-runs the recorded invokes one after another in the order they ran – what a script resuming its own interrupted run does.

One instance can be activated again once its scope has ended, and each activation replays the trace from its start; is_exhausted and replayed_response_count describe the most recent run.

Parameters

  • path (str | Path) — Path to an ATIF .atif.json trace (as written by TrajectoryRecorder).
  • detect_divergence (bool) (default: False) — When True, each invoke’s starting prompt is compared to the saved one, and each saved response is paired with the message edits composed for its query, with the assistant turn the query committed, and with the REPL observation that followed its exec; a differing starting prompt, the first query whose edits or committed turn differ, or the first exec whose output differs marks THAT invoke diverged, switching it (only it) to live LLM for the rest of the run.

Raises

  • ValueError — If the trace holds no trajectory, or if a trajectory’s recorded observations or message edits are not 1:1 with its responses (a misaligned trace cannot be replayed, since the divergence checks index them by response).
__init__(path: str | Path, *, detect_divergence: bool = False) -> None
setup() -> None

Rewind to the start of the trace, so each activation replays it from its first response.

Raises

  • HookActivationError — If an invoke on this instance is still open: a run is in progress elsewhere, or an earlier run was interrupted before this hook saw its end. Construct a new TrajectoryReplay instead.
is_exhausted: bool

Whether all saved responses have been replayed.

replayed_response_count: int

How many saved responses have been handed back so far.

Counts individual responses, not passes over the trajectory: a recorded run is a tree of invokes, each node holding its own response list, and this sums how far each node’s cursor has advanced. It never exceeds saved_response_count, but it does not have to reach it: once the live run diverges from the recording, the diverged node stops advancing and the count stalls below the total for the rest of the run.

saved_response_count: int

Total number of saved responses this hook will serve.

The public count used by resume banners; the total lives in the invoke tree.

on_invoke_enter(event: InvokeEnter) -> list
on_invoke_exit(event: InvokeExit) -> list
on_llm_query_enter(event: LLMQueryEnter) -> list
on_llm_query_send(event: LLMQuerySend) -> list
on_llm_query_exit(event: LLMQueryExit) -> list
on_repl_exec_exit(event: REPLExecExit) -> list

Bases: Hook

Refuse an attempted finish (return/raise) up to a given number of times.

A refused finish is shown to the agent as a recoverable error, so it keeps working instead of stopping. After refusals refusals this hook stops refusing and lets the next one through.

Inspired by budget-forcing decoding, which suppresses the model’s end-of-thinking token to make it keep reasoning. Here the finish being refused is the agent’s return/raise rather than a decoding token.

Under with it applies to every invoke in scope, nested ones included, each counting its own refusals against refusals. Passed positionally, only that invoke’s finishes are refused.

Parameters

  • refusals (int) — Number of early return/raise attempts to refuse before allowing the agent to finish.
  • refusal_text (str) — The text shown to the agent as the recoverable error when a finish is refused. Required — this hook prescribes no default wording; the caller supplies exactly what the agent sees (used verbatim for both return and raise refusals). Named to parallel the warning_text of the limit/budget hooks (the caller-owned agent-facing string), while refusal_ marks that it is an error reason, not an advisory nudge.
__init__(refusals: int, refusal_text: str) -> None
on_invoke_exit(event: InvokeExit) -> list[Effect]
on_repl_exec_complete(event: REPLExecComplete) -> list[Effect]

Bases: Hook

Enforce one shared LLM cost/call budget over everything in the hook’s scope.

Every invoke the hook is active for draws on the same budget. Reaching cost_budget or calls_budget is a hard stop: the invoke ends by raising BudgetPoolExhaustedError. Before that, if a warn_*_remaining headroom is set, the agent is warned to finish once the remaining budget falls to it.

The scope covered by the budget pool depends on how it is activated:

  • with BudgetPool(...): — every jaz.invoke() in the block and every invoke nested inside those shares the one budget. Use this to cap a whole workflow.

  • jaz.invoke(BudgetPool(...), ...) — the pool covers only that invoke’s own LLM calls, excluding its sub-invokes.

  • with BudgetPool(...): opened mid-REPL — written in the agent’s own turn of code, or by anything that turn calls — behaves exactly like the first shape. It covers the with statement’s body: every invoke started while that body runs, and everything nested inside those. It covers nothing before or after the body, including the rest of the same turn’s code.

    The enclosing invoke is never covered, whatever the body contains. A hook applies to whole invokes, and that invoke was already running when the body was entered; it also outlives the body, which cannot span turns because the turn’s code has to unwind it before returning.

The budget starts empty when the scope opens.

This hook enforces only; it produces no cost report. For a per-invoke cost/token breakdown (including the full sub-invoke tree), read the trace written by TrajectoryRecorder — it records the same cost off the same event.

Note that if a single turn jumps from above the warning headroom straight past the budget, the agent is stopped with no warning at all. Set warn_cost_remaining / warn_calls_remaining appreciably larger than a typical turn’s cost / a single call so the warning turn is not skipped.

Missing token usage degrades; it does not crash. A provider may return a response with no usage block; this hook does not track tokens, so a missing usage block is a non-event for it. A missing cost (cost_usd is None) under a cost_budget is a different matter — the budget is then unenforceable and the hook aborts (see on_llm_query_exit); with no cost_budget the call is booked as $0 and the calls_budget keeps counting it.

Parameters

  • cost_budget (float | None) (default: None) — Hard ceiling on total LLM cost in USD. None (default) means no cost limit; otherwise must be positive.
  • calls_budget (int | None) (default: None) — Hard ceiling on total LLM calls. None (default) means no call limit; otherwise must be positive.
  • warn_cost_remaining (float | None) (default: None) — If set, warn the agent to finish once the remaining cost budget (cost_budget minus spend) falls to this many USD or fewer. Absolute headroom, not a fraction of the budget. None (default) emits no approaching cost warning; the hard stop at cost_budget still applies. Requires cost_budget (the budget it measures against) and must be paired with warning_text.
  • warn_calls_remaining (int | None) (default: None) — Same, in remaining LLM calls against calls_budget. None (default) emits no approaching calls warning. Requires calls_budget and must be paired with warning_text.
  • warning_text (str | None) (default: None) — The warning text, used verbatim — the only text this hook emits (an empty string emits nothing). None (default) means no warning at all. Coupled with the thresholds (like IterationLimit): warning_text and at least one warn_*_remaining are either both set (a warning fires), or all None (no warning).

Raises

  • ValueError — If cost_budget, calls_budget, warn_cost_remaining, or warn_calls_remaining is set but not positive; if a warn_*_remaining is set without its matching budget (cost_budget / calls_budget); or if exactly one of warning_text / (a warn_*_remaining threshold) is set — they are coupled, so it is all-None (no warning) or both.
__init__(*, cost_budget: float | None = None, calls_budget: int | None = None, warn_cost_remaining: float | None = None, warn_calls_remaining: int | None = None, warning_text: str | None = None) -> None
setup() -> None

Reset the aggregate for this hook’s scope (with/local_hooks entry).

teardown(exc: BaseException | None = None) -> None

No-op: this hook writes no report. Present so the scope-close contract is explicit.

on_llm_query_exit(event: LLMQueryExit) -> list[Effect]
on_llm_query_enter(event: LLMQueryEnter) -> list[Effect]

Bases: Hook

Warn the agent as its prompt approaches the model’s context window.

Advisory only: it emits a warning into the prompt and never terminates the invoke. The model’s own context-window limit remains the hard stop — the LLM call fails once the prompt exceeds it.

Under with, every invoke in scope is watched, each against its own prompt. Passed positionally, only that invoke is — this hook does not warn the invokes it nests.

Parameters

  • warn_fraction (float) — The warning threshold — warn once prompt_tokens / max_input_tokens reaches this fraction. Required. Deliberately kept a FRACTION, unlike the absolute thresholds on IterationLimit / BudgetPool: context windows span ~100x across models, so only a scale-free threshold is meaningful across models.
  • warning_text (str) — Agent-facing warning text emitted alongside the context-window warning. Required; used verbatim. An empty string emits nothing.
on_invoke_enter(event: InvokeEnter) -> list[Effect]
on_llm_query_exit(event: LLMQueryExit) -> list[Effect]
on_invoke_exit(event: InvokeExit) -> list[Effect]
on_llm_query_enter(event: LLMQueryEnter) -> list[Effect]
__init__(warn_fraction: float, warning_text: str) -> None

Bases: Hook

Hard-stop the agent at its per-level REPL iteration limit.

Stops the agent with IterationLimitExhaustedError if it does not finish within max_iterations iterations. Iterations are numbered from 0, so the agent runs indices 0 through max_iterations - 1 and is aborted on reaching max_iterations.

If warn_remaining is set, once that many iterations or fewer are left the caller’s warning_text is emitted verbatim to nudge the agent to finish. There is no separate last-turn notice: with warn_remaining unset (⟺ warning_text unset), the hard stop is the only behaviour.

Under with the cap applies to every invoke in scope, nested ones included (or to those inside min_depth/max_depth, when set), each counting its own iterations against max_iterations. Passed positionally to one jaz.invoke, it caps only that invoke and not the invokes it nests.

Parameters

  • max_iterations (int) — Max number of iterations. Must be positive (>= 1).
  • warning_text (str | None) (default: None) — The warning text, used verbatim — the only text this hook emits (an empty string emits nothing). None (default) means no warning text. Must be paired with warn_remaining: both set, or both None.
  • warn_remaining (int | None) (default: None) — If set, warn the agent to finish once this many iterations or fewer remain (counting the current one). An absolute turn count, not a fraction of the cap. None (default) emits no warning at all. Must be paired with warning_text (both set, or both None).
  • min_depth (int | None) (default: None) — If set, apply nothing — neither the cap nor the warning — to invokes shallower than this. Absolute recursion depth, 1-based (a top-level invoke is depth 1), so min_depth=2 means “delegated invokes only”. None (default) sets no floor. Subject to the depth attribution gap RecursionLimit documents — see the note below the field definitions.
  • max_depth (int | None) (default: None) — If set, apply nothing to invokes DEEPER than this, so max_depth=1 means “the top-level invoke only”. None (default) sets no ceiling.

Raises

  • ValueError — If max_iterations is not positive; if exactly one of warning_text / warn_remaining is set (they are coupled); if warn_remaining is not positive; if min_depth or max_depth is less than 1; or if min_depth > max_depth.
  • HookActivationError — On setup(), if a depth window is set and the hook is installed positionally on invoke rather than activated with with.
setup() -> None
on_llm_query_enter(event: LLMQueryEnter) -> list[Effect]
__init__(max_iterations: int, *, warning_text: str | None = None, warn_remaining: int | None = None, min_depth: int | None = None, max_depth: int | None = None) -> None

Bases: Hook

Cap jaz.invoke recursion at max_depth levels.

max_depth is the maximum number of invokes on the stack, so max_depth=1 allows a top-level invoke and no sub-invokes at all.

Depth is taken from the invoke a call runs inside, not from where the call is written. A function of yours that calls jaz.invoke produces a depth-1 invoke when your own code calls it, and a depth-2 invoke when an agent calls it from within an invoke.

Must be activated with with RecursionLimit(max_depth=N):. Passing it positionally raises HookActivationError: a positional hook does not reach nested invokes, so it could not cap them.

An agent at max_depth runs normally but is not given the invoke tool. It can still reach one indirectly — through a function you passed it that invokes internally — so a sub-invoke that lands past the cap is refused with RecursionLimitError.

Known gap. Under the above definition of “depth”, a sub-invoke is considered the sub-invoke of the invoke that calls it, including when an agent wraps its bound jaz.invoke in a function and passes that function down. However, the current implementation does not obey this when the wrapper’s jaz.invoke call runs on a thread that did not inherit the calling invoke’s context — either because the caller ran the wrapper on a thread it spawned (a ThreadPoolExecutor worker, say), or because the wrapper spawns one itself and invokes inside it. The invoke is then counted at the binding invoke’s depth instead of the caller’s, so a stack deeper than max_depth can be built that way. (Note that this gap requires allowed_imports to be set to allow agents to spawn threads.)

Parameters

  • max_depth (int) — Deepest allowed invoke depth, 1-based — a top-level invoke is depth 1, its sub-invokes depth 2, sub-sub-invokes depth 3, etc. (User code outside any invoke is at depth 0.)

Raises

  • ValueError — If max_depth is less than 1.
setup() -> None
on_invoke_enter(event: InvokeEnter) -> list[Effect]
__init__(*, max_depth: int) -> None

Bases: Hook

Log every event to the terminal, with colors.

A pure observer: it emits no effects, so it never influences the run.

Under with it logs invokes nested inside too. Passed positionally, it logs only that invoke’s events.

Parameters

  • level (int) (default: logging.INFO) — Logging level for the emitted records.
  • max_field_length (int | None) (default: 1000) — Truncate the inputs, scope, hooks and result fields longer than this; conversation message lines are written whole. None disables truncation.
__init__(*, level: int = logging.INFO, max_field_length: int | None = 1000)
on_any(event: Event)

Log event to terminal.

teardown(exc: BaseException | None = None) -> None

Bases: Hook

Log every event to a file, without colors.

A pure observer: it emits no effects, so it never influences the run.

Under with it logs invokes nested inside too. Passed positionally, it logs only that invoke’s events.

Parameters

  • file_path (str | Path) — Destination file, appended to: existing content is kept. It is opened when the logger is constructed and closed when each scope exits; the next record written reopens it and keeps appending.
  • level (int) (default: logging.INFO) — Logging level for the emitted records.
  • max_field_length (int | None) (default: 1000) — Truncate the inputs, scope, hooks and result fields longer than this; conversation message lines are written whole. None disables truncation.
__init__(file_path: str | Path, *, level: int = logging.INFO, max_field_length: int | None = 1000)
on_any(event: Event)

Log event to file.

teardown(exc: BaseException | None = None) -> None

Flush and close file handlers.

Bases: Hook

Declare an invoke’s return type — the agent is told it, and the value is checked.

Pass it as the first positional argument so the type is also inferred statically:

x: str = invoke(ReturnType(str), task=...)

A returned value of the wrong type is shown to the agent as a recoverable error and it keeps working; a wrong-typed value never escapes to the caller. By default there is no cap — the agent retries until it returns the right type or hits another limit (iteration/budget). Set max_failures to instead abort terminally once the agent has produced that many wrong-typed returns and one more — what you want when the type may be impossible for the agent to construct: the caller then gets a type-specific error rather than a generic budget-exhausted one.

Every class in the type other than a builtin — your own (Apology, list[Apology], Apology | None), the standard library’s (datetime.date) or an installed package’s (np.ndarray) — is added as an input under its own name: it renders in the prompt like any input (constructor signature, docstring, members) and binds in the REPL, so the agent can return Apology(...) without importing anything. A large library class renders as large as it would if passed by hand. Builtins, typing forms, protocols and abstract classes are not added. That includes the exceptions outside Exception (KeyboardInterrupt, SystemExit, BaseException, …), which the default REPL does not give the agent, so a return type naming one exactly cannot be constructed unless you pass the class as an input yourself. A name the caller already passes as an input or a jaz.scope value is left alone. Another hook adding the same class under the same name is fine; a different value under that name raises REPLInputConflictError. If another hook drops the caller’s same-named input, nothing binds the class.

Passed positionally — the usual form, and the only one that types the call statically — it applies to that invoke alone. Under with it also applies to every invoke nested inside, holding each of them to the same return type.

Parameters

  • return_type (TypeForm[ReturnT] | None) — The expected return type. Any type annotation works (None, str, list, dict[str, int], …).
  • max_failures (int | None) (default: None) — How many wrong-typed returns the agent may make and recover from before the next one aborts the invoke — a tolerance, not a total (0 aborts on the first wrong type; 2 allows two recoveries, aborting on the third). The abort raises a type-specific error naming the offending value. Only type mismatches count, and they are counted cumulatively across the whole invoke (a valid return ends it; a later wrong-typed one still draws on the same budget). None (the default) never escalates — the agent may keep retrying until it returns the right type, so IterationLimit / BudgetPool is the backstop, not this hook. Must be >= 0. Mirrors ValidateReturn.max_failures.

Raises

  • TypeError — At construction, if return_type is not a proper type annotation.
  • ValueError — At construction, if max_failures is negative.
__init__(return_type: TypeForm[ReturnT] | None, *, max_failures: int | None = None) -> None
on_invoke_enter(event: InvokeEnter) -> list[Effect]
on_llm_query_enter(event: LLMQueryEnter) -> list[Effect]
on_repl_exec_complete(event: REPLExecComplete) -> list[Effect]
on_invoke_complete(event: InvokeComplete) -> list[Effect]
on_invoke_exit(event: InvokeExit) -> list[Effect]

Bases: Hook

Accumulate each invoke’s TurnRecords and freeze them into rollouts.

Use as a context manager (with RolloutRecorder() as rec:); after the block, rec.rollouts holds one Rollout per recorded invoke, in completion order. Invokes whose backend produced no turn records (text backends, replay overrides) yield no rollout — a warning is logged once per invoke.

__init__() -> None
setup() -> None
on_llm_query_exit(event: LLMQueryExit) -> list[Effect]
on_invoke_exit(event: InvokeExit) -> list[Effect]

One invoke’s frozen trajectory record: its turns plus terminal facts.

Attributes

  • invoke_id (str) — The invoke this trajectory belongs to.
  • depth (int) — Nesting depth of that invoke — 1 for a top-level call — which is what separates a sub-invoke’s trajectory from its parent’s.
  • turns (tuple[TurnRecord, ...]) — The token record of every LLM query the invoke made, in order.
  • finished (str) — "completed" for a normal return, or "aborted:<ExceptionType>" (e.g. "aborted:IterationLimitExhaustedError") carrying the concrete exception class name. Partial rollouts are emitted, not dropped, and are filterable on this.
to_spans() -> list[Sample]

The trajectory as flat masked samples, one per maximal prefix-monotone span.

Exactly one sample when every turn’s context extended the previous one; a new sample at each break — a stripped reasoning trace, a transient hook nudge, a compaction. Always resolves. A pre-break turn appearing in a later span’s context has loss mask 0 there: it was sampled against its own span’s prefix and gets its loss there, so each sampled token is trained exactly once across the list.

__init__(invoke_id: str, depth: int, turns: tuple[TurnRecord, ...], finished: str) -> None

One flat masked token sequence — a training sample, plus what a batched consumer needs.

Attributes

  • ids (tuple[int, ...]) — The full token sequence.
  • loss_mask (tuple[int, ...]) — 1 exactly where ids[i] was sampled by the policy, else 0.
  • logprobs (tuple[float, ...]) — The sampling logprob where loss_mask[i] == 1, 0.0 elsewhere, aligned to the full ids.
  • prefix_len (int) — The prompt/response boundary: ids[:prefix_len] is everything the model conditioned on before the first sampled token, so len(ids) - prefix_len is a trainer’s response length and logprobs[prefix_len:] its response-only alignment.
  • invoke_id (str) — As on Rollout.
  • span_index (int) — This row’s position among the rollout’s spans; (invoke_id, span_index) identifies it once samples are batched across rollouts.
to_dict() -> dict[str, Any]

JSON-compatible projection — the JSONL unit (ids/mask/logprobs as lists).

__init__(ids: tuple[int, ...], loss_mask: tuple[int, ...], logprobs: tuple[float, ...], prefix_len: int, invoke_id: str, span_index: int) -> None

Bases: Hook

Validate an invoke’s return value, rejecting it as a recoverable error.

A rejected value does not end the invoke: the agent is shown the validator’s exception and keeps going, so it can correct itself and return again. The agent may be rejected max_failures times and recover; the next rejection ends the invoke by raising, so max_failures=0 makes the very first rejection terminal.

Passed positionally it validates that one invoke. Under with the same validator is applied to every invoke in scope, nested ones included — usually not what you want, since a sub-invoke returns to its caller, not to you, and is rarely subject to the same rule. Either way each invoke counts its own rejections against max_failures rather than drawing down its parent’s.

Parameters

  • validator (Callable[[ReturnT], None]) — Called with the return value; it should raise iff the value is invalid. The exception it raises is shown to the agent as a recoverable error, except for the one past the cap, which propagates out of the invoke unchanged — include the offending value in the message if the caller needs to see it.
  • max_failures (int | None) (default: None) — How many rejected returns the agent may recover from before the next rejection ends the invoke — a tolerance, not a total (0 raises on the first rejection; 2 allows two recoveries, raising on the third). Counted cumulatively across the whole invoke (a valid return ends it; a later rejected one still draws on the same budget). None (the default) never escalates — the agent may keep retrying until it satisfies the validator, so IterationLimit / BudgetPool is the backstop, not this hook. Must be >= 0.

Raises

  • ValueError — At construction, if max_failures is negative.
__init__(validator: Callable[[ReturnT], None], *, max_failures: int | None = None) -> None
on_invoke_complete(event: InvokeComplete) -> list[Effect]
on_invoke_exit(event: InvokeExit) -> list[Effect]
on_repl_exec_complete(event: REPLExecComplete) -> list[Effect]

Bases: Hook

Validate REPL code before execution, rejecting invalid code as a recoverable error.

On rejection the code never runs: the agent is shown the validator’s exception and retries. The agent may be rejected max_failures times and recover; the next rejection ends the invoke (the validator’s exception aborts out), so max_failures=0 makes the very first rejection terminal.

Passed positionally it validates that one invoke. Under with the same validator is applied to every invoke in scope, nested ones included — so a sub-invoke’s code is held to the same rule. Either way each invoke counts its own rejections against max_failures rather than drawing down its parent’s.

Parameters

  • validator (Callable[[str], None]) — Called with the code as a source string; it should raise iff the code is rejected. The exception it raises is shown to the agent as a recoverable error, except for the one past the cap, which aborts the invoke carrying that exception.
  • max_failures (int | None) (default: None) — How many rejections the agent may recover from before the next rejection aborts the invoke — a tolerance, not a total (0 aborts on the first rejection; 2 allows two recoveries, aborting on the third). Counted cumulatively across the whole invoke: a rejection on one turn and an unrelated one many turns later draw on the same budget, and valid code does not reset it. None (the default) never aborts on rejection — the agent may keep revising indefinitely, so IterationLimit / BudgetPool is the backstop, not this hook. Must be >= 0.

Raises

  • ValueError — At construction, if max_failures is negative.
__init__(validator: Callable[[str], None], *, max_failures: int | None = None) -> None
on_invoke_exit(event: InvokeExit) -> list[Effect]
on_repl_exec_send(event: REPLExecSend) -> list[Effect]

Bases: Hook

Export the run as OpenTelemetry spans over OTLP HTTP.

Under with the trace covers invokes nested inside. Passed positionally, only that invoke is traced and its sub-invokes contribute no spans to this trace.

One span per span event family, named after it: invoke (InvokeEnter to InvokeExit), repl_exec (REPLExecEnter to REPLExecExit) and llm_query (LLMQueryEnter to LLMQueryExit); a turn’s repl_exec and the llm_query that chose its code are both children of the invoke span, siblings in call order rather than nested, because the query closes before the turn’s execution opens. An LLMQueryRetry is a span event named llm_query_retry on the open llm_query span. Every field of the events that open, commit and close a span is an attribute under jaz.<field>, with a nested payload flattened by path: jaz.outcome holds the outcome variant’s name (completed / aborted / failed), jaz.outcome.result the result’s type (return / raise / continue / llmresponse), and jaz.outcome.result.<field> its fields (every record node carries its type name, so a plain record such as LLMQuerySend.message_edits appears as jaz.message_edits too). Only the framework’s own records are flattened; a value of the agent’s, a returned dataclass say, is recorded as text. None and empty collections are omitted; strings are truncated to max_attribute_length. jaz.messages is the whole committed message list of every query, each message carrying its provenance stamp, so a long run should set max_attribute_length. The REPL namespace is the one event field left out as a matter of size rather than type: which names the turn bound and unbound ride jaz.namespace_edits, without their values. jaz.scope and jaz.hooks are resolved once per invoke and stamped on the invoke span alone, since copying them onto its every child span would multiply the trace without adding to it; jaz.invoke_id and jaz.depth are on every span, to correlate them. A *Send overwrites what its *Enter stamped, writing an empty collection rather than omitting it, so a committed empty value replaces the proposal instead of leaving it standing. Beside those, the viewer-facing conventions: input.value / output.value and their langfuse.* twins, gen_ai.request.model, and error.type / error.message with ERROR status on a raise, an abort or a failure.

Parameters

  • endpoint (str) — OTLP HTTP traces endpoint (e.g., .../v1/traces)
  • service_name (str) (default: 'jaz-agent') — OTel service.name resource attribute
  • headers (dict[str, str] | None) (default: None) — Optional OTLP exporter headers (auth, tenant, etc.)
  • max_attribute_length (int | None) (default: None) — Maximum length for string attributes. If None, strings are not truncated.

Reads one blackboard key: label, a human name for the run. Seed it with a MetaData(label=...) hook; absent, it is "main". Spans are named after their events (invoke, llm_query, repl_exec), so the label does not name one — it rides the root span as the langfuse.trace.name attribute, which is what Langfuse titles a trace by.

__init__(*, endpoint: str, service_name: str = 'jaz-agent', headers: dict[str, str] | None = None, max_attribute_length: int | None = None)
on_any(event: Event) -> list
teardown(exc: BaseException | None = None) -> None

Bases: OTelTracing

Hook preset for exporting JAZ traces to Jaeger.

Parameters

  • endpoint (str) (default: 'http://localhost:4318/v1/traces') — OTLP HTTP endpoint URL. Defaults to http://localhost:4318/v1/traces.
  • service_name (str) (default: 'jaz-agent') — Service name shown in Jaeger. Defaults to jaz-agent.
  • max_attribute_length (int | None) (default: None) — Maximum length for string attributes. If None (default), no truncation is applied.
__init__(endpoint: str = 'http://localhost:4318/v1/traces', service_name: str = 'jaz-agent', max_attribute_length: int | None = None)

Bases: OTelTracing

Hook preset for exporting JAZ traces to Langfuse Cloud.

By default, credentials are read from environment:

  • LANGFUSE_PUBLIC_KEY
  • LANGFUSE_SECRET_KEY
  • LANGFUSE_HOST (optional, defaults to https://cloud.langfuse.com; LANGFUSE_BASE_URL is also supported as an alias)

Parameters

  • public_key (str | None) (default: None) — Langfuse public key. Falls back to env if omitted.
  • secret_key (str | None) (default: None) — Langfuse secret key. Falls back to env if omitted.
  • base_url (str | None) (default: None) — Langfuse base URL. Falls back to env/default if omitted.
  • service_name (str) (default: 'jaz-agent') — OTel service name attribute.
  • max_attribute_length (int | None) (default: None) — Maximum length for string attributes. If None (default), no truncation is applied.
__init__(*, public_key: str | None = None, secret_key: str | None = None, base_url: str | None = None, service_name: str = 'jaz-agent', max_attribute_length: int | None = None)