{"slug": "building-your-first-ai-agent-in-python-with-the-openai-agents-sdk", "title": "Building Your First AI Agent in Python with the OpenAI Agents SDK", "summary": "A tutorial demonstrates building a Python research agent with the OpenAI Agents SDK, using the SDK's Runner to manage the tool-calling loop, a hosted WebSearchTool for live web lookups, and a custom @tool-decorated Python function for calculations. In the walkthrough's sample run, the agent reported Python 3.14.7 as the latest stable maintenance release and said Python 3.15's final release is scheduled for October 1, 2026. The setup requires installing the openai-agents package via uv or pip and setting an OpenAI API key.", "body_md": "# Building Your First AI Agent in Python with the OpenAI Agents SDK\n\nBuild your first AI agent in Python with the OpenAI Agents SDK, adding web search, Python tools, conversation memory, and tracing in a simple end-to-end workflow.\n\nBuilding an **AI agent in Python** is now much simpler than it used to be. With the **OpenAI Agents SDK**, you can create agents, connect tools, maintain conversation state, and run multi-step workflows without building your own tool-calling loop from scratch.\n\nIn this tutorial, we will build a practical research agent that can **search the web, call a custom Python function, remember previous messages, and decide when to use each capability**.\n\n## What Is an AI Agent?\n\nA standard large language model (LLM) application usually follows a simple flow:\n\n**Prompt — Model — Response**\n\nThe model receives a prompt, generates an answer, and stops.\n\nAn AI agent adds **tools and an execution loop**:\n\n**User — Agent — Tool if needed — Agent — Final Response**\n\nInstead of only generating text, the agent can decide whether it needs to take an action first, such as searching the web, calling a Python function, or retrieving information from memory.\n\nWith the OpenAI Agents SDK, the `Runner` manages this process automatically. It sends the request to the model, executes any requested tools, passes the results back to the agent, and continues until the agent produces a final answer.\n\nThis ability to **reason, use tools, and continue working across multiple steps** is what makes an agent different from a basic LLM application.\n\n## Set Up the Project\n\nBefore we build the agent, let's create a clean Python environment and install everything we need.\n\nCreate a Python project with `uv`:\n\n```\nmkdir first-ai-agent\ncd first-ai-agent\n\nuv init\nuv add openai-agents\n```\n\nOr install the package with `pip`:\n\n```\npip install openai-agents\n```\n\nSet your OpenAI API key:\n\n```\nexport OPENAI_API_KEY=\"your-api-key\"\n```\n\nOn Windows, `export` works in Git Bash. In Command Prompt or PowerShell, you can use:\n\n```\nsetx OPENAI_API_KEY \"your-api-key\"\n```\n\n## Build Your First Agent\n\nNow we can turn a few lines of Python into an agent that decides when it needs fresh information from the web.\n\nCreate `main.py`:\n\n``` python\nfrom agents import Agent, Runner, WebSearchTool\n\nagent = Agent(\n    name=\"Research Assistant\",\n    instructions=(\n        \"You are a concise research assistant. \"\n        \"Use web search when current information is required.\"\n    ),\n    tools=[WebSearchTool()],\n)\n\nresult = Runner.run_sync(\n    agent,\n    \"What are the latest developments in Python?\"\n)\n\nprint(result.final_output)\n```\n\n**Run it:**\n\n```\nuv run main.py\n```\n\n**Output:**\n\n```\nAs of **September 14, 2026**, the major Python developments are:\n- **Python 3.14 is the latest stable feature series**; the newest maintenance\n  release is **3.14.7**. It adds officially supported free-threaded builds,\n  deferred annotation evaluation, template string literals (`t\"\"`), ...\n- **Python 3.15 is nearing release**: the final release is scheduled for\n  **October 1, 2026**. ...\n\nFor new projects, **Python 3.14.7** is currently the safest default.\n```\n\n`WebSearchTool()` is a hosted OpenAI tool, so the model can decide when it needs current information instead of you manually calling a search API.\n\nFor example, our run correctly identified Python 3.14.7 as the current stable release.\n\n## Add Your Own Python Tool\n\nWeb search is useful, but agents become much more powerful when they can also interact with your own Python code.\n\nAdd a calculation tool:\n\n``` python\nfrom agents.decorators import tool\n\n@tool\ndef calculate_total(\n    price: float,\n    quantity: int\n) -> float:\n    \"\"\"Calculate the total cost of an order.\"\"\"\n\n    return price * quantity\n```\n\nThen give it to the agent:\n\n```\nagent = Agent(\n    name=\"Assistant\",\n    instructions=\"Help with research and calculations.\",\n    tools=[\n        WebSearchTool(),\n        calculate_total,\n    ],\n)\n```\n\n**Test it:**\n\n```\nresult = Runner.run_sync(\n    agent,\n    \"I need 14 GPUs costing $2.49 each per hour. \"\n    \"What will they cost per hour?\"\n)\n\nprint(result.final_output)\n```\n\n**Output:**\n\n```\n14 GPUs x $2.49/hour = **$34.86 per hour**.\n```\n\nThe SDK automatically uses the function name, arguments, type hints, and docstring to create a tool schema the model can understand. You do not need to manually define JSON schemas or write the tool-calling loop yourself.\n\n**Tip:** Write clear docstrings because they help the model understand what a tool does and when it should use it.\n\n## Adding Conversation Memory\n\nA useful agent should not forget everything the moment the next message arrives, so let's give it conversation memory.\n\nTo make the agent conversational, add a session:\n\n``` python\nfrom agents import SQLiteSession\n\nsession = SQLiteSession(\n    \"user_1\",\n    \"conversations.db\"\n)\n```\n\nThen pass it into each run:\n\n```\nwhile True:\n    message = input(\"You: \")\n\n    if message.lower() in {\"exit\", \"quit\"}:\n        break\n\n    result = Runner.run_sync(\n        agent,\n        message,\n        session=session,\n    )\n\n    print(\"Agent:\", result.final_output)\n```\n\n**Now try:**\n\nThe second request automatically receives the earlier conversation, so the agent understands what **\"the latest version\"** refers to.\n\nBecause we used a file-backed SQLite database, the history can also persist after restarting the program.\n\nFor larger applications, the SDK also provides session backends for systems such as **Redis, SQLAlchemy, and MongoDB**.\n\n## How the Complete Agent Works\n\nAt this point, all the pieces come together:\n\nThe **agent decides what action to take**, the **Runner executes the agent loop and any requested tools**, and the **session preserves conversation history** between requests.\n\nHere is the complete `main.py`:\n\n``` python\nimport os\nimport sys\n\nfrom agents import Agent, Runner, SQLiteSession, WebSearchTool\nfrom agents.decorators import tool\n\n@tool\ndef calculate_total(\n    price: float,\n    quantity: int\n) -> float:\n    \"\"\"Calculate the total cost of an order.\"\"\"\n\n    return price * quantity\n\ndef main() -> None:\n    if not os.environ.get(\"OPENAI_API_KEY\"):\n        sys.exit(\n            \"Error: set the OPENAI_API_KEY environment variable first.\"\n        )\n\n    agent = Agent(\n        name=\"Assistant\",\n        instructions=\"\"\"\n        Help the user with research and calculations.\n        Use the available tools when necessary.\n        \"\"\",\n        tools=[\n            WebSearchTool(),\n            calculate_total,\n        ],\n    )\n\n    session = SQLiteSession(\n        \"user_1\",\n        \"conversations.db\"\n    )\n\n    try:\n        while True:\n            try:\n                message = input(\"You: \")\n            except (EOFError, KeyboardInterrupt):\n                print()\n                break\n\n            command = message.strip().lower()\n\n            if command in {\"exit\", \"quit\"}:\n                break\n\n            if not command:\n                continue\n\n            try:\n                result = Runner.run_sync(\n                    agent,\n                    message,\n                    session=session,\n                )\n            except Exception as exc:\n                print(\n                    f\"Agent error \"\n                    f\"({type(exc).__name__}): {exc}\"\n                )\n                continue\n\n            print(\"Agent:\", result.final_output)\n\n    finally:\n        session.close()\n\nif __name__ == \"__main__\":\n    main()\n```\n\nThis gives us a small but complete conversational agent with **web search, a custom Python tool, persistent memory, basic error handling, and a continuous chat interface**.\n\nThe Agents SDK also enables **tracing by default**, which is especially useful once your workflows become more complex. Traces let you inspect the model calls, tool usage, handoffs, and other steps taken during an agent run.\n\nYou can inspect these traces in the **OpenAI dashboard** to understand how the agent reached its answer, which tools it selected, and where problems occurred. This makes tracing particularly useful for debugging tool-calling behavior and improving agent instructions.\n\n## Final Thoughts\n\nBuilding your first AI agent is less about creating a complex autonomous system and more about giving a model the ability to **take useful actions**.\n\nIn this guide, we started with a simple agent, added **web search**, connected a **custom Python tool**, introduced **persistent conversation memory**, and brought everything together in a complete application with tracing and error handling.\n\nThat foundation is enough to build surprisingly capable workflows. From here, you can gradually add **APIs, MCP servers, guardrails, handoffs, more specialized tools, and additional agents** as your application grows.\n\nThe pattern stays the same: **give the agent the right tools, let it decide when to use them, and let the Agents SDK handle the execution loop**.\n\nStart small, make one workflow useful, and expand only when you actually need more complexity.\n\n \n\n \n\n[**\\[Abid Ali Awan\\](https://abid.work)**](https://abid.work) ([@1abidaliawan](https://www.linkedin.com/in/1abidaliawan)) is a certified data scientist professional who loves building machine learning models. Currently, he is focusing on content creation and writing technical blogs on machine learning and data science technologies. Abid holds a Master's degree in technology management and a bachelor's degree in telecommunication engineering. His vision is to build an AI product using a graph neural network for students struggling with mental illness.", "url": "https://wpnews.pro/news/building-your-first-ai-agent-in-python-with-the-openai-agents-sdk", "canonical_source": "https://www.kdnuggets.com/building-your-first-ai-agent-in-python-with-the-openai-agents-sdk", "published_at": "2026-10-26 14:00:00+00:00", "updated_at": "2026-10-26 14:14:58.508514+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "large-language-models", "artificial-intelligence"], "entities": ["OpenAI", "OpenAI Agents SDK", "Python", "WebSearchTool", "Runner", "Python 3.14.7", "Python 3.15"], "also_reported_by": [], "alternates": {"html": "https://wpnews.pro/news/building-your-first-ai-agent-in-python-with-the-openai-agents-sdk", "markdown": "https://wpnews.pro/news/building-your-first-ai-agent-in-python-with-the-openai-agents-sdk.md", "text": "https://wpnews.pro/news/building-your-first-ai-agent-in-python-with-the-openai-agents-sdk.txt", "jsonld": "https://wpnews.pro/news/building-your-first-ai-agent-in-python-with-the-openai-agents-sdk.jsonld"}}