Installing and Running Ollama
Ollama provides a straightforward way to run large language models locally. Download the binary from the official site for macOS, Linux, or Windows. On macOS and Linux the installer adds the ollama command to your PATH.
Start the server with:
ollama serve
This launches the service on http://localhost:11434. The server automatically downloads models when first referenced. To run Llama 3.1 8B use:
ollama run llama3.1
The command pulls the 4.7 GB quantized model if not present and drops you into an interactive chat. Models are stored in ~/.ollama/models on Linux/macOS. Each model variant (Q4_0, Q5_K_M, Q8_0) trades accuracy for memory and speed. Q4_0 typically offers the best balance for local development on machines with 16 GB RAM.
For headless environments, avoid the interactive runner and use the HTTP API directly. This approach fits better in Docker-based deployments and production services.
Creating and Understanding Modelfiles
Modelfiles let you create customized versions of base models without retraining. A minimal Modelfile looks like this:
FROM llama3.1
SYSTEM You are an expert software engineer. Always respond with concise, production-ready code and explain trade-offs.
PARAMETER temperature 0.7
PARAMETER top_p 0.9
PARAMETER num_ctx 8192
PARAMETER num_predict 1024
Build the custom model with ollama create my-engineer -f Modelfile. The FROM instruction references a base model or another Modelfile. SYSTEM sets the default system prompt. Parameter values directly map to sampling settings used during inference.
Useful parameters include:
num_ctx: context window size in tokens. Llama 3.1 supports up to 128k but higher values increase VRAM usage.temperature: controls randomness. Values below 0.5 produce more deterministic output suitable for code generation.stop: custom stop sequences. Multiplestoplines can be added.template: overrides the chat template for models that need specific formatting.
Advanced Modelfiles can include ADAPTER for LoRA weights and LICENSE, MESSAGE for few-shot examples. After creation, the new model appears in ollama list and can be referenced by its tag in API calls. This pattern enables consistent behavior across development, staging, and production environments without changing application code.
Trade-off: custom Modelfiles increase disk usage because each variant stores its own copy of weights unless using external adapters. For teams, store Modelfiles in version control and build them in CI/CD pipelines.
The Ollama HTTP API Fundamentals
Ollama exposes a REST API that works with any language. All endpoints live under http://localhost:11434/api/. The two primary endpoints for text are /api/generate for completions and /api/chat for conversational use.
A basic chat completion request in TypeScript using native fetch:
import { randomUUID } from 'node:crypto';
const response = await fetch('http://localhost:11434/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'llama3.1',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Explain how to implement rate limiting' }
],
stream: false,
options: {
temperature: 0.6,
num_ctx: 4096
}
})
});
const result = await response.json();
console.log(result.message.content);
The stream: true option returns Server-Sent Events. For streaming UI responses, parse each newline-delimited JSON object and extract message.content incrementally. This pattern mirrors the Vercel AI SDK streaming interface but runs entirely offline.
Error handling is important. Ollama returns standard HTTP status codes. A 404 indicates the model is not downloaded. Pull models explicitly with a POST to /api/pull before use in production flows.
Structured Output and JSON Mode
Recent versions of Ollama support forcing JSON output. Add format: "json" to the request payload. Combine this with a system prompt that instructs the model to respond only with valid JSON.
const jsonResponse = await fetch('http://localhost:11434/api/chat', {
method: 'POST',
body: JSON.stringify({
model: 'llama3.1',
messages: [
{
role: 'system',
content: 'Respond only with valid JSON matching this schema: {"title": string, "priority": "high"|"medium"|"low"}'
},
{ role: 'user', content: 'Create a task for documentation update' }
],
format: 'json',
stream: false
})
});
This technique works reliably with Llama 3.1 70B and Gemma 2 27B but can be less consistent on smaller 8B models. When consistency matters, combine JSON mode with few-shot examples in the system prompt. For even stricter control, use grammar-based sampling available through the grammar field, though this remains an advanced feature with limited documentation.
Implementing Tool Calling Patterns
Tool calling (also called function calling) allows models to request execution of external functions. Ollama supports this through the same /api/chat endpoint when using models fine-tuned for tool use.
Define tools using the OpenAI-compatible schema:
const tools = [{
type: 'function',
function: {
name: 'get_weather',
description: 'Get current weather for a city',
parameters: {
type: 'object',
properties: {
city: { type: 'string' }
},
required: ['city']
}
}
}];
const toolResponse = await fetch('http://localhost:11434/api/chat', {
method: 'POST',
body: JSON.stringify({
model: 'llama3.1',
messages: [{ role: 'user', content: 'What is the weather in Berlin?' }],
tools,
stream: false
})
});
const data = await toolResponse.json();
if (data.message.tool_calls) {
// Execute the requested function
const toolCall = data.message.tool_calls[0].function;
const args = JSON.parse(toolCall.arguments);
const weatherData = await getWeather(args.city);
// Send tool result back to model
const finalResponse = await fetch('http://localhost:11434/api/chat', {
method: 'POST',
body: JSON.stringify({
model: 'llama3.1',
messages: [
{ role: 'user', content: 'What is the weather in Berlin?' },
data.message,
{
role: 'tool',
content: JSON.stringify(weatherData),
name: toolCall.name
}
]
})
});
}
This round-trip pattern forms the foundation of agentic systems. Llama 3.1 8B can handle simple tool use but 70B variants produce significantly fewer hallucinated parameters. Track token usage from the response prompt_eval_count and eval_count fields to implement cost controls even in local deployments.
Trade-off: tool calling increases latency because it requires at least two inference passes. Cache frequent tool results when possible. For production, wrap tool execution in timeouts and permission checks to prevent malicious model behavior.
Embedding Generation for RAG Applications
Ollama supports embedding models through the /api/embeddings endpoint. Popular choices include nomic-embed-text and all-minilm.
Pull the embedding model once:
ollama pull nomic-embed-text
Generate embeddings for documents:
async function createEmbedding(text: string): Promise<number[]> {
const res = await fetch('http://localhost:11434/api/embeddings', {
method: 'POST',
body: JSON.stringify({
model: 'nomic-embed-text',
prompt: text
})
});
const data = await res.json();
return data.embedding;
}
// Store embeddings with metadata
const documents = [
{ id: 1, content: 'TypeScript 5.5 introduced new utility types...', embedding: await createEmbedding(...) }
];
For retrieval, compute cosine similarity between the query embedding and stored vectors. A simple in-memory implementation for small knowledge bases (under 10,000 documents) performs adequately:
function cosineSimilarity(a: number[], b: number[]): number {
let dotProduct = 0;
let normA = 0;
let normB = 0;
for (let i = 0; i < a.length; i++) {
dotProduct += a[i] * b[i];
normA += a[i] * a[i];
normB += b[i] * b[i];
}
return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
}
Return the top 3-5 most similar documents and inject them into the system prompt. This basic RAG pattern improves factual accuracy for domain-specific questions. For larger corpora, integrate with libraries such as LanceDB or pgvector. The embedding dimension for nomic-embed-text is 768, which keeps memory usage manageable.
Performance note: embedding generation is significantly faster than token generation. A single embedding call usually completes under 50 ms on CPU. Batch multiple documents in one request when indexing by passing an array to the input field instead of prompt.
Multi-Modal Models and Vision Capabilities
Ollama supports vision models such as Llava 1.6 and Moondream2. Pull with ollama pull llava:7b. The API accepts base64-encoded images in the messages array.
const imageBase64 = 'data:image/jpeg;base64,...';
const visionResponse = await fetch('http://localhost:11434/api/chat', {
method: 'POST',
body: JSON.stringify({
model: 'llava',
messages: [{
role: 'user',
content: 'Describe this image in detail and suggest improvements for web design.',
images: [imageBase64.split(',')[1]]
}]
})
});
The images array contains raw base64 without the data URL prefix. Llava 13B provides better description quality than the 7B variant at the cost of 8 GB VRAM. Use cases include automated accessibility audits, screenshot analysis for bug reports, and document understanding.
Trade-off: vision models consume more resources and run slower than text-only equivalents. Limit image resolution before encoding. Ollama resizes internally but preprocessing reduces token usage in the vision encoder.
Production Deployment Considerations
Running Ollama in production requires attention to resource management. The official Docker image ollama/ollama works well with GPU passthrough. Example docker-compose snippet:
services:
ollama:
image: ollama/ollama
ports:
- "11434:11434"
volumes:
- ./ollama:/root/.ollama
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 1
capabilities: [gpu]
Expose Ollama only internally or add authentication middleware. The open-source project Ollama does not include built-in auth. Implement a simple reverse proxy with API key validation using Nginx or Traefik.
Monitor GPU utilization with nvidia-smi. Models larger than available VRAM automatically layer off to system RAM, which reduces speed by a factor of 3-5x. Use quantized variants (Q4_K_M recommended for most production workloads) to balance quality and resource usage.
Scaling horizontally is possible by running multiple Ollama instances behind a load balancer, but model loading time (often 5-30 seconds depending on size) makes cold starts expensive. Keep frequently used models warm by sending periodic keep-alive requests or using orchestration tools that pin models in memory.
Observability and Logging
Each API response includes useful metadata:
total_duration: complete request time in nanosecondsload_duration: model load timeprompt_eval_countandprompt_eval_durationeval_countandeval_duration: token generation statistics
Calculate tokens-per-second with eval_count / (eval_duration / 1_000_000_000). Log these metrics to track performance degradation over time. Integrate with OpenTelemetry by wrapping the HTTP client and recording duration, model name, and token counts as span attributes. This provides visibility into which prompts consume the most compute.
For debugging, enable debug logging by setting the OLLAMA_DEBUG environment variable to 1. This outputs detailed information about model loading and inference parameters.
Comparison of Available Models
Different models excel at different tasks within Ollama:
- llama3.1:8b: excellent general reasoning, strong tool calling, 128k context.
- gemma2:9b: fast, good at creative writing, smaller memory footprint.
- phi3:14b: strong at code generation and technical tasks.
- llava:13b: solid vision capabilities with reasonable speed.
Test multiple models for your specific domain. Create a benchmark suite using a fixed set of 20 representative prompts and measure accuracy, latency, and token efficiency. Smaller models often suffice for classification or routing tasks while reserving larger models for final synthesis steps. This mixture-of-models approach reduces average cost and latency.
Security and Privacy Patterns
Running models locally eliminates data exfiltration risks associated with cloud APIs. However, the Ollama server itself accepts requests from any host by default. Bind to 127.0.0.1 in production or use network policies. Never expose Ollama directly to the internet without authentication and rate limiting.
Scan user prompts for injection attempts before sending them to the model. Even local models can be tricked into revealing system prompts or executing dangerous instructions when connected to tools. Implement input validation and output sanitization for any data returned to users.
When using vision models, be aware that images may contain sensitive metadata. Strip EXIF data before processing. For regulated industries, maintain audit logs of all model inputs and outputs to satisfy compliance requirements.
Complete Worked Example: Local Research Assistant
Combine the patterns above into a small but functional research assistant. The application accepts a research topic, gathers information using a search tool simulation, generates embeddings to retrieve relevant context, and produces a structured report using tool calling for formatting.
Key files:
modelfilewith a custom system prompt focused on academic tone.index.tsorchestrating the workflow.- Simple vector store using an array and cosine similarity.
The complete implementation demonstrates prompt chaining, embedding retrieval, tool use for JSON report generation, and streaming final output to the console. Running the example on consumer hardware with an RTX 4060 typically completes a full research cycle in under 25 seconds for 800-word outputs.
This example serves as a template that can be extended with real web search via APIs, persistent vector databases, and a web frontend using Server-Sent Events for live updates.
The full code for the research assistant, including error handling, retry logic for model loading, and configurable model selection, exceeds 350 lines but follows the patterns described throughout this article. Each component can be tested independently, facilitating incremental adoption in existing codebases.
By combining Modelfiles for consistent behavior, embeddings for knowledge grounding, tool calling for structured actions, and careful resource management, Ollama becomes a viable foundation for privacy-sensitive AI features in web applications, internal tools, and customer-facing products.
