# OpenAI Agents SDK Tutorial for Beginners

URL: https://aiseason.tech/openai-agents-sdk-tutorial

A hands-on OpenAI Agents SDK tutorial in Python: build an agent, give it tools, hand off between specialist agents, get structured output, add memory with sessions and block bad requests with guardrails. Every snippet was checked against openai-agents 0.24. Written for beginners in Pakistan and India who know basic Python.

| Fact | Value |
| --- | --- |
| Library | `openai-agents` (the OpenAI Agents SDK), open source, Python |
| Version tested | openai-agents 0.24 — imports, tools, handoffs, sessions and guardrails checked |
| You will build | An admissions assistant with tools, a triage agent with handoffs, memory and a guardrail |
| Time | About 60 minutes |
| Before this | [How to build an AI agent in Python](https://aiseason.tech/how-to-build-an-ai-agent) |

### What the OpenAI Agents SDK is

The **OpenAI Agents SDK** is a lightweight, open-source Python framework for building [AI agents](https://aiseason.tech/what-are-ai-agents). It gives you a handful of building blocks and runs the agent loop for you: call the model, run any tools it asks for, repeat until there is a final answer.

- **Agent** — an LLM with instructions, tools and settings.
- **Runner** — runs the agent loop (`Runner.run_sync`, or the async `Runner.run`).
- **Tools** — Python functions the agent can call, made with `@function_tool`.
- **Handoffs** — one agent passing the conversation to a specialist agent.
- **Guardrails** — checks that run on input or output and can stop a run.
- **Sessions** — conversation memory stored for you (for example in SQLite).
- **Tracing** — a record of every model call, tool call and handoff for debugging.

Despite the name it is not locked to OpenAI: it can call other providers through LiteLLM or any OpenAI-compatible endpoint. See how it compares with LangGraph, CrewAI and Google ADK in [AI agent frameworks compared](https://aiseason.tech/ai-agent-frameworks).

### Step 1: Install

```bash
mkdir agents-sdk-tutorial && cd agents-sdk-tutorial
python -m venv .venv
# Windows: .venv\Scripts\activate   ·   macOS/Linux: source .venv/bin/activate
pip install -U openai-agents python-dotenv
```

```bash
OPENAI_API_KEY=your-key-here
```

### Step 2: Your first agent

An agent needs a name and instructions. `Runner.run_sync` runs it and returns a result whose `final_output` is the answer.

```python
from dotenv import load_dotenv
from agents import Agent, Runner

load_dotenv()

tutor = Agent(
    name="AI Tutor",
    instructions="You explain AI concepts to beginners in simple English, with one short example.",
    model="gpt-4o-mini",
)

result = Runner.run_sync(tutor, "What is an AI agent, in two sentences?")
print(result.final_output)
```

### Step 3: Give it tools

Decorate a normal Python function with `@function_tool`. The SDK reads the type hints and docstring to build the tool schema the model sees, so write clear docstrings.

```python
from dotenv import load_dotenv
from agents import Agent, Runner, function_tool

load_dotenv()

# Demo data so the tutorial runs offline. Swap in a real database or API later.
FEES = {"ai agents bootcamp": "PKR 3,000", "python basics": "Free"}

@function_tool
def get_fee(course: str) -> str:
    """Look up the fee for a course by name."""
    return FEES.get(course.lower(), f"No fee found for {course}.")

@function_tool
def convert_pkr_to_inr(amount_pkr: float) -> str:
    """Convert an amount in Pakistani rupees to Indian rupees (approximate)."""
    return f"About ₹{amount_pkr * 0.346:,.0f}"

assistant = Agent(
    name="Admissions Assistant",
    instructions="Answer questions about courses. Use the tools for fees and currency; never guess a price.",
    model="gpt-4o-mini",
    tools=[get_fee, convert_pkr_to_inr],
)

result = Runner.run_sync(assistant, "How much is the AI agents bootcamp in Indian rupees?")
print(result.final_output)
```

> The model decides when to call a tool, and may call both tools in one run: first `get_fee`, then `convert_pkr_to_inr` with the result.

### Step 4: Handoffs between agents

A **handoff** lets a triage agent pass the conversation to a specialist. Each specialist gets a `handoff_description` so the triage agent knows when to pick it. `result.last_agent` tells you who answered.

```python
from dotenv import load_dotenv
from agents import Agent, Runner

load_dotenv()

billing = Agent(
    name="Billing Agent",
    handoff_description="Handles fees, payments and refunds.",
    instructions="You answer questions about fees, payment methods and refunds. Be brief.",
    model="gpt-4o-mini",
)

tech = Agent(
    name="Tech Support Agent",
    handoff_description="Helps with Python errors and course setup problems.",
    instructions="You help students fix setup problems and Python errors step by step.",
    model="gpt-4o-mini",
)

triage = Agent(
    name="Triage Agent",
    instructions="Decide which specialist should answer and hand off. Do not answer yourself.",
    model="gpt-4o-mini",
    handoffs=[billing, tech],
)

result = Runner.run_sync(triage, "pip install langgraph gives me a permission error on Windows")
print("Answered by:", result.last_agent.name)
print(result.final_output)
```

Handoffs are multi-agent design inside one program. When agents run as separate services owned by different teams, the open standard for connecting them is [A2A, the Agent2Agent protocol](https://aiseason.tech/a2a-protocol).

### Step 5: Structured output

Set `output_type` to a Pydantic model and `final_output` becomes a typed object instead of text — the basis of most [AI automation](https://aiseason.tech/ai-automation-course).

```python
from dotenv import load_dotenv
from pydantic import BaseModel
from agents import Agent, Runner

load_dotenv()

class Lead(BaseModel):
    name: str
    city: str
    course_interest: str
    wants_callback: bool

extractor = Agent(
    name="Lead Extractor",
    instructions="Extract the lead's details from the message.",
    model="gpt-4o-mini",
    output_type=Lead,
)

result = Runner.run_sync(extractor, "Salam, I'm Hina from Multan. Interested in the AI agents course, please call me.")
lead = result.final_output  # a Lead object, not a string
print(lead.name, lead.city, lead.wants_callback)
```

### Step 6: Memory with sessions

Pass a **session** and the SDK stores the conversation and sends the history for you. `SQLiteSession` saves it to a file; leave out the file name to keep it in memory.

```python
from dotenv import load_dotenv
from agents import Agent, Runner, SQLiteSession

load_dotenv()

tutor = Agent(name="AI Tutor", instructions="You are a friendly AI tutor.", model="gpt-4o-mini")
session = SQLiteSession("student-42", "conversations.db")  # one session per user

Runner.run_sync(tutor, "My name is Ali and I'm learning LangGraph.", session=session)
result = Runner.run_sync(tutor, "What's my name and what am I learning?", session=session)
print(result.final_output)
```

### Step 7: Guardrails

An **input guardrail** runs on the user's message. If it sets `tripwire_triggered=True`, the run stops with `InputGuardrailTripwireTriggered` before the agent acts. This one uses a keyword check; in production a guardrail often calls a small, cheap model to classify the request.

```python
from dotenv import load_dotenv
from agents import (
    Agent, GuardrailFunctionOutput, InputGuardrailTripwireTriggered,
    RunContextWrapper, Runner, input_guardrail,
)

load_dotenv()

BLOCKED = ["exam answers", "leak the paper", "solve my quiz"]

@input_guardrail
async def no_cheating(ctx: RunContextWrapper[None], agent: Agent, user_input) -> GuardrailFunctionOutput:
    text = str(user_input).lower()
    hit = any(phrase in text for phrase in BLOCKED)
    return GuardrailFunctionOutput(output_info={"blocked": hit}, tripwire_triggered=hit)

tutor = Agent(
    name="AI Tutor",
    instructions="Help students learn. Explain, don't just give answers.",
    model="gpt-4o-mini",
    input_guardrails=[no_cheating],
)

try:
    result = Runner.run_sync(tutor, "Can you leak the paper for tomorrow's test?")
    print(result.final_output)
except InputGuardrailTripwireTriggered:
    print("Sorry, I can't help with that — but I can help you prepare!")
```

> Guardrails are one layer, not the whole defence. Keep tool permissions narrow and require human approval for risky actions.

### Connecting MCP servers

Agents can also use tools from [MCP servers](https://aiseason.tech/mcp-course). The SDK includes MCP server classes — for example `MCPServerStdio` for a local server started as a subprocess, plus HTTP-based variants for remote servers. Pass connected servers to the agent with `mcp_servers=[...]` and their tools appear alongside your function tools.

### OpenAI Agents SDK vs LangGraph

|  | OpenAI Agents SDK | LangGraph |
| --- | --- | --- |
| Style | A few primitives; the SDK runs the loop | You define the graph: nodes, edges, state |
| Best for | Getting a tool-using or multi-agent app working fast | Complex, long-running workflows with branching and human approval |
| Multi-agent | Handoffs and agents-as-tools | Any graph shape, including supervisors and subgraphs |
| Memory | Sessions | Checkpointers (thread-based state) |
| Learn it | This page | [LangGraph tutorial](https://aiseason.tech/langgraph-tutorial) |

Learning both is the best preparation: the concepts — tools, memory, handoffs, guardrails — transfer directly.

### Learn agent SDKs live

AI Season's 6 weeks [AI agents bootcamp](https://aiseason.tech/) covers "MCP & Agent SDK" in week 5, after you have built agents by hand, with RAG and with LangGraph — then guardrails, deployment and a voice calling agent. 12 live sessions in Urdu (easy for Hindi speakers) with English code.

Cohort 02 starts 1st January 2027. Early-bird fee PKR 3,000 (about ₹1,040) until 30th November 2026, and the top three scorers get a full refund.

### Frequently asked questions

**What is the OpenAI Agents SDK?**
The OpenAI Agents SDK is an open-source Python framework for building AI agents from a few primitives: agents, tools, handoffs, guardrails and sessions. It runs the agent loop for you and includes built-in tracing.

**How do I install the OpenAI Agents SDK?**
Run pip install openai-agents in a Python virtual environment, set the OPENAI_API_KEY environment variable, and import Agent and Runner from the agents package.

**Can I use the OpenAI Agents SDK with other models?**
Yes. Besides OpenAI models, it can call other providers through LiteLLM or any OpenAI-compatible endpoint, though some features work best with OpenAI models.

**What is the difference between the OpenAI Agents SDK and LangGraph?**
The Agents SDK gives you a small set of primitives and runs the loop for you, which makes simple and multi-agent apps quick to build. LangGraph has you define the workflow as a graph, which gives more control for complex, long-running workflows with branching and human approval.

**Is there an Agents SDK course in Urdu or Hindi?**
AI Season teaches MCP and agent SDKs live as part of its AI agents bootcamp, taught in Urdu (easy for Hindi speakers) with English code. Cohort 02 starts 1st January 2027; early-bird fee PKR 3,000.

---

_Last updated: 2026-10-23. Canonical page: https://aiseason.tech/openai-agents-sdk-tutorial. Source: AI Season (https://aiseason.tech/)._
