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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

For a typical managed agent workflow, define an Agent and call Runner. The OpenAI Agents SDK handles the 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 can do, what limits apply, and how conversation state is stored.

Install the SDK and run a minimal agent

The official quickstart uses the Python package openai-agents and an OPENAI_API_KEY environment variable. Install the package, set your key, then create an agent with a name and instructions.

pip install openai-agents

Set OPENAI_API_KEY in your environment using your usual secret-management method. Do not hard-code the key in a script or commit it to source control.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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())

Runner.run is the asynchronous entry point in this example, and result.final_output contains the completed answer. For synchronous code, use Runner.run_sync; to consume events as the run proceeds, use Runner.run_streamed. OpenAI models use the Responses API beneath the SDK’s orchestration layer by default. See the official quickstart and SDK overview.

What Runner does—and when it stops

Runner manages the repeated work that a hand-written loop would otherwise perform. The official quickstart puts it plainly: “The runner handles executing individual agents, any handoffs, and any tool calls.”

  1. Runner sends the current input to the active agent.
  2. If the model requests a tool, Runner executes the tool and supplies its result in another model turn.
  3. If the model requests a handoff, Runner switches to the selected agent and continues the run.
  4. When the model returns final output of the requested type without another tool call, the run ends.

The SDK does not decide your application’s policy. You still configure instructions, tools, context, handoff targets, guardrails, output behavior, and operational limits. A run’s max_turns setting bounds how many turns it can take; exceeding the limit raises MaxTurnsExceeded. The running guide documents max_turns=None as disabling that limit, so use that only when an unbounded run is acceptable for your application. Details are in the running agents guide.

Add a Python function tool

A function decorated with the SDK’s tool decorator can be offered to an agent. The SDK generates a schema for the function and validates inputs with Pydantic-backed validation. Listing a function in tools makes it available to the model; Runner takes care of executing a requested tool call and continuing the run.

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)

This example’s function returns a fixed fact and has no external side effect. For tools that send messages, change records, spend money, or otherwise affect the outside world, make the function’s purpose and boundaries explicit. Add application-side checks or human review where the consequence warrants it; exposing a tool does not mean the model should have unrestricted authority. The quickstart demonstrates the decorator pattern, and the SDK overview describes guardrails and human-in-the-loop mechanisms.

Choose how specialist agents fit into the workflow

Use a handoff when a specialist should take over the conversation. Use an agent as a tool when a manager should retain responsibility for the final response and consult specialists as needed.

Pattern Who owns the final response? What happens to the specialist’s work? Routing to maintain
Handoff The specialist that receives control can produce the response. Control transfers to the selected agent for that part of the turn. Describe when a handoff is appropriate and maintain the handoff target’s description.
Agent as a tool The orchestrator remains responsible for the final response. The specialist returns a result to the manager, which can use it in its answer. Describe when the orchestrator should call each specialist and how to use its result.

A handoff is a transfer of control, not merely a function call with a different label. By default, the handoff guide represents a transfer to the model as a tool named transfer_to_<agent_name>; handoff() allows customization. The quickstart shows the short handoff pattern, while the handoff guide and orchestration guide cover routing and manager-style orchestration.

Pick one conversation-state strategy

A completed run does not by itself choose how your application should carry conversation history into the next turn. The quickstart describes three approaches; pick one according to who should own history.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Approach How you continue Who manages history?
Manual history Pass result.to_input_list() as input to a later run. Your application controls what history is retained and passed along.
SDK session Attach a session to the run. The SDK loads and saves conversation history for the session.
OpenAI-managed continuation Continue with a conversation_id or previous_response_id. OpenAI-managed conversation or response state provides continuity.

Do not combine SDK session persistence in the same run with conversation_id, previous_response_id, or auto_previous_response_id. The quickstart shows the continuation options; the sessions guide explains the session constraint.

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

Inspect a run with traces

Use tracing to inspect which agents ran, where tools were called, and how the workflow progressed. The quickstart directs developers to the Trace viewer in the OpenAI Dashboard; runner configuration also provides tracing controls and metadata, and the running guide recommends setting a workflow name.

Traces are useful for debugging and understanding execution, not proof that an answer is correct. Trace settings can control whether sensitive inputs and outputs are included, so review those settings against your data-handling requirements. See the quickstart and running agents guide.

When to use a custom loop or a sandbox workspace

Use direct Responses API calls when you need lower-level control

Call the Responses API directly when your application should own tool dispatch, state handling, and the orchestration loop—or when a short-lived task mainly needs a response. Use the Agents SDK when you want its runtime to manage turns, tools, guardrails, handoffs, or sessions. Both approaches can coexist in one application: use managed SDK paths for workflows that benefit from orchestration and direct API calls where lower-level control is the better fit. The SDK overview and quickstart describe these paths.

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

Use Sandbox Agents for work centered on files or repositories

If the task depends on real files, a repository, or isolated workspace state, consider Sandbox Agents rather than treating a basic conversational example as a workspace solution. Its quickstart retains the Agent/Runner pattern but adds a manifest, sandbox-native capabilities, and a SandboxRunConfig. The documented prerequisite is Python 3.10 or higher. See the Sandbox Agents quickstart.

OpenAI’s linked SDK documentation is rolling documentation accessed on October 7, 2026; it does not state a specific documentation version or release date. Check the linked guides for current package requirements and signatures when implementing later.

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.