Run decisions in your app¶
This page takes you from nothing to a saved policy that your app calls, using only the base install. You don't need labels or an evaluation to get started. Once you have labeled cases, move on to Evaluate and compare.
Install the runtime¶
You need Python 3.13 or later. Add the base package to your app. It depends directly on just httpx and pydantic, and it neither installs nor imports the evaluation tools.
Your first decision¶
Your app decides which model connections it allows. For example, connections.toml:
Put the provider's API key in the environment (TYPESAFE_API_KEY in this example). In a sandbox whose proxy adds
the key on the way out (a network secret), leave the variable unset: s1flow then sends no key of its own, and a
401 or 403 back is reported as the key not being set. Which file is trusted, and
how the SDK and the CLI find it, is covered in Connections and discovery.
The file must define the connection that a policy names. A policy adopted from an evaluation names a model from
your project's line-up, such as jev@openrouter, so copy that model's entry from s1flow/s1flow.toml.
Now write bug.json. You don't need any evaluation data, model responses or placeholder scores:
{
"schema": "s1flow/policy@2",
"task": "ticket-bug",
"version": 1,
"connection": "triage",
"model_id": "jev-1.14.0",
"questions": {
"bug": {
"question": {"type": "boolean", "instructions": "Does this report describe a software defect?"},
"rule": {"threshold": 0.5}
}
}
}
s1flow adopt --spec bug.json --connections connections.toml --validate --json
s1flow adopt --spec bug.json --root policies --connections connections.toml --reason "first rule" --json
s1flow decide --policy ticket-bug@v1 --path policies/ticket-bug/v1.json \
--connections connections.toml --state '{"text":"Crash on startup"}' --json
adopt --spec FILE --validate validates the spec and that the connection file (--connections, else the project's
s1flow.toml) defines its connection and allows its model ID, without calling a model or saving anything. adopt --spec saves the policy as a new version that can't be changed,
stamped with when it was created and which SDK version created it, and makes it current; it doesn't claim the
policy has been evaluated.
In app.py, next to connections.toml, build paths from the location of the file itself so it doesn't matter
which directory the app is started from:
from pathlib import Path
from s1flow import Client, policies
APP = Path(__file__).resolve().parent
client = Client(connections=APP / "connections.toml")
policy = policies.load(path=APP / "policies/ticket-bug/v1.json", client=client,
log=APP / "decisions.jsonl", keep_state=True)
decision = policy.decide({"text": "Crash on startup"}, case_id="ticket-42")
print(decision.value, decision.probability, decision.decision_id)
policy.feedback(decision.decision_id, True) # the correct answer, once you know it
log= is where decisions and right answers are kept, so they can be measured and become new cases. Without it
(and without an OpenTelemetry tracer provider) nothing is recorded: the first decide warns, and feedback raises.
The policy API¶
You can also build a PolicySpec in Python and pass it to DecisionPolicy(spec, client=client). Use adecide
for async code. Neither decide nor adecide reads a Task or an Evaluation.
The optional state_schema checks the shape of the input against a subset of JSON Schema: object, array and
scalar types, properties, required fields and additional properties. It is not a full JSON Schema validator. If
the input doesn't match, you get a DataError before any request is sent. Without a schema, s1flow can't
promise that production inputs have the same shape as the ones you evaluated.
A DecisionRule can set a threshold (for a yes/no question, or a choice question with a positive option) and a
min_probability.
Decision.below_min_probability is None when no minimum is set, True when the answer's probability is below it, and
False otherwise. It doesn't mean the answer is right, or that the action is allowed. What happens next is up to
your app (see What s1flow leaves to your app).
What s1flow leaves to your app¶
s1flow keeps something only if changing it would change what your evaluation measured (the request sent to the model, the model version, how the answer is read against the threshold, enforcing the time limit you pass), or if it is needed to record the correct answer later (decision IDs, the log, feedback). Everything around a decision belongs to your code or your agent framework, because changing it doesn't change the numbers you measured for that decision:
- Acting on the answer. s1flow returns the decision. What your app does with it, and whether it is allowed to, is your code.
- Where unsure answers go. When
below_min_probabilityisTrue, the answer's probability is below your minimum. Sending it to a person, a larger model or a default is your code. - Falling back when a call fails. A failed call, or one past its time limit, raises
ProviderError. s1flow doesn't switch to another model: another model is a separate thing to measure. - Order, branching and loops. Which decisions run, in what order and how many times, belongs to your code or a
framework. Call
policy.decideinside it. - Combining scores. Weighting, ranking or choosing from several scores is your own calculation.
s1flow runs in two ways: as a library inside your Python app, which is the path for production, and as the CLI, for
CI, GitHub Actions, scripts and hooks that run now and then. Each CLI call starts a new process and opens a new
connection, which adds a few hundred milliseconds, so it doesn't suit decisions a person or a loop is waiting on.
s1flow has no server of its own; to serve decisions over HTTP, wrap policy.decide in your web framework.
Errors¶
If a provider returns an invalid response, s1flow raises ProviderError instead of returning a decision. A
refused question comes back as Refusal from the Client and as Rejected when a policy runs. Configuration
errors, bad input and unsupported features each raise their own subclass of S1flowError.
Time limit¶
A provider that throttles (429), fails on the server or times out is retried, up to four attempts with waits of 0.5, 1 and 2 seconds, and each attempt can take up to 60 seconds. Without a limit, one decision can therefore take minutes. When a person is waiting on the answer, give the decision a limit in seconds:
from s1flow import ProviderError
try:
decision = policy.decide(state, case_id="ticket-42", timeout=1.5)
except ProviderError:
... # no decision in time, or the call failed: send the case to a person or a fallback
The limit covers the whole call, retries and waits included. When it passes, s1flow cancels the call and raises
TimedOut, a ProviderError, so code that already falls back on a failed call also falls back on a late one.
The log records it as failed with the error TimedOut: ..., apart from other failures. adecide takes the same
timeout. Without one, a decision takes as long as its retries do.
Images, audio, video, PDFs and logged input¶
Media must be passed as values your code prepares before the policy runs: media.prepare("audio", data) (or
"image", "video", "pdf") as top-level items of a list state. Input JSON can't make the runtime fetch files or
URLs. On the CLI, --image, --audio, --video and --pdf PATH load a local file you name; images need
s1flow[images]. Audio is WAV or MP3, video MP4, sent as the file's own bytes; images are resized and re-encoded.
Input is logged only if you ask for it (keep_state=True or --keep-state).
Call a model directly¶
Use Client or AsyncClient when you don't need a saved policy or a threshold. You still don't need an
evaluation.
from s1flow import Client
from s1flow.client import ModelSpec
from s1flow.questions import Boolean
response = Client().responses.create(
model=ModelSpec(provider="typesafe", id="jev-1.14.0"),
state={"text": "Crash on startup"},
questions={"bug": Boolean(instructions="Does this report describe a software defect?")},
)
print(response.answers["bug"].probability)
The ModelSpec here is written in your own code, so this example needs no connection file. From the shell, s1flow decide --model
liquid:d1.2 --state '"Crash on startup"' --boolean "Does this report describe a software defect?" does the same
with no project: provider:id names a built-in provider and the id it sends. If you refer to
the model by an alias instead, pass the app's list of allowed models:
response = Client(connections="connections.toml").responses.create(
model="triage",
state={"text": "Crash on startup"},
questions={"bug": Boolean(instructions="Does this report describe a software defect?")},
)
The Client supports yes/no (boolean), choice, score and box questions, and several questions in one request, as far as
the provider supports them. Evaluation compares all four. A policy holds one question of any of these types.
It also asks for a value read from the state (Text, Number, Date) or a number the state does not state
(RangeEstimate, between a min and a max), where a model answers them: Liquid's d1.2 and d1.2-ultra take all four on Liquid's own API, in the same call as other questions; through OpenRouter, Clairic takes all four,
Schematron text, numbers and dates, Perplexity's Decider v1.3 and ScaleDown Extract text. A read answer's value
is None when the model found nothing; p_null, confidence and span come with it when the model gives them. An
estimate comes with p10 and p90. A span counts characters in the text sent (Liquid's is kept for a text state only): for a JSON state, the state with its
keys sorted, dumped with an indent of 1. Some models read the question's name as well as its instructions, so name
it for what it reads (order_number, not q). OpenRouter serves these on another route, so one request asks either
these or the other four types. Evaluation compares them too (evaluate.md), and a policy holds one like any other type.
A box answer's box is None when the model says the target is not in the picture, with found (the probability
that it is there) where the model gives one: Liquid's d1.2 does. A model that always gives a box (jev) cannot say so.
A box policy's decision is then None, and feedback record ... false labels a case with no target.
Boxes asks for a box for every instance of the target, none when there is none: the answer's boxes, each with
its confidence and found, at_least when the model stopped at the question's max, and the presence of each
slot. Liquid's d1.2 and d1.2-ultra answer it; evaluation compares it, and a policy holds one
(feedback record takes its boxes as JSON, none for none).
MultiChoice asks for every option that applies, possibly none: the answer's choices, with each option's own
probability in probabilities (they do not sum to 1). Liquid's d1.2 and d1.2-ultra answer it; evaluation compares it,
and a policy holds one (feedback record ... late,damage, or none).
Every call sends the state with the keys of each JSON object in sorted order, so a case in an evaluation and a call in production that differ only in key order send the same request. Lists keep their order.