Route support tickets
Produce a queue, review decision and priority from a customer message.
An incoming support ticket needs a processing queue. The input is the original notebook's fictional delivery-address message; the output is a ticket ID, intent queue, address-change probability, explicitness score (0β2), and review priority. The program only proposes a queue: it does not modify an order.
How it worksβ
Ask all three questions about the same input. A choice needs selected probability β₯ 0.8 and a top-two gap β₯ 0.2 to route automatically. A predicted address change also needs its independent predicate probability β₯ 0.8; disagreement goes to human_review. Rank review work by address_change_probability Γ explicitness_score / 2. A score near 2 indicates a more explicit request, not a 100% likelihood of successful fulfillment.
These thresholds illustrate a workflow. They are not calibrated accuracy guarantees. Measure false routing costs on your own labeled tickets and tune thresholds before operational use. Ambiguous, novel and low-confidence messages remain reviewable.
The sample input, from samples.json:
{
"id": "ticket-001",
"text": "I moved. Can you ship my order to 12 Elm Street instead of the old address?",
"questions": [
{
"name": "intent",
"type": "choice",
"instructions": "Which intent does the user's message express?",
"choices": [
{
"value": "billing_question",
"description": "Asks about a charge, invoice or payment"
},
{
"value": "cancel_order",
"description": "Wants to cancel an order"
},
{
"value": "change_address",
"description": "Wants to change the delivery address"
},
{
"value": "report_damage",
"description": "Received an item that is broken or damaged"
},
{
"value": "track_order",
"description": "Wants to know where an order is or when it arrives"
}
]
},
{
"name": "address_change",
"type": "predicate",
"instructions": "The user requests a delivery address change."
},
{
"name": "explicitness",
"type": "score",
"instructions": "How explicit is the request to change the delivery address?",
"levels": [
{
"label": "none",
"description": "No request"
},
{
"label": "possible",
"description": "Asks whether a change is possible"
},
{
"label": "explicit",
"description": "Explicitly requests a change"
}
]
}
]
}
Run itβ
Python 3.11+ and curl. No API key is needed: the recorded answers in caches/ticket_routing.json let the script run offline.
Download the bundleβ
- uv
- pip
curl -fLO https://valen-team.github.io/cookbook/valen-cookbook.zip
python -m zipfile -e valen-cookbook.zip .
cd valen-cookbook
uv venv --python 3.11
source .venv/bin/activate
uv pip install -r requirements.txt
curl -fLO https://valen-team.github.io/cookbook/valen-cookbook.zip
python -m zipfile -e valen-cookbook.zip .
cd valen-cookbook
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
Run with the recorded answersβ
python ticket_routing.py --asset-dir . --output result.json
This prints the same answers as the recorded run in Output.
Call the modelβ
--replay off calls the free hosted API instead of the recorded answers; the last command uses an existing local HTTP deployment:
python ticket_routing.py --replay off --model valen-2b --asset-dir . --output result.json
# An existing local HTTP deployment instead:
python ticket_routing.py --replay off --base-url http://127.0.0.1:8000/v1 --model valen --asset-dir . --output result.json
Codeβ
"""Turn an incoming ticket into a queue and a review priority. Apache-2.0."""
from common import choice_status, client, emit, parser, request, samples
def run(predict, sample):
answers = request(predict, sample["text"], sample["questions"])
intent = answers["intent"]
confidence, certain = choice_status(intent)
probability = answers["address_change"]["probability"]
explicitness = answers["explicitness"]["score"]
# These are illustrative workflow thresholds, not calibrated accuracy claims.
route = intent["choice"] if certain else "human_review"
if route == "change_address" and probability < 0.8:
route = "human_review"
return {"ticket_id": sample["id"], "queue": route, "confidence": confidence,
"address_change_probability": probability, "explicitness_score": explicitness,
"review_priority": round(probability * explicitness / 2, 6),
"action": "review_request_before_changing_order", "answers": list(answers.values())}
def main():
args = parser(__doc__).parse_args()
with client(args) as predict:
emit(run(predict, samples()["ticket"]), args)
if __name__ == "__main__":
main()
The shared runner and samples.json are included in the download bundle, from the same maintained source as this page.
common.py
"""Shared cookbook runner. Apache-2.0. No implicit model or media downloads."""
import argparse
import base64
from contextlib import ExitStack, contextmanager
import datetime
import hashlib
import json
import math
import os
from pathlib import Path
import sys
HERE = Path(__file__).resolve().parent
CACHES = HERE / "caches"
def samples():
return json.loads((HERE / "samples.json").read_text())
def parser(description):
p = argparse.ArgumentParser(description=description)
p.add_argument("--backend", choices=["remote", "onnx", "native"], default="remote")
p.add_argument("--base-url", default=os.environ.get("VALEN_BASE_URL", "https://api.valen-team.workers.dev/v1"))
p.add_argument("--model", default=os.environ.get("VALEN_MODEL"))
p.add_argument("--threads", type=int, default=4)
p.add_argument("--asset-dir", type=Path, default=Path("."))
p.add_argument("--output", type=Path)
p.add_argument("--replay", choices=["auto", "only", "off"], default="auto",
help="auto: reuse recorded answers and record new ones; only: recorded answers only; "
"off: always call the model")
return p
@contextmanager
def client(args):
"""Answers for remote requests are recorded in caches/<script>.json, keyed by model and request."""
mode = getattr(args, "replay", "off") if args.backend == "remote" else "off"
if mode == "off":
with live_client(args) as predict:
yield predict
return
with recorded(lambda: live_client(args), mode, args.model or "valen-2b", args.base_url) as predict:
yield predict
@contextmanager
def recorded(open_live, mode, model, base_url):
"""Replay answers from caches/<script>.json; record new ones with the model's revision and date under _meta[model]."""
path = CACHES / (Path(sys.argv[0]).stem + ".json")
store = json.loads(path.read_text()) if path.exists() else {}
with ExitStack() as stack:
live, shown = [], []
def predict(body):
key = hashlib.sha256(json.dumps({"model": model, **pixels(body)}, sort_keys=True,
ensure_ascii=False).encode()).hexdigest()
if key in store:
if not shown:
shown.append(True)
meta = store["_meta"][model]
print(f"Replaying caches/{path.name}: {meta['model']} ({meta['model_id']}, revision {meta['revision']}) "
f"from {meta['base_url']}, recorded {meta['recorded']}. Use --replay off to call the model.",
file=sys.stderr)
return store[key]
if mode == "only":
raise KeyError(f"No recorded answer in caches/{path.name}; run with --replay auto to call the model")
if not live:
live.append(stack.enter_context(open_live()))
response = store[key] = live[0](body)
store.setdefault("_meta", {})[model] = {"model": response.get("model"), "model_id": response.get("model_id"),
"revision": response.get("revision"), "base_url": base_url,
"recorded": datetime.date.today().isoformat()}
CACHES.mkdir(exist_ok=True)
path.write_text(json.dumps(store, indent=1, sort_keys=True, ensure_ascii=False) + "\n")
return response
yield predict
def pixels(value):
"""Key images by their decoded pixels, so another zlib or Pillow build finds the same recorded answer."""
if isinstance(value, dict):
return {k: pixels(v) for k, v in value.items()}
if isinstance(value, list):
return [pixels(v) for v in value]
if isinstance(value, str) and value.startswith("data:image/"):
import io
from PIL import Image
with Image.open(io.BytesIO(base64.b64decode(value.split(",", 1)[1]))) as image:
return f"image {image.size} " + hashlib.sha256(image.convert("RGB").tobytes()).hexdigest()
return value
@contextmanager
def live_client(args):
if args.threads < 1:
raise ValueError("--threads must be positive")
if args.backend == "native":
if not args.model or not Path(args.model).is_dir():
raise ValueError("native requires --model pointing to an existing local Valen model directory")
import torch
from transformers import AutoModel, AutoProcessor
torch.set_num_threads(args.threads)
model = AutoModel.from_pretrained(args.model, trust_remote_code=True, local_files_only=True,
dtype=torch.float32, attn_implementation="eager").float().cpu().eval()
model.backbone_autocast_dtype = None
processor = AutoProcessor.from_pretrained(args.model, trust_remote_code=True, local_files_only=True)
def predict(body):
with torch.inference_mode():
return model.predict(body, processor=processor, execution="shared_state",
temperature=body.get("temperature", 1.0))
yield predict
else:
from valen_sdk import Valen
if args.backend == "onnx":
if not args.model or not Path(args.model).is_dir():
raise ValueError("onnx requires --model pointing to an existing local ONNX bundle")
instance = Valen.local(args.model, variant="fp32", local_files_only=True, num_threads=args.threads)
else:
instance = Valen.remote(args.base_url, model=args.model or "valen-2b",
api_key=os.environ.get("VALEN_API_KEY"), max_retries=0)
with instance:
yield instance.predict
def image_input(payload):
"""Inline media works across HTTP services; never send a client-local path."""
return [{"role": "user", "content": [
{"type": "input_text", "text": "Answer using only the visible image."},
{"type": "input_image", "image_url": "data:image/png;base64," + base64.b64encode(payload).decode("ascii")},
]}]
def png(image):
"""Lossless 512px PNG: the pixels sent are exactly the pixels decoded, on any machine."""
import io
from PIL import ImageOps
image = ImageOps.exif_transpose(image).convert("RGB")
image.thumbnail((512, 512))
buffer = io.BytesIO()
image.save(buffer, format="PNG")
return buffer.getvalue()
def image_bytes(path):
from PIL import Image
with Image.open(path) as image:
return png(image)
def frame_image(frame):
"""RGB from the decoded YUV planes, converted by Pillow: H.264 decoding is bit-exact, ffmpeg's RGB conversion is not."""
from PIL import Image
if frame.format.name != "yuv420p":
frame = frame.reformat(format="yuv420p")
y, u, v = (Image.frombuffer("L", (plane.width, plane.height), bytes(plane), "raw", "L", plane.line_size, 1)
for plane in frame.planes)
# Video stores limited range (16-235 luma, 16-240 chroma); Pillow's YCbCr expects full range.
y = y.point(lambda x: min(255, max(0, round((x - 16) * 255 / 219))))
u, v = (c.point(lambda x: min(255, max(0, round((x - 128) * 255 / 224 + 128)))).resize(y.size, Image.BILINEAR)
for c in (u, v))
return Image.merge("YCbCr", (y, u, v)).convert("RGB")
def middle_frame(path):
"""Decode a bounded clip twice: count first, then keep only its middle frame."""
import av
with av.open(str(path)) as video:
stream = video.streams.video[0]
if stream.width * stream.height > 4096 * 2160:
raise ValueError("Clip exceeds the cookbook's 4K frame limit")
count = 0
for _ in video.decode(video=0):
count += 1
if count > 1800:
raise ValueError("Clip exceeds the cookbook's 1800-frame limit")
if not count:
raise ValueError("Clip contains no decodable frames")
target = count // 2
with av.open(str(path)) as video:
for index, frame in enumerate(video.decode(video=0)):
if index == target:
return png(frame_image(frame)), {"frame_index": target, "total_frames": count,
"timestamp_seconds": float(frame.time) if frame.time is not None else None}
raise ValueError("Clip changed while decoding")
def request(predict, source, questions):
response = predict({"input": source, "questions": questions, "temperature": 1.0})
answers = response["answers"]
if [a["name"] for a in answers] != [q["name"] for q in questions]:
raise ValueError("Service returned missing or reordered answers")
return {a["name"]: a for a in answers}
def choice_status(answer, *, threshold=0.8, margin=0.2):
probabilities = [float(x["probability"]) for x in answer["probabilities"]]
if (not probabilities or any(not math.isfinite(x) or not 0 <= x <= 1 for x in probabilities)
or abs(sum(probabilities) - 1) > 1e-4):
raise ValueError("Invalid choice probability distribution")
selected = next(x for x in answer["probabilities"]
if type(x["value"]) is type(answer["choice"]) and x["value"] == answer["choice"])
ordered = sorted(probabilities, reverse=True)
confidence = float(selected["probability"])
gap = ordered[0] - (ordered[1] if len(ordered) > 1 else 0)
return confidence, confidence >= threshold and gap >= margin
def emit(value, args):
text = json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
if args.output:
args.output.write_text(text)
print(text, end="")
Outputβ
Real-model verification: 2026-11-10 Β· Valen-Decision-1.5-2B Β· SDK 0.2.0 Β· Valen hosted API (api.valen-team.workers.dev), answers recorded in caches/ticket_routing.json.
Source model revision: hosted valen-2b. Machine-readable results
{
"ticket_id": "ticket-001",
"queue": "change_address",
"confidence": 0.9998090381762026,
"address_change_probability": 0.9989510209459393,
"explicitness_score": 1.955565405501435,
"review_priority": 0.976757,
"action": "review_request_before_changing_order",
"answers": [
{
"type": "choice",
"name": "intent",
"choice": "change_address",
"probabilities": [
{
"value": "billing_question",
"probability": 0.0000029615462656269814
},
{
"value": "cancel_order",
"probability": 0.00011410188981165587
},
{
"value": "change_address",
"probability": 0.9998090381762026
},
{
"value": "report_damage",
"probability": 0.000009486926433594504
},
{
"value": "track_order",
"probability": 0.00006441146128656554
}
],
"confidence": 0.9997612977202532
},
{
"type": "predicate",
"name": "address_change",
"probability": 0.9989510209459393
},
{
"type": "score",
"name": "explicitness",
"score": 1.955565405501435,
"probabilities": [
{
"value": 0,
"label": "none",
"probability": 0.003707516304216059
},
{
"value": 1,
"label": "possible",
"probability": 0.03701956189013287
},
{
"value": 2,
"label": "explicit",
"probability": 0.9592729218056512
}
],
"confidence": 0.9333481082521525
}
]
}
Results belong to the recorded model and backend; they do not imply identical versions, scores or speed on the default public service. Policy unit tests use constructed answers. Real-model execution is recorded separately and is not replaced by those tests.
Make it yoursβ
- For direct ONNX execution, use
--backend onnx --model /path/to/Valen-Decision-1.5-0.8B-ONNXand first installvalen-sdk[onnx,video]==0.5.0. Connect a GGUF service through--backend remote; a GGUF file is not aValen.localmodel. - To choose a routing threshold using your own labeled data, continue with calibrated ticket routing.
- Could the correct category be missing? See handling unknown categories to compare explicit none choices and review thresholds.
Sources, licensing and related documentationβ
Code and authored JSON text samples use Apache-2.0. The ticket is fictional. sheep.jpg and momos.mp4 are evaluation cases from VisualDecisionBench. sheep.jpg is a COCO image from the A-OKVQA validation set (visualdecisionbench_image:000196); momos.mp4 is YouTube video HlDfIuavPjg from LLaVA-Video-178K (visualdecisionbench_video:000110). They keep their upstream terms: COCO images follow the Flickr terms of their owners, and the clip follows YouTube's terms. The Apache-2.0 code licence covers the code and text samples.
Decisions API Β· SystemOne API Β· ONNX / SDK Β· Native deployment Β· GGUF deployment Β· Evaluation Β· Validation and performance