Triage Incidents with LangGraph
Build a durable multi-agent CLI that triages incidents with team approvals.
Introduction
30 Second Summary
It's 2 a.m., checkout is failing, and one on-call engineer is digging through logs, deploys, and metrics one at a time while customers wait.
In this project, you'll build a multi-agent incident triage tool in LangGraph. Three AI specialists investigate logs, deploys, and metrics at the same time, keep their finished work if one crashes, and add a fix to the runbook only after the team that owns the service approves it. It stands on its own: the starter repo includes the finished workflow from Build a Resumable LangGraph Workflow, so you don't need to do that project first.
What You'll Build
Run one fixture alert and watch three specialists trace its logs, deploys, and metrics before the CLI writes approved fixes and every team decision to runbooks/inc-001.md.
By the end of this project, you'll have:
- A parallel specialist triage flow that routes INC-2041 to logs, deploys, and metrics investigators. You can watch their completion order vary before their typed findings merge into one diagnosis.
- A crash-safe recovery workflow that keeps completed logs and deploys findings. You can restart the CLI and see only the failed metrics investigation run again.
- A team-owned approval process that remains paused until each service owner decides. The published runbooks/inc-001.md runbook contains approved actions plus a complete decision audit log.
- Secret Mission: Finish a live web status page in Cloud Shell Web Preview that shows saved findings, team decisions, pending approvals, and the runbook without resuming the workflow.
Are there any prerequisites?
- A Google Cloud account with billing enabled for usage-based model requests.
- Access to Google Cloud Shell, which includes Git, Python, pip, and the Google Cloud CLI.
- Basic familiarity with Python and LangGraph.
Before We Start
Before you begin, picture the on-call problem you're solving: three AI agents check logs, deploys, and metrics at the same time, a crash-safe workflow keeps their finished work if one fails, and each team approves its own fix before anything reaches the runbook.
Set Up the Starter Repo
The starter repo gives you a working durable LangGraph workflow to build on. Proving that baseline first keeps later orchestration bugs separate from credential or fixture problems.
You will prepare Google Cloud Shell for Vertex AI. You will install the starter repository before smoke-testing its approval pause.
In this step, get ready to:
- Select a Google Cloud project for Vertex AI.
- Install the starter repository inside an isolated Python environment.
- Prove the inherited durable workflow reaches its approval pause.
Select your Google Cloud project
Vertex AI charges model requests to the active Google Cloud project. Cloud Shell also exposes that selection through the GOOGLE_CLOUD_PROJECT environment variable.
✔️ I have a Google Cloud account
- Sign in through the Google Cloud console.
- Confirm that the console opens. You don't need to select a project here, because you create one in Cloud Shell next.
ⓧ I need a Google Cloud account
Creating the account has no minimum spend. Google may request a payment method, and this project makes usage-based model requests after billing is enabled.
- Open the official Google Cloud signup page.
- Complete the account and billing setup.
- Return to the Google Cloud console.
- Confirm that the console opens. You don't need to select a project here, because you create one in Cloud Shell next.
- Open Google Cloud Shell in a new browser tab.
- Click Activate Cloud Shell if the terminal does not start automatically.
- Approve the authorization prompt if Google Cloud displays one.
- Wait for the command prompt. Initialization normally takes a few seconds.
You now have an authenticated terminal with the Google Cloud CLI available.
Create a new project
A dedicated project gives this build its own billing boundary. Linking billing permits paid Gemini requests.
Billing setup can feel consequential. The supplied project estimate stays under $0.50 for the full build.
- Create the dedicated project by running these commands. They make a unique project ID for you, so you don't need to choose one:
gcloud projects create "langgraph-triage-$(date +%s)" --name="LangGraph Incident Triage" --set-as-default
gcloud config get project
What do these commands do?
- The first command creates a Google Cloud project named LangGraph Incident Triage. $(date +%s) adds the current time in seconds to the ID, so no one else has the same ID.
- The project ID is permanent and must be globally unique. The name is only a display label, and you can change it later.
- --set-as-default makes the new project active in Cloud Shell.
- The second command prints the new project's ID.
You should see the project creation operation finish, then Updated property [core/project], then your new project ID on its own line.
Project creation failed?
Run the first command again. It makes a new ID each time. If it fails again, your account may not be allowed to create projects. Help me diagnose the project creation error.
- Copy the project ID the last command printed, and record it here: your Google Cloud project ID. Don't use an ID from the console's project selector, because that's an existing project.
- List the billing accounts available to your account by running this command:
gcloud billing accounts list --filter=open=true
What does this command do?
This lists billing accounts whose status is open. You need one account ID for the project link.
You should see at least one open billing account. Its ID is an 18-character value like 010101-F0FFF0-10XX01.
No open billing account?
An empty list means your account has no open billing account, or you can't view it. Create one with the billing account setup guide, then run the command again.
To check in the console instead, open My Billing Accounts in a new browser tab, so this project page stays open. Each billing account's ID is listed there.
- Record the open billing account ID here: your billing account ID.
- Link billing and enable Vertex AI by running these commands:
gcloud billing projects link [[PROJECT_ID="your Google Cloud project ID"]] --billing-account=[[BILLING_ACCOUNT_ID="your billing account ID"]]
gcloud services enable aiplatform.googleapis.com
What do these commands do?
- The first command links the open billing account to your project.
- The second command enables aiplatform.googleapis.com for Vertex AI access.
The last command can take up to 2 minutes and prints nothing until it finishes, so the terminal isn't frozen. You should see confirmation that billing is linked. You should also see the service enable operation finish successfully.
Billing or API setup failed?
A permissions error usually means your account cannot link the selected billing account or enable APIs in the project. Confirm both permissions before retrying. Help me diagnose the setup error.
Reuse an existing project
An existing project with billing linked works too, such as one from an earlier NextWork project. Reusing it skips project creation and the billing link.
- Choose this route only if the project still exists and has billing linked.
- Record the existing project ID here: your Google Cloud project ID.
- Select the project and enable Vertex AI by running these commands:
gcloud config set project [[PROJECT_ID="your Google Cloud project ID"]]
gcloud services enable aiplatform.googleapis.com
What do these commands do?
- The first command makes your existing project active in the current Cloud Shell session.
- The second command ensures aiplatform.googleapis.com is enabled for model access.
The last command can take up to 2 minutes and prints nothing until it finishes, so the terminal isn't frozen. You should see the selected project in the configuration output. You should also see the service enable operation finish successfully.
Existing project not available?
Confirm that the project ID matches your existing project. A permissions error means your current account cannot select the project or enable its APIs. Help me diagnose the existing-project setup.
Cloud Shell now propagates the selected project into GOOGLE_CLOUD_PROJECT. The starter app reads this value when it connects to Vertex AI.
Install the starter repository
The starter repository holds a working durable approval CLI, the incident fixtures used throughout this build, and setup code for the specialists and the status page. Its pinned dependencies keep every learner on the same Python package versions.
- Clone the starter repository into ~/langgraph-incident-triage-agents by running this command:
git clone https://github.com/nextwork-projects/langgraph-incident-triage.git ~/langgraph-incident-triage-agents
What does this command do?
Git copies the starter repository into a fixed location in your Cloud Shell home directory. That path remains consistent throughout the project.
You should see Git download the repository files into ~/langgraph-incident-triage-agents.
Clone failed?
Check that your Cloud Shell session has internet access. Confirm that the destination directory does not already contain an incomplete clone.
If the clone still fails, help me diagnose the Git clone problem.
- Enter the repository before creating its virtual environment by running these commands:
cd ~/langgraph-incident-triage-agents
python3 -m venv .venv
source .venv/bin/activate
What do these commands do?
- The first command moves your terminal into the cloned repository.
- The second command creates an isolated environment in .venv.
- The third command activates that environment for the current terminal session.
Your terminal prompt now starts with (.venv).
No (.venv) in your prompt?
Run source .venv/bin/activate again from ~/langgraph-incident-triage-agents. If it says No such file or directory, the python3 -m venv .venv command didn't finish, so run it again first.
- Install the pinned project dependencies by running this command:
python3 -m pip install -r requirements.txt
What does this command do?
Python reads the exact package pins from requirements.txt. It installs them inside the active virtual environment.
The installation output should finish without a dependency error.
Dependency installation failed?
Confirm that your terminal is inside ~/langgraph-incident-triage-agents. Confirm that the virtual environment is active before retrying the installation.
If the failure continues, help me troubleshoot the dependency installation.
The Vertex AI API can need a few minutes after enablement. This short wait gives you time to inspect the local evidence specialists use later.
- Click Open Editor in the Cloud Shell toolbar.
- Click Open Home Directory on the Welcome tab if the Explorer pane shows No folder opened.
- Expand langgraph-incident-triage-agents in the Explorer pane.
- Inspect data/alerts.json in the Cloud Shell file editor for alert records including INC-2041 plus INC-2042.
- Inspect data/logs.jsonl for incident log entries.
- Inspect data/deploys.json for recent deployment records including d-1042.
- Inspect data/metrics.json for service metric time series.
- Inspect data/services.json for service dependencies plus owning teams.
✔️ Awesome, I've got everything!
Your repository is installed with its original starter app, the fixture files, and the setup code for the specialist agents you build next.
ⓧ I'd like to double check the full code
Compare your requirements.txt with this complete pinned file:
langgraph==1.2.14
langgraph-checkpoint-sqlite==3.1.1
langchain-google-genai==4.4.0
langchain==1.4.4
What should match?
LangChain supplies the agent APIs used later. The checkpoint package connects LangGraph to SQLite for durable workflow state.
- The inherited app.py remains the original durable single-workflow approval CLI.
- specialists.py holds the model connection and the three fixture tools for the specialist agents.
- status_page.py holds the web page you finish in the Secret Mission.
- The start command still accepts the --thread flag plus the --incident flag.
- The data/alerts.json fixture contains INC-2041 plus INC-2042.
- The data/deploys.json fixture contains recent deployment records including d-1042.
- The data/logs.jsonl fixture contains incident log entries.
- The data/metrics.json fixture contains service metric time series.
- The data/services.json fixture maps services to dependencies plus owning teams.
Smoke-test the inherited workflow
The smoke test checks your credentials through a real model request. It also proves the inherited checkpoint workflow can still pause for approval.
The first model call can take one or two minutes while Gemini responds. A quiet terminal during that wait does not indicate a failure.
Before you run the smoke test, do you think the workflow will complete immediately or pause for a human decision?
- Click in the terminal panel below the Editor. Your prompt should start with (.venv).
No (.venv) in your prompt?
Your virtual environment isn't active. This happens in a new terminal. Run cd ~/langgraph-incident-triage-agents && source .venv/bin/activate, then continue. If your prompt doesn't show your project ID either, also run gcloud config set project YOUR_PROJECT_ID.
- Start the inherited incident workflow by running this command:
python3 app.py start --thread smoke-001 --incident "Checkout API returns HTTP 500 for 1 in 6 requests after a config deploy."
What does this command do?
The command starts a durable workflow under the thread ID smoke-001. The incident description gives the inherited analyst a concrete failure to assess.
The existing policy gate checks the resulting action before its approval interrupt pauses the workflow.
You should see WORKFLOW PAUSED with an approval payload. That pause proves the credentials plus model access are working.
First run looks noisy?
- Wait a few minutes before retrying if the first call reports 403 PERMISSION_DENIED.
- Treat a LangChainBetaWarning about the v3 streaming protocol as informational.
- Treat a warning that mentions function_call as informational when the workflow still pauses.
If the workflow still cannot reach its pause, help me troubleshoot the Cloud Shell smoke run.
You have your baseline. The inherited durable CLI now reaches its approval payload from the selected Google Cloud project.
Your cloud project plus starter repository are ready. Next, you will split the single analyst into role-specific logs, deploys, and metrics specialists.
Build Specialist Agents
Your inherited workflow can pause for approval. However, one general analyst hides which evidence came from each investigative role.
You will build three independent agents in Google Cloud Shell. Each agent can inspect one evidence source, and every result follows the same typed JSON structure.
In this step, get ready to:
- Connect the specialist module to Gemini through Vertex AI.
- Build logs, deploys, and metrics agents with role-limited tools.
- Run each specialist against INC-2041 and compare the typed findings.
Open the starter specialist tools
Each specialist needs the same model connection, plus a tool that shows it one slice of the fixture data. The starter repo already includes both in specialists.py, so you can go straight to the agents.
- Switch back to the Cloud Shell editor from the previous step.
- In the Explorer, open specialists.py in the langgraph-incident-triage-agents folder.
- Cloud Shell Editor saves your changes automatically, so you never need to save files in this project.
What's already in specialists.py?
- MODEL_ID sets gemini-3.7-flash for every specialist. DATA_DIR points at the data/ folder.
- load_json() reads one fixture file from data/.
- build_model() connects to Gemini through Vertex AI in the project from GOOGLE_CLOUD_PROJECT. It retries a failed request up to two times and waits up to 180 seconds for each answer.
- search_logs, recent_deploys, and metric_window are the three tools: one for logs, one for deploys, and one for metrics. The @tool line above each function turns it into a tool an agent can call, and the text under the function name tells the agent what the tool does.
- metric_window fails on purpose when TRIAGE_FAIL=metrics is set. You use this in Step 4 to crash the metrics specialist.
- Scroll to the bottom of specialists.py. It ends with the metric_window tool, and you add the agents below it.
Define the role-specific agents
A tool controls which evidence an agent can access. A system prompt gives that agent its investigative role. Structured output gives every result the same Finding shape.
- Add the roles and the Finding schema at the bottom of specialists.py, below metric_window, by pasting this code:
SPECIALISTS = {
"logs": {
"tools": [search_logs],
"prompt": "You are the logs investigator on an incident response team. "
"Search the logs of the alerting service and its dependencies for "
"errors that explain the alert, and note when they started.",
},
"deploys": {
"tools": [recent_deploys],
"prompt": "You are the change investigator on an incident response team. "
"Find deploys to the alerting service or its dependencies shortly "
"before the alert, and judge which change could cause it.",
},
"metrics": {
"tools": [metric_window],
"prompt": "You are the metrics investigator on an incident response team. "
"Read the metrics of the alerting service and its dependencies and "
"describe what changed, when, and by how much.",
},
}
FINDING_SCHEMA = {
"title": "Finding",
"type": "object",
"properties": {
"summary": {"type": "string"},
"evidence": {"type": "array", "items": {"type": "string"}},
"suspected_cause": {"type": "string"},
"severity": {"type": "string", "enum": ["SEV1", "SEV2", "SEV3", "SEV4"]},
},
"required": ["summary", "evidence", "suspected_cause", "severity"],
}
What do the roles and the schema define?
SPECIALISTS pairs each role with one tool. It also stores one role-specific prompt.
The logs role can inspect only logs through its agent tool list. The same boundary applies to deploys and metrics.
FINDING_SCHEMA makes every specialist return a summary, an evidence list, a suspected cause, and a severity.
Severity is limited to SEV1 through SEV4. A shared shape lets later graph nodes combine the three findings predictably.
- Confirm that SPECIALISTS contains the logs, deploys, and metrics roles, and that FINDING_SCHEMA lists four required properties.
- Add the agent factory and runner below FINDING_SCHEMA by pasting these functions:
def build_specialist(name: str):
spec = SPECIALISTS[name]
return create_agent(
build_model(),
tools=spec["tools"],
system_prompt=spec["prompt"]
+ " Use your tools before answering. Quote exact evidence. "
"Rate severity from SEV1 (worst) to SEV4 from what you found.",
response_format=FINDING_SCHEMA,
name=f"{name}_specialist",
)
def run_specialist(name: str, brief: str) -> dict:
result = build_specialist(name).invoke(
{"messages": [("human", brief)]},
config={"recursion_limit": 25},
)
return result["structured_response"]
def alert_brief(alert_id: str) -> str:
alert = {a["id"]: a for a in load_json("alerts.json")}[alert_id]
service = alert["service"]
related = [service] + load_json("services.json")[service]["depends_on"]
return (
f"Alert {alert['id']} fired at {alert['fired_at']} on {service}.\n"
f"{alert['title']}: {alert['description']}\n"
f"Services to check: {', '.join(related)}."
)
How do these functions build and run an agent?
build_specialist() looks up the selected role. It passes that role's tool and prompt to create_agent().
response_format applies the Finding schema. The agent name identifies the selected specialist in later graph output.
run_specialist() sends the alert brief as a human message. It returns the typed structured_response.
The recursion_limit caps each agent at 25 graph steps. A specialist stuck calling its tool stops with GraphRecursionError instead of making thousands of billed model calls.
alert_brief() combines the selected alert with its service dependencies. Every role receives the same incident scope.
- Confirm that create_agent() receives system_prompt, response_format, and name, and that run_specialist() sets recursion_limit to 25.
Agent factory showing an error?
Check that create_agent comes from langchain.agents. Confirm that the prompt argument is named system_prompt.
Help me debug the build_specialist function and its create_agent arguments.
Add the standalone CLI and test each role
The graph stays unchanged in this step. A standalone CLI proves that every specialist can investigate the same alert through its own evidence source.
- Add the command-line entry point at the bottom of specialists.py, below alert_brief(), by pasting this final chunk:
def main():
parser = argparse.ArgumentParser(description="Run one specialist on one alert.")
parser.add_argument("specialist", choices=list(SPECIALISTS))
parser.add_argument("alert")
args = parser.parse_args()
print(f"{args.specialist} specialist investigating {args.alert}...")
finding = run_specialist(args.specialist, alert_brief(args.alert))
print(json.dumps(finding, indent=2))
if __name__ == "__main__":
main()
What does the CLI accept?
main() requires a specialist name and an alert ID. The specialist value is restricted to the roles in SPECIALISTS.
The final print formats the typed Finding as indented JSON. This makes the shared output structure visible in the terminal.
Before you run the checks, do you expect every role to return the same evidence?
Each specialist can take 1 to 5 minutes while Gemini responds. A quiet terminal during that wait is normal.
- Click in the terminal panel below the Editor. Your prompt should start with (.venv).
No (.venv) in your prompt?
Your virtual environment isn't active. This happens in a new terminal. Run cd ~/langgraph-incident-triage-agents && source .venv/bin/activate, then continue. If your prompt doesn't show your project ID either, also run gcloud config set project YOUR_PROJECT_ID.
- Run the logs specialist against the planted incident by running this command:
python3 specialists.py logs INC-2041
What does this command test?
The command loads INC-2041 from the fixtures. It gives the resulting brief to the logs specialist.
The agent can use only search_logs before returning its Finding object.
You should see an investigation message followed by JSON containing summary, evidence, suspected_cause, and severity. A warning about non-text parts that lists function_call can appear first, and it's expected.
Specialist run failed?
Confirm that the terminal still shows the active .venv environment. Check that the terminal is inside ~/langgraph-incident-triage-agents.
A missing project message means GOOGLE_CLOUD_PROJECT is unavailable, so run gcloud config set project YOUR_PROJECT_ID in this terminal. A fixture failure usually points to a misspelled file name or alert ID.
A 504 DEADLINE_EXCEEDED, 429 RESOURCE_EXHAUSTED, or ReadTimeout error means Gemini is busy or didn't respond in time. This happens during busy periods, so wait a minute and run the same command again.
An IndentationError or SyntaxError means a pasted block landed on a line that already had code or spaces. Open the line the error names, and check that each pasted def line starts at the far left, on its own line. Delete any spaces in front of it, then run the command again.
Help me diagnose why specialists.py failed for INC-2041.
- Run the deploys specialist against the same incident by running this command:
python3 specialists.py deploys INC-2041
What does this command test?
This runs the change investigator with the same alert. The specialist can inspect only the recent deployment fixture before returning a typed finding.
You should see another Finding JSON object. Its evidence should focus on recent changes. At least one of the three findings should identify d-1042 or the connection-pool change.
- Run the metrics specialist against the same incident by running this command:
python3 specialists.py metrics INC-2041
What does this command test?
This runs the metrics investigator with the same alert. The specialist can inspect only the stored metric time series before returning a typed finding.
You should see a third Finding JSON object based on metric time series. The wording can vary because the model generates each response from the fixture evidence.
Deploys or metrics finding doesn't name d-1042?
The model writes each finding, so the wording changes between runs. If neither the deploys nor the metrics finding names d-1042 or the connection-pool change, run python3 specialists.py deploys INC-2041 again.
✔️ Awesome, I've got everything!
That worked. All three roles now return typed findings from their own evidence sources. Keep app.py unchanged for the next step.
ⓧ I'd like to double check the full code
Compare your complete specialists.py with this cumulative version:
# Import the CLI, fixture, and agent helpers used throughout this file.
import argparse
import json
import os
from pathlib import Path
from langchain.agents import create_agent
from langchain_core.tools import tool
from langchain_google_genai import ChatGoogleGenerativeAI
# Keep every specialist on one model and one fixture directory.
MODEL_ID = "gemini-3.7-flash"
DATA_DIR = Path(__file__).parent / "data"
LEVELS = {"INFO": 0, "WARN": 1, "ERROR": 2}
def load_json(name: str):
# Load one fixture file relative to specialists.py.
return json.loads((DATA_DIR / name).read_text(encoding="utf-8"))
def build_model():
# Read the active project selected in Cloud Shell.
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
if not project_id:
raise RuntimeError("GOOGLE_CLOUD_PROJECT is not set.")
# Use Vertex AI with bounded retries and request time.
return ChatGoogleGenerativeAI(
model=MODEL_ID,
project=project_id,
location="global",
vertexai=True,
max_retries=2,
timeout=180,
)
@tool
def search_logs(service: str, min_level: str = "WARN") -> str:
"""Return log lines for one service at or above a level: INFO, WARN, or ERROR."""
threshold = LEVELS.get(min_level.upper(), 1)
lines = []
for raw in (DATA_DIR / "logs.jsonl").read_text(encoding="utf-8").splitlines():
entry = json.loads(raw)
if entry["service"] == service and LEVELS[entry["level"]] >= threshold:
lines.append(f"{entry['ts']} {entry['level']} {entry['message']}")
return "\n".join(lines[-25:]) or f"No {min_level} logs for {service}."
@tool
def recent_deploys(service: str = "") -> str:
"""List recent deploys, newest first. Pass a service name, or leave it empty for every service."""
deploys = sorted(
load_json("deploys.json"), key=lambda d: d["deployed_at"], reverse=True
)
if service:
deploys = [d for d in deploys if d["service"] == service]
return "\n".join(
f"{d['deployed_at']} {d['id']} {d['service']} ({d['team']}): {d['change']}"
for d in deploys
) or f"No deploys for {service}."
@tool
def metric_window(service: str) -> str:
"""Return every metric time series for one service."""
if os.environ.get("TRIAGE_FAIL") == "metrics":
raise RuntimeError("Metrics backend timed out.")
series = load_json("metrics.json").get(service)
if not series:
return f"No metrics for {service}."
return "\n".join(
f"{name}: " + ", ".join(f"{p['ts'][11:16]}={p['value']}" for p in points)
for name, points in series.items()
)
SPECIALISTS = {
"logs": {
"tools": [search_logs],
"prompt": "You are the logs investigator on an incident response team. "
"Search the logs of the alerting service and its dependencies for "
"errors that explain the alert, and note when they started.",
},
"deploys": {
"tools": [recent_deploys],
"prompt": "You are the change investigator on an incident response team. "
"Find deploys to the alerting service or its dependencies shortly "
"before the alert, and judge which change could cause it.",
},
"metrics": {
"tools": [metric_window],
"prompt": "You are the metrics investigator on an incident response team. "
"Read the metrics of the alerting service and its dependencies and "
"describe what changed, when, and by how much.",
},
}
FINDING_SCHEMA = {
"title": "Finding",
"type": "object",
"properties": {
"summary": {"type": "string"},
"evidence": {"type": "array", "items": {"type": "string"}},
"suspected_cause": {"type": "string"},
"severity": {"type": "string", "enum": ["SEV1", "SEV2", "SEV3", "SEV4"]},
},
"required": ["summary", "evidence", "suspected_cause", "severity"],
}
def build_specialist(name: str):
spec = SPECIALISTS[name]
return create_agent(
build_model(),
tools=spec["tools"],
system_prompt=spec["prompt"]
+ " Use your tools before answering. Quote exact evidence. "
"Rate severity from SEV1 (worst) to SEV4 from what you found.",
response_format=FINDING_SCHEMA,
name=f"{name}_specialist",
)
def run_specialist(name: str, brief: str) -> dict:
result = build_specialist(name).invoke(
{"messages": [("human", brief)]},
config={"recursion_limit": 25},
)
return result["structured_response"]
def alert_brief(alert_id: str) -> str:
alert = {a["id"]: a for a in load_json("alerts.json")}[alert_id]
service = alert["service"]
related = [service] + load_json("services.json")[service]["depends_on"]
return (
f"Alert {alert['id']} fired at {alert['fired_at']} on {service}.\n"
f"{alert['title']}: {alert['description']}\n"
f"Services to check: {', '.join(related)}."
)
def main():
parser = argparse.ArgumentParser(description="Run one specialist on one alert.")
parser.add_argument("specialist", choices=list(SPECIALISTS))
parser.add_argument("alert")
args = parser.parse_args()
print(f"{args.specialist} specialist investigating {args.alert}...")
finding = run_specialist(args.specialist, alert_brief(args.alert))
print(json.dumps(finding, indent=2))
if __name__ == "__main__":
main()
Your specialist boundaries now work. Next, you will route alerts into parallel branches and merge the resulting findings into one diagnosis.
Route Alerts in Parallel
Your logs, deploys, and metrics specialists can investigate an alert independently. The inherited workflow still lacks an Incident Commander that chooses the right investigators for each incident.
A router architecture in LangGraph can dispatch selected specialists at the same time. This first parallel run also exposes what happens when several branches update one shared field.
In this step, get ready to:
- Route each alert to the specialists most likely to explain it.
- Fan selected investigations out across parallel graph branches.
- Merge concurrent findings before one deferred synthesis.
Build the routed fan-out
The router reads the alert before specialist work begins. Its structured response contains an initial severity plus the roles needed for that incident. You will update app.py in focused chunks and run a syntax check after each group.
- Switch back to app.py in the Cloud Shell editor.
- Replace everything from the top of app.py down to the line above RUNBOOK_DIR with this code:
# Import CLI, serialization, path, and typed-state helpers.
import argparse
import json
import os
from pathlib import Path
from typing import Literal, TypedDict
# Require checkpoint values to serialize without silent fallbacks.
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
# Reuse the tested specialists and fixture helpers.
from specialists import SPECIALISTS, alert_brief, build_model, load_json, run_specialist
DB_PATH = "triage_checkpoints.db"
SEVERITY_ORDER = ["SEV4", "SEV3", "SEV2", "SEV1"]
What changes at the top of the file?
The Send type carries a destination node plus the state for one branch. The specialist imports let the graph reuse the agents you already tested.
The new database separates this graph from checkpoints created by the inherited workflow. SEVERITY_ORDER gives the graph a consistent ranking from the lowest severity to the highest severity.
MODEL_ID is gone from app.py, because every model now comes from build_model() in specialists.py.
Parallel branches will soon return separate findings to one shared state. The first version deliberately gives that field no merge rule.
- Add the router schema above the existing IncidentState declaration:
# Constrain the Incident Commander's routing response.
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"],
}
What does the router return?
The schema limits the router to one severity, a list of known specialist names, and a reason for its choice. That predictable shape becomes the input to parallel fan-out.
- Replace the existing IncidentState declaration with this deliberately incomplete shared state and branch task:
# Store values shared across the incident workflow.
class IncidentState(TypedDict, total=False):
incident_id: str
incident: str
alert: dict
severity: str
specialists: list[str]
findings: list[dict]
analysis: dict
requires_approval: bool
policy_reason: str
decision: bool
actions: list[dict]
approvals: list[dict]
status: str
audit_log: list[str]
runbook_path: str
# Give each parallel branch only the data it needs.
class SpecialistTask(TypedDict):
specialist: str
brief: str
Why is findings still a plain list?
The first version deliberately gives findings no merge rule. You will run this version and see why parallel state needs a reducer.
- Check the schema and state edits by running:
python3 -m py_compile app.py && echo "Schema and state passed."
You should see Schema and state passed. and return to the terminal prompt.
Syntax check failed?
Open the line named in the error. Check that each pasted line uses the indentation shown in the snippet.
Help me fix the schema and state syntax error.
- Replace the existing build_analyst() function with the two model factories below:
def build_analyst():
# Apply the inherited analysis schema to the shared model.
return build_model().with_structured_output(
schema=ANALYSIS_SCHEMA,
method="json_schema",
)
def build_router():
# Apply the routing schema to the Incident Commander.
return build_model().with_structured_output(
schema=ROUTER_SCHEMA,
method="json_schema",
)
Why use two model factories?
Both factories reuse build_model() from specialists.py. Each applies the output schema required by its graph node.
- Add the alert helper and router node below safe_incident_id():
def incident_brief(state: IncidentState) -> str:
# Build the same evidence scope for every selected branch.
return alert_brief(state["alert"]["id"])
def route_incident(state: IncidentState):
# Ask the Incident Commander to classify and route the alert.
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']}"],
}
What does the router save?
The node prints its routing choice. It then saves the selected roles, initial severity, status, and routing reason in shared state.
- Check the model factories and router by running:
python3 -m py_compile app.py && echo "Router code passed."
You should see Router code passed. with no Python traceback.
- Add the fan-out and specialist node below route_incident():
def dispatch_specialists(state: IncidentState):
# Create one parallel task for every selected specialist.
brief = incident_brief(state)
return [
Send("investigate", {"specialist": name, "brief": brief})
for name in state["specialists"]
]
def investigate(task: SpecialistTask):
# Run one role inside its own parallel branch.
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"],
}
How does fan-out work?
dispatch_specialists() creates one Send per selected role. Each branch runs investigate() with the same alert brief.
- Replace the existing analyze_incident() function with the synthesis node:
def analyze_incident(state: IncidentState):
# Give the analyst every finding returned by the branches.
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. 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."],
}
What does synthesis receive?
The analyst receives the complete findings list as JSON. Its audit entry records how many branch results supported the diagnosis.
- Check the fan-out and synthesis nodes by running:
python3 -m py_compile app.py && echo "Specialist nodes passed."
You should see Specialist nodes passed. before wiring the nodes into the graph.
Node syntax check failed?
Open the first line named in the traceback. A misplaced def line or copied indentation usually identifies the incomplete edit.
Help me fix the routed node syntax error.
- Replace the whole build_graph() function with this version:
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)
builder.add_node("policy_check", policy_check)
builder.add_node("approval_gate", approval_gate)
builder.add_node("publish_runbook", publish_runbook)
builder.add_node("reject_runbook", reject_runbook)
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)
builder.add_conditional_edges("approval_gate", approval_route)
builder.add_edge("publish_runbook", END)
builder.add_edge("reject_runbook", END)
return builder.compile(checkpointer=checkpointer)
How does the graph flow?
The graph starts with routing. Its conditional edge expands the returned tasks into parallel investigations.
Every selected investigation points to synthesis. The inherited policy flow continues after analysis.
- Replace the whole parse_args() function with the fixture-based CLI parser:
def parse_args():
# Accept a fixture alert when starting a new thread.
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"],
required=True,
)
return parser.parse_args()
What does the CLI accept?
The start command now accepts an alert ID such as INC-2041 instead of free-form incident text. The resume command keeps the inherited approval decision.
- Replace the whole main() function with the fixture-loading workflow:
def main():
# Reopen the same checkpoint thread for starts and resumes.
args = parse_args()
config = {"configurable": {"thread_id": args.thread}}
with SqliteSaver.from_conn_string(DB_PATH) as checkpointer:
graph = build_graph(checkpointer)
if args.command == "start":
# Load the selected fixture into shared graph state.
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": [],
}
else:
graph_input = Command(resume=args.decision)
stream = graph.stream_events(
graph_input, config=config, durability="sync", version="v3"
)
display_stream(stream)
How does the CLI load an incident?
main() indexes every fixture by alert ID. The selected alert becomes shared state for routing and specialist investigation.
- Run the final syntax check before starting the graph:
python3 -m py_compile app.py && echo "Routed workflow passed."
That is the setup complete. You should see Routed workflow passed. with no traceback.
Final syntax check failed?
Check the first traceback line inside app.py. A misplaced function or an old --incident reference usually identifies the incomplete replacement.
Help me fix the final app.py syntax check.
Watch parallel writes collide
Several investigations can now finish during one graph step. Each branch returns a separate value for the same plain findings field.
Before you run the graph, do you think one plain state field can accept all three branch updates?
- Click in the terminal panel below the Editor. Your prompt should start with (.venv).
No (.venv) in your prompt?
Your virtual environment isn't active. This happens in a new terminal. Run cd ~/langgraph-incident-triage-agents && source .venv/bin/activate, then continue. If your prompt doesn't show your project ID either, also run gcloud config set project YOUR_PROJECT_ID.
- Start the first parallel investigation by running:
python3 app.py start --thread parallel-001 --alert INC-2041
This failure is intentional
You will see the router select specialists before the run fails with InvalidUpdateError: At key 'findings': Can receive only one value per step. Use an Annotated key to handle multiple values..
Every branch produced a valid finding. The shared state needs an explicit rule for combining those updates.
Merge results and verify the join
A reducer combines concurrent updates for one state field. The findings reducer joins branch lists while the severity reducer preserves the worst reported level.
- Near the top of app.py, find the current typing import:
from typing import Literal, TypedDict
- Replace the typing import with the two lines below to add operator and Annotated.
import operator
from typing import Annotated, Literal, TypedDict
What do these imports provide?
operator.add concatenates the one-item lists returned by parallel branches. Annotated attaches that merge rule to a state field.
- Add the severity reducer above IncidentState by pasting this function:
def highest_severity(current: str, new: str) -> str:
# Keep the most urgent severity reported by any branch.
if current not in SEVERITY_ORDER:
return new
return max(current, new, key=SEVERITY_ORDER.index)
How does severity reduction work?
The reducer returns the incoming value when no valid severity exists yet. Later updates are compared by their position in SEVERITY_ORDER.
- In IncidentState, find the plain severity and findings fields:
severity: str
findings: list[dict]
- Replace those two fields with the reducer-backed versions:
severity: Annotated[str, highest_severity]
findings: Annotated[list[dict], operator.add]
How do the reducers protect state?
- The findings reducer concatenates each branch's one-item list.
- The severity reducer keeps the highest-severity update.
- The other fields keep their inherited single-update behavior.
- In build_graph(), find the current synthesis registration:
builder.add_node("analyze_incident", analyze_incident)
Why change this registration?
A normal downstream node can become eligible while other branch work remains pending. Synthesis needs every selected finding before it runs.
- Replace the registration with this deferred version:
builder.add_node("analyze_incident", analyze_incident, defer=True)
What does deferred execution guarantee?
Deferred execution waits until no selected specialist task remains pending. The graph then runs synthesis once with the merged findings.
- Check the reducer and deferred-node edits by running:
python3 -m py_compile app.py && echo "Reducer fix passed."
You should see Reducer fix passed. before you retry the workflow.
Before you retry, which specialist completion lines do you expect to appear in an unpredictable order?
Allow time for the agents
A complete start can take 1 to 7 minutes while the router plus selected specialists call the model. A quiet terminal during an investigation is expected.
A 504 DEADLINE_EXCEEDED, 429 RESOURCE_EXHAUSTED, or ReadTimeout error comes from a busy or slow model, not your code. Wait a minute, then rerun with a new thread ID such as parallel-002b, because the failed thread keeps its partial findings.
- Run the repaired workflow with a fresh thread ID:
python3 app.py start --thread parallel-002 --alert INC-2041
What should you see?
You should see the router send the severe alert to logs, deploys, and metrics. Their completion lines can appear in any order.
Synthesis runs once after every selected specialist finishes. The inherited policy flow then continues.
Still seeing a concurrent update error?
Confirm that findings uses Annotated[list[dict], operator.add] in IncidentState.
Confirm that operator plus Annotated are imported near the top of app.py.
Ask for help with my parallel findings reducer.
The Incident Commander can also choose a smaller team for a narrower alert. This keeps specialist work proportional to the incident.
Before you check the second fixture, do you expect the router to select all three specialists again?
- Run the lower-severity fixture with a fresh thread ID:
python3 app.py start --thread parallel-small-001 --alert INC-2042
Check the narrower route
You should see the router choose fewer specialists when one or two roles can explain the symptom. Synthesis still runs once after every selected branch finishes.
INC-2042 is low severity and matches no policy rule, so it needs no approval. The workflow completes and publishes runbooks/parallel-small-001.md straight away.
Router picked all three specialists?
The router asks the model which specialists to send, so its choice can vary. In testing, it chose metrics and deploys for INC-2042. If it picked all three, the workflow still works. Run it again with a new thread ID, such as parallel-small-002, to see the narrower route.
✔️ Awesome, I've got everything!
Your router now selects specialist branches. Their concurrent findings merge before one deferred synthesis.
ⓧ I'd like to double check the full code
Compare your complete app.py with this cumulative Step 3 version:
# Import CLI, serialization, path, and typed-state helpers.
import argparse
import json
import operator
import os
from pathlib import Path
from typing import Annotated, Literal, TypedDict
# Require checkpoints to deserialize only known-safe values.
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
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": "IncidentAnalysis",
"type": "object",
"properties": {
"severity": {
"type": "string",
"enum": ["SEV1", "SEV2", "SEV3", "SEV4"],
},
"summary": {"type": "string"},
"proposed_action": {"type": "string"},
"risk": {"type": "string", "enum": ["low", "high"]},
"rationale": {"type": "string"},
},
"required": [
"severity",
"summary",
"proposed_action",
"risk",
"rationale",
],
}
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:
# Keep the most urgent severity reported by any branch.
if current not in SEVERITY_ORDER:
return new
return max(current, new, key=SEVERITY_ORDER.index)
# Store values shared across the incident workflow.
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
requires_approval: bool
policy_reason: str
decision: bool
actions: list[dict]
approvals: list[dict]
status: str
audit_log: list[str]
runbook_path: str
# Give each parallel branch only the data it needs.
class SpecialistTask(TypedDict):
specialist: str
brief: str
def build_analyst():
# Apply the inherited analysis schema to the shared model.
return build_model().with_structured_output(
schema=ANALYSIS_SCHEMA,
method="json_schema",
)
def build_router():
# Apply the routing schema to the Incident Commander.
return build_model().with_structured_output(
schema=ROUTER_SCHEMA,
method="json_schema",
)
def safe_incident_id(incident_id: str) -> str:
# Keep generated runbook paths inside the runbooks directory.
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:
# Build the same evidence scope for every selected branch.
return alert_brief(state["alert"]["id"])
def route_incident(state: IncidentState):
# Ask the Incident Commander to classify and route the alert.
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):
# Create one parallel task for every selected specialist.
brief = incident_brief(state)
return [
Send("investigate", {"specialist": name, "brief": brief})
for name in state["specialists"]
]
def investigate(task: SpecialistTask):
# Run one role inside its own parallel branch.
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):
# Give the analyst every finding returned by the branches.
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. 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):
# Apply the inherited approval policy to the synthesized proposal.
analysis = state["analysis"]
searchable_text = f"{state['incident']} {analysis['proposed_action']}".lower()
severity_requires_review = analysis["severity"] in {"SEV1", "SEV2"}
term_requires_review = any(
term in searchable_text for term in RESTRICTED_TERMS
)
requires_approval = severity_requires_review or term_requires_review
reason = (
"High severity or restricted operational language detected."
if requires_approval
else "No high-risk policy rule matched."
)
return {
"requires_approval": requires_approval,
"policy_reason": reason,
"status": "policy_checked",
"audit_log": state["audit_log"] + [f"Policy check: {reason}"],
}
def policy_route(state: IncidentState) -> Literal["approval_gate", "publish_runbook"]:
# Route risky proposals through human approval.
return "approval_gate" if state["requires_approval"] else "publish_runbook"
def approval_gate(state: IncidentState):
# Pause the graph until a human approves or rejects the proposal.
decision = interrupt(
{
"question": "Approve this remediation proposal?",
"incident_id": state["incident_id"],
"incident": state["incident"],
"analysis": state["analysis"],
"policy_reason": state["policy_reason"],
"allowed_decisions": ["approve", "reject"],
}
)
if decision not in ("approve", "reject"):
raise ValueError("Decision must be 'approve' or 'reject'.")
approved = decision == "approve"
return {
"decision": approved,
"status": "approved" if approved else "rejected",
"audit_log": state["audit_log"]
+ ["Human approved the proposal." if approved else "Human rejected the proposal."],
}
def approval_route(state: IncidentState) -> Literal["publish_runbook", "reject_runbook"]:
# Publish only an approved proposal.
return "publish_runbook" if state["decision"] else "reject_runbook"
def publish_runbook(state: IncidentState):
# Write the approved or low-risk diagnosis to Markdown.
RUNBOOK_DIR.mkdir(exist_ok=True)
path = RUNBOOK_DIR / f"{safe_incident_id(state['incident_id'])}.md"
analysis = state["analysis"]
approval_outcome = "Approved" if state.get("decision") else "Not required by policy"
audit_log = state["audit_log"] + [f"Published runbook to {path}."]
audit_lines = "\n".join(f"- {entry}" for entry in audit_log)
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: {analysis['severity']}\n\n"
f"Summary: {analysis['summary']}\n\n"
f"Proposed action: {analysis['proposed_action']}\n\n"
f"Rationale: {analysis['rationale']}\n\n"
f"Model risk: {analysis['risk']}\n\n"
f"Policy result: {state['policy_reason']}\n\n"
f"Approval outcome: {approval_outcome}\n\n"
"Audit log:\n"
f"{audit_lines}\n",
encoding="utf-8",
)
return {
"status": "published",
"runbook_path": str(path),
"audit_log": audit_log,
}
def reject_runbook(state: IncidentState):
# End the workflow without publishing a rejected proposal.
return {
"status": "rejected_without_publish",
"audit_log": state["audit_log"] + ["Publishing was skipped."],
}
def build_graph(checkpointer: SqliteSaver):
# Register the routed investigation and inherited policy nodes.
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)
builder.add_node("reject_runbook", reject_runbook)
# Fan out after routing, then continue through the policy flow.
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)
builder.add_conditional_edges("approval_gate", approval_route)
builder.add_edge("publish_runbook", END)
builder.add_edge("reject_runbook", END)
return builder.compile(checkpointer=checkpointer)
def display_stream(stream):
# Print either the pending approval or the final workflow state.
final_state = stream.output
if stream.interrupted:
print("WORKFLOW PAUSED")
print(json.dumps(stream.interrupts[0].value, indent=2))
return
print("WORKFLOW COMPLETE")
print(json.dumps(final_state, indent=2))
def parse_args():
# Accept a fixture alert when starting a new thread.
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"],
required=True,
)
return parser.parse_args()
def main():
# Reopen the same checkpoint thread for starts and resumes.
args = parse_args()
config = {"configurable": {"thread_id": args.thread}}
with SqliteSaver.from_conn_string(DB_PATH) as checkpointer:
graph = build_graph(checkpointer)
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": [],
}
else:
graph_input = Command(resume=args.decision)
stream = graph.stream_events(
graph_input, config=config, durability="sync", version="v3"
)
display_stream(stream)
if __name__ == "__main__":
main()
Your Incident Commander now routes alerts through parallel specialist investigations without losing branch results. Next, you will prove that completed investigations remain saved when one specialist crashes.
Resume a Crashed Specialist
Your router now sends logs, deploys, and metrics work down parallel branches. A metrics crash can still interrupt the entire super-step.
LangGraph preserves completed sibling updates as pending writes in SQLite. This step makes that durable state visible before a new process resumes the unfinished branch.
In this step, get ready to:
- Report the specialist findings saved before a workflow failure.
- Allow a failed thread to resume without an approval decision.
- Prove that only the crashed metrics investigation runs again.
Report the saved work after failure
A raw exception hides the useful checkpoint state behind a traceback. A failure summary can show which branches finished plus which node remains pending.
- Return to app.py in the Google Cloud Shell Editor.
- Find the existing display_stream() function.
- Add the failure-reporting function immediately below it using this code:
def display_failure(graph, config, error):
# Read the durable snapshot after the branch failure.
snapshot = graph.get_state(config)
saved = [finding["specialist"] for finding in snapshot.values.get("findings", [])]
# Separate completed branch output from work that must resume.
print(f"WORKFLOW FAILED: {error}")
print(f"Saved findings: {', '.join(saved) or 'none'}")
print(f"Waiting to re-run: {', '.join(snapshot.next)}")
What does this code do?
- The call to graph.get_state(config) reads the latest checkpoint for the current thread.
- The saved list collects the specialist names already stored under findings.
- The snapshot.next value identifies the graph work that remains pending.
- Scroll to the call to graph.stream_events() inside main().
- Wrap the stream plus its display call with this exception handler:
try:
# Persist each graph step before displaying its streamed events.
stream = graph.stream_events(
graph_input,
config=config,
durability="sync",
version="v3",
)
display_stream(stream)
except Exception as error:
# Report the checkpoint instead of hiding it behind a traceback.
display_failure(graph, config, error)
How does the failure reach the summary?
The try block keeps the existing synchronous checkpoint stream unchanged. The except block passes the same graph plus thread configuration to display_failure().
Before you run this, predict which branch will fail. Also predict which sibling findings will survive.
This run often needs 1 to 7 minutes while the specialist agents work, so a quiet terminal is normal.
- Click in the terminal panel below the Editor. Your prompt should start with (.venv).
No (.venv) in your prompt?
Your virtual environment isn't active. This happens in a new terminal. Run cd ~/langgraph-incident-triage-agents && source .venv/bin/activate, then continue. If your prompt doesn't show your project ID either, also run gcloud config set project YOUR_PROJECT_ID.
- Trigger the metrics fixture failure by running this command:
TRIAGE_FAIL=metrics python3 app.py start --thread crash-001 --alert INC-2041
You will see WORKFLOW FAILED after the metrics investigation raises Metrics backend timed out..
The summary lists the completed logs and deploys specialists under Saved findings. It lists investigate under Waiting to re-run.
Missing the saved findings?
Check that you used the fresh thread ID crash-001. An older checkpoint can place the thread at a different graph state.
Confirm that metric_window() still raises the fixture failure when TRIAGE_FAIL=metrics.
If Saved findings lists only one specialist, or investigate appears twice under Waiting to re-run, another specialist also hit a model error such as 504 or 429. Your resume reruns that specialist as well as metrics.
A NameError for display_failure means the function landed indented inside display_stream(). Delete the spaces in front of def display_failure so it starts at the far left, then run the crash command again with a new thread ID.
Help me diagnose why my failed parallel LangGraph run does not show saved sibling findings.
Resume only the unfinished branch
A resume command can serve two different states. An approval resume carries a decision while a failure resume supplies None so LangGraph retries the pending work.
- Return to parse_args() in app.py.
- Find the argument definition for --decision.
- Replace that definition with this optional argument:
resume_parser.add_argument(
"--decision",
choices=["approve", "reject"],
help="Leave out to retry a failed run.",
)
Why make the decision optional?
The existing approval path can still receive approve or reject. Leaving the flag out now represents a failed execution that needs to continue from its checkpoint.
- Scroll to the resume input logic inside main().
- Change the current resume condition to elif args.decision: so the existing Command path handles approval decisions.
- Add this fallback immediately after the decision branch:
else:
graph_input = None
What does the fallback change?
The None input tells the graph to continue the saved thread. The checkpoint determines that investigate for metrics is the remaining task.
- Clear the metrics failure hook from your shell by running this command:
unset TRIAGE_FAIL
The metrics tool can now read data/metrics.json when the pending branch runs again.
Before you resume, predict whether the logs or deploys specialist will print another investigating message.
- Resume the saved thread from a new Python process by running this command:
python3 app.py resume --thread crash-001
You will see only the metrics specialist investigate before synthesis continues. The logs and deploys investigation messages stay absent because their pending writes were already saved.
That recovery is the key operational win. Your graph can reuse completed model work after a process ends.
Why use checkpoint resume?
Checkpoint resume exposes durable recovery across separate processes. It also avoids repeating successful sibling model calls.
This lesson keeps RetryPolicy, error_handler=, and node timeout= out of the graph. The recovery behavior comes from pending writes plus durability="sync".
🙋♀️ Did every specialist run again?
Confirm that the resume command uses the same crash-001 thread ID as the failed run. A different ID has no saved pending work.
Confirm that DB_PATH still points to triage_checkpoints.db from the same repository directory.
Help me find why resuming crash-001 reruns completed specialists or cannot find pending work.
✔️ The metrics branch resumed by itself
Great work. Your checkpoint preserved the completed logs and deploys findings while the new process retried metrics.
ⓧ I'd like to double check the full code
Compare every recovery change in app.py with the reference snippets below.
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)}")
This function reads the persisted snapshot before reporting saved findings plus pending graph work.
resume_parser.add_argument(
"--decision",
choices=["approve", "reject"],
help="Leave out to retry a failed run.",
)
This argument keeps approval decisions available while allowing a decision-free recovery command.
else:
graph_input = None
This fallback resumes the checkpoint when the command carries no decision.
try:
stream = graph.stream_events(
graph_input,
config=config,
durability="sync",
version="v3",
)
display_stream(stream)
except Exception as error:
display_failure(graph, config, error)
This handler reports checkpoint state after an exception without changing the synchronous durability or event-stream version.
Your workflow now survives a crashed specialist without discarding completed investigations. Next, you will give each owning team an independent approval decision.
Gate Fixes by Team
Your LangGraph workflow now survives a failed specialist without repeating successful work. That durability makes parallel triage dependable across processes.
A single global approval still gives one person control over fixes owned by different services. This step gives each service team its own interrupt before publication.
In this step, get ready to:
- Assign every proposed action to the team that owns its service.
- Resume one team-specific approval without resolving the other pending approvals.
- Publish a runbook containing approved actions plus a complete decision audit.
Update the analysis contract
- Replace the existing ANALYSIS_SCHEMA in app.py with this service-aware schema:
# Return one diagnosis with service-specific remediation actions.
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"],
}
What does the new schema capture?
The analyst now returns the likely cause plus a list of service-specific actions. Each action carries the service name that the ownership lookup needs.
- Replace the existing IncidentState declaration with this shared state:
# Merge decisions returned by independent approval branches.
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
Why add an approvals reducer?
Each approval branch returns a one-item list. operator.add combines those lists without allowing one team decision to overwrite another.
- Check the schema and state replacements by running:
python3 -m py_compile app.py && echo "Team state passed."
You should see Team state passed. with no traceback.
Schema check failed?
Check that the old ANALYSIS_SCHEMA and IncidentState blocks were replaced completely. A leftover closing brace or field usually points to the incomplete edit.
Help me fix the team state syntax error.
Generate team-owned actions
- Add ActionTask immediately below SpecialistTask:
# Carry one proposed action into its owning team's branch.
class ActionTask(TypedDict):
incident_id: str
team: str
service: str
action: str
policy_reason: str
What travels with an action?
The branch receives the incident, owning team, service, proposed action, and policy reason. That payload keeps every interrupt independent.
- Replace the existing analyze_incident() function with this service-aware version:
def analyze_incident(state: IncidentState):
# Turn the merged findings into service-specific fixes.
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."],
}
What changes in the analyst prompt?
The analyst proposes one reversible action for each implicated service. The response stays capped at three services so the approval flow remains focused.
- Replace policy_check() with both consecutive parts below.
- Paste the second part directly beneath the first part without changing its indentation.
def policy_check(state: IncidentState):
# Match every proposed service to its owning team.
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})
# Record low-risk actions without opening an interrupt.
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."],
}
How does the policy handle each action?
The ownership fixture maps each service to a team. High-severity or restricted actions enter the approval flow, while low-risk actions receive a not required decision immediately.
- Check the completed policy function by running:
python3 -m py_compile app.py && echo "Policy code passed."
You should see Policy code passed. with no indentation error.
Policy check failed?
Confirm that the second code block remains inside policy_check(). Its first line needs eight leading spaces because it continues the for loop.
Help me fix the policy function.
Fan out team approvals
- Replace policy_route() with this fan-out function:
def policy_route(state: IncidentState):
# Open one approval branch for every gated action.
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
]
How does approval fan-out work?
Each Send creates an approval task with its own payload. If no action is gated, the route skips interrupts and moves directly to publication.
- Replace approval_gate() with this team-specific interrupt:
def approval_gate(task: ActionTask):
# Pause this branch for the team that owns the service.
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}]}
What does each gate return?
The interrupt asks only the owning team to decide. Its result returns as a one-item approvals list so the state reducer can merge every branch.
- Check both approval functions by running:
python3 -m py_compile app.py && echo "Approval branches passed."
You should see Approval branches passed. before updating publication.
Approval branch check failed?
Check that policy_route() returns a list of Send objects. Confirm that approval_gate() accepts an ActionTask instead of the full incident state.
Help me fix the approval branches.
Publish approved actions
- Replace publish_runbook() with the three consecutive parts below.
- Paste each part directly beneath the previous part without changing its indentation.
def publish_runbook(state: IncidentState):
# Separate publishable actions from rejected actions.
approvals = state.get("approvals", [])
approved = [
action
for action in approvals
if action["decision"] in ("approve", "not required")
]
decisions = [
f"Team {action['team']} decision for {action['service']}: {action['decision']}."
for action in approvals
]
if not approved:
return {
"status": "rejected_without_publish",
"audit_log": state["audit_log"]
+ decisions
+ ["Every action was rejected. Publishing was skipped."],
}
# Build the Markdown sections from evidence and approved actions.
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"- {finding['specialist']} ({finding['severity']}): {finding['summary']}"
for finding in state["findings"]
)
action_lines = "\n".join(
f"- {action['team']} / {action['service']}: {action['action']} "
f"({'approved by team' if action['decision'] == 'approve' else 'approval not required'})"
for action in approved
)
# Write the filtered actions and complete decision audit.
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,
}
What does the publisher preserve?
Approved and policy-exempt actions appear in the runbook. Every approval and rejection remains in the audit log, so filtering never erases the decision history.
- Check the complete publisher by running:
python3 -m py_compile app.py && echo "Publisher passed."
You should see Publisher passed. before wiring the new branches into the graph.
Publisher check failed?
Confirm that the second and third chunks remain indented inside publish_runbook(). Check the first traceback line for a missing parenthesis or quote.
Help me fix the publisher.
Wire the graph and team resume CLI
- Replace build_graph() with this deferred approval graph:
def build_graph(checkpointer: SqliteSaver):
# Register routed investigations and team-owned approvals.
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)
Why defer the publisher?
The deferred publisher waits until no selected approval branch remains pending. It then runs once with the merged decisions.
- Replace display_stream() with this summary function:
def display_stream(stream):
# Show pending approvals or the final publication state.
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')}")
- Add display_pending() immediately below display_stream():
def display_pending(interrupts):
# List every team request that still needs a decision.
print(f"WORKFLOW PAUSED: {len(interrupts)} team approvals pending")
for pending in interrupts:
request = pending.value
print(f"- {request['team']} ({request['service']}): {request['action']}")
What does the pause summary show?
The terminal lists every pending team, service, and action. That output supplies the exact team name required by the resume command.
- Check the graph and display functions by running:
python3 -m py_compile app.py && echo "Graph wiring passed."
You should see Graph wiring passed. before updating the CLI.
- Replace parse_args() with this team-aware parser:
def parse_args():
# Accept a team when resuming one pending decision.
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
Why keep the decision optional?
A team approval resume supplies both --team and --decision. A crash recovery still omits both flags so the checkpoint can retry unfinished work.
- Inside main(), replace the old resume branch with this team-specific branch:
elif args.decision:
# Resume only interrupts owned by the requested team.
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:
# Resume unfinished work without resolving an interrupt.
graph_input = None
How does the CLI select one interrupt?
The resume branch filters pending interrupts by team. It passes only the matching interrupt IDs to Command(resume=...), so every other team remains paused.
- Delete the old approval_route() function from its def line through its return line.
- Delete the old reject_runbook() function from its def line through its return block.
You should see Legacy gates removed. before cleaning up the unused import.
- Near the top of app.py, find this typing import:
from typing import Annotated, Literal, TypedDict
- Remove Literal so the import now looks like this:
from typing import Annotated, TypedDict
- Run the final syntax check before starting the workflow:
That is the code update complete. You should see Team approval workflow passed. with no traceback.
Final syntax check failed?
Open the first line named in the traceback. Compare that function with the visible chunk above before using the full-file tab as a final reference.
Help me fix the final team approval code.
✔️ Awesome, I've got everything!
Great. You're ready to start the approval workflow.
ⓧ I'd like to double check the full code
Compare your app.py with this final version. Pay close attention to the approval reducer, team-specific resume map, deferred publisher, and audit logic.
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
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():
args = parse_args()
config = {"configurable": {"thread_id": args.thread}}
with SqliteSaver.from_conn_string(DB_PATH) as checkpointer:
graph = build_graph(checkpointer)
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": [],
}
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
try:
stream = graph.stream_events(
graph_input,
config=config,
durability="sync",
version="v3",
)
display_stream(stream)
except Exception as error:
display_failure(graph, config, error)
if __name__ == "__main__":
main()
What changed in the workflow?
The approvals field uses Annotated[list[dict], operator.add] so parallel approval branches can merge their results. Each decision remains attached to its team plus its service.
The publisher uses defer=True so it waits for every selected approval branch. Rejected actions stay in the audit log without appearing under approved actions.
This start can take one to seven minutes while the specialists investigate plus the analyst creates service-specific actions.
Before you run this, consider which teams should own the fixes suggested by the planted incident evidence.
- Click in the terminal panel below the Editor
- Start the ownership-gated workflow for INC-2041 by running this command:
python3 app.py start --thread inc-001 --alert INC-2041
You should see every selected specialist finish before the workflow reports WORKFLOW PAUSED. The pending list should include separate requests for payments plus platform-data.
Do the pending teams look different?
Model-generated action wording can vary between runs. Confirm that the findings still reference the fixture evidence before checking which services the analysis implicated.
If the workflow fails before pausing, compare app.py with the double-check tab. Focus on the state reducers plus the edges leaving policy_check.
Help me debug my team approval branches.
Resume the payments approval
Every pending interrupt has its own ID. The resume command selects only the interrupt whose payload belongs to the requested team.
The CLI passes that selected ID through Command(resume={interrupt_id: decision}). Other interrupt IDs remain paused in the durable checkpoint.
- Approve the payments action by running this command:
python3 app.py resume --thread inc-001 --team payments --decision approve
You should see Recorded approve for payments. followed by WORKFLOW PAUSED again. The remaining pending list should contain platform-data.
What did this decision change?
The payments branch records an approved decision in the checkpoint. The platform-data branch keeps the workflow paused.
The deferred publisher still has pending upstream work. That prevents runbooks/inc-001.md from being created after only one decision.
- Expand runbooks in the Explorer. You'll see parallel-small-001.md from Step 3, but no inc-001.md yet.
Did the wrong approval resume?
Check that the team value exactly matches a pending team printed by the previous command. The CLI leaves the state unchanged when it cannot find a matching request.
Help me trace the selected interrupt ID.
Reject platform-data and inspect the runbook
The final pending decision releases the deferred publisher. The publisher includes approved or policy-exempt actions while keeping every team decision in the audit log.
Before you run this, consider which action should appear under approved actions after payments approves plus platform-data rejects.
- Reject the platform-data action by running this command:
python3 app.py resume --thread inc-001 --team platform-data --decision reject
The terminal reports WORKFLOW COMPLETE and names runbooks/inc-001.md as the published runbook. Open it to check the result.
- Return to the Cloud Shell Editor.
- Expand runbooks in the Explorer pane.
- Click inc-001.md to open the published runbook.
You should see the planted d-1042 connection-pool cause in the diagnosis. Approved actions should contain the payments fix without the rejected platform-data fix.
The audit log should contain both team decisions. This proves that publication filtered the action list without erasing the rejected decision.
Is the runbook missing or incorrect?
Confirm that the previous output reported a completed workflow. A remaining pending interrupt means the deferred publisher is still waiting.
If a rejected action appears under approved actions, compare the approved filter in publish_runbook with the double-check tab.
Help me debug the published runbook.
You now have separate approval authority for each service owner. Your published runbook preserves the incident evidence plus every decision while exposing only permitted actions.
Secret mission
Build a Live Incident Status Page
Give your team a live, read-only web page for every saved incident. Finish status_page.py so it shows findings, team decisions, who it's waiting on, and the runbook, straight from the checkpoint, without advancing anything.
Clean Up Your Resources
Clean Up Your Resources
Google Cloud Shell is free to use. Your files do not trigger model charges while the workflow is idle.
Decide whether to keep your resources available, pause your work, or delete the resources you no longer need. Future model requests can still incur charges.
Resources you used:
- The dedicated Google Cloud project with the Vertex AI API enabled, if you created a new project in Step 1.
- The ~/langgraph-incident-triage-agents folder in Cloud Shell. This contains the workflow code, fixture data, and .venv virtual environment.
- The triage_checkpoints.db SQLite database containing checkpoints, pending interrupts, findings, and approval decisions.
- The generated runbooks/ directory, if your workflow published a runbook.
Keep everything running
No action is needed. Choose this if you want to inspect saved incidents or continue experimenting with the workflow.
- Your Google Cloud project remains available for later LangGraph work.
- Your ~/langgraph-incident-triage-agents folder retains the application code and fixture data.
- Your triage_checkpoints.db database retains every saved thread and pending approval.
- Future Gemini requests can incur charges when you run the workflow again.
Pause - I'll come back to this later
Pause your work by leaving the cloud project and saved workflow state intact. No new model charges occur while you make no new requests.
- Stop running new incident-triage commands.
- End your current Cloud Shell session when you finish.
- Leave the Google Cloud project in place.
- Leave the ~/langgraph-incident-triage-agents folder in place.
- Return to the saved checkpoint database when you are ready to continue.
Delete - I don't want to use this again
Remove the Cloud Shell artifacts you created for this project. Your cloud cleanup depends on whether Step 1 created a dedicated project or reused an existing project.
I created a dedicated project
This path removes the local workflow files and the dedicated Google Cloud project.
Check Before Deleting
Deleting these resources is permanent. Your saved checkpoints and generated runbooks cannot be recovered after the local folder is removed.
- Exit the active virtual environment and remove the Cloud Shell repository by running these commands:
deactivate
cd ~
rm -rf ~/langgraph-incident-triage-agents
What Do These Commands Do?
- The deactivate command exits the active Python virtual environment.
- The cd ~ command moves the shell outside the repository before deletion.
- The final command deletes ~/langgraph-incident-triage-agents. This also removes .venv, triage_checkpoints.db, and runbooks/.
- Refresh Cloud Shell's file browser.
- Confirm that langgraph-incident-triage-agents is no longer listed.
Still See the Project Folder?
Check that the command targeted ~/langgraph-incident-triage-agents. A different path leaves the repository untouched.
Help me diagnose why Cloud Shell did not remove my incident-triage folder.
- Open the Manage resources page in the Google Cloud console.
- Select the dedicated project you created in Step 1.
- Click Delete in the toolbar.
- Enter the dedicated project ID when the confirmation dialog requests it.
- Click Shut down anyway to submit the deletion request.
- Confirm that the project enters its pending-deletion state.
Cannot Delete the Cloud Project?
Project deletion can be blocked by account permissions or an organization policy. Confirm that your account has permission to delete the selected project.
Help me diagnose why I cannot delete my dedicated Google Cloud project.
I reused an existing project
This path preserves the shared Google Cloud project. It removes only the local repository and its saved workflow artifacts.
Preserve the Shared Project
The reused project may still support your other work. Keep that cloud project in place while you remove this project's Cloud Shell folder.
- Exit the active virtual environment and remove the Cloud Shell repository by running these commands:
deactivate
cd ~
rm -rf ~/langgraph-incident-triage-agents
What Do These Commands Do?
- The deactivate command exits the active Python virtual environment.
- The cd ~ command moves the shell outside the repository before deletion.
- The final command deletes ~/langgraph-incident-triage-agents. This also removes .venv, triage_checkpoints.db, and runbooks/.
- Refresh Cloud Shell's file browser.
- Confirm that langgraph-incident-triage-agents is no longer listed.
- Confirm that the reused Google Cloud project remains available for your other resources.
Still See the Project Folder?
Check that the command targeted ~/langgraph-incident-triage-agents. A different path leaves the repository untouched.
Help me diagnose why Cloud Shell did not remove my incident-triage folder.
Nice Work!
Nice Work!
Excellent work! You have built a multi-agent LangGraph incident triage system. Your system now turns fixture alerts into durable runbooks backed by specialist evidence and team-owned decisions.
You've learned how to:
- Build role-specific specialists that inspect logs, deploys, and metrics before returning typed findings.
- Route alerts through parallel investigations with Send, reducers, deferred synthesis, and checkpoint recovery.
- Enforce team-owned approvals before publishing an audited runbook containing permitted actions.
- Secret Mission: Build a live, read-only incident status page that shows saved findings, team decisions, pending approvals, and the runbook in the browser.
Ready to quiz yourself?