Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
AI Tools
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Course
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM Tools
Machine Learning
Machine Learning & AI
Machine Learning Tools
Manage Data
MLOps
Natural Language Processing
Newsletter Archive
NumPy
Pandas
Polars
PySpark
Python Helpers
Python Tips
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

python

Auto-created tag for python

TypeSafe Jev vs RapidFuzz vs Sentence Transformers for Duplicate Records

Table of Contents

Introduction
Setup
Match Names That Look Alike with RapidFuzz
Match Meaning with Sentence Transformers
Ask Jev Which Product Is the Same
Combine Sentence Transformers and Jev
Which Approach Should You Use?

Introduction
In a previous article, I compared four text similarity tools, from regex to Sentence Transformers. Fuzzy matching handled typos and word order, and embeddings handled different words with the same meaning:
Jon Smith John Smith <- typo, fuzzy matching catches it
NYC New York City <- abbreviation, embeddings catch it

One case none of them handled well is two records that describe the same product in different words:
Haier 13' Silver Tube TV – HTR13
13in Crt Tv W/atsc Tuner – HTR13 <- same model (HTR13), different words

An LLM could decide what makes two products the same, for example with PydanticAI forcing a yes or no answer, but running one on every product would be slow and expensive. TypeSafe Jev is a cheaper option: it picks from fixed answers instead of writing a reply, and you can still give it your own rules.
This article tests whether Jev can catch the mistakes RapidFuzz and Sentence Transformers make, and what it costs to run.

💻 Get the Code: The full script and setup are in the GitHub companion folder.

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

Setup
Install the libraries:
pip install rapidfuzz sentence-transformers typesafe-sdk pandas python-dotenv

This article uses rapidfuzz v3.14.6, sentence-transformers v5.6.0, typesafe-sdk v0.7.5, and pandas v2.3.3.
The Abt-Buy benchmark has two product lists, 1,081 products from Abt (the first list) and 1,092 from Buy.com (the second list), plus a file of the 1,097 known matches. I use it to count each tool’s correct and wrong merges.
first list (1,081) second list (1,092)
Samsung … SBH500 ────── Samsung SBH500 …
Sony … CDPCX455 ────── Sony CDP-CX455 …
… Sony CDP-CX355 …
…

The code below shows only the call that matters for each tool. The data download and the full code are in the companion folder.
Match Names That Look Alike with RapidFuzz
RapidFuzz is a fast fuzzy string matching library. It scores how similar two strings look from 0 to 100.
John Smith vs Smith, John 100 same words
John Smith vs Jon Smith 95 one letter off
John Smith vs Mary Jones 50 different names

Let’s start with an easy case for RapidFuzz: the same product, with the same words in a different order.
First list: Samsung Stereo Bluetooth Headset In Black – SBH500
Right match: Samsung SBH500 Stereo Bluetooth Headset

Ask RapidFuzz for the closest match in the second list:
from rapidfuzz import fuzz, process, utils

def closest_match(product_name: str) -> tuple:
best_name, score, _ = process.extractOne(
product_name,
second_list.name,
scorer=fuzz.token_set_ratio,
processor=utils.default_process, # lowercase and strip punctuation
)
return best_name, score

best_name, score = closest_match("Samsung Stereo Bluetooth Headset In Black – SBH500")
print(f"Closest match: {best_name} (score {score:.1f})")

OutputClosest match: Samsung SBH500 Stereo Bluetooth Headset (score 100.0)

Every word in the second list’s name also appears in the first list’s name, so RapidFuzz gives it a perfect score and finds the right match.
Now try a harder product, where the right match adds many extra words:
First list: GE GSD4000NWW White Built-In Dishwasher – GSD4000WH
Right match: GE GSD4000NWW Dishwasher with 5 Wash Cycles STD TUB ESTAR ( White) – gsd4000nww

They are the same product because both carry the model number GSD4000NWW.
product_name = "GE GSD4000NWW White Built-In Dishwasher – GSD4000WH"
right_match = "GE GSD4000NWW Dishwasher with 5 Wash Cycles STD TUB ESTAR ( White) – gsd4000nww"

best_name, best_score = closest_match(product_name)
right_score = fuzz.token_set_ratio(product_name, right_match, processor=utils.default_process)

print(f"Closest match: {best_name} (score {best_score:.1f})")
print(f"Right match: {right_match} (score {right_score:.1f})")

OutputClosest match: LG Dishwasher (score 87.0)
Right match: GE GSD4000NWW Dishwasher with 5 Wash Cycles STD TUB ESTAR ( White) – gsd4000nww (score 75.9)

The right match shares more words, but it also adds more extra words, so it scores lower.

Merging every product in the first list with its closest match gives these results:

Merged
Correct
Wrong

1,081
740
341

Nearly 1 in 3 merges is wrong.
Match Meaning with Sentence Transformers
Sentence Transformers turns text into a list of numbers, called an embedding, so texts with similar meaning end up with similar numbers. The similarity between two embeddings runs from 0 to 1.
numbers = similarity to "cell phone"

★ cell phone
● mobile phone (0.87)

● laptop (0.44)

● banana (0.31)

Because Sentence Transformers compares meaning instead of letters, it might do better on the dishwasher example that RapidFuzz got wrong:
First list: GE GSD4000NWW White Built-In Dishwasher – GSD4000WH
Right match: GE GSD4000NWW Dishwasher with 5 Wash Cycles STD TUB ESTAR ( White) – gsd4000nww

Ask Sentence Transformers for the closest match:
from sentence_transformers import SentenceTransformer, util

model = SentenceTransformer("all-MiniLM-L6-v2")
second_list_vectors = model.encode([utils.default_process(name) for name in second_list.name])

query = model.encode(utils.default_process("GE GSD4000NWW White Built-In Dishwasher – GSD4000WH"))
best = util.semantic_search(query, second_list_vectors, top_k=1)[0][0]
print(f"Closest match: {second_list.name[best['corpus_id']]} (similarity {best['score']:.2f})")

OutputClosest match: GE GSD4000NWW Dishwasher with 5 Wash Cycles STD TUB ESTAR ( White) – gsd4000nww (similarity 0.83)

As expected, Sentence Transformers finds the right match. This is because it rewards shared details such as the brand, model number, and color. Here is how much each detail adds:
similarity to: GE GSD4000NWW White Built-In Dishwasher

Dishwasher 0.65
+ GE 0.75 +0.10 brand matches
+ GSD4000NWW 0.91 +0.16 model number matches
+ White 0.95 +0.04 color matches

Now let’s try a product where a wrong match shares more words than the right one. I expect Sentence Transformers to pick the wrong one:
First list: Sony 400 Disc MegaStorage CD Changer – CDPCX455
Right match: Sony CDP-CX455 CD Player/Changer – CDPCX455 <- same model number
Wrong match: Sony CDP-CX355 300 Disc MegaStorage CD Changer <- more words in common

Run Sentence Transformers and show its top 2 matches:
query = model.encode(utils.default_process("Sony 400 Disc MegaStorage CD Changer – CDPCX455"))
for hit in util.semantic_search(query, second_list_vectors, top_k=2)[0]:
print(f"{hit['score']:.2f} {second_list.name[hit['corpus_id']]}")

Output0.93 Sony CDP-CX355 300 Disc MegaStorage CD Changer
0.86 Sony CDP-CX455 CD Player/Changer – CDPCX455

As I expected, Sentence Transformers picks the wrong match.
Merging every product in the first list with its closest match gives these results:

Merged
Correct
Wrong

1,081
763
318

Still nearly 1 in 3 merges is wrong, only slightly better than RapidFuzz.
Ask Jev Which Product Is the Same
TypeSafe Jev is a decision model. Instead of generating text, it answers a question with fixed answers and returns the probability of each one.
For example, here is the same question asked to a chat model and to Jev:
review: "Cheaper than the store, though the left earbud crackles."
question: What is this review about? (product quality, price, shipping)

Chat model (Claude Haiku 5.5):
**Product quality.** The review's complaint is that the left earbud
crackles. …

Jev:
product quality 0.79 <- picked
price 0.21
shipping 0.00

Unlike RapidFuzz and Sentence Transformers, Jev:

Follows a rule you give it, so you can specify what “the same product” means in your data
Answers with a probability, so you can match the pairs with high confidence and review the rest
Runs fast and cheap, so checking thousands of pairs is practical

Start with the CD changer that Sentence Transformers got wrong:
First list: Sony 400 Disc MegaStorage CD Changer – CDPCX455
Right match: Sony CDP-CX455 CD Player/Changer – CDPCX455

Let’s give Jev the product and 3 similar names from the second list, plus “none of these”. We will also specify what makes two products the same: the same model number, capacity, and color.
from typesafe_sdk import Choice, TypeSafeClient

client = TypeSafeClient(model="jev-latest")

def ask_jev(product_name: str, shortlist: list) -> dict:
response = client.system_one(
state=product_name,
questions={"match": Choice(
instructions=(
"Which candidate is the same product? Same model, same capacity or size, "
"and same color or variant. Different model numbers mean different products."
),
criteria={name: None for name in shortlist + ["none of these"]},
)},
)
return response.choices["match"].probabilities

cd_changer = ask_jev(
"Sony 400 Disc MegaStorage CD Changer – CDPCX455",
[
"Sony CDP-CX355 300 Disc MegaStorage CD Changer",
"Sony CDP-CX455 CD Player/Changer – CDPCX455",
"Sony CDP-CE375 CD Player/Changer – CDPCE375",
],
)
for name, probability in cd_changer.items():
print(f"{probability:.2f} {name}")

Output0.00 Sony CDP-CX355 300 Disc MegaStorage CD Changer
0.93 Sony CDP-CX455 CD Player/Changer – CDPCX455
0.00 Sony CDP-CE375 CD Player/Changer – CDPCE375
0.07 none of these

Jev gives the right match the highest probability, 0.93. This means it follows the rule we gave it: different model numbers mean different products.
Let’s compare this result with the scores from the other two tools:

Candidate
RapidFuzz
Sentence Transformers
Jev

Sony CDP-CX455 CD Player/Changer (right match)
73.8
0.86
0.93

Sony CDP-CX355 300 Disc MegaStorage CD Changer
94.5
0.93
0.00

Sony CDP-CE375 CD Player/Changer
62.8
0.83
0.00

Only Jev ranks the right match first. It is also confident the other two are wrong.
What does Jev do when none of the choices is the right match? Let’s find out by giving it three wrong candidates:
First list: Sony Stereo Audio Receiver – STRDE197

Candidates: Sony STR-DG720 A/V Receiver – STRDG720 <- not a match
Sony STR-DG920 A/V Receiver – STRDG920 <- not a match
Sony STR-DG820 A/V Receiver – STRDG820 <- not a match

receiver = ask_jev(
"Sony Stereo Audio Receiver – STRDE197",
[
"Sony STR-DG720 A/V Receiver – STRDG720",
"Sony STR-DG920 A/V Receiver – STRDG920",
"Sony STR-DG820 A/V Receiver – STRDG820",
],
)
for name, probability in receiver.items():
print(f"{probability:.2f} {name}")

Output0.00 Sony STR-DG720 A/V Receiver – STRDG720
0.00 Sony STR-DG920 A/V Receiver – STRDG920
0.00 Sony STR-DG820 A/V Receiver – STRDG820
1.00 none of these

Jev picks “none of these”, which is the right answer. RapidFuzz and Sentence Transformers always return a closest name, so they would merge a wrong one.
Combine Sentence Transformers and Jev
We can’t give Jev all 1,092 names from the second list as answers, because a Choice question takes at most 255. So let’s use Sentence Transformers to keep the 3 closest names for each product, and Jev chooses among them.
1,092 names in the second list
│ Sentence Transformers
▼
3 closest names
│ Jev
▼
1 match, or none

Because Jev returns a probability, each product can be merged, left unmatched, or sent to a person to review.
Top answer "none of these"? ── yes ──▶ leave unmatched
│ no
▼
Probability above 0.7? ── yes ──▶ merge
│ no
▼
Probability below 0.3? ── yes ──▶ leave unmatched
│ no
▼
send to a person

Running this on every product in the first list gives these results:

Route
Pairs
Correct
Wrong

Merge (p > 0.7)
808
807
1

Send to a person
62

Leave unmatched
211

Jev merges 808 pairs with only one wrong. The run took about 35 seconds and cost about $0.03 for 1,081 questions. With one wrong merge out of 808, the merges are reliable enough to apply automatically.
Which Approach Should You Use?
Here are the three approaches side by side:

Approach
Merged
Correct
Wrong merges

RapidFuzz
1,081
740
341

Sentence Transformers
1,081
763
318

Top 3 + Jev (p > 0.7)
808
807
1

RapidFuzz and Sentence Transformers are free, but about 1 in 3 of their merges is wrong, so you still have to check every one of them. Jev costs about $0.03 for the whole list and makes only one wrong merge, so you only need to look at the few products it is unsure about. This means you end up saving a lot by spending a little.
So should you always use Jev? No. I recommend starting with the free tools to see how well they work for your data, and moving to more complicated tools only if the current ones are not good enough.
As a rule of thumb:

Use RapidFuzz when names look almost the same but differ in typos, case, punctuation, or word order.
Use Sentence Transformers when names use different words for the same product, and no near-identical products are in the list.
Use Jev when you need rules to decide if two products are the same, such as matching the model number, capacity, or color.

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

Related Tutorials

Structured Output Tools for LLMs Compared: Get fixed, typed answers from a chat model
Auto-Optimize an LLM Classifier with DSPy: Build a classifier from prompts and let DSPy tune them
langextract vs spaCy: AI-powered against rule-based extraction of entities from text

TypeSafe Jev vs RapidFuzz vs Sentence Transformers for Duplicate Records Read More »

What’s New in Polars 2.1: Faster Group-Bys, More SQL, Encrypted Parquet

Table of Contents

Introduction
Run Group-Bys Faster
Run Warehouse SQL Directly
Encrypt Sensitive Columns
Other Additions in 2.1
Final Thoughts

Introduction
Polars 2.0 changed how your existing code behaves. The streaming engine became the default, joins stopped keeping row order, and types got stricter. But it had few new features.
Polars 2.1 came out on October 25, 2026, three weeks later. This time, the release is all about new features.
This article continues the Polars 2.0 post and covers the three new features I find most useful, plus a few smaller ones.

Run group-bys faster and with less memory
Use common SQL functions that Polars SQL didn’t support before
Encrypt sensitive columns in a Parquet file
Smaller additions like full joins in join_where, approx_quantile, and masked NumPy arrays

💻 Get the Code: The scripts are on GitHub.

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

Run Group-Bys Faster
Polars 1.x holds all groups in RAM at once, so a big group-by needs a lot of memory.
Polars 2.1 splits the groups into partitions instead. It keeps one partition in RAM and stores the others on disk until Polars is ready to process them.

To see the difference on real data, group 10 months of taxi trips by route and hour. With 33 million trips and 12 million groups, this query needs a lot of memory.
months = [
f"data/yellow_tripdata_2024-{m:02d}.parquet"
for m in range(1, 11)
]
trips = pl.scan_parquet(months)

routes_by_hour = (
trips.group_by(
"PULocationID",
"DOLocationID",
pl.col("tpep_pickup_datetime")
.dt.truncate("1h")
.alias("pickup_hour"),
)
.agg(
pl.len().alias("trips"),
pl.col("fare_amount").mean().alias("avg_fare"),
)
.collect()
)

Here is the same code on Polars 1.44.2 and 2.1.0, as the median of 3 runs.
version peak memory time
1.44.2 ████████████████████ 4,453 MB 0.75 s
2.1.0 ███████████ 2,389 MB 0.34 s

The same code runs twice as fast in 2.1 and uses about half the memory.
Run Warehouse SQL Directly
Many SQL features common in warehouses like Snowflake or BigQuery were not supported in Polars 1.x. You had to rewrite those queries as Polars expressions, or run them in another engine.
Polars 2.1 adds many of these features. Here are three of them on the taxi data.
Read Several Files at Once
In Polars 1.x, read_parquet in SQL took one string, either a path or a glob. In Polars 2.1, it also takes a list of paths, so you can pick exactly which files to read.
three_months = pl.sql(
"""
SELECT COUNT(*) AS trips
FROM read_parquet([
'data/yellow_tripdata_2024-01.parquet',
'data/yellow_tripdata_2024-02.parquet',
'data/yellow_tripdata_2024-03.parquet'
])
""",
eager=True,
)
three_months

Output┌─────────┐
│ trips │
│ — │
│ i64 │
╞═════════╡
│ 9554778 │
└─────────┘

Group Rows by Hour with DATE_TRUNC
DATE_TRUNC rounds a timestamp down to a unit such as the hour or the day, which is how you count events per hour in SQL. Polars 2.1 now supports it.
The query below rounds each pickup time down to the hour, for pickups in zone 12 on January 2.
trips = pl.scan_parquet("data/taxi.parquet")

pl.sql(
"""
SELECT
tpep_pickup_datetime,
DATE_TRUNC('hour', tpep_pickup_datetime)
AS pickup_hour
FROM trips
WHERE PULocationID = 12
AND CAST(tpep_pickup_datetime AS DATE)
= '2024-01-02'
ORDER BY tpep_pickup_datetime
LIMIT 4
""",
eager=True,
)

Output┌──────────────────────┬─────────────────────┐
│ tpep_pickup_datetime ┆ pickup_hour │
│ — ┆ — │
│ datetime[μs] ┆ datetime[μs] │
╞══════════════════════╪═════════════════════╡
│ 2024-01-02 09:31:54 ┆ 2024-01-02 09:00:00 │
│ 2024-01-02 10:04:05 ┆ 2024-01-02 10:00:00 │
│ 2024-01-02 10:06:16 ┆ 2024-01-02 10:00:00 │
│ 2024-01-02 10:28:21 ┆ 2024-01-02 10:00:00 │
└──────────────────────┴─────────────────────┘

Fill Missing Hours with generate_series
generate_series creates one row per step between a start and an end, such as every hour of a day. Polars 2.1 now supports it.
The query below creates one row for each hour from 6 AM to 9 AM on January 2.
pl.sql(
"""
SELECT *
FROM generate_series(
TIMESTAMP '2024-01-02 06:00:00',
TIMESTAMP '2024-01-02 09:00:00',
INTERVAL '1 hour'
) AS t(pickup_hour)
""",
eager=True,
)

Output┌─────────────────────┐
│ pickup_hour │
│ — │
│ datetime[μs] │
╞═════════════════════╡
│ 2024-01-02 06:00:00 │
│ 2024-01-02 07:00:00 │
│ 2024-01-02 08:00:00 │
│ 2024-01-02 09:00:00 │
└─────────────────────┘

2.1 also adds ASOF JOIN, WITH RECURSIVE, CREATE TEMP TABLE, REGEXP_REPLACE, and correlated subqueries in JOIN … ON. See the release notes for the full list.
Encrypt Sensitive Columns
Sometimes only certain people should see some columns. For example, in the taxi data, only the finance team should see fares and tips, while everyone can see the rest.
Polars 2.1 allows you to encrypt chosen columns in a Parquet file with a specific key.

To encrypt sensitive columns, use ParquetEncryptionProperties. It takes two kinds of keys:

The footer key protects the file from being tampered with.
The column keys lock the sensitive columns, so only people with the key can read them.

trips = pl.read_parquet("data/taxi.parquet")

# Define keys (each must be 16 or 32 bytes)
footer_key = b"footer-key-16byt"
payment_key = b"payment-key-16by"

# Define sensitive columns
payment_columns = {
"fare_amount": payment_key,
"tip_amount": payment_key,
}

# Encrypt the file
encryption = pl.ParquetEncryptionProperties(
footer_key=footer_key,
column_keys=payment_columns,
# Let readers without keys read unencrypted columns
plaintext_footer=True,
)
trips.write_parquet(
"data/trips_encrypted.parquet",
encryption=encryption,
)

Without the keys, you can only read the unencrypted columns.
pl.read_parquet(
"data/trips_encrypted.parquet",
columns=["PULocationID", "trip_distance"],
).head(3)

Output┌──────────────┬───────────────┐
│ PULocationID ┆ trip_distance │
│ — ┆ — │
│ i32 ┆ f64 │
╞══════════════╪═══════════════╡
│ 186 ┆ 1.72 │
│ 140 ┆ 1.8 │
│ 236 ┆ 4.7 │
└──────────────┴───────────────┘

Passing the keys with ParquetDecryptionProperties allows you to read the sensitive columns.
decryption = pl.ParquetDecryptionProperties(
footer_key=footer_key, column_keys=payment_columns
)
pl.read_parquet(
"data/trips_encrypted.parquet",
columns=["fare_amount", "tip_amount"],
decryption=decryption,
).head(3)

Output┌─────────────┬────────────┐
│ fare_amount ┆ tip_amount │
│ — ┆ — │
│ f64 ┆ f64 │
╞═════════════╪════════════╡
│ 17.7 ┆ 0.0 │
│ 10.0 ┆ 3.75 │
│ 23.3 ┆ 3.0 │
└─────────────┴────────────┘

Other Additions in 2.1
Here are a few smaller additions worth knowing about.
Full Joins in join_where
join_where joins two tables on conditions like “a value falls within a range”. In Polars 2.1, you can pass how="full" to keep the rows that don’t match on either side.
trips = pl.DataFrame({"pickup_hour": [8, 13]})
rush = pl.DataFrame(
{
"period": ["morning", "evening"],
"start": [7, 17],
"end": [9, 19],
}
)

joined = trips.join_where(
rush,
pl.col("pickup_hour").is_between("start", "end"),
how="full",
)

Output┌─────────────┬─────────┬───────┬──────┐
│ pickup_hour ┆ period ┆ start ┆ end │
│ — ┆ — ┆ — ┆ — │
│ i64 ┆ str ┆ i64 ┆ i64 │
╞═════════════╪═════════╪═══════╪══════╡
│ 8 ┆ morning ┆ 7 ┆ 9 │ <- both
│ 13 ┆ null ┆ null ┆ null │ <- trips only
│ null ┆ evening ┆ 17 ┆ 19 │ <- rush only
└─────────────┴─────────┴───────┴──────┘

Estimate Quantiles with approx_quantile
An exact quantile, such as the median, needs every value in the column in memory to find the one in the middle. On large data, that costs time and memory.
approx_quantile estimates the quantile from a sample of the values instead. It runs faster and uses less memory, at the cost of a small error, which is usually good enough.

Let’s compare the performance of the two approaches on 33 million fares, using the median of 3 runs.
months = [
f"data/yellow_tripdata_2024-{m:02d}.parquet"
for m in range(1, 11)
]
fares = pl.scan_parquet(months)

fare = pl.col("fare_amount")
fares.select(
fare.quantile(0.5).alias("exact_median"),
fare.approx_quantile(0.5).alias("approx_median"),
).collect()

Output┌──────────────┬───────────────┐
│ exact_median ┆ approx_median │
│ — ┆ — │
│ f64 ┆ f64 │
╞══════════════╪═══════════════╡
│ 13.5 ┆ 13.5 │
└──────────────┴───────────────┘

The estimate matches the exact median. Better yet, it is 2x faster and uses 38% less memory.
peak memory
quantile ██████████████████████████████ 681 MB
approx_quantile ███████████████████ 422 MB

time
quantile ██████████████████████████████ 0.09 s
approx_quantile █████████████ 0.04 s

Convert Masked NumPy Arrays
A NumPy masked array pairs the data with a list of True/False flags, where True marks a value as missing. Polars 2.1 reads the mask and turns each hidden value into a null.
import numpy as np

masked_tips = np.ma.array(
[3.75, 0.0, 3.0], mask=[False, True, False]
)
tips = pl.Series("tip_amount", masked_tips)

print(tips.to_list())

Output[3.75, None, 3.0]

Final Thoughts
What I like about Polars 2.1 is that most of the gains need no code changes. The same group-by runs twice as fast as in Polars 1.x with about half the memory, and you can write more of your usual SQL without workarounds.
Joins can’t spill to disk yet, but the Polars team plans to add it. Until then, a very large join needs enough RAM, or an engine like DuckDB.
References

Polars 2.0 release post (Polars, 2026): spilling to disk starts at about 80% of RAM, with a 64 GB default disk budget.

Related Tutorials

What’s New in Polars 2.0: the streaming default, row order changes, and stricter types
pandas vs Polars vs DuckDB: when each DataFrame tool fits best

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

What’s New in Polars 2.1: Faster Group-Bys, More SQL, Encrypted Parquet Read More »

Python 3.15 for Data Scientists: Lazy Imports, frozendict, and Tachyon

Table of Contents

Introduction
Lazy Imports: Load Libraries Only When You Use Them
frozendict: Immutable Dicts, Built In
Unpacking in Comprehensions: Flatten and Merge in One Line
Tachyon: Profile a Running Job Without Restarting It
Clearer Error Messages
Smaller Improvements Worth Knowing
Final Thoughts
References

Introduction
Python 3.15 was released on October 9, 2026. The changelog is long, so this article picks the five changes you’re most likely to care about as a data scientist.
For each feature, you’ll see the problem with the old way and how the new feature solves it.

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

Lazy Imports: Load Libraries Only When You Use Them
A normal import loads a module right when Python reaches the import line:
import pandas as pd # pandas loads here, even if the script never uses it
print("hello")

The usual workaround is to move import pandas inside the function that needs it. That works, but the imports end up spread across functions. Anyone reading the code has to check every function to see which libraries it uses.
def load_trips(path):
import pandas as pd
return pd.read_parquet(path)

In Python 3.15, the lazy keyword (PEP 810) lets the import stay at the top while delaying the load until the module is first used:
lazy import pandas as pd # nothing loads yet
print("hello")
df = pd.read_parquet("taxi.parquet") # pandas loads here, on first use

To measure the difference, compare two scripts that differ only in the import line. Neither uses pandas, so the lazy script should skip loading it entirely and run much faster:
# normal.py
import pandas as pd
print("hello")

# lazy.py
lazy import pandas as pd
print("hello")

Running each script 20 times and taking the median gives:

Outputnormal: 280 ms
lazy: 14 ms <— 20 times faster

The lazy version starts about 20 times faster. This shows that it never loads pandas.
frozendict: Immutable Dicts, Built In
Plain dicts can be changed by any function they’re passed to. In a pipeline, that means one step can quietly change a setting that later steps rely on.
config = {"min_fare": 0, "max_fare": 500}

def drop_outliers(cfg):
cfg["max_fare"] = 1000 # meant as a local tweak

print("before:", config)
drop_outliers(config)
print("after: ", config)

Outputbefore: {'min_fare': 0, 'max_fare': 500}
after: {'min_fare': 0, 'max_fare': 1000} <- max_fare changed

Python 3.15 solves this problem with a built-in frozendict (PEP 814), a dict that can’t be changed after it’s created:
config = frozendict(min_fare=0, max_fare=500)

def drop_outliers(cfg):
cfg["max_fare"] = 1000

drop_outliers(config)

OutputTypeError: 'frozendict' object does not support item assignment

To change a value, create a new frozendict with |. The original stays the same:
strict_config = config | {"max_fare": 300}
print("original:", config)
print("new: ", strict_config)

Outputoriginal: frozendict({'min_fare': 0, 'max_fare': 500})
new: frozendict({'min_fare': 0, 'max_fare': 300})

Changing a setting now takes a deliberate step, so it can’t happen by accident.

📚 For comprehensive guidance on managing pipeline configs, check out Production-Ready Data Science.

Unpacking in Comprehensions: Flatten and Merge in One Line
You can flatten a list of lists with a double for or itertools.chain.from_iterable. However, the double for is hard to read at a glance.
column_groups = [
["fare_amount", "tip_amount"],
["trip_distance"],
["passenger_count", "payment_type"],
]
print([column for group in column_groups for column in group])

Output['fare_amount', 'tip_amount', 'trip_distance', 'passenger_count', 'payment_type']

Python 3.15 makes this more readable by allowing * inside comprehensions (PEP 798). It unpacks each inner list, so the items end up in one flat list:
print([*group for group in column_groups])

Output['fare_amount', 'tip_amount', 'trip_distance', 'passenger_count', 'payment_type']

The same syntax works for sets:
monthly_payment_types = [{1, 2}, {2, 3, 4}, {1, 5}]
print({*types for types in monthly_payment_types})

Output{1, 2, 3, 4, 5}

** allows merging a list of dicts into one. If two dicts share a key, the dict that comes later in the list overrides the earlier one.
layers = [
{"min_fare": 0, "max_fare": 500}, # defaults
{"max_fare": 300}, # overrides max_fare
{"payment_types": (1, 2)}, # adds a new key
]
print({**layer for layer in layers})

Output{'min_fare': 0, 'max_fare': 300, 'payment_types': (1, 2)}

Tachyon: Profile a Running Job Without Restarting It
Tachyon vs cProfile
A profiler tells you which parts of your code take the most time. Python’s built-in profiler, cProfile, times every function call, even when the same function runs millions of times. That extra work makes the program run slower:
call 1 func_1 start timer … stop timer
call 2 func_1 start timer … stop timer <- same function, timed again
call 3 func_2 start timer … stop timer
… every call gets timed -> extra work on each one

Tachyon, the new profiler in Python 3.15, doesn’t time every function call. Instead, it checks which function is running once every millisecond. A function that shows up in 3 of 4 checks used about 75% of the time:
1 ms func_1
2 ms func_1
3 ms func_2
4 ms func_1

func_1 3 of 4 checks = 75% of the time
func_2 1 of 4 checks = 25% of the time

Profile with Tachyon
Let’s try profiling a pipeline with Tachyon. Start by installing pyarrow and downloading one month of NYC Yellow Taxi trip records:
uv pip install pyarrow
curl -o taxi.parquet https://d37ci6vzurychx.cloudfront.net/trip-data/yellow_tripdata_2024-01.parquet

Create a simple data pipeline:
# pipeline.py
import pandas as pd

def load_trips(path):
columns = ["PULocationID", "fare_amount", "tip_amount", "trip_distance"]
return pd.read_parquet(path, columns=columns)

def clean_trips(trips):
return trips[(trips["fare_amount"] > 0) & (trips["trip_distance"] > 0)]

def tip_rate(row):
return row["tip_amount"] / row["fare_amount"]

def add_tip_rate(trips):
return trips.assign(tip_rate=trips.apply(tip_rate, axis=1))

def summarize_zones(trips):
return trips.groupby("PULocationID")["tip_rate"].median()

trips = load_trips("taxi.parquet")
trips = clean_trips(trips)
trips = add_tip_rate(trips)
summary = summarize_zones(trips)
print(summary.sort_values(ascending=False).head(3))

To run profiling with Tachyon, run:
python -m profiling.sampling run –sort cumtime -l 9 pipeline.py

Add the –flamegraph option to write an interactive HTML report:
python -m profiling.sampling run –flamegraph -o flamegraph.html pipeline.py

Each bar is a function. Bars below it are the functions it called. A bar’s width and color show how much of the run time it took:
orange-red 60% or more
yellow 35% to 60%
green 18% to 35%
blue under 18%

Hover over a bar to see its details. add_tip_rate takes 78.5% of the run, so it’s the slow step:

add_tip_rate calls tip_rate through pandas apply, once for every row. tip_rate alone takes 54.2% of the run:

The narrow stack on the right is import pandas as pd, at 18.6% of the run. The import is slow because pandas loads 293 submodules, and each one runs its own setup code:

So the slow part of this pipeline is the row-by-row apply in add_tip_rate, not loading the data.
To understand how Tachyon got these results, look at the Profile Summary panel in the sidebar. It shows that Tachyon:

Collected 3.1K samples in 5.52 seconds
Saw 261 different functions in those samples
Succeeded on 56.7% of its checks (sampling efficiency)

Tachyon also barely slows the program down. It added about 4% to the run time, while cProfile made it more than 3 times slower:
python pipeline.py ~4.9 s no profiler
python -m profiling.sampling run pipeline.py ~5.1 s Tachyon: +4%
python -m cProfile pipeline.py ~16.7 s cProfile: 3.4x slower

Attach to a Running Process
cProfile can’t attach to a program that’s already running. To profile a long job with it, you’d have to restart the job.
Tachyon can attach to a job that’s already running, without restarting it.
The command below samples a running job for 5 seconds. Replace <PID> with your job’s process ID:
python -m profiling.sampling attach -d 5 <PID>

To find the process ID, search the running processes for your script’s name with pgrep:
pgrep -af pipeline.py # Linux; on macOS, use pgrep -lf pipeline.py

Output27086 python pipeline.py -> 27086 is the <PID>

Clearer Error Messages
Hints for Missing Attributes
Missing-attribute errors now include a suggestion for what you likely meant, not just a note that the attribute is missing.
Let’s say you keep each experiment’s data in a dataclass, then call .shape on the dataclass instead of on its DataFrame. In Python 3.14 and earlier, the error only says the attribute is missing:
from dataclasses import dataclass

import pandas as pd

@dataclass
class Experiment:
name: str
data: pd.DataFrame

exp = Experiment(name="baseline", data=pd.DataFrame({"fare": [12.5, 8.0]}))
exp.shape

OutputAttributeError: 'Experiment' object has no attribute 'shape'

Python 3.15 points to where the attribute actually is:

OutputAttributeError: 'Experiment' object has no attribute 'shape'. Did you mean '.data.shape' instead of '.shape'?

Hints for Method Names from Other Languages
Those come from other languages such as JavaScript might get confused of syntax. For example, calling a JavaScript-style push on a list, or append on a tuple:
["fare", "tip"].push("distance")
("fare", "tip").append("distance")

Python 3.14 simply says the method is missing:

OutputAttributeError: 'list' object has no attribute 'push'
AttributeError: 'tuple' object has no attribute 'append'

Python 3.15 figures out the correct syntax and gives a hint:

OutputAttributeError: 'list' object has no attribute 'push'. Did you mean '.append'?
AttributeError: 'tuple' object has no attribute 'append'. Did you mean to use a 'list' object?

Smaller Improvements Worth Knowing
Python 3.15 also includes smaller changes that make everyday work smoother.
UTF-8 by Default: Fewer Cross-Platform CSV Bugs
A file stores bytes, not letters. An encoding is the rule for turning those bytes back into letters. A few common ones:
encoding characters it covers where you see it
——– ———————————— ———————————-
ascii 128: English letters, digits, symbols old systems; no é, no emoji
cp1252 256: adds Western European letters default on many Windows machines
utf-8 every character, including 日本 and 🙂 macOS, Linux, and most of the web

Before 3.15, if you called open() without saying which rule to use, Python picked based on the computer. So the same script gives different results on different machines. Code that works on your laptop can quietly misread files on a teammate’s.
same file, saved as UTF-8: c a f é
bytes: 63 61 66 C3 A9 (é takes 2 bytes)

Mac reads it with UTF-8 -> café correct
Windows reads it with cp1252 -> café wrong letters

Python 3.15 makes UTF-8 the default on every platform (PEP 686), so open() reads a file the same way on every machine:
same file, saved as UTF-8: c a f é
bytes: 63 61 66 C3 A9

Mac reads it with UTF-8 -> café correct
Windows reads it with UTF-8 -> café correct

Tab Completion for Imports
In the interactive shell, pressing Tab after from module import now suggests the names inside the module:
>>> from statistics import me<Tab>
mean median median_grouped median_high median_low

For a third-party package like pandas, the first Tab offers to import it, and the second Tab shows the names:
>>> from pandas import read_c<Tab>
[ module not imported, press again to import it and propose attributes ]
>>> from pandas import read_c<Tab>
read_clipboard read_csv

Tab completions are also colored by object kind now, so functions, classes, and modules are easier to tell apart. Here, classes are magenta, functions are blue, and submodules are cyan:

Final Thoughts
After upgrading to Python 3.15, here are some things to try:

If a script takes a long time to start up, mark heavy imports like pandas, scikit-learn, and matplotlib as lazy.
If you pass a config dict between functions and don’t want it changed by accident, freeze it with frozendict.
If a job is slow, generate a Tachyon flame graph and hover over the widest bars to find the bottleneck.

References

What’s New in Python 3.15 (Python Software Foundation, 2026): release date and the full list of features covered here.
profiling.sampling documentation (Python Software Foundation, 2026): run, attach, dump, modes, and output formats.

Related Tutorials

What’s New in pandas 3.0: Expressions, Copy-on-Write, and Faster Strings: The biggest pandas changes to know if you’re upgrading pandas along with Python.
The Hidden Cost of Python Dictionaries (And 3 Safer Alternatives): Covers the bugs that mutable dicts cause, which frozendict now helps prevent.

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

Python 3.15 for Data Scientists: Lazy Imports, frozendict, and Tachyon Read More »

Graphify – Query a Codebase as a Knowledge Graph

Grab your coffee. Here are this week’s highlights.

📅 Today’s Picks

kotaemon – Build Private Document QA with Citations

Problem
ChatGPT’s file upload is useful for quick questions, but it is not built for shared document workflows.
Teams often need page-level citations, shared document collections, user access control, and a way to keep sensitive files inside their own infrastructure.
Solution
kotaemon provides a self-hosted document QA interface for that.
It lets teams ask questions across documents, verify answers in a built-in PDF viewer, and organize files into private or public collections.
Key benefits:

Finds answers with both keyword search and semantic search
Reasons across multiple documents for more complex questions
Runs on your own infrastructure with one Docker command
Works with OpenAI, Anthropic, and local models

Graphify – Query a Codebase as a Knowledge Graph

Problem
When asking repo-level questions, the usual workflow is to search with grep, jump between definitions, read docs, and paste context back into the chat.
But this workflow takes time, makes indirect connections easy to miss, and forces the assistant to load more context than needed.
Solution
Graphify turns a project folder into a local knowledge graph that maps those relationships, so follow-up questions become cheaper and easier to answer accurately.
The following example shows how Graphify traces the shortest path between two scikit-learn components without manually opening files.

Stay Current with CodeCut

Actionable Python tips, curated for busy data pros. Skim in under 2 minutes, three times a week.

.codecut-subscribe-form .codecut-input {
background: #2F2D2E !important;
border: 1px solid #72BEFA !important;
color: #FFFFFF !important;
}
.codecut-subscribe-form .codecut-input::placeholder {
color: #999999 !important;
}
.codecut-subscribe-form .codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
}
.codecut-subscribe-form .codecut-subscribe-btn:hover {
background: #5aa8e8 !important;
}

.codecut-subscribe-form {
max-width: 650px;
display: flex;
flex-direction: column;
gap: 8px;
}
.codecut-input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #FFFFFF;
border-radius: 8px !important;
padding: 8px 12px;
font-family: ‘Comfortaa’, sans-serif !important;
font-size: 14px !important;
color: #333333;
border: none !important;
outline: none;
width: 100%;
box-sizing: border-box;
}
input[type=”email”].codecut-input {
border-radius: 8px !important;
}
.codecut-input::placeholder {
color: #666666;
}
.codecut-email-row {
display: flex;
align-items: stretch;
height: 36px;
gap: 8px;
}
.codecut-email-row .codecut-input {
flex: 1;
}
.codecut-subscribe-btn {
background: #72BEFA;
color: #2F2D2E;
border: none;
border-radius: 8px;
padding: 8px 14px;
font-family: ‘Comfortaa’, sans-serif;
font-size: 14px;
font-weight: 500;
cursor: pointer;
text-decoration: none;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}
.codecut-subscribe-btn:hover {
background: #5aa8e8;
}
.codecut-subscribe-btn:disabled {
background: #999;
cursor: not-allowed;
}
.codecut-message {
font-family: ‘Comfortaa’, sans-serif;
font-size: 12px;
padding: 8px;
border-radius: 6px;
display: none;
}
.codecut-message.success {
background: #d4edda;
color: #155724;
display: block;
}
@media (max-width: 480px) {
.codecut-email-row {
flex-direction: column;
height: auto;
gap: 8px;
}
.codecut-input {
border-radius: 8px;
height: 36px;
}
.codecut-subscribe-btn {
width: 100%;
text-align: center;
border-radius: 8px;
height: 36px;
}
}

Subscribe

Graphify – Query a Codebase as a Knowledge Graph Read More »

Stop Treating Your RAG Grounding Score as a Safety Net

Table of Contents

Introduction
Why this matters to you right now
The hypothesis
The setup
The scoring mechanism
The benchmark score
Flip one negation
Change one number
What the results show
What to change in your system
Running the code yourself
Key takeaways
Related Tutorials

Introduction
A grounding checker can look reliable on a benchmark because many benchmark errors are easy to see: long unsupported passages, extra details, or invented explanations.
But doing well on those cases does not mean the checker will catch every unsupported claim.
Your application may need it to catch smaller errors: a policy answer flipped by one “not,” or a pricing, healthcare, or logistics answer changed by one digit.
For example:
policy source You can export data after approval.
wrong answer You cannot export data after approval.
^^^

pricing source The monthly plan costs $15.
wrong answer The monthly plan costs $25.
^

I wanted to test whether benchmark performance transfers to those errors, or whether the checker is mostly good at catching larger unsupported passages.
Why this matters to you right now
If you are using a grounding checker in any of these settings, the benchmark score may not tell you enough:

A policy assistant that must catch words like “not,” “never,” or “must.”
A finance, healthcare, pricing, or logistics assistant that must catch wrong values.
A production RAG app where unsupported answers are blocked only when the checker flags them.

This article shows how the checker behaves on three error types: benchmark hallucinations, one flipped negation, and one changed number.
The hypothesis
The hypothesis is simple: if a checker really understands grounding, it should flag unsupported claims no matter how small they are.
expected behavior

large unsupported passage flagged
changed number flagged
flipped negation flagged

That is the behavior you would want in production. A wrong number or one flipped “not” can matter just as much as several unsupported sentences.
The experiment below tests whether the checker behaves that way.

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

The setup
What a grounding checker checks
A grounding checker tests whether the retrieved document supports the LLM-generated answer.
For example, if the source says the refund window is 30 days but the answer says 60 days, the checker should flag that claim as unsupported.
THE DOCUMENT THE ANSWER THE CHECKER SHOULD SAY

"Returns are accepted + "You can return -> unsupported
within 30 days of items within "60 days" appears
purchase." 60 days." nowhere in the document

"Returns are accepted + "You can return -> supported
within 30 days of items within every claim traces
purchase." 30 days." back to the source

This experiment uses LettuceDetect, an open-source checker for unsupported spans in RAG answers. I chose it because it can run locally and deterministically, which makes the results easier to reproduce.
Install the packages
Install the packages:
uv venv –python 3.11 .venv
uv pip install –python .venv/bin/python datasets scikit-learn numpy lettucedetect

This article uses lettucedetect v0.2.3, datasets v5.0.1, and scikit-learn v1.9.0.
Initialize the detector
First, initialize LettuceDetect with the ModernBERT checkpoint used in this experiment:
from lettucedetect.models.inference import HallucinationDetector

detector = HallucinationDetector(
method="transformer",
model_path="KRLabsOrg/lettucedect-base-modernbert-en-v1",
)

Build the RAGTruth sample
The experiment uses 200 RAGTruth QA answers: 100 with hallucinated text and 100 clean. This checks whether the model can tell unsupported answers apart from supported ones.
import json
import random

from datasets import load_dataset

rows = load_dataset("wandb/RAGTruth-processed", split="test")
qa_rows = [row for row in rows if row["task_type"] == "QA"]

def is_hallucinated(row):
return len(json.loads(row["hallucination_labels"])) > 0

hallucinated = [row for row in qa_rows if is_hallucinated(row)]
clean = [row for row in qa_rows if not is_hallucinated(row)]

rng = random.Random(0)
rng.shuffle(hallucinated)
rng.shuffle(clean)
sample = hallucinated[:100] + clean[:100]
rng.shuffle(sample)

cases = [
{
"id": str(row["id"]),
"query": row["query"],
"answer": row["output"],
"context": row["context"],
"hallucinated": is_hallucinated(row),
}
for row in sample
]

print(f"{len(cases)} cases, {sum(case['hallucinated'] for case in cases)} hallucinated")

Output200 cases, 100 hallucinated

The scoring mechanism
Before scoring the full sample, let’s look at one RAGTruth example to understand how the checker works.
case = next(case for case in cases if case["id"] == "12045")

source_document = case["context"]
question = case["query"]
answer = case["answer"].replace("\n", " ")
source_start = source_document.find("If using a gas grill")

print("question:", question)
print()
print(
"source:",
source_document[source_start : source_start + 220].replace("\n", " "),
"…",
)
print()
print("answer:", answer[answer.find("7. Cook") : answer.find("8. Remove")].strip())
print("answer:", answer[answer.find("8. Remove") :].strip())

Outputquestion: how to grill a porterhouse

source: If using a gas grill, set it up for three-zone grilling. 1 Leave the section closest to you coal-free. 2 Replace the grill grate. 3 If using a gas grill, set it up for three-zone grilling. 4 Keep it hot, keep it clea …

answer: 7. Cook for 4-5 minutes per side, or until the internal temperature reaches your desired doneness (unspecified in passages)
answer: 8. Remove from the grill and let rest for 5-10 minutes before slicing and serving (unspecified in passages)

The source explains how to set up the grill, but it does not say how long to cook the steak or how long to let it rest. Those timing instructions are added by the answer. Let’s see if LettuceDetect can catch those unsupported claims.
Turn checker output into a score
First, ask LettuceDetect for spans. A span is a phrase in the answer that the checker thinks is unsupported by the document. If the checker finds no unsupported phrase, it returns an empty list.
spans = detector.predict(
context=[source_document],
question=question,
answer=answer,
output_format="spans",
)

for span in sorted(spans, key=lambda span: span["confidence"], reverse=True):
print(f"{span['confidence']:.3f}: {span['text']}")

Output0.988: 8. Remove from the grill and let rest for 5-10 minutes before slicing and serving (unspecified in passages)
0.983: 7. Cook for 4-5 minutes per side, or until the internal temperature reaches your desired doneness (unspecified in passages)
0.898: . Place the Porterhouse steak on the grill, bone side down (Passage 3)

LettuceDetect gives the strongest span a confidence of 0.988, meaning it is highly confident the span is unsupported. This flagging makes sense: the source mentions grill setup, but it does not give the steak cooking time or resting time.
To turn spans into one score per answer, we could count how many spans were flagged:
print(f"span count: {len(spans)}")

Outputspan count: 3

The problem is that longer answers can naturally produce more spans. To avoid making answer length part of the score too early, switch to token output instead.
Token output gives each small piece of the answer a suspicion score between 0 and 1, which is easier to compare across answers of different lengths.
tokens = detector.predict(
context=[source_document],
question=question,
answer=answer,
output_format="tokens",
)

for token in sorted(tokens, key=lambda token: token["prob"], reverse=True)[:8]:
print(f"{token['prob']:.3f}: {token['token']!r}")

Output0.988: '-'
0.987: '10'
0.983: ' 4'
0.979: ' 5'
0.976: ' minutes'
0.973: ' minutes'
0.973: '-'
0.969: '5'

The highest-scoring tokens come from the same unsupported timing details that appeared in the span output. Token scores stay on a 0 to 1 scale. The closer a score is to 1, the more confident the checker is that the token is unsupported.
One answer now has many token scores, not one score. To reduce them to a single answer-level score, take the maximum token probability.
def score_by_token(tokens):
return max(token["prob"] for token in tokens)

To flag unsupported answers, define two helpers: one returns the answer score, and the other checks whether that score is high enough to count as a flag.
def score_answer(case):
tokens = detector.predict(
context=[case["context"]],
question=case["query"],
answer=case["answer"],
output_format="tokens",
)
return score_by_token(tokens)

def is_flagged(case, threshold=0.5):
return score_answer(case) > threshold

Run both helpers on the Porterhouse example:
print(f"token score: {score_answer(case):.3f}")
print(f"flagged: {is_flagged(case)}")

Outputtoken score: 0.988
flagged: True

A score of 0.988 means the checker is highly confident that some part of the answer is unsupported. Since it is above 0.5, the answer is flagged.
The benchmark score
Now score all 200 answers with their own documents:
flagged = {True: 0, False: 0}
for case in cases:
if is_flagged(case):
flagged[case["hallucinated"]] += 1

print(f"hallucinated answers flagged: {flagged[True]} of 100")
print(f"clean answers flagged: {flagged[False]} of 100")

Outputhallucinated answers flagged: 75 of 100
clean answers flagged: 13 of 100

This is a strong baseline: the checker catches most hallucinated answers while only flagging a small number of clean ones.
This is the same kind of quality question I explored in the MLflow RAG evaluation guide, but here I focus on smaller controlled errors.
Next, calculate the typical amount of unsupported text in the hallucinated answers:
import statistics

unsupported_lengths = [
sum(len(label["text"]) for label in json.loads(row["hallucination_labels"]))
for row in qa_rows
if is_hallucinated(row)
]

print(f"answers: {len(unsupported_lengths)}")
print(f"median unsupported text: {int(statistics.median(unsupported_lengths))} characters")

Outputanswers: 160
median unsupported text: 134 characters

This gives useful context for the baseline result: many benchmark hallucinations are fairly large pieces of unsupported text, often equivalent to one or two sentences.
That raises a narrower question: what happens when the unsupported claim is tiny? The next two tests change only one negation or one number and measure whether the checker catches it.
Flip one negation
Negation is a small edit with a large effect. Adding “not” can turn a supported claim into its opposite.
Here is one clean answer before and after a negation flip:
answer To peel potatoes quickly, you can follow these steps
^^^
flipped To peel potatoes quickly, you cannot follow these steps
^^^^^^

To build many negated examples, I created flip_a_negation() in run_negation.py. On a clean answer about peeling potatoes, it changes “you can follow” to “you cannot follow”:

Outputoriginal: To peel potatoes quickly, you can follow these steps: 1.
negated: To peel potatoes quickly, you cannot follow these steps: 1.

original score: 0.000
negated score: 0.000

The negated answer should get a higher score because it now contradicts the source. Instead, it stays at 0.000, so the checker is treating an unsupported answer as if it were still supported.
To see whether this is a pattern, I ran run_negation.py across 100 clean answers and score each answer before and after the edit:

Answer
flagged

unchanged
13 of 100

one negation flipped
17 of 100

Only 4 more answers are flagged after every answer gets a negation flip. That means the checker is not reliably detecting this kind of contradiction.
Change one number
I wanted to know whether this was specific to negation or a broader problem with small edits, so I repeated the test with one changed number.
This time, start with a number the source supports, then change one digit so the answer gives a value the source never mentions:
answer Boil the potatoes for about 15 minutes
^
changed Boil the potatoes for about 25 minutes
^

To create the number test set, I wrote run_numbers.py. For each clean answer, it changes one supported number to a value the source does not mention.
On the same potato answer, the number test changes “about 15 minutes” to “about 25 minutes”:

Outputoriginal: Boil the potatoes for about 15 minutes.
changed: Boil the potatoes for about 25 minutes.

original score: 0.000
changed score: 0.010

The changed answer should get a higher score because the source says 15 minutes, not 25. Instead, the score stays close to 0, so the checker is treating the wrong number as if it were still supported.
Then I ran run_numbers.py on 100 clean answers to see how often the checker flags the changed version:

Answer
flagged

unchanged
16 of 100

one number changed
48 of 100

The number edit is caught more often than the negation flip. But even here, more than half of the changed answers are still not flagged.
What the results show
Here is the full comparison across the three error types:

Unsupported claim
size
caught

invented passage
~134 chars
75 of 100

changed number
~2 chars
48 of 100

flipped negation
~4 chars
17 of 100

nothing changed
0
13 of 100

The pattern is clear:

Large invented passages are usually detected.
One-digit number changes are detected about half the time.
One-word negation flips are almost missed entirely.

This means the checker is more likely to catch large unsupported text than small edits, even when the small edits are important.
What to change in your system
From this experiment, I learned that a strong benchmark result does not guarantee good performance on every error. LettuceDetect caught many large unsupported passages, but often missed edits that changed only one word or one number.
Because of that, do not adopt a checker on benchmark performance alone. It should earn trust on the exact errors your application needs it to catch:

If your app answers policy questions, test negation flips.
If it answers finance, healthcare, pricing, or logistics questions, test numbers, dates, thresholds, and units.

You do not need a large benchmark for this. A small set of targeted examples can reveal the blind spots that matter.
Running the code yourself
The full scripts and recorded results are in the companion repository.
To reproduce the three measurements, run:
cd delete-the-evidence-rag-grounding-control

python run_sentences.py –stage report
python run_negation.py –stage report
python run_numbers.py –stage report

The scripts also save the generated examples and raw scores as JSON, so you can inspect the cases behind each summary table.
Key takeaways

A grounding checker can look strong on benchmark hallucinations and still miss smaller errors.
Error size matters: long unsupported passages are easier to catch than a changed word or digit.
Test the checker against the failure modes your application depends on, not only against a general benchmark score.

Related Tutorials

Build a Complete RAG System with 5 Open-Source Tools: See where a grounding checker fits after retrieval and answer generation.
5 Python Tools for Structured LLM Outputs: Compare tools for enforcing output format, a complementary reliability layer.
Before You Upgrade the Model, Try Thinking Mode: Test whether a behavior change solves the failure before switching models.

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

Stop Treating Your RAG Grounding Score as a Safety Net Read More »

Codon – Mix Compiled Speed with Python Libraries

Grab your coffee. Here are this week’s highlights.

📅 Today’s Picks

Codon – Mix Compiled Speed with Python Libraries

Problem
Compiled languages can make Python workloads faster, but they often come with a tradeoff.
You need to learn new syntax and give up easy access to libraries like pandas, scikit-learn, and matplotlib.
Solution
Codon lets you keep using Python libraries while speeding up the parts that benefit from compilation.
Key benefits:

Use the @python decorator to run Python code inside Codon
Keep using libraries like pandas and matplotlib from Codon code
Mix compiled Codon functions with regular Python code
Convert values between Codon and Python when needed

SenseLab – Switch Coding Agents Without Re-Explaining Context

Problem
Most coding agents keep their working memory inside one chat session, one model, or one IDE.
Switching tools means explaining the task again, and the new agent may not know which tradeoffs were made or why certain decisions worked.
Solution
SenseLab keeps the working context available across sessions, models, and coding tools.
The next agent can pick up from the previous agent’s saved context instead of starting over.
Key capabilities:

Shared memory across Codex, Claude, and other MCP clients
Multi-agent coordination, so agents can see each other’s work before they overlap
Continuous learning from past outcomes, so agents know what worked before
Decision lineage helps you debug what went wrong with an agent

️📦 Link to SenseLab: https://www.sense-lab.ai/

Stay Current with CodeCut

Actionable Python tips, curated for busy data pros. Skim in under 2 minutes, three times a week.

.codecut-subscribe-form .codecut-input {
background: #2F2D2E !important;
border: 1px solid #72BEFA !important;
color: #FFFFFF !important;
}
.codecut-subscribe-form .codecut-input::placeholder {
color: #999999 !important;
}
.codecut-subscribe-form .codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
}
.codecut-subscribe-form .codecut-subscribe-btn:hover {
background: #5aa8e8 !important;
}

.codecut-subscribe-form {
max-width: 650px;
display: flex;
flex-direction: column;
gap: 8px;
}
.codecut-input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #FFFFFF;
border-radius: 8px !important;
padding: 8px 12px;
font-family: ‘Comfortaa’, sans-serif !important;
font-size: 14px !important;
color: #333333;
border: none !important;
outline: none;
width: 100%;
box-sizing: border-box;
}
input[type=”email”].codecut-input {
border-radius: 8px !important;
}
.codecut-input::placeholder {
color: #666666;
}
.codecut-email-row {
display: flex;
align-items: stretch;
height: 36px;
gap: 8px;
}
.codecut-email-row .codecut-input {
flex: 1;
}
.codecut-subscribe-btn {
background: #72BEFA;
color: #2F2D2E;
border: none;
border-radius: 8px;
padding: 8px 14px;
font-family: ‘Comfortaa’, sans-serif;
font-size: 14px;
font-weight: 500;
cursor: pointer;
text-decoration: none;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}
.codecut-subscribe-btn:hover {
background: #5aa8e8;
}
.codecut-subscribe-btn:disabled {
background: #999;
cursor: not-allowed;
}
.codecut-message {
font-family: ‘Comfortaa’, sans-serif;
font-size: 12px;
padding: 8px;
border-radius: 6px;
display: none;
}
.codecut-message.success {
background: #d4edda;
color: #155724;
display: block;
}
@media (max-width: 480px) {
.codecut-email-row {
flex-direction: column;
height: auto;
gap: 8px;
}
.codecut-input {
border-radius: 8px;
height: 36px;
}
.codecut-subscribe-btn {
width: 100%;
text-align: center;
border-radius: 8px;
height: 36px;
}
}

Subscribe

Codon – Mix Compiled Speed with Python Libraries Read More »

Automate Model Tuning with an Agentic Training Loop

Table of Contents

The Problem with Hand-Tuning a Model
What We’re Building
Define the Evaluation Code
Define the Editable Training Script
Define the Agent Interface
Define the Safety Checks
Final Thoughts
Related Tutorials

The Problem with Hand-Tuning a Model
Model-tuning experiments often follow a repeatable pattern: change the code, train the model, compare the validation score, and decide what to try next.
Doing this by hand is slow because every iteration needs human attention. If the steps are this predictable, could the loop be automated?
This article shows how to automate model tuning with an agent. The agent proposes changes to the training script, a fixed evaluation step checks whether each change improves the metric, and only better versions are kept.

If you are tuning prompts instead of training code, my DSPy auto-optimization guide shows how DSPy automates that process with a metric-driven loop.

By the end, you will have a loop that tests training changes automatically, so experiments can keep running while you work on something else.
What We’re Building
This article builds the loop around nanoGPT, a compact GPT implementation for small language-model experiments. Its training code is lightweight, which makes it a good fit for repeated agent edits and quick evaluations.
To build the loop, we first set up the parts that stay stable:

Start with a small training script that is fast enough to run many times.
Use the same validation data and metrics for every candidate, so improvements are easy to compare.

Then we repeat the improvement loop:

Let the agent propose one candidate change to the training script.
Train the candidate and measure it with the same validation setup.
Make the candidate the new starting point only if it improves the metric.

Put together, the loop looks like this:

The runnable version of this loop lives in the companion repo: khuyentran1401/agent-tune. The article focuses on the design, while the repo provides the full nanoGPT example, templates, backend options, and CLI.

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

Define the Evaluation Code
The data.py file is the stable evaluation file. It loads the text, samples validation batches, reports the final score, and is not modified by the agent.
It exposes two things the training script relies on:
# data.py gives the training script two fixed things:
def get_batch(split, batch_size):
…
return inputs, targets # a batch of inputs and next-char targets

def evaluate(model):
…
print(f"val_loss {val_loss:.4f}") # the format the loop parses

In the code above:

get_batch gives the training script consistent training and validation data.
evaluate computes the validation score and prints it in a format the loop can read.

See the full implementation in examples/nanogpt/data.py.
Define the Editable Training Script
The train.py file is the editable training script. It contains the model, optimizer, hyperparameters, and training loop that define each candidate:
# train.py: the agent may rewrite anything here.
N_LAYER, N_HEAD, N_EMBD = 4, 4, 128
BATCH_SIZE, LR, MAX_ITERS = 32, 1e-3, 300

model = GPT()
optimizer = torch.optim.AdamW(model.parameters(), lr=LR)
for _ in range(MAX_ITERS):
… # train the model
data.evaluate(model) # prints val_loss for the loop

In the code above:

The constants define the model and training settings the agent can tune.
The script trains the candidate model, then calls data.evaluate to report the score.

See the full implementation in examples/nanogpt/train.py.
Run the current training script to get the baseline score.
python train.py

Outputval_loss 2.1321

Define the Agent Interface
The agent interface in agent.py is the bridge between the loop and the language model. It sends the current train.py and the best score so far to the model, then expects a rewritten training script in return.
The main function in that interface is propose_edit, which has three steps:
def propose_edit(code, best, config):
prompt = build_prompt(code, best, config) # assemble the instruction shown below
reply = ask_model(prompt, config) # send it to the configured model
return extract_code_block(reply) # extract the rewritten train.py

In the code above:

build_prompt creates the prompt from the metric to improve and the current training script.
ask_model sends that prompt to the configured backend, such as Ollama, OpenAI, or Anthropic, and receives the model’s response.
extract_code_block extracts the rewritten script from that response so the loop can test it.

If you want more context on local model backends, my LangChain and Ollama guide shows how Ollama can run private AI workflows without sending data to a cloud API.
The prompt includes the current training script and asks for a complete rewrite:
Current best {metric} is {best} ({goal_word}).

Here is the current {editable}, between markers:

<{editable}>
{code}
</{editable}>

Propose ONE change to improve {metric}.
{instructions}

Return the COMPLETE rewritten {editable} in a single fenced code block and nothing else.

See the backend implementation in agent_tune/agent.py.
Define the Safety Checks
This step is implemented in loop.py. It lets the system test agent-generated code without constant supervision: each candidate is tried, scored, and either accepted or rolled back.
run_loop is the function that coordinates that process:
def run_loop(config):
# Start from the current editable file and its baseline score.
editable_path = get_editable_path(config)
best_code = read_script(editable_path)
best_score = run_and_measure(config)

# Run the improvement cycle for the configured number of steps.
for step in range(config.iterations):
# Ask the agent to propose one edit to the current best code.
candidate_code = propose_edit(best_code, best_score, config)
if candidate_code is None:
continue

# Temporarily replace the file so the run command scores the candidate.
write_script(editable_path, candidate_code)

# Run the candidate and parse the metric from its output.
candidate_score = run_and_measure(config)

# If the candidate improved, remember it as the new best.
if is_better(candidate_score, best_score, config.goal):
best_score, best_code = candidate_score, candidate_code
# Otherwise, restore the previous best.
else:
write_script(editable_path, best_code)

# Leave the editable file as the best version found.
write_script(editable_path, best_code)

Running the repo prints one line per step:

Outputbaseline val_loss 2.1321
step 0: val_loss None [discard] (best 2.1321)
step 1: val_loss None [discard] (best 2.1321)
step 2: val_loss 2.8146 [discard] (best 2.1321)
step 3: val_loss 1.8189 [keep] (best 1.8189)

The run starts with a baseline val_loss of 2.1321, measured before any agent edits. Every candidate is compared against the current best:

Steps 0 and 1 have val_loss None, so neither candidate can replace the baseline.
Step 2 has val_loss 2.8146, which is higher than 2.1321, so it is discarded.
Step 3 lowers val_loss to 1.8189, so it becomes the new best version.

See the full loop implementation in agent_tune/loop.py.
Final Thoughts
This article showed how to turn manual tuning into a propose-evaluate-keep loop: keep the evaluation stable, let the agent edit one file, and carry forward only candidates that improve the score.
This approach works best when the task has a clear metric, a focused editable file, and fast enough iterations to explore multiple candidates. Examples include tuning small models, optimizing prompts, adjusting hyperparameters, searching over simulation constants, or improving scripts that report one score.
It is not a good fit when each run is costly, the output needs human judgment, or a single metric would hide important correctness or safety issues.
Related Tutorials

Structured Output Tools for LLMs: Compares tools for making LLM responses easier to parse and validate.
Build Production-Ready LLM Agents with LangChain 1.0 Middleware: Shows how to add stronger safeguards around agent behavior.

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

Automate Model Tuning with an Agentic Training Loop Read More »

Before You Upgrade the Model, Try Thinking Mode

Table of Contents

Introduction
What Is Thinking Mode?
Setup
Multi-Step Problems: Where Thinking Helps
Single-Step Problems: When Plain Mode Is Enough
Final Thoughts

Introduction
When a local model gets a simple task wrong, the natural reaction is to reach for a bigger one. But some failures are not model-size failures. They are reasoning failures.
This showed up while I was testing a local model on imported finance data. The model’s job was to review transactions before reporting: catch bad splits, duplicate card rows, refunds, and fee calculations.
One test looked like this:
A parent transaction of $1,000.00 was split into these children:
8.84, 86.18, 74.53, 74.53, 20.64, 12.61, 1.49, 1.49, 719.59
What is the difference between the parent amount and the total of the children?
Answer with the absolute difference, to 2 decimal places, and conclude whether
the split balances.

The model answered:
{"difference": 0.0, "conclusion": "The split balances."}

But the children total $999.90, so the correct answer is 0.10.
The natural next move was to use a larger local model or send the task to a stronger cloud model. But neither was free: locally, it meant more memory and slower inference; in the cloud, it meant token costs and sending the data off the machine.
Before upgrading the model, I tried the cheaper question first: could the same model get it right if it spent more time reasoning?
To find out, I ran twelve finance prompts through the same model twice, once with thinking off and once with thinking on. The benchmark included two kinds of prompts:

Eight multi-step problems, where each step depends on a value calculated earlier.
Four single-step problems, where the answer comes from one direct calculation.

By the end, you will know when thinking mode is worth the extra time and when it is better to switch to a larger model.

💻 Get the Code: Grab the runnable benchmark script, prompt list, and recorded results from GitHub.

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

What Is Thinking Mode?
Thinking mode asks the model to work through the problem before returning the final answer. The reasoning trace is kept separate, so your application can still receive the same clean response shape.

That extra reasoning step is what improves the answer, but it is also what makes the response slower.
Setup
Pull the model with Ollama. qwen3:30b-a3b is a mixture-of-experts model: it has about 30 billion total parameters, but activates only about 3 billion for each token. That makes it practical to run locally while still supporting thinking mode:
ollama pull qwen3:30b-a3b

This article uses ollama v0.32.8 and qwen3:30b-a3b.
Point at the local endpoint and the model:
import json
import time
import urllib.request

MODEL = "qwen3:30b-a3b"
URL = "localhost:11434/api/chat"

The code below defines the response contract. The model should answer with exactly one numeric field, answer, so each result can be compared directly with the known correct value:
SYSTEM = (
"You are a careful financial assistant. Answer the question with a "
"single number only. Do not include currency symbols, thousands "
"separators, units, or any explanation in the answer field."
)

SCHEMA = {
"type": "object",
"required": ["answer"],
"properties": {"answer": {"type": "number"}},
}

For a typed Python approach to the same problem, the PydanticAI structured-output guide shows how to validate LLM responses with models instead of raw schemas.
Next, the sampling settings. The benchmark uses two decoding setups: greedy decoding for the fast non-thinking baseline, and non-greedy decoding for thinking mode.
Greedy decoding means the model always takes the most likely next token:
yes 70% <- chosen
no 20%
maybe 10%

That is useful for the non-thinking baseline because it is fast and repeatable.
Thinking mode uses Qwen’s recommended non-greedy settings. Non-greedy decoding can choose from a controlled set of likely tokens instead of locking every step to the top one:
yes 70% <- likely
no 20% <- still allowed
maybe 10% <- unlikely, but possible depending on settings

That extra flexibility is useful for reasoning because the model has to explore intermediate steps before settling on the final answer:
GREEDY = {"temperature": 0}
THINKING = {"temperature": 0.6, "top_p": 0.95, "top_k": 20, "min_p": 0.0} # settings recommended by Qwen

Next, define the helpers that send the request to Ollama and get the answer:
def _get_ollama_message(question, think):
options = dict(THINKING if think else GREEDY, seed=0)
body = {
"model": MODEL,
"stream": False,
"think": think, # the only variable
"format": SCHEMA,
"options": options,
"messages": [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": question},
],
}
request = urllib.request.Request(
URL, json.dumps(body).encode(), {"Content-Type": "application/json"}
)
reply = json.loads(urllib.request.urlopen(request).read())
return reply["message"]

def _print_thinking_preview(message, max_lines):
if max_lines == 0 or not message.get("thinking"):
return
lines = [line for line in message["thinking"].splitlines() if line.strip()]
if len(lines) > max_lines:
head_count = max_lines // 2
tail_count = max_lines – head_count
lines = lines[:head_count] + ["…"] + lines[-tail_count:]
print("\n".join(lines))

def _extract_answer(message):
return json.loads(message["content"])["answer"]

Then wrap them in ask(). The decorator records each call’s latency in ask.last_seconds, which makes plain and thinking runs easy to compare:
def _timed(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
wrapper.last_seconds = time.perf_counter() – start
return result

wrapper.last_seconds = 0.0
return wrapper

@_timed
def ask(question, think=False, trace_lines=0):
message = _get_ollama_message(question, think)
_print_thinking_preview(message, trace_lines)
return _extract_answer(message)

Multi-Step Problems: Where Thinking Helps
Multi-step problems are hard because the answer is not available from one operation. It has to be built through several intermediate steps. For example:

Subtract charges in order
Add split transactions before comparing totals
Divide an invoice before applying a fee

These are the questions that thinking mode is good for: keeping track of the steps before giving the answer.
To test that, I ran eight multi-step finance questions with thinking mode off and on. Plain mode missed five, while thinking mode answered every one correctly:

Condition
Correct
Average Time

Plain
3 / 8
0.36s

Thinking
8 / 8
13.30s

Let’s look at the two multi-step problems that plain mode got wrong.
The first failure is a two-step reconciliation problem. The model has to total the nine child transactions first, then subtract that total from the $1,000.00 parent:
split_check = """A parent transaction of $1,000.00 was split into these children:
8.84, 86.18, 74.53, 74.53, 20.64, 12.61, 1.49, 1.49, 719.59
What is the difference between the parent amount and the total of the children?
Answer the absolute difference, to 2 decimal places."""

print(ask(split_check))

Output0.0

The answer is wrong. The children total $999.90, so the correct difference is 0.10.
Let’s turn the flag on and see if the answer improves:
print(ask(split_check, think=True, trace_lines=4))

OutputOkay, let's see. I need to find the difference between the parent transaction amount of $1,000.00 and the total of all the children amounts. The children amounts are: 8.84, 86.18, 74.53, 74.53, 20.64, 12.61, 1.49, 1.49, 719.59.
First, I should add up all the children's amounts. Let me list them out again to make sure I have them all:
…
So the absolute difference is $0.10, which is 0.10 when rounded to two decimal places.
I think that's right. My initial mistake was in the first addition step where I added 169.55 +74.53 as 244.63 instead of 244.08. That was the error. But after correcting that, it's 999.90, so difference is 0.10.
0.1

The answer is now correct! The trace shows the extra work that made the difference:

It restates the task: compare the $1,000.00 parent with the total of the child transactions.
It starts by adding the child amounts instead of jumping straight to an answer.
It notices that an intermediate sum is wrong.
It recomputes the total another way to check itself.
It lands on $999.90 for the children.
It subtracts that from $1,000.00 and returns the correct difference: 0.1.

Instead of jumping to 0.0, thinking mode gives the model room to work through the sum and find the missing ten cents.
The second failure is about operation order. The model has to divide the invoice into installments before applying the processing fee.
installment_fees = """An invoice of $4,800.00 was paid in 3 equal installments.
Each installment was charged a 2.5% processing fee.
What were the total processing fees, to 2 decimal places?"""

print(ask(installment_fees))

Output360.0

The answer is wrong. The invoice is paid in three installments, so the fee should be calculated after the split:

$4,800 / 3 = $1,600 per installment
$1,600 × 2.5% = $40 fee per installment
$40 × 3 = $120 total fees

The model probably came up with the wrong answer because it applied the fee to the full invoice three times: $4,800 × 2.5% × 3 = $360.
The speed is the problem here. It gets to a plausible formula quickly, but skips the slower intermediate step: calculate the installment amount first.
Now, let’s turn on thinking mode and see if the answer improves:
print(ask(installment_fees, think=True, trace_lines=4))

OutputOkay, let's see. The problem is about an invoice of $4,800.00 paid in 3 equal installments, each with a 2.5% processing fee. I need to find the total processing fees to two decimal places.
First, I need to figure out what each installment amount is before the processing fee. Since it's 3 equal installments, I should divide the total invoice by 3. So, $4,800 divided by 3. Let me calculate that: 4800 / 3 = 1600. So each installment is $1,600 before the fee.
…
Another way: Total fees = 3 * (4800/3 * 0.025) = 3 * (1600 * 0.025) = 3 * 40 = 120. Yep, same result.
So the total processing fees are $120.00. To two decimal places, that's 120.00.
120.0

This time the model gets the operation order right:

It divides $4,800 by 3 before applying the fee.
It calculates the fee on one $1,600 installment.
It multiplies the $40 fee by 3 installments.
It checks the same calculation another way before returning 120.0.

Thinking mode gets it right because it takes time to work through the problem instead of jumping to the most obvious formula.
Single-Step Problems: When Plain Mode Is Enough
Single-step problems are different: the answer comes from one direct calculation, with no intermediate value to carry forward. Here is a percentage example:
percent_of_deposit = """A deposit of $1,250.00 funded a single charge of $100.00.
What percentage of the deposit was that charge?
Answer to 2 decimal places."""

print(f"answer: {ask(percent_of_deposit)}")
print(f"time: {ask.last_seconds:.2f}s")

Outputanswer: 8.0
time: 0.40s

Plain mode gets the right answer in 0.40s. Thinking mode gives the same answer in 6.90s, about 17x slower:
print(f"answer: {ask(percent_of_deposit, think=True)}")
print(f"time: {ask.last_seconds:.2f}s")

Outputanswer: 8.0
time: 6.90s

The other four single-step prompts also show the same pattern: both models get the right answer, but plain mode is faster, and thinking mode is slower.

Condition
Correct
Average Time

Plain
4 / 4
1.38s

Thinking
4 / 4
8.67s

This shows that for one-step tasks, plain mode is the better default: it gives the same answer but with much less latency.
To view the full results, with the exact prompt and both models’ answers for each, see the full results file.
Final Thoughts
Here is the summary of the benchmark results:

Kind
Plain
Thinking
Average Time

Multi-step (8 problems)
3 / 8
8 / 8
0.36s → 13.30s

Single-step (4 problems)
4 / 4
4 / 4
1.38s → 8.67s

The decision whether to use thinking mode comes down to one question: is this a one-step answer, or does the model need to carry state across steps?
Here is the rule of thumb in more concrete terms:

Task Shape
Example
Better Default

One lookup
Pulling a due date from an email
Plain mode

One classification
Labeling a review sentiment
Plain mode

One format conversion
Turning a record into JSON
Plain mode

Multi-step debugging
Reading logs in order to find which earlier step caused a later job failure
Thinking mode

Rule chain
Checking whether a user qualifies after applying eligibility rules and exceptions
Thinking mode

Dependent decisions
Building a schedule where each meeting choice changes the remaining available slots
Thinking mode

In short, start with plain mode for obvious one-step tasks and thinking mode for obvious multi-step tasks. When the boundary is unclear, test both on a small set of real failures before deciding which default to use.
When thinking mode does not help, prompt optimization is the next lever. The DSPy guide covers that path for classifier-style LLM tasks.
Related Tutorials

Structured Output Tools for LLMs: enforcing the JSON schema this article relies on for gradeable answers.
Run Private AI Workflows with LangChain and Ollama: the local setup this runs on.
Build a Private Email Q&A System with Local and Cloud LLMs: a hybrid architecture for deciding what stays local and what gets escalated.

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

Before You Upgrade the Model, Try Thinking Mode Read More »

llama.cpp – Run local LLMs on any hardware with one binary

Grab your coffee. Here are this week’s highlights.

📅 Today’s Picks

Headroom – Cut agent tokens without touching your prompts

Problem
AI agents can waste tokens on context they do not fully need.
Long logs, full files, API responses, and retrieved documents often contain repeated structure that slows the model down.
Solution
Headroom compresses what your agent reads before it reaches the model, helping reduce token usage and cost.
Key benefits:

Compresses JSON, code, logs, diffs, and plain text
Keeps original content available when the agent needs more detail
Works with Claude Code, Codex, Cursor, or directly as a Python library

llama.cpp – Run local LLMs on any hardware with one binary

Problem
Running an open LLM locally usually means a heavy Python stack, CUDA drivers, and several gigabytes of dependencies.
This adds friction everywhere: installation takes longer, dependencies break more easily, and the same model may behave differently across hardware.
Solution
llama.cpp makes local inference more portable by replacing the heavy Python/CUDA setup with a C++ runtime that supports GGUF models.
Key benefits:

No heavy Python environment required
Works on CPUs, Mac GPUs, NVIDIA GPUs, and AMD GPUs
Loads GGUF-quantized models designed for lower memory use
Direct Hugging Face model loading
Built-in tools for chatting, serving, benchmarking, and quantizing models

Stay Current with CodeCut

Actionable Python tips, curated for busy data pros. Skim in under 2 minutes, three times a week.

.codecut-subscribe-form .codecut-input {
background: #2F2D2E !important;
border: 1px solid #72BEFA !important;
color: #FFFFFF !important;
}
.codecut-subscribe-form .codecut-input::placeholder {
color: #999999 !important;
}
.codecut-subscribe-form .codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
}
.codecut-subscribe-form .codecut-subscribe-btn:hover {
background: #5aa8e8 !important;
}

.codecut-subscribe-form {
max-width: 650px;
display: flex;
flex-direction: column;
gap: 8px;
}
.codecut-input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #FFFFFF;
border-radius: 8px !important;
padding: 8px 12px;
font-family: ‘Comfortaa’, sans-serif !important;
font-size: 14px !important;
color: #333333;
border: none !important;
outline: none;
width: 100%;
box-sizing: border-box;
}
input[type=”email”].codecut-input {
border-radius: 8px !important;
}
.codecut-input::placeholder {
color: #666666;
}
.codecut-email-row {
display: flex;
align-items: stretch;
height: 36px;
gap: 8px;
}
.codecut-email-row .codecut-input {
flex: 1;
}
.codecut-subscribe-btn {
background: #72BEFA;
color: #2F2D2E;
border: none;
border-radius: 8px;
padding: 8px 14px;
font-family: ‘Comfortaa’, sans-serif;
font-size: 14px;
font-weight: 500;
cursor: pointer;
text-decoration: none;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}
.codecut-subscribe-btn:hover {
background: #5aa8e8;
}
.codecut-subscribe-btn:disabled {
background: #999;
cursor: not-allowed;
}
.codecut-message {
font-family: ‘Comfortaa’, sans-serif;
font-size: 12px;
padding: 8px;
border-radius: 6px;
display: none;
}
.codecut-message.success {
background: #d4edda;
color: #155724;
display: block;
}
@media (max-width: 480px) {
.codecut-email-row {
flex-direction: column;
height: auto;
gap: 8px;
}
.codecut-input {
border-radius: 8px;
height: 36px;
}
.codecut-subscribe-btn {
width: 100%;
text-align: center;
border-radius: 8px;
height: 36px;
}
}

Subscribe

llama.cpp – Run local LLMs on any hardware with one binary Read More »

CloakBrowser – Make Browser Automation Look Real

Grab your coffee. Here are this week’s highlights.

📅 Today’s Picks

CloakBrowser – Make Browser Automation Look Real

Problem
Playwright is a browser automation framework that lets you control Chrome, Firefox, and Safari-like browsers with code.
But the browser Playwright launches does not always look like a normal user’s browser. Sites can detect those differences and respond with CAPTCHAs, blocked access, broken login flows, or misleading test results.
Solution
CloakBrowser replaces the default browser used by Playwright or Puppeteer with a more realistic Chrome-like browser.
It helps the browser behave more like a real user session, reducing CAPTCHAs, blocked pages, and broken login flows in automated workflows.

uv – Apply Dependency Overrides Without Side Effects

Problem
A global override can affect every package that uses the same dependency, creating new conflicts in parts of the project that were already working.
Solution
uv 0.11.25 introduced scoped dependency overrides.
You can apply the override only to the package that needs it instead of changing dependency resolution for the whole project.
This keeps temporary compatibility fixes from affecting unrelated packages.

📖 Read the docs

Stay Current with CodeCut

Actionable Python tips, curated for busy data pros. Skim in under 2 minutes, three times a week.

.codecut-subscribe-form .codecut-input {
background: #2F2D2E !important;
border: 1px solid #72BEFA !important;
color: #FFFFFF !important;
}
.codecut-subscribe-form .codecut-input::placeholder {
color: #999999 !important;
}
.codecut-subscribe-form .codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
}
.codecut-subscribe-form .codecut-subscribe-btn:hover {
background: #5aa8e8 !important;
}

.codecut-subscribe-form {
max-width: 650px;
display: flex;
flex-direction: column;
gap: 8px;
}
.codecut-input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #FFFFFF;
border-radius: 8px !important;
padding: 8px 12px;
font-family: ‘Comfortaa’, sans-serif !important;
font-size: 14px !important;
color: #333333;
border: none !important;
outline: none;
width: 100%;
box-sizing: border-box;
}
input[type=”email”].codecut-input {
border-radius: 8px !important;
}
.codecut-input::placeholder {
color: #666666;
}
.codecut-email-row {
display: flex;
align-items: stretch;
height: 36px;
gap: 8px;
}
.codecut-email-row .codecut-input {
flex: 1;
}
.codecut-subscribe-btn {
background: #72BEFA;
color: #2F2D2E;
border: none;
border-radius: 8px;
padding: 8px 14px;
font-family: ‘Comfortaa’, sans-serif;
font-size: 14px;
font-weight: 500;
cursor: pointer;
text-decoration: none;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}
.codecut-subscribe-btn:hover {
background: #5aa8e8;
}
.codecut-subscribe-btn:disabled {
background: #999;
cursor: not-allowed;
}
.codecut-message {
font-family: ‘Comfortaa’, sans-serif;
font-size: 12px;
padding: 8px;
border-radius: 6px;
display: none;
}
.codecut-message.success {
background: #d4edda;
color: #155724;
display: block;
}
@media (max-width: 480px) {
.codecut-email-row {
flex-direction: column;
height: auto;
gap: 8px;
}
.codecut-input {
border-radius: 8px;
height: 36px;
}
.codecut-subscribe-btn {
width: 100%;
text-align: center;
border-radius: 8px;
height: 36px;
}
}

Subscribe

CloakBrowser – Make Browser Automation Look Real Read More »

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran