Observe Agent Workflows with Langfuse

Add Langfuse tracing, scoring, dashboards, and alerts to LangGraph triage CLI.

Introduction

30 Second Summary

When a team of AI agents triages an outage, a confident diagnosis can hide a tool that timed out or a run that cost far more than it should.

In this project, you will add Langfuse tracing to a LangGraph incident-triage app where several AI agents work together, so every agent and tool step, its cost, and whether the diagnosis was right show up in one place. You will then track quality and cost on one dashboard and send an alert to a webhook, a URL that receives messages from other apps, when accuracy drops.

What You'll Build

You will open one Langfuse session where the full path from alert to scored diagnosis is visible.

By the end of this project, you'll have:

  • A step-by-step trace that shows which specialist agent and tool ran for every start or resume command.
  • A searchable failure trail that leads to metric_window and its exact Metrics backend timed out. message.
  • A quality-and-cost dashboard that sends an automatic alert when the root-cause score falls.
  • Secret Mission: Compare two versions of the analyst prompt by speed, text usage, cost, response count, and root-cause score.

Are there any prerequisites?

Before We Start

Before you change the triage app, define the evidence you need it to record. You will focus on what the agents and tools did, how long each incident took, what it cost, and whether the final diagnosis was correct.

Set Up Cloud Shell and Langfuse

To measure changes accurately, you need a working baseline run of the triage app. This step prepares that baseline run inside Google Cloud Shell, a browser-based terminal provided by Google Cloud.

You will run the original workflow before adding tracing code. Its output shows which questions the terminal alone cannot answer.

In this step, get ready to:
  • Prepare a Google Cloud project with billing turned on for Vertex AI.
  • Run the triage app before adding tracing.
  • Create a Langfuse project and load its credentials into Cloud Shell.
Prepare Cloud Shell and the starter

The workflow asks a model to analyze each incident through Google Cloud Vertex AI, Google's service for running AI models. Your Google Cloud project needs active billing before the model can respond.

Cloud Shell uses the project selected in the Google Cloud console. Its $HOME directory is your personal storage area, so it keeps your project files between sessions.

Choose the path that matches your current Google Cloud account.

I have a billing account

Use your existing Cloud Billing account when you create the project. Google Cloud links the new project to the selected account during creation.

  • Open the Manage resources page.
  • Click Create Project.
  • Enter Langfuse Triage Lab in the Project name field.
  • Select your active account in the Billing account field.
  • Select the appropriate parent in the Location field if Google Cloud shows it.
  • Click Create.

You should see Langfuse Triage Lab in the project selector with billing enabled.

I need to set up a billing account

This setup enables paid services. The model calls in this project cost less than $0.25 in total.

  • Open the Manage billing accounts page.
  • Click Create account.
  • Enter Langfuse Triage Billing in the Name field.
  • Select your organization if Google Cloud shows an organization list.
  • Click Continue.
  • Select the Google payments profile that pays for this account.
  • Complete the payment-profile fields shown for your country if Google asks you to create a profile.
  • Click Submit and enable billing.

Your billing account is ready. Now create the project that uses it.

  • Open the Manage resources page.
  • Click Create Project.
  • Enter Langfuse Triage Lab in the Project name field.
  • Select Langfuse Triage Billing in the Billing account field.
  • Click Create.

You should see Langfuse Triage Lab in the project selector with billing enabled.

  • Open the project selector in the Google Cloud console header.
  • Select Langfuse Triage Lab.
  • Click Activate Cloud Shell in the console header.
  • Click Authorize if Cloud Shell asks to use your Google Cloud credentials.
  • Wait for the terminal prompt to finish loading. This usually takes a few seconds.
  • Confirm the active Google Cloud project by running this command:
gcloud config get-value project

You should see your billed project's ID, such as langfuse-triage-lab-123456.

Seeing the wrong project ID?

Return to the project selector and choose the billed project. Restart Cloud Shell before running the check again.

Help me connect Cloud Shell to my billed Google Cloud project.

  • Record the verified project ID for the rest of the project: your Google Cloud project ID.
  • Enable the Vertex AI API for your active project by running this command:
gcloud services enable aiplatform.googleapis.com

What does this command do?

The command enables the Vertex AI service that the triage app uses for its model calls.

The terminal prints a line ending in finished successfully. once the service is enabled.

API enablement failed?

Run gcloud config get-value project again to confirm Cloud Shell is using your billed project.

Help me diagnose my Vertex AI enablement problem.

The starter files are on the main branch of the public langgraph-triage-observability GitHub repository.

  • Clone the starter repository into your Cloud Shell home directory by running these commands:
git clone https://github.com/nextwork-projects/langgraph-triage-observability.git ~/langgraph-triage-observability
cd ~/langgraph-triage-observability

What do these commands do?

  • The first command downloads the starter into ~/langgraph-triage-observability.
  • The second command moves your terminal into that folder.
  • The clone keeps main as the active starter branch.
  • Create an isolated Python environment by running:
python3 -m venv .venv
source .venv/bin/activate

Why use a virtual environment?

A virtual environment keeps this project's Python packages inside .venv. Activating it makes later installs use those isolated packages.

You should see (.venv) at the start of your terminal prompt.

  • Install the starter dependencies by running:
python3 -m pip install -r requirements.txt

What does this command install?

The requirements.txt file lists the Python packages and exact versions this project needs. Those packages include LangGraph plus the Langfuse software development kit, or SDK, which lets your Python code send data to Langfuse.

The install can take a few minutes while Python downloads the packages. A stream of package names in the terminal means the installation is progressing.

The installation completes when the terminal returns to the (.venv) prompt without an error.

Dependency installation failed?

Check that your prompt starts with (.venv). Confirm that your terminal is inside ~/langgraph-triage-observability.

Help me troubleshoot the pinned dependency installation.

Start the baseline run

The starter already routes incidents through specialist agents. It also saves each incident's progress in a checkpoint, a snapshot stored in the SQLite file triage_checkpoints.db, so an interrupted run can resume. This run gives you a reference point before any observability code exists.

Before you run it, do you think the terminal can identify the slowest specialist or prove that the diagnosis is correct?

  • Run the uninstrumented INC-2042 workflow by entering:
python3 app.py start --thread smoke-001 --alert INC-2042

What does this command run?

  • The start command begins triage of a new incident.
  • The thread ID smoke-001 identifies this durable incident run.
  • The alert ID INC-2042 selects the search-latency fixture.

This run usually takes about two to three minutes. The specialists are making model calls while the terminal is quiet between status lines.

The terminal may first print two LangChainBetaWarning lines and a Warning: there are non-text parts in the response line. These warnings are expected, and every later run prints them too.

You will eventually see WORKFLOW COMPLETE followed by Runbook: runbooks/smoke-001.md.

The workflow published its runbook successfully. The terminal printed no trace URL or per-agent cost.

It also omitted per-agent latency and an objective root-cause score. That blind spot is the designed result of this baseline run.

Baseline run printed WORKFLOW FAILED?

Billing can take a few minutes to reach Vertex AI. A newly enabled project can also briefly report 403 PERMISSION_DENIED.

A Vertex AI rate limit or timeout can also interrupt the first run. Retry the saved thread without starting over by running:

python3 app.py resume --thread smoke-001

This command resumes smoke-001 from its checkpoint.

Help me troubleshoot my interrupted baseline run.

You now have a working baseline run plus a concrete observability gap. The next setup adds the destination where future traces and scores will live.

Connect Langfuse and load the environment

Langfuse Cloud stores the traces that you add in the next step. Its Hobby plan provides the project features needed here without requiring a credit card.

Choose the path that matches your Langfuse account.

I have a Langfuse account

  • Sign in to Langfuse Cloud US.
  • Create a new project, or open an existing project on the Hobby plan.

Your account must be in the US data region, because .env sends traces to https://us.cloud.langfuse.com. If your account is in another region, follow I need to create a Langfuse account instead.

I need to create a Langfuse account

Langfuse keeps each data region completely separate, and this project's .env file points to the US region.

  • Open the Langfuse Cloud US sign-up page.
  • Select US in the Data Region field.
  • Sign up with an email and password, or with one of the sign-in providers shown.
  • Select any option under What will you use Langfuse for?. Your answers don't change the setup.
  • Leave Enable AI powered features as it is. This project doesn't use it.
  • Click Next.

Langfuse creates an organization and a starter project called My Project, then opens it.

  • Open API Keys from the project's Settings.

Creating credentials deserves a careful pause. The secret key appears only once after creation.

  • Create a new project API key pair.
  • Keep the reveal page open while you configure Cloud Shell.
  • Close the reveal page only after both keys are stored securely.

That is the sensitive part complete. Your Langfuse project now has a public key plus a one-time secret key for its SDK connection.

The starter's .env.example file lists every configuration name the project uses. It contains placeholders only, so it is safe to show on screen.

What does this configuration define?

  • The Google Cloud project value tells the model client which billed project to use.
  • The Langfuse key pair authenticates the SDK to your Langfuse project.
  • The base URL keeps trace data in the Langfuse Cloud US region.
  • The tracing environment labels future telemetry as dev.
  • Create your private environment file from the template by running:
cp .env.example .env

Why create a separate environment file?

The command copies the safe template into .env. That private file receives your real project ID plus your Langfuse credentials.

  • Open .env in the Cloud Shell Editor by running:
cloudshell edit .env

The editor opens in place of the terminal with .env ready to edit. Its file explorer hides files whose names start with a dot, so open .env with this command rather than from the explorer. The editor saves your changes automatically, so you won't see an unsaved-changes marker.

  • Replace your-project-id with your Google Cloud project ID.
  • Replace pk-lf-... with the public key from Langfuse.
  • Replace sk-lf-... with the secret key from Langfuse.
  • Keep LANGFUSE_BASE_URL=https://us.cloud.langfuse.com and LANGFUSE_TRACING_ENVIRONMENT=dev unchanged.

Keep the secret key private

Do not upload .env or show it in a screenshot. The public .env.example file remains the safe configuration reference.

The environment file is ready. Loading it exports the five values into the current Cloud Shell session.

Before you run the command, what do you expect the terminal to show if the file is valid?

  • Switch back to the terminal by clicking Open terminal in the Cloud Shell menu bar.
  • Load the environment variables from the Cloud Shell terminal by running:
set -a && . ./.env && set +a

How is the file loaded?

  • The first set -a makes subsequently defined shell variables available to child processes.
  • The middle command reads the assignments from .env.
  • The final set +a restores the shell's normal export behavior.

A clean return to the prompt confirms that the shell parsed the file. Your credentials remain hidden because the command prints none of their values.

Environment file did not load?

Check that every line in .env uses one variable name followed by one equals sign. Remove accidental spaces around the equals signs.

Help me troubleshoot my environment file without exposing secrets.

Your triage app runs inside its pinned environment. Next, you will turn each command into a Langfuse trace that exposes the nested agent work.

Trace Every Workflow Run

The baseline run proved that your triage app can publish a runbook. Its terminal output still hides which agent calls took time and how much text the model processed.

A LangChain callback is a listener that sends each model and tool action to Langfuse. Langfuse stores one command as a step-by-step trace, while a session groups all commands for the same incident.

In this step, get ready to:
  • Create a tracing file that sends workflow activity to Langfuse.
  • Connect every start and resume command to that file.
  • Inspect one trace that shows each nested agent and tool action.
Create the tracing file

The tracing file, telemetry.py, keeps the code that records workflow activity separate from the workflow steps themselves. Every command can then use the same path for sending records to Langfuse.

  • Create telemetry.py in the project folder and open it in the editor by running:
cd ~/langgraph-triage-observability && touch telemetry.py && cloudshell edit telemetry.py
  • Add the Langfuse client helpers by pasting this code into telemetry.py:
"""Langfuse tracing for the triage workflow."""
import os

from specialists import load_json

_langfuse = None


def tracing_enabled() -> bool:
    return bool(os.environ.get("LANGFUSE_PUBLIC_KEY"))


def langfuse_client():
    global _langfuse
    if _langfuse is None:
        from langfuse import get_client

        _langfuse = get_client()
    return _langfuse


def owning_team(alert_id: str) -> str:
    alert = {a["id"]: a for a in load_json("alerts.json")}[alert_id]
    return load_json("services.json")[alert["service"]]["team"]

What do these helpers do?

  • The tracing_enabled() check keeps the workflow runnable when no Langfuse public key is loaded.
  • The langfuse_client() function creates one client for the command.
  • The owning_team() function maps an alert to the team responsible for its service.

Each command needs a fresh callback handler, which listens for activity during that command. It records the model and tool calls without changing the workflow's existing steps.

  • Add the callback configuration below owning_team() by pasting this code:
def trace_config(
    thread_id: str, command: str, alert_id: str, skip: list[str] = ()
) -> tuple[dict, object | None]:
    if not tracing_enabled():
        return {}, None
    from langfuse.langchain import CallbackHandler

    langfuse_client()
    handler = CallbackHandler()
    tags = [command, alert_id] + [f"skip:{name}" for name in skip]
    return {
        "callbacks": [handler],
        "run_name": f"triage {command}",
        "metadata": {
            "langfuse_session_id": thread_id,
            "langfuse_user_id": owning_team(alert_id),
            "langfuse_tags": tags,
        },
    }, handler


def trace_url(trace_id: str) -> str | None:
    return langfuse_client().get_trace_url(trace_id=trace_id)


def shutdown():
    if _langfuse is not None:
        _langfuse.flush()

How does tracing work?

  • A new CallbackHandler listens to the nested work from one command.
  • The run_name value gives the trace a readable name such as triage start.
  • The langfuse_session_id value groups commands from the same workflow thread.
  • The metadata stores identifying details such as the session, owning team, and searchable tags alongside the trace.
  • The trace_url() helper turns the completed trace ID into a link.
  • The shutdown() helper sends any remaining records before the command ends.
  • Compare the complete file with the reference below.

✔️ Awesome, I've got everything!

Your tracing file now creates callbacks and trace links. It also assigns session metadata before flushing queued events.

ⓧ I'd like to double check the full code

Compare your complete telemetry.py file with this reference.

"""Langfuse tracing for the triage workflow."""
import os

from specialists import load_json

_langfuse = None


def tracing_enabled() -> bool:
    return bool(os.environ.get("LANGFUSE_PUBLIC_KEY"))


def langfuse_client():
    global _langfuse
    if _langfuse is None:
        from langfuse import get_client

        _langfuse = get_client()
    return _langfuse


def owning_team(alert_id: str) -> str:
    alert = {a["id"]: a for a in load_json("alerts.json")}[alert_id]
    return load_json("services.json")[alert["service"]]["team"]


def trace_config(
    thread_id: str, command: str, alert_id: str, skip: list[str] = ()
) -> tuple[dict, object | None]:
    if not tracing_enabled():
        return {}, None
    from langfuse.langchain import CallbackHandler

    langfuse_client()
    handler = CallbackHandler()
    tags = [command, alert_id] + [f"skip:{name}" for name in skip]
    return {
        "callbacks": [handler],
        "run_name": f"triage {command}",
        "metadata": {
            "langfuse_session_id": thread_id,
            "langfuse_user_id": owning_team(alert_id),
            "langfuse_tags": tags,
        },
    }, handler


def trace_url(trace_id: str) -> str | None:
    return langfuse_client().get_trace_url(trace_id=trace_id)


def shutdown():
    if _langfuse is not None:
        _langfuse.flush()

How to use this reference

Check every function name against your file. Pay close attention to the metadata keys inside trace_config().

  • Switch back to the terminal by clicking Open terminal in the Cloud Shell menu bar.
  • Check that Python can import your tracing file and see your Langfuse keys by running this command:
python3 -c "import telemetry; print(telemetry.tracing_enabled())"

You should see True. That means Python found telemetry.py, and LANGFUSE_PUBLIC_KEY is loaded in this terminal.

Didn't see True?

Seeing False? Your Langfuse keys aren't loaded in this terminal. Run set -a && . ./.env && set +a again, then retry.

Help me find why app.py cannot import telemetry.py.

Connect tracing to the triage app

The workflow already sends graph activity through graph.stream_events(...). Passing the callback through the same configuration lets Langfuse observe the existing workflow.

  • Open app.py in the editor by running:
cloudshell edit app.py
  • Add the telemetry import below the existing specialists import using these lines:
from specialists import SPECIALISTS, alert_brief, build_model, load_json, run_specialist
import telemetry

Why import telemetry here?

The import gives app.py access to the callback configuration. It also gives main() access to the final flush.

  • In app.py, find the existing main() function near the bottom of the file.
  • Select the entire function from def main(): through the line immediately before if __name__ == "__main__":.
  • Replace that selection with the next two code blocks in order.
def main():
    # Parse the CLI command and reuse its thread ID for checkpointing.
    args = parse_args()
    config = {"configurable": {"thread_id": args.thread}}
    try:
        run_command(args, config)
    finally:
        # Flush queued Langfuse events before the process exits.
        telemetry.shutdown()

Why use finally?

  • The try block runs the requested workflow command.
  • The finally block flushes telemetry after successful commands and failed commands.
  • Paste this complete run_command() function directly below main().
def run_command(args, config):
    # Open the saved workflow and read its current state.
    with SqliteSaver.from_conn_string(DB_PATH) as checkpointer:
        graph = build_graph(checkpointer)
        snapshot = graph.get_state(config)
        before = snapshot.values

        # Build input for a new incident or a saved resume.
        if args.command == "start":
            alert = {a["id"]: a for a in load_json("alerts.json")}[args.alert]
            graph_input = {"incident_id": args.thread, "incident": f"{alert['title']}: {alert['description']}", "alert": alert, "status": "new", "audit_log": []}
        elif args.decision:
            team_requests = {r.id: args.decision for r in snapshot.interrupts if r.value["team"] == args.team}
            if not team_requests:
                teams = sorted({r.value["team"] for r in snapshot.interrupts})
                print(f"No pending approval for team {args.team}. Waiting on: {', '.join(teams) or 'nobody'}")
                return
            graph_input = Command(resume=team_requests)
        else:
            graph_input = None

        # Add one Langfuse callback and run the command.
        alert_id = args.alert if args.command == "start" else snapshot.values["alert"]["id"]
        trace_extra, handler = telemetry.trace_config(args.thread, args.command, alert_id)
        try:
            stream = graph.stream_events(graph_input, config={**config, **trace_extra}, durability="sync", version="v3")
            display_stream(stream)
        except Exception as error:
            display_failure(graph, config, error)
        values = graph.get_state(config).values
        if handler and handler.last_trace_id:
            print(f"Trace: {telemetry.trace_url(handler.last_trace_id)}")

What does this replacement change?

  • The snapshot value contains the saved workflow state and any pending approval requests.
  • A start command builds a new incident from alerts.json.
  • A resume command continues the saved workflow with an approval decision or a retry.
  • The merged configuration gives LangGraph its thread ID and gives Langfuse its callback.
  • The completed handler provides the trace ID for the final link.
  • Confirm that one main() function and one run_command() function sit directly above if __name__ == "__main__":.
  • Compare your complete app.py with the reference below.

✔️ I've got everything

Your app.py now sends every start and resume command to Langfuse and prints a trace link.

ⓧ I'd like to double check the full code

Compare your complete app.py file with this reference.

import argparse
import json
import os
import operator
from pathlib import Path
from typing import Annotated, TypedDict

os.environ.setdefault("LANGGRAPH_STRICT_MSGPACK", "true")

from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, Send, interrupt

from specialists import SPECIALISTS, alert_brief, build_model, load_json, run_specialist
import telemetry

DB_PATH = "triage_checkpoints.db"
SEVERITY_ORDER = ["SEV4", "SEV3", "SEV2", "SEV1"]
RUNBOOK_DIR = Path("runbooks")
RESTRICTED_TERMS = (
    "delete",
    "disable",
    "drop",
    "production",
    "restart",
    "rotate",
)

ANALYSIS_SCHEMA = {
    "title": "IncidentPlan",
    "type": "object",
    "properties": {
        "severity": {
            "type": "string",
            "enum": ["SEV1", "SEV2", "SEV3", "SEV4"],
        },
        "summary": {"type": "string"},
        "likely_cause": {"type": "string"},
        "rationale": {"type": "string"},
        "actions": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "service": {"type": "string"},
                    "action": {"type": "string"},
                },
                "required": ["service", "action"],
            },
        },
    },
    "required": [
        "severity",
        "summary",
        "likely_cause",
        "rationale",
        "actions",
    ],
}

ROUTER_SCHEMA = {
    "title": "TriageDecision",
    "type": "object",
    "properties": {
        "severity": {
            "type": "string",
            "enum": ["SEV1", "SEV2", "SEV3", "SEV4"],
        },
        "specialists": {
            "type": "array",
            "items": {"type": "string", "enum": list(SPECIALISTS)},
        },
        "reason": {"type": "string"},
    },
    "required": ["severity", "specialists", "reason"],
}

def highest_severity(current: str, new: str) -> str:
    if current not in SEVERITY_ORDER:
        return new
    return max(current, new, key=SEVERITY_ORDER.index)

class IncidentState(TypedDict, total=False):
    incident_id: str
    incident: str
    alert: dict
    severity: Annotated[str, highest_severity]
    specialists: list[str]
    findings: Annotated[list[dict], operator.add]
    analysis: dict
    actions: list[dict]
    approvals: Annotated[list[dict], operator.add]
    status: str
    audit_log: list[str]
    runbook_path: str

class SpecialistTask(TypedDict):
    specialist: str
    brief: str

class ActionTask(TypedDict):
    incident_id: str
    team: str
    service: str
    action: str
    policy_reason: str

def build_analyst():
    return build_model().with_structured_output(
        schema=ANALYSIS_SCHEMA,
        method="json_schema",
    )

def build_router():
    return build_model().with_structured_output(
        schema=ROUTER_SCHEMA,
        method="json_schema",
    )

def safe_incident_id(incident_id: str) -> str:
    safe_id = "".join(
        character
        for character in incident_id
        if character.isalnum() or character in {"-", "_"}
    )
    if not any(character.isalnum() for character in safe_id):
        raise ValueError("Incident ID must contain a letter or number.")
    return safe_id

def incident_brief(state: IncidentState) -> str:
    return alert_brief(state["alert"]["id"])

def route_incident(state: IncidentState):
    decision = build_router().invoke(
        [
            (
                "system",
                "You are the incident commander. Set a first severity and choose "
                "which specialists investigate: logs, deploys, metrics. For SEV1 "
                "or SEV2, send every specialist. For SEV3 or SEV4, send only the "
                "one or two most likely to explain the symptom.",
            ),
            ("human", incident_brief(state)),
        ]
    )
    print(f"Router: {decision['severity']}, sending {', '.join(decision['specialists'])}")
    return {
        "severity": decision["severity"],
        "specialists": decision["specialists"],
        "status": "routed",
        "audit_log": state["audit_log"]
        + [f"Router chose {decision['specialists']}: {decision['reason']}"],
    }

def dispatch_specialists(state: IncidentState):
    brief = incident_brief(state)
    return [
        Send("investigate", {"specialist": name, "brief": brief})
        for name in state["specialists"]
    ]

def investigate(task: SpecialistTask):
    name = task["specialist"]
    print(f"  {name} specialist investigating...")
    finding = run_specialist(name, task["brief"])
    print(f"  {name} specialist done: {finding['severity']}, {finding['suspected_cause']}")
    return {
        "findings": [{"specialist": name, **finding}],
        "severity": finding["severity"],
    }

def analyze_incident(state: IncidentState):
    analyst = build_analyst()
    findings = json.dumps(state["findings"], indent=2)
    analysis = analyst.invoke(
        [
            (
                "system",
                "You are an SRE incident analyst. Combine the specialists' "
                "findings into one diagnosis and name the most likely cause with "
                "its evidence. Propose one reversible remediation step for each "
                "service the evidence implicates: the alerting service and every "
                "dependency named in the findings' evidence, at most three. Each "
                "service's owning team must approve its own step. Keep every "
                "field concise.",
            ),
            ("human", f"{state['incident']}\n\nFindings:\n{findings}"),
        ]
    )
    return {
        "analysis": analysis,
        "severity": analysis["severity"],
        "status": "analyzed",
        "audit_log": state["audit_log"]
        + [f"Model combined {len(state['findings'])} findings into one analysis."],
    }

def policy_check(state: IncidentState):
    services = load_json("services.json")
    severity_requires_review = state["severity"] in {"SEV1", "SEV2"}
    actions, approvals = [], []
    for proposed in state["analysis"]["actions"]:
        service = services.get(proposed["service"], {"team": "unowned"})
        searchable_text = f"{state['incident']} {proposed['action']}".lower()
        term_requires_review = any(
            term in searchable_text for term in RESTRICTED_TERMS
        )
        requires_approval = severity_requires_review or term_requires_review
        action = {
            "incident_id": state["incident_id"],
            "team": service["team"],
            "service": proposed["service"],
            "action": proposed["action"],
            "policy_reason": (
                "High severity or restricted operational language detected."
                if requires_approval
                else "No high-risk policy rule matched."
            ),
        }
        actions.append(action | {"requires_approval": requires_approval})
        if not requires_approval:
            approvals.append(action | {"decision": "not required"})
    gated = sum(action["requires_approval"] for action in actions)
    return {
        "actions": actions,
        "approvals": approvals,
        "status": "policy_checked",
        "audit_log": state["audit_log"]
        + [f"Policy check: {gated} of {len(actions)} actions need team approval."],
    }

def policy_route(state: IncidentState):
    gated = [action for action in state["actions"] if action["requires_approval"]]
    if not gated:
        return "publish_runbook"
    return [
        Send(
            "approval_gate",
            {key: value for key, value in action.items() if key != "requires_approval"},
        )
        for action in gated
    ]

def approval_gate(task: ActionTask):
    decision = interrupt(
        {
            "question": f"Approve this action for team {task['team']}?",
            "incident_id": task["incident_id"],
            "team": task["team"],
            "service": task["service"],
            "action": task["action"],
            "policy_reason": task["policy_reason"],
            "allowed_decisions": ["approve", "reject"],
        }
    )
    if decision not in ("approve", "reject"):
        raise ValueError("Decision must be 'approve' or 'reject'.")
    return {"approvals": [task | {"decision": decision}]}

def publish_runbook(state: IncidentState):
    approvals = state.get("approvals", [])
    approved = [a for a in approvals if a["decision"] in ("approve", "not required")]
    decisions = [
        f"Team {a['team']} decision for {a['service']}: {a['decision']}."
        for a in approvals
    ]
    if not approved:
        return {
            "status": "rejected_without_publish",
            "audit_log": state["audit_log"]
            + decisions
            + ["Every action was rejected. Publishing was skipped."],
        }

    RUNBOOK_DIR.mkdir(exist_ok=True)
    path = RUNBOOK_DIR / f"{safe_incident_id(state['incident_id'])}.md"
    analysis = state["analysis"]
    audit_log = state["audit_log"] + decisions + [f"Published runbook to {path}."]
    audit_lines = "\n".join(f"- {entry}" for entry in audit_log)
    finding_lines = "\n".join(
        f"- {f['specialist']} ({f['severity']}): {f['summary']}"
        for f in state["findings"]
    )
    action_lines = "\n".join(
        f"- {a['team']} / {a['service']}: {a['action']} "
        f"({'approved by team' if a['decision'] == 'approve' else 'approval not required'})"
        for a in approved
    )

    path.write_text(
        "# Policy-Controlled Incident Runbook\n\n"
        f"Incident ID: {state['incident_id']}\n\n"
        f"Incident: {state['incident']}\n\n"
        f"Severity: {state['severity']}\n\n"
        f"Summary: {analysis['summary']}\n\n"
        f"Likely cause: {analysis['likely_cause']}\n\n"
        f"Rationale: {analysis['rationale']}\n\n"
        "Findings:\n"
        f"{finding_lines}\n\n"
        "Approved actions:\n"
        f"{action_lines}\n\n"
        "Audit log:\n"
        f"{audit_lines}\n",
        encoding="utf-8",
    )
    return {
        "status": "published",
        "runbook_path": str(path),
        "audit_log": audit_log,
    }

def build_graph(checkpointer: SqliteSaver):
    builder = StateGraph(IncidentState)
    builder.add_node("route_incident", route_incident)
    builder.add_node("investigate", investigate)
    builder.add_node("analyze_incident", analyze_incident, defer=True)
    builder.add_node("policy_check", policy_check)
    builder.add_node("approval_gate", approval_gate)
    builder.add_node("publish_runbook", publish_runbook, defer=True)

    builder.add_edge(START, "route_incident")
    builder.add_conditional_edges(
        "route_incident", dispatch_specialists, ["investigate"]
    )
    builder.add_edge("investigate", "analyze_incident")
    builder.add_edge("analyze_incident", "policy_check")
    builder.add_conditional_edges(
        "policy_check", policy_route, ["approval_gate", "publish_runbook"]
    )
    builder.add_edge("approval_gate", "publish_runbook")
    builder.add_edge("publish_runbook", END)

    return builder.compile(checkpointer=checkpointer)

def display_stream(stream):
    final_state = stream.output
    if stream.interrupted:
        display_pending(stream.interrupts)
        return

    print("WORKFLOW COMPLETE")
    print(f"Status: {final_state['status']}")
    print(f"Runbook: {final_state.get('runbook_path', 'not published')}")

def display_pending(interrupts):
    print(f"WORKFLOW PAUSED: {len(interrupts)} team approvals pending")
    for pending in interrupts:
        request = pending.value
        print(f"- {request['team']} ({request['service']}): {request['action']}")

def display_failure(graph, config, error):
    snapshot = graph.get_state(config)
    saved = [finding["specialist"] for finding in snapshot.values.get("findings", [])]
    print(f"WORKFLOW FAILED: {error}")
    print(f"Saved findings: {', '.join(saved) or 'none'}")
    print(f"Waiting to re-run: {', '.join(snapshot.next)}")

def parse_args():
    parser = argparse.ArgumentParser(
        description="Run a resumable incident-triage workflow."
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    start_parser = subparsers.add_parser("start")
    start_parser.add_argument("--thread", required=True)
    start_parser.add_argument("--alert", required=True)

    resume_parser = subparsers.add_parser("resume")
    resume_parser.add_argument("--thread", required=True)
    resume_parser.add_argument(
        "--decision",
        choices=["approve", "reject"],
        help="Leave out to retry a failed run.",
    )
    resume_parser.add_argument("--team", help="The team whose action you decide.")

    args = parser.parse_args()
    if args.command == "resume" and args.decision and not args.team:
        parser.error("--decision needs --team.")
    return args

def main():
    # Parse the CLI command and reuse its thread ID for checkpointing.
    args = parse_args()
    config = {"configurable": {"thread_id": args.thread}}
    try:
        run_command(args, config)
    finally:
        # Flush queued Langfuse events before the process exits.
        telemetry.shutdown()

def run_command(args, config):
    # Open the saved workflow and read its current state.
    with SqliteSaver.from_conn_string(DB_PATH) as checkpointer:
        graph = build_graph(checkpointer)
        snapshot = graph.get_state(config)
        before = snapshot.values

        # Build input for a new incident or a saved resume.
        if args.command == "start":
            alert = {a["id"]: a for a in load_json("alerts.json")}[args.alert]
            graph_input = {"incident_id": args.thread, "incident": f"{alert['title']}: {alert['description']}", "alert": alert, "status": "new", "audit_log": []}
        elif args.decision:
            team_requests = {r.id: args.decision for r in snapshot.interrupts if r.value["team"] == args.team}
            if not team_requests:
                teams = sorted({r.value["team"] for r in snapshot.interrupts})
                print(f"No pending approval for team {args.team}. Waiting on: {', '.join(teams) or 'nobody'}")
                return
            graph_input = Command(resume=team_requests)
        else:
            graph_input = None

        # Add one Langfuse callback and run the command.
        alert_id = args.alert if args.command == "start" else snapshot.values["alert"]["id"]
        trace_extra, handler = telemetry.trace_config(args.thread, args.command, alert_id)
        try:
            stream = graph.stream_events(graph_input, config={**config, **trace_extra}, durability="sync", version="v3")
            display_stream(stream)
        except Exception as error:
            display_failure(graph, config, error)
        values = graph.get_state(config).values
        if handler and handler.last_trace_id:
            print(f"Trace: {telemetry.trace_url(handler.last_trace_id)}")

if __name__ == "__main__":
    main()

How to use this reference

Check that main() only parses arguments and calls run_command(), and that graph.stream_events(...) receives the merged configuration.

Seeing a Python error after the edit?

Check that import telemetry is at the top level. An indented import can become part of another block.

Check that snapshot is assigned before the resume path reads the saved alert and approval requests.

Help me compare my tracing edits with the required integration.

Run and inspect one incident session

One command produces one top-level trace. The workflow's agents and tools become nested observations beneath it.

This first traced run can take about 30 seconds to 4 minutes while Vertex AI completes the model calls. A quiet terminal during that wait does not mean the command has stopped.

Before you run the command, do you expect the workflow pause to prevent Langfuse from recording a trace?

  • Switch back to the terminal by clicking Open terminal in the Cloud Shell menu bar.
  • Start incident thread obs-001 by running this command:
python3 app.py start --thread obs-001 --alert INC-2041

What should you see?

The workflow pauses for team approvals. The terminal then prints a Trace: link.

That link confirms the callback recorded a triage start trace even though the workflow reached interrupt().

🙋‍♀️ Did Vertex AI return a limit or timeout error?

The SQLite checkpoint keeps completed workflow state. Retry the unfinished work without supplying an approval decision by running:

python3 app.py resume --thread obs-001

This decision-free resume continues from the saved checkpoint. It creates a triage resume trace in the same session.

Help me interpret my failed Vertex AI run and retry it safely.

  • Approve the payments action by running this command:
python3 app.py resume --thread obs-001 --team payments --decision approve
  • Approve the platform-data action by running this command:
python3 app.py resume --thread obs-001 --team platform-data --decision approve

What completes this thread?

The remaining approval lets the workflow publish its runbook. The terminal prints another Trace: link for the final resume command.

Before you inspect Langfuse, do you expect three separate sessions or one session containing every command trace?

  • Open your project in Langfuse Cloud US.
  • Click Sessions in the sidebar, then open session obs-001.
  • Confirm that one triage start trace and the triage resume traces belong to this session.
  • Click Open trace on the triage start trace, then open the Tree to see its nested observations for routing, specialist work, and analysis.
  • Open the last triage resume trace the same way to see approval_gate and publish_runbook.

You should see nested observations for routing and investigation. You should also see analysis and policy work from the start command.

Session missing or doesn't match?

If Sessions shows You aren't using sessions yet, no obs-001 trace has reached this project yet.

  • Scroll up the terminal for WORKFLOW FAILED. If it mentions BILLING_DISABLED, link billing as in Step 1, wait a few minutes, then run python3 app.py resume --thread obs-001.
  • Check that each command printed a Trace: link. No link means your Langfuse keys aren't loaded, so run set -a && . ./.env && set +a and retry.
  • Check that you're in the US project whose API keys are in .env.
  • Refresh the page. A new trace can take a minute to appear.

Confirm that you opened session obs-001 instead of an individual trace. The session view should group the start and resume commands together.

Help me verify the obs-001 session structure.

That is the blind spot closed: session obs-001 now preserves the work behind every start and resume command.

Your workflow now leaves a traceable history across starts and resumes. Next, you can use those observations to follow an intentional failure to its exact source.

Attribute Traces and Debug Failures

Debug Failures

Your obs-001 session in Langfuse now groups each command into its own trace. Inside each trace, observations are individual records showing which agents and tools ran.

A trace can show what ran without showing who owns the affected service. In this step, you will attach ownership, command, and alert details before using an intentional crash to find the exact failing tool.

In this step, get ready to:
  • Trigger the built-in metrics failure.
  • Trace the error to the failing metric_window observation.
  • Resume the saved workflow and confirm it moves past the failure.
Debug the planted metrics failure

The project includes a prepared test case that can make the metrics tool crash during a real workflow run. Its trace keeps the full path from the starting command to the tool that failed.

Before you run this, which specialist do you expect the red error path to end on?

  • Switch back to the terminal by clicking Open terminal in the Cloud Shell menu bar.
  • Create the failing obs-002 run by running this command:
TRIAGE_FAIL=metrics python3 app.py start --thread obs-002 --alert INC-2041

This failure is intentional

You will see WORKFLOW FAILED: Metrics backend timed out.

The SQLite checkpoint keeps completed workflow state. Langfuse records the failing observation path for inspection.

  • Open the printed trace URL in Langfuse.
  • Click the ⋮ menu above the observation tree, then set Min Level to ERROR.
  • Open metric_window at the end of the red path, then check its Preview tab for the timeout status.

You will see the exact status message Metrics backend timed out. The agent retries the tool, so up to three metric_window calls can show the same error.

  • Check the trace header for the user payments and the tags start and INC-2041.
  • Click route_incident, then open its Attributes tab to confirm that the environment is dev.

You found the failure at its source. The trace now identifies the responsible team, incident context, environment, plus exact broken tool.

Cannot find the error path?

  • Check that the trace belongs to obs-002.
  • Set Min Level back to ERROR from the ⋮ menu.

Help me find the planted metrics failure in my Langfuse observations.

Before you retry, do you expect the workflow to repeat the metrics error or continue from its checkpoint?

  • Retry the failed workflow without an approval decision by running:
python3 app.py resume --thread obs-002

What does this retry prove?

The first command set TRIAGE_FAIL only for that process. This retry re-enters the saved workflow without the injected failure.

The new triage resume trace keeps the same session plus attribution metadata.

You will see the workflow move beyond the previous metrics error. It stops at WORKFLOW PAUSED: 2 team approvals pending and prints a fresh Trace: URL.

Leave both approvals pending. This step only needs the retry trace, so obs-002 can stay paused.

Temporary model error?

  • Wait briefly if Vertex AI returns a temporary service error.
  • Rerun the decision-free resume command above.

Help me recover my saved thread after a temporary model error.

Your traces now show who owned each run and where the built-in failure occurred. Next, you will add a root-cause score, a true-or-false result that Langfuse can chart.

Score Root-Cause Quality

Your Langfuse traces now reveal the path each incident followed. They still cannot prove that the final diagnosis matches the known root cause, which is the underlying reason the incident happened.

This step adds a root-cause score that compares each diagnosis with the expected deployment ID, the unique label for a code release. Every new analysis receives an objective result without another model call.

In this step, get ready to:
  • Create a Python file that checks each diagnosis against the known answer.
  • Score only the trace that creates a new analysis.
  • Compare a complete investigation with one that skips deployment evidence.
Create the root-cause score

The root-cause score is a Boolean score, which stores one of two results: true or false. The prepared test incident earns true only when the diagnosis includes the expected deployment ID.

  • Create score.py in the project folder and open it in the editor by running:
cd ~/langgraph-triage-observability && cloudshell edit score.py
  • Paste this scoring logic into score.py.
ROOT_CAUSES = {"INC-2041": "d-1042", "INC-2042": "d-1039"}


def root_cause_correct(alert_id: str, analysis: dict) -> bool:
    expected = ROOT_CAUSES.get(alert_id)
    return bool(expected) and expected in analysis.get("likely_cause", "")


def score_run(langfuse, trace_id: str, alert_id: str, analysis: dict) -> bool:
    correct = root_cause_correct(alert_id, analysis)
    langfuse.create_score(
        name="root_cause_correct",
        value=1 if correct else 0,
        trace_id=trace_id,
        data_type="BOOLEAN",
        comment=f"Expected {ROOT_CAUSES.get(alert_id)} in: {analysis.get('likely_cause', '')}",
    )
    return correct

What does this scoring logic do?

  • The ROOT_CAUSES dictionary connects each prepared test alert to its expected deployment ID.
  • The root_cause_correct() function checks whether the diagnosis names that deployment ID.
  • The score_run() function saves the result on the current trace as root_cause_correct.
  • The values 1 and 0 represent true and false.

Good progress. Your project now has a repeatable root-cause score for every diagnosis.

Can't find score.py?

Check that you created the file inside ~/langgraph-triage-observability. A similarly named file outside that folder cannot be imported by app.py.

Ask for help with the file location or scoring code: Help me check why app.py cannot find my score.py module.

✔️ Awesome, I've got everything!

Your score.py file is ready to connect to the triage app.

ⓧ I'd like to double check the full code

ROOT_CAUSES = {"INC-2041": "d-1042", "INC-2042": "d-1039"}


def root_cause_correct(alert_id: str, analysis: dict) -> bool:
    expected = ROOT_CAUSES.get(alert_id)
    return bool(expected) and expected in analysis.get("likely_cause", "")


def score_run(langfuse, trace_id: str, alert_id: str, analysis: dict) -> bool:
    correct = root_cause_correct(alert_id, analysis)
    langfuse.create_score(
        name="root_cause_correct",
        value=1 if correct else 0,
        trace_id=trace_id,
        data_type="BOOLEAN",
        comment=f"Expected {ROOT_CAUSES.get(alert_id)} in: {analysis.get('likely_cause', '')}",
    )
    return correct

What should match?

Compare the answer-key values and both function definitions with your score.py file. The score name and data type must also match exactly.

Score only new analysis

Approval commands reuse the analysis saved in the SQLite checkpoint. The new check compares the checkpoint before and after each command, so later approvals do not create duplicate scores.

  • Open app.py in the editor
  • In app.py, find the existing import telemetry line.
  • Add the scoring import directly below it so the local imports look like this:
import telemetry
from score import score_run

Why import score_run?

The workflow keeps score creation in score.py. Importing score_run gives app.py one function for evaluating the diagnosis and writing the result.

  • In run_command(), find the block that prints the trace URL after values = graph.get_state(config).values.
  • Select that whole trace-output block, starting from the spaces before its first if.
  • Replace it with this guarded scoring block. The block keeps the same 8-space indentation, so it stays inside run_command():
        if handler and handler.last_trace_id:
            print(f"Trace: {telemetry.trace_url(handler.last_trace_id)}")
            if "analysis" in values and "analysis" not in before:
                correct = score_run(telemetry.langfuse_client(), handler.last_trace_id, alert_id, values["analysis"])
                print(f"Score root_cause_correct: {correct}")

How does the guard prevent duplicates?

  • The outer condition confirms that the command produced a traced run with a trace ID.
  • The inner condition confirms that analysis exists after the command.
  • The same condition confirms that analysis did not exist before the command.
  • Only the command that crosses that state boundary receives the root-cause score.
  • Switch back to the terminal by clicking Open terminal in the Cloud Shell menu bar.
  • Check app.py for indentation mistakes by running:
python3 -m py_compile app.py

No output means Python can read the file.

Seeing an IndentationError?

Help me fix the indentation in run_command().

Compare complete and skipped runs

The skip option you add in this substep creates a deliberately weaker investigation by leaving out one specialist. This tests whether the score can tell a complete diagnosis from one that lacks deployment evidence.

The complete run can take roughly 30 seconds to 4 minutes while the agents investigate. A quiet terminal during that window does not mean the workflow has stalled.

Before you run the complete investigation, do you expect its diagnosis to contain the planted deployment ID?

  • Start the complete INC-2041 investigation on a fresh thread by running:
python3 app.py start --thread obs-003 --alert INC-2041

What does this run test?

This command starts a fresh traced investigation with the normal specialist routing. The new analysis is compared with the expected root cause before the command ends.

You should see Score root_cause_correct: True after the trace link. That result proves the complete investigation found the planted deployment evidence.

Temporary model error?

If the start prints WORKFLOW FAILED: The read operation timed out, retry the saved thread without a decision by running:

python3 app.py resume --thread obs-003

The score then appears after the resume's Trace: link, on the triage resume trace.

Help me recover obs-003 after a temporary model error.

Next, add a --skip option so you can run the same incident without one specialist.

  • In app.py, find the existing IncidentState class.
  • Replace the entire class with the grouped version below.
class IncidentState(TypedDict, total=False):
    incident_id: str
    incident: str
    alert: dict
    severity: Annotated[str, highest_severity]
    specialists: list[str]
    findings: Annotated[list[dict], operator.add]
    analysis: dict
    actions: list[dict]
    approvals: Annotated[list[dict], operator.add]
    status: str
    audit_log: list[str]
    runbook_path: str
    skip_specialists: list[str]

What changed in IncidentState?

The class now stores skip_specialists so start and resume commands share the same omitted specialists.

  • In app.py, find the existing parse_args() function.
  • Replace the entire function with the grouped version below.
def parse_args():
    parser = argparse.ArgumentParser(
        description="Run a resumable incident-triage workflow."
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    start_parser = subparsers.add_parser("start")
    start_parser.add_argument("--thread", required=True)
    start_parser.add_argument("--alert", required=True)
    start_parser.add_argument("--skip", nargs="*", default=[], choices=list(SPECIALISTS))

    resume_parser = subparsers.add_parser("resume")
    resume_parser.add_argument("--thread", required=True)
    resume_parser.add_argument(
        "--decision",
        choices=["approve", "reject"],
        help="Leave out to retry a failed run.",
    )
    resume_parser.add_argument("--team", help="The team whose action you decide.")

    args = parser.parse_args()
    if args.command == "resume" and args.decision and not args.team:
        parser.error("--decision needs --team.")
    return args

What changed in parse_args()?

The start parser now accepts --skip with zero or more specialist names. Existing commands still use an empty list by default.

  • In run_command(), find the existing graph_input dictionary in the start branch.
  • Replace the entire dictionary with the grouped version below.
            graph_input = {
                "incident_id": args.thread,
                "incident": f"{alert['title']}: {alert['description']}",
                "alert": alert,
                "status": "new",
                "audit_log": [],
                "skip_specialists": args.skip,
            }

What changed in graph_input?

The dictionary now saves args.skip in the checkpoint as skip_specialists.

  • In app.py, find the existing route_incident() function.
  • Replace the entire function with the grouped version below.
def route_incident(state: IncidentState):
    decision = build_router().invoke(
        [
            (
                "system",
                "You are the incident commander. Set a first severity and choose "
                "which specialists investigate: logs, deploys, metrics. For SEV1 "
                "or SEV2, send every specialist. For SEV3 or SEV4, send only the "
                "one or two most likely to explain the symptom.",
            ),
            ("human", incident_brief(state)),
        ]
    )
    skipped = state.get("skip_specialists", [])
    decision["specialists"] = [name for name in decision["specialists"] if name not in skipped]
    print(f"Router: {decision['severity']}, sending {', '.join(decision['specialists'])}")
    return {
        "severity": decision["severity"],
        "specialists": decision["specialists"],
        "status": "routed",
        "audit_log": state["audit_log"]
        + [f"Router chose {decision['specialists']}: {decision['reason']}"],
    }

What changed in route_incident()?

The function now removes names in skip_specialists from the router's specialist list before dispatch.

  • In run_command(), replace the trace_config line with these lines:
        skip = args.skip if args.command == "start" else before.get("skip_specialists", [])
        trace_extra, handler = telemetry.trace_config(args.thread, args.command, alert_id, skip)

What changed in run_command()?

The trace now reads skipped specialists from start arguments or the saved checkpoint, so resumed runs keep the same skip tags.

✔️ Awesome, I've got everything!

Your triage app now scores the trace that first creates an analysis, and can leave out a specialist with --skip.

ⓧ I'd like to double check the updated code

import argparse
import json
import os
import operator
from pathlib import Path
from typing import Annotated, TypedDict

os.environ.setdefault("LANGGRAPH_STRICT_MSGPACK", "true")

from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, Send, interrupt

from specialists import SPECIALISTS, alert_brief, build_model, load_json, run_specialist
import telemetry
from score import score_run

DB_PATH = "triage_checkpoints.db"
SEVERITY_ORDER = ["SEV4", "SEV3", "SEV2", "SEV1"]
RUNBOOK_DIR = Path("runbooks")
RESTRICTED_TERMS = (
    "delete",
    "disable",
    "drop",
    "production",
    "restart",
    "rotate",
)

ANALYSIS_SCHEMA = {
    "title": "IncidentPlan",
    "type": "object",
    "properties": {
        "severity": {
            "type": "string",
            "enum": ["SEV1", "SEV2", "SEV3", "SEV4"],
        },
        "summary": {"type": "string"},
        "likely_cause": {"type": "string"},
        "rationale": {"type": "string"},
        "actions": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "service": {"type": "string"},
                    "action": {"type": "string"},
                },
                "required": ["service", "action"],
            },
        },
    },
    "required": [
        "severity",
        "summary",
        "likely_cause",
        "rationale",
        "actions",
    ],
}

ROUTER_SCHEMA = {
    "title": "TriageDecision",
    "type": "object",
    "properties": {
        "severity": {
            "type": "string",
            "enum": ["SEV1", "SEV2", "SEV3", "SEV4"],
        },
        "specialists": {
            "type": "array",
            "items": {"type": "string", "enum": list(SPECIALISTS)},
        },
        "reason": {"type": "string"},
    },
    "required": ["severity", "specialists", "reason"],
}


def highest_severity(current: str, new: str) -> str:
    if current not in SEVERITY_ORDER:
        return new
    return max(current, new, key=SEVERITY_ORDER.index)


class IncidentState(TypedDict, total=False):
    incident_id: str
    incident: str
    alert: dict
    severity: Annotated[str, highest_severity]
    specialists: list[str]
    findings: Annotated[list[dict], operator.add]
    analysis: dict
    actions: list[dict]
    approvals: Annotated[list[dict], operator.add]
    status: str
    audit_log: list[str]
    runbook_path: str
    skip_specialists: list[str]


class SpecialistTask(TypedDict):
    specialist: str
    brief: str


class ActionTask(TypedDict):
    incident_id: str
    team: str
    service: str
    action: str
    policy_reason: str


def build_analyst():
    return build_model().with_structured_output(
        schema=ANALYSIS_SCHEMA,
        method="json_schema",
    )


def build_router():
    return build_model().with_structured_output(
        schema=ROUTER_SCHEMA,
        method="json_schema",
    )


def safe_incident_id(incident_id: str) -> str:
    safe_id = "".join(
        character
        for character in incident_id
        if character.isalnum() or character in {"-", "_"}
    )
    if not any(character.isalnum() for character in safe_id):
        raise ValueError("Incident ID must contain a letter or number.")
    return safe_id


def incident_brief(state: IncidentState) -> str:
    return alert_brief(state["alert"]["id"])


def route_incident(state: IncidentState):
    decision = build_router().invoke(
        [
            (
                "system",
                "You are the incident commander. Set a first severity and choose "
                "which specialists investigate: logs, deploys, metrics. For SEV1 "
                "or SEV2, send every specialist. For SEV3 or SEV4, send only the "
                "one or two most likely to explain the symptom.",
            ),
            ("human", incident_brief(state)),
        ]
    )
    skipped = state.get("skip_specialists", [])
    decision["specialists"] = [name for name in decision["specialists"] if name not in skipped]
    print(f"Router: {decision['severity']}, sending {', '.join(decision['specialists'])}")
    return {
        "severity": decision["severity"],
        "specialists": decision["specialists"],
        "status": "routed",
        "audit_log": state["audit_log"]
        + [f"Router chose {decision['specialists']}: {decision['reason']}"],
    }


def dispatch_specialists(state: IncidentState):
    brief = incident_brief(state)
    return [
        Send("investigate", {"specialist": name, "brief": brief})
        for name in state["specialists"]
    ]


def investigate(task: SpecialistTask):
    name = task["specialist"]
    print(f"  {name} specialist investigating...")
    finding = run_specialist(name, task["brief"])
    print(f"  {name} specialist done: {finding['severity']}, {finding['suspected_cause']}")
    return {
        "findings": [{"specialist": name, **finding}],
        "severity": finding["severity"],
    }


def analyze_incident(state: IncidentState):
    analyst = build_analyst()
    findings = json.dumps(state["findings"], indent=2)
    analysis = analyst.invoke(
        [
            (
                "system",
                "You are an SRE incident analyst. Combine the specialists' "
                "findings into one diagnosis and name the most likely cause with "
                "its evidence. Propose one reversible remediation step for each "
                "service the evidence implicates: the alerting service and every "
                "dependency named in the findings' evidence, at most three. Each "
                "service's owning team must approve its own step. Keep every "
                "field concise.",
            ),
            ("human", f"{state['incident']}\n\nFindings:\n{findings}"),
        ]
    )
    return {
        "analysis": analysis,
        "severity": analysis["severity"],
        "status": "analyzed",
        "audit_log": state["audit_log"]
        + [f"Model combined {len(state['findings'])} findings into one analysis."],
    }


def policy_check(state: IncidentState):
    services = load_json("services.json")
    severity_requires_review = state["severity"] in {"SEV1", "SEV2"}
    actions, approvals = [], []
    for proposed in state["analysis"]["actions"]:
        service = services.get(proposed["service"], {"team": "unowned"})
        searchable_text = f"{state['incident']} {proposed['action']}".lower()
        term_requires_review = any(
            term in searchable_text for term in RESTRICTED_TERMS
        )
        requires_approval = severity_requires_review or term_requires_review
        action = {
            "incident_id": state["incident_id"],
            "team": service["team"],
            "service": proposed["service"],
            "action": proposed["action"],
            "policy_reason": (
                "High severity or restricted operational language detected."
                if requires_approval
                else "No high-risk policy rule matched."
            ),
        }
        actions.append(action | {"requires_approval": requires_approval})
        if not requires_approval:
            approvals.append(action | {"decision": "not required"})
    gated = sum(action["requires_approval"] for action in actions)
    return {
        "actions": actions,
        "approvals": approvals,
        "status": "policy_checked",
        "audit_log": state["audit_log"]
        + [f"Policy check: {gated} of {len(actions)} actions need team approval."],
    }


def policy_route(state: IncidentState):
    gated = [action for action in state["actions"] if action["requires_approval"]]
    if not gated:
        return "publish_runbook"
    return [
        Send(
            "approval_gate",
            {key: value for key, value in action.items() if key != "requires_approval"},
        )
        for action in gated
    ]


def approval_gate(task: ActionTask):
    decision = interrupt(
        {
            "question": f"Approve this action for team {task['team']}?",
            "incident_id": task["incident_id"],
            "team": task["team"],
            "service": task["service"],
            "action": task["action"],
            "policy_reason": task["policy_reason"],
            "allowed_decisions": ["approve", "reject"],
        }
    )
    if decision not in ("approve", "reject"):
        raise ValueError("Decision must be 'approve' or 'reject'.")
    return {"approvals": [task | {"decision": decision}]}


def publish_runbook(state: IncidentState):
    approvals = state.get("approvals", [])
    approved = [a for a in approvals if a["decision"] in ("approve", "not required")]
    decisions = [
        f"Team {a['team']} decision for {a['service']}: {a['decision']}."
        for a in approvals
    ]
    if not approved:
        return {
            "status": "rejected_without_publish",
            "audit_log": state["audit_log"]
            + decisions
            + ["Every action was rejected. Publishing was skipped."],
        }

    RUNBOOK_DIR.mkdir(exist_ok=True)
    path = RUNBOOK_DIR / f"{safe_incident_id(state['incident_id'])}.md"
    analysis = state["analysis"]
    audit_log = state["audit_log"] + decisions + [f"Published runbook to {path}."]
    audit_lines = "\n".join(f"- {entry}" for entry in audit_log)
    finding_lines = "\n".join(
        f"- {f['specialist']} ({f['severity']}): {f['summary']}"
        for f in state["findings"]
    )
    action_lines = "\n".join(
        f"- {a['team']} / {a['service']}: {a['action']} "
        f"({'approved by team' if a['decision'] == 'approve' else 'approval not required'})"
        for a in approved
    )

    path.write_text(
        "# Policy-Controlled Incident Runbook\n\n"
        f"Incident ID: {state['incident_id']}\n\n"
        f"Incident: {state['incident']}\n\n"
        f"Severity: {state['severity']}\n\n"
        f"Summary: {analysis['summary']}\n\n"
        f"Likely cause: {analysis['likely_cause']}\n\n"
        f"Rationale: {analysis['rationale']}\n\n"
        "Findings:\n"
        f"{finding_lines}\n\n"
        "Approved actions:\n"
        f"{action_lines}\n\n"
        "Audit log:\n"
        f"{audit_lines}\n",
        encoding="utf-8",
    )
    return {
        "status": "published",
        "runbook_path": str(path),
        "audit_log": audit_log,
    }


def build_graph(checkpointer: SqliteSaver):
    builder = StateGraph(IncidentState)
    builder.add_node("route_incident", route_incident)
    builder.add_node("investigate", investigate)
    builder.add_node("analyze_incident", analyze_incident, defer=True)
    builder.add_node("policy_check", policy_check)
    builder.add_node("approval_gate", approval_gate)
    builder.add_node("publish_runbook", publish_runbook, defer=True)

    builder.add_edge(START, "route_incident")
    builder.add_conditional_edges(
        "route_incident", dispatch_specialists, ["investigate"]
    )
    builder.add_edge("investigate", "analyze_incident")
    builder.add_edge("analyze_incident", "policy_check")
    builder.add_conditional_edges(
        "policy_check", policy_route, ["approval_gate", "publish_runbook"]
    )
    builder.add_edge("approval_gate", "publish_runbook")
    builder.add_edge("publish_runbook", END)

    return builder.compile(checkpointer=checkpointer)


def display_stream(stream):
    final_state = stream.output
    if stream.interrupted:
        display_pending(stream.interrupts)
        return

    print("WORKFLOW COMPLETE")
    print(f"Status: {final_state['status']}")
    print(f"Runbook: {final_state.get('runbook_path', 'not published')}")


def display_pending(interrupts):
    print(f"WORKFLOW PAUSED: {len(interrupts)} team approvals pending")
    for pending in interrupts:
        request = pending.value
        print(f"- {request['team']} ({request['service']}): {request['action']}")


def display_failure(graph, config, error):
    snapshot = graph.get_state(config)
    saved = [finding["specialist"] for finding in snapshot.values.get("findings", [])]
    print(f"WORKFLOW FAILED: {error}")
    print(f"Saved findings: {', '.join(saved) or 'none'}")
    print(f"Waiting to re-run: {', '.join(snapshot.next)}")


def parse_args():
    parser = argparse.ArgumentParser(
        description="Run a resumable incident-triage workflow."
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    start_parser = subparsers.add_parser("start")
    start_parser.add_argument("--thread", required=True)
    start_parser.add_argument("--alert", required=True)
    start_parser.add_argument("--skip", nargs="*", default=[], choices=list(SPECIALISTS))

    resume_parser = subparsers.add_parser("resume")
    resume_parser.add_argument("--thread", required=True)
    resume_parser.add_argument(
        "--decision",
        choices=["approve", "reject"],
        help="Leave out to retry a failed run.",
    )
    resume_parser.add_argument("--team", help="The team whose action you decide.")

    args = parser.parse_args()
    if args.command == "resume" and args.decision and not args.team:
        parser.error("--decision needs --team.")
    return args


def main():
    args = parse_args()
    config = {"configurable": {"thread_id": args.thread}}
    try:
        run_command(args, config)
    finally:
        telemetry.shutdown()


def run_command(args, config):
    with SqliteSaver.from_conn_string(DB_PATH) as checkpointer:
        graph = build_graph(checkpointer)
        before = graph.get_state(config).values

        if args.command == "start":
            alerts = {alert["id"]: alert for alert in load_json("alerts.json")}
            alert = alerts[args.alert]
            graph_input = {
                "incident_id": args.thread,
                "incident": f"{alert['title']}: {alert['description']}",
                "alert": alert,
                "status": "new",
                "audit_log": [],
                "skip_specialists": args.skip,
            }
        elif args.decision:
            pending = graph.get_state(config).interrupts
            team_requests = {
                request.id: args.decision
                for request in pending
                if request.value["team"] == args.team
            }
            if not team_requests:
                teams = sorted({request.value["team"] for request in pending})
                print(
                    f"No pending approval for team {args.team}. "
                    f"Waiting on: {', '.join(teams) or 'nobody'}"
                )
                return
            graph_input = Command(resume=team_requests)
            print(f"Recorded {args.decision} for {args.team}.")
        else:
            graph_input = None

        alert_id = args.alert if args.command == "start" else before["alert"]["id"]
        skip = args.skip if args.command == "start" else before.get("skip_specialists", [])
        trace_extra, handler = telemetry.trace_config(args.thread, args.command, alert_id, skip)
        try:
            stream = graph.stream_events(graph_input, config={**config, **trace_extra}, durability="sync", version="v3")
            display_stream(stream)
        except Exception as error:
            display_failure(graph, config, error)
        values = graph.get_state(config).values
        if handler and handler.last_trace_id:
            print(f"Trace: {telemetry.trace_url(handler.last_trace_id)}")
            if "analysis" in values and "analysis" not in before:
                correct = score_run(telemetry.langfuse_client(), handler.last_trace_id, alert_id, values["analysis"])
                print(f"Score root_cause_correct: {correct}")


if __name__ == "__main__":
    main()

What should you compare?

Focus on the score_run import, the guarded score call near the end of run_command(), and the skip changes. The existing tracing and checkpoint behavior remains unchanged.

Before you run the weaker investigation, do you think the diagnosis can still identify the expected deployment without the deploys specialist?

  • Switch back to the terminal by clicking Open terminal in the Cloud Shell menu bar.
  • Start the skipped-deploys investigation on another fresh thread by running:
python3 app.py start --thread obs-004 --alert INC-2041 --skip deploys

What changes in this run?

The --skip deploys option removes the deploys specialist from routing. The trace also receives the skip:deploys tag so the degraded run stays searchable.

You should see Score root_cause_correct: False after the second trace link. The root-cause score has caught the deliberately weak diagnosis.

Both runs stop at WORKFLOW PAUSED: 2 team approvals pending. Leave them paused, because the scores are already recorded.

  • Open the Scores view in your Langfuse project.
  • Click Columns, then turn on Trace Tags and Trace Name.
  • Confirm that the root_cause_correct row without a skip tag is true and the row with the skip:deploys tag is false.

Missing or unexpected scores?

If no score appears, confirm that your Langfuse credentials remain loaded before rerunning a fresh thread. The scoring block only runs when a traced command creates analysis for the first time.

If the complete run is false, inspect whether its diagnosis includes d-1042. A model or service error can leave the investigation without the fixture's expected evidence.

Get targeted help here: Help me debug my missing or incorrect Langfuse root-cause scores.

Your traces now show what ran and whether each diagnosis was correct. Next, you will combine those results into one view of cost, speed, errors, and accuracy.

Build a Quality and Cost Dashboard

Your traces now explain what happened during each incident. Your root-cause scores show whether each diagnosis found the expected cause.

A single run cannot show whether quality is improving across many incidents. In this step, you will build a Langfuse dashboard, a screen that combines key measurements, and send quality alerts to a webhook, a URL that receives automatic messages.

In this step, get ready to:
  • Build four charts for cost, speed, accuracy, and errors.
  • Create a webhook automation that sends alerts to webhook.site.
  • Send an alert when the root-cause score falls.
Create the four-widget dashboard

A custom dashboard combines measurements from many workflow runs on one screen. You will build it from the traces and scores already stored in your development project.

  • Open Dashboards, click New dashboard, then create one named Triage quality and cost.
  • Set the time range to Past 7 days in the dashboard header.
  • For each widget below, click Add Widget, then Custom Chart. Set the fields listed, then click Save Widget.
  • Add the cost widget:
    • View: Observations.
    • Metric: Total Cost (Sum).
    • Name: Cost per triage thread.
    • Chart Type: Horizontal Bar Chart. Set this before the breakdown.
    • Breakdown Dimension: Session Id. A breakdown splits the chart into one bar per value.
  • Add the latency widget:
    • View: Observations.
    • Metric: Latency (P 95).
    • Filters: Observation Name is logs_specialist, metrics_specialist, deploys_specialist, route_incident, and analyze_incident.
    • Breakdown Dimension: Name.
    • Name: P95 latency per agent.
    • Chart Type: Horizontal Bar Chart.
  • Add the accuracy widget:
    • View: Scores Boolean.
    • Metric: Value (Avg).
    • Filters: in Score Name, type root_cause_correct in Enter custom value and tick it.
    • Name: Root-cause accuracy.
    • Chart Type: Vertical Bar Chart, under Time Series.
  • Add the errors widget:
    • View: Observations.
    • Metric: Count.
    • Filters: Status is ERROR.
    • Breakdown Dimension: Name.
    • Name: Errors by step.
    • Chart Type: Horizontal Bar Chart.
  • Drag the widgets by their handles into a 2 × 2 grid, so all four fit on one screen.

Why these chart settings?

Use Session Id for the cost breakdown because Trace Name grouped the demo cost under n/a. Keep accuracy as a time-series Vertical Bar so quiet days do not look like zero accuracy.

You should now see four populated widgets covering cost, latency, accuracy, and errors. That single view turns separate incident runs into an operational trend.

How do you read this dashboard?

Cost per triage thread shows the model cost of each incident thread. A thread far above the others points to extra model calls, such as retries or a resumed run.

  • P95 latency per agent shows each agent's P95 latency, the time that 95 percent of its calls finish within. The longest bar is the slowest agent, and the first place to look when triage feels slow.
  • Root-cause accuracy shows the share of runs whose diagnosis named the planted cause. Any bar below 1 means at least one diagnosis missed it. Your obs-004 run skipped the deploys specialist, so today's bar sits below 1.
  • Errors by step counts failed observations by name. The planted obs-002 metrics failure appears here along with its parent steps, because an error travels upward through the recorded execution path.

🙋‍♀️ Dashboard does not match?

Compare each chart's source data, calculation, grouping, chart type, and filter with the settings above.

If the cost widget shows High cardinality dimension(s) 'sessionId' cannot be used with timeDimension., change its chart type to Horizontal Bar Chart.

Help me check the four dashboard widgets.

Connect the webhook automation

In Langfuse, an automation is a saved rule for delivering notifications. You will point your webhook automation at a webhook endpoint, the web address that receives each alert.

  • Open webhook.site in a new browser tab.
  • Copy the generated HTTPS URL into this project value: your webhook.site HTTPS URL.
  • In Langfuse, open Alerts, then click Connect Webhooks.
  • Create an Alert automation named Triage quality webhook with a Webhook action that uses your webhook.site HTTPS URL.
  • Save the automation.
  • Close the one-time Webhook Secret Created dialog. This project does not verify webhook signatures, so you do not need the secret.

Why Create the Automation First?

Each alert needs at least one automation. Creating the webhook automation first prevents the alert setup from stopping with At least one automation is required.

A free webhook endpoint from webhook.site expires after 7 days. It accepts at most 100 requests during that period.

Your webhook automation now gives Langfuse a destination for future alert notifications. Your workflow data remains unchanged.

Automation Not Saving?

  • Confirm that the event source is set to Alert.
  • Confirm that the action is set to Webhook.

Get help with connecting the Langfuse webhook automation.

Create and test the accuracy alert

The accuracy chart lets you review changes manually. The alert watches the average score for you and sends a notification whenever it falls below perfect accuracy.

  • Open Alerts, then click Create Alert.
  • Enter Root-cause accuracy dropped as the Title.
  • Choose the Scores (boolean) view, the Value measure, and the Avg aggregation.
  • In the Score Name filter, type root_cause_correct in Enter custom value and tick it.
  • Set the condition to below with an ALERT threshold of 1.
  • Set Over the past to 1 hour.
  • Open Advanced Options, then set When there is no data to Show severity NO DATA.
  • Check that Triage quality webhook is ticked under Automations in Notifications.
  • Save the alert.

You should see the saved alert with the Boolean average condition, the one-hour window, the no-data behavior, and the attached automation. The new alert starts at NO DATA until a fresh score arrives.

This model-backed run can take roughly 30 seconds to 4 minutes. A quiet terminal during that window is normal.

Before you run this, do you expect a diagnosis without the deploys specialist to earn a true or false score?

  • Generate a fresh weak diagnosis for the alert by running this command:
python3 app.py start --thread obs-005 --alert INC-2041 --skip deploys

What Does This Command Test?

  • The obs-005 thread creates a fresh checkpoint and Langfuse session.
  • The INC-2041 fixture has the planted deploy root cause that the root-cause score checks for.
  • The --skip deploys option removes the deploys specialist and adds the skip:deploys trace tag.

The terminal should print Score root_cause_correct: False and a Trace: URL. The false score supplies fresh data for the alert condition.

Alert Still Unchanged?

  • Refresh the alert if its state remains NO DATA or OK.
  • Confirm that root_cause_correct is ticked in the score-name filter.
  • Confirm that the webhook automation is still attached to the alert.

Get help with checking why the accuracy alert has not updated.

  • Refresh the saved alert and confirm that its no-data behavior reads Show severity NO DATA.
  • Confirm that all four widgets on the Triage quality and cost dashboard contain data.
  • Check your webhook.site tab for an alert request.

Within about a minute, the alert changes to ALERT and your webhook.site tab receives a POST request from Langfuse. Its body includes "type": "monitor-alert".

You now have one screen for workflow cost, agent speed, root-cause score, and errors. Your saved alert turns a quality drop into an automatic notification.

Secret mission

Compare Two Analyst Prompt Versions

Move the analyst prompt into Langfuse. Publish two versions without changing the application code, then compare their speed, text usage, cost, response count, and root-cause score.

Clean Up Your Resources

Clean Up Your Resources

Choose whether to keep your work available, pause it for later, or delete it. Resources that sit idle do not create new model-call charges.

Cost warning

Running more incidents sends new requests to the model on Vertex AI. Those requests can create usage charges, so stop running terminal commands when you finish testing.

The Langfuse Hobby plan remains free within its documented limits. Your free webhook endpoint, which receives automated alert messages, expires after seven days.

Resources you used:

  • Your Google Cloud Shell project folder at ~/langgraph-triage-observability. It contains the isolated Python environment, environment settings in .env, checkpoints, generated runbooks, and project code.
  • Your Google Cloud project with the Vertex AI API enabled, if you created it only for this project.
  • Your Langfuse project with traces, observations, sessions, root-cause scores, the Triage quality and cost dashboard, alert, webhook automation, API keys, and triage-analyst prompt versions.

Keep everything running

No action is needed. Choose this option if you are still comparing incidents or prompt versions.

  • Keep the Cloud Shell project folder so you can run more triage incidents.
  • Keep the Langfuse project so its traces, scores, dashboard, alert, and prompt comparisons remain available.
  • Keep the dedicated Google Cloud project only while you are actively using it.
  • Run new triage commands only when you have something specific to measure.

Your free webhook.site URL expires after seven days. It accepts at most 100 requests before then.

Pause - I'll come back to this later

Stop running the triage app to prevent new model requests while keeping your code, traces, and measurements available.

  • Stop running triage commands.
  • Close the existing Google Cloud Shell session.
  • Leave ~/langgraph-triage-observability in your Cloud Shell home directory.
  • Leave the Langfuse project intact so its dashboard and prompt comparisons remain available.
  • Leave the Google Cloud project intact so you can resume without repeating the cloud setup.

What remains while paused?

Your Langfuse traces, scores, dashboard, alert, webhook automation, and prompt versions remain available. Each incident thread's checkpoint also remains in triage_checkpoints.db.

No new model-request cost occurs while the triage app stays idle.

Delete - I don't want to use this again

Deleting these resources is permanent. This can feel risky, so choose this option only when you no longer need the code or traces.

Delete the Langfuse resources:

  • Open API Keys in the Langfuse project settings.
  • Revoke each API key to stop it from accessing the project.
  • Open Settings and use the project deletion control.
  • Complete the confirmation Langfuse shows.
  • Confirm that the project no longer appears in your Langfuse organization.

Remove the local project files:

This command permanently removes the project folder from Cloud Shell. Check the path carefully before you run it.

  • Remove the Cloud Shell project folder by running this command:
rm -rf ~/langgraph-triage-observability

What does this remove?

This command removes the entire ~/langgraph-triage-observability folder and everything inside it. That includes the isolated Python environment in .venv, settings in .env, checkpoints in triage_checkpoints.db, generated runbooks, and source files.

  • Confirm that langgraph-triage-observability no longer appears in your Cloud Shell home directory.

Delete a dedicated Google Cloud project:

Delete only a project that you created solely for this work. Keep any shared project that runs other applications or services.

  • Select the dedicated project in the Google Cloud console.
  • Open the project settings page.
  • Schedule the project for deletion.
  • Complete the confirmation Google Cloud shows.
  • Confirm that the dedicated project is scheduled for deletion.

Your free webhook endpoint expires on its own after seven days.

Nice Work!

Nice Work!

Outstanding work! You built a monitoring system in Langfuse that shows how your multi-agent triage app behaves.

You've learned how to:

  • Record every start and resume command as a trace, a step-by-step record of one command. Follow each specialist and tool step, then group runs from the same incident into a session with the responsible team attached.
  • Find the planted metrics failure at metric_window and confirm the Metrics backend timed out. message. Add a root-cause score, root_cause_correct, that catches a weak diagnosis.
  • Build a four-part dashboard that turns separate runs into trends. Send an automated webhook alert when the root_cause_correct score drops.
  • Complete the optional Secret Mission by saving two versions of triage-analyst in Langfuse. Connect each version to its analyst response, then compare v1 and v2 in Prompt Metrics.

Ready to quiz yourself?