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

CLI-Anything – Turn Any Desktop App into an Agent-Ready CLI

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

📅 Today’s Picks

Caveman – Make AI Coding Replies Cheaper

Problem
Extra framing and repeated context make AI replies longer, more expensive, and harder to scan.
Solution
Caveman makes agent replies shorter while preserving code, commands, paths, errors, and technical meaning.
You get the same technical answer with fewer tokens spent on filler.

CLI-Anything – Turn Any Desktop App into an Agent-Ready CLI

Problem
A common workaround is to automate the visible interface: click buttons, wait for screens to load, and infer progress from screenshots.
But the agent cannot easily see the underlying state, repeat the same steps reliably, or recover when the interface changes.
Solution
CLI-Anything does the upfront work of building a command-line layer for a desktop app.
It looks at how the app works, creates commands for common workflows, and turns them into an installable CLI.
Once that CLI exists, agents can operate the app through commands instead of screenshots and clicks.

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

CLI-Anything – Turn Any Desktop App into an Agent-Ready CLI Read More »

Vulture – Scan Python Projects for Dead Code

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

📅 Today’s Picks

Vulture – Scan Python Projects for Dead Code

Problem
Dead code creates maintenance cost without adding value to the current workflow. However, asking an LLM to find dead code can be expensive and inconsistent.
It only sees the context you provide, may invent usage patterns that do not exist, and can return different cleanup suggestions for the same project.
Solution
Vulture scans your code locally with static analysis, so the same input produces the same findings without token cost.
You can use Vulture for the repeatable dead-code scan, then bring in an LLM for the refactor.

Repomix – Turn GitHub Repos into AI-Ready Context

Problem
You might want an AI assistant to scan a repo so it can understand how the files work together.
But without controlled context, it may read generated files, old tests, docs, or unrelated modules before reaching the code that matters.
Solution
Repomix turns the repo into a prepared context file with filtering, compression, and token counts.
You decide what gets packed before sending it to the AI, so the prompt stays focused and cheaper.

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

Vulture – Scan Python Projects for Dead Code Read More »

Understand Anything – Turn Codebases into Knowledge Graphs

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

📅 Today’s Picks

gws – Give coding agents Drive access with one CLI

Problem
Claude, Codex, and other coding agents are comfortable with shell commands.
But asking them to automate Google Drive often means making them handle OAuth, API request bodies, pagination, uploads, and response parsing before they can do the actual task.
Solution
gws makes Google Workspace easier for agents to use by wrapping Drive tasks in predictable CLI commands.
Instead of building a custom Drive client, an agent can use gws to:

Inspect Drive folders and files
Upload generated files or reports
Handle pagination when Drive has many files
Read structured JSON output for downstream steps

Understand Anything – Turn Codebases into Knowledge Graphs

Problem
Have you ever opened a large codebase and wondered where to start? A common shortcut is to ask an LLM to explain files one by one.
But it is still hard to visualize how the pieces connect unless you spend time building your own graph, diagrams, and navigation interface.
Solution
Instead of manually building diagrams, Understand Anything creates a visual map of how your codebase fits together with a single slash command: /understand.
After running /understand, you can:

Explore files, functions, classes, and dependencies as an interactive knowledge graph
Find code by name or meaning with fuzzy and semantic search
Ask natural-language questions with /understand-chat
Generate an onboarding guide for new contributors

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

Understand Anything – Turn Codebases into Knowledge Graphs Read More »

PySpark – Write Reusable SQL Queries Without Hardcoding Values

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

📅 Today’s Picks

Git Revert vs Reset – Choose the Right Undo Method

Problem
Have you made a commit mistake? Every data scientist faces this situation, but choosing the wrong recovery method can create bigger problems than the original error. The key is understanding when to use git revert versus git reset.
Solution
The decision depends on one critical question: “Has this commit been shared?”
If YES, use git revert which adds new commits that reverse previous changes while preserving history for audit trails.
If NO, use git reset which removes commits entirely and rewrites the timeline for clean, readable history.
Both are powerful tools when used correctly.

📖 Dive deeper in Production Ready Data Science

PySpark – Write Reusable SQL Queries Without Hardcoding Values

Problem
Hardcoding values into PySpark SQL queries leads to messy, repetitive code that’s hard to maintain.
Solution
Instead, define parameterized SQL templates in Apache Spark. These templates let you insert dynamic variables into your queries, making them reusable, testable, and easier to manage across your codebase.

📖 View Full Article

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

PySpark – Write Reusable SQL Queries Without Hardcoding Values Read More »

PydanticAI – Control OpenAI Data Retention with openai_store

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

📅 Today’s Picks

PydanticAI: Control OpenAI Data Retention with openai_store

Problem
By default, OpenAI may retain your API request data for internal review and model improvement. For healthcare, finance, and legal applications, this default creates compliance risks you can’t afford.
Solution
PydanticAI provides the openai_store setting to explicitly disable data retention in one line.

📖 View Full Article

DuckDB – read an entire CSV folder in one line

Problem
Working with multiple CSV files often means writing extra code to load, combine, and process each file.
Solution
DuckDB makes this simpler by letting you query multiple CSV files directly with SQL and pattern matching, so you can analyze them in one efficient query.

📖 View Full Article

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

PydanticAI – Control OpenAI Data Retention with openai_store Read More »

dotenvx – Separate Dev, Staging, and Prod Configs Safely

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

📅 Today’s Picks

dotenvx – Separate Dev, Staging, and Prod Configs Safely

Problem
A single .env file is fine for a small project.
Once you add dev, staging, production, and CI, those settings need to be separated because each environment connects to different resources and should not share the same secrets.
Solution
dotenvx makes each environment explicit: load .env.production, .env.staging, or .env.ci directly with -f.
Because each file can be encrypted, you can commit the config safely without sharing the private keys across environments.

Ideogram 4 – Run Open-Weight Image Generation Locally

Problem
Most image generation tools are hosted behind an API. That works for quick experiments, but it limits control over cost, infrastructure, privacy, and customization.
Solution
Ideogram 4 changes that with an open-weight release. You can download the 9.3B parameter model files and run them on your own machine or server.
Key features:

Strong text rendering inside images, with a 0.97 score on an English text-accuracy benchmark
Structured JSON prompts instead of only free-form sentences
Control over subject, style, lighting, typography, and color palettes by hex code
Bounding-box coordinates for placing visual elements exactly where you want them

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

dotenvx – Separate Dev, Staging, and Prod Configs Safely Read More »

PP-OCRv6 – Extract Text from Receipts with Small OCR Models

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

📅 Today’s Picks

LM Studio – Pick Local Models That Fit Your Machine

Problem
Choosing a local LLM is not just about picking the smartest model.
You also need to know whether your machine can actually run it.
Model size, quantization, GPU memory, and system RAM all affect whether the model will load successfully.
Solution
LM Studio makes local model selection easier by showing the details that affect whether a model will run well.
What LM Studio shows:

Download options: choose among model variants by comparing format, quantization, and download size.
Fit signal: see whether the model is likely to fit your machine before downloading.
README: review model-specific instructions and benchmarks from the model page.

📖 View LM Studio

PP-OCRv6 – Extract Text from Receipts with Small OCR Models

Problem
When extracting text from messy documents, many teams now reach for large vision-language models.
But if you only need to find and read text, a smaller OCR-specific model may be faster and cheaper to run.
Solution
PP-OCRv6 is designed for reading text from images, rather than broad vision-language reasoning, so it can focus on text extraction efficiently.
It delivers strong text detection and recognition while staying much smaller than billion-parameter VLMs.
With tiny, small, and medium variants, you can start lightweight and switch to a larger model only when the extracted text needs better accuracy.

🧪 Run code

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

PP-OCRv6 – Extract Text from Receipts with Small OCR Models Read More »

Stop Hand-Tuning Prompts: Auto-Optimize an LLM Classifier with DSPy

Table of Contents

The Problem with Hand-Written Prompts
What Is DSPy?
Setup: Banking Query Classification
Define the Task with a Signature
Run the Task with DSPy Modules
Evaluate the Baseline
Optimize the Classifier with Examples
Compare Before vs. After
Save and Reuse the Optimized Program
Final Thoughts

The Problem with Hand-Written Prompts
Model choice matters, but prompt quality matters too. If the prompt is vague or hard to maintain, the classifier can still produce wrong labels.
A typical example is a prompt written as one string:
prompt = """
Classify this banking query as:
– card_arrival
– card_delivery_estimate
– card_not_working
– card_swallowed

Return only the label.

Query: My new card still has not arrived after two weeks.
Intent:
"""

This works for a simple demo, but real queries quickly reveal cases the prompt does not handle well.
For example:
My new card arrived, but it does not work at the ATM.

Because the prompt does not clarify this edge case, the model may focus on “new card” and return:

Outputcard_arrival

But the correct intent is:

Outputcard_not_working

You can patch the prompt with another rule, but that creates a new problem: every change needs to be retested. A fix for one visible mistake can hide new failures elsewhere.
Without a dataset and metric, you cannot tell whether the classifier improved overall.
DSPy replaces manual prompt tweaking with four repeatable steps:

Define the task as a program.
Evaluate the program with examples and a metric.
Let an optimizer improve the program.
Compare the score before and after.

This article walks through that loop by building a small banking intent classifier.

💻 Get the Code: Open the notebook in Google Colab to run it in your browser, or grab the source 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 DSPy?
DSPy is a Python framework for programming LLM workflows instead of hand-writing prompts.
It breaks an LLM workflow into explicit parts:

Signatures define the inputs and outputs.
Modules run the task with strategies such as Predict or ChainOfThought.
Metrics score the outputs.
Optimizers improve the program using examples and metrics.

This structure makes prompt engineering measurable. You can compare versions, optimize against a metric, and reuse the improved program.
Manual prompt DSPy program
————- ————
Task description —> Signature
Prompting style —> Module
Manual inspection —> Metric
Prompt tweaking —> Optimizer

Setup: Banking Query Classification
Install the libraries used in this tutorial:
pip install -U dspy pandas python-dotenv

This article uses dspy v3.2.1, pandas v2.3.1, and python-dotenv v1.1.1.
This tutorial uses OpenAI’s gpt-4o-mini through DSPy’s language model interface. Store your API key in a .env file:
OPENAI_API_KEY=your-openai-api-key

Then load the environment variables and configure DSPy:
from typing import Literal

import dspy
import pandas as pd
from dotenv import load_dotenv

load_dotenv()

lm = dspy.LM("openai/gpt-4o-mini")
dspy.configure(lm=lm)

We will use BANKING77, a dataset of banking support questions labeled with customer intents. To keep loading simple, this tutorial reads the raw CSV files from the original PolyAI repository.
TRAIN_URL = "https://raw.githubusercontent.com/PolyAI-LDN/task-specific-datasets/master/banking_data/train.csv"
TEST_URL = "https://raw.githubusercontent.com/PolyAI-LDN/task-specific-datasets/master/banking_data/test.csv"

train_df = pd.read_csv(TRAIN_URL)
test_df = pd.read_csv(TEST_URL)

print(train_df.head())

Output text category
0 I am still waiting on my card? card_arrival
1 What can I do if my card still hasn't arrived … card_arrival
2 I have been waiting over a week. Is the card s… card_arrival
3 Can I track my card while it is in the process… card_arrival
4 How do I know if I will get my card, or if it … card_arrival

To keep the example small, we will use four card-support intents instead of all 77 labels. The subset is still useful because card_arrival and card_delivery_estimate are similar enough to create meaningful mistakes.
INTENTS = [
"card_arrival",
"card_delivery_estimate",
"card_not_working",
"card_swallowed",
]

def sample_intents(data: pd.DataFrame, examples_per_intent: int) -> pd.DataFrame:
return (
data[data["category"].isin(INTENTS)]
.groupby("category", group_keys=False)
.sample(n=examples_per_intent, random_state=42)
.reset_index(drop=True)
)

train_sample = sample_intents(train_df, examples_per_intent=8)
dev_sample = sample_intents(test_df, examples_per_intent=10)

print(train_sample["category"].value_counts())

Outputcategory
card_arrival 8
card_delivery_estimate 8
card_not_working 8
card_swallowed 8
Name: count, dtype: int64

Before evaluation, prepare the data for DSPy:

Store each query-label pair as a dspy.Example.
Mark query as the input field with .with_inputs("query").
Keep intent as the target label DSPy will compare against the prediction.

def to_dspy_examples(data: pd.DataFrame) -> list[dspy.Example]:
return [
dspy.Example(query=row.text, intent=row.category).with_inputs("query")
for row in data.itertuples(index=False)
]

trainset = to_dspy_examples(train_sample)
devset = to_dspy_examples(dev_sample)

Let’s inspect one row to confirm that only query is marked as model input:
example = trainset[0]

print("Full example:")
print(example)

print("\nWhat the model receives:")
print(example.inputs())

print("\nExpected answer kept for scoring:")
print(example.intent)

OutputFull example:
Example({'query': 'If I ordered my new card last week, how much longer should I wait to receive it?', 'intent': 'card_arrival'}) (input_keys={'query'})

What the model receives:
Example({'query': 'If I ordered my new card last week, how much longer should I wait to receive it?'}) (input_keys={'query'})

Expected answer kept for scoring:
card_arrival

Notice that the full example contains both query and intent, but example.inputs() contains only query. This prevents the model from seeing the expected answer during prediction.
Define the Task with a Signature
A DSPy signature makes the task explicit. Instead of hiding the task inside a prompt string, you define the input fields, output fields, and output constraints in code.
The signature below defines the task schema:

Input field: query
Output field: intent
Allowed outputs: card_arrival, card_delivery_estimate, card_not_working, card_swallowed
Field descriptions: short hints DSPy can use when prompting the model

class ClassifyBankingIntent(dspy.Signature):
"""Classify a banking support query into one of the allowed intents."""

query: str = dspy.InputField(desc="Customer support query")
intent: Literal[
"card_arrival",
"card_delivery_estimate",
"card_not_working",
"card_swallowed",
] = dspy.OutputField(desc="Predicted banking intent")

The typed intent field is how DSPy keeps outputs within the allowed labels. For a dedicated way to enforce and validate typed LLM outputs with Python types, see Enforce Structured Outputs from LLMs with PydanticAI.
Run the Task with DSPy Modules
A DSPy module turns the signature into callable code.
Different modules run the same task in different ways:

Predict returns the output directly.
ChainOfThought adds a reasoning step before the output.
ReAct can call tools before answering.

Because they can share the same signature, you can switch strategies without redefining the task.
Predict: Direct Prediction
Predict is the simplest module. It asks the model to return the output directly.
predict_classifier = dspy.Predict(ClassifyBankingIntent)

prediction = predict_classifier(
query="The ATM kept my card and did not return it. How do I get it back?"
)

print(f'Intent: {prediction.intent}')

OutputIntent: card_swallowed

This matches the query and stays within the allowed intent labels.
ChainOfThought: Reason Before Predicting
ChainOfThought keeps the same input and output fields, but adds a reasoning step before the prediction:
cot_classifier = dspy.ChainOfThought(ClassifyBankingIntent)

prediction = cot_classifier(
query="The ATM kept my card and did not return it. How do I get it back?"
)

print(f'Reasoning: {prediction.reasoning}')
print(f'Intent: {prediction.intent}')

OutputReasoning: The customer's query indicates that their card was not returned by an ATM, which suggests that the card was likely swallowed by the machine. The customer is seeking information on how to retrieve their card, which aligns with the intent of a card being swallowed by the ATM.
Intent: card_swallowed

Unlike Predict, ChainOfThought exposes the reasoning before the final label. The predicted intent is still card_swallowed.
ReAct: Use Tools Before Answering
ReAct is useful when the model needs to use tools before answering. In the example below:

lookup_transfer_status is a Python tool that retrieves transfer details.
dspy.ReAct decides when to call that tool and uses the result to answer.

def lookup_transfer_status(reference_id: str) -> str:
"""Return transfer status for a reference ID."""
transfers = {
"TRX-1042": "Completed on March 12. Recipient bank confirmed receipt.",
"TRX-2048": "Pending review. Expected completion within 1 business day.",
}
return transfers.get(reference_id, "Transfer reference not found.")

react_agent = dspy.ReAct(
signature="query -> answer", # receive query, return answer
tools=[lookup_transfer_status], # allow transfer lookup
max_iters=3, # stop after 3 iterations
)

response = react_agent(
query="Did transfer TRX-1042 reach the recipient?"
)

print(response.answer)

OutputYes, transfer TRX-1042 has reached the recipient.

Notice that the model answers using the lookup result instead of guessing from the prompt alone.
Now that the modules are defined, the next step is to score the classifier versions and optimize one of them.
Evaluate the Baseline
Before optimizing the classifier, we need to measure the baseline. Here, the metric is simple: a prediction is correct when the predicted intent matches the expected label.
def intent_exact_match(example: dspy.Example, prediction: dspy.Prediction, trace=None) -> bool:
return example.intent == prediction.intent

Now create a DSPy evaluator:
evaluate = dspy.Evaluate(
devset=devset, # examples to score
metric=intent_exact_match, # scoring function
num_threads=4, # parallel model calls
display_progress=True, # show progress bar
display_table=5, # show sample predictions
)

Use the same evaluator to compare Predict and ChainOfThought on the dev set:
predict_score = evaluate(predict_classifier)
print(f"Predict score: {predict_score.score}")

Because display_table=5 is set, the evaluator prints a sample of predictions before the score:

query
example_intent
pred_intent
intent_exact_match

My card still hasn’t arrived after 2 weeks. Is it lost?
card_arrival
card_arrival
✅ True

I’ve been waiting longer than expected for my card.
card_arrival
card_delivery_estimate
❌ False

I have been waiting longer than expected for my bank card, could you provide information on when it will arrive?
card_arrival
card_delivery_estimate
❌ False

I think something went wrong with my card delivery as I haven’t received it yet.
card_arrival
card_delivery_estimate
❌ False

My card has not arrived yet.
card_arrival
card_arrival
✅ True

… 35 more rows not displayed …

OutputPredict score: 77.5

Run the same evaluator on ChainOfThought:
cot_score = evaluate(cot_classifier)
print(f"ChainOfThought score: {cot_score.score}")

query
example_intent
pred_intent
intent_exact_match

My card still hasn’t arrived after 2 weeks. Is it lost?
card_arrival
card_arrival
✅ True

I’ve been waiting longer than expected for my card.
card_arrival
card_arrival
✅ True

I have been waiting longer than expected for my bank card, could you provide information on when it will arrive?
card_arrival
card_delivery_estimate
❌ False

I think something went wrong with my card delivery as I haven’t received it yet.
card_arrival
card_delivery_estimate
❌ False

My card has not arrived yet.
card_arrival
card_arrival
✅ True

… 35 more rows not displayed …

OutputChainOfThought score: 80.0

The displayed rows make the comparison easier to inspect: you can see which examples matched the expected intent and which ones failed. In this run, ChainOfThought scores higher because the reasoning step helps with some ambiguous delivery queries.
Optimize the Classifier with Examples
Once the metric shows where the baseline fails, DSPy can use training examples to search for a better version of the program.
DSPy provides several optimizer options depending on how much search you want:

BootstrapFewShot improves the prompt by adding better examples.
MIPROv2 improves the prompt by tuning both instructions and examples.
GEPA improves the prompt by using feedback from previous attempts.

This article uses BootstrapFewShot because it is the simplest optimizer for this setup. It uses the training set and metric to choose examples that make the prompt stronger.
Few-shot examples are useful when the label name alone is not enough.
For example, card_arrival could sound like a successful delivery, but this example shows what it means in the dataset:
Query: My card has not arrived yet.
Intent: card_arrival

The label refers to questions or problems about card delivery. BootstrapFewShot helps find examples like this and add them to the prompt:

from dspy.teleprompt import BootstrapFewShot

optimizer = BootstrapFewShot(
metric=intent_exact_match, # score each candidate
max_bootstrapped_demos=4, # generated examples to keep
max_labeled_demos=8, # labeled examples to include
max_rounds=1, # bootstrap attempts per example
)

optimized_classifier = optimizer.compile(
student=cot_classifier,
trainset=trainset,
)

Inspect the examples added to the optimized prompt:
predictor = optimized_classifier.predictors()[0]

bootstrapped_demos = [
demo for demo in predictor.demos
if getattr(demo, "augmented", False)
]

for i, demo in enumerate(bootstrapped_demos, start=1):
print(f"Bootstrapped demo {i}")
print("Query:", demo.query)
print("Reasoning:", demo.reasoning)
print("Intent:", demo.intent)
print()

OutputBootstrapped demo 1
Query: If I ordered my new card last week, how much longer should I wait to receive it?
Reasoning: The query asks about the expected waiting time for a newly ordered card, which suggests that the customer is inquiring about when it will arrive.
Intent: card_arrival

Bootstrapped demo 2
Query: Is there a reason my new card hasn't arrived?
Reasoning: The query is asking about the status of a new card that has not been received yet, indicating concern over the arrival of the card.
Intent: card_arrival

Bootstrapped demo 3
Query: I still haven't gotten my new card. When will it get here?
Reasoning: The query expresses concern about not receiving a new card yet and asks for information on its arrival. This indicates a focus on the status of the card's delivery.
Intent: card_arrival

Bootstrapped demo 4
Query: My card hasn't arrived in the mail yet. I ordered it two weeks ago. What can I do?
Reasoning: The customer is inquiring about the status of their card, which they have not received yet after ordering it two weeks ago. This indicates they are concerned about the arrival of their card.
Intent: card_arrival

The demos teach a consistent pattern: when the customer asks whether a new card has arrived, where it is, or what to do after waiting, the expected intent is card_arrival.
Compare Before vs. After
Evaluate the optimized classifier on the same dev set:
optimized_score = evaluate(optimized_classifier)

scores = pd.DataFrame(
[
{"program": "Predict", "score": predict_score.score},
{"program": "ChainOfThought", "score": cot_score.score},
{"program": "BootstrapFewShot + ChainOfThought", "score": optimized_score.score},
]
)

print(scores)

Output program score
0 Predict 77.5
1 ChainOfThought 80.0
2 BootstrapFewShot + ChainOfThought 87.5

Nice! The optimized classifier performs best in this run, improving from 80.0 with ChainOfThought to 87.5 after adding optimized few-shot examples.
You can also inspect individual misses to understand what still fails:
for example in devset:
prediction = optimized_classifier(query=example.query)

if prediction.intent != example.intent:
print("Query:", example.query)
print("Expected:", example.intent)
print("Predicted:", prediction.intent)
print()

OutputQuery: Is there tracking info available?
Expected: card_arrival
Predicted: card_delivery_estimate

Query: Where is the tracking number for the card you sent me?
Expected: card_arrival
Predicted: card_delivery_estimate

Query: Do you know if there is a tracking number for the new card you sent me?
Expected: card_arrival
Predicted: card_delivery_estimate

Query: I'm just wondering when my card will get here.
Expected: card_delivery_estimate
Predicted: card_arrival

Query: I am waiting for my card to arrive.
Expected: card_delivery_estimate
Predicted: card_arrival

Most misses are between card_arrival and card_delivery_estimate. That makes sense: both intents mention waiting for a card, tracking, or delivery timing.
To improve this, we could add more labeled examples that separate “my card has not arrived” from “how long does delivery take?”
Save and Reuse the Optimized Program
Optimization can take time and spend LLM tokens, so you do not want to run it every time you classify a query. Instead, save the optimized classifier once so it can be loaded later:
save_path = "optimized_banking_classifier.json"
optimized_classifier.save(save_path)

When you need the classifier again, rebuild the same DSPy module and load the saved file:
loaded_classifier = dspy.ChainOfThought(ClassifyBankingIntent)
loaded_classifier.load(path=save_path)

prediction = loaded_classifier(
query="I have been waiting two weeks and my new card still has not arrived."
)

print(prediction.intent)

Outputcard_arrival

This skips optimization and reuses the same saved prompt, making inference faster and reproducible.
Final Thoughts
DSPy is worth using when an LLM workflow will run repeatedly and quality matters. It is especially useful when you have:

Labeled examples
A metric
Several prompt or module versions to compare
A task that will evolve over time

It is probably too much for one-off prompts, quick brainstorming, or tasks where you do not have examples to evaluate against.
In this article, we followed the core DSPy workflow:

Define the task
Run the task with different strategies
Evaluate each version
Optimize the workflow with examples
Save the optimized result for reuse

Once this workflow is familiar, you can extend it with larger dev sets, more intent labels, and richer metrics. For more advanced optimization, explore DSPy’s MIPROv2 and GEPA docs.
Related Tutorials

Structured Output Tools for LLMs: Instructor, PydanticAI, LangChain, Outlines, and Guidance Compared: Compares libraries that force LLMs to return valid, typed outputs, the same problem DSPy signatures solve.
Build Production-Ready RAG Systems with MLflow Quality Metrics: Measures LLM output quality with metrics, complementing DSPy’s evaluate-and-optimize loop.

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 Hand-Tuning Prompts: Auto-Optimize an LLM Classifier with DSPy Read More »

Polars 1.41 – Speed Up Wide Parquet Scans Without Code Changes

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

📅 Today’s Picks

LiteLLM – One interface for OpenAI, Anthropic, and Gemini

Problem
Frameworks like LangChain and LlamaIndex are useful when you need chains, agents, retrieval, memory, or orchestration.
But if you only need to call different providers through the same interface, you may not want to restructure your app around a full LLM framework.
Solution
LiteLLM solves this as a lightweight interface layer.
You can keep one completion() call across 100+ providers, then switch models by changing only the model string.

📖 View Full Article

Polars 1.41 – Speed Up Wide Parquet Scans Without Code Changes

Problem
scan_parquet is Polars’ lazy way to read a Parquet file, allowing it to optimize the query before loading data.
Before the query runs, Polars still needs to decode the Parquet footer to understand the schema, row groups, and column statistics. For very wide files, that setup step can take noticeable time.
Solution
Polars 1.41 makes scan_parquet faster by replacing the old metadata decoder with one built specifically for Parquet files.
In the Polars 1.41 release benchmark, footer decoding was up to 3.29x faster on a 10,000-column file.

📖 Read the release

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

Polars 1.41 – Speed Up Wide Parquet Scans Without Code Changes Read More »

Add Long-Term Memory to LLM Applications with Mem0

Table of Contents

Introduction
Vector Search vs Memory
Setup
Build a Stateless Support Bot
Test the Stateless Support Bot
Store Support Interactions in Mem0
Retrieve Memories Before Responding
Compare Stateless vs Memory-Aware Responses
Add a Status Update
Manage Stored Memories
Final Thoughts

Introduction
LLM applications are often stateless by default. Each prompt only knows what you include at that moment, so useful context from earlier interactions can disappear between sessions.
For simple questions, that is often enough. For returning users, it can lead to repeated explanations, missing preferences, and less helpful responses.
Mem0 helps by extracting important facts from conversations, storing them by user, and retrieving relevant memories when needed.
To see how Mem0 works, we will build a simple e-commerce support workflow, first without memory and then with Mem0, so you can compare how stored context changes the response.

💻 Get the Code: Open the notebook in Google Colab to run it in your browser, or grab the source 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

Vector Search vs Memory
A vector database is a good starting point for retrieval, but memory requires more than finding similar text. You still need a way to decide which details are worth saving for future interactions.
In this customer support example, the vector database may retrieve the entire message, including the coffee detail even though it is unrelated to the delayed order:
My order #4821 still has not arrived. I contacted support last week and got no update. Also, I was checking this while making coffee this morning.

A memory layer should keep only the support-relevant facts:
Order #4821 is delayed, and the customer contacted support last week without receiving an update.

To get from raw retrieval to useful memory, your application still needs logic for:

Deciding which details from the message should be remembered for future replies.
Making sure each memory is tied to the right user or conversation.
Deciding how to handle newer memories that conflict with or supersede earlier ones.
Formatting retrieved messages into prompt-ready context.

You can implement this yourself, but the extra extraction and memory-management logic adds up. Mem0 packages that workflow behind a simpler memory API, which we will use in the next section.

If vector search is new to you, see our Pinecone vector database tutorial for a practical introduction to semantic search and retrieval.

Setup
Install the libraries used in this tutorial:

mem0ai: Adds long-term memory for storing and retrieving user context.
litellm: Provides a unified interface for calling LLM providers.
python-dotenv: Loads API keys and configuration from a .env file.

pip install mem0ai litellm python-dotenv

This article uses mem0ai v2.0.4, litellm v1.87.0, and python-dotenv v1.2.2.
Since this tutorial uses OpenAI’s GPT-4o-mini, store your OPENAI_API_KEY in a .env file in your project folder so Mem0 and LiteLLM can access it.
OPENAI_API_KEY=your-openai-api-key

Start by loading the environment variables and imports used throughout the tutorial:
from dotenv import load_dotenv
from litellm import completion
from mem0 import Memory

load_dotenv()

Next, define a helper that sends a list of chat messages to GPT-4o-mini through LiteLLM and returns only the generated text:
def ask_model(messages: list[dict[str, str]]) -> str:
response = completion(model="openai/gpt-4o-mini", messages=messages)
return response.choices[0].message.content

To use another model, replace "openai/gpt-4o-mini" with a model name from the LiteLLM provider docs.
Finally, configure Mem0 with an LLM for extracting memories from messages. This example uses GPT-4o-mini, but Mem0 and LiteLLM do not have to use the same model:
memory = Memory.from_config(
{
"llm": {
"provider": "openai",
"config": {"model": "gpt-4o-mini"},
},
}
)

Build a Stateless Support Bot
First, create a support bot with no memory. It only sees the current message.
SYSTEM_PROMPT = (
"You are a helpful e-commerce customer support agent. "
"Be polite, concise, and practical."
)

def ask_stateless_bot(question: str) -> str:
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": question},
]
return ask_model(messages)

The customer opens a support chat about a delayed order. We will also include an irrelevant detail in the message, so that we can later show that Mem0 can focus on the useful support facts:
initial_message = (
"My order #4821 still has not arrived. "
"I contacted support last week and got no update. "
"Also, I was checking this while making coffee this morning." # irrelevant detail
)

print(ask_stateless_bot(initial_message))

OutputI'm sorry to hear that your order #4821 hasn't arrived yet. I understand how frustrating this can be. Let me assist you by checking the status for you. Please give me a moment.

The reply is reasonable for a first message. The problem shows up when the customer returns later.
Test the Stateless Support Bot
Let’s see how the bot responds to a follow-up question without passing the earlier conversation:
follow_up = "Hi, any update on my delayed order?"

print(ask_stateless_bot(follow_up))

OutputI’d be happy to help with your order. Could you please provide me with your order number? This will help me look up the status for you.

The response is polite, but it loses the context that matters most: the order number, the prior support contact, and the customer’s frustration.
Store Support Interactions in Mem0
To preserve the missing order context, add Mem0 as a memory layer. Store the customer message under a stable customer_id so it can be retrieved in later interactions.
customer_id = "cust_4821"
order_id = "4821"
issue_type = "shipping"
sentiment = "frustrated"

memory_extraction_prompt = (
"Extract only useful customer-support facts. Ignore unimportant information."
)

add_result = memory.add(
messages=[{"role": "user", "content": initial_message}],
user_id=customer_id,
metadata={
"issue_type": issue_type,
"sentiment": sentiment,
"order_id": order_id,
},
prompt=memory_extraction_prompt,
)

print(add_result)

Output{
"results": [
{
"id": "8d4cf548-683c-49cf-8d68-44d431155741",
"memory": (
"User's order #4821 has not arrived as of June 3, 2026, "
"and they contacted support last week but received no update."
),
"event": "ADD",
}
]
}

Note that the saved memory keeps the support-relevant details: the order number, the delayed delivery, and the prior support contact. It does not include the unrelated coffee detail from the original message.
Raw customer message
|
v
LLM-based extraction step
|
+–> Save: order #4821 has not arrived
+–> Save: customer contacted support last week
+–> Drop: customer was making coffee

This has a few practical benefits:

Cleaner retrieval: Future searches return useful support context instead of unrelated conversation details.
Lower API cost: Passing compact memories instead of noisy chat history can reduce the number of tokens sent to the model.
Better privacy boundaries: Incidental personal details are less likely to be retained when they are not needed.

If you do not want Mem0 to infer or rewrite memories, set infer=False. In that mode, Mem0 stores the provided message directly instead of extracting selected facts from it.
Retrieve Memories Before Responding
Before answering a new message, define a helper that searches Mem0 for memories related to the current question and limits the search to the current customer_id:
def retrieve_customer_memories(question: str, customer_id: str) -> dict:
return memory.search(
query=question,
filters={"user_id": customer_id},
top_k=3,
)

for item in retrieve_customer_memories(follow_up, customer_id)["results"]:
print(item["memory"])

OutputUser's order #4821 has not arrived and they contacted support last week but received no update.

Next, convert the dictionary returned by Mem0 into plain text so it can be inserted into the system prompt:
def format_memories(search_result: dict) -> str:
memories = search_result["results"]
if not memories:
return "No relevant memories found."

return "\n".join(f"- {item['memory']}" for item in memories)

print(format_memories(retrieve_customer_memories(follow_up, customer_id)))

Output- User's order #4821 has not arrived and they contacted support last week but received no update.

Compare Stateless vs Memory-Aware Responses
Now we are ready to create a memory-aware support bot. The function below does three things:

Retrieves relevant customer memories from Mem0.
Adds those memories to the system prompt.
Sends the updated prompt to the model.

def ask_memory_aware_bot(question: str, customer_id: str) -> str:
customer_memories = format_memories(
retrieve_customer_memories(question, customer_id)
)

messages = [
{
"role": "system",
"content": (
f"{SYSTEM_PROMPT}\n\n"
f"Relevant customer memories:\n{customer_memories}"
),
},
{"role": "user", "content": question},
]
return ask_model(messages)

Ask the same follow-up again:
print(ask_memory_aware_bot(follow_up, customer_id))

OutputThanks for checking back on order #4821. I can see it is still delayed and that you contacted us last week without an update. I am escalating this with shipping now and will email you a new delivery estimate today.

This response now uses the stored memory. It remembers the order number, the earlier support contact, and the unresolved shipping issue without asking the customer to repeat them.
Add a Status Update
Next, add a new message that changes the order status. This lets us see how the memory-aware bot handles newer information:
status_update_result = memory.add(
messages=[{"role": "user", "content": "Order #4821 arrived today."}],
user_id=customer_id,
metadata={"order_id": order_id, "issue_type": issue_type},
)

print(status_update_result)

Output{
"results": [
{
"id": "1fb682a4-9da2-4a7b-a174-9d77c015c1d1",
"memory": (
"User's order #4821 arrived on June 3, 2026, after "
"previously not arriving and contacting support for an update."
),
"event": "ADD",
}
]
}

Mem0 stores this as a new memory. Ask the same follow-up again:
print(ask_memory_aware_bot(follow_up, customer_id))

OutputHello! I see that your order #4821 has actually arrived on June 3, 2026. If you need any further assistance or have questions about your order, feel free to let me know!

The answer changes because the model now receives both the earlier delay and the newer arrival status in the retrieved memories.
Manage Stored Memories
When memory affects model responses, you need a way to inspect what was stored. Use get_all() to see the memories Mem0 has saved for a customer:
all_memories = memory.get_all(filters={"user_id": customer_id})

for item in all_memories["results"]:
print(item["id"], "-", item["memory"])

Output8d4cf548-683c-49cf-8d68-44d431155741 – User's order #4821 has not arrived and they contacted support last week but received no update.
1fb682a4-9da2-4a7b-a174-9d77c015c1d1 – User's order #4821 arrived on June 3, 2026, after previously not arriving and contacting support for an update.

If a memory is wrong or a ticket is resolved, delete it by ID:
memory_id = all_memories["results"][0]["id"]
memory.delete(memory_id)

Output{'message': 'Memory deleted successfully!'}

You can also delete all memories for a user at once using delete_all(). Be careful because this permanently removes every stored memory for that user:
# Irreversible: deletes all memories for this user
memory.delete_all(user_id=customer_id)

Output{'message': 'Memories deleted successfully!'}

Final Thoughts
Stateless LLM applications are easy to build, but they only know what is included in the current prompt.
Mem0 adds a memory layer for applications that need continuity across sessions. The same pattern can support customer support bots, personal assistants, tutoring apps, healthcare intake tools, CRM workflows, and onboarding assistants.
With Mem0, applications can save important details from past interactions and retrieve the most relevant context for future responses.
Use memory when you don’t want returning users to have to repeat important details. Skip it when each request is self-contained or when storing user history adds unnecessary complexity.
Related Tutorials

Implement Semantic Search in Postgres Using pgvector and Ollama: Learn how to store embeddings in Postgres and retrieve semantically similar records with pgvector.
Enforce Structured Outputs from LLMs with PydanticAI: Learn how to validate extracted LLM outputs with typed Pydantic 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

Add Long-Term Memory to LLM Applications with Mem0 Read More »

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran