• Home
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy
Monday, September 21, 2026
newsaiworld
  • Home
  • Artificial Intelligence
  • ChatGPT
  • Data Science
  • Machine Learning
  • Crypto Coins
  • Contact Us
No Result
View All Result
  • Home
  • Artificial Intelligence
  • ChatGPT
  • Data Science
  • Machine Learning
  • Crypto Coins
  • Contact Us
No Result
View All Result
Morning News
No Result
View All Result
Home Data Science

How one can Flip a Python Script Into an AI Agent

Admin by Admin
September 21, 2026
in Data Science
0
Awan turn python script ai agent 4.png
0
SHARES
0
VIEWS
Share on FacebookShare on Twitter


How to Turn a Python Script Into an AI Agent

You don’t want to rewrite your Python purposes to start out utilizing AI brokers.

In case your script already incorporates helpful features, you possibly can expose these features as instruments and let an LLM resolve when to name them, what arguments to supply, and the best way to use their outputs.

On this tutorial, we’ll take a easy website-monitoring script and switch it into an AI agent utilizing the OpenAI Brokers SDK.

Beginning With a Regular Python Script

Earlier than constructing an AI agent, let’s begin with a traditional Python program.

Suppose we need to verify whether or not an internet site is responding and measure how lengthy the request takes:

from time import perf_counter

import requests


def check_website(url: str) -> str:
    begin = perf_counter()

    strive:
        response = requests.get(url, timeout=10)
        latency = perf_counter() - begin

        return (
            f"{url}n"
            f"Standing: {response.status_code}n"
            f"Response time: {latency:.2f}s"
        )

    besides requests.RequestException as error:
        return f"{url}nError: {error}"


print(check_website("https://www.python.org"))

Output:

https://www.python.org
Standing: 200
Response time: 0.99s

The script does precisely what we programmed it to do: ship an HTTP request, gather the standing code, measure the response time, and return the outcome.

That is helpful, however the workflow is totally fastened:

How to Turn a Python Script Into an AI Agent

If we need to verify 5 web sites, examine their response instances, or decide which one seems unhealthy, we have to write that logic ourselves.

That is the place an AI agent adjustments the workflow.

As a substitute of encoding each resolution in Python, we will expose check_website() as a device and provides an AI mannequin a purpose. The mannequin can then resolve when to name the device, which URL to verify, what number of instances to make use of it, and what to do with the outcomes.

How to Turn a Python Script Into an AI Agent

Step 1: Putting in the Brokers SDK

First, arrange a Python venture and set up the packages we have to construct and run the agent.

Create a brand new venture:

mkdir website-agent
cd website-agent

uv init
uv add openai-agents requests

Or use pip:

pip set up openai-agents requests

Set your OpenAI API key:

export OPENAI_API_KEY="your-api-key"

The Brokers SDK supplies a light-weight runtime for brokers, instruments, handoffs, periods, and tracing.

Step 2: Turning the Python Operate Right into a Instrument

Subsequent, expose our current Python perform as a device that the mannequin can select to name.

We will maintain nearly all of our current perform.

The primary change is including @function_tool:

from time import perf_counter

import requests
from brokers import function_tool


@function_tool
def check_website(url: str) -> str:
   """Examine an internet site's HTTP standing and response time."""

   begin = perf_counter()

   strive:
       response = requests.get(url, timeout=10)
       latency = perf_counter() - begin

       return (
           f"URL: {url}n"
           f"Standing: {response.status_code}n"
           f"Response time: {latency:.2f}s"
       )

   besides requests.RequestException as error:
       return f"URL: {url}nError: {error}"

The OpenAI Brokers SDK mechanically converts the perform signature into the JSON schema required by the mannequin. It additionally makes use of the perform identify and docstring to explain the device.

We don’t must manually create a device schema.

Step 3: Creating the Agent

Now, create an Agent, outline what it ought to do, and provides it entry to our check_website() device.

from brokers import Agent, Runner

agent = Agent(
   identify="Web site Monitor",
   mannequin="gpt-5.6-luna",
   directions="""
   Monitor web sites utilizing the obtainable device.
   Examine outcomes and clarify issues clearly.
   """,
   instruments=[check_website],
)

Run the agent:

outcome = Runner.run_sync(
   agent,
   "Examine python.org, github.com, and openai.com. "
   "Which one has the slowest response?"
)

print(outcome.final_output)

Output:

python.org is the slowest, responding in **1.59 seconds**.

- github.com: 0.83s
- openai.com: 0.49s

All returned HTTP 200.

Beforehand, we might have wanted to jot down the loop and comparability logic ourselves:

for url in urls:
    check_website(url)

Now the mannequin interprets the request, calls check_website() for the three web sites, receives the outcomes, compares them, and produces the reply.

How the Agent Loop Works

Behind the scenes, the Runner manages the interplay between the mannequin and the instruments.

Conceptually, the loop appears like this:

How to Turn a Python Script Into an AI Agent

If the mannequin wants extra info, it may name the device once more. The loop continues till it has sufficient info to provide a remaining response.

That is what makes the workflow agentic. As a substitute of following a hard and fast sequence written completely in Python, the mannequin decides which actions to take based mostly on the request and the outcomes it receives.

Different Python Scripts You Can Flip Into Brokers

The identical sample works with nearly any current Python automation. You retain the Python features that do the precise work and let the agent resolve which features to name and the best way to mix the outcomes.

For instance:

  • CSV analyzer: Capabilities filter rows, calculate metrics, and discover traits. The agent solutions natural-language questions in regards to the information.
  • Server monitor: Capabilities verify CPU, reminiscence, disk, and processes. The agent investigates why a server appears unhealthy.
  • Log analyzer: Capabilities search logs, depend errors, and extract occasions. The agent investigates incidents and summarizes what occurred.
  • API automation: Capabilities fetch information, replace information, or create stories. The agent decides which operations are wanted and in what order.

With the OpenAI Brokers SDK, you possibly can expose current Python features with @function_tool and add them to the agent’s instruments checklist.

The Python code nonetheless performs the work; the agent provides natural-language understanding, device choice, and orchestration.

Ultimate Ideas

Agentic AI is changing into a sensible technique to automate workflows, with extra firms utilizing brokers to deal with multi-step duties as a substitute of counting on fastened scripts.

On the similar time, cheaper fashions corresponding to GPT-5.6 Luna make it rather more inexpensive to run tool-using and even multi-agent methods at scale.

On this information, we began with a traditional Python perform, turned it right into a device, linked it to an agent, and let the Runner handle the decision-making loop.

That’s the core thought behind agentic purposes: give the mannequin a purpose and the best instruments, then let it resolve the best way to full the duty.

 
 

Abid Ali Awan (@1abidaliawan) is an authorized information scientist skilled who loves constructing machine studying fashions. Presently, he’s specializing in content material creation and writing technical blogs on machine studying and information science applied sciences. Abid holds a Grasp’s diploma in know-how administration and a bachelor’s diploma in telecommunication engineering. His imaginative and prescient is to construct an AI product utilizing a graph neural community for college students battling psychological sickness.

READ ALSO

Europe’s Proptech Winners Are Competing on Knowledge, Not Software program

5 Immediate Optimization Methods That Really Enhance LLM Output


How to Turn a Python Script Into an AI Agent

You don’t want to rewrite your Python purposes to start out utilizing AI brokers.

In case your script already incorporates helpful features, you possibly can expose these features as instruments and let an LLM resolve when to name them, what arguments to supply, and the best way to use their outputs.

On this tutorial, we’ll take a easy website-monitoring script and switch it into an AI agent utilizing the OpenAI Brokers SDK.

Beginning With a Regular Python Script

Earlier than constructing an AI agent, let’s begin with a traditional Python program.

Suppose we need to verify whether or not an internet site is responding and measure how lengthy the request takes:

from time import perf_counter

import requests


def check_website(url: str) -> str:
    begin = perf_counter()

    strive:
        response = requests.get(url, timeout=10)
        latency = perf_counter() - begin

        return (
            f"{url}n"
            f"Standing: {response.status_code}n"
            f"Response time: {latency:.2f}s"
        )

    besides requests.RequestException as error:
        return f"{url}nError: {error}"


print(check_website("https://www.python.org"))

Output:

https://www.python.org
Standing: 200
Response time: 0.99s

The script does precisely what we programmed it to do: ship an HTTP request, gather the standing code, measure the response time, and return the outcome.

That is helpful, however the workflow is totally fastened:

How to Turn a Python Script Into an AI Agent

If we need to verify 5 web sites, examine their response instances, or decide which one seems unhealthy, we have to write that logic ourselves.

That is the place an AI agent adjustments the workflow.

As a substitute of encoding each resolution in Python, we will expose check_website() as a device and provides an AI mannequin a purpose. The mannequin can then resolve when to name the device, which URL to verify, what number of instances to make use of it, and what to do with the outcomes.

How to Turn a Python Script Into an AI Agent

Step 1: Putting in the Brokers SDK

First, arrange a Python venture and set up the packages we have to construct and run the agent.

Create a brand new venture:

mkdir website-agent
cd website-agent

uv init
uv add openai-agents requests

Or use pip:

pip set up openai-agents requests

Set your OpenAI API key:

export OPENAI_API_KEY="your-api-key"

The Brokers SDK supplies a light-weight runtime for brokers, instruments, handoffs, periods, and tracing.

Step 2: Turning the Python Operate Right into a Instrument

Subsequent, expose our current Python perform as a device that the mannequin can select to name.

We will maintain nearly all of our current perform.

The primary change is including @function_tool:

from time import perf_counter

import requests
from brokers import function_tool


@function_tool
def check_website(url: str) -> str:
   """Examine an internet site's HTTP standing and response time."""

   begin = perf_counter()

   strive:
       response = requests.get(url, timeout=10)
       latency = perf_counter() - begin

       return (
           f"URL: {url}n"
           f"Standing: {response.status_code}n"
           f"Response time: {latency:.2f}s"
       )

   besides requests.RequestException as error:
       return f"URL: {url}nError: {error}"

The OpenAI Brokers SDK mechanically converts the perform signature into the JSON schema required by the mannequin. It additionally makes use of the perform identify and docstring to explain the device.

We don’t must manually create a device schema.

Step 3: Creating the Agent

Now, create an Agent, outline what it ought to do, and provides it entry to our check_website() device.

from brokers import Agent, Runner

agent = Agent(
   identify="Web site Monitor",
   mannequin="gpt-5.6-luna",
   directions="""
   Monitor web sites utilizing the obtainable device.
   Examine outcomes and clarify issues clearly.
   """,
   instruments=[check_website],
)

Run the agent:

outcome = Runner.run_sync(
   agent,
   "Examine python.org, github.com, and openai.com. "
   "Which one has the slowest response?"
)

print(outcome.final_output)

Output:

python.org is the slowest, responding in **1.59 seconds**.

- github.com: 0.83s
- openai.com: 0.49s

All returned HTTP 200.

Beforehand, we might have wanted to jot down the loop and comparability logic ourselves:

for url in urls:
    check_website(url)

Now the mannequin interprets the request, calls check_website() for the three web sites, receives the outcomes, compares them, and produces the reply.

How the Agent Loop Works

Behind the scenes, the Runner manages the interplay between the mannequin and the instruments.

Conceptually, the loop appears like this:

How to Turn a Python Script Into an AI Agent

If the mannequin wants extra info, it may name the device once more. The loop continues till it has sufficient info to provide a remaining response.

That is what makes the workflow agentic. As a substitute of following a hard and fast sequence written completely in Python, the mannequin decides which actions to take based mostly on the request and the outcomes it receives.

Different Python Scripts You Can Flip Into Brokers

The identical sample works with nearly any current Python automation. You retain the Python features that do the precise work and let the agent resolve which features to name and the best way to mix the outcomes.

For instance:

  • CSV analyzer: Capabilities filter rows, calculate metrics, and discover traits. The agent solutions natural-language questions in regards to the information.
  • Server monitor: Capabilities verify CPU, reminiscence, disk, and processes. The agent investigates why a server appears unhealthy.
  • Log analyzer: Capabilities search logs, depend errors, and extract occasions. The agent investigates incidents and summarizes what occurred.
  • API automation: Capabilities fetch information, replace information, or create stories. The agent decides which operations are wanted and in what order.

With the OpenAI Brokers SDK, you possibly can expose current Python features with @function_tool and add them to the agent’s instruments checklist.

The Python code nonetheless performs the work; the agent provides natural-language understanding, device choice, and orchestration.

Ultimate Ideas

Agentic AI is changing into a sensible technique to automate workflows, with extra firms utilizing brokers to deal with multi-step duties as a substitute of counting on fastened scripts.

On the similar time, cheaper fashions corresponding to GPT-5.6 Luna make it rather more inexpensive to run tool-using and even multi-agent methods at scale.

On this information, we began with a traditional Python perform, turned it right into a device, linked it to an agent, and let the Runner handle the decision-making loop.

That’s the core thought behind agentic purposes: give the mannequin a purpose and the best instruments, then let it resolve the best way to full the duty.

 
 

Abid Ali Awan (@1abidaliawan) is an authorized information scientist skilled who loves constructing machine studying fashions. Presently, he’s specializing in content material creation and writing technical blogs on machine studying and information science applied sciences. Abid holds a Grasp’s diploma in know-how administration and a bachelor’s diploma in telecommunication engineering. His imaginative and prescient is to construct an AI product utilizing a graph neural community for college students battling psychological sickness.

Tags: AgentPythonScriptTurn

Related Posts

European proptech data pipeline integration.jpg.jpg
Data Science

Europe’s Proptech Winners Are Competing on Knowledge, Not Software program

September 20, 2026
KDN Shittu 5 Prompt Optimization Strategies That Actually Improve LLM Output scaled.png
Data Science

5 Immediate Optimization Methods That Really Enhance LLM Output

September 20, 2026
Glassdoor infostealer ransomware gd app compromise 1.jpg
Data Science

Glassdoor’s Ransomware Deadline Expired Two Weeks In the past: The Knowledge By no means Confirmed Up

September 19, 2026
Kdn reusing the prompt prefix with a key value cache for slm optimization feature.png
Data Science

Reusing the Immediate Prefix with a Key-Worth Cache for SLM Optimization

September 18, 2026
Healthcare data breaches strict information governance featured.png
Data Science

Healthcare Information Breaches: Strict Data Governance

September 18, 2026
India demat 2 tokenized bonds sebi.jpg
Data Science

India Tokenizes Company Debt: Demat 2.0 Turns $107M in Bonds Into Digital Tokens, No Bitcoin Required

September 17, 2026
Next Post
5f06e7372a414a3aaf1658247b9cc280.png.jpeg

USDT on TRON Turns into Most Used Onchain Fee Possibility on CoinsBee as Stablecoin Spending Grows

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

POPULAR NEWS

Gemini 2.0 Fash Vs Gpt 4o.webp.webp

Gemini 2.0 Flash vs GPT 4o: Which is Higher?

January 19, 2025
Chainlink Link And Cardano Ada Dominate The Crypto Coin Development Chart.jpg

Chainlink’s Run to $20 Beneficial properties Steam Amid LINK Taking the Helm because the High Creating DeFi Challenge ⋆ ZyCrypto

May 17, 2025
Image 100 1024x683.png

Easy methods to Use LLMs for Highly effective Computerized Evaluations

August 13, 2025
Blog.png

XMN is accessible for buying and selling!

October 10, 2025
0 3.png

College endowments be a part of crypto rush, boosting meme cash like Meme Index

February 10, 2025

EDITOR'S PICK

Imagen 1 1.png

We Didn’t Invent Consideration — We Simply Rediscovered It

November 5, 2025
Blog 3070x1400 5 1.png

A dense week forward: Fed choice, Huge Tech earnings, and month-end crypto expiry

July 24, 2026
019b5c90 ca1e 771d 9766 9b8b2f8d992d.jpg

Ethereum’s TVL To Surge ’10X’ In 2026: Sharplink CEO

December 27, 2025
Mara bitcoin vault financing.jpg

MARA’s $600M Lengthy Ridge financing

August 7, 2026

About Us

Welcome to News AI World, your go-to source for the latest in artificial intelligence news and developments. Our mission is to deliver comprehensive and insightful coverage of the rapidly evolving AI landscape, keeping you informed about breakthroughs, trends, and the transformative impact of AI technologies across industries.

Categories

  • Artificial Intelligence
  • ChatGPT
  • Crypto Coins
  • Data Science
  • Machine Learning

Recent Posts

  • USDT on TRON Turns into Most Used Onchain Fee Possibility on CoinsBee as Stablecoin Spending Grows
  • How one can Flip a Python Script Into an AI Agent
  • CBAM Paper Walkthrough: The Double-Consideration Mechanism
  • Home
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy

© 2024 Newsaiworld.com. All rights reserved.

No Result
View All Result
  • Home
  • Artificial Intelligence
  • ChatGPT
  • Data Science
  • Machine Learning
  • Crypto Coins
  • Contact Us

© 2024 Newsaiworld.com. All rights reserved.

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?