{"slug": "how-to-turn-a-python-script-into-an-ai-agent", "title": "How to Turn a Python Script Into an AI Agent", "summary": "A tutorial published by OpenAI demonstrates how to convert an existing Python script into an AI agent using the OpenAI Agents SDK, wrapping a website-monitoring function with the @function_tool decorator so a model can decide when to call it. The guide walks through installing the openai-agents and requests packages, setting an OPENAI_API_KEY, and defining an Agent named \"Website Monitor\" that runs on the model \"gpt-5.6-luna\" with the check_website tool attached. The SDK automatically converts the function signature into the JSON schema the model requires, eliminating the need to hand-write a tool schema.", "body_md": "# How to Turn a Python Script Into an AI Agent\n\nLearn how to build a Python AI agent with the OpenAI Agents SDK, using tool calling and function tools to automate multi-step workflows.\n\nYou do not need to rewrite your Python applications to start using AI agents.\n\nIf your script already contains useful functions, you can expose those functions as **tools** and let an LLM decide when to call them, what arguments to provide, and how to use their outputs.\n\nIn this tutorial, we will take a simple website-monitoring script and turn it into an AI agent using the **[OpenAI Agents SDK](https://openai.github.io/openai-agents-python/)**.\n\n## Starting With a Normal Python Script\n\nBefore building an AI agent, let's start with a normal Python program.\n\nSuppose we want to check whether a website is responding and measure how long the request takes:\n\n``` php\nfrom time import perf_counter\n\nimport requests\n\ndef check_website(url: str) -> str:\n    start = perf_counter()\n\n    try:\n        response = requests.get(url, timeout=10)\n        latency = perf_counter() - start\n\n        return (\n            f\"{url}\\n\"\n            f\"Status: {response.status_code}\\n\"\n            f\"Response time: {latency:.2f}s\"\n        )\n\n    except requests.RequestException as error:\n        return f\"{url}\\nError: {error}\"\n\nprint(check_website(\"https://www.python.org\"))\n```\n\nOutput:\n\n```\nhttps://www.python.org\nStatus: 200\nResponse time: 0.99s\n```\n\nThe script does exactly what we programmed it to do: send an HTTP request, collect the status code, measure the response time, and return the result.\n\nThis is useful, but the workflow is completely fixed:\n\nIf we want to check five websites, compare their response times, or determine which one appears unhealthy, we need to write that logic ourselves.\n\nThis is where an AI agent changes the workflow.\n\nInstead of encoding every decision in Python, we can expose `check_website()` as a **tool** and give an AI model a goal. The model can then decide when to call the tool, which URL to check, how many times to use it, and what to do with the results.\n\n## Step 1: Installing the Agents SDK\n\nFirst, set up a Python project and install the packages we need to build and run the agent.\n\nCreate a new project:\n\n```\nmkdir website-agent\ncd website-agent\n\nuv init\nuv add openai-agents requests\n```\n\nOr use pip:\n\n```\npip install openai-agents requests\n```\n\nSet your OpenAI API key:\n\n```\nexport OPENAI_API_KEY=\"your-api-key\"\n```\n\nThe Agents SDK provides a lightweight runtime for agents, tools, handoffs, sessions, and tracing.\n\n## Step 2: Turning the Python Function Into a Tool\n\nNext, expose our existing Python function as a tool that the model can choose to call.\n\nWe can keep almost all of our existing function.\n\nThe main change is adding `@function_tool`:\n\n``` python\nfrom time import perf_counter\n\nimport requests\nfrom agents import function_tool\n\n@function_tool\ndef check_website(url: str) -> str:\n   \"\"\"Check a website's HTTP status and response time.\"\"\"\n\n   start = perf_counter()\n\n   try:\n       response = requests.get(url, timeout=10)\n       latency = perf_counter() - start\n\n       return (\n           f\"URL: {url}\\n\"\n           f\"Status: {response.status_code}\\n\"\n           f\"Response time: {latency:.2f}s\"\n       )\n\n   except requests.RequestException as error:\n       return f\"URL: {url}\\nError: {error}\"\n```\n\nThe OpenAI Agents SDK automatically converts the function signature into the JSON schema required by the model. It also uses the function name and docstring to describe the tool.\n\nWe do not need to manually create a tool schema.\n\n## Step 3: Creating the Agent\n\nNow, create an **Agent**, define what it should do, and give it access to our `check_website()` tool.\n\n``` python\nfrom agents import Agent, Runner\n\nagent = Agent(\n   name=\"Website Monitor\",\n   model=\"gpt-5.6-luna\",\n   instructions=\"\"\"\n   Monitor websites using the available tool.\n   Compare results and explain problems clearly.\n   \"\"\",\n   tools=[check_website],\n)\n```\n\nRun the agent:\n\n```\nresult = Runner.run_sync(\n   agent,\n   \"Check python.org, github.com, and openai.com. \"\n   \"Which one has the slowest response?\"\n)\n\nprint(result.final_output)\n```\n\nOutput:\n\n```\npython.org is the slowest, responding in **1.59 seconds**.\n\n- github.com: 0.83s\n- openai.com: 0.49s\n\nAll returned HTTP 200.\n```\n\nPreviously, we would have needed to write the loop and comparison logic ourselves:\n\n```\nfor url in urls:\n    check_website(url)\n```\n\nNow the model interprets the request, calls `check_website()` for the three websites, receives the results, compares them, and produces the answer.\n\n## How the Agent Loop Works\n\nBehind the scenes, the **Runner** manages the interaction between the model and the tools.\n\nConceptually, the loop looks like this:\n\nIf the model needs more information, it can call the tool again. The loop continues until it has enough information to produce a final response.\n\nThis is what makes the workflow **agentic**. Instead of following a fixed sequence written entirely in Python, the model decides which actions to take based on the request and the results it receives.\n\n## Other Python Scripts You Can Turn Into Agents\n\nThe same pattern works with almost any existing Python automation. You keep the Python functions that do the actual work and let the agent decide **which functions to call and how to combine the results**.\n\nFor example:\n\n- **CSV analyzer:** Functions filter rows, calculate metrics, and find trends. The agent answers natural-language questions about the data.\n- **Server monitor:** Functions check CPU, memory, disk, and processes. The agent investigates why a server looks unhealthy.\n- **Log analyzer:** Functions search logs, count errors, and extract events. The agent investigates incidents and summarizes what happened.\n- **API automation:** Functions fetch data, update records, or create reports. The agent decides which operations are needed and in what order.\n\nWith the OpenAI Agents SDK, you can expose existing Python functions with `@function_tool` and add them to the agent's `tools` list.\n\nThe Python code still performs the work; the agent adds **natural-language understanding, tool selection, and orchestration**.\n\n## Final Thoughts\n\nAgentic AI is becoming a practical way to automate workflows, with more companies using agents to handle multi-step tasks instead of relying on fixed scripts.\n\nAt the same time, cheaper models such as **GPT-5.6 Luna** make it much more affordable to run tool-using and even multi-agent systems at scale.\n\nIn this guide, we started with a normal Python function, turned it into a tool, connected it to an agent, and let the **Runner** manage the decision-making loop.\n\nThat is the core idea behind agentic applications: **give the model a goal and the right tools, then let it decide how to complete the task.**\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/how-to-turn-a-python-script-into-an-ai-agent", "canonical_source": "https://www.kdnuggets.com/how-to-turn-a-python-script-into-an-ai-agent", "published_at": "2026-09-21 14:00:07+00:00", "updated_at": "2026-09-21 14:33:05.597267+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "large-language-models", "ai-products"], "entities": ["OpenAI", "OpenAI Agents SDK", "Python", "gpt-5.6-luna", "Website Monitor", "check_website", "requests"], "alternates": {"html": "https://wpnews.pro/news/how-to-turn-a-python-script-into-an-ai-agent", "markdown": "https://wpnews.pro/news/how-to-turn-a-python-script-into-an-ai-agent.md", "text": "https://wpnews.pro/news/how-to-turn-a-python-script-into-an-ai-agent.txt", "jsonld": "https://wpnews.pro/news/how-to-turn-a-python-script-into-an-ai-agent.jsonld"}}