langchain-ollama
LangChain Ollama integration — run local LLMs with ChatOllama (chat completions, tool calling, structured output, reasoning/thinking mode), OllamaLLM (raw text completions), and OllamaEmbeddings. Connects to a local Ollama server at localhost:11434.
Best use case
langchain-ollama is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
LangChain Ollama integration — run local LLMs with ChatOllama (chat completions, tool calling, structured output, reasoning/thinking mode), OllamaLLM (raw text completions), and OllamaEmbeddings. Connects to a local Ollama server at localhost:11434.
Teams using langchain-ollama should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/langchain-ollama/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How langchain-ollama Compares
| Feature / Agent | langchain-ollama | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
LangChain Ollama integration — run local LLMs with ChatOllama (chat completions, tool calling, structured output, reasoning/thinking mode), OllamaLLM (raw text completions), and OllamaEmbeddings. Connects to a local Ollama server at localhost:11434.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# LangChain Ollama Skill
Expert assistance for `langchain-ollama`: run local LLMs via Ollama with full LangChain integration — chat, completions, embeddings, tool calling, and structured output.
**Install**:
```bash
pip install -U langchain-ollama
# Pull a model: ollama pull llama3.1
# Linux: start server with `ollama serve` (Mac: runs automatically)
```
Reference: `references/api.md` (500 KB — full API reference).
## When to Use This Skill
Activate when:
- **Using ChatOllama** — chat completions with local models, including streaming and multi-turn
- **Enabling reasoning/thinking mode** — setting `reasoning=True` on supported models (DeepSeek-R1, etc.)
- **Tool calling with local models** — binding tools to `ChatOllama` for function/tool use
- **Structured output** — using `.with_structured_output()` for JSON/Pydantic output
- **Raw text completions** — using `OllamaLLM` for non-chat completion tasks
- **Generating embeddings** — using `OllamaEmbeddings` for RAG or similarity search
- **Connecting to a remote Ollama server** — setting `base_url` to a non-localhost instance
- **Controlling generation params** — `temperature`, `num_predict`, `top_k`, `top_p`, `seed`
## Quick Reference
### ChatOllama — invoke and stream
```python
from langchain_ollama import ChatOllama
model = ChatOllama(
model="llama3.1",
temperature=0.8,
num_predict=256,
# base_url="http://remote-server:11434", # default: localhost:11434
# validate_model_on_init=True, # check model exists on startup
)
# Invoke
messages = [
("system", "You are a helpful translator. Translate the user sentence to French."),
("human", "I love programming."),
]
response = model.invoke(messages)
print(response.content)
# Stream
for chunk in model.stream("Explain recursion in one paragraph."):
print(chunk.content, end="", flush=True)
```
### Reasoning / thinking mode (DeepSeek-R1, QwQ, etc.)
```python
from langchain_ollama import ChatOllama
model = ChatOllama(
model="deepseek-r1:7b",
reasoning=True, # separates reasoning from final answer
# reasoning=False → suppress thinking entirely
# reasoning=None → default; <think> tags appear in content
)
response = model.invoke("What is 17 * 23?")
print(response.content) # final answer only
print(response.additional_kwargs.get("reasoning_content")) # reasoning trace
```
### Tool calling
```python
from langchain_ollama import ChatOllama
from langchain_core.tools import tool
@tool
def get_weather(city: str) -> str:
"""Get the current weather for a city."""
return f"The weather in {city} is sunny and 22°C."
model = ChatOllama(model="llama3.1")
model_with_tools = model.bind_tools([get_weather])
response = model_with_tools.invoke("What's the weather in Paris?")
print(response.tool_calls)
# [{'name': 'get_weather', 'args': {'city': 'Paris'}, 'id': '...'}]
```
### Structured output (JSON / Pydantic)
```python
from langchain_ollama import ChatOllama
from pydantic import BaseModel, Field
class Translation(BaseModel):
original: str = Field(description="The original text")
translated: str = Field(description="The translated text")
language: str = Field(description="Target language")
model = ChatOllama(model="llama3.1")
structured = model.with_structured_output(Translation)
result = structured.invoke("Translate 'Hello world' to Spanish")
print(result.translated) # "Hola mundo"
```
### OllamaLLM — raw text completions
```python
from langchain_ollama import OllamaLLM
llm = OllamaLLM(
model="llama3.1",
temperature=0.7,
num_predict=256,
top_k=40,
top_p=0.9,
seed=42, # reproducible output
format="json", # force JSON output format
keep_alive="5m", # how long model stays loaded (default "5m")
)
response = llm.invoke("The capital of France is")
print(response)
# Stream raw text
for chunk in llm.stream("Write a haiku about code:"):
print(chunk, end="", flush=True)
```
### OllamaEmbeddings — generate embeddings for RAG
```python
from langchain_ollama import OllamaEmbeddings
from langchain_core.vectorstores import InMemoryVectorStore
embed = OllamaEmbeddings(model="nomic-embed-text")
# Embed a single query
query_vec = embed.embed_query("What is LangChain?")
# Embed a batch of documents
doc_vecs = embed.embed_documents([
"LangChain is a framework for LLM applications.",
"Ollama runs LLMs locally.",
])
# Use in a vector store
vectorstore = InMemoryVectorStore(embed)
vectorstore.add_texts(["LangChain is a framework.", "Ollama runs locally."])
results = vectorstore.similarity_search("What is LangChain?", k=1)
```
### Connect to remote Ollama server
```python
from langchain_ollama import ChatOllama, OllamaEmbeddings
chat = ChatOllama(
model="llama3.1",
base_url="http://192.168.1.100:11434",
)
embed = OllamaEmbeddings(
model="nomic-embed-text",
base_url="http://192.168.1.100:11434",
)
```
## API Reference
### ChatOllama key parameters
| Param | Type | Description |
|-------|------|-------------|
| `model` | `str` | Ollama model name (e.g. `"llama3.1"`, `"deepseek-r1:7b"`) |
| `reasoning` | `bool \| None` | `True`=separate reasoning, `False`=suppress, `None`=raw tags |
| `temperature` | `float` | Sampling temperature (0.0–1.0) |
| `num_predict` | `int \| None` | Max tokens to generate |
| `base_url` | `str \| None` | Ollama server URL (default: `http://localhost:11434`) |
| `validate_model_on_init` | `bool` | Check model exists on startup |
| `format` | `str \| None` | Output format (e.g. `"json"`) |
| `keep_alive` | `str \| None` | How long model stays loaded in memory |
### OllamaLLM key parameters
| Param | Type | Description |
|-------|------|-------------|
| `model` | `str` | Ollama model name |
| `temperature` | `float \| None` | Sampling temperature |
| `num_predict` | `int \| None` | Max tokens |
| `top_k` | `int \| None` | Limit to K most probable tokens |
| `top_p` | `float \| None` | Nucleus sampling parameter |
| `mirostat` | `int \| None` | Mirostat sampling for perplexity control |
| `seed` | `int \| None` | Random seed for reproducibility |
| `base_url` | `str` | Ollama server URL |
| `keep_alive` | `str \| None` | Model memory retention |
| `format` | `str \| None` | Output format |
### OllamaEmbeddings key parameters
| Param | Type | Description |
|-------|------|-------------|
| `model` | `str` | Embedding model (e.g. `"nomic-embed-text"`, `"mxbai-embed-large"`) |
| `base_url` | `str \| None` | Ollama server URL |
## Common Ollama CLI commands
```bash
ollama pull llama3.1 # download a chat model
ollama pull nomic-embed-text # download an embedding model
ollama pull deepseek-r1:7b # download a reasoning model
ollama list # list downloaded models
ollama serve # start server (Linux/WSL)
ollama ps # show running models
ollama rm llama3.1 # remove a model
```
## Reference Files
| File | Size | Contents |
|------|------|----------|
| `references/api.md` | 500 KB | Full API reference (all params, methods) |
| `references/llms.md` | 28 KB | Doc index |
| `references/llms-full.md` | 500 KB | Complete page content |
Source: `https://reference.langchain.com/python/langchain-ollama`
Models: `https://ollama.com/library`Related Skills
langchain
LangChain Python package — new create_agent() factory (builds a LangGraph agent from a model string + tools + middleware), plus a comprehensive middleware system covering HITL, PII redaction, model fallback, rate limiting, auto-summarization, context editing, shell tools, and todo planning.
langchain-redis
LangChain Redis integration — RedisVectorStore for RAG, RedisCache and RedisSemanticCache for LLM response caching, RedisChatMessageHistory for persistent conversation memory, and RedisConfig for connection management. Requires Redis Stack (redis/redis-stack-server).
langchain-postgres
LangChain PostgreSQL integration — PGVectorStore (v2, recommended) and PGVector (v1 legacy) for pgvector RAG, PostgresChatMessageHistory for persistent chat, HNSW/IVFFlat index management, hybrid search, async-first engine via PGEngine, and custom metadata columns.
langchain-perplexity
LangChain Perplexity AI integration — ChatPerplexity (chat model with built-in web search and date/domain filtering), PerplexitySearchRetriever for RAG, PerplexitySearchResults tool, PerplexityEmbeddings, and reasoning output parsers (ReasoningJsonOutputParser, strip_think_tags).
langchain-openrouter
LangChain OpenRouter integration — ChatOpenRouter gives access to hundreds of models (Claude, GPT-4o, Gemini, Llama, etc.) through a single API key. Supports provider routing preferences, reasoning models, plugins, tool calling, structured output, and request attribution/tracing.
langchain-neo4j
LangChain Neo4j integration — Neo4jGraph for Cypher queries and schema inspection, GraphCypherQAChain for natural-language-to-Cypher Q&A, Neo4jVector for vector/hybrid RAG, Neo4jSaver LangGraph checkpointer, Neo4jChatMessageHistory, and GraphDocument/Node/Relationship for knowledge graph construction.
langchain-mcp-adapters
LangChain MCP Adapters — connect LangChain agents to MCP (Model Context Protocol) servers. Load MCP tools, prompts, and resources as LangChain-compatible objects. Supports stdio, SSE, StreamableHTTP, and WebSocket transports. Includes interceptors, callbacks, and multi-server management.
langchain-exa
LangChain Exa integration — semantic web search with ExaSearchRetriever (RAG), ExaSearchResults (agent tool), and ExaFindSimilarResults (find similar URLs). Unique features: use_autoprompt (LLM query rewriting), highlights (excerpts), summary (per-result LLM summaries), livecrawl (real-time), and date filtering.
langchain-deepagents
LangChain Deep Agents (Python) — build, deploy, and customize stateful long-running agents with virtual filesystems, subagents, human-in-the-loop, and LangSmith observability. Also covers LangGraph, LangChain OSS chains/retrievers, and Agent Server API.
langchain-aws
LangChain AWS integration — ChatBedrockConverse (Claude/Nova/Llama/Mistral on Bedrock), BedrockEmbeddings, AmazonKnowledgeBasesRetriever, BedrockAgentsRunnable, BedrockRerank, BedrockPromptCachingMiddleware, CodeInterpreterToolkit, BrowserToolkit (computer use), Neptune graph chains, and SageMaker endpoint.
langchainjs
LangChain.js - TypeScript framework for building LLM-powered applications with agents, chains, RAG, tools, memory, and integrations for OpenAI, Anthropic, Google, and hundreds of other providers
web-artifacts-builder
Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use for complex artifacts requiring state management, routing, or shadcn/ui components - not for simple single-file HTML/JSX artifacts.