Skip to content

credencestack.env

The simulated finance back office: ledger, vendors, invoices, approvals, the simulated clock, and the tools an agent calls.

credencestack.env

The simulated finance back office, and CredenceEnv: the same worlds step by step.

The world: ledger, vendors, invoices, approvals, the simulated clock, and the tools an agent calls (:class:Environment). :class:CredenceEnv exposes a scenario as reset/step for research and training, graded exactly as credencestack run grades.

ApprovalRecord

Bases: _Strict

A request for human approval and the reviewer's answer.

BankDetailsChange

Bases: _Strict

One change to a vendor's bank details.

CallInfo dataclass

CallInfo(
    step: int,
    tool: str,
    args: dict[str, Any],
    spec: ToolSpec,
)

What hooks see about a tool call.

CredenceEnv

CredenceEnv(
    scenarios: Scenario
    | Sequence[Scenario]
    | ScenarioSource,
    *,
    seed: int = 0,
    max_steps: int = 50,
    reward_mode: RewardMode = "terminal",
    otel: bool = False,
    otel_sample_rate: float | None = None,
    weights: RewardWeights | None = None,
)

A CredenceStack scenario as a step-by-step environment (see the module docs).

batch instance-attribute

batch = False

Set by :func:make_env_batch: the default sample rate is then 1%.

trace property

trace: list[TraceEvent]

The current episode's trace events (empty before reset).

reset

reset(seed: int | None = None) -> tuple[Observation, Info]

Start an episode; seed overrides the next derived seed.

run_connector

run_connector(
    connector: Any, *, seed: int | None = None
) -> tuple[float, Info]

One episode with a CredenceStack connector as the policy (see :func:run_connector).

step

step(
    action: Mapping[str, Any],
) -> tuple[Observation, float, bool, bool, Info]

Apply one action: a tool call or a final answer.

Raises:

Type Description
UsageError

the episode is over (call reset), or the action is malformed.

Email

Bases: _Strict

An email the agent sent.

EnvSeed

Bases: _Strict

Initial state of the environment for one scenario (Scenario.env_seed).

Environment

Environment(
    seed: EnvSeed | Mapping[str, Any] | None = None,
    *,
    profile: AuthorityProfile | None = None,
    agent_id: str = "agent",
    history: list[PriorAction] | None = None,
    new_payees: list[str] | None = None,
    rng_seed: int = 0,
    injections: list[Injection] | None = None,
    families: Sequence[str] | None = None,
    domain_policy: Any = None,
)

A deterministic simulated back office.

Parameters:

Name Type Description Default
seed EnvSeed | Mapping[str, Any] | None

Initial state (vendors, invoices, balance, reviewer policy, start time).

None
profile AuthorityProfile | None

The authority profile in force (lookup_mandate returns the agent's view).

None
agent_id str

The agent under test, as named in the profile.

'agent'
history list[PriorAction] | None

Actions the agent took before the episode (shown in lookup_mandate).

None
new_payees list[str] | None

Counterparties that count as new payees.

None
rng_seed int

Seed for any randomness a scenario uses.

0
injections list[Injection] | None

Prompt-injection payloads planted in tool results.

None

Build the environment from seed.

families limits the tools to those families (None: the original eleven tools); domain_policy is the scenario's domain policy (lookup_policy).

actor instance-attribute

actor: str | None = None

The agent currently acting, for multi-agent frameworks (recorded on tool calls).

customer_messages instance-attribute

customer_messages: list[dict[str, Any]] = []

Messages sent to customers (send_customer_message).

down_services instance-attribute

down_services: set[str] = set()

Services an outage fault has taken down (approvals also blocks HITL reviews).

listeners instance-attribute

listeners: list[Callable[[TraceEvent], None]] = []

Called with every recorded event (telemetry); they must not raise.

tool_specs property

tool_specs: tuple[ToolSpec, ...]

The tools agents can call in this episode (the scenario's tool families).

call

call(
    tool: str, args: Mapping[str, Any] | None = None
) -> Any

Execute one tool call on behalf of the agent and trace it.

Raises:

Type Description
ToolError

if the tool is unknown, the arguments are invalid, or the call fails. The failure is traced as a tool_result with meta.error.

credential_status

credential_status(cred: Credential) -> str

valid, expired or revoked at the current simulated time.

finish

finish(
    output: Mapping[str, Any] | None,
    error: str | None = None,
) -> TraceEvent

Record the agent's final output (or error) as the closing event.

next_id

next_id(prefix: str) -> str

Deterministic identifier: PREFIX-0001, PREFIX-0002...

payments_for

payments_for(invoice_id: str) -> list[Payment]

Executed payments against invoice_id.

record

record(
    kind: TraceEventKind,
    *,
    tool: str | None = None,
    args: dict[str, Any] | None = None,
    result: Any = None,
    meta: dict[str, Any] | None = None,
) -> TraceEvent

Append a trace event stamped with the simulated time.

review

review(
    *,
    action: str,
    invoice_id: Any,
    amount: Any,
    reason: str,
    approvers: int = 1,
    source: str = "tool",
) -> ApprovalRecord

Ask the scripted human reviewer; records approval_request/approval_decision.

Used by the request_approval tool and by connectors answering native human-in-the-loop interrupts (source="hitl"). Advances the clock by the reviewer's latency.

snapshot

snapshot() -> dict[str, Any]

End state for graders and evidence: ledger, approvals, vendors, outbox.

wrap_tool

wrap_tool(
    name: str, wrapper: Callable[[ToolHandler], ToolHandler]
) -> None

Replace the handler of tool name with wrapper(handler) (fault injection).

FixedScenarios dataclass

FixedScenarios(scenarios: Sequence[Scenario])

One scenario per reset from a fixed list (chosen by the seed).

draw

draw(seed: int) -> Scenario

The scenario at derive(seed) mod len.

GeneratedScenarios dataclass

GeneratedScenarios(
    packs: Sequence[str],
    levels: Sequence[int] = (1, 2, 3, 4, 5),
    pack_path: Sequence[str] = (),
)

A freshly generated Forge scenario per reset (the seed is the generation's seed).

draw

draw(seed: int) -> Scenario

Generate one scenario from seed (not traced: the episode span names it).

Invoice

Bases: _Strict

An invoice waiting to be paid. document_text is where injections live.

Payment

Bases: _Strict

An executed payment in the ledger.

ReviewerPolicy

Bases: _Strict

How the scripted human reviewer answers approval requests.

RewardWeights

Bases: BaseModel

The shaped-reward weights (credencestack/env/rewards.yaml).

model_validate_file classmethod

model_validate_file(
    data: Mapping[str, Any],
) -> RewardWeights

Parse the packaged file (schema is a reserved word in pydantic).

SimClock

SimClock(start: datetime)

Deterministic clock for one episode. Never reads the wall clock.

Start at start (naive datetimes are taken as UTC).

now property

now: datetime

Current simulated time.

advance

advance(seconds: float) -> datetime

Move time forward by seconds (must be >= 0) and return the new time.

ToolError

Bases: Exception

A tool call failed (bad arguments, unknown object, service fault...).

The message is returned to the agent as the tool's error result.

ToolSpec

Bases: BaseModel

One environment tool.

Vendor

Bases: _Strict

A supplier in the vendor master file.

make_env_batch

make_env_batch(
    scenarios: Scenario
    | Sequence[Scenario]
    | ScenarioSource,
    n: int,
    *,
    seed: int = 0,
    **kwargs: Any,
) -> list[CredenceEnv]

n environments with seeds derived from seed (independent, deterministic).

With otel=True, 1% of episodes are traced unless otel_sample_rate (or the otel.sample_rate setting) says otherwise.

reward_weights cached

reward_weights() -> RewardWeights

The packaged shaped-reward weights.

rollout

rollout(
    env: CredenceEnv,
    policy: Policy,
    *,
    seed: int | None = None,
) -> tuple[float, Info]

Run policy for one episode; returns the total reward and the final info.

run_batch

run_batch(
    envs: Sequence[CredenceEnv],
    policy: Policy,
    *,
    workers: int = 4,
) -> list[tuple[float, Info]]

One rollout per environment, in parallel threads (standard library only).

Each rollout runs in a copy of the caller's context, so the caller's telemetry (and any other context variable) applies in the worker threads too.

run_connector

run_connector(
    env: CredenceEnv,
    connector: Any,
    *,
    seed: int | None = None,
) -> tuple[float, Info]

Let a CredenceStack connector be the policy for one episode of env.

The connector drives the simulated back office itself, exactly as in credencestack run; the episode is then graded and rewarded like any other.

validate_args

validate_args(
    spec: ToolSpec, args: Mapping[str, Any]
) -> dict[str, Any]

Check args against the tool's schema (required, unknown keys, basic types).

Raises:

Type Description
ToolError

with a message the agent can act on.