ops-agent: A LangGraph Agentic SRE Copilot

How ops-agent’s orchestrator delegates to fifteen scoped subagents, and the LangGraph mechanics — interrupt/resume, a CNPG-backed checkpointer — behind it.

k8s-docs answers questions the documentation already has the answer to. A lot of real SRE questions aren't like that — "is this pod actually healthy right now," "does this image have known CVEs," "restart the crashlooping pod in yana-stocks." Those need to touch live systems, not just retrieve text, and some of them need to act, not just answer.

ops-agent is the second app in the ml repo: an SRE copilot for this on-prem cloud, built on deepagents and LangGraph, live at ml.yanatech.co.uk/ops-agent behind Authentik. One orchestrator, fifteen subagents, one write path that always stops and asks first. This post is about how that's actually put together, two real production bugs it caused and then fixed, and the LangGraph mechanics behind letting an agent take real action safely.


LangChain, LangGraph, deepagents — Briefly

Three names, three layers, each built on the one below it — not three ways to say the same thing.

LangChain is the base library: a standard interface for calling different model providers, wrapping a Python function as a tool an LLM can invoke, and composing reusable pieces like memory and output parsing. It's also the umbrella project — LangGraph and deepagents come from the same team, not a separate one. ops-agent reaches into LangChain directly for one specific thing, its agent middleware system (langchain.agents.middleware), to gate a tool call behind human approval — covered further down.

LangGraph is the execution engine underneath. LangChain's original abstraction was a chain: a fixed, linear sequence of steps. Real agents don't run that way — they loop, call a tool, look at the result, and decide what to do next, sometimes for many steps, sometimes doubling back. LangGraph models that as a graph instead of a chain: nodes and edges, with state that persists at every step. That persistence is what makes two things possible that a plain chain can't do: resuming a long-running agent exactly where it left off, and pausing mid-execution to wait on a human — which is exactly what ops-agent's remediation-approval flow depends on.

deepagents is the opinionated layer on top of LangGraph. It doesn't introduce new primitives — it packages one specific, proven agent shape: an orchestrator that plans and delegates, plus named subagents it hands focused sub-tasks to, each with its own scoped tools and system prompt. Building that shape by hand in raw LangGraph is possible but tedious; deepagents gives you create_deep_agent() and one list of subagent definitions, and you're most of the way there. That's ops-agent's entire architecture, in the section below.

ops-agent architecture: a user question reaches an orchestrator built with deepagents create_deep_agent, which delegates to four grouped clusters of subagents — Cluster and Workloads, GitOps and Delivery, Infra and Hypervisor, and a dashed HITL-gated write path — fifteen subagents total

One Orchestrator, Fifteen Scoped Subagents

In code, a subagent in this codebase is just a dict — name, description, system_prompt, tools, and optionally interrupt_on:

{
    "name": "cluster-inspector",
    "description": (
        "Inspects the CURRENT live state of the Kubernetes cluster — pod "
        "status, deployment replica health and image tags, recent events, "
        "node readiness, and KEDA ScaledObject/HPA autoscaling status. "
        "Use for 'is X healthy right now', 'what image is X running', or "
        "'why isn't X scaling up' style questions."
    ),
    "system_prompt": CLUSTER_INSPECTOR_PROMPT,
    "tools": [list_pods, get_deployment, list_events, list_nodes,
              list_scaled_objects, get_hpa_status],
}

Fifteen of these — cluster-inspector, docs-researcher, release, github, proxmox, argocd, observability, storage, network, certs, backup, kafka, harbor, minio, remediate — get handed to create_deep_agent() along with an orchestrator system prompt, and that's the whole agent.

The alternative — one agent, one enormous tool list — sounds simpler and isn't. Every tool call would compete for the model's attention against sixty-plus other tools it might have meant instead, and the system prompt would need to explain all sixty inside one context instead of fifteen focused ones. Splitting by domain means cluster-inspector's system prompt only has to talk about pods and deployments; it never has to know Ceph exists. The narrower the subagent's job, the less there is for the model to get wrong inside it.


Prompt Engineering as API Design

The orchestrator's system prompt is, functionally, a router. It doesn't just name the fifteen subagents — it draws the boundary between each pair that could plausibly overlap, in prose, because that's the only place this codebase gets to say it:

'storage' for CNPG (CloudNativePG) Postgres cluster health... (distinct from 'proxmox', which covers Ceph, the underlying storage pool, not the K8s objects provisioned on top of it)

'kafka' for Strimzi Kafka/KafkaTopic CR status only... NOT consumer lag or real broker-side topic state, which this subagent cannot see

Every one of those parenthetical disambiguations exists because two subagents' names or domains were close enough that the orchestrator picked the wrong one at least once. The system prompt isn't documentation bolted on after the fact — it's the actual dispatch table, and every gap in it is a routing bug waiting to happen.

The same prompt also carries two production-learned performance rules, word for word:

Scope every delegation to exactly what was asked... One or two targeted delegations answer most questions; each subagent call and each of its tool calls costs real time, so unscoped fan-out makes the answer needlessly slow.

When a question does need more than one subagent... delegate to them together in the same turn rather than one at a time waiting for each to finish first — independent delegations run concurrently, so batching them cuts wall-clock time.

Neither of those is a LangGraph feature — they're plain-English instructions that only exist because the first version of this agent was slow, fanned out too wide, and dispatched independent subagent calls serially when nothing prevented running them concurrently.


When Routing Goes Wrong: Two Real Bugs

"Check cilium" was the first one. cluster-inspector doesn't have visibility into kube-system, but nothing initially told the orchestrator that Cilium questions shouldn't go there — so they did, and got answered from a subagent that structurally couldn't see the answer. The fix was a new tool, get_cilium_agent_status, on the network subagent, plus an explicit routing sentence in both prompts.

The second was worse, because the answer wasn't an error — it was confidently wrong. "Check network," with no namespace named, got answered from roughly eight namespaces the model already had in context, out of the real ~40 in the cluster. The report came back "no critical issues," having silently never looked at the other 32.

Two panels: without a discovery tool, check network gets answered from a guessed 8-namespace subset and confidently reports no critical issues, missing 32 real namespaces; with summarize_network_policies, the tool discovers every real namespace live via CoreV1Api.list_namespace and reports an accurate cluster-wide answer

Both bugs are the same bug. Neither subagent had a tool that could answer "what are all the valid values here" — only tools that needed you to already know one. summarize_network_policies fixed the second case by calling CoreV1Api.list_namespace live instead of trusting whatever names were already floating around in context. The morning after finding it, the same shape got checked for and fixed in storage.py's list_cnpg_clusters — which had exactly the same latent bug, a hardcoded namespace map — before it ever produced a wrong answer in production. That's the generalizable rule this whole exercise produced: any tool that needs a specific identifier needs a "list all valid identifiers" companion, or the model will guess.


Human-in-the-Loop, By Design

remediate has two tools — restart_pod, cordon_node — and both are wired with LangChain's HumanInTheLoopMiddleware, the piece mentioned in the primer above. The middleware is the configuration surface; underneath, it pauses execution using LangGraph's own interrupt() primitive — the middleware is what makes that primitive easy to attach to a specific tool with a specific set of allowed responses, rather than something you'd wire up by hand for every tool call:

REMEDIATE_INTERRUPT_ON: dict[str, bool | InterruptOnConfig] = {
    "restart_pod": InterruptOnConfig(allowed_decisions=["approve", "edit", "reject"]),
    "cordon_node": InterruptOnConfig(allowed_decisions=["approve", "edit", "reject"]),
}

allowed_decisions deliberately omits "respond" — that option exists in LangChain's middleware for tools where a human could plausibly answer on the tool's behalf instead of running it, which makes sense for a clarifying-question tool but not for an action tool. There's no sensible synthetic answer a human could give in place of actually restarting a pod. "edit" stays, because an edited call still runs through this codebase's own namespace/guest allowlist validation before it executes — a human editing the target doesn't bypass the safety check, it just changes what the safety check evaluates.

Human-in-the-loop remediation flow: user asks to restart a pod, the orchestrator delegates to remediate which proposes a restart_pod tool call, LangChain's HumanInTheLoopMiddleware pauses the underlying LangGraph run via interrupt() and checkpoints the pending action to ops-agent-pg so it survives across both Deployment replicas, a human reviews and either approves/edits it through to execution against the real Kubernetes API or rejects it and the graph resumes with the rejection noted

The gotcha that isn't in any changelog: HumanInTheLoopMiddleware requires exactly one decision per pending tool call, not one decision for the turn. If a single turn proposes two remediations at once, the approval payload needs two decisions, not one — treating it as "approve this turn" silently drops the second action. The ApproveRequest/DecisionModel pair in main.py models this correctly: a thread_id plus a list of decisions.

None of this survives a pod restart without a durable checkpointer — this is the LangGraph state persistence from the primer, made concrete, and the actual reason ops-agent-pg — a dedicated CNPG cluster, plain Postgres, no pgvector — exists at all:

async with AsyncExitStack() as stack:
    checkpointer = None
    if settings.database_url:
        checkpointer = await stack.enter_async_context(
            AsyncPostgresSaver.from_conn_string(settings.database_url)
        )
        await checkpointer.setup()
    ...
    get_agent(checkpointer=checkpointer)

ops-agent runs two Deployment replicas. Without a shared, durable checkpointer, a pending approval that happened to land on replica A would vanish if the next request hit replica B, or if either pod simply restarted while a human was still deciding. AsyncPostgresSaver makes the interrupted graph state — and everything needed to resume it — a database row instead of in-memory state tied to one process.


What It's Not Allowed to Do

The most consequential design decision in this codebase might be the one that added nothing: when asked whether ops-agent should get raw SSH to the Proxmox hosts, the answer was no. It would have been the first genuinely unscoped command-execution tool in this whole workspace — one tool call away from arbitrary shell access, with every future safety property depending on prompt engineering holding up under adversarial or just-wrong input. Instead, proxmox gained four narrow, typed, read-only tools — get_node_journal, get_node_task_log, get_node_status, list_node_services — each of which can only return the specific thing it's named for. A typed tool can be wrong; it can't be redirected into doing something else.

The same instinct shows up as a two-layer RBAC model: a ClusterRole allowlist at the Kubernetes level (ops-agent-reader, ops-agent-remediator, and several narrow, deliberate cluster-wide exceptions for resource kinds that carry no secrets — nodes, NetworkPolicies, CNPG cluster status, PersistentVolumes), and every tool's own in-code namespace or guest allowlist on top of that. Getting past the Kubernetes RBAC layer still leaves the application-level allowlist in the way. reboot_guest is scoped to exactly two non-Kubernetes Proxmox guests — the cluster's own node VMs are explicitly excluded, because they already have etcd-quorum-aware remediation at the Kubernetes level (cordon_node, kured, kubectl drain), and a raw Proxmox-level reboot of a control-plane node is a different, worse kind of action than anything this agent should be proposing.

Two systems were considered for read access during a later capability audit and rejected on purpose: Authentik and Kong's admin API. Both are control-plane, security-boundary systems for every other service in the workspace — SSO's root of trust, and the live auth-plugin config for everything behind Kong. Neither had a demonstrated incident behind the request, only a hypothetical future one, and neither has a read path this codebase's existing patterns already prove safe. When the justification for a new capability is "might be useful" rather than "this already went wrong once," that's exactly the point to say no.


Was It Worth Building?

The honest answer came from dogfooding it, not from designing it. list_repo_runners — added to check whether self-hosted GitHub Actions runners were actually up — gave wrong advice the first time it was asked a real question: it reported zero runners for ml and suggested configuring self-hosted infrastructure, when the real cause was completely normal — that repo's runner scale set runs minRunners: 0 by design, an ephemeral runner that only exists for the duration of one job. The fix wasn't a code change to the tool, it was teaching the prompt the nuance: which repos are ephemeral-by-design and which ones genuinely mean "nothing is configured" when the list comes back empty. A tool can return perfectly correct data and still produce a wrong answer if the prompt around it doesn't know what "empty" is supposed to mean.

That's the pattern worth taking away from all of it: almost none of the real bugs here were LangGraph bugs, or deepagents bugs, or even Kubernetes RBAC bugs. They were routing and interpretation bugs — a subagent boundary drawn in the wrong place, a tool with no way to discover the full set of valid answers, an empty result with no context for what empty means. The framework got the plumbing right on the first try. Getting the agent to reason correctly about this specific cluster took actually asking it real questions and watching it get some of them wrong.

No ratings yet

Comments

0/2000

Connect