Roadmaps / DevOps & Cloud / Lab 8

Lab 8 of 8 · AI in operations: running AI apps

Explain error logs with a local AI model

Run a small open-source model with Ollama, add an `/explain-log` endpoint that asks it to explain an error line, and test it safely.

Time
60–90 minutes
Cost
Free: the model runs on your computer. It downloads about 400 MB and needs about 2 GB of free memory.

What you learn

DevOps engineers now run AI models next to normal services, and use AI to work faster. In this lab you run an open-source model locally, call it from your app, and add guard rails around it.

  • Running an open-source model with Ollama in Docker
  • Calling a model over HTTP from your service
  • Timeouts, fallbacks and size limits for AI calls
  • Reviewing AI-written infrastructure before you use it

In the AI era: This is the AI era in practice: models are just another dependency to deploy, monitor, secure and pay for, and AI assistants are a tool you check, not a teammate you trust blindly.

Before you start

  • Finish labs 1, 2 and 6. Docker must be running.

Step by step

  1. 1 Start Ollama and download a small model

    Ollama serves open-source models over a simple HTTP API. The second line waits until Ollama has started. qwen2.5:0.5b is small enough for a laptop.

    Run this
    docker run -d --name ollama -p 11434:11434 -v ollama:/root/.ollama ollama/ollama
    until curl -s http://localhost:11434/ > /dev/null; do sleep 2; done
    docker exec ollama ollama pull qwen2.5:0.5b
    OLLAMA=http://localhost:11434
    curl "$OLLAMA/api/generate" -d '{"model": "qwen2.5:0.5b", "prompt": "Say hello in five words.", "stream": false}'
    You should see:

    A JSON answer whose response field contains a short greeting.

  2. 2 Add the AI endpoint

    Create this new file. It sends one log line to the model, keeps the answer short (num_predict), gives up after 2 minutes, refuses very long input, and returns a clear message instead of crashing if the model is unavailable.

    File: app/ai.py
    import os
    
    import httpx
    
    OLLAMA_URL = os.getenv("OLLAMA_URL", "http://localhost:11434")
    MODEL = os.getenv("OLLAMA_MODEL", "qwen2.5:0.5b")
    
    
    def explain_log(line: str) -> str:
        prompt = (
            "You help DevOps engineers. In two short sentences, explain what this log line "
            "means and the most likely fix. Log line:\n" + line
        )
        try:
            response = httpx.post(
                f"{OLLAMA_URL}/api/generate",
                json={
                    "model": MODEL,
                    "prompt": prompt,
                    "stream": False,
                    "options": {"num_predict": 120},
                },
                timeout=120,
            )
            response.raise_for_status()
            return response.json()["response"].strip()
        except (httpx.HTTPError, KeyError):
            return "The AI model is not available right now. Check that Ollama is running."
    
  3. 3 Wire it into the app

    Add these lines to the end of app/main.py. The Field limit stops someone sending a huge request that would be slow and expensive.

    File: app/main.py (add to the end)
    from pydantic import BaseModel, Field
    
    from app.ai import explain_log
    
    
    class LogLine(BaseModel):
        line: str = Field(min_length=1, max_length=2000)
    
    
    @app.post("/explain-log")
    def explain(body: LogLine) -> dict[str, str]:
        REQUESTS.labels(path="/explain-log").inc()
        return {"explanation": explain_log(body.line)}
    
  4. 4 Try it

    Start your app locally (with the virtual environment active), then send it a real-looking error.

    Run this
    uvicorn app.main:app --port 8000
    # in a second terminal:
    curl -s -X POST http://localhost:8000/explain-log -H "content-type: application/json" -d '{"line": "ERROR connection refused: postgres:5432"}'
    You should see:

    A short explanation that mentions the database not accepting connections. The first answer can take up to a minute while the model loads. Small models can be wrong: judge the answer yourself.

  5. 5 Test it without the model

    Tests must not depend on a model being online. This test replaces the AI call with a fake one and also checks the size limit.

    File: tests/test_ai.py
    from fastapi.testclient import TestClient
    
    import app.main as main
    
    client = TestClient(main.app)
    
    
    def test_explain_log_uses_the_model(monkeypatch) -> None:
        monkeypatch.setattr(main, "explain_log", lambda line: f"explained: {line}")
        response = client.post("/explain-log", json={"line": "disk full"})
        assert response.status_code == 200
        assert response.json() == {"explanation": "explained: disk full"}
    
    
    def test_explain_log_rejects_huge_input() -> None:
        response = client.post("/explain-log", json={"line": "x" * 5000})
        assert response.status_code == 422
    
  6. 6 Run all the tests

    Your CI pipeline from lab 3 runs these on every push too.

    Run this
    python -m pytest -q
    You should see:

    3 passed.

  7. 7 Review AI-written infrastructure

    Ask any AI assistant: "Write a Kubernetes HorizontalPodAutoscaler for my ai-status-app deployment, between 2 and 5 replicas at 70% CPU." Save its answer as k8s/hpa.yaml, then check it with the list below before you trust it: correct apiVersion (autoscaling/v2), the right deployment name, sensible min and max, and no secrets or extra permissions. Validate the file format with kubectl.

    Run this
    kubectl apply --dry-run=client -f k8s/hpa.yaml
    You should see:

    horizontalpodautoscaler.autoscaling/ai-status-app created (dry run). If kubectl reports an error, fix the file and explain in your commit message what the AI got wrong.

  8. 8 Commit and clean up

    Stop Ollama when you are done; the downloaded model stays in the ollama volume for next time.

    Run this
    git add app tests k8s
    git commit -m "Add AI log explanation endpoint with tests"
    git push
    docker stop ollama

You are done when

  • /explain-log returns an explanation from the local model.

  • Three tests pass without the model running.

  • You reviewed and validated an AI-written Kubernetes file before committing it.

Finished? Get your proof page

We check your public GitHub repository and give you a page to share with recruiters, and can add the project to your resume.