LangChain and LangGraph
A LangGraph agent whose tools ask LumoAuth before they run, and a payment that waits in an interrupt until a person approves it.
What it shows
- The agent signs in to LumoAuth as itself, with its client ID and secret, when the program starts.
- Each tool asks LumoAuth first, with the Ask API. A refused tool returns the reason to the model, and does nothing.
- To pay an invoice, the agent needs a person. The tool stops the graph with
interrupt(), and LangGraph saves its state. - The program asks LumoAuth for a just-in-time permission. LumoAuth sends the request to the approvers of the agent and waits for the decision.
- The graph continues with
Command(resume=…). After an approval, the tool receives a token that allows exactly this payment.
Before you start
- An agent with a client ID and secret. The setup script below registers "Payables agent", which may read invoices and nothing else.
- A person who may approve the requests of the agent, other than its owner. The setup script gives the agent to Maya Chen, so that you can approve as administrator.
- Python 3.11 or later, and an OpenAI API key for the model.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
AGENT_CLIENT_ID | The client ID of the agent "Payables agent". The setup script prints it. |
AGENT_CLIENT_SECRET | Its client secret. The setup script prints it. |
OPENAI_API_KEY | The API key of your OpenAI account, for the model. |
OPENAI_MODEL | Optional. The model. Default: gpt-5-mini. |
The setup script registers "Payables agent" with the capability invoices:read, and gives it to the user Maya Chen, so that you can approve its requests. Its API key needs the scopes admin:agents:read, admin:agents:write and admin:users:write.
node frameworks/langgraph/setup.mjs
setup.mjs
// Registers the agent of this recipe, "Payables agent", which may read
// invoices, and gives it to another person, so that you can approve its
// requests. Run it again at any time.
//
// node frameworks/langgraph/setup.mjs
//
// The API key needs the scopes admin:agents:read, admin:agents:write and
// admin:users:write.
import { randomBytes } from 'node:crypto';
import { call, ensure, printEnv } from '../../_lib/admin.mjs';
const agent = await ensure('/admin/agents', (a) => a.name === 'Payables agent', {
name: 'Payables agent',
description: 'Reads invoices. It asks a person before it pays one, and it may not delete one.',
identityType: 'client_secret',
capabilities: ['invoices:read'],
});
// LumoAuth shows a secret once, in the answer that creates it. On a second
// run the script therefore asks for a new secret, and the old one stops.
const secret =
agent.clientSecret ??
(await call('POST', `/admin/agents/${agent.agentId}/rotate-credentials`)).data.clientSecret;
// The owner of an agent cannot decide its requests, and the agent belongs to
// the person who created it: you. Give it to another person, so that you can
// approve in the portal.
const owner = await ensure('/admin/users', (u) => u.email === 'maya.chen@example.com', {
email: 'maya.chen@example.com',
name: 'Maya Chen',
// The recipe never signs in as this user, so nobody needs the password.
password: `${randomBytes(18).toString('base64url')}#Aa1`,
emailVerified: true,
});
await call('PATCH', `/admin/agents/${agent.agentId}`, { ownerId: owner.id });
console.log(`Agent "${agent.name}" holds invoices:read. Its owner is ${owner.email}.`);
printEnv({ AGENT_CLIENT_ID: agent.agentId, AGENT_CLIENT_SECRET: secret });
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. The order of the tool calls and the last line depend on the model.
- Python
"""A LangGraph agent whose tools ask LumoAuth before they run.
The agent may read invoices. It may not delete one, and LumoAuth tells the
model why. To pay an invoice it needs a person: the graph stops with
interrupt(), LumoAuth asks a person, and the graph continues with the answer.
cd frameworks/langgraph/python
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
.venv/bin/python agent.py
"""
import json
import os
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition
from langgraph.types import Command, interrupt
from lumoauth import JITContext, LumoAuthAgent
# The agent signs in as itself, with the client credentials grant.
# Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
lumo = LumoAuthAgent()
lumo.authenticate()
jit = JITContext(lumo)
INVOICES = {"INV-7741": {"vendor": "Northwind Labs", "amount_usd": 4500}}
def refusal(tool_name: str, action: str, **context) -> str | None:
"""Asks LumoAuth whether the agent may do the action. Returns the reason of a refusal."""
answer = lumo.ask(action, context)
print(f"{tool_name}: {action} {'allowed' if answer['allowed'] else 'refused'}")
return None if answer["allowed"] else answer["reason"]
@tool
def list_invoices() -> str:
"""List the open invoices."""
if reason := refusal("list_invoices", "invoices:read"):
return f"Refused by LumoAuth: {reason}"
return json.dumps(INVOICES)
@tool
def delete_invoice(invoice_id: str) -> str:
"""Delete an invoice."""
if reason := refusal("delete_invoice", "invoices:delete", invoice=invoice_id):
# The model reads the reason and can tell the person.
return f"Refused by LumoAuth: {reason}"
return f"Deleted {invoice_id}"
@tool
def pay_invoice(invoice_id: str, amount_usd: int) -> str:
"""Pay an invoice."""
if refusal("pay_invoice", "invoices:pay", invoice=invoice_id, amount_usd=amount_usd):
# The agent may not pay by itself. The graph stops here and saves its
# state. It continues with the answer of a person (see below). Then
# LangGraph runs this tool again from the top, so it asks once more.
answer = interrupt({
"detail": {"type": "invoices", "actions": ["pay"], "identifier": invoice_id},
"justification": f"Pay {invoice_id}: {amount_usd} USD to {INVOICES[invoice_id]['vendor']}.",
})
if answer["status"] != "approved":
return f"Not paid: the request was {answer['status']}."
# The token allows exactly this payment. Send it to your payment API.
token = jit.get_token(answer["request_id"])
return f"Paid {invoice_id}: {amount_usd} USD"
tools = [list_invoices, delete_invoice, pay_invoice]
model = ChatOpenAI(model=os.environ.get("OPENAI_MODEL", "gpt-5-mini")).bind_tools(tools)
def plan(state: MessagesState):
return {"messages": [model.invoke(state["messages"])]}
builder = StateGraph(MessagesState)
builder.add_node("plan", plan)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "plan")
builder.add_conditional_edges("plan", tools_condition)
builder.add_edge("tools", "plan")
# A checkpointer keeps the state of a stopped graph until it continues.
graph = builder.compile(checkpointer=InMemorySaver())
if __name__ == "__main__":
# A task frames the permissions that a person grants during the run.
jit.create_task(name="Pay the invoices of Northwind Labs", task_type="finance")
config = {"configurable": {"thread_id": "payables-run-1"}}
run = {"messages": [("user", "List the open invoices, pay INV-7741, then delete it.")]}
try:
while True:
result = graph.invoke(run, config)
if not result.get("__interrupt__"):
break
# The graph stopped for a person. LumoAuth sends the request to the
# approvers of the agent and waits for the decision (5 minutes at most).
request = result["__interrupt__"][0].value
print(f"waiting for a person: {request['justification']}")
decision = jit.request_permission(request["detail"], justification=request["justification"])
print(f"decision: {decision['status']}")
run = Command(resume=decision)
print(f"model: {result['messages'][-1].content}")
finally:
# The end of the task revokes every token that a person granted in it.
jit.complete_task()
langgraph>=1.2
langchain-openai>=1.8
lumoauth>=1.7.0
cd frameworks/langgraph/python
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
.venv/bin/python agent.py
Compiles. Not run against an organization. The LumoAuth calls ran against an organization, with a scripted stand-in for the model, and the payment was approved in the portal. The run with a real model did not happen: it needs a model API key.
Check the result
list_invoices: invoices:read allowed
pay_invoice: invoices:pay refused
waiting for a person: Pay INV-7741: 4500 USD to Northwind Labs.
decision: approved
pay_invoice: invoices:pay refused
delete_invoice: invoices:delete refused
model: I paid INV-7741 (4,500 USD to Northwind Labs). I could not delete it: LumoAuth refused, because the agent lacks the capability invoices:delete.
- While the program waits, open AI Agents, Approvals in the portal. The request "Pay INV-7741: 4500 USD to Northwind Labs." is pending. Approve it, and the graph continues.
- Deny it instead: the tool returns "Not paid: the request was denied." and the model tells the person.
- The audit log shows
agent.capability_check_deniedforinvoices:delete, andjit.permission_requestedandjit.permission_approvedfor the payment.
Limits
- The program waits for the decision for 5 minutes at most. A request that nobody decides ends as
expired. - When the graph continues, LangGraph runs the stopped tool again from the top. The tool therefore asks LumoAuth a second time, and the line
pay_invoice: invoices:pay refusedappears twice. InMemorySaverkeeps the stopped graph only while the program runs. A service that waits longer stores the state in a database checkpointer.- To link the audit rows to the trace of the run, see Link agent actions to traces.