Thursday, December 3, 2026

Agents Tutorial 1: Smart SQL Agent in 10 minutes

Exported Document

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
  2. Code Walkthrough
  3. The ReAct Pattern
  4. Reference

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:

ToolRole
GitVersion control; clone the tutorial repo
VS CodeOptional editor (a terminal is enough)
uvPython package manager — replaces pip, venv, and pip-tools
OllamaLocal model runtime on http://127.0.0.1:11434
qwen3.5:4bThe local model the agent drives
StreamlitThe chat UI
MLflowAutomatic 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 open http://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 get4.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 testollama 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

ToolCommandYou should see
Gitgit --versiongit version 2.x
VS Codecode --version1.x
uvuv --versionuv 0.x
Ollamaollama --versionollama version 0.x
Modelollama listqwen3.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

ProblemFix
uv: command not foundRestart the terminal first. If it persists, add %USERPROFILE%\.local\bin (Windows) or ~/.local/bin (macOS/Linux) to PATH.
Ollama isn't respondingRun 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 onlyCheck /api/ps: size_vram should exceed 0. On Windows Intel iGPUs set OLLAMA_IGPU_ENABLE=1 before starting Ollama.
Wrong model tagqwen3.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=0 keeps SQL generation deterministic.
  • validate_model_on_init fails fast if the model isn't pulled yet.
  • num_ctx raises 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:

ToolPurpose
sql_db_list_tablesList the tables in the database
sql_db_schemaInspect a table's columns and types
sql_db_query_checkerValidate a query before running it
sql_db_queryExecute a read-only SQL query
duckduckgo_searchLook 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:

RuleWhat it means
Look before you queryVerify table names with sql_db_list_tables, inspect schemas with sql_db_schema first.
Check before you runRun non-trivial queries through sql_db_query_checker before sql_db_query.
Read-only, alwaysNo INSERT, UPDATE, DELETE, DROP — ever.
Plan multi-step workUse 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: deepagents injects its own filesystem/subagent tools (and write_todos) around the tools you pass. The app's Max recursion steps slider defaults to 50; deepagents itself hard-codes a recursion_limit of 9999.


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:

ApproachLimitation
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 agentsCan 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
StepWhat happens
ThoughtDecides what to check next.
ActionCalls a tool to find out.
ObservationThe tool's result comes back.
RepeatBack to Thought with new information.
AnswerReplies with no more calls once there's enough information.

3. Mapped Onto the Code

ReAct stepIn this agent's trajectory
ThoughtFolded into the model's next tool call
ActionAIMessage(tool_calls=[sql_db_schema(...)])
ObservationToolMessage(content=<query result>)
RepeatLangGraph's model ↔ tools nodes run again
AnswerAIMessage, 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

BenefitWhy
GroundedThe agent checks the real schema instead of guessing a column name — fewer hallucinated facts.
InterpretableEvery thought, action, and observation is a message you can read — literally the trajectory expander.
RecoverableA bad query doesn't fail silently — the next loop iteration can look again and correct course.
ExtensibleDeep agents layer planning and sub-agents on top of this same Thought → Action → Observation core.

4. Reference

Tutorial files

FileWhat it is
01_deep_agent.pyMain Streamlit SQL deep agent (this document)
02_deep_agent_detail.pyLean ReAct implementation, no framework wrapper
03_rag_agent.pyRAG agent
data/Chinook.dbSQLite database used by the agent
data/mlflow.dbMLflow trace store
slides/01-Deep Agent.htmlThe tutorial slide deck

Key packages (pyproject.toml)

PackageRole
deepagentscreate_deep_agent, planning, virtual filesystem
langchain-ollamaChatOllama model wrapper
langchain-communitySQL toolkit, DuckDuckGo tool, SQLDatabase
streamlitChat UI
mlflowTracing and trace UI
ddgsDuckDuckGo search backend

langgraph (the graph runtime behind the ReAct loop and InMemorySaver) is pulled in transitively by deepagents; it is not declared directly in pyproject.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