← THE LIBRARY

Engineering / Agent framework / FIELD GUIDE

Build a first agent with the OpenAI Agents SDK

Install the OpenAI Agents SDK for Python, run a first agent, add a tool that waits for your approval and check the pause without spending a token.

Checked 22 Oct 2026

Pinned source guide with authored example files. Original project by OpenAI; guide and labeled adaptations by Agent Setup Kits.

Use case
First agent in Python
Architecture
Single agent, two tools
Trigger
Manual, python script
Runs
Your machine, your key
License
MIT SDK, hosted models
Human approval
needs_approval on writes

First step

bash
python offline_check.py n

A no-key check of the approval pause. Run it twice, with n then y, and compare the ticket state, as the file says.

Copy this first step, then read the setup and the human approval notes before you go further.

01 / PURPOSE

The autonomous job

Handle one ticket request: look up the ticket with a read tool, then propose closing it with a write tool that pauses for a person. The run resumes only after the person approves or rejects the call.

02 / SYSTEM

Architecture and handoffs

Single agent in your own Python process. Runner.run loops between the model and the agent's tools until there is a final output or max_turns is hit (the kit passes max_turns=6 on the first run and on each resume; the SDK default is 10). lookup_ticket runs freely; close_ticket is declared with needs_approval=True, so the run stops with interruptions. Your code calls state.approve or state.reject and runs again from the saved RunState. Tickets live in an in-memory dict, so nothing outside the process changes.

System for Build a first agent with the OpenAI Agents SDK Your Python process prompt model turns free call after approval spans unless disabled interruption HUMAN Developer AGENT Runner + agent SERVICE lookup_ticket SERVICE close_ticket SERVICE OpenAI API SERVICE Tracing ASK ASK
Built from this kit's roles, tools and boundaryHumanAgentServiceBoundary
01 / HUMAN

Developer

Writes the agent, sets the API key, answers the approval prompt and checks the ticket state

HandoffApproves or rejects each gated tool call

02 / AGENT

Ticket helper agent

Reads the request, looks up the ticket and proposes the close

HandoffReturns a final output after approval or rejection

03 / SERVICE

OpenAI Responses API

Serves each model turn

HandoffReturns tool calls or text to the runner

Model
The SDK default when Agent.model is unset (gpt-5.6-luna with reasoning effort none and low verbosity at v0.24.0, per the models docs), overridable with OPENAI_DEFAULT_MODEL or model=. offline_check.py uses a scripted stand-in model and calls no API.
Memory
None between runs. Within a run, RunState holds the conversation and pending approvals, and can be serialized to resume later; the kit keeps it in memory.

03 / CONNECTIONS

Tools and triggers

Tool access described by this edition
ToolPurposeAccess
lookup_ticketRead one ticket by idRuns without approval; reads the in-memory dict
close_ticketMark a ticket closedneeds_approval=True: every call pauses the run until a person decides

What starts the work

  • Manual A developer runs python tool_agent.py with OPENAI_API_KEY set, or python offline_check.py with no key.
Permissions in this edition
ControlDecision
Send prompts and tool results to the OpenAI APIYes
Call lookup_ticket freelyYes
Call close_ticket only after approvalYes
Send traces to OpenAI unless tracing is disabledYes
Enforced by the SDK: a tool with needs_approval=True pauses the run and appears in result.interruptions; it runs only after state.approve.Ask
Rejected calls do not run; the SDK returns its standard rejection text into the run (configurable with RunConfig.tool_error_formatter).Ask
Not a gate: lookup_ticket and any tool without needs_approval run as soon as the model calls them.Ask
Instructions such as 'close a ticket only when asked' are model guidance, not enforcement.Ask
Your Python process. Tools are plain functions with whatever access your process has; here they touch only an in-memory dict. close_ticket cannot run until your code approves it.Yes

04 / BOUNDARIES

Capabilities and safety

Credentials
OPENAI_API_KEY in the environment. Keep it out of code and Git. Tracing is on by default and can include tool inputs and outputs; set OPENAI_AGENTS_DISABLE_TRACING=1 or trace_include_sensitive_data=False if that matters.
Shutdown
Ctrl+C stops the run. A paused run holds nothing open; discard the state to cancel.

Capabilities

  • Send prompts and tool results to the OpenAI API
  • Call lookup_ticket freely
  • Call close_ticket only after approval
  • Send traces to OpenAI unless tracing is disabled

05 / SETUP

The files behind the workflow.

Original-project files retain their attribution and license; our installation notes, dependency profiles and custom wrappers are identified separately.

  1. Install the SDK

  2. Set your key

  3. Run a first agent

  4. Add a tool that needs approval

  5. Check the pause without a key

requirements.txtView file +

Pins openai-agents 0.24.0

Download requirements.txt ↓

openai-agents==0.24.0

Agent Setup Kits authored

hello_agent.pyView file +

First agent: one call, no tools

Download hello_agent.py ↓

"""First agent: one call to the model, no tools.

Needs OPENAI_API_KEY in your environment. Uses the SDK default model
unless you set OPENAI_DEFAULT_MODEL or pass model= to Agent.
"""
from agents import Agent, Runner

agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant. Answer in two sentences.",
)

result = Runner.run_sync(agent, "What does an agent loop do?", max_turns=3)
print(result.final_output)

Agent Setup Kits authored; follows examples/basic/hello_world.py at the pinned commit

tool_agent.pyView file +

Read tool plus an approval-gated write tool with an approve or reject loop

Download tool_agent.py ↓

"""Agent with one read tool and one write tool that waits for a person.

The tools work on an in-memory dict, so nothing outside this process
changes. Swap in your real system only after the approval step works.

Run:  python tool_agent.py "Close ticket 7, it is fixed."
Needs OPENAI_API_KEY. For a no-key check of the approval pause, run
offline_check.py instead.
"""
import asyncio
import sys

from agents import Agent, Runner
from agents.decorators import tool

TICKETS = {7: {"title": "Login button misaligned", "state": "open"}}


@tool
def lookup_ticket(ticket_id: int) -> str:
    """Read one ticket by id."""
    t = TICKETS.get(ticket_id)
    return f"{ticket_id}: {t['title']} ({t['state']})" if t else "not found"


@tool(needs_approval=True)
def close_ticket(ticket_id: int) -> str:
    """Close a ticket. A person must approve every call."""
    if ticket_id not in TICKETS:
        return "not found"
    TICKETS[ticket_id]["state"] = "closed"
    return f"ticket {ticket_id} closed"


def build_agent(model=None) -> Agent:
    kwargs = {"model": model} if model is not None else {}
    return Agent(
        name="Ticket helper",
        instructions="Look up tickets before acting. Close a ticket only when asked.",
        tools=[lookup_ticket, close_ticket],
        **kwargs,
    )


async def run(agent: Agent, prompt: str, decide=None) -> str:
    """Run until done, asking a person about every gated tool call."""
    result = await Runner.run(agent, prompt, max_turns=6)
    while result.interruptions:
        state = result.to_state()
        for item in result.interruptions:
            question = f"Allow {item.tool_name} with {item.arguments}? [y/N] "
            answer = decide(item) if decide else input(question)
            print(question + answer)
            if answer.strip().lower() == "y":
                state.approve(item)
            else:
                state.reject(item)
        result = await Runner.run(agent, state, max_turns=6)
    return str(result.final_output)


if __name__ == "__main__":
    prompt = sys.argv[1] if len(sys.argv) > 1 else "Close ticket 7, it is fixed."
    print(asyncio.run(run(build_agent(), prompt)))
    print("ticket state:", TICKETS[7]["state"])

Agent Setup Kits authored; uses the documented human-in-the-loop API

offline_check.pyView file +

No-key check of the approval pause with a scripted stand-in model

Download offline_check.py ↓

"""No-key check of the approval pause, using a scripted stand-in model.

The stand-in asks for close_ticket(7) on its first turn and then replies
with text. Nothing is sent to OpenAI: tracing is turned off and no API
key is read. Run it twice: answer n, then y, and compare the state.
"""
import asyncio
import sys

from openai.types.responses import (
    ResponseFunctionToolCall,
    ResponseOutputMessage,
    ResponseOutputText,
)

from agents import set_tracing_disabled
from agents.items import ModelResponse
from agents.models.interface import Model
from agents.usage import Usage

import tool_agent

set_tracing_disabled(True)


class ScriptedModel(Model):
    def __init__(self):
        self.turn = 0

    async def get_response(self, *args, **kwargs) -> ModelResponse:
        self.turn += 1
        if self.turn == 1:
            out = [ResponseFunctionToolCall(
                type="function_call", call_id="call_1", name="close_ticket",
                arguments='{"ticket_id": 7}', id="fc_1", status="completed")]
        else:
            out = [ResponseOutputMessage(
                type="message", id="msg_1", role="assistant", status="completed",
                content=[ResponseOutputText(type="output_text", text="Done.",
                                            annotations=[])])]
        return ModelResponse(output=out, usage=Usage(), response_id=None)

    def stream_response(self, *args, **kwargs):
        raise NotImplementedError


if __name__ == "__main__":
    answer = sys.argv[1] if len(sys.argv) > 1 else "n"
    agent = tool_agent.build_agent(model=ScriptedModel())
    out = asyncio.run(tool_agent.run(agent, "Close ticket 7.", decide=lambda _i: answer))
    print("final output:", out)
    print("ticket state:", tool_agent.TICKETS[7]["state"])

Agent Setup Kits authored

SOURCE.mdView file +

Original-project attribution, source hashes and adaptation notes

Download SOURCE.md ↓

# Source and attribution

The OpenAI Agents SDK for Python is built and maintained by OpenAI:
https://github.com/openai/openai-agents-python

Pinned release: v0.24.0 (PyPI openai-agents 0.24.0), commit
17d994bd3045dae71acda676a4ef4762ed8ecd94
https://github.com/openai/openai-agents-python/commit/17d994bd3045dae71acda676a4ef4762ed8ecd94

License: MIT (LICENSE-openai-agents-python.txt is a verbatim copy of LICENSE
at the pinned commit).

hello_agent.py follows the upstream examples/basic/hello_world.py.
tool_agent.py and offline_check.py were written by Agent Setup Kits using
the documented human-in-the-loop API (docs/human_in_the_loop.md at the
pinned commit). Checked 22 Oct 2026. Not affiliated with or endorsed by
OpenAI.

Agent Setup Kits authored documentation for Pinned source guide with authored example files; upstream code and licenses remain attributed separately

LICENSE-openai-agents-python.txtView file +

Upstream MIT license

Download LICENSE-openai-agents-python.txt ↓

MIT License

Copyright (c) 2025 OpenAI

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Verbatim copy of LICENSE at the pinned commit

Migrating from OpenAI Agent Builder

OpenAI is deprecating Agent Builder, its visual canvas for agent workflows. Per OpenAI's deprecations page, the deprecation was announced on June 3, 2026, and Agent Builder is scheduled to shut down on November 30, 2026. ChatKit remains available.

OpenAI's migration guide offers two paths. For code, open the workflow, choose Code, then Agents SDK, then TypeScript or Python, and copy the export into your application. The other path recreates the workflow as a ChatGPT workspace agent, which needs a Business, Enterprise or Edu workspace.

The guide is plain about the limits: the export "does not convert your workflow graph or guarantee that every behavior transfers unchanged." Review control flow, triggers, tools and permissions as you test.

If your workflow had an approval step, this kit is a useful second stop. Put needs_approval=True on every tool that changes something, run offline_check.py-style tests with a scripted model, and only then point it at real systems.

06 / ORIGINAL WORK

Sources, pins, and license

This guide draws on OpenAI Agents SDK by OpenAI, at the linked source revision. Agent Setup Kits is independent of the upstream project. Edition-specific changes are labeled in the file provenance.

OpenAI Agents SDK, by OpenAI

Pinned source guide with authored example files

Open source
Sources this edition relies on
SourceWhat it supports
Immutable source revision (tag v0.24.0) ↗Exact source snapshot for every API cited
README.md ↗pip install openai-agents, OPENAI_API_KEY, hello world
pyproject.toml ↗version 0.24.0, requires-python >=3.10, MIT
docs/human_in_the_loop.md ↗needs_approval, interruptions, ToolApprovalItem, RunState approve/reject and resume, MCP require_approval
docs/running_agents.md ↗Agent loop, max_turns (DEFAULT_MAX_TURNS = 10 in run_config.py) and MaxTurnsExceeded, error_handlers, conversation state options
docs/models/index.md ↗Default model gpt-5.6-luna when Agent.model is unset; OPENAI_DEFAULT_MODEL
docs/tracing.md ↗Tracing on by default, OPENAI_AGENTS_DISABLE_TRACING=1, unavailable under Zero Data Retention, sensitive span data
docs/guardrails.md ↗Input, output and tool guardrails
examples/basic/hello_world.py ↗Shape of hello_agent.py
LICENSE ↗MIT license
Migrate from Agent Builder (official docs) ↗Migration paths from Agent Builder, export to Agents SDK code, and the limits of the export
OpenAI deprecations page ↗Agent Builder deprecation announced June 3, 2026; scheduled shutdown Nov 30, 2026; ChatKit remains available
Source versions and guide targets
ComponentPinSource
openai-agents (PyPI)0.24.0Original source ↗
Python>=3.10Original source ↗

MIT

The SDK is MIT. Models are OpenAI's paid hosted service under OpenAI's terms. LICENSE-openai-agents-python.txt is a verbatim copy; all other kit files are authored by Agent Setup Kits.

Read the original license ↗

Related guides

Part of: Which setup should I use to add human approval to an agent?

Your privacy choices

Choose optional tools. Rejecting them keeps the setup library available. Advertising consent stays off.

Choices stay in this browser for 90 days. You can change them using Privacy settings. Privacy and cookie details