Integrate Elasticsearch with Ollama for Log Analysis

integrate Elasticsearch/ELK with Ollama like this:

Filebeat / Logstash
Elasticsearch ← Kibana dashboards
Python log-analysis API
Ollama local LLM
AI summary / root cause / recommendation

1. Install Ollama model

curl -fsSL https://ollama.com/install.sh | sh
ollama pull llama3.1
# or lighter:
ollama pull mistral

Test:

ollama run llama3.1

2. Python script to analyze Elasticsearch logs with Ollama

pip install elasticsearch requests
from elasticsearch import Elasticsearch
import requests
ES_URL = "http://localhost:9200"
OLLAMA_URL = "http://localhost:11434/api/generate"
INDEX = "filebeat-*"
es = Elasticsearch(ES_URL)
query = {
"size": 50,
"sort": [{"@timestamp": {"order": "desc"}}],
"query": {
"bool": {
"must": [
{"match": {"log.level": "error"}}
]
}
}
}
result = es.search(index=INDEX, body=query)
logs = []
for hit in result["hits"]["hits"]:
src = hit["_source"]
logs.append(str(src.get("message", src)))
log_text = "\n".join(logs)
prompt = f"""
You are a senior DevOps/SRE log analyst.
Analyze these logs and provide:
1. Summary
2. Possible root cause
3. Impact
4. Recommended fix
5. Exact next commands to troubleshoot
Logs:
{log_text}
"""
payload = {
"model": "llama3.1",
"prompt": prompt,
"stream": False
}
response = requests.post(OLLAMA_URL, json=payload)
print(response.json()["response"])

Run:

python3 analyze_logs.py

3. Better Elasticsearch query examples

For Docker errors:

{
"size": 100,
"query": {
"bool": {
"must": [
{ "match": { "container.name": "kong" }},
{ "match": { "message": "error" }}
]
}
}
}

For last 15 minutes:

{
"size": 100,
"query": {
"range": {
"@timestamp": {
"gte": "now-15m"
}
}
}
}

4. Best architecture for your ELK setup

For your Docker/syslog environment:

Linux servers
├── Filebeat syslog
├── Filebeat Docker logs
Central Logstash
Elasticsearch
AI Analyzer Service
Ollama
Kibana / Email / Slack report

5. Example AI output you can generate

Incident Summary:
Kong is returning intermittent 500 errors.
Likely Root Cause:
Upstream service closed the connection before Kong received a valid response.
Evidence:
- upstream prematurely closed connection
- HTTP 500 from upstream
- repeated failures from same container
Recommended Actions:
1. Check upstream container logs
2. Verify health checks
3. Check Kong upstream timeout settings
4. Check DNS resolution from Kong container

For production, do not send all logs to Ollama. First filter in Elasticsearch, then send only relevant errors/warnings to the model.

How Ollama Optimizes AI Model Deployment

At its core, Ollama acts like “Docker for AI models.” It packages large language models (LLMs) into self-contained, easily transportable configurations and wraps them in a highly optimized engine that lets you run them locally with zero setup friction.

1. High-Level Architecture (Client-Server)

Ollama is structured as a lightweight client-server application:

  • The Ollama Daemon (Server): Runs continuously in your background. Written primarily in Go, it manages your system memory, pulls and indexes model files, schedules compute workloads, and provisions a local REST API endpoint (by default at http://localhost:11434).
  • The Ollama CLI (Client): The terminal tool you interact with (ollama run, ollama pull). It passes commands to the daemon via standard HTTP requests. Because it uses a decoupled API layout, any application—like an IDE plugin, a web UI, or your ELK pipeline—can function as the client.

2. The Core Execution Engine

Ollama does not run raw PyTorch or Python code. Instead, it serves as a sophisticated, automated wrapper around llama.cpp (an incredibly fast C/C++ inference implementation) and, on macOS, Apple’s MLX machine learning framework.

  • The GGUF Format: Ollama distributes its models using the GGUF file format. GGUF embeds critical metadata (like tokenizers, architectural parameters, and alignment profiles) directly inside the file containing the neural network weights.
  • Deduplicated Blob Storage: Mirroring container image registries, Ollama splits models into content-addressable layer files stored at ~/.ollama/models/blobs/. If you create three different custom variants of a 8B model with different system prompts, Ollama stores the massive base weights layer exactly once, saving gigabytes of disk space.

3. Dynamic Hardware Optimization & Memory Allocation

Ollama’s standout feature is that it removes the headache of configuring complex GPU compute libraries.

  • Hardware Auto-Detection: When the daemon initializes, it automatically audits your hardware capabilities to choose the absolute fastest execution path available:
    • Nvidia: Compiles kernels on the fly utilizing CUDA.
    • Apple Silicon: Interlaces natively with Metal (MPS) or MLX for hardware acceleration on unified memory.
    • AMD: Leverages the ROCm stack.
    • CPU Fallback: Drops down to your processor using AVX/AVX2/AVX-512 vector instructions if no graphic processing units are present.
  • Layer Offloading: If a model is too massive to fit inside your GPU’s dedicated Video RAM (VRAM), Ollama calculates exactly how many layers can fit. It splits the workload—pushing the heavy math to your GPU VRAM and spilling the remaining layers over to standard system RAM/CPU. This allows you to run models that exceed your system specs without experiencing out-of-memory (OOM) fatal crashes.
  • Keep-Alive Cache: To prevent the massive latency cost of spinning up a multi-gigabyte file from a cold storage drive every time you send a message, Ollama keeps the model cached in RAM/VRAM for a default cooldown window of 5 minutes after your last request before cleanly unloading it.

4. The Modelfile: Customizing Personas and Parameters

Ollama allows you to construct custom models using a declarative text script called a Modelfile. This functions exactly like a Dockerfile.

Dockerfile

# 1. Specify the base model weights
FROM llama3.2
# 2. Adjust internal model hyperparameters
PARAMETER temperature 0.3
PARAMETER num_ctx 8192
# 3. Bake in permanent behavioral instructions
SYSTEM "You are a senior Linux system engineer. Respond entirely in clean markdown blocks containing direct commands."

By pointing Ollama to this file using ollama create my-custom-engineer -f ./Modelfile, it compiles the configurations and parameters into a brand new standalone model tag ready to run immediately.

5. Built-in API Compatibility Layer

To maximize adoption, Ollama expands beyond its own API endpoints to feature built-in compatibility layers for standard enterprise frameworks:

  • OpenAI API Compatibility: It natively accepts payloads structured for /v1/chat/completions, allowing you to replace cloud dependencies in existing code by changing your client base URL to point locally.
  • Anthropic Messages API Support: Allows local integration with advanced orchestration tools like Claude Code.
  • Built-in Agent Utilities: Modern editions feature integrated tool calling (function execution), native token calculation metrics, and automated subagent orchestration hooks directly accessible via terminal commands (ollama launch).

Optimize Your Logs with Ollama and the ELK Stack

Here are the two detailed ways to integrate Ollama with the ELK Stack based on your structural preference.

  • Option 1: The Ingest Pipeline Method (Recommended) – Uses Elasticsearch’s Native Inference API to call Ollama directly whenever a log document is indexed.
  • Option 2: The Logstash Method – Enriches logs mid-flight before they reach Elasticsearch.

Option 1: Using Elasticsearch’s Native Inference API (Modern Way)

Elasticsearch includes a built-in Inference API that natively treats Ollama as an OpenAI-compatible provider. This eliminates the need for middleman scripts.

[Raw Error Log] ──> [Elasticsearch Ingest Pipeline] ──> [Ollama Inference API] ──> [Enriched Log Document]
Step 1: Allow Elasticsearch to Communicate with Ollama

By default, Ollama only listens to localhost. If Elasticsearch is running on a different server or container, you must configure Ollama to accept external connections.

  • Linux (systemd): Run systemctl edit ollama.service and add:Ini, TOML[Service] Environment="OLLAMA_HOST=0.0.0.0:11434" Save and run systemctl daemon-reload && systemctl restart ollama.
  • Windows: Set a system environment variable named OLLAMA_HOST to 0.0.0.0:11434 and restart Ollama.
Step 2: Download Your Analytics Model

Pull a technical model designed for reasoning or code analytics (like mistral or llama3.2):

Bash

ollama pull mistral
Step 3: Define the Inference Model in Elasticsearch

Run this command inside Kibana’s Dev Tools (Console) to register Ollama as an inference service. (Replace the URL if Elasticsearch is calling an external machine IP).

JSON

PUT _inference/text_completion/ollama_log_analyzer
{
"service": "openai",
"service_settings": {
"api_key": "not-needed-for-local",
"url": "http://localhost:11434/v1/chat/completions",
"model": "mistral"
}
}
Step 4: Create an Ingest Pipeline

This pipeline instructs Elasticsearch to intercept any incoming log file, run it through the inference model we defined above, and save the AI analysis to a new field called ai_summary.

JSON

PUT _ingest/pipeline/log_ai_enrichment_pipeline
{
"description": "Analyzes error logs using local Ollama instance",
"processors": [
{
"inference": {
"model_id": "ollama_log_analyzer",
"input_output": [
{
"input_field": "message",
"output_field": "ai_summary"
}
],
"task_settings": {
"user": "Explain this system log error concisely in one sentence and provide a brief fix recommendation."
}
}
}
]
}
Step 5: Route Logs to the Pipeline

When configuring Filebeat, Logstash, or Elastic Agent, specify your new pipeline in the configuration.

For a quick test, manually index a document using the pipeline:

JSON

POST my-system-logs/_doc/1?pipeline=log_ai_enrichment_pipeline
{
"message": "FATAL: connection back-off failure, system.db.Pool empty. Max capacity 50 reached."
}

When you view the document, it will contain a populated ai_summary field containing Ollama’s localized insight.

Option 2: Using the Logstash Mid-Flight Method

If you already use Logstash to process and transform your logs before shipping them to Elasticsearch, you can leverage Logstash’s http filter plugin to interact with Ollama dynamically.

Step 1: Configure logstash.conf

Open your logstash configuration file and place an conditional block in the filter section. You should isolate the AI triggers to error or critical logs so you do not flood your LLM with benign info logs.

Ruby

input {
beats {
port => 5044
}
}
filter {
# Only trigger Ollama on actual system faults
if [log][level] == "error" or [log][level] == "critical" {
http {
url => "http://localhost:11434/api/generate"
method => "post"
# Structuring the payload contextually
body => '{"model": "mistral", "prompt": "Analyze this system error. Provide a 1-sentence root cause explanation and a 1-sentence fix. Log: %{[message]}", "stream": false}'
headers => {
"Content-Type" => "application/json"
}
# Temporary target field for the raw response JSON
target_body => "[@metadata][ollama_raw]"
}
# Extract the clean text out of the API response structure
if [@metadata][ollama_raw] {
json {
source => "[@metadata][ollama_raw]"
target => "[ollama_parsed]"
}
mutate {
add_field => { "ai_analysis" => "%{[ollama_parsed][response]}" }
}
}
}
}
output {
elasticsearch {
hosts => ["http://localhost:9200"]
index => "production-logs-%{+YYYY.MM.dd}"
}
}

Step 6: Mapping the Output in Kibana

No matter which architecture option you choose, the resulting fields flow natively into your indexes.

  1. Head to Kibana -> Discover.
  2. Refresh your index pattern or create a new data view matching my-system-logs-* or production-logs-*.
  3. Add the fields message and ai_analysis (or ai_summary) directly to your active column view for real-time localized troubleshooting triage.

Maximize Engineering Efficiency with Local AI Models

When presenting local AI log analysis to executives, skip the raw code, config files, and API endpoints. Executives care about three things: reducing system downtime, maximizing engineering efficiency, and keeping data secure and cost-effective.

Frame this initiative as a business efficiency upgrade rather than a cool engineering experiment.

1. The Core Pitch (The 30-Second Hook)

“Right now, when a critical system fails, our engineers spend valuable time digging through thousands of lines of cryptic error logs to find the root cause. By integrating a secure, local Large Language Model directly into our existing ELK monitoring stack, we can automatically translate complex raw errors into instant, plain-English root causes and action items. This slashes our Mean Time to Resolution (MTTR), protects our intellectual property, and incurs zero monthly cloud vendor fees.”

2. High-Level Architecture (The Strategic Flow)

Your executive slide deck should simplify the technical implementation down to its raw business value stream. Avoid technical deep-dives on Logstash filters.

[Raw System Logs] ──> [ELK Filtering Engine] ──> [Secure, Local AI (Ollama)] ──> [Kibana Dashboard]
Instant Plain-English
Root Cause & Fixes

3. Key Business Pillars to Highlight

Drop in MTTR (Mean Time to Resolution)
  • The Problem: Junior engineers or on-call staff often struggle to decode advanced stack traces, escalating issues to senior architects and delaying fixes.
  • The AI Solution: The ELK dashboard instantly populates a clear “AI Analysis” field alongside the error. On-call staff can patch the issue immediately without waking up tier-3 support teams.
Ironclad Data Privacy & Security
  • The Problem: Sending proprietary application data, user metadata, or internal system logs to external APIs (like OpenAI or Anthropic) introduces massive compliance risks and potential data leaks.
  • The AI Solution: Ollama runs entirely on-premise on our hardware. Our system logs never leave our secure network perimeter, ensuring full compliance with privacy regulations (GDPR, SOC 2, HIPAA).
Zero Scaling / Token Costs
  • The Problem: Commercial LLM APIs charge per “token” (word fragment). Processing gigabytes of streaming infrastructure logs through a cloud API would generate an astronomical monthly bill.
  • The AI Solution: By leveraging local hardware and open-weights models (like Mistral or Llama), our operational cost is flat-rate power and hardware amortization. No surprise subscription fees or variable usage spikes.

4. Before vs. After (The Visual Reality)

Show the executives exactly what an engineer sees in Kibana today versus what they will see after this implementation.

Metric / ExperienceCurrent State (Without Local AI)Future State (With Ollama Enriched ELK)
Log AppearanceFATAL: connection back-off failure, system.db.Pool empty. Max capacity 50 reached.Same log, plus:
[AI Analysis] Root Cause: DB connection pool exhausted. Fix: Audit connection leaks or scale pool capacity.
Initial TriageRequires specialized database/infrastructure knowledge to trace.Readable by any tier-1 support engineer or operator immediately.
Resolution Speed30 to 60+ minutes of searching documentation and internal wikis.Under 5 minutes to identify the vector of failure and deploy the patch.

5. Proposed Next Steps (The Proof of Concept)

Conclude by asking for approval to run a low-risk, zero-budget trial.

  • Phase 1 (2 Weeks): Spin up a local instance on an existing development machine. Route a non-production log stream (e.g., staging environment) into it.
  • Phase 2 (1 Week): Measure accuracy and evaluate the quality of the AI’s troubleshooting suggestions with the engineering team.
  • Phase 3: Report back on verified time-savings before asking for dedicated production hardware resources (GPUs).

Integrate Ollama with ELK Stack for AI-Driven Logs

Here is how to set up Ollama on your computer to run large language models locally.

1. Download and Install

  • Mac: Download the zip file from the Ollama website, unzip it, and drag Ollama to your Applications folder.
  • Windows: Download the Windows installer (OllamaSetup.exe) from the website and run it.
  • Linux: Run the following command in your terminal:Bashcurl -fsSL https://ollama.com/install.sh | sh

2. Verify the Installation

Open your terminal (Mac/Linux) or Command Prompt/PowerShell (Windows) and type:

Bash

ollama --version

If it returns a version number, Ollama is running.

3. Run a Model

To download and start chatting with a model, use the ollama run command followed by the model name. For example, to run Llama 3:

Bash

ollama run llama3

The first time you run this, Ollama will download the model weights (usually a few gigabytes), so it might take a few minutes depending on your internet speed.

Once the download finishes, you will see a >>> prompt. You can now type your questions and chat with the model directly in your terminal.

4. Useful Commands

  • /bye : Type this inside the chat prompt to exit the model.
  • ollama list : Shows all the models you have downloaded on your machine.
  • ollama rm <model_name> : Deletes a downloaded model to free up space.
  • ollama pull <model_name> : Downloads or updates a model without opening the chat interface.

Popular Models to Try

  • ollama run mistral (Great all-rounder)
  • ollama run phi3 (Lightweight and fast for lower-spec machines)
  • ollama run codegemma (Tuned for coding tasks)

Integrating Ollama with the ELK Stack (Elasticsearch, Logstash, Kibana) allows you to bring the power of localized Large Language Models directly to your log telemetry. Instead of manually writing complex regex or staring at lines of stack traces, you can use Ollama to explain cryptic error codes, detect anomalous behavior, and summarize massive log spikes.

There are two primary architectural patterns to achieve this:

  • Pattern A (Reactive Pipeline): Passing logs through a Python script or Logstash webhook into Ollama before indexing them into Elasticsearch.
  • Pattern B (Elastic Inference API): Using Elasticsearch’s native AI capabilities to query Ollama directly as an external inference service.

Below is the implementation guide for Pattern A, which is the most reliable, customizable, and widely used method for custom AI log processing.

The Architecture

  1. Logstash / Filebeat collects the logs.
  2. An Intermediate Processor (Logstash Webhook or a Python Worker) intercepts the logs, calls Ollama’s local HTTP API, and gets an AI summary or anomaly score.
  3. The enriched log (Original data + AI Explanation) is indexed into Elasticsearch.
  4. You visualize the AI-generated insights in Kibana.

Step 1: Prepare your Local Ollama Model

You want a model that is fast and skilled at code or technical troubleshooting. Mistral, Llama3, or Phi3 are highly recommended.

  1. Start Ollama and pull your model:Bashollama pull mistral
  2. Verify that Ollama’s local API is listening on port 11434 by querying it via curl:Bashcurl http://localhost:11434/api/generate -d '{ "model": "mistral", "prompt": "What does a 500 Internal Server Error mean?", "stream": false }'

Step 2: Set up the Ingestion and AI Enrichment

Because logs stream continuously and can overwhelm an LLM, you typically want to filter logs so only Errors or Warnings get sent to Ollama.

You can accomplish this using Logstash’s HTTP Filter plugin to dynamically call Ollama during ingestion.

Logstash Configuration (logstash.conf)

Ruby

input {
# Your standard log input (e.g., Filebeat, Syslog, Beats)
beats {
port => 5044
}
}
filter {
# 1. Filter out info logs; only process actual errors through the LLM to save CPU/GPU cycles
if [log][level] == "error" or [log][level] == "critical" {
# 2. Use the HTTP filter to hit Ollama's local API
http {
url => "http://localhost:11434/api/generate"
method => "post"
# Craft a robust system prompt + your raw log message
body => '{"model": "mistral", "prompt": "Analyze this system log. Provide a 1-sentence root cause explanation and a 1-sentence fix. Log: %{[message]}", "stream": false}'
headers => {
"Content-Type" => "application/json"
}
# Target field where Ollama's JSON response will land
target_body => "[@metadata][ollama_response]"
}
# 3. Parse out the textual string from Ollama's JSON structure
if [@metadata][ollama_response] {
json {
source => "[@metadata][ollama_response]"
target => "[ollama]"
}
# Rename the output to a clean root-level field
mutate {
add_field => { "ai_analysis" => "%{[ollama][response]}" }
}
}
}
}
output {
elasticsearch {
hosts => ["http://localhost:9200"]
index => "ollama-enriched-logs-%{+YYYY.MM.dd}"
# user => "elastic" # Uncomment if security is enabled
# password => "changeme" # Uncomment if security is enabled
}
}

Step 3: View the Results in Kibana

Once Logstash restarts with the updated configuration, look at your incoming indices.

  1. Go to Kibana -> Management -> Data Views and create a view for ollama-enriched-logs-*.
  2. Navigate to Discover.
  3. Add the field message (your raw system error) alongside your brand new custom field: ai_analysis.
Example of what you’ll see in Kibana:
  • message: [2026-07-08 14:02:11] FATAL: connection back-off failure, system.db.Pool empty. Max capacity 50 reached.
  • ai_analysis: Root Cause: The application has exhausted its database connection pool because connections aren’t being closed properly. Fix: Increase the max_connections parameter in your database configuration or audit your code for connection leaks.

Advanced Architecture Strategy: Vector Search (RAG)

If you have massive logs and don’t want Logstash to trigger Ollama sequentially for every single error, you should shift to a RAG (Retrieval-Augmented Generation) workflow using Elasticsearch as a Vector Database.

  1. You use an embedding model (like ollama pull nomic-embed-text) to convert error logs into vectors.
  2. Store these vectors in Elasticsearch natively using the dense_vector field type.
  3. When a new system anomaly breaks out, write a Python/LangChain script to fetch similar past errors from Elasticsearch, bundle them together, and feed them into Ollama. This lets Ollama explain the current issue using historical context unique to your company’s network stack.

Introducing Gordon: The AI Agent for Docker Users

Gordon is Docker’s official built-in AI agent.

Instead of being a generic AI assistant (like ChatGPT or Claude) where you have to manually copy and paste error logs, Gordon is purpose-built to understand your actual containerized environment. It is integrated directly into Docker Desktop and the Docker CLI.

Here is a quick overview of what Gordon does and how to use it:

1. What Makes Gordon Different?

Most AI assistants guess based on what you paste. Gordon has direct, secure access to your system (with your approval) to check the real state of your machine:

  • Real Context: It can read your running containers, inspect logs, look at your docker-compose.yml files, and analyze your local project directories.
  • Action-Oriented: If a container crashes with a vague exit code, Gordon doesn’t just explain what the code means; it can look at the logs, pinpoint the issue, rewrite the Dockerfile, and offer a button for you to approve the fix.
  • Approval First: Gordon will never execute a command, modify a file, or stop a container without showing you the exact command first and waiting for your permission.

2. Main Capabilities

  • Debugging: “My container exited with code 137, why?” Gordon will check your local memory limits, see if it was an Out-Of-Memory (OOM) error, and propose a fix.
  • Containerization: “Make this Node.js app run in Docker.” Gordon will scan your directory, detect dependencies, and write optimized multi-stage Dockerfiles.
  • Optimization & Security: It can review your active Docker files and recommend ways to reduce image sizes or implement security health checks.

3. How to Use It

  • In Docker Desktop: You will see the Gordon icon in the left sidebar. You can open it, select your project folder, and start chatting.
  • In the Terminal: You can interact with it directly by running:Bashdocker ai This opens an interactive terminal assistant that lets you ask questions like “Why is my container unhealthy?” or “Clean up my unused volumes”, giving you commands you can hit y to approve and execute immediately.

Run Large Language Models Locally with Ollama

Ollama

Ollama is a free, open-source tool that lets you run large language models (LLMs) locally on your own machine — no cloud, no API keys, no data leaving your computer.


Core Idea

Instead of calling OpenAI/Anthropic APIs, you download and run models directly:

ollama run llama3.2
# → pulls the model, starts a chat in your terminal

That’s it. A full LLM running locally.


What It Does

  • Downloads and manages models from a model registry
  • Serves a local REST API (compatible with OpenAI’s API format)
  • Handles all the complexity of quantization, GPU layers, memory management
  • Runs on Mac, Linux, and Windows

Hardware Support

HardwareSupport
Apple Silicon (M1/M2/M3/M4)Excellent — uses Metal GPU
NVIDIA GPUGreat — uses CUDA
AMD GPUSupported via ROCm
CPU onlyWorks, but slow for large models

Apple Silicon Macs are particularly well-suited because of unified memory — a MacBook Pro with 32GB RAM can run surprisingly capable models.


Model Library

Ollama hosts a registry at ollama.com/library. Popular models include:

ModelSizeGood For
llama3.23B / 8BGeneral chat, fast
llama3.18B / 70BStrong general purpose
mistral7BFast, capable
gemma34B / 12B / 27BGoogle’s open model
phi414BMicrosoft, efficient
deepseek-r17B–671BReasoning/coding
codellama7B–70BCode generation
nomic-embed-textEmbeddings
llava7B / 13BVision + language

Models are quantized (compressed) to fit consumer hardware — e.g., a 7B model typically needs ~4–8GB of RAM/VRAM.


CLI Commands

# Run a model (downloads if not present)
ollama run llama3.2
# Pull a model without running it
ollama pull mistral
# List installed models
ollama list
# Remove a model
ollama rm llama3.2
# Show model info
ollama show llama3.2
# Run a specific quantization
ollama run llama3.2:8b-instruct-q5_K_M
# Serve the API (runs automatically, but can be explicit)
ollama serve

REST API

Ollama exposes a local API on port 11434:

# Generate (streaming)
curl http://localhost:11434/api/generate -d '{
"model": "llama3.2",
"prompt": "Explain Loki in one sentence"
}'
# Chat (OpenAI-compatible)
curl http://localhost:11434/v1/chat/completions -d '{
"model": "llama3.2",
"messages": [{"role": "user", "content": "Hello!"}]
}'

The OpenAI-compatible endpoint (/v1/...) means you can drop Ollama into any app that uses the OpenAI SDK by just changing the base URL.


Using with OpenAI SDK

from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="ollama" # required by SDK, value doesn't matter
)
response = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)

Modelfile — Custom Models

You can create custom models with a Modelfile, similar to a Dockerfile:

FROM llama3.2
# Set system prompt
SYSTEM """
You are a helpful DevOps assistant who specializes in
Kubernetes, Prometheus, and Grafana Loki.
"""
# Set parameters
PARAMETER temperature 0.7
PARAMETER num_ctx 4096
ollama create devops-assistant -f Modelfile
ollama run devops-assistant

Integrations

Ollama works with a huge ecosystem:

ToolUse Case
Open WebUIChatGPT-like browser UI for Ollama
LangChain / LlamaIndexRAG pipelines, agents
Continue.devVS Code AI coding assistant
Dify / FlowiseNo-code LLM app builders
Obsidian pluginsLocal AI in your notes
EnchantedNative macOS UI for Ollama

Ollama vs Alternatives

OllamaLM Studiollama.cpp
Ease of useVery easyVery easy (GUI)Technical
API serverBuilt-inBuilt-inManual setup
Model managementCLI registryGUI downloadManual
CustomizationModelfileLimitedFull control
Best forDevelopersNon-technical usersPower users

Common Use Cases

  • Privacy-first AI — sensitive data never leaves your machine
  • Offline use — works without internet after model download
  • Local RAG — pair with a vector DB for document Q&A
  • Development/testing — prototype without API costs
  • Self-hosted AI tools — run your own Copilot, chatbot, etc.

Quick Setup

# macOS
brew install ollama
# Linux
curl -fsSL https://ollama.com/install.sh | sh
# Then run your first model
ollama run llama3.2

Key Takeaways

  1. Easiest way to run LLMs locally
  2. OpenAI-compatible API — drop-in for many existing tools
  3. Great on Apple Silicon — unified memory is a big advantage
  4. Model quality has exploded — modern 7B models are genuinely useful
  5. Privacy by default — nothing leaves your machine

Enhancing IT Infrastructure with AIOps: A Strategic Roadmap

Executive Summary: Project “Sentinel

Transitioning from Reactive Maintenance to Predictive AIOps

The Vision

To transform our servers infrastructure from a collection of “isolated silos” into a high-visibility, AI-enhanced ecosystem. This project moves the IT department away from emergency “firefighting” and toward a data-driven model that identifies and resolves system failures before they impact business operations.


The Two-Phase Strategic Roadmap

Phase 1: Foundations of Visibility (Current)

  • Centralized Observation: Implementation of a “Single Pane of Glass” (Grafana) to monitor Linux, Windows, and Docker environments.
  • Data Integrity: Established a 90-day high-resolution data retention policy for quarterly auditing and compliance.
  • Zero-Risk Lifecycle: Integrated vSphere snapshot protocols into the patching workflow to ensure 100% recovery capability.
  • Outcome: Eliminated “blind spots” and reduced the time to detect system failures by [X]%.

Phase 2: The AIOps Intelligence Layer (Upcoming)

  • Predictive Forecasting: Deploying Machine Learning models to analyze usage trends, providing the team with 48-hour warnings for hardware exhaustion (Disk/RAM).
  • Generative Incident Response: Linking monitoring alerts to AI-driven “Repair Guides,” providing junior staff with instant troubleshooting steps and reducing senior engineer escalations.
  • Anomaly Detection: Utilizing “Heartbeat” algorithms to identify subtle system irregularities that traditional monitoring misses.
  • Outcome: Transitioning to Zero-Downtime operations and reducing Mean Time to Repair (MTTR).

Wins for your “Phase 2” Roadmap

  1. Zero Cost: We are using open-source models. There are no monthly subscription fees for the AI.
  2. Data Sovereignty: Our server IP addresses, log files, and infrastructure names stay on our hardware. Nothing is sent to the cloud.
  3. Low Latency: Since the AI is in the same data center (or even the same server) as Prometheus, alerts are enriched with AI fixes in milliseconds.

Business Value Proposition

  • Cost Avoidance: Utilizing an open-source architecture to save an estimated $10,000 – $15,000 annually in enterprise licensing fees.
  • Operational Efficiency: AI-enriched alerts act as a “Force Multiplier,” allowing our current team to manage a growing fleet without increasing headcount.
  • Business Continuity: Shifting from reactive repairs to planned maintenance, ensuring our critical applications (Email, Databases, Docker apps) remain online 24/7.

Enhance Monitoring with AI: Predictive and Generative Alerting

To achieve both Predictive Maintenance (knowing when things will fail) and Generative Alerting (getting an AI explanation of the failure), you need to build an “AI Feedback Loop” around your existing Prometheus and Grafana stack.

Here is how you can implement both for your fleet:


1. Predictive: The “Forecasting” Layer

This uses mathematical AI (Linear Regression) to look at your current trends and project them into the future. It’s perfect for preventing “Disk Full” or “Memory Exhaustion” crashes.

How to set it up in Grafana:

  1. Create a new Alert Rule.
  2. Use this formula to predict if a disk will be full in 24 hours based on the last 6 hours of data:$$predict\_linear(node\_filesystem\_free\_bytes{job=”nodes”}[6h], 86400) < 0$$
  3. The Result: Instead of waiting for the disk to hit 95%, the AI alerts you when the trend indicates you are 24 hours away from disaster.

2. Generative: The “Explainable” Layer

This is the most “impressive” part for your Executive Director. It converts technical errors into plain English. Since you have a Mail Server (Postfix) and Grafana, you can use a “Webhook” to send alerts through an AI.

The Workflow:

  1. Trigger: A Pilot Group server crashes.
  2. Webhook: Grafana sends the alert JSON to a simple Python script or an automation tool like n8n or Make.com.
  3. AI Processing: The script sends the error to an LLM (OpenAI or a local Llama model) with this prompt:“I am a Linux admin. I received this alert: [Alert Data]. Explain what happened and give me 3 commands to fix it on Ubuntu.”
  4. Delivery: The AI sends a clean, formatted email through your Postfix server.

3. Integrated Tooling: Netdata

If you want both of these features without writing custom code, I highly recommend installing Netdata on your pilot group.

  • Machine Learning (ML): Netdata has an “Anomaly Advisor” built-in. It trains a model on every single metric (CPU, Disk, Net) every hour.
  • AIOps: It highlights “unusual” behavior in violet on the graphs. If your mail server suddenly starts sending 1,000% more mail than usual, the AI marks it as an anomaly before you even set an alert.

4. Implementation Plan for your 20 Servers

PhaseActionAI Benefit
Step 1Add predict_linear queries to Grafana.Predictive: No more emergency disk-clearing at 2 AM.
Step 2Use Grafana Play-app or n8n to link Alerts to an LLM.Generative: Your team gets “Smart Alerts” with solutions included.
Step 3Install a local AI (like Ollama) on your central server.Privacy: Keep your server data local while still getting AI insights.

How to Present This to Your Director

When you talk to the Executive Director, frame it like this:

“We are moving from Traditional Monitoring to AIOps.

  1. Predictive AI will save us money by preventing downtime before it happens.
  2. Generative AI will act as a ‘Force Multiplier’ for the team, providing instant troubleshooting steps for any system error, reducing our recovery time by 80%.”

Integrating AI in Monitoring: From Observability to AIOps

Integrating AI into a monitoring stack (Prometheus + Grafana + cAdvisor) moves you from Observability (seeing what happened) to AIOps (predicting what will happen).

For your fleet of 20 servers, here are three ways to integrate AI, ranked from easiest to most advanced:


1. The “Quick Win”: Grafana’s Machine Learning (ML)

Grafana has built-in “Machine Learning” features that can detect anomalies. Instead of setting a static alert (e.g., “Alert me if CPU > 90%”), the AI learns the “normal” pattern of your pilot group.

  • How it works: It uses a “Holt-Winters” or “Prophet” algorithm to create a “predicted band” of behavior.
  • Use Case: If a server normally runs at 10% CPU at 3:00 AM, but suddenly jumps to 40%, the AI triggers an alert because that is “abnormal” for that specific time, even though 40% isn’t “high.”
  • Implementation: In Grafana, go to Machine Learning > Outlier Detection. You can select your Prometheus metrics as the source.

2. Intelligent Log Analysis (The “GPT” Layer)

Since you are using Postfix and Docker, you generate thousands of log lines. You can use an LLM (like GPT-4 or a local Llama 3 model) to analyze errors.

  • How it works: When a container in your pilot group crashes, a script sends the last 50 lines of the docker logs to an AI API.
  • The Result: Instead of an email saying “Container Exit 137,” you get an email saying: “Your cAdvisor container crashed due to an Out-of-Memory (OOM) error. Suggestion: Increase the memory limit in your docker run command.”
  • Tool: Vector or Loki can pipe logs into an AI processing script.

3. Predictive Forecasting (Capacity Planning)

You can use AI to predict when your 20 servers will run out of disk space.

  • How it works: Prometheus provides a predict_linear function, which is a basic form of regression AI.
  • The Query: “`promqlpredict_linear(node_filesystem_free_bytes[4h], 3600 * 24 * 7) < 0*This tells the AI: "Look at the last 4 hours of disk usage trends. If we continue at this exact rate, will we hit zero bytes in the next 7 days?"*
  • Executive Value: You can tell your Director: “The AI predicts we will need more storage on Server #09 by next Tuesday.”

4. Open Source AIOps Tools

If you want a dedicated AI “Brain” for your project, look at these:

ToolAI Function
Netdata (ML)Automatically detects “anomalies” across all 20 nodes with zero config.
Robusta.devAn open-source AI engine specifically for Kubernetes/Docker that explains why an alert happened.
KeepAn AIOps alert manager that uses AI to group 100 small alerts into 1 meaningful “Incident.”

Which path fits your goal?

Next post I will explain two scenarios :

1. predict hardware failure (Predictive)

2. an AI that explains your alerts in plain English (Generative).