Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

Build your first agent in Python

Three tools, a hard turn limit, a clear stop condition and a log of every tool call it makes.

By Intermediate1 h hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

An agent is a model running in a loop: it reads the task, decides whether to call a tool, sees the result, and repeats until it can answer or something stops it. That is the whole idea. Frameworks differ in how much they add on top, but every agent you will meet has the same three parts: a model with instructions, a set of tools, and a loop with a stop condition.

In this tutorial you build a small but real agent with the OpenAI Agents SDK: a notes assistant that answers questions from a folder of Markdown files. It has three tools, a hard limit on how many turns it can take, and a log of every tool call so you can see what it did. These are the habits that matter more than the framework.

What you will build

$ python agent.py
-> search_notes
<- search_notes: ['deploy.md']
-> read_note
<- read_note: # Deploy checklist Run migrations before the release. Rollback with git revert.

Before a release, run the database migrations. To roll back, use git revert
on the release commit. Source: deploy.md.

The exact wording will differ on your machine; the shape will not. The model chose which tools to call and in what order. Your code only defined the tools and the limits.

1. Set up the project

Create a folder, a virtual environment and a few notes to search:

mkdir notes-agent && cd notes-agent
python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install openai-agents
export OPENAI_API_KEY="sk-..."   # Windows PowerShell: $env:OPENAI_API_KEY = "sk-..."

mkdir notes
printf "# Deploy checklist\nRun migrations before the release. Rollback with git revert.\n" > notes/deploy.md
printf "# Onboarding\nNew starters get laptop access on day one.\n" > notes/onboarding.md

If you use uv instead of pip, run uv init and uv add openai-agents in place of the venv and pip lines, then start later commands with uv run (for example uv run python agent.py). The uv commands cheat sheet lists the other equivalents.

Add a few notes of your own if you like. The agent works better with more material to choose from, and it is more convincing when it answers from your real notes.

2. Write the tools

A tool is an ordinary Python function with a decorator. The SDK reads the function signature and docstring to build the JSON schema the model sees, so the docstring is not decoration: it is the tool’s documentation for the model.

# agent.py
import asyncio
from pathlib import Path

from agents import Agent, MaxTurnsExceeded, RunContextWrapper, RunHooks, Runner, function_tool

NOTES_DIR = Path("notes").resolve()


def safe_path(name: str) -> Path:
    """Resolve a note name inside NOTES_DIR and refuse anything outside it."""
    path = (NOTES_DIR / name).resolve()
    if path.parent != NOTES_DIR or path.suffix != ".md":
        raise ValueError(f"{name!r} is not a note in {NOTES_DIR.name}/")
    return path


@function_tool
def list_notes() -> list[str]:
    """List the file names of all Markdown notes."""
    return sorted(p.name for p in NOTES_DIR.glob("*.md"))


@function_tool
def search_notes(query: str) -> list[str]:
    """Return the names of notes whose text contains the query (case-insensitive).

    Args:
        query: A word or short phrase to look for.
    """
    q = query.lower()
    return [p.name for p in sorted(NOTES_DIR.glob("*.md")) if q in p.read_text(encoding="utf-8").lower()]


@function_tool
def read_note(name: str) -> str:
    """Read one note in full.

    Args:
        name: The file name, for example "deploy.md".
    """
    return safe_path(name).read_text(encoding="utf-8")

Design choices worth copying:

  • Small, single-purpose tools. Search returns names, read returns content. The model can combine them, and each result stays small.
  • A guard in the tool, not in the prompt. safe_path refuses ../.env or any path outside the notes folder. Never rely on instructions to keep a model away from files; enforce it in code.
  • Errors the model can read. If read_note raises, the SDK’s default behaviour is to send the error message back to the model as the tool result, so it can correct itself (for example, by listing notes and picking a real name).

3. Define the agent

Add the agent definition below the tools:

agent = Agent(
    name="Notes assistant",
    instructions=(
        "You answer questions using only the user's notes. "
        "Search or list the notes, read the ones that look relevant, then answer in two or three sentences "
        "and name the notes you used. If the notes do not contain the answer, say so plainly."
    ),
    tools=[list_notes, search_notes, read_note],
)

The instructions say what success looks like (two or three sentences, cite the notes) and give the agent a permitted way to fail (“say so plainly”). Without that last sentence, an agent that finds nothing tends to answer from general knowledge and sound confident about it.

We have not set a model, so the SDK uses its default. To pin one, pass model="..." with a model name from OpenAI’s current list. Pinning is a good idea once you have an eval, so that behaviour does not change underneath you.

4. Log every step

An agent you cannot observe is an agent you cannot debug. The SDK sends traces to the OpenAI dashboard by default, which is useful, but you also want something in your terminal. Run hooks are called at each stage of the loop:

class LogSteps(RunHooks):
    async def on_tool_start(self, context: RunContextWrapper, agent: Agent, tool) -> None:
        print(f"-> {tool.name}")

    async def on_tool_end(self, context: RunContextWrapper, agent: Agent, tool, result: object) -> None:
        preview = str(result).replace("\n", " ")[:80]
        print(f"<- {tool.name}: {preview}")

In a real application you would send these to your logging or tracing system with the run ID, the tool arguments and the timing. The tracing workflow shows one way.

5. Run it with a stop condition

Finally, run the agent. max_turns is the stop condition: if the agent has not produced a final answer within that many model turns, the SDK raises MaxTurnsExceeded instead of looping forever.

async def main() -> None:
    question = "What do I need to do before a release, and how do I roll back?"
    try:
        result = await Runner.run(agent, question, max_turns=8, hooks=LogSteps())
    except MaxTurnsExceeded:
        print("Stopped: the agent used all 8 turns without finishing.")
        return
    print("\n" + result.final_output)


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

Run it:

python agent.py

Try a question your notes cannot answer (“What is our parental leave policy?”) and check that the agent says so instead of making something up. Then try one that needs two notes. Watching the tool log is the fastest way to build an intuition for how the model plans.

What the SDK did for you

It is worth knowing what happens inside Runner.run, because every framework does the same thing:

  1. Send the instructions, the tool schemas and the question to the model.
  2. If the model’s response contains tool calls, run the matching Python functions and append their results to the conversation.
  3. Send the whole conversation back to the model and repeat.
  4. Stop when the model returns a final answer with no tool calls, or when the turn limit is reached.

You could write this loop yourself in about forty lines with any provider’s SDK. Frameworks earn their place when you need what comes next: handoffs between agents, guardrails that run in parallel with the model, sessions that persist conversation history, approval steps for risky tools, and tracing.

Pitfalls

Tools with side effects and no approval. A delete_note tool is one bad plan away from deleting the wrong note. For anything destructive or expensive, require human approval. The Agents SDK supports this per tool with a needs_approval option on function_tool; otherwise, make the tool produce a proposal that a person confirms. Add human approval to agent actions builds that gate into this notes agent, with logging and tests.

Huge tool results. Returning a 10,000-line file fills the context and slows every later turn. Return the relevant part, or add an offset and limit to the tool.

Vague tool docstrings. If two tools sound alike, the model will pick the wrong one some of the time. Say what each returns and when to use it.

No eval. “It worked when I tried it” is not a test. Write five questions with known answers, including one the notes cannot answer, and run them after every change. See Write your first LLM eval.

Reaching for an agent too early. If the steps are always the same (search, then read the top hit, then answer), a fixed pipeline is cheaper, faster and easier to test. The article Workflows vs agents covers when the loop is worth it.

Next steps

Covers

Check your understanding

Build your first agent in Python quiz

The agent loop, tool design, path guards, stop conditions and logging with the OpenAI Agents SDK.

7 questions · pass mark 70%

Question 1 of 70 answered
  1. How does the OpenAI Agents SDK build the schema the model sees for a function tool?
  • Build your first agent in TypeScript

    Tools that search and read notes, a step limit, a clear stop condition and logged steps.

    TutorialIntermediate1 h

  • What is an AI agent? A plain explanation

    An AI agent is a language model that uses tools in a loop until a task is done. What that means in practice, what agents are good at and where they go wrong.

    Article

  • Workflows vs agents: start with the simplest thing that works

    Most LLM features should be a fixed workflow, not an agent. How to tell which one you need, when an agent earns its cost, and the useful patterns in between.

    Article

  • Agent loop

    The repeating cycle of model call, tool call, observation and next decision that drives an agent until the task is done or a limit is hit.

    Glossary

  • Tool calling

    A model emitting a structured request to call a defined function, which your code runs and whose result is then fed back to the model.

    Glossary

Back to top