Skip to main content

OpenAI Agents SDK

Tools that ask LumoAuth before they run, and a tool that stops the run until a person approves it.

RecipeDraftView source
This page is a draft. The code exists, and not all of it has been run for this page yet. The page says what was checked.
Packages
lumoauth
Works with
PythonOpenAI Agents SDK

What it shows​

  1. The agent signs in to LumoAuth as itself, with its client ID and secret, when the program starts.
  2. Each tool asks LumoAuth first, with the Ask API. A refused tool returns the reason to the model, and does nothing.
  3. The tool that extends a trial has a needs_approval function, which asks LumoAuth too. When LumoAuth refuses, the SDK stops the run with an interruption.
  4. 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.
  5. The program approves or rejects the interruption with the decision, and the run continues. After an approval, the tool receives a token that allows exactly this change.

Before you start​

  • An agent with a client ID and secret. The setup script below registers "Subscription desk agent", which may read subscriptions 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.10 or later, and an OpenAI API key for the model.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
AGENT_CLIENT_IDThe client ID of the agent "Subscription desk agent". The setup script prints it.
AGENT_CLIENT_SECRETIts client secret. The setup script prints it.
OPENAI_API_KEYThe API key of your OpenAI account, for the model.
OPENAI_MODELOptional. The model. Default: gpt-5-mini.

The setup script registers "Subscription desk agent" with the capability subscriptions: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/openai-agents/setup.mjs
setup.mjs
// Registers the agent of this recipe, "Subscription desk agent", which may read
// subscriptions, and gives it to another person, so that you can approve its
// requests. Run it again at any time.
//
// node frameworks/openai-agents/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 === 'Subscription desk agent', {
name: 'Subscription desk agent',
description: 'Reads subscriptions. A person approves each trial extension. It may not cancel one.',
identityType: 'client_secret',
capabilities: ['subscriptions: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 subscriptions: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.

frameworks/openai-agents/python/agent.py
"""An OpenAI Agents SDK agent whose tools ask LumoAuth before they run.

The agent may read subscriptions. It may not cancel one, and LumoAuth tells
the model why. To extend a trial it needs a person: LumoAuth decides that the
tool needs approval, the run stops with an interruption, a person decides in
LumoAuth, and the run continues with the decision.

cd frameworks/openai-agents/python
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
.venv/bin/python agent.py
"""
import asyncio
import json
import os

from agents import Agent, Runner, function_tool
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)

SUBSCRIPTIONS = {"SUB-5150": {"customer": "Northwind Labs", "plan": "Team", "trial_ends": "2026-12-01"}}
# The approved requests of this run, by subscription.
approved: dict[str, str] = {}


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"]


@function_tool
def get_subscription(subscription_id: str) -> str:
"""Read one subscription: the customer, the plan and the end of the trial."""
if reason := refusal("get_subscription", "subscriptions:read", subscription=subscription_id):
return f"Refused by LumoAuth: {reason}"
return json.dumps(SUBSCRIPTIONS.get(subscription_id, {}))


@function_tool
def cancel_subscription(subscription_id: str) -> str:
"""Cancel a subscription."""
if reason := refusal("cancel_subscription", "subscriptions:cancel", subscription=subscription_id):
# The model reads the reason and can tell the person.
return f"Refused by LumoAuth: {reason}"
return f"Cancelled {subscription_id}"


async def needs_person(_context, params: dict, _call_id: str) -> bool:
"""The SDK asks this before the tool runs. A refusal of LumoAuth means: a person decides."""
return refusal("extend_trial", "subscriptions:extend", **params) is not None


@function_tool(needs_approval=needs_person)
def extend_trial(subscription_id: str, days: int) -> str:
"""Extend the trial of a subscription by a number of days."""
# The tool runs only after a person approved it. The token allows exactly
# this change. Send it to your billing API.
token = jit.get_token(approved[subscription_id])
return f"Extended the trial of {subscription_id} by {days} days"


agent = Agent(
name="Subscription desk",
instructions="You help the support team with subscriptions. If LumoAuth refuses a tool, say why.",
model=os.environ.get("OPENAI_MODEL", "gpt-5-mini"),
tools=[get_subscription, cancel_subscription, extend_trial],
)


async def main() -> None:
# A task frames the permissions that a person grants during the run.
jit.create_task(name="Help Northwind Labs with SUB-5150", task_type="support")
try:
result = await Runner.run(agent, "Show SUB-5150, extend its trial by 14 days, then cancel it.")
while result.interruptions:
# The run stopped before a tool that needs a person. LumoAuth sends the
# request to the approvers of the agent and waits (5 minutes at most).
state = result.to_state()
for item in result.interruptions:
args = json.loads(item.arguments)
justification = f"Extend the trial of {args['subscription_id']} by {args['days']} days."
print(f"waiting for a person: {justification}")
decision = jit.request_permission(
{"type": "subscriptions", "actions": ["extend"], "identifier": args["subscription_id"]},
justification=justification,
)
print(f"decision: {decision['status']}")
if decision["status"] == "approved":
approved[args["subscription_id"]] = decision["request_id"]
state.approve(item)
else:
state.reject(item, rejection_message=f"A person did not approve: {decision['status']}.")
result = await Runner.run(agent, state)
print(f"model: {result.final_output}")
finally:
# The end of the task revokes every token that a person granted in it.
jit.complete_task()


if __name__ == "__main__":
asyncio.run(main())
frameworks/openai-agents/python/requirements.txt
openai-agents>=0.26
lumoauth>=1.7.0
cd frameworks/openai-agents/python
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
.venv/bin/python agent.py

Compiles. Not run against an organization. The run, its interruption and the LumoAuth calls ran against an organization with a scripted stand-in for the model, and the trial extension was approved in the portal. The run with a real model did not happen: it needs a model API key.

Check the result​

Output
get_subscription: subscriptions:read allowed
extend_trial: subscriptions:extend refused
waiting for a person: Extend the trial of SUB-5150 by 14 days.
decision: approved
cancel_subscription: subscriptions:cancel refused
model: I extended the trial of SUB-5150 by 14 days. I could not cancel it: LumoAuth refused, because the agent lacks the capability subscriptions:cancel.
  • While the program waits, open AI Agents, Approvals in the portal. The request "Extend the trial of SUB-5150 by 14 days." is pending. Approve it, and the run continues.
  • Deny it instead: the program rejects the interruption, and the model reads "A person did not approve: denied."
  • The audit log shows agent.capability_check_denied for subscriptions:cancel, and jit.permission_requested and jit.permission_approved for the trial.

Limits​

  • The program waits for the decision for 5 minutes at most. A request that nobody decides ends as expired.
  • The state of a stopped run stays in memory here. A service that waits longer stores it as JSON (RunState.to_json()) and continues later from the stored state.
  • The SDK sends traces of the run to OpenAI by default. To link the audit rows of LumoAuth to the trace of the run, see Link agent actions to traces.