123DevOps··11 min read

AI with Python: the practical guide from environment to libraries (ML, LLMs, and RAG)

How to set up an AI project in Python the right way with venv, pip, and uv, which libraries to use for data, machine learning, and LLMs, an end-to-end tour with pandas, scikit-learn, and the Anthropic SDK, and good practices for tests, cost, secrets, and security.

AI

Almost every AI tutorial starts with an import in Python. The hard part is knowing which library to use, building a project that runs the same on your machine and in CI, and getting from the notebook to production. This guide is the starting point of the series: environment, library map, an end-to-end tour, and three paths to go deeper.

If AI, machine learning, and LLMs still blur together for you, read what is AI, machine learning, and an LLM first.

Why Python dominates AI

  • Ecosystem. numpy, pandas, scikit-learn, PyTorch, and transformers make up a mature stack. The heavy lifting runs in C, C++, Fortran, or on the GPU; Python is the glue.
  • Notebooks. Jupyter lets you explore data cell by cell, with tables and charts next to the code.
  • Official SDKs. Anthropic, OpenAI, and Google maintain official Python SDKs, and so does Ollama. Documentation examples usually show up in Python first.

The limits are real too:

  • Speed. A for loop in pure Python over millions of rows is slow. The fix is to vectorize with numpy and pandas. For very high-concurrency services or tools shipped as a single binary, Go and Rust are often better choices.
  • Packaging. Conflicting versions, native dependencies, GPU drivers, and the classic “works on my machine.” That’s why the next section exists.

To compare with other languages, see programming languages for DevOps.

Setting up a project the right way

The golden rule: one isolated environment per project. Never install packages into the system Python.

venv and pip: the path that ships with Python

python3 -m venv .venv
source .venv/bin/activate          # on Windows: .venv\Scripts\activate
pip install pandas scikit-learn anthropic
pip freeze > requirements.txt      # records exact versions, including indirect ones

It works everywhere, but you have to remember to activate the venv and to update requirements.txt.

uv: the same result, faster, with a lockfile

uv installs packages, creates the venv, and even downloads the Python version the project asks for. The commands below were tested with uv 0.13.9:

uv init my-ai-project
cd my-ai-project
uv add scikit-learn anthropic      # writes to pyproject.toml and pins everything in uv.lock
uv add pandas pydantic
uv add --dev pytest                # development-only dependency
uv run python tour.py              # runs in the project venv, created automatically
uv run pytest

uv init creates pyproject.toml, .python-version, a .gitignore, a Git repository, and some starter code. uv add writes a lower bound to pyproject.toml (such as anthropic>=2.14.0) and the exact version of every package, including indirect ones, to uv.lock. Commit both. On another machine or in CI, uv sync --locked recreates exactly the same environment and fails if the lockfile is out of date.

Pinned versions and .env out of Git

AI libraries move fast, and a major version of an SDK can rename methods and parameters. The lockfile makes sure today’s code runs the same six months from now. Upgrade on purpose, one package at a time, and run the tests right after: uv lock --upgrade-package anthropic.

API keys and settings go in a .env file, which never goes into Git:

ANTHROPIC_API_KEY=put-your-key-here
CLAUDE_MODEL=copy-the-id-from-the-models-page
echo ".env" >> .gitignore           # the .gitignore created by uv init doesn't include .env
uv run --env-file .env python diagnosis.py

The examples in this guide don’t hardcode model names: they read CLAUDE_MODEL (and, in the other articles, OPENAI_MODEL, GEMINI_MODEL, and OLLAMA_MODEL). Copy the current id from each provider’s models page. So the team knows which variables exist, commit a .env.example with no values.

Jupyter or scripts?

Use the notebook to explore data and try ideas. Use scripts for anything that runs again: cron, CI, an API. Notebooks hide execution order, produce bad diffs in Git, and keep outputs that may contain sensitive data. A good flow: explore in the notebook, move the functions into .py files, and import them into the notebook.

uv run --with jupyter jupyter lab  # Jupyter for this run only, kept out of pyproject.toml

The library map

Area Library What it’s for Tested version
Data numpy Fast arrays and linear algebra, the base of almost everything 2.5.5
Data pandas Tables (DataFrames): read CSV, filter, group 3.1.1
Classic ML scikit-learn Classification, regression, clustering, and anomaly detection 1.9.1
Deep learning PyTorch Neural networks, GPU training not installed in this guide
Pre-trained models transformers (Hugging Face) Download and run open text, vision, and audio models not installed in this guide
LLM SDK anthropic Claude API 2.14.0
LLM SDK openai OpenAI API 3.59.0
LLM SDK google-genai Gemini API 3.6.1
LLM SDK ollama Local models via Ollama not installed in this guide
Validation pydantic Validate data and structured outputs with type hints 2.14.4

Versions tested in November 2026 with Python 3.15. Where to start: the basics of numpy and pandas, because everything talks in arrays and DataFrames; then scikit-learn, which teaches the train, evaluate, and predict cycle; then one LLM SDK together with pydantic. PyTorch and transformers can wait until you need to train or fine-tune models.

A tiny end-to-end tour

The scenario: you have the p95 latency and the error rate of ten services. pandas reads the data, scikit-learn points out the service that’s out of pattern, and the script builds a prompt ready for an LLM to suggest hypotheses.

Data and detection with pandas and scikit-learn

"""Tour: pandas reads latencies, scikit-learn finds the outlier, and the script builds the prompt."""
import io

import pandas as pd
from sklearn.ensemble import IsolationForest

CSV = """service,p95_latency_ms,errors_per_min
checkout,180,1
login,95,0
search,140,1
catalog,120,0
payments,950,14
cart,160,1
profile,110,0
shipping,150,2
inventory,130,1
notifications,105,0
"""


def detect_anomalies(df: pd.DataFrame) -> pd.DataFrame:
    """Return the rows that IsolationForest flags as out of pattern."""
    model = IsolationForest(contamination=0.1, random_state=42)
    labels = model.fit_predict(df[["p95_latency_ms", "errors_per_min"]])
    return df[labels == -1]  # -1 = anomaly, 1 = normal


def build_prompt(anomalies: pd.DataFrame) -> str:
    table = anomalies.to_string(index=False)
    return (
        "The anomaly detector flagged these services:\n\n"
        f"{table}\n\n"
        "List 3 likely hypotheses and the first command you would run "
        "to confirm each one. Answer in at most 150 words."
    )


if __name__ == "__main__":
    df = pd.read_csv(io.StringIO(CSV))
    print(df.describe().loc[["mean", "50%", "max"]])
    anomalies = detect_anomalies(df)
    print("\nAnomalies:\n", anomalies, sep="")
    print("\nPrompt:\n" + build_prompt(anomalies))

Output of uv run python tour.py:

      p95_latency_ms  errors_per_min
mean           214.0             2.0
50%            135.0             1.0
max            950.0            14.0

Anomalies:
    service  p95_latency_ms  errors_per_min
4  payments             950              14

Prompt:
The anomaly detector flagged these services:

 service  p95_latency_ms  errors_per_min
payments             950              14

List 3 likely hypotheses and the first command you would run to confirm each one. Answer in at most 150 words.

IsolationForest isolates points with random splits: whatever gets separated with few splits is an anomaly. contamination=0.1 says you expect about 10% anomalies, and random_state makes the result reproducible. Notice the division of labor: the numbers stay with classic ML, which is cheap and deterministic; the LLM only explains.

From finding to LLM

Save this as diagnosis.py, next to tour.py:

import io
import os

import anthropic
import pandas as pd

from tour import CSV, build_prompt, detect_anomalies

df = pd.read_csv(io.StringIO(CSV))
prompt = build_prompt(detect_anomalies(df))

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment
response = client.messages.create(
    model=os.environ["CLAUDE_MODEL"],
    max_tokens=1024,
    system="You are an experienced SRE. Be direct and don't make up data.",
    messages=[{"role": "user", "content": prompt}],
)

for block in response.content:
    if block.type == "text":
        print(block.text)

response.content is a list of blocks, which is why the loop prints only the text ones. The model receives only the summary of the finding, not the raw data: the prompt is smaller, cheaper, and exposes less information. The hypotheses that come back are suggestions for an on-call engineer to confirm, not a diagnosis.

Three paths from here

Local vs API models

Through an API you use large models without managing hardware, but the data goes to the provider. With a local model, the text never leaves the machine, which helps with privacy laws such as Brazil’s LGPD or the GDPR, in exchange for hardware, operations, and usually smaller models. Follow your company’s data policy and check the terms of your plan. To get started locally, see Ollama with Python.

Good practices

Type hints and pydantic

Type hints document the contract of your functions and let the editor catch errors before you run anything. pydantic goes further and validates data at runtime, which is useful on input (CSV, APIs) and on structured LLM output:

from pydantic import BaseModel, Field, ValidationError


class Measurement(BaseModel):
    service: str = Field(min_length=1)
    p95_latency_ms: float = Field(gt=0)
    errors_per_min: int = Field(ge=0)


rows = [
    {"service": "checkout", "p95_latency_ms": "180", "errors_per_min": 1},
    {"service": "search", "p95_latency_ms": -5, "errors_per_min": 0},
]

for row in rows:
    try:
        print(Measurement.model_validate(row))
    except ValidationError as error:
        first = error.errors()[0]
        print(f"row skipped: {first['loc'][0]} -> {first['msg']}")

The string "180" becomes 180.0; the negative latency is rejected with a clear message instead of polluting the analysis.

Tests

Test the deterministic part: detection and prompt building. Save this as test_tour.py and run uv run pytest:

import pandas as pd

from tour import build_prompt, detect_anomalies


def test_flags_only_the_slow_service():
    df = pd.DataFrame({
        "service": [f"svc{i}" for i in range(9)] + ["slow"],
        "p95_latency_ms": [100, 110, 120, 105, 115, 130, 125, 108, 112, 2000],
        "errors_per_min": [0, 1, 0, 1, 0, 1, 0, 0, 1, 30],
    })
    assert detect_anomalies(df)["service"].tolist() == ["slow"]


def test_prompt_carries_the_finding():
    anomalies = pd.DataFrame(
        {"service": ["payments"], "p95_latency_ms": [950], "errors_per_min": [14]}
    )
    assert "payments" in build_prompt(anomalies)

Unit tests don’t call the paid API. Answer quality is measured with dedicated evaluations; see LLMOps: evaluation and observability.

Cost and latency of every call

Every LLM call costs tokens and time. Log both from day one:

import logging
import os
import time

import anthropic

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("llm")

client = anthropic.Anthropic(max_retries=3, timeout=60.0)


def ask(prompt: str) -> str:
    start = time.perf_counter()
    response = client.messages.create(
        model=os.environ["CLAUDE_MODEL"],
        max_tokens=1024,
        messages=[{"role": "user", "content": prompt}],
    )
    latency_ms = (time.perf_counter() - start) * 1000
    log.info(
        "llm_call model=%s latency_ms=%.0f input_tokens=%d output_tokens=%d stop=%s",
        response.model,
        latency_ms,
        response.usage.input_tokens,
        response.usage.output_tokens,
        response.stop_reason,
    )
    return "".join(b.text for b in response.content if b.type == "text")


if __name__ == "__main__":
    print(ask("Explain what an SLO is in one sentence."))

The SDK already retries transient errors on its own, such as rate limits and 5xx failures; max_retries and timeout tune that behavior. With input and output tokens in the log, you multiply by the provider’s price list and get the cost per request and per feature. See FinOps for AI: cost per token.

Secrets

  • Keys live in environment variables or a secrets manager, never in code, notebooks, or Git. See environment variables and the 12-factor app.
  • Use one key per environment and per application, with a spending limit when the provider offers one, and revoke it immediately if it leaks.

Security

  • Treat model output as untrusted input: never pass it to eval, exec, or a shell without validation.
  • Logs, tickets, and documents can carry prompt injection. Mark that content as data in the prompt and don’t give the model the power to act on its own.
  • Don’t send personal data or secrets to the provider without approval. See the risks in AI application security and the OWASP Top 10 for LLMs.

Checklist

  • I created one isolated environment per project (venv or uv), never in the system Python
  • I committed pyproject.toml and uv.lock (or a requirements.txt with exact versions)
  • I added .env to .gitignore and read keys and model ids from environment variables
  • I let classic ML handle the numbers and the LLM handle only the explanation
  • I validate inputs and outputs with pydantic and test the deterministic part with pytest
  • I log latency and tokens for every LLM call
  • I treat model output as untrusted data

Python is just the glue; what makes an AI project work is a reproducible environment, validated data, and someone checking what the model answers.

Get updates on new posts and stay in the loop!