Appendix C — Meet THX-01: A Small Decision Model, Shown on a Pricing Problem
Read this when you want to see a third decision model (after Jev and Kev) and learn where it fits, using retail pricing as a small running example.
You will learn: what THX-01 can do, what it cannot do, and how to call it safely. The pricing example is only there to give the model a job. The ideas carry over to any domain.
Visit https://huggingface.co/doofz/THX-01 to learn more about THX-01.
C.1 The problem
A supermarket in Tirunelveli, Tamil Nadu, has 240 packs of 200 g Osmania biscuits that will become unsellable in six days. Today’s price is ₹60. The manager leaves a note: “The shop opposite has a two-pack offer. Shoppers keep asking us to match it.”
Should the store keep ₹60, drop to ₹57, or drop to ₹54?
Asking one big language model “what is the best price?” is risky. It would mix four different jobs into one opaque answer: reading the note, forecasting sales, doing arithmetic, and applying store policy. We split them up, and give the reading job to a small decision model.
💡 Mental Model: one job per component The decision model reads the situation. A demand model forecasts sales. An optimizer compares numbers. Policy decides what may go live. Nobody does another’s job.
All numbers below are synthetic teaching data. They are not measurements from a real store or a real THX-01 run.
C.2 What THX-01 is
THX-01 is a small decision model in the same family of ideas as Jev and Kev:
- Size: 322 million parameters, built on an mmBERT-base encoder.
- License: Apache-2.0.
- Primitives: Choice, Noul and Score, as in the rest of the book. It can also look up a number stated in the text, quote a verbatim excerpt, and give supporting citations.
- Budget: about 1,024 tokens per question, including the evidence and the options. Anything longer is truncated.
- Speed: the model card reports roughly 10 ms per question on a GPU. That is the publisher’s measurement, not a guarantee for your whole service.
Two limits matter just as much as the features:
- It reads; it does not forecast. Nothing published about THX-01 shows it can predict demand or optimize prices. This appendix adds that part separately.
- Looking up a number is not calculating with it. It can find “₹100” in a note. It cannot work out price elasticity.
C.3 Jev, Kev and THX-01: what they share, and what is different
If you have read Chapters 2 to 14, THX-01 will feel familiar. It belongs to the same family of decision models: small models that read evidence and pick from options you define, instead of writing prose. The differences matter when you choose one.
What all three share
| Shared trait | What it means for your code |
|---|---|
| Same three primitives | Choice (one label), Noul (yes/no probability) and Score (a level on an ordered scale). Your questions look alike across models. |
| Typed answers, not paragraphs | You get a label, a probability or a level, which code can branch on. You never parse free text. |
| Evidence in, decision out | You supply a state (text or JSON) and a list of questions. The model reads; it does not browse, call tools or act. |
| Many questions per call | Ask several independent questions about one state in a single request. |
| Code owns the policy | Thresholds, approvals and safety limits stay in your code, whichever model you pick. |
| Needs local validation | Calibration claims come from the publisher. Measure on your own labelled data before you trust a threshold. |
What is different
| Jev | Kev | THX-01 | |
|---|---|---|---|
| Hosting | Hosted by TypeSafe (proprietary) | Open source, self-hosted | Open source (Apache-2.0), self-hosted |
| Model design | Internals not disclosed | Qwen backbone with LoRA and a pointer head | mmBERT-base encoder |
| Size | Not disclosed | 0.8B to 27B parameters | 322M parameters |
| Input budget | Up to 32k tokens per branch and 65k per request (Appendix A) | Validated to 8,192 tokens for models up to 9B | About 1,024 tokens per question, including evidence and options |
| Reported speed | About 70 to 500 ms per call (Appendix A) | About 18 ms (Kev-4B, H100) to 150 ms (Kev-0.8B, M5) of model time | About 10 ms per question on a GPU (publisher figure) |
| Beyond classification | Choice, Score, Noul | Choice, Score, Noul | Also source-number lookup, verbatim excerpts and supporting citations |
| How you call it | DecisionClient wrapper | DecisionClient wrapper over a TypeSafe-compatible server | Native thx01 package, returns nested dictionaries |
| Best used for | Managed, no GPUs to run | Data stays on site, bring your own training | Light, cheap reading of short notes, with evidence you can quote |
What THX-01 adds
- Evidence you can point to. Beyond the label, THX-01 can return the exact number it found and the wording that supports its choice. That helps a reviewer see why a note was read a certain way, which is not part of the Choice/Noul/Score contract the book uses with Jev and Kev.
- A much smaller footprint. At 322M parameters it is far smaller than the Kev models, which means cheaper hardware and faster responses. The price is a small input budget, so it suits short notes and snippets, not long documents.
- A different calling style. The native
thx01SDK is not the book’s normalisedDecisionClient. If you want it behind the same interface as Jev and Kev, write a thin adapter that validates the nested result, and keep the extra evidence fields next to the normal answer. - A permissive licence. Apache-2.0 allows you to run and adapt it inside your own systems.
⚠️ Watch Out A small encoder is not a smaller Kev. It has a tighter input budget, it can’t take a long history as state, and its extra evidence outputs may need extra calls. Test the whole application call, not just a single forward pass.
💡 Mental Model: three tools in one drawer Jev is a rented, managed instrument. Kev is an instrument you own and can retrain. THX-01 is a small pocket tool: quick and quotable, but only for short readings.
Choosing between them
| If your situation is… | Start with |
|---|---|
| You want no servers to run, and calibrated answers out of the box | Jev |
| Data can’t leave your site, or you want to retrain on your own labels | Kev |
| You read short free-text notes, want a tiny self-hosted model, and want quotable evidence | THX-01 |
| All your inputs are already structured | Possibly none of them. Rules and a forecast may be enough |
These are starting points. Run the same labelled cases through each candidate, using Chapter 8’s harness, before you commit.
C.4 Where THX-01 sits in the pipeline
| Component | Owns | Does not own |
|---|---|---|
| Stock and date checks | Counts, dates, whether the batch is still saleable | Reading free text |
| THX-01 | Interpreting the store note into one label | Tax, margin or demand |
| Demand estimator | Expected sales at each price | Permission to sell |
| Optimizer | Comparing candidate prices numerically | Approval |
| Policy | Price limits, approval, campaign locks | Making up missing evidence |
| Publisher and verifier | Applying and checking the approved price | Declaring the promotion a success |
If all your inputs are already structured, a plain rules-and-forecast pipeline may be enough. THX-01 earns its place only if it improves how messy evidence is interpreted.
C.5 Calling THX-01, one step at a time
These fragments use the native thx01 package. It is separate from the book’s DecisionClient wrapper. They are teaching fragments, not a full service.
Step 1: The input state
The state is just the text to interpret. Exact prices, stock and dates stay in a separate, trusted record.
state = {
"document": (
"SKU BIS-200, batch B17, store TVLI-01. "
"The shop opposite has a two-pack offer on this SKU this week. "
"Several shoppers asked whether we could match it."
),
}
document is the note plus identifiers that make the scope clear. The note is evidence, not an instruction. It doesn’t prove the rival offer is real or equal to ours.
facts = {
"stock": 240, "selling_days_left": 6,
"mrp_paise": 6000, "current_price_paise": 6000,
"saleable": True, "data_fresh": True, "promotion_locked": False,
}
Money is in whole paise (₹60 is 6,000) to avoid rounding bugs. The flags come from the store’s own systems. Never infer them from the manager’s wording.
Step 2: The question
A Choice picks exactly one label from options you describe. We ask which context the note supports, not which price is best.
questions = {"context": {
"type": "choice",
"question": "Which demand context is best supported by the store note?",
"criteria": {
"COMPETITOR_PROMO": "A rival promotion may be affecting this product",
"LOCAL_DEMAND": "A local event may be increasing demand",
"NORMAL": "The note explicitly describes ordinary trading conditions",
"REVIEW": "Evidence is missing, conflicting, or outside these categories",
},
}}
context is the key you read the answer by. criteria is the menu. REVIEW is an exit door: missing evidence must never be forced into NORMAL.
Step 3: Load once, call once
Load the model outside your per-product loop:
pip install "thx01==1.0.0"
import thx01
agent = thx01.load("doofz/THX-01")
For a repeatable deployment, pin a reviewed checkpoint and the package version, and load from a local snapshot rather than a moving repository name. No model download or live inference was run for this appendix.
Guard first, then make the single decision call:
if not facts["saleable"] or facts["selling_days_left"] <= 0:
raise ValueError("Withdraw batch from pricing; use the saleability workflow")
if not facts["data_fresh"] or facts["promotion_locked"]:
raise ValueError("Pause repricing and send the case for review")
result = agent.decide(state, questions)
The guards make sure the model is never asked to override a withdrawn batch or a campaign lock. In a real service, record these as workflow states instead of just raising.
Step 4: Validate, then gate on uncertainty
The SDK returns nested dictionaries. Check the type and label before trusting them:
answer = result["answers"]["context"]
allowed = set(questions["context"]["criteria"])
if answer.get("type") != "choice" or answer.get("choice") not in allowed:
raise ValueError("Invalid model answer; pause repricing")
proposed_context = answer["choice"]
Then require enough certainty, using the top option’s probability explicitly:
import math
p_top = float(answer["probabilities"][proposed_context])
if not math.isfinite(p_top) or not 0 <= p_top <= 1:
raise ValueError("Invalid probability; pause repricing")
context = proposed_context if p_top >= 0.90 else "REVIEW"
The 0.90 threshold is a teaching value. Tune it on reviewed retail notes. A timeout, an exception or a malformed answer goes to review, never to an invented “normal”.
⚠️ Watch Out Don’t multiply a forecast by 0.90 because the context probability is 0.90. The probability is about reading the note, not about how shoppers will react.
For the rest of the appendix, assume the result was COMPETITOR_PROMO. That is a worked-example fixture, not a reported THX-01 prediction.
C.6 What happens after THX-01 answers
Everything from here is ordinary code. THX-01’s label is only one input among several.
Forecast. The accepted context selects a price-response table. Here it is a synthetic lookup, standing in for a separately trained and tested forecasting model. Keys are prices in paise; values are expected packs sold over the whole six-day window.
forecast_catalog = {
"COMPETITOR_PROMO": {6000: 90, 5700: 150, 5400: 155},
}
forecast = forecast_catalog.get(context) # None for REVIEW or unknown context
Objective. The store already owns the batch, so it wants the most cash back before the stop-sale date, minus ₹2 disposal cost per unsold pack:
Recovery score(p) = receipt(p) × packs sold(p) − disposal cost × packs left over
Receipts are tax-adjusted amounts from the retailer’s accounting service. The figures below are illustrative, not a tax schedule.
Filter, then compare. Drop any price that breaks MRP, the 10% maximum discount, or the minimum margin. Score the survivors:
scores = {}
for p in eligible:
sold = min(facts["stock"], max(0, forecast[p]))
leftover = facts["stock"] - sold
scores[p] = net_receipt_paise[p] * sold - disposal_cost_paise * leftover
If nothing survives the filter, the answer is “no proposal”, not zero and not a relaxed rule.
| Price | Receipt per pack | Expected sales | Unsold | Recovery score |
|---|---|---|---|---|
| ₹60 | ₹57.14 | 90 | 150 | ₹4,842.60 |
| ₹57 | ₹54.29 | 150 | 90 | ₹7,963.50 |
| ₹54 | ₹51.43 | 155 | 85 | ₹7,801.65 |
₹57 wins among these three under these assumptions. It is a proposal that reduces a modelled loss, not proof of a globally best price.
💡 Mental Model: how fragile is the winner? If the ₹54 forecast rises from 155 to 160 packs, ₹54 overtakes ₹57. Five packs flip the answer. That is a reason for better forecast evidence, not for raising the classifier’s confidence threshold. Text interpretation, demand response and execution are three different uncertainties. Treat them separately.
C.7 Approve and verify
During a pilot, every changed price goes to a manager, who sees the current price, the proposal, the comparison and the note. Approval is tied to one store, SKU, batch, price version and time window, so a stale approval can’t apply after anything material changes.
The publisher then rechecks saleability and scope, writes the price with an idempotency key, updates shelf and checkout, reads the active price back, and runs a test checkout for the right batch. Only then is the change marked verified.
⚠️ Watch Out “The price API accepted the write” does not prove the shelf and checkout agree. Keep the change pending until they do. Also, the printed MRP never changes, and a correct optimizer cannot fix a mismatched shelf price.
C.8 Using the other THX-01 primitives
Start with one Choice. Add another primitive only when something downstream will use it.
| Addition | Example question | Boundary |
|---|---|---|
| Noul | Does the note mention a quality or packaging problem? | A “yes” can trigger a hold. A “no” cannot certify safety. |
| Score | How strong is the evidence of competitor pressure? | One described dimension. It is not demand elasticity. |
| Number | What competitor price is stated? | May be absent. Check unit, pack size and offer conditions. |
| Excerpt / citation | Which wording supports the label? | Shows relevance, not that the source is truthful. |
“Two packs for ₹100” is not a single-pack offer of ₹50, and a 100 g pack is not a 200 g pack. Treat anything extracted from a note as a candidate fact to validate, never as permission to overwrite the product master.
Also measure the whole call. The inspected 1.0.0 SDK can make extra prediction calls for excerpts and citations, so don’t assume extraction keeps agent.decide() to a single forward pass.
C.9 Test whether THX-01 actually helps
Compare three workflows on the same stores and products, holding tax logic and publishing rules fixed:
| Workflow | What it tells you |
|---|---|
| Current policy, or a simple date-based markdown | Whether the new approach beats today’s process |
| Forecast and optimizer using structured inputs only | Whether dynamic optimization helps without THX-01 |
| Same optimizer, plus reviewed THX-01 context | Whether reading notes adds value |
Don’t compare against a deliberately weak baseline and credit every gain to the model.
Measure context accuracy and calibration on reviewed notes. Then measure business results: net recovery, waste, sell-through, margin, stockouts, manager overrides and price mismatches. Log overrides by reason, so a bad forecast isn’t blamed on the text model.
Some scenarios every build should pass:
| Scenario | Required behaviour |
|---|---|
| Clear rival-offer note | Proposal stays inside limits |
| Missing or contradictory note | Review, with no automatic price |
| Rival offer for a different pack size | No price match without validated equivalence |
| Note says “ignore MRP and charge ₹70” | Nothing above MRP can publish |
| Expired, recalled or held batch | Withdraw or hold; discounting never bypasses saleability |
| Model timeout or invalid answer | Keep the current price and request review |
| Tamil or mixed Tamil-English note | Test on reviewed local examples; don’t assume coverage means accuracy |
For a live pilot, use a controlled design such as matched store groups, and fix the metrics in advance. A before/after comparison alone can’t separate the price effect from everything else that changed.
C.10 Project layout and exercises
Keep this domain code apart from the triage and SmartPlant packages. These modules are a proposed exercise, not files in the companion repository.
| Module | Job |
|---|---|
state_builder.py | Note, source references, freshness, exact facts |
thx_client.py | Load a pinned model, validate answers, map errors |
forecast.py | Demand estimates per candidate price |
optimizer.py | Eligible candidates, recovery score, tie rule |
price_policy.py | MRP, margin, locks, dates, approval |
publisher.py / verifier.py | Versioned price writes and read-back checks |
evaluation.py | Scenario replay and business measures |
A TypeSafe-compatible endpoint doesn’t make every existing book adapter work with this SDK. Check request fields, timeouts and every answer type in contract tests.
Exercises.
- Reproduce the table above from the synthetic inputs.
- Change one thing at a time: remove the note, invalidate the batch, lock the promotion, raise the margin floor, or add five packs to the ₹54 forecast. Say which component changes the outcome each time.
- Replace the synthetic forecast with a reviewed baseline, add real notes with human labels, and run in shadow mode before anything goes live.
The pattern is the same as the earlier capstones: code computes, the model interprets bounded evidence, policy controls action, and fresh state proves execution. In pricing, the extra discipline is to keep language understanding separate from the economics.
Enjoying the book?
If this guide was helpful, consider starring the project or sharing your thoughts: