Ollama With LangChain

Use the ChatOllama wrapper to drop local models into LangChain and LangGraph agent pipelines.

TL;DR

  1. Wrap a local model with LangChain's ChatOllama class.
  2. Install the langchain-ollama package before importing the ChatOllama class.
  3. Add tools to a model with bind_tools for agents.

Install And Import

    Install

    Add the dedicated LangChain Ollama package.

    pip install langchain-ollama
    Import ChatOllama

    Bring in the chat model wrapper.

    from langchain_ollama import ChatOllama
    Embeddings

    Import the embeddings class when needed.

    from langchain_ollama import OllamaEmbeddings

Basic Usage

    Create The Model

    Instantiate ChatOllama with a local model name.

    llm = ChatOllama(model="llama3.1")
    Invoke

    Send a prompt and get a message back.

    resp = llm.invoke("Explain RAG briefly")
    Read Content

    Access the reply text on the content field.

    print(resp.content)

Tool Calling

    bind_tools

    Attach tools so the model can call them.

    model = llm.bind_tools([get_weather])
    JSON Mode

    Force JSON output for structured parsing.

    ChatOllama(model="llama3.1", format="json")
    Temperature

    Set sampling options on the constructor.

    ChatOllama(model="llama3.1", temperature=0)

LangGraph Nodes

    Same Wrapper

    Use ChatOllama as the model inside a graph.

    llm = ChatOllama(model="llama3.1")
    Bind In A Node

    Give a graph node tool access via bind_tools.

    node_llm = llm.bind_tools(tools)
    Swap Models

    Change one line to switch local models.

    ChatOllama(model="qwen2.5-coder")

Tips

  1. Use ChatOllama anywhere LangChain expects a chat model, so a local model swaps into existing chains and graphs unchanged.
  2. Enable structured output with format="json" or bind_tools, which helps smaller local models return parseable, reliable results.

Warnings

  1. Tool calling depends on the model; pick a tool-capable model like llama3.1, or bind_tools may be ignored silently.
  2. Point ChatOllama at a running server; without ollama serve, calls fail with a connection error to localhost:11434.

In Practice

FAQ