Running large language models locally has moved from experimental to essential. If you’re building cost-sensitive, privacy-first, or offline-capable AI systems, local inference isn’t a luxury. It’s a requirement. But moving from a quick proof-of-concept to a production system that handles real workloads on edge hardware requires deliberate choices about model selection, memory management, and orchestration.
This guide walks through the practical patterns I’ve learned building local inference stacks with Ollama and LangGraph for teams in the UAE and beyond who need fast, private AI without cloud API dependencies.
Why Local Inference Matters Now
Three things have changed the game. First, quantization techniques have matured. A 7B parameter model quantized to 4-bit runs on modest hardware without unacceptable quality loss. Second, frameworks like Ollama have abstracted away the complexity of model serving. Third, agentic workflows powered by LangGraph let you build multi-step reasoning chains that benefit enormously from low-latency local execution.
The business case is straightforward: no API costs per token, no network latency, no data leaving your infrastructure, and predictable compute budgets. For teams handling sensitive data or operating in bandwidth-constrained environments, it’s non-negotiable.
Model Selection: Balancing Quality and Constraints
Your hardware ceiling determines your options. Start by knowing your constraints: available RAM, GPU memory (if any), and latency targets.
For most production scenarios, I recommend these tiers:
- 7B models (Mistral 7B, Llama 2 7B): Run on 8GB RAM comfortably. Fast inference. Good for classification, extraction, routing. Start here if you’re unsure.
- 13B models (Llama 2 13B, Mistral Medium): Need 16GB RAM. Noticeably better reasoning. Worth it if you have the hardware.
- Larger models (30B, 70B): Require GPU acceleration. Excellent quality but higher operational complexity. Reserve for scenarios where quality is non-negotiable.
Don’t chase model size. A well-prompted 7B model often outperforms a poorly-prompted 13B. Test your specific task before committing hardware.
Quantization Trade-offs
Quantization reduces model size and speeds inference by representing weights with fewer bits. The trade-off is measurable but often acceptable.
Common options with Ollama:
- Q4 (4-bit): Smallest size, fastest inference. Quality loss is real but usually tolerable for production tasks. Start here.
- Q5 (5-bit): Sweet spot for many teams. Slightly larger than Q4, noticeably better quality. Recommended.
- Q8 (8-bit): Near-original quality. Larger models, slower inference. Use only if quality testing shows Q5 isn’t sufficient.
Test quantization impact on your specific task before production deployment. A classification task might tolerate Q4 perfectly; a nuanced content generation task might need Q5.
Setting Up Ollama for Production
Ollama handles model download, quantization, and serving. Getting it running locally is straightforward, but production setup requires attention to resource limits and configuration.
Basic Installation and Model Loading
#!/bin/bash
# Install Ollama (macOS, Linux, Windows WSL)
curl https://ollama.ai/install.sh | sh
# Pull a model (Q4 quantized by default)
ollama pull mistral:latest
# Verify it's available
ollama list
Models are stored locally. First pull takes time depending on your connection and model size, but subsequent runs are instant.
Running Ollama as a Service
For production, run Ollama as a daemon with resource controls:
#!/bin/bash
# Set memory and GPU limits
export OLLAMA_MAX_LOADED_MODELS=2 # Keep 2 models in memory
export OLLAMA_NUM_PARALLEL=1 # Single request at a time (adjust based on hardware)
export OLLAMA_KEEP_ALIVE=5m # Unload model after 5 minutes of inactivity
# Start Ollama server
ollama serve
Ollama exposes a REST API on localhost:11434 by default. You can call it directly:
curl http://localhost:11434/api/generate -d '{
"model": "mistral",
"prompt": "What is local inference?",
"stream": false
}'
Integrating with LangGraph for Agentic Workflows
LangGraph lets you orchestrate multi-step workflows where an LLM makes decisions about which tools to call and how to chain them. Local inference shines here because latency is predictable and you control the entire loop.
Basic Setup
from langchain_ollama import OllamaLLM
from langgraph.graph import StateGraph, END
from typing import TypedDict, Annotated
import operator
# Initialize local Ollama model
llm = OllamaLLM(model="mistral", temperature=0.7)
# Define agent state
class AgentState(TypedDict):
messages: Annotated[list, operator.add]
task: str
result: str
# Create graph
graph = StateGraph(AgentState)
def process_task(state: AgentState) -> dict:
"""LLM processes the task"""
response = llm.invoke(state["task"])
return {"messages": [{"role": "assistant", "content": response}], "result": response}
# Add nodes
graph.add_node("process", process_task)
graph.set_entry_point("process")
graph.add_edge("process", END)
# Compile
app = graph.compile()
# Run
result = app.invoke({"messages": [], "task": "Explain local LLM inference"})
print(result["result"])
This is the simplest pattern. For more complex workflows, add conditional routing, tool calls, and memory management.
Token Streaming for Real-Time Feedback
Don’t wait for the full response. Stream tokens as they arrive for better UX and faster perceived latency:
from langchain_ollama import OllamaLLM
llm = OllamaLLM(model="mistral")
# Stream tokens
for chunk in llm.stream("Explain quantization in LLMs"):
print(chunk, end="", flush=True)
This is critical for production. Users see results immediately rather than waiting for the entire generation to complete.
Memory Management and Context Handling
Local inference runs on finite hardware. Managing memory is non-negotiable.
Context Window Limits
Every model has a maximum context window (tokens it can process). Mistral 7B supports 8K tokens by default, though this varies by model. Ollama sets context windows based on available VRAM: less than 24GB gets 4K context, 24-48GB gets 32K, and 48GB or more gets 256K. Exceeding your model’s window causes errors or degraded output.
Implement sliding window context management:
from langchain.text_splitter import TokenCounterSplitter
from langchain_ollama import OllamaLLM
llm = OllamaLLM(model="mistral")
def manage_context(messages: list, max_tokens: int = 6000) -> list:
"""Keep only recent messages within context window"""
total_tokens = 0
kept_messages = []
# Work backwards from most recent
for msg in reversed(messages):
msg_tokens = len(msg["content"].split())
if total_tokens + msg_tokens > max_tokens:
break
kept_messages.insert(0, msg)
total_tokens += msg_tokens
return kept_messages
# Usage
conversation_history = [
{"role": "user", "content": "..."},
{"role": "assistant", "content": "..."},
# ... many more messages
]
trimmed = manage_context(conversation_history)
response = llm.invoke(f"Context: {trimmed}
New question: ...")
Model Unloading and Memory Recycling
Ollama’s keep-alive setting controls how long a model stays in memory after the last request. For edge devices with tight memory, set it to unload quickly:
export OLLAMA_KEEP_ALIVE=2m # Unload after 2 minutes
export OLLAMA_MAX_LOADED_MODELS=1 # Only one model in memory at a time
This trades latency (model reload time) for memory savings. Measure the trade-off for your hardware. You can also use the API’s keep_alive parameter to control this per request, setting it to 0 to unload immediately or -1 to keep the model loaded indefinitely.
Scaling Patterns for Edge Deployment
Moving from one machine to many requires different thinking.
Single-Machine Optimization
Before scaling horizontally, max out a single machine:
- Use GPU acceleration if available (CUDA, Metal on Mac).
- Batch requests where possible.
- Use smaller quantized models to free RAM for more concurrent requests.
- Profile actual latency and throughput under realistic load.
Multi-Node Deployment
For higher throughput, distribute inference across multiple edge devices:
import asyncio
from typing import List
import httpx
class LocalInferenceCluster:
def __init__(self, nodes: List[str]):
"""nodes: list of Ollama server URLs (e.g., ['http://edge1:11434', 'http://edge2:11434'])"""
self.nodes = nodes
self.current_node = 0
async def infer(self, prompt: str, model: str = "mistral") -> str:
"""Round-robin inference across cluster"""
node_url = self.nodes[self.current_node]
self.current_node = (self.current_node + 1) % len(self.nodes)
async with httpx.AsyncClient() as client:
response = await client.post(
f"{node_url}/api/generate",
json={"model": model, "prompt": prompt, "stream": False},
timeout=30.0
)
return response.json()["response"]
# Usage
cluster = LocalInferenceCluster([
"http://edge-device-1:11434",
"http://edge-device-2:11434",
"http://edge-device-3:11434"
])
result = await cluster.infer("Explain edge AI")
This simple round-robin approach works well for homogeneous clusters. Add health checks and adaptive routing for production:
import asyncio
from typing import List
import httpx
class RobustInferenceCluster:
def __init__(self, nodes: List[str]):
self.nodes = nodes
self.health_status = {node: True for node in nodes}
async def check_health(self, node: str) -> bool:
"""Verify node is responsive"""
try:
async with httpx.AsyncClient() as client:
response = await client.get(f"{node}/api/tags", timeout=2.0)
self.health_status[node] = response.status_code == 200
return self.health_status[node]
except Exception:
self.health_status[node] = False
return False
async def get_healthy_node(self) -> str:
"""Return first healthy node"""
for node in self.nodes:
if await self.check_health(node):
return node
raise RuntimeError("No healthy nodes available")
async def infer(self, prompt: str, model: str = "mistral") -> str:
node = await self.get_healthy_node()
async with httpx.AsyncClient() as client:
response = await client.post(
f"{node}/api/generate",
json={"model": model, "prompt": prompt, "stream": False},
timeout=30.0
)
return response.json()["response"]
# Usage
cluster = RobustInferenceCluster([
"http://edge-device-1:11434",
"http://edge-device-2:11434"
])
result = await cluster.infer("What is resilience in distributed systems?")
Production Patterns and Monitoring
Graceful Error Handling
Local inference can fail. Networks go down. Models crash. Plan for it:
import asyncio
from typing import Optional
import httpx
async def infer_with_fallback(
primary_url: str,
fallback_url: Optional[str],
prompt: str,
model: str = "mistral"
) -> str:
"""Try primary, fall back to secondary"""
try:
async with httpx.AsyncClient() as client:
response = await client.post(
f"{primary_url}/api/generate",
json={"model": model, "prompt": prompt, "stream": False},
timeout=10.0
)
response.raise_for_status()
return response.json()["response"]
except Exception as e:
if fallback_url:
async with httpx.AsyncClient() as client:
response = await client.post(
f"{fallback_url}/api/generate",
json={"model": model, "prompt": prompt, "stream": False},
timeout=10.0
)
return response.json()["response"]
raise RuntimeError(f"Inference failed on both primary and fallback: {e}")
# Usage
result = await infer_with_fallback(
"http://edge-device-1:11434",
"http://edge-device-2:11434",
"Explain fallback patterns"
)
Latency Monitoring
Track inference latency to catch degradation early:
import time
from collections import deque
class LatencyTracker:
def __init__(self, window_size: int = 100):
self.latencies = deque(maxlen=window_size)
def record(self, latency_ms: float):
self.latencies.append(latency_ms)
def avg_latency(self) -> float:
return sum(self.latencies) / len(self.latencies) if self.latencies else 0
def p95_latency(self) -> float:
if not self.latencies:
return 0
sorted_latencies = sorted(self.latencies)
idx = int(0.95 * len(sorted_latencies))
return sorted_latencies[idx]
tracker = LatencyTracker()
# In your inference loop
start = time.time()
response = llm.invoke(prompt)
latency_ms = (time.time() - start) * 1000
tracker.record(latency_ms)
print(f"Avg latency: {tracker.avg_latency():.1f}ms")
print(f"P95 latency: {tracker.p95_latency():.1f}ms")
Practical Workflow: Building a Local RAG Agent
Retrieval-Augmented Generation is a common local inference use case. Here’s a minimal example:
from langchain_ollama import OllamaLLM
from langchain_community.vectorstores import FAISS
from langchain.embeddings import OllamaEmbeddings
from langgraph.graph import StateGraph, END
from typing import TypedDict, Annotated
import operator
# Initialize embeddings and LLM locally
# Use nomic-embed-text for embeddings, mistral for generation
embeddings = OllamaEmbeddings(model="nomic-embed-text")
llm = OllamaLLM(model="mistral")
# Create vector store (load your documents first)
vector_store = FAISS.load_local("faiss_index", embeddings)
class RAGState(TypedDict):
query: str
context: str
answer: str
graph = StateGraph(RAGState)
def retrieve(state: RAGState) -> dict:
"""Retrieve relevant documents"""
docs = vector_store.similarity_search(state["query"], k=3)
context = "
".join([doc.page_content for doc in docs])
return {"context": context}
def generate(state: RAGState) -> dict:
"""Generate answer from context"""
prompt = f"""Context:
{state['context']}
Question: {state['query']}
Provide a concise answer based on the context."""
answer = llm.invoke(prompt)
return {"answer": answer}
graph.add_node("retrieve", retrieve)
graph.add_node("generate", generate)
graph.set_entry_point("retrieve")
graph.add_edge("retrieve", "generate")
graph.add_edge("generate", END)
app = graph.compile()
# Run
result = app.invoke({"query": "How does local inference work?", "context": "", "answer": ""})
print(result["answer"])
Common Pitfalls and How to Avoid Them
Oversizing models for your hardware. Start small. A 7B model that runs smoothly beats a 13B model that thrashes your disk with swap. Profile before committing.
Ignoring context window limits. Your model will fail silently or produce garbage if you exceed its context. Implement context management from day one, not after production issues.
Not testing quantization impact. A 4-bit model is much faster but quality loss varies by task. Benchmark on your actual use case, not generic benchmarks.
Treating local inference as set and forget. Monitor latency, error rates, and memory usage. Local systems are closer to your infrastructure; you own the reliability story.
Underestimating deployment complexity. Local inference removes cloud dependencies but adds operational ones. Plan for model updates, hardware failures, and scaling across devices.
Next Steps
Start with a single machine and a 7B model. Get comfortable with Ollama’s API and basic LangGraph workflows. Measure latency and quality on your specific tasks. Only then add complexity like clustering, multiple models, or larger quantizations.
Local LLM inference is mature now. The tooling is solid, the patterns are proven, and the business case is compelling. Build it right from the start, and you’ll have a system that scales with your needs while keeping costs and latency predictable.
What’s the difference between Q4 and Q5 quantization, and which should I use?
Q4 (4-bit) quantization produces the smallest models and fastest inference, but with noticeable quality loss on nuanced tasks. Q5 (5-bit) is slightly larger and slower but offers a better balance of size, speed, and quality for most production use cases. Q8 (8-bit) is near-original quality but requires more memory and compute. Test on your specific task before production deployment. For classification and routing, Q4 often works fine. For content generation or reasoning, Q5 is usually worth the trade-off.
How do I prevent my local LLM from running out of memory during long conversations?
Implement sliding window context management to keep only recent messages within the model’s context window (usually 6000-8000 tokens for 7B models). Discard older messages beyond this limit. Additionally, configure Ollama’s keep-alive setting to unload models from memory after a period of inactivity, freeing RAM for other tasks. Monitor actual memory usage under realistic load and adjust context window and keep-alive settings based on your hardware constraints.
Can I run multiple different models on the same machine, or will they conflict?
Ollama can manage multiple models, but only one typically stays loaded in memory at a time, controlled by the OLLAMA_KEEP_ALIVE setting. You can switch between models, but loading a new model unloads the previous one. For production scenarios requiring multiple models simultaneously, either use machines with enough GPU memory to hold both, or distribute models across separate machines in a cluster.
What’s the typical latency difference between local inference and cloud APIs?
Local inference eliminates network round-trip time (typically 50-200ms for cloud APIs) but adds model loading and processing time. A 7B model on modest hardware typically generates tokens at 5-20 tokens per second depending on quantization and hardware. For short responses, local inference is often faster. For long responses, the streaming nature of token generation means users see results immediately rather than waiting for the full cloud response.
How do I handle inference failures across a cluster of edge devices?
Implement health checks on each node before sending requests, and include fallback logic to retry on secondary nodes if the primary fails. Track latency and error rates per node, and route requests away from degraded nodes. For critical applications, use load balancing with automatic failover and consider running each model on at least two nodes for redundancy.