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

docker

Auto-created tag for docker

Build AI Agents in YAML with docker-agent

Table of Contents

Introduction
What Is docker-agent?
Setup
Create the Agent
Swap the Model
Reuse Instructions Across Questions
Add Variants with Flavors
Run Different Agents from One File
Test the Agent
Share the Agent
Final Thoughts

Introduction
There are plenty of frameworks for building AI agents, such as LangChain or LlamaIndex. But as you add models, tools, and features, the agent quickly grows into a lot of code to maintain. More code means more places for mistakes when you need to make a change.
docker-agent keeps the entire workflow in one YAML file. With this approach, you can mix and match models, tools, and features, and see how the whole agent is set up at a glance.
In this article, you will learn nice features of docker-agent by building an agent that answers questions about Polars.

💻 Get the Code: The agent configs and eval files are on GitHub.

What Is docker-agent?
docker-agent is Docker’s open-source tool for building and running AI agents.
docker-agent does for AI agents what Docker did for apps. Instead of setting up an environment and writing code, you describe the agent in one YAML file and run it with one command.

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 docker-agent with Homebrew, or use the docker agent command that ships with Docker Desktop 4.63 and later:
brew install docker-agent

The agent will search the Polars user guide and answer questions about it.
The project folder looks like this:
docker-agent-docs-qa/
└── docs/polars/ # 72 markdown files the agent will search

Create the Agent
To create the agent, define its model, instructions, and tools in a YAML file called embeddings.yaml. Start with the agents section.
agents:
root: # the agent that receives your message
model: openai/gpt-5-mini
description: Answers questions about Polars from the user guide
instruction: |
You answer questions about the Polars DataFrame library.
Always search the knowledge base before answering.
Answer only from what the search returns.
End with a "Sources:" list of the file paths you used, relative to docs/polars.

To let the agent search the docs, give it a rag tool and tell the tool which folder to search.
agents:
root:
…
toolsets:
– type: rag
ref: polars_docs # use the source defined below

rag:
polars_docs: # the name the ref points to
tool:
description: The Polars user guide
docs: [./docs/polars] # what to search
strategies: # how to search
– type: chunked-embeddings # split each file into chunks and embed them
embedding_model: openai/text-embedding-3-small
vector_dimensions: 1536 # number of values per vector

RAG setups usually need a vector database and a separate indexing step. docker-agent handles both for you. It stores the vectors in a local SQLite file, indexes the folder the first time the agent starts, and re-indexes files when they change.
rag is one of 30 built-in toolsets. Here are a few others that are useful:

shell: run shell commands, such as a Python script or duckdb
filesystem: read, write, and search files in a folder
fetch: read web pages and online docs
mcp: call external services like GitHub or a database through MCP
memory: remember facts across sessions

After the YAML file is created, ask the agent a question. The –exec flag runs the agent without opening the interactive terminal UI.
docker agent run –exec embeddings.yaml "How do I read a Parquet file without loading it all into memory?"

The output shows the search the agent made, followed by its answer. The search results and the model’s reasoning summary are trimmed here:

OutputCalling polars_docs(query: "read Parquet without loading all into memory scan_parquet
scan_parquet streaming lazy read_parquet memory efficient 'scan_parquet' 'read_parquet'
'scan' 'Parquet'")

Use a lazy scan and streaming collect so Polars parses and processes the file in
batches instead of materializing everything in RAM.

– Use pl.scan_parquet(…) (returns a LazyFrame) instead of pl.read_parquet(…).
Scanning delays parsing and enables column/row pruning via the optimizer
(projection & predicate pushdown).
– Apply selects/filters on the LazyFrame so the reader can skip unnecessary
columns/rows.
– When collecting, use streaming execution to process in batches:
.collect(engine="streaming").

Sources:
– io/parquet.md
– lazy/sources_sinks.md
– lazy/execution.md

The answer is correct, and every claim traces back to a file you can open.
To ask another question, run the same command with a new question without changing the YAML file.
docker agent run –exec embeddings.yaml "When should I use join_asof?"

Swap the Model
To try a cheaper model without committing to it, you can simply pass –model for a single run.
embeddings.yaml –model what runs
┌───────────────────┐ ┌───────────────────┐
│ model: gpt-5-mini │ ── gpt-5-nano ──> │ model: gpt-5-nano │
│ instruction: … │ │ instruction: … │
│ toolsets: rag │ │ toolsets: rag │
└───────────────────┘ └───────────────────┘
unchanged this run only

For example, this runs the same question on gpt-5-nano.
docker agent run –exec embeddings.yaml –model openai/gpt-5-nano \
"How do I read a Parquet file without loading it all into memory?"

Output- Use scan_parquet to read lazily. This returns a LazyFrame and does not parse the
data into memory until you collect.
…
Sources:
io/parquet.md

This is very nice for several reasons:

You can quickly try different models and compare their answers
Because the YAML file does not change during the experiment, your teammates are not affected
Once you like a model, you can edit the YAML file to use it permanently

Reuse Instructions Across Questions
You might want to vary the instructions based on the context, such as the audience, the length, or the tone.
With docker-agent, you can write different instructions in separate files, then pick one with the –prompt-file flag.
For example, you can create a pandas-users.md file with the instructions for pandas users and a sql-users.md file with the instructions for SQL users.
"How do I read a Parquet file without loading it all into memory?"
│
┌───────────────────┴───────────────────┐
▼ ▼
–prompt-file pandas-users.md –prompt-file sql-users.md
│ │
▼ ▼
Pandas: read_parquet() loads SQL: SELECT * FROM
the file into memory read_parquet('data.parquet')

Let’s try the pandas-users.md file first. Start by creating the file.
The reader knows pandas. Show the pandas equivalent next to each Polars answer.
Keep each answer under 8 lines.

Then start an interactive chat with the file passed to –prompt-file.
docker agent run embeddings.yaml –prompt-file pandas-users.md

Now every answer follows the instructions in pandas-users.md, even though the questions never mention pandas.
> How do I read a Parquet file without loading it all into memory?

Polars: use scan_parquet("file.parquet") to get a LazyFrame (parsing is delayed).
Collect with streaming to process in batches: lf.collect(engine="streaming").
…
Pandas: read_parquet("file.parquet") loads the file into memory (no built-in
lazy/streaming scan).

If your audience knows SQL instead, create a prompt file called sql-users.md.
The reader knows SQL. Show the Polars SQL equivalent next to each Polars answer.
Keep each answer under 8 lines.

Start a chat with that file instead.
docker agent run embeddings.yaml –prompt-file sql-users.md

The same question now gets a SQL answer instead of a pandas one.
> How do I read a Parquet file without loading it all into memory?

– Polars: Use lazy scanning so the file isn't parsed upfront:
lf = pl.scan_parquet("data.parquet"), which returns a LazyFrame.
SQL: SELECT * FROM read_parquet('data.parquet');
– Polars: Push down projections/filters so only needed columns/rows are read.
SQL: SELECT col1, col2 FROM read_parquet('data.parquet') WHERE …;
…

Add Variants with Flavors
Sometimes you want more than one version of an agent, such as one with a different search method or a different model. It is redundant to write another YAML file for each version with most of the settings staying the same.
With docker-agent, you can add a flavor to the same file. A flavor lists only the settings that change, and everything else stays the same.
–flavor hybrid
off on
│ │
▼ ▼
┌──────────────────┐ ┌──────────────────┐
│ embedding search │ │ embedding search │
│ │ │ + keyword search │
└──────────────────┘ └──────────────────┘
base config base + hybrid

In this example, we add a flavor called hybrid that adds keyword search to the existing embedding search strategy.
# embeddings.yaml
agents:
root: …

rag:
polars_docs:
…
strategies:
– type: chunked-embeddings # embedding search

flavors: # new section at the bottom of the file
hybrid:
rag:
polars_docs:
strategies+: # keep chunked-embeddings and add bm25
– type: bm25 # keyword search
results:
fusion:
strategy: rrf # merge the keyword and embedding results
k: 60
deduplicate: true
limit: 5

To use a flavor, pass its name with –flavor:
# embedding search only
docker agent run embeddings.yaml

# embedding search + keyword search
docker agent run embeddings.yaml –flavor hybrid

Here is what the config looks like after docker-agent applies the hybrid flavor.
rag:
polars_docs:
…
strategies:
– type: chunked-embeddings # from the base file
– type: bm25 # from hybrid
results:
fusion:
strategy: rrf # from hybrid
…

To see how this is useful, ask about SQLContext, a class name that appears in the docs. Without the flavor, the agent uses the embedding search strategy and finds nothing.
docker agent run –exec embeddings.yaml "What is SQLContext?"

OutputCalling polars_docs(query: "SQLContext")
Calling polars_docs(query: "SQL")

I searched the Polars documentation for "SQLContext" (and for "SQL") but found
no matching documents, so I cannot provide a definition from the docs.

With the hybrid flavor, every search runs both strategies. Keyword search finds the exact name, so the right page comes back.
docker agent run –exec embeddings.yaml –flavor hybrid "What is SQLContext?"

OutputCalling polars_docs(query: "SQLContext")

SQLContext is the Polars object that manages SQL queries…

Sources:
– sql/intro.md

Run Different Agents from One File
Sometimes you might want to have multiple agents for different purposes. For example, you might want to have a small model for answering questions and a stronger model for reviewing code.
docker-agent lets you add more agents to the same file. They can share tools already defined there, so you don’t need to repeat the configuration.
root reviewer
┌───────────────────┐ ┌───────────────────┐
│ gpt-5-mini │ │ gpt-5 │
│ answers questions │ │ reviews code │
└─────────┬─────────┘ └─────────┬─────────┘
│ │
└──────────────┐ ┌───────────────┘
▼ ▼
┌─────────────────┐
│ polars_docs │
│ defined once │
└─────────────────┘

In the code below, we add a second agent called reviewer that uses a stronger model for reviewing code but uses the same polars_docs tool as the root agent.
agents:
root:
model: openai/gpt-5-mini # small model for answering questions
instruction: |
You answer questions about the Polars DataFrame library.
…
toolsets:
– type: rag
ref: polars_docs # shared search

reviewer:
model: openai/gpt-5 # stronger model for the harder task
instruction: |
You review Polars code.
Search the docs for each function the code uses.
Point out slower or outdated patterns and suggest the fix the docs recommend.
…
toolsets:
– type: rag
ref: polars_docs # same shared search

By default, docker-agent runs the first agent in the file. To run the reviewer instead, pass –agent.
docker agent run –exec embeddings.yaml –agent reviewer \
'Review this code: df = pl.read_parquet("big.parquet").filter(pl.col("amount") > 0).select(["id", "amount"])'

OutputFindings:
– Using read_parquet eagerly loads the entire file before your filter/select are
applied. This prevents predicate and projection pushdown, which is slower and
uses more memory on large Parquet files.

Recommended fix:
– Switch to scan_parquet and collect at the end:
df = (
pl.scan_parquet("big.parquet")
.filter(pl.col("amount") > 0)
.select(["id", "amount"])
.collect()
)
…

The reviewer spots the eager read_parquet call and suggests switching to scan_parquet.
Test the Agent
As you experiment with different models and settings, you might want to make sure the agent keeps working as expected. It can be easy to miss mistakes by just observing the output.
docker-agents provides an easy way to define the test cases and run them against the agent.
evals/streaming-parquet.json
┌──────────────────────────────────────────────────┐
│ question: How do I read a Parquet file without │
│ loading it all into memory? │
└────────────────────────┬─────────────────────────┘
▼
┌─────────────┐
│ agent │
└──────┬──────┘
▼
answer
│
┌──────────────────┼──────────────────┐
▼ ▼ ▼
✓ uses ✓ mentions ✓ searched
scan_parquet streaming the docs

To define a test case, create a JSON file in the evals/ folder, such as evals/streaming-parquet.json.
{
"title": "Large Parquet file question",
"messages": [
{"message": {"message": {"role": "user", "content": "How do I read a Parquet file without loading it all into memory?"}}}
],
"evals": {
"assertions": [
{ "name": "uses scan_parquet", "type": "contains", "value": "scan_parquet" },
{ "name": "mentions streaming", "type": "contains", "value": "streaming" },
{ "name": "searched the docs", "type": "tool_called", "value": "polars_docs" }
]
}
}

For this question to pass, the answer must mention scan_parquet and streaming, and the agent must have searched the docs.
Now run the suite with docker agent eval:
docker agent eval embeddings.yaml ./evals

Output✓ Asof join question ($0.001918)
✓ assertions 3/3
✓ Large Parquet file question ($0.002629)
✓ assertions 3/3
[██████████] 100% (2/2) ✓2 ✗0

✅ Assertions: 6/6 passed (100.0%)

Total Cost: $0.004546
Total Time: 26s

Each run reports which tests passed, what each answer cost, and how long it took. Together, they tell you whether a change broke the agent, made it pricier, or slowed it down.
Since each eval runs in its own container, one test can’t leave files behind that change another’s result.
Compare variants before you switch
Because eval takes –flavor too, you can test a variant before adopting it. Let’s say you want to know whether the cheaper gpt-5-nano is good enough for your use case. Add it as a second flavor called cheap.
flavors:
hybrid: …
cheap:
agents:
root:
model: openai/gpt-5-nano # smallest, lowest-cost GPT-5 model

Then compare the default model against the cheap flavor. Since answers vary between runs, –repeat 3 runs each test three times.
docker agent eval embeddings.yaml ./evals –repeat 3
docker agent eval embeddings.yaml ./evals –flavor cheap –repeat 3

gpt-5-mini gpt-5-nano (cheap)
assertions passed 18/18 13/18 <- less reliable
Parquet eval 3/3 runs 0/3 runs
asof join eval 3/3 runs 2/3 runs
total cost $0.015 $0.007 <- less than half the cost

The cheap model saves more than half the cost, but its answers are less reliable. It passed 13 of 18 checks, compared with 18 of 18 for the default model.
Share the Agent
Once you are happy with a configuration, you might want to share it with your teammates.
Sharing a Python agent usually means your teammates have to download the code, install the dependencies, and run a setup script before they can use it.
docker-agent makes sharing agents as easy as sharing Docker images. Teammates run it with one command instead of setting up a Python project.
To push the YAML file to a registry such as Docker Hub (after docker login), run:
docker agent share push embeddings.yaml docker.io/<username>/polars-docs:v1

Teammates can then run the agent by name, without downloading the file first.
docker agent run docker.io/<username>/polars-docs:v1

To get a local copy of the YAML file instead, use docker agent share pull.
Note that only the YAML file is shared. Any files it points to, such as docs folders or prompt files, must exist in the folder where you run the agent.
Final Thoughts
What I like about docker-agent is that it takes so little code to get a working agent. An LLM can help you write a Python agent, but you still have to maintain that code, and more code means more places for mistakes.
Keeping everything in one YAML file also makes agents easy to change and easy to read, even for people who do not write Python every day. And with Docker-style sharing, your teammates can try your agent with one command.
But docker-agent is not the right fit for everything. If you need to control each step the agent takes, with custom branches or retries, a code-first framework like LangGraph is a better fit.
The same principle of keeping configuration separate from code is a core chapter in Production-Ready Data Science.
References

docker-agent RAG docs (Docker, 2026): retrieval strategies, the default 0.5 similarity threshold, hybrid search with RRF fusion, and SQLite index storage.

Related Tutorials

Hydra for Python Configuration: The same “change settings without editing code” idea for data pipelines

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

Build AI Agents in YAML with docker-agent Read More »

Shrink Your Python Container in One Command with SlimToolkit

Table of Contents

Introduction
What Is SlimToolkit?
Build the Chatbot Image
Slim the Image
Inspecting the Result with slim xray
Final Thoughts

Introduction
Most Docker images contain far more than a Python application actually needs at runtime. They include full OS layers with shells, compilers, and utilities that often go completely unused, leading to unnecessarily large images that consume storage and slow deployment pipelines.
SlimToolkit analyzes your container at runtime, identifies which files are actually used, and builds a minimal image with only those dependencies.
This article walks through slimming a Chainlit LLM chatbot, but the same approach works on any Python container.

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 SlimToolkit?
SlimToolkit is a command-line tool that strips unused files from a container image without touching your Dockerfile. It works in two steps:

Static analysis. Looks at the image’s contents without running it.
Dynamic analysis. Runs the image to see which files the app actually uses.

The first step lists everything in the image. The second narrows that list to what the app actually needs. Everything outside the second list gets stripped.

Install it via the official install script (works on Linux and macOS):
curl -sL https://raw.githubusercontent.com/slimtoolkit/slim/master/scripts/install-slim.sh | sudo -E bash –

Or with Homebrew on macOS:
brew install docker-slim

Verify the install:
slim –version

Outputmint version darwin/arm64|Aurora|1.41.8|latest|latest

💻 Get the Code: The complete source code and Jupyter notebook for this tutorial are available on GitHub. Clone it to follow along!

Build the Chatbot Image
To test SlimToolkit, build a small Chainlit chatbot image first. We’ll write a small Chainlit chatbot, package it with a Dockerfile, and build it.
The Chainlit App
The chatbot app uses two libraries:

Chainlit: an open-source Python framework for building LLM chat UIs; provides the web interface and message handling
OpenAI SDK: calls gpt-4o-mini for responses

# app.py
import os
import chainlit as cl
from openai import AsyncOpenAI

client = AsyncOpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

@cl.on_chat_start
async def start():
cl.user_session.set("messages", [])

@cl.on_message
async def main(message: cl.Message):
messages = cl.user_session.get("messages")
messages.append({"role": "user", "content": message.content})

response = await client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
)
reply = response.choices[0].message.content

messages.append({"role": "assistant", "content": reply})
cl.user_session.set("messages", messages)

await cl.Message(content=reply).send()

Here’s what happens when someone uses the chatbot:

At import time, AsyncOpenAI reads the OPENAI_API_KEY environment variable and constructs the client
When a new chat session opens, @cl.on_chat_start initializes an empty message list for that session
When the user types something, @cl.on_message appends it to the history, sends the whole conversation to gpt-4o-mini, stores the reply, and displays it

Before containerizing, let’s test it locally first. Export your OpenAI key:
export OPENAI_API_KEY=sk-…

Then run the app:
chainlit run app.py

Open http://localhost:8000, you should see the Chainlit welcome screen.

The Dockerfile
Pin every dependency in a requirements.txt so the build is reproducible:
# requirements.txt
chainlit==2.11.1
openai==2.16.0

Create a Dockerfile to build the image:
# Dockerfile
FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install –no-cache-dir -r requirements.txt

COPY app.py .

EXPOSE 8000
CMD ["chainlit", "run", "app.py", "–host", "0.0.0.0", "–port", "8000", "-h"]

Here’s what each step does:

Pulls python:3.11-slim as the base image
Installs the pinned dependencies from requirements.txt
Copies in app.py
Starts Chainlit on port 8000 when the container runs

Build the image:
docker build -t llm-chatbot:fat .

Verify the image size:
docker images llm-chatbot:fat

OutputIMAGE ID DISK USAGE CONTENT SIZE EXTRA
llm-chatbot:fat e8de32dd85d4 308MB 0B

Around 300 MB. Let’s see if we can shrink it with SlimToolkit.
Slim the Image
To slim the image, start with the basic command:
slim build \
–target llm-chatbot:fat \
–tag llm-chatbot:slim \
–env OPENAI_API_KEY=$OPENAI_API_KEY

Each flag plays a role in the slim build:

–target llm-chatbot:fat: tells slim which image to minify
–tag llm-chatbot:slim: names the output image
–env OPENAI_API_KEY=$OPENAI_API_KEY: sets the env var inside slim’s probe container so the module-level AsyncOpenAI() can construct at import time

Here’s what happens when you run the command:

Slim inspects the fat image
Starts it in a sandbox
Sends a GET / probe and records every file the container touches
Builds a slim image containing only those files

But the default GET / only loads the chat UI shell. It doesn’t actually send a chat message, so files needed for the chat path (OpenAI’s lazy submodules, httpcore, etc.) get stripped. To trace the chat path too, add –continue-after enter:
slim build \
–target llm-chatbot:fat \
–tag llm-chatbot:slim \
–env OPENAI_API_KEY=$OPENAI_API_KEY \
–continue-after enter

–continue-after enter pauses slim after the default probe so you can open the chatbot in a browser and send a message; this tells slim what files the chat actually needs.

Now that the chat path runs during the probe, slim keeps openai.resources and httpcore in the final image:

Let’s compare both images:
docker images llm-chatbot

OutputIMAGE ID DISK USAGE CONTENT SIZE EXTRA
llm-chatbot:fat e8de32dd85d4 308MB 0B U
llm-chatbot:slim e1f5e9b31e53 123MB 0B

Nice! We reduced the image size from 308 MB to 123 MB, about a 2.5x reduction.
Let’s run the slim image with the environment variable and see what happens.
docker run -p 8000:8000 -e OPENAI_API_KEY=$OPENAI_API_KEY llm-chatbot:slim

OutputFile "/usr/local/lib/python3.11/site-packages/chainlit/server.py", line 181, in get_build_dir
raise FileNotFoundError(f"{local_target} built UI dir not found")
FileNotFoundError: libs/copilot built UI dir not found

The error comes from a mismatch between Chainlit and slim:

Chainlit expects chainlit/copilot/ to exist when the server starts
Even with –continue-after enter, slim removed chainlit/copilot/ because the chat you exercised in the browser only loaded the main chat UI. The Copilot widget is a separate Chainlit feature; no file inside chainlit/copilot/ was opened during the probe
Now Chainlit’s startup check finds the directory missing and the container crashes

This is not unique to Chainlit or chat-UI frameworks. Any framework that loads features lazily but checks for them at startup is vulnerable. Django’s admin, FastAPI apps with multiple routers, ML serving frameworks with embedded UIs, and plugin systems all hit the same problem.
Add –include-path for the Chainlit Package
The fix is –include-path, which tells SlimToolkit to preserve a path regardless of whether probing touched it. The path that matters is the whole Chainlit package directory, which contains every feature bundle Chainlit ships:
slim build \
–target llm-chatbot:fat \
–tag llm-chatbot:slim \
–include-path /usr/local/lib/python3.11/site-packages/chainlit \
–continue-after enter \
–env OPENAI_API_KEY=$OPENAI_API_KEY

Compare the images again:
docker images llm-chatbot

OutputIMAGE ID DISK USAGE CONTENT SIZE EXTRA
llm-chatbot:fat e8de32dd85d4 308MB 0B U
llm-chatbot:slim 952b6b44df9f 163MB 0B U

Re-run the image to confirm it works:
docker run -p 8000:8000 -e OPENAI_API_KEY=$OPENAI_API_KEY llm-chatbot:slim

With the chainlit directory preserved, the slim container starts and runs as expected.

Inspecting the Result with slim xray
To see exactly which files slim stripped, run slim xray against both images. It reverse-engineers a built image into a JSON report listing every file, its size, and the layer it came from. Slim always writes its output to slim.report.json, so rename the first report before the second run overwrites it:
slim xray –target llm-chatbot:fat
mv slim.report.json fat.report.json

slim xray –target llm-chatbot:slim

Each report is several megabytes of JSON, which makes manual comparison painful. To handle that, I packaged the diff and summary steps into compare.sh:
bash compare.sh

Here are the biggest deletions, grouped by bucket:

Removed
Size
Bucket

/usr/bin/perl
3.8 MB
OS cruft

libapt-pkg.so
2.4 MB
OS cruft (apt)

ensurepip/pip-24.0.whl
2.1 MB
Python build leftover

libdb-5.3.so
1.8 MB
OS cruft (apt)

/usr/bin/sqv
1.6 MB
OS cruft (apt’s PGP verifier)

/usr/bin/bash
1.4 MB
OS cruft

ensurepip/setuptools-79.0.1.whl
1.3 MB
Python build leftover

multidict/_multidict.so
923 kB
Unused part of aiohttp

jiter/jiter.so
880 kB
Unused part of openai

pydoc_data/topics.py
775 kB
Python build leftover

aiohttp/_http_writer.so
600 kB
Unused part of aiohttp

The biggest savings come from the Debian base image, not from the Python packages. Of the top 11 deletions:

Five are base-image binaries: perl, bash, libapt-pkg, libdb-5.3, sqv
Three are install-time leftovers: bundled pip and setuptools wheels, plus the pydoc help-text database
Three are write-side or helper modules of runtime libraries the probe didn’t exercise: aiohttp/_http_writer, multidict, jiter

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

Final Thoughts
A single slim build command took this chatbot from 308 MB to 163 MB. That is one data point on one image. Your numbers will likely look different. The wider the gap between what your image installs and what it actually runs at runtime, the bigger the reduction tends to be. Give it a try on your own images and see what kind of improvement you get.
Related Tutorials

How to Test GitHub Actions Locally with act: Iterate on a slim-build CI workflow locally before pushing.
Unregistry: Skip the Registry, Deploy Docker Images Directly: Deploy the slimmed image straight to a server, no registry required.

📚 Want to go deeper? Learning new techniques is the easy part. Knowing how to structure, test, and deploy them is what separates side projects from real work. My book shows you how to build data science projects that actually make it to production. Get the book →

Shrink Your Python Container in One Command with SlimToolkit Read More »

How to Test GitHub Actions Locally with act

Table of Contents

The Slow Feedback Loop
What Is act?
Setup
Installing act
Creating a Sample ML Project

Running Workflows Locally
Listing Available Workflows
Running a Workflow
Running a Specific Job
Dry Run

Managing Secrets
Passing Secrets Directly
Loading Secrets from a File

Summary

The Slow Feedback Loop
If you have used GitHub Actions, you have probably gone through something like this:

Edit .github/workflows/test.yml
Commit, push, and wait 2-5 minutes for the runner to start
Discover a typo or missing dependency
Fix it, commit again, push again, wait again

After a few iterations, you can easily spend 15 to 30 minutes debugging what turns out to be a small YAML mistake.
The root issue is that there is no way to run GitHub Actions locally. Every test requires a push, a wait, and a review of logs.
For data scientists iterating on CI workflows for training or validation, this feedback loop slows everything down.
In this article, you will learn how to use act to run GitHub Actions locally and catch errors in seconds instead of minutes.

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 act?
act is an open-source CLI tool that runs GitHub Actions workflows on your local machine. It uses Docker containers to simulate GitHub’s runner environment, so the same workflow YAML that runs on GitHub runs locally with no changes.
The key difference is speed. Instead of waiting for GitHub to provision a hosted VM, act uses a pre-pulled Docker image and starts execution in seconds.
Setup
Installing act
act requires Docker to run workflows in containers. Install Docker Desktop if you don’t have it already.
Install act with Homebrew:
brew install act

For other package managers, see the act installation guide.
Verify the installation:
act –version

act version 0.2.86

Creating a Sample ML Project
To demonstrate act, let’s create a small ML project with data validation and model tests.
Project structure:
ml-project/
├── .github/
│ └── workflows/
│ └── test.yml
├── src/
│ ├── train.py
│ └── validate.py
├── tests/
│ ├── test_data.py
│ └── test_model.py
└── requirements.txt

The project includes:

src/train.py: Trains a RandomForest on Iris and saves the model
src/validate.py: Asserts data has the expected shape and value ranges
tests/test_data.py: Validates data schema and distribution
tests/test_model.py: Checks model accuracy and reproducibility
requirements.txt: Lists dependencies (scikit-learn, pytest)

Here is the GitHub Actions workflow:
# .github/workflows/test.yml
name: ML Tests
on: [push, pull_request]

jobs:
validate:
runs-on: ubuntu-latest
steps:
– uses: actions/checkout@v4
– uses: actions/setup-python@v5
with:
python-version: "3.11"
– run: pip install -r requirements.txt
– run: python src/validate.py

test:
runs-on: ubuntu-latest
needs: validate
steps:
– uses: actions/checkout@v4
– uses: actions/setup-python@v5
with:
python-version: "3.11"
– run: pip install -r requirements.txt
– run: pytest tests/ -v

This workflow defines two jobs that run in sequence:

validate: Runs data checks first
test: Runs the pytest suite only if validation passes

On GitHub, you’d wait several minutes to see whether these jobs succeed. With act, you can test them in seconds.
Running Workflows Locally
Listing Available Workflows
Before running anything, you can inspect what workflows and jobs are available:
act -l

Stage Job ID Job name Workflow name Workflow file Events
0 validate validate ML Tests test.yml push,pull_request
1 test test ML Tests test.yml push,pull_request

This shows both jobs, their execution order (stage 0 runs first), and the events that trigger them.
To list only jobs triggered by a specific event such as a pull request, run:
act -l pull_request

Running a Workflow
To run all workflows triggered by a push event, run:
act push

The first time you run this command, act prompts you to select a default image size (Large, Medium, or Micro). Pick Medium for a good balance between compatibility and download size.
You’ll see familiar GitHub Actions log output in your terminal:
[ML Tests/validate] 🚀 Start image=catthehacker/ubuntu:act-latest
[ML Tests/validate] ✅ Success – Main actions/checkout@v4
[ML Tests/validate] ✅ Success – Main actions/setup-python@v5
[ML Tests/validate] ✅ Success – Main pip install -r requirements.txt
[ML Tests/validate] ✅ Success – Main python src/validate.py
[ML Tests/validate] 🏁 Job succeeded
[ML Tests/test ] 🚀 Start image=catthehacker/ubuntu:act-latest
[ML Tests/test ] ✅ Success – Main actions/checkout@v4
[ML Tests/test ] ✅ Success – Main actions/setup-python@v5
[ML Tests/test ] ✅ Success – Main pip install -r requirements.txt
[ML Tests/test ] ✅ Success – Main pytest tests/ -v
| ============================== 5 passed in 1.21s ===============================
[ML Tests/test ] 🏁 Job succeeded

Like GitHub Actions, act resolves job dependencies and runs each step in order, but in local Docker containers instead of hosted VMs. If a step fails, you see the error immediately without pushing to GitHub.
The same approach works for other events like act pull_request, act schedule, or act workflow_dispatch.
Running a Specific Job
If you are debugging a failing test, it is time-consuming to run the entire workflow. Instead, target a specific job by name by using the -j flag:
act -j test

Or run a specific workflow file by using the -W flag:
act -W .github/workflows/test.yml

Dry Run
Downloading Docker images and executing steps takes time. If you only want to check your workflow YAML for syntax errors, use a dry run:
act -n

*DRYRUN* [ML Tests/validate] ✅ Success – Main actions/checkout@v4
*DRYRUN* [ML Tests/validate] ✅ Success – Main actions/setup-python@v5
*DRYRUN* [ML Tests/validate] ✅ Success – Main pip install -r requirements.txt
*DRYRUN* [ML Tests/validate] ✅ Success – Main python src/validate.py
*DRYRUN* [ML Tests/validate] 🏁 Job succeeded
*DRYRUN* [ML Tests/test ] ✅ Success – Main pytest tests/ -v
*DRYRUN* [ML Tests/test ] 🏁 Job succeeded

The *DRYRUN* prefix indicates that no containers were created. This is useful for verifying that your workflow file is valid and that jobs run in the expected order before committing to a full execution.
Managing Secrets
Many workflows need API keys or credentials. For example, you might add a Slack notification step to the existing workflow:
# .github/workflows/test.yml
name: ML Tests
on: [push, pull_request]

jobs:
validate:
…
test:
…
notify:
runs-on: ubuntu-latest
needs: test
steps:
– name: Notify
uses: slackapi/slack-github-action@v2.0.0
with:
webhook: ${{ secrets.SLACK_WEBHOOK }}
webhook-type: incoming-webhook
payload: |
text: "Tests passed"

The notify job references secrets.SLACK_WEBHOOK. Configuring secrets through GitHub’s repository settings UI is slow and requires multiple clicks. With act, you can provide them locally with a single flag.
Passing Secrets Directly
Pass secrets using the -s flag:
act -s SLACK_WEBHOOK=https://hooks.slack.com/test

For sensitive values, omit the value and act will prompt you securely (input is not echoed):
act -s SLACK_WEBHOOK

Loading Secrets from a File
For projects with multiple secrets, store them in a .env file:
# .env (add this to .gitignore!)
SLACK_WEBHOOK=https://hooks.slack.com/services/T00/B00/xxx
AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE

Then load all secrets at once:
act –secret-file .env

This is easier than repeating -s for every secret, especially as the number of secrets grows.
Summary
act removes the commit-push-wait loop from GitHub Actions development. Here are the key commands:

Command
Description

act push
Run all push-triggered workflows

act -l
List all available workflows and jobs

act -j test
Run a specific job by name

act -W path/to/workflow.yml
Run a specific workflow file

act -n
Dry run without executing

act -s KEY=VALUE
Pass a secret

act –secret-file .env
Load secrets from file

For a complete reference, see the act documentation.
Related Tutorials

pytest for Data Scientists: Writing the data validation and model tests that act runs in your workflows
How to Structure a Data Science Project for Maintainability: Organizing ML projects with automated code quality checks
Version Control for Data and Models Using DVC: Version-controlling datasets alongside your Git-managed code

📚 Want to go deeper? Learning new techniques is the easy part. Knowing how to structure, test, and deploy them is what separates side projects from real work. My book shows you how to build data science projects that actually make it to production. Get the book →

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

How to Test GitHub Actions Locally with act Read More »

Unregistry: Skip the Registry, Deploy Docker Images Directly

Table of Contents

Table of Contents
The Registry Problem
Introduction to Unregistry
Setup and Installation
Building a Docker Application
Deployment Workflow
Production Use Cases
Conclusion

The Registry Problem
Docker deployments create two pain points: expensive private registries and wasteful transfers.
Teams choose between costly Docker Hub subscriptions or public code exposure. Meanwhile, small code changes trigger multi-gigabyte transfers of unchanged layers.
# Resource-heavy deployment cycle
docker push ml-model:latest # 2GB upload for model tweaks
ssh server "docker pull ml-model:latest" # 2GB download of unchanged ML libraries

These methods transfer complete images regardless of what changed. A small code update forces you to move gigabytes of unchanged base layers.
Introduction to Unregistry
Unregistry eliminates registry overhead by transferring images directly between Docker hosts. It creates a temporary registry on the target server and transfers only the missing layers over SSH.
Install unregistry as a Docker CLI plugin:
# macOS/Linux via Homebrew
brew install psviderski/tap/docker-pussh

# Create Docker CLI plugin symlink
mkdir -p ~/.docker/cli-plugins
ln -sf $(brew –prefix)/bin/docker-pussh ~/.docker/cli-plugins/docker-pussh

Smart Transfers: Only Changed Parts
Traditional Docker Hub workflows push entire images regardless of changes. A 2GB ML model with a small code tweak still transfers all layers, wasting bandwidth and time.
Unregistry analyzes Docker image layers and transfers only what’s missing on the target server. Instead of pushing entire multi-gigabyte images, it sends only the changed layers, dramatically reducing bandwidth usage and deployment time.
No Registry Infrastructure Required
Docker Hub subscriptions cost teams hundreds monthly for private repositories. Private registry infrastructure requires dedicated servers, maintenance, and security management.
Unregistry eliminates these costs entirely by working without intermediate storage. You deploy directly from your development machine to production servers, bypassing registry infrastructure completely.
Works with Existing SSH Connections
Registry deployments require API keys, service accounts, and firewall configurations
Unregistry uses your existing SSH keys and server access. No additional setup needed.
Faster Deployments via Deduplication
Subsequent deployments become incredibly fast since unchanged base layers already exist on the target server. A small code change doesn’t require transferring the entire Python runtime or ML libraries again.
Setup and Installation
Set up unregistry for direct Docker deployments by ensuring your target server meets the requirements:
Server Requirements:

Docker installed and running
SSH user has docker permissions (in docker group or uses sudo)
Internet access to pull unregistry image on first use

Local Requirements:

Docker CLI with plugin support (19.03+)
SSH client configured for target server

Verify the installation works:
# Test the plugin installation
docker pussh –help

Output:
Usage: docker pussh [OPTIONS] IMAGE DESTINATION

Push docker images directly to remote servers without an external registry

Arguments:
IMAGE Docker image to push
DESTINATION Remote server (user@host[:port])

Options:

-i, –identity-file <PATH> SSH private key file
–platform <PLATFORM> Target platform for multi-platform images
-h, –help Print help

Building a Docker Application
Create a simple Streamlit application that demonstrates data visualization:
# app.py
import streamlit as st
import pandas as pd
import numpy as np

st.title("Unregistry Demo App")
st.write("This Streamlit app demonstrates direct Docker deployment")

# Sample data visualization
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['A', 'B', 'C']
)

st.line_chart(chart_data)
st.write("Deployed without registry overhead!")

Define the required dependencies:
streamlit==1.28.1
pandas==2.1.3
numpy==1.24.3

Configure the Docker container for the Streamlit app:
FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY app.py .
EXPOSE 8501

CMD ["streamlit", "run", "app.py", "–server.address", "0.0.0.0"]

Build the application:
docker build -t demo-app:latest .

Sending build context to Docker daemon 3.584kB
Step 1/6 : FROM python:3.11-slim
—> f4c2c1c2d8a1
Step 2/6 : WORKDIR /app
—> Using cache
—> 8d9a4c5b6e2f
Step 3/6 : COPY requirements.txt .
—> b7e3f8a9d1c4
Step 4/6 : RUN pip install -r requirements.txt
—> Running in 3a2b5c7d8e9f
Successfully installed streamlit-1.28.1 pandas-2.1.3 numpy-1.24.3
—> 9f1e4d2c5b8a
Step 5/6 : COPY app.py .
—> 4b7a8e1f9c3d
Step 6/6 : CMD ["streamlit", "run", "app.py", "–server.address", "0.0.0.0"]
—> Running in 6e8f2a4b9d1c
—> 2d5c8f1a7e9b
Successfully built 2d5c8f1a7e9b
Successfully tagged demo-app:latest

Deployment Workflow
Deploy your application using unregistry’s efficient transfer process:
# Direct deployment to production server
docker pussh demo-app:latest deploy@prod-server

# Use SSH config for simplified commands
docker pussh demo-app:latest prod-server # Uses ~/.ssh/config

# Deploy with specific SSH key (common in CI/CD)
docker pussh demo-app:latest ubuntu@192.168.1.100 -i ~/.ssh/deploy_key

The deployment process creates a temporary registry on the target server, transfers only missing layers, and cleans up automatically. Your image becomes available immediately on the remote Docker daemon.
For modern dependency management that eliminates traditional complexity, see our UV Python Package Manager guide.
Production Use Cases
Unregistry works well for several deployment scenarios where registry overhead creates friction:
Direct Production Deployment:
Build locally, deploy directly to production servers without intermediate registries.
# Build for production platform
docker build –platform linux/amd64 -t demo-app:1.2.3 .

# Deploy directly to production
docker pussh demo-app:1.2.3 deploy@prod-server

# Start the Streamlit service
ssh deploy@prod-server "docker run -d -p 8501:8501 demo-app:1.2.3"

CI/CD Pipeline Integration:
Integrate unregistry into your CI/CD pipeline for seamless deployment.
# GitHub Actions example
– name: Deploy to staging
run: |
docker build -t demo-app:${{ github.sha }} .
docker pussh demo-app:${{ github.sha }} deploy@staging-server

📚 For comprehensive CI/CD practices and production workflow best practices, check out Production-Ready Data Science.

Conclusion
Unregistry simplifies ML model deployments by eliminating registry complexity. It transfers only missing layers over SSH, making model updates faster and reducing infrastructure overhead for data science teams.
This approach works best for direct model deployments where registry management creates unnecessary complexity during the research-to-production workflow.

Unregistry: Skip the Registry, Deploy Docker Images Directly Read More »

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran