October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Stop Writing Your Own Agent Loop: A Hands-On Tutorial for OpenAI’s Agents SDK

Learn how OpenAI’s Agents SDK Runner manages model turns, tools, handoffs, and final output—and how to add tools, choose a state strategy, and inspect traces.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a standard managed agent workflow, define an Agent and call Runner. The OpenAI Agents SDK runtime handles repeated model turns, tool execution, handoffs, and final-output detection, so you do not have to write the dispatch-and-continue loop yourself. You still decide what the agent may do, how it should behave, and when its run must stop.

Install the SDK and run a minimal agent

The official quickstart’s Python setup uses the openai-agents package and an OPENAI_API_KEY environment variable. The example below follows its async pattern:

As an Amazon Associate I earn from qualifying purchases.

pip install openai-agents
import asyncio
from agents import Agent, Runner

agent = Agent(
    name="History Tutor",
    instructions="Answer history questions clearly and concisely.",
)

async def main():
    result = await Runner.run(agent, "When did the Roman Empire fall?")
    print(result.final_output)

if __name__ == "__main__":
    asyncio.run(main())

Set OPENAI_API_KEY in your environment before running the script. Runner.run returns a result whose final_output contains the completed response. You can also run synchronously with Runner.run_sync or consume events as they arrive with Runner.run_streamed. The SDK uses OpenAI models through the Responses API by default beneath its orchestration layer. OpenAI Agents SDK Quickstart · SDK overview

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What Runner does—and what still stops the run

Runner owns the repeated execution cycle for the supported SDK workflow. It sends the current input to the active agent, then responds to what the model returns:

  • If the model produces final output of the requested type and no tool calls, the run ends.
  • If the model requests a handoff, Runner switches to the selected agent and continues.
  • If the model requests tool calls, Runner executes them, appends their results, and calls the model again.

Use max_turns to bound a run. When the limit is exceeded, the SDK raises MaxTurnsExceeded. The running guide documents max_turns=None as disabling that limit; do not use an unbounded run without considering how your application will control it. Running agents

This removes repeated dispatch-and-continue plumbing, not application design. You remain responsible for the agent’s instructions, tools, context, handoff targets, guardrails, output behavior, and operational limits.

Add a Python function tool

A tool lets the model request a specific operation; the SDK handles executing the request and feeding the result back into the run. The quickstart demonstrates decorating a Python function and adding it to an agent’s tools list:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from agents import Agent, Runner
from agents.decorators import tool

@tool
def history_fun_fact() -> str:
    """Return a short history fact."""
    return "Sharks are older than trees."

agent = Agent(
    name="History Tutor",
    instructions="Answer history questions clearly. Use the fact tool when it helps.",
    tools=[history_fun_fact],
)

result = await Runner.run(agent, "Tell me something surprising about ancient life.")
print(result.final_output)

The SDK can generate a tool schema from the function and validate inputs with Pydantic-backed validation. Keep tools narrow, describe their purpose clearly, and make side effects explicit. Adding a function to tools makes it available to the model; it does not mean every requested action should be allowed automatically. For consequential actions, design appropriate review or approval controls and use the SDK’s guardrail and human-in-the-loop capabilities where they fit. Quickstart: tools · SDK capabilities

Choose how specialists participate

Multi-agent workflows have two distinct control patterns. Choose based on who should own the response to the user:

Pattern Who owns the final answer? What happens to the specialist? Routing to maintain
Handoff The specialist that receives control can produce the final response. Control transfers to that agent for its part of the conversation. Describe the handoff target and when the active agent should route to it.
Agents as tools The orchestrating agent remains responsible for the final response. A specialist returns a result to the orchestrator, which can incorporate it. Explain when the orchestrator should call each specialist and how to use its result.

A handoff is a control transfer, not merely a function call with a different label. By default, handoffs are represented to the model as tools named transfer_to_<agent_name>; the SDK’s handoff() supports customization. The quickstart’s short multi-agent example uses handoffs, while the orchestration guide covers the manager-style agents-as-tools approach. Handoffs · Multi-agent orchestration

Pick one strategy for conversation state

For a later turn, choose who should own the history. The quickstart documents three approaches:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Manual history: pass result.to_input_list() as input on the next run. Your application controls which history to retain and provide.
  • SDK-managed session: attach a session so the SDK loads and saves conversation history.
  • OpenAI-managed continuation: continue with conversation_id or previous_response_id.

Do not stack state mechanisms casually: the sessions guide says session persistence cannot be combined in the same run with conversation_id, previous_response_id, or auto_previous_response_id. Select one approach for each run based on whether your application, the SDK session, or OpenAI-managed continuation should own the conversation history. Quickstart: adding a conversation · Sessions

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Inspect execution with traces

Use traces to inspect which agents ran, where tools were called, and how the workflow progressed. The quickstart points to the Trace viewer in the OpenAI Dashboard; the running guide describes workflow names, tracing controls, and metadata. Traces help with inspection and debugging, but they do not prove that an answer or action was correct. Configure trace settings with care because they can control whether sensitive inputs and outputs are included. Quickstart: traces · Runner configuration

When to use the SDK, the Responses API, or a sandbox

Use the Agents SDK when you want its runtime to manage turns, tools, guardrails, handoffs, or sessions. Use the Responses API directly when you need to own orchestration and state handling, or when a short-lived workflow mainly returns a response. The two approaches can coexist in one application: managed paths can use the SDK while lower-level paths make direct Responses API calls. SDK overview · Quickstart

If the task is centered on real files, repositories, or isolated workspace state, use the Sandbox Agents workflow rather than extending this conversational example. Its quickstart retains the Agent/Runner pattern but adds a manifest, sandbox-native capabilities, and a SandboxRunConfig; it lists Python 3.10 or higher as a prerequisite. Sandbox Agents quickstart

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The linked OpenAI documentation is rolling documentation accessed on October 7, 2026; it does not state a specific release date or SDK version. Check the current guides before implementation if package requirements or method signatures may have changed.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.