HITLGuides

OpenAI Agents SDK

Gate OpenAI Agents SDK function tools; approvals flow through the SDK's interruptions and resume from a saved RunState.

Code blocks on this page are excerpts of tested programs; each block's title names its file in examples/, where the complete program runs.

Install from the registry (to run the repo's own examples, clone it as in the README):

pip install "viewport-hitl[openai-agents]"    # openai-agents >= 0.26
npm install @viewportai/hitl @openai/agents zod    # @openai/agents >= 0.22

Verified against openai-agents 0.26.0 (Python) and @openai/agents 0.22.0 (TypeScript). The example uses a scripted Model, so it runs with no key.

Gate the tools

tools(gate, [...]) takes function tools (or core tools) and sets, per tool, needs_approval / needsApproval while an approval is pending, a tool input guardrail that refuses anything the gate did not grant (policy denials never reach a person or the tool), and an execution wrapper that consumes the approval right before the function runs.

examples/python/openai-agents/main.py (excerpt)
gate = hitl.Gate(
    {
        "approvers": {"finance": {"channel": "desk", "members": ["desk:dana"]}},
        "rules": {
            "refunds": {"allow": "issue_refund"},
            "large-refunds": {
                "ask": "issue_refund",
                "when": {"args": {"amount": {"gt": 50}}},
                "approver": "finance",
                "reason": "Refunds over $50 need finance",
            },
        },
    },
    channels=[desk],
    clock=FakeClock("2026-11-25T10:00:00Z"),
)


@function_tool
def issue_refund(order_id: str, amount: float) -> str:
    """Refund an order."""
    refunded.append({"order_id": order_id, "amount": amount})
    return f"Refunded ${amount:g} on {order_id}"


# Call ids come from the model's client, so approvals are scoped to the conversation (or user) they belong to.
SCOPE = "conversation-42"
agent = Agent(name="support", model=ScriptedModel(), tools=hitl.openai_agents.tools(gate, [issue_refund], scope=SCOPE))
examples/ts/openai-agents/main.ts (excerpt)
const gate = new Gate(
  {
    approvers: { finance: { channel: "desk", members: ["desk:dana"] } },
    rules: {
      refunds: { allow: "issue_refund" },
      "large-refunds": {
        ask: "issue_refund",
        when: { args: { amount: { gt: 50 } } },
        approver: "finance",
        reason: "Refunds over $50 need finance",
      },
    },
  },
  { channels: [desk], clock: new FakeClock("2026-11-25T10:00:00Z") },
);

const issueRefund = tool({
  name: "issue_refund",
  description: "Refund an order",
  parameters: z.object({ order_id: z.string(), amount: z.number() }),
  execute: async ({ order_id, amount }) => {
    refunded.push({ order_id, amount });
    return `Refunded $${amount} on ${order_id}`;
  },
});

// Call ids come from the model's client, so approvals are scoped to the conversation (or user) they belong to.
const SCOPE = "conversation-42";
const agent = new Agent({
  name: "support",
  model: new ScriptedModel(),
  tools: tools(gate, [issueRefund], { scope: SCOPE }),
});

In Python, pass plain functions to tools() for full binding: the gate validates their args with the SDK's own schema and approves exactly the args that will run, defaults, coercion and validators included. A prebuilt FunctionTool is parsed inside the SDK, so it must be strict with no defaults (hitl.adapter_unsupported otherwise), and a transforming validator inside one runs on the approved args after approval.

Run, suspend, resume

run(agent, input, gate=...) runs the agent and settles each interruption from the gate. In wait mode (the default) it waits for every decision and returns the final result. With wait=False it returns Suspended while an approval is pending: save state.to_string() / state.toString() anywhere.

examples/python/openai-agents/main.py (excerpt)
paused = await hitl.openai_agents.run(agent, "Refund A-1002, it arrived broken", gate=gate, wait=False, scope=SCOPE)
assert isinstance(paused, hitl.openai_agents.Suspended)
saved = paused.state.to_string()  # persist this with paused.approvals[0].id
examples/ts/openai-agents/main.ts (excerpt)
const paused = await run(agent, "Refund A-1002, it arrived broken", { gate, wait: false, scope: SCOPE });
assert.ok(isSuspended(paused));
const saved = paused.state.toString(); // persist this with paused.approvals[0].id

resume(agent, saved, gate=...) restores the state and decides every pending item again from the gate's store before the run continues. The SDK documents the serialized state as unauthenticated, so approvals written into it are ignored, and an item with no approval in the store is refused rather than asked: a forged state cannot create new approval requests. Resuming the same saved state twice does not run the tool twice.

examples/python/openai-agents/main.py (excerpt)
# Later, after finance approved (Slack, the CLI, or gate.respond), any process resumes the run.
await gate.respond(desk.requests[0].approval_id, hitl.approve(by="desk:dana"))

# Re-checks approvals in the store:
done = await hitl.openai_agents.resume(agent, saved, gate=gate, wait=False, scope=SCOPE)
assert not isinstance(done, hitl.openai_agents.Suspended)
print(f"agent: {done.final_output}")  # agent: Refund sent.
examples/ts/openai-agents/main.ts (excerpt)
// Later, after finance approved (Slack, the CLI, or gate.respond), any process resumes the run.
await gate.respond(requests[0]?.approval_id as string, approve({ by: "desk:dana" }));

const done = await resume(agent, saved, { gate, wait: false, scope: SCOPE }); // re-checks every approval in the store
if (isSuspended(done) || !("finalOutput" in done)) throw new Error("still waiting for approval");
console.log(`agent: ${done.finalOutput}`); // agent: Refund sent.

Hosted and local MCP

  • Hosted MCP tools (TypeScript): hostedMcpTool({ requireApproval: "always", onApproval: onApproval(gate, { scope }) }) waits for the decision and consumes it. Or leave onApproval unset and let the calls flow through interruptions like function tools.
  • Call ids come from the model's client, so approvals are keyed inside a scope you own: a conversation or user id (scope="conversation-42" / { scope: "conversation-42" }, or in TypeScript a function of the call). tools(...), run(...), resume(...) and onApproval(...) require a scope, or an action function that sets the actor or tenant from the run context; without either they raise hitl.scope_required.

On this page