01 — Deep Agents
Agents Tutorial · Smart Agents in 10 minutes: SQL Agent
A local SQL agent built with LangChain's
deepagents,langchain-community, Ollama, Streamlit, and MLflow. This document follows the tutorial deck: Setup → Code Walkthrough → The ReAct Pattern.
Contents
1. Setup Guide
Install the Toolchain
Everything you need, from a clean machine to a running agent — exact commands for Windows, Linux, and macOS.
You need: a terminal, about 10 GB of free disk, 8 GB+ of RAM, and an internet connection — roughly 20 minutes.
The stack:
| Tool | Role |
|---|---|
| Git | Version control; clone the tutorial repo |
| VS Code | Optional editor (a terminal is enough) |
| uv | Python package manager — replaces pip, venv, and pip-tools |
| Ollama | Local model runtime on http://127.0.0.1:11434 |
qwen3.5:4b | The local model the agent drives |
| Streamlit | The chat UI |
| MLflow | Automatic tracing for every question |
1. Install Git
Windows
winget install --id Git.Git -e --source winget
Or run the installer from git-scm.com/download/win.
Verify:
git --version
macOS
xcode-select --install
This includes Apple's Command Line Tools. With Homebrew:
brew install git
Verify:
git --version
Linux — Debian / Ubuntu
sudo apt update && sudo apt install git
Fedora:
sudo dnf install git
Arch:
sudo pacman -S git
Verify:
git --version
Set your identity and clone the repo
Set your identity once, then clone the repo:
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git clone https://github.com/mohamedadaly/agents-workshop.git
2. Install VS Code
Optional but recommended — a terminal is enough to run everything.
Windows
winget install Microsoft.VisualStudioCode
Or run the installer from code.visualstudio.com.
Verify:
code --version
macOS
brew install --cask visual-studio-code
Or drag the .app from code.visualstudio.com.
Verify:
code --version
Linux
sudo snap install code --classic
Or install the .deb / .rpm from code.visualstudio.com.
Verify:
code --version
Open the repo
code .
Accept the Python extension prompt — or install it directly:
code --install-extension ms-python.python
3. Install uv
uv replaces pip, venv, and pip-tools. It also downloads the right Python version for the project.
Windows — PowerShell
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
Or with winget:
winget install --id=astral-sh.uv -e
Verify:
uv --version
macOS
curl -LsSf https://astral.sh/uv/install.sh | sh
Or with Homebrew:
brew install uv
Verify:
uv --version
Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
Or with pipx:
pipx install uv
Verify:
uv --version
PATH note: installs land in
%USERPROFILE%\.local\bin(Windows) or~/.local/bin(macOS/Linux). Restart the terminal afterward so PATH picks it up.
4. Install Ollama
Ollama runs the model locally and exposes it on http://127.0.0.1:11434. The desktop app starts the server for you.
Windows
winget install Ollama.Ollama
Or download OllamaSetup.exe from ollama.com/download/windows.
Verify:
ollama --version
macOS
brew install ollama
Or download the app from ollama.com/download/mac.
Start it (Homebrew install only):
brew services start ollama
Verify:
ollama --version
Linux
curl -fsSL https://ollama.com/install.sh | sh
This starts a systemd service automatically. No desktop app needed.
Verify:
ollama --version
No service? Run
ollama serve, then openhttp://127.0.0.1:11434.
5. Download qwen3.5:4b
Same command on every OS — Ollama picks the right backend:
ollama pull qwen3.5:4b
| What you get | 4.2B parameters, Q4_K_M quantization, about 3.1 GB on disk. Handles tools, thinking, and vision. |
| Which tag? | qwen3.5:4b on Windows and Linux. The -mlx variant (qwen3.5:4b-mlx) is Apple Silicon only. |
| Smoke test | ollama list then ollama run qwen3.5:4b "Say hello" |
No Ollama config needed: the app requests a 16k window itself with
num_ctx=16384. Expect CPU-only inference until a supported GPU is enabled.
6. Verify the Toolchain & Run
| Tool | Command | You should see |
|---|---|---|
| Git | git --version | git version 2.x |
| VS Code | code --version | 1.x |
| uv | uv --version | uv 0.x |
| Ollama | ollama --version | ollama version 0.x |
| Model | ollama list | qwen3.5:4b |
Install dependencies and launch the app:
cd agents-workshop
uv sync
uv run streamlit run 01_deep_agent.py
Streamlit opens at http://localhost:8501. Pick the model, confirm data/Chinook.db, then click Connect.
Other apps use the same run command:
uv run streamlit run 02_deep_agent_detail.py
uv run streamlit run 03_rag_agent.py
7. View MLflow Traces
Every question you ask is traced automatically. In a separate terminal:
uv run mlflow ui --backend-store-uri sqlite:///data/mlflow.db
Then open the URL it prints — typically http://localhost:5000.
8. Troubleshooting
| Problem | Fix |
|---|---|
uv: command not found | Restart the terminal first. If it persists, add %USERPROFILE%\.local\bin (Windows) or ~/.local/bin (macOS/Linux) to PATH. |
| Ollama isn't responding | Run ollama serve and open http://127.0.0.1:11434. If the port is busy, quit the stale Ollama process first. |
| Inference is slow / CPU only | Check /api/ps: size_vram should exceed 0. On Windows Intel iGPUs set OLLAMA_IGPU_ENABLE=1 before starting Ollama. |
| Wrong model tag | qwen3.5:4b-mlx is Apple Silicon only. On Windows and Linux pull qwen3.5:4b — the app default already matches. |
2. Code Walkthrough
Anatomy of the Agent
Four pieces, wired together in build_agent():
Model → Tools → Prompt → Memory → Agent
Everything lives in 01_deep_agent.py. The core imports:
from deepagents import create_deep_agent
from langchain_community.agent_toolkits import SQLDatabaseToolkit
from langchain_community.tools import DuckDuckGoSearchRun
from langchain_community.utilities import SQLDatabase
from langchain_ollama import ChatOllama
from langgraph.checkpoint.memory import InMemorySaver
1. Model
llm = ChatOllama(
model=model,
base_url=base_url,
validate_model_on_init=True,
temperature=0,
num_ctx=16384,
)
Picked in the sidebar at connect time.
temperature=0keeps SQL generation deterministic.validate_model_on_initfails fast if the model isn't pulled yet.num_ctxraises Ollama's 4k default to 16k so tool results don't evict the conversation.
2. Tools
db = SQLDatabase.from_uri(db_uri)
tools = SQLDatabaseToolkit(db=db, llm=llm).get_tools() + [DuckDuckGoSearchRun()]
The toolkit, plus one web-search tool, hands the agent five tools:
| Tool | Purpose |
|---|---|
sql_db_list_tables | List the tables in the database |
sql_db_schema | Inspect a table's columns and types |
sql_db_query_checker | Validate a query before running it |
sql_db_query | Execute a read-only SQL query |
duckduckgo_search | Look up information the database can't answer |
3. System Prompt
Passed as system_prompt=INSTRUCTIONS — four rules keep the ReAct loop safe and on-task:
| Rule | What it means |
|---|---|
| Look before you query | Verify table names with sql_db_list_tables, inspect schemas with sql_db_schema first. |
| Check before you run | Run non-trivial queries through sql_db_query_checker before sql_db_query. |
| Read-only, always | No INSERT, UPDATE, DELETE, DROP — ever. |
| Plan multi-step work | Use the agent's built-in todo list before a multi-step question. |
4. The Prompt, Verbatim
Source: the INSTRUCTIONS constant in 01_deep_agent.py.
You are an agent designed to interact with a SQL database.
Given an input question, create a syntactically correct sqlite query, run it,
inspect the results, and return a concise answer. Unless the user asks for a
specific number of rows, limit results to at most 10. Never `SELECT *` — only
request the columns you need.
Do NOT issue any DML statements (INSERT, UPDATE, DELETE, DROP, etc.).
Always verify table names with `sql_db_list_tables` and inspect schemas with
`sql_db_schema` before writing a query. Use `sql_db_query_checker` on any
non-trivial query before running it with `sql_db_query`.
For multi-step questions, use your todo list to plan the steps before you
start querying.
Always try the SQL tools first. If the data isn't in the database — either
the question is about something outside it (e.g. background on an artist)
or a query comes back empty — use `duckduckgo_search` to look it up on the
web instead of saying you don't know.
Answer in plain language. Do not describe the database schema or the steps
you took.
5. Memory via Checkpointer
checkpointer=InMemorySaver()
run_config = {"configurable": {"thread_id": thread_id}}
agent.invoke({"messages": [...]}, config=run_config)
Same thread_id on every turn — the checkpointer replays the full message history, so the agent remembers earlier questions in the conversation.
In the app, thread_id is created once per connection and reused across turns. Clear chat generates a fresh thread_id, which starts a brand-new conversation.
6. Assemble with create_deep_agent()
agent = create_deep_agent(
model=llm,
tools=tools,
system_prompt=INSTRUCTIONS,
checkpointer=InMemorySaver(),
)
create_deep_agent wraps all four pieces in a LangGraph ReAct loop, with planning and a virtual file system built in — this agent only ever reaches for the SQL tools above (plus the DuckDuckGo fallback).
Implementation note:
deepagentsinjects its own filesystem/subagent tools (andwrite_todos) around the tools you pass. The app's Max recursion steps slider defaults to50;deepagentsitself hard-codes arecursion_limitof9999.
3. The ReAct Pattern
ReAct: Reasoning + Acting
The pattern behind create_deep_agent's loop — and most LLM agents since 2022.
Thought → Action → Observation → Answer
1. Why It Was Invented
Two 2022-era approaches each got half the job done:
| Approach | Limitation |
|---|---|
| Reasoning-only (Chain-of-Thought) | Great at step-by-step logic, but frozen in time — no way to look anything up, so it confidently hallucinates facts it can't know. |
| Acting-only agents | Can call tools, but act impulsively — no visible plan, hard to debug, and errors compound with no reflection. |
ReAct (Yao et al., 2022) interleaves both: reasoning steers which action to take next, and each action's result corrects the reasoning.
2. How the Loop Works
┌──────────────────────────────┐
│ │
▼ │
Thought ──────────────► Action │
│ │ │
│ ▼ │
│ Observation ───┘
│
│ enough info
▼
Answer
| Step | What happens |
|---|---|
| Thought | Decides what to check next. |
| Action | Calls a tool to find out. |
| Observation | The tool's result comes back. |
| Repeat | Back to Thought with new information. |
| Answer | Replies with no more calls once there's enough information. |
3. Mapped Onto the Code
| ReAct step | In this agent's trajectory |
|---|---|
| Thought | Folded into the model's next tool call |
| Action | AIMessage(tool_calls=[sql_db_schema(...)]) |
| Observation | ToolMessage(content=<query result>) |
| Repeat | LangGraph's model ↔ tools nodes run again |
| Answer | AIMessage, no tool_calls → trajectory[-1].content |
Every row above is exactly what the Agent trajectory expander in the app shows you, turn by turn.
4. Why It Matters
| Benefit | Why |
|---|---|
| Grounded | The agent checks the real schema instead of guessing a column name — fewer hallucinated facts. |
| Interpretable | Every thought, action, and observation is a message you can read — literally the trajectory expander. |
| Recoverable | A bad query doesn't fail silently — the next loop iteration can look again and correct course. |
| Extensible | Deep agents layer planning and sub-agents on top of this same Thought → Action → Observation core. |
4. Reference
Tutorial files
| File | What it is |
|---|---|
01_deep_agent.py | Main Streamlit SQL deep agent (this document) |
02_deep_agent_detail.py | Lean ReAct implementation, no framework wrapper |
03_rag_agent.py | RAG agent |
data/Chinook.db | SQLite database used by the agent |
data/mlflow.db | MLflow trace store |
slides/01-Deep Agent.html | The tutorial slide deck |
Key packages (pyproject.toml)
| Package | Role |
|---|---|
deepagents | create_deep_agent, planning, virtual filesystem |
langchain-ollama | ChatOllama model wrapper |
langchain-community | SQL toolkit, DuckDuckGo tool, SQLDatabase |
streamlit | Chat UI |
mlflow | Tracing and trace UI |
ddgs | DuckDuckGo search backend |
langgraph(the graph runtime behind the ReAct loop andInMemorySaver) is pulled in transitively bydeepagents; it is not declared directly inpyproject.toml.
Common commands
# Install / refresh dependencies
uv sync
# Run the main app
uv run streamlit run 01_deep_agent.py
# Run the other apps
uv run streamlit run 02_deep_agent_detail.py
uv run streamlit run 03_rag_agent.py
# View traces
uv run mlflow ui --backend-store-uri sqlite:///data/mlflow.db
Tracing in code
Tracing is enabled once at the top of 01_deep_agent.py:
import mlflow
mlflow.set_tracking_uri("sqlite:///data/mlflow.db")
mlflow.set_experiment("01_deep_agent")
mlflow.langchain.autolog()
Each agent.invoke() becomes a trace with nested spans for the model and tool calls.

No comments :
Post a Comment