2  Setup

Every chapter in this book is built around one Python file from the companion repository (code/chNN_*.py). The chapter walks through it, and the output blocks you see are what it printed. So before Chapter 3, make sure one such file runs on your machine. It takes ten minutes, and if it fails, nothing after it will run either.

Part I needs Python and two packages. No API keys, no cloud, no model: every Part I example runs hard-coded logic. A real model arrives in Part II, and it is a free one that runs on your own laptop — or a hosted one, if your laptop cannot hold it. Appendix A points the same code at OpenAI or at the book’s open model on a hosting provider.

2.1 What you need

  • Python 3.11 or newer. The book uses list[str], NotRequired, and the X | Y union throughout.
  • A virtual environment, so the book’s packages stay out of everything else’s way.
  • Two packages: langgraph and langchain-core.

Download the companion repository first and open a terminal in its root — the folder that contains code/. Every command in this book runs from there, and every file it names is a path under that folder.

python3.11 -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate
pip install langgraph==1.2.19 langchain-core==1.6.9

2.2 The smoke test

Before Chapter 3, run one quick check. code/ch00_setup.py does three things: prints the library versions, builds and runs a one-node graph, and optionally looks for a local LLM.

First the versions. A mismatched version is the most common reason the examples won’t run, so they print before anything else can fail:

from importlib.metadata import version, PackageNotFoundError

def show_versions() -> None:
    for pkg in ("langgraph", "langchain-core", "langchain-openai"):
        try:
            # version() reads what pip installed; it does not import the package
            print(f"  {pkg:<18} {version(pkg)}")
        except PackageNotFoundError:
            print(f"  {pkg:<18} (not installed)")

(langchain-openai is a Part II package, so seeing (not installed) here in Part I is expected.)

Second, it builds a one-node graph and runs it, which proves the StateGraph → compile → invoke chain works end to end. Chapter 3 explains every line of this skeleton; here it only has to turn over:

def build_and_run() -> str:
    from typing import TypedDict
    from langgraph.graph import StateGraph, START, END

    class State(TypedDict):
        ok: str

    def ping(state: State) -> dict:
        return {"ok": "LangGraph is working"}

    builder = StateGraph(State)
    builder.add_node("ping", ping)
    builder.add_edge(START, "ping")
    builder.add_edge("ping", END)
    graph = builder.compile()

    return graph.invoke({"ok": ""})["ok"]

flowchart TD
    START(["START"]) --> ping("ping") --> END(["END"])

Third, and optional, it probes a local LM Studio server, the free local model server Part II runs on. You can set that up now (the next section) or later; “not reachable” is not a failure in Part I:

def check_lm_studio(base_url: str = "http://localhost:1234/v1") -> None:
    try:
        import json
        import urllib.request

        # A health check with the standard library, so setup needs no packages:
        # ask the server what models it has, and give up after 2 seconds.
        req = urllib.request.Request(f"{base_url}/models")
        with urllib.request.urlopen(req, timeout=2) as resp:
            data = json.load(resp)
        ids = [m.get("id", "?") for m in data.get("data", [])]
        print(f"  LM Studio is up; loaded models: {ids or '(none)'}")
    except Exception:
        print("  LM Studio not reachable (Part I doesn't need it; start it in Part II)")

Run it — python code/ch00_setup.py, from the repository root — and continue when the last line reads Required checks passed. Versions and the graph are the required checks; the LM Studio probe is optional. The __main__ block that prints those lines:

if __name__ == "__main__":
    print("== library versions ==")
    show_versions()

    print("\n== minimal-graph smoke test ==")
    result = build_and_run()
    assert result == "LangGraph is working", f"unexpected: {result!r}"
    print(f"  {result}")

    print("\n== local LLM (optional) ==")
    check_lm_studio()

    print("\nRequired checks passed — on to Chapter 1.")

On a fresh Part I setup (two packages installed, no model running) that prints:

== library versions ==
  langgraph          1.2.19
  langchain-core     1.6.9
  langchain-openai   (not installed)

== minimal-graph smoke test ==
  LangGraph is working

== local LLM (optional) ==
  LM Studio not reachable (Part I doesn't need it; start it in Part II)

Required checks passed — on to Chapter 1.
WarningGotcha: version drift is the first thing that breaks

An old langgraph, or a Python older than 3.11, makes the examples fail in confusing ways before you have written anything wrong. If an import fails, or the langgraph or langchain-core line does not match the output above, stop here and fix it. Re-run the pinned install, pip install langgraph==1.2.19 langchain-core==1.6.9, and confirm python --version reads 3.11 or newer. Do not reach for pip install -U. It installs whatever is newest, which stops matching the book the moment a newer release ships.

TipTry it: find out what this check will not catch

Spin up a throwaway virtual environment, install a langgraph from before the 1.0 release — pip install langgraph==0.2.74 — and run the smoke test there. It does not fail. The graph compiles, the node runs, and the last line still reads Required checks passed — on to Chapter 3. All that changed is two lines you have to read:

  langgraph          0.2.74
  langchain-core     0.3.86

A three-node graph is the part of LangGraph that has changed least. It worked in 0.2 and it works now, so nothing built out of one can tell you your versions are wrong. The version lines are the check; the rest is a liveness test. That is why the Gotcha above asks you to compare them by eye rather than trust the green line at the bottom.

2.3 Optional: a local model for Part II

Part I never calls a model, so you can stop here and start Chapter 3. Part II needs a real LLM; the book runs one locally with LM Studio, no API key and no cloud bill. If you would rather set it up now, it is three steps:

  1. Install the LM Studio desktop app (macOS, Windows, or Linux).

  2. Download the models from LM Studio’s catalog — lms get <id> on the command line, or the entry of that name in the app. The book uses three. Grab the first now and the other two when a chapter asks, or all three if you have the disk:

    Model id What it is Size First needed
    qwen/qwen3.8-27b the book’s default chat model, the string most model= lines expect 16 GB Chapter 12
    openai/gpt-oss-20b a second chat model two chapters run on purpose, and each says why 12 GB Chapter 13
    text-embedding-nomic-embed-text-v1.5 the embedding model behind retrieval 84 MB Chapter 27

    Install from the catalog, not from a Hugging Face URL: only the catalog copy carries the switch that turns Qwen3.8’s thinking off, and the code relies on it (Chapter 12). A 7B model is fine for a connectivity check but may not reproduce the book’s later behaviour.

  3. Start its local server, which exposes an OpenAI-compatible endpoint at http://localhost:1234/v1:

lms server start     # or turn the server on in the app's Developer tab

Re-run code/ch00_setup.py and the third section flips from “not reachable” to a list of your loaded models. Every Part II and Part III example talks to this endpoint.

That probe only answers “is the server up.” To learn whether your model can do what Parts II and III rely on, run code/preflight.py once. It is a tool from the companion repository, not a listing to type. It prints one PASS/WARN/FAIL line per check, with a one-line hint (a different model, a different install) when something is missing. The checks, in the order they run:

  • Python 3.11 or newer, and the pins of the three packages that drift most — langgraph, langchain-core, langchain-openai — against requirements.txt; a mismatch is a warning, a missing package a failure. The rest of the file is not checked here; pip install -r is what installs it.
  • LM Studio reachable at the endpoint above, listing the models it has loaded. If it is not, the remaining checks are skipped rather than failed.
  • Chat completion — the chat model answers at all.
  • Thinking switch — the chat model was installed from the catalog, so reasoning_effort="none" has something to switch off (a warning otherwise).
  • Tool-calling — the model asks for a tool when given one (Chapter 13).
  • json_schema structured output — a typed reply parses (Chapter 16).
  • Streaming — tokens arrive in more than one chunk (Chapter 18).
  • Embeddings — the embedding model returns a vector (Chapter 27).

Better to find a gap here than mid-chapter.

Two models can also collide. Some Part II/III chapters use two at once (a chat model and an embedding model), and a few switch models between runs. On a memory-constrained machine LM Studio unloads one to load another, and a request caught mid-swap comes back as Model unloaded or Operation canceled. That is the environment, not your graph. Run the model-backed examples one at a time, and give LM Studio enough memory (or a smaller model) to keep what a chapter needs resident.

With the venv, the three models, and a green preflight.py, you are set up for every example and every challenge in the book.

That is all the setup. Next we build the smallest possible graph and take it apart one piece at a time.

Code in this chapter

File What it runs
code/ch00_setup.py The smoke test Chapter 0 ends on: prints the pinned versions, builds and runs a one-node graph, and probes for a local model.
code/preflight.py Run once before Part II: PASS/WARN/FAIL per capability the later chapters need, with a one-line hint when one is missing.