Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 54/ 160
03. AI Agents

OpenAI Agents SDK

Official SDK patterns for agents, tools, handoffs, and tracing in production apps.

IntermediateAgents SDK · Handoffs3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

It's a toolkit that makes it easy to create AI helpers that can use tools, pass work to each other and be monitored.

Think of it like…

A starter kit for building a team of assistants: it hands you ready-made desks (agents), phones (tools), a way to forward calls (handoffs), a security checkpoint (guardrails) and a CCTV system (tracing), but you still decide who works on what.

Where you’ve seen it

A travel-booking app defines three agents: Triage, Flights (tools search_flights, hold_booking) and Hotels (tools search_hotels). Triage has handoffs to both. An input guardrail rejects messages containing payment card numbers before any model sees them, and an output guardrail checks that quoted prices match tool results. Runner.run(triage, user_message, session=session, max_turns=12) handles the loop; traces in the dashboard show each model call, tool call and handoff, which helped the team find that the Hotels agent was calling search_hotels twice per request.

Words you’ll hear

Agent
A configured LLM with instructions, tools, optional handoffs, guardrails and an output type.
Runner
Executes the agent loop, including tool calls and handoffs, with a max-turns limit.
Handoff
Delegation of the conversation to another agent, exposed to the model as a tool.
Guardrail
A validation check on inputs or outputs that can halt the run (a tripwire).

Visual diagram

Loading interactive diagram

Theory & deep dive

The core primitives

An Agent is configured with name, instructions (a string or function), model, tools, handoffs, output_type (a Pydantic model or dataclass for structured final output) and guardrails. Function tools are ordinary Python functions turned into tools with a @function_tool decorator: the SDK builds the JSON schema from type hints and the docstring. Hosted tools (web search, file search, code interpreter) run on the provider's side, and an agent can be exposed to another as a tool with agent.as_tool(...), which keeps control with the caller, unlike a handoff.

Runner.run(agent, input) (and sync and streaming variants) executes the loop. If the model returns a handoff, the runner switches to the target agent; if it returns tool calls, the runner executes them and loops; if it returns a final output of the expected type, it stops. max_turns raises an error when exceeded. Sessions (for example SQLite-backed) store conversation items so later runs continue the thread without you managing message lists.

A small agent with a tool and handoff (sketch)

@function_tool def search_flights(origin: str, dest: str, date: str) -> list[dict]: ... then flights = Agent(name="Flights", instructions="Find options under the user's budget.", tools=[search_flights]) and triage = Agent(name="Triage", instructions="Route to the right specialist.", handoffs=[flights, hotels]); run with await Runner.run(triage, "Pune to Delhi Friday under ₹8,000").

Key takeaway: Agents plus function tools, handoffs and a runner that owns the loop.

Guardrails, tracing and when to choose it

Guardrails run validation in parallel with the agent: input guardrails check the user's message (off-topic, sensitive data, abuse), output guardrails check the final result, and tool guardrails can wrap function tools. A guardrail returns whether its tripwire was triggered; if so, the run raises an exception you handle (refuse, redact, escalate). They are best for cheap, targeted checks and are not a substitute for server-side authorisation of tool actions.

Tracing is built in: each run records spans for model generations, tool calls, handoffs and guardrails, viewable in the provider's dashboard or exported to other observability systems. Use traces to debug unexpected behaviour, build evaluation datasets from real runs and watch cost and latency. Choose an SDK like this when you want a thin layer over the agent loop with handoffs and tracing and are comfortable with its model-provider ecosystem (it can also work with other providers through compatible interfaces). Choose a graph framework when you need explicit branching, checkpointing and human-in-the-loop pauses, and a hand-written loop when requirements are simple. In all cases, bound the loop, validate tool arguments and apply least privilege.

An input guardrail idea

A small fast model (or a regex plus classifier) checks each incoming message for card numbers; if found, the tripwire fires, the run stops and the user sees "Please don't share card details here", before the main agent or any tool sees the data.

Key takeaway: Guardrails for cheap checks, traces for debugging, and pick the framework by control needs.

How it works, step by step

Step 1 of 4
Developer

1. Define agents and tools

Create agents with focused instructions and decorate Python functions as tools with typed arguments.

Agent(name, instructions, tools=[…])
Key numbers at this step
Few
tools per agent

When to use it & trade-offs

What it is

The OpenAI Agents SDK is a lightweight, open-source framework (Python and TypeScript) for building agents with a small set of primitives: an Agent (model, instructions, tools), tools (Python functions exposed via a decorator, hosted tools such as web search, or other agents), handoffs (delegating the conversation to another agent), guardrails (input and output checks that run alongside the agent), sessions (conversation memory) and built-in tracing. A Runner executes the agent loop: call the model, run tools, follow handoffs, repeat until a final output is produced or a turn limit is reached.

Why it matters: Most agent code is the same loop, tool plumbing, tracing and safety checks rewritten for each project. A small SDK removes that boilerplate while keeping behaviour transparent, and its primitives map directly onto the concepts in this track (tool calling, handoffs, guardrails, observability). Knowing what such an SDK provides, and what it deliberately leaves to you, helps you choose between SDKs, graph frameworks and hand-written loops.

When to reach for it

  • Support and booking assistants with specialist agents
  • Agents needing input and output validation
  • Teams wanting built-in traces for evaluation

When to avoid or be careful

  • Relying on guardrails instead of server-side authorisation
  • Running without max_turns
  • Many overlapping tools on one agent

Choosing an agent framework

Agents SDK (thin primitives)
Best for: Tool-using agents with handoffs and tracing

Strengths: Little boilerplate; built-in tracing and guardrails.

Watch out: Less explicit control over complex flows.

Graph framework (LangGraph)
Best for: Branching, cyclic, resumable workflows

Strengths: Explicit state and checkpoints.

Watch out: More concepts and setup.

Hand-written loop
Best for: Simple agents and maximum transparency

Strengths: Full control; no dependency.

Watch out: You build tracing, retries and guardrails yourself.

Interview signals & numbers to know

When this topic comes up

  • “What does the Agents SDK give us over our own loop?”
  • “Where do guardrails run?”
  • “Handoff vs agent as a tool”
  • Tracing agent runs
  • Sessions

Benchmarks & rules of thumb

5 -
core primitives: agents, tools, handoffs, guardrails, sessions/tracing
12 -
max_turns in the example
2 -
ways to delegate: handoff or agent-as-tool

Common mistakes & follow-ups

Common interview mistakes

  • Treating an output guardrail as the only protection for a refund tool.
  • Using handoffs when the caller should keep control (use agent-as-tool).
  • Not reading traces and missing duplicate tool calls that doubled cost.

Likely interviewer follow-ups

  • What's the difference between a handoff and using an agent as a tool?
  • What are guardrails good for, and what are they not?
  • When would you choose LangGraph instead?
Interview tip: Name the primitives in one breath (agent, tool, handoff, guardrail, session, trace) and say which ones you'd need for your use case.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply OpenAI Agents SDK with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
LangGraph
Next topic
State and Checkpoints