Thursday, November 5, 2026

AI & Machine Learning: Stop Deploying AI Without a Clear Strategy

 

AI & Machine Learning: Stop Deploying AI Without a Clear Strategy

Artificial Intelligence (AI) and Machine Learning (ML) are transforming the modern technology landscape. Businesses across industries are investing in AI-powered applications to automate tasks, improve productivity and make better decisions. From chatbots and recommendation systems to predictive analytics and intelligent automation, AI is becoming an important part of digital transformation.

However, there is one important problem: many organisations are rushing to deploy AI solutions without understanding whether they actually need them. Introducing AI simply because it is popular can increase costs, create unnecessary complexity and deliver disappointing results.

The real objective should not be to deploy AI everywhere. Instead, organisations should identify genuine problems, evaluate suitable technologies and build solutions that provide measurable value.

What Are Artificial Intelligence and Machine Learning?

Artificial Intelligence is a field of computer science that focuses on developing systems capable of performing tasks that normally require human intelligence. These tasks include understanding language, recognising images, solving problems and generating content.

Machine Learning is a branch of AI that enables computer systems to learn patterns from data and improve their performance without being explicitly programmed for every situation.

For example, an email application can use machine learning to identify spam messages by analysing patterns in previously labelled emails.

Why Are Businesses Rushing to Deploy AI?

AI has received significant attention because of improvements in computing power, data availability and advanced machine learning models. Businesses want to benefit from these developments and remain competitive.

Some common reasons behind rapid AI adoption include:

  • Business competition: Companies want to introduce innovative products and services.
  • Automation: AI can help reduce repetitive manual work.
  • Productivity: Intelligent tools can support employees with research, writing and data analysis.
  • Customer experience: AI-powered systems can provide faster responses and personalised recommendations.
  • Data analysis: Machine learning can identify patterns in large datasets.
  • Innovation: Organisations want to explore new business opportunities using AI.

Although these benefits are attractive, adopting AI without proper planning can create more problems than it solves.

Stop Deploying AI Without Understanding the Problem

One of the biggest mistakes organisations make is selecting an AI tool before identifying the actual business problem. Technology should support a clear objective rather than become the objective itself.

For example, a small business may introduce an expensive AI chatbot even though its customers mainly need a simple contact form and accurate product information. In this situation, a traditional solution may be more affordable and effective.

Before deploying an AI system, organisations should ask three important questions:

  • What specific problem are we trying to solve?
  • Can AI solve this problem more effectively than existing solutions?
  • Will the expected benefits justify the development and maintenance costs?

If there is no clear answer, the organisation should reconsider the deployment.

Common Problems Caused by Unplanned AI Deployment

1. High Development and Maintenance Costs

Building an AI application requires more than selecting a model. Organisations may need suitable computing infrastructure, quality datasets, skilled developers, security systems and ongoing maintenance.

Some AI solutions also involve recurring expenses for cloud computing, model usage and data storage. Without a proper budget, these costs can become difficult to manage.

2. Poor Data Quality

Machine learning systems depend heavily on data. If the training information is incomplete, outdated or inaccurate, the model may produce unreliable predictions.

Businesses should establish data quality standards before investing in machine learning projects.

3. Security and Privacy Risks

AI applications may process sensitive business information, customer records and personal data. Poorly designed systems can expose information or create privacy problems.

Organisations should introduce appropriate access controls, encryption, data protection practices and security testing.

4. Incorrect or Misleading Results

AI systems are not always accurate. Generative AI tools can produce convincing but incorrect information, while predictive models may perform poorly when real-world conditions change.

Important decisions should include suitable human review and verification procedures.

5. Lack of Skilled Professionals

Successful AI implementation requires knowledge of software engineering, data management, machine learning and cybersecurity. Organisations without the necessary expertise may struggle to operate and maintain their systems.

When Should You Actually Deploy AI?

AI is useful when it addresses a genuine problem and provides benefits that justify its complexity and cost.

Here are some situations where AI can deliver meaningful results:

  • Customer support: AI assistants can answer common questions and help users find relevant information.
  • Fraud detection: Machine learning models can identify unusual transaction patterns for further investigation.
  • Predictive maintenance: AI can analyse equipment information to help identify possible maintenance requirements.
  • Healthcare research: AI can assist researchers in analysing medical information and identifying patterns.
  • Recommendation systems: Online platforms can suggest products, films or other content based on user preferences.
  • Document processing: AI can extract and organise information from large collections of documents.

In each case, the technology should be selected according to the problem, available data and expected results.

AI vs Traditional Software: Which One Should You Choose?

Not every software problem requires artificial intelligence. Traditional programming is often a better choice when requirements are clear and tasks follow predictable rules.

Feature Traditional Software AI-Based Software
Working method Follows programmed rules Uses models to identify patterns and generate outputs
Data requirements May require limited data Often requires suitable training or reference data
Predictability Usually predictable for defined inputs Results may vary depending on the model and input
Best use Fixed rules and calculations Complex patterns and uncertain information
Maintenance Requires code updates and testing May also require monitoring, evaluation and model updates

The best solution depends on the requirements. Sometimes traditional software is enough, while other situations benefit from machine learning or generative AI.

How to Deploy AI Responsibly

Organisations should follow a structured approach instead of rushing an AI project into production.

Step 1: Identify a Real Business Problem

Start by understanding the problem and identifying the expected outcome. Avoid selecting AI technology simply because it is trending.

Step 2: Evaluate Existing Solutions

Compare traditional software, automation tools and AI-based approaches. Choose the simplest solution that meets the requirements.

Step 3: Check Data Availability

Evaluate whether the organisation has enough relevant, accurate and legally usable data to support the proposed AI system.

Step 4: Build a Small Prototype

Create a limited version of the application to test its usefulness. A prototype helps identify technical limitations before a large investment is made.

Step 5: Test Accuracy and Security

Evaluate the system using realistic examples. Check its reliability, privacy protections, security and performance under different conditions.

Step 6: Introduce Human Oversight

Keep qualified people involved in important decisions. Human review is particularly important when AI outputs may affect customers, finances or public services.

Step 7: Monitor Performance

After deployment, regularly examine accuracy, operating costs, user feedback and potential risks. Update or discontinue the system when it no longer provides sufficient value.

The Importance of Responsible AI

Responsible AI means developing and using artificial intelligence in ways that are safe, transparent, fair and accountable.

Businesses should consider the following principles:

  • Transparency: Explain when AI is being used and communicate important limitations.
  • Privacy: Protect personal and confidential information.
  • Fairness: Evaluate systems for possible bias and discriminatory outcomes.
  • Accountability: Establish clear responsibility for AI-related decisions.
  • Safety: Test systems carefully before introducing them into important environments.
  • Human supervision: Ensure people can review and challenge significant AI-generated decisions.

The Future of AI and Machine Learning

Artificial Intelligence and Machine Learning will continue to influence software development, business operations, scientific research and digital services.

Generative AI, AI agents, natural language processing, computer vision and predictive analytics are creating new opportunities. However, future success will depend not only on developing powerful models but also on using them responsibly.

Organisations that focus on practical applications, reliable data, security and measurable outcomes will be better positioned to benefit from AI advancements.

Conclusion: Build Solutions, Not Just AI Projects

Artificial Intelligence and Machine Learning offer valuable opportunities, but deploying AI without a clear purpose can waste time, money and resources. Every organisation should understand its requirements before introducing new technology.

The most effective strategy is to identify a real problem, compare available solutions, test carefully and measure the results. If traditional software can solve the problem efficiently, there may be no reason to introduce AI.

Remember: The goal is not to deploy more AI. The goal is to solve real problems with the right technology.

Sunday, November 1, 2026

When to Use GenAI Versus Predictive AI: Understanding the Key Differences

 

When to Use GenAI Versus Predictive AI: Understanding the Key Differences

Introduction

Artificial Intelligence (AI) is transforming how businesses operate, make decisions, and interact with customers. Two important AI technologies are Generative AI (GenAI) and Predictive AI. Although both use artificial intelligence and machine learning, they serve different purposes.

Generative AI focuses on creating new content, such as text, images, videos, music, and computer code. Predictive AI analyses existing data to identify patterns, forecast future outcomes, and support decision-making.

Understanding when to use GenAI versus Predictive AI can help businesses improve productivity, save time, reduce costs, and make better decisions.

1. What Is Generative AI (GenAI)?

Generative AI is a type of artificial intelligence that creates new content based on patterns learned from existing training data.

It uses advanced technologies such as Large Language Models (LLMs), deep learning, and neural networks to generate human-like responses and creative outputs.

Common Applications of Generative AI

  • Content Creation: Generates blog posts, articles, product descriptions, and marketing content.
  • Image Generation: Creates images, illustrations, and graphics from text prompts.
  • Code Generation: Helps developers write, explain, and improve programming code.
  • Customer Support: Generates conversational responses through AI-powered chatbots.
  • Video Creation: Produces videos using text descriptions and other inputs.
  • Document Summarisation: Converts lengthy documents into shorter summaries.

Popular Generative AI Tools

  • ChatGPT
  • Google Gemini
  • Claude
  • Midjourney
  • GitHub Copilot

2. What Is Predictive AI?

Predictive AI is a technology that uses historical data, statistical methods, and machine learning algorithms to predict future events or possible outcomes.

It identifies patterns in existing datasets and uses those patterns to estimate what might happen next.

Common Applications of Predictive AI

  • Sales Forecasting: Estimates future sales based on previous business performance.
  • Fraud Detection: Identifies unusual transaction patterns.
  • Customer Behaviour: Predicts customer preferences and purchasing patterns.
  • Healthcare: Helps analyse medical data to estimate potential health risks.
  • Weather Forecasting: Uses historical and real-time weather information to predict weather conditions.
  • Inventory Management: Estimates future product demand.

Popular Predictive AI Technologies

  • Python
  • TensorFlow
  • Scikit-learn
  • PyTorch
  • XGBoost
  • Microsoft Azure Machine Learning

3. GenAI vs Predictive AI: Key Differences

Although both technologies belong to the artificial intelligence ecosystem, their objectives and applications are different.

Feature Generative AI Predictive AI
Main Purpose Creates new content Predicts future outcomes
Input Prompts, text, images and data Historical and current data
Output Text, images, videos and code Predictions, scores and classifications
Technology Generative models and deep learning Machine learning and statistical models
Main Focus Content generation Forecasting and analysis
Business Use Marketing and automation Risk analysis and forecasting

In simple words: Generative AI creates something new, whereas Predictive AI estimates what is likely to happen.

4. When Should You Use Generative AI?

Generative AI is particularly useful when your business needs to create content, automate communication, or improve creative workflows.

A. Content and Marketing

Businesses can use Generative AI to create marketing campaigns, social media posts, blog articles, advertisements, and product descriptions. It helps marketing teams prepare content more efficiently.

B. Software Development

Developers can use AI coding assistants to generate code suggestions, explain programming concepts, identify potential errors, and support software development.

C. Customer Service Automation

AI-powered chatbots can understand customer questions and generate relevant responses. They can also help customers find information about products and services.

D. Creative Projects

Designers and content creators can use GenAI to develop images, videos, presentations, and other creative materials.

Best choice: Use Generative AI when the primary requirement is creating, writing, designing, or generating new content.

5. When Should You Use Predictive AI?

Predictive AI is useful when businesses need to understand historical information and make data-driven decisions about future possibilities.

A. Business Forecasting

Companies can analyse previous sales records, market trends, and customer demand to estimate future business performance.

B. Financial Risk Management

Financial institutions can use predictive models to evaluate credit risk, identify unusual financial patterns, and support risk assessment.

C. Customer Retention

Predictive AI can estimate which customers may stop using a particular service. Businesses can use these insights to improve customer satisfaction.

D. Supply Chain Management

Companies can forecast product demand, identify potential inventory shortages, and improve supply chain planning.

E. Healthcare Analysis

Healthcare organisations can use predictive models to analyse patient information and support clinical decision-making.

Best choice: Use Predictive AI when your primary requirement is forecasting, identifying patterns, estimating risks, or making data-driven decisions.

6. Can Businesses Use GenAI and Predictive AI Together?

Yes! Combining Generative AI and Predictive AI can create more powerful business solutions.

Instead of choosing only one technology, organisations can integrate both to improve automation and decision-making.

Practical Example: An E-commerce Business

Imagine an online shopping company that wants to increase sales and improve customer experience.

  1. Predictive AI: Analyses customer purchase history, browsing behaviour, and product preferences to estimate which products customers are more likely to purchase.
  2. Generative AI: Creates personalised product descriptions, promotional messages, and customer communication.
  3. Business Results: The company can improve product recommendations, automate marketing activities, and provide a better shopping experience.

Other Combined Use Cases

Industry Predictive AI Generative AI
Banking Fraud risk prediction Customer communication
Healthcare Health risk assessment Medical report summaries
Retail Demand forecasting Product descriptions
Education Student performance analysis Learning materials
Manufacturing Equipment failure prediction Maintenance reports
Marketing Customer behaviour prediction Advertisement creation

7. Advantages of Generative AI and Predictive AI

Benefits of Generative AI

  • Saves time in content creation.
  • Supports creative workflows.
  • Improves customer communication.
  • Helps developers write code.
  • Automates repetitive content-related tasks.
  • Supports personalised experiences.

Benefits of Predictive AI

  • Improves business forecasting.
  • Supports data-driven decisions.
  • Helps identify potential risks.
  • Improves inventory management.
  • Supports customer behaviour analysis.
  • Helps organisations plan future activities.

8. Challenges and Limitations

Generative AI Challenges

  • Incorrect Information: AI-generated content can sometimes contain inaccurate information.
  • Data Privacy: Sensitive information must be protected when using AI platforms.
  • Copyright Concerns: Generated content may raise intellectual property questions.
  • Human Verification: Important outputs require review before publication or implementation.

Predictive AI Challenges

  • Data Quality: Poor-quality historical data can produce unreliable predictions.
  • Model Bias: Biased training data can affect prediction results.
  • Changing Conditions: Unexpected market changes can reduce prediction accuracy.
  • Maintenance: Predictive models require monitoring and periodic updates.

Businesses should combine AI technologies with human expertise, reliable data, and appropriate security practices.

9. Future of Generative AI and Predictive AI

The future of artificial intelligence will involve increasingly intelligent systems that can generate content, analyse information, and support complex business operations.

Generative AI is expected to become more useful in software development, content production, education, and business automation.

Predictive AI will continue to support industries that depend on forecasting, risk assessment, customer analytics, and operational planning.

Another important development is the integration of both technologies into AI agents and automated business systems.

For example, an AI-powered business assistant could use Predictive AI to analyse sales performance and Generative AI to prepare a business report containing recommendations.

This combination can make AI systems more useful for everyday business operations.

Conclusion

Generative AI and Predictive AI are two important technologies that solve different types of problems.

Generative AI is the better choice when businesses need to create content, generate ideas, develop software, or automate communication.

Predictive AI is more suitable when organisations need to forecast sales, analyse customer behaviour, identify risks, or estimate future outcomes.

However, businesses do not always need to choose between them. Combining Generative AI and Predictive AI can create intelligent solutions that support both creativity and data-driven decision-making.

The key is to understand your business requirements and select the AI technology that best supports your goals.

.

Friday, October 30, 2026

Search for a Name from a List in Python: A Beginner-Friendly Guide

 

Search for a Name from a List in Python: A Beginner-Friendly Guide

https://technologiesinternetz.blogspot.com


Introduction

Python is one of the most popular programming languages because of its simplicity and powerful features. One common programming task is searching for a particular name from a list of names.

For example, imagine you have a list of students in a classroom and want to check whether a particular student's name is present. Instead of checking every name manually, you can use Python to perform the search automatically.

In this tutorial, we will explore different ways to search for a name in a Python list using simple and practical examples.

1. Understanding Python Lists

A list in Python is used to store multiple items in a single variable. You can store names, numbers, strings, and other types of data.

Example:

names = ["Rahul", "Amit", "Priya", "Neha", "Rohan"]

print(names)

Output:

['Rahul', 'Amit', 'Priya', 'Neha', 'Rohan']

In this example, we have created a list containing five names.

2. Search for a Name Using the in Operator

The easiest way to check whether a name exists in a Python list is by using the in operator.

Example:

names = ["Rahul", "Amit", "Priya", "Neha", "Rohan"]

search_name = "Priya"

if search_name in names:
    print("Name found in the list!")
else:
    print("Name not found in the list.")

Output:

Name found in the list!

How does it work?

  • First, we create a list of names.
  • Next, we define the name we want to search for.
  • The in operator checks whether the name exists in the list.
  • If the name is available, Python displays a success message.
  • Otherwise, it displays a message indicating that the name was not found.

3. Search for a Name Using a for Loop

Another method is to use a for loop. This approach checks each name individually.

Example:

names = ["Rahul", "Amit", "Priya", "Neha", "Rohan"]

search_name = "Neha"

found = False

for name in names:
    if name == search_name:
        found = True
        break

if found:
    print("Name found!")
else:
    print("Name not found!")

Output:

Name found!

The for loop goes through each item in the list. When it finds the matching name, the break statement stops the loop.

This method is useful when you want to perform additional operations during the search.

4. Search for a Name Without Considering Uppercase and Lowercase

Python string comparisons are case-sensitive by default. For example, Rahul and rahul are considered different strings.

You can solve this problem using the lower() method.

Example:

names = ["Rahul", "Amit", "Priya", "Neha"]

search_name = "rahul"

if search_name.lower() in [name.lower() for name in names]:
    print("Name found!")
else:
    print("Name not found!")

Output:

Name found!

The lower() method converts all names into lowercase before comparing them. This makes the search case-insensitive.

5. Search for a Name Using the index() Method

Python also provides an index() method that returns the position of an item in a list.

Example:

names = ["Rahul", "Amit", "Priya", "Neha"]

search_name = "Priya"

if search_name in names:
    position = names.index(search_name)
    print("Name found at position:", position)
else:
    print("Name not found!")

Output:

Name found at position: 2

Remember that Python list indexing starts from zero. Therefore, the third name has an index of 2.

6. Search for a Partial Name

Sometimes, you may want to search for only a part of a name rather than the complete name.

For example, searching for Rah should find Rahul.

You can achieve this using the in operator inside a list comprehension.

Example:

names = ["Rahul", "Amit", "Priya", "Neha", "Rohan"]

search_name = "Rah"

results = [
    name for name in names
    if search_name.lower() in name.lower()
]

if results:
    print("Matching names:", results)
else:
    print("No matching names found.")

Output:

Matching names: ['Rahul']

This method is useful for creating search features in applications and websites.

7. Create a Simple Name Search Program

Now, let's combine these concepts to create a small interactive Python program. Users can enter a name, and Python will check whether it exists in the list.

Complete Python Code:

names = ["Rahul", "Amit", "Priya", "Neha", "Rohan"]

search_name = input("Enter a name to search: ")

found = False

for name in names:
    if name.lower() == search_name.lower():
        found = True
        break

if found:
    print(search_name, "was found in the list.")
else:
    print(search_name, "was not found in the list.")

Sample Output:

Enter a name to search: priya

priya was found in the list.

This program allows users to search for names without worrying about uppercase or lowercase letters.

8. Where Can Python List Searching Be Used?

Searching for names in a list is a basic programming concept, but it has several practical applications.

  1. Student Management Systems: Check whether a student is registered in a school database.
  2. Contact Applications: Find a person's name from a contact list.
  3. Employee Management: Search for employees using their names.
  4. Attendance Systems: Check whether a student is included in an attendance list.
  5. Registration Forms: Verify whether a username already exists.
  6. Search Applications: Build simple search functionality for websites and applications.

9. Which Python Search Method Should You Choose?

Different methods are useful for different situations.

Method Best Use
in operator Checking whether a name exists
for loop Custom search operations
lower() Case-insensitive searching
index() Finding the position of a name
List comprehension Searching for partial matches

For beginners, the in operator is usually the simplest method. As you gain experience, you can explore loops, list comprehensions, and more advanced searching techniques.

Conclusion

Searching for a name from a list in Python is an excellent beginner programming exercise. It helps you understand important concepts such as lists, conditional statements, loops, string methods, and operators.

You can start with the simple in operator and gradually learn more advanced techniques, such as case-insensitive searching and partial-name matching.

By practising these examples, you can build a strong foundation in Python and use these skills to develop real-world applications.


Thursday, October 29, 2026

Building Your First AI Agent in Python with the OpenAI Agents SDK

 

Building Your First AI Agent in Python with the OpenAI Agents SDK

Artificial intelligence is moving beyond simple chatbots. Modern AI applications can interpret instructions, use tools, perform multiple steps, and delegate work to specialised agents. These applications are commonly called AI agents.

Python developers can build these applications with the OpenAI Agents SDK, a framework that provides components for defining agents, executing tasks, connecting tools, and coordinating multiple agents. In this tutorial, you will create a beginner-friendly AI study assistant using Python.

What Is an AI Agent?

An AI agent is a software system that uses an AI model to work towards a specified goal. Depending on its configuration, it can interpret a request, decide which tool to use, gather information, and return a response.

For example, a conventional chatbot might explain how to solve a mathematics problem. An AI agent equipped with suitable tools could also retrieve information from a permitted source, perform a calculation, or organise a study plan.

An agent's capabilities depend on its instructions, available tools, permissions, and the model powering it. An agent does not automatically have access to the internet, private files, or external applications.

What Is the OpenAI Agents SDK?

The OpenAI Agents SDK is a Python framework for developing applications that use AI agents. It provides a structured way to define an agent, run it, connect Python functions as tools, and coordinate specialised agents.

Its major building blocks include:

  • Agents: AI assistants configured with instructions and optional tools.
  • Runner: Executes an agent and manages its interaction cycle.
  • Tools: Functions and supported integrations that allow agents to perform specific tasks.
  • Handoffs: Allow one agent to transfer responsibility to another specialised agent.
  • Guardrails: Help validate inputs or outputs and enforce application rules.
  • Tracing: Helps developers inspect and debug agent workflows.

These features make it possible to start with a small assistant and gradually develop a more advanced AI application.

Official documentation: OpenAI Agents SDK Quickstart.

Prerequisites

Before starting, make sure you have the following:

  • Python installed on your computer.
  • A basic understanding of Python functions and variables.
  • An OpenAI API key.
  • An internet connection for API requests.
  • A code editor or terminal.

You should also understand that API usage may incur charges. Check your account's current pricing and usage limits before running your application.

Step 1: Create a Python Project

Start by creating a separate folder for your AI agent project. Open your terminal and execute these commands:

mkdir ai-agent-project
cd ai-agent-project
python -m venv .venv

A virtual environment keeps the project's Python dependencies separate from other applications.

Activate the environment on Windows PowerShell:

.venv\Scripts\Activate.ps1

On macOS or Linux, use:

source .venv/bin/activate

Step 2: Install the OpenAI Agents SDK

Install the required package with pip:

pip install openai-agents

This installs the Python package needed to define and run agents. You can find installation instructions and additional examples in the official GitHub repository.

Step 3: Configure Your API Key

The SDK needs an API key to authenticate requests to OpenAI. Set the OPENAI_API_KEY environment variable before running the program.

For Windows PowerShell:

$env:OPENAI_API_KEY = "your-api-key"

For macOS or Linux:

export OPENAI_API_KEY="your-api-key"

Replace the example value with your actual API key. Obtain it through the official OpenAI API keys page.

Security tip: Never publish your API key in a blog post, upload it to a public GitHub repository, or include it in frontend JavaScript. Keep it in a secure environment variable or an appropriate secrets manager.

Step 4: Build Your First AI Agent

Now create a Python file named main.py. This first example creates an AI study assistant that explains programming concepts in simple language.

import asyncio
from agents import Agent, Runner

study_agent = Agent(
    name="Python Study Assistant",
    instructions=(
        "You are a friendly Python tutor. "
        "Explain programming concepts in simple language. "
        "Use short examples when helpful. "
        "If you are unsure about a fact, say so."
    ),
)

async def main():
    result = await Runner.run(
        study_agent,
        "Explain Python lists with a simple example."
    )

    print(result.final_output)

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

Run the application with:

python main.py

The program sends the question to the agent, waits for the result, and displays the final response. The exact wording will depend on the model and its response.

Understanding the Code

  • Agent defines the assistant's name, instructions, and optional capabilities.
  • Runner executes the agent's task.
  • Runner.run() is asynchronous, so it is called with await inside an asynchronous function.
  • result.final_output contains the final answer returned by the run.
  • asyncio.run(main()) starts the asynchronous program.

This is the foundation of your first agent. It can answer questions, but it does not yet have a custom Python tool to perform a specific action.

Step 5: Give the Agent a Python Tool

One important advantage of AI agents is their ability to use tools. A tool connects the model's decision-making process to a function that performs a defined task.

For example, you can create a Python function that calculates the average of a list of marks. The agent can call this function when a user requests a calculation.

Replace the contents of main.py with the following example:

import asyncio
from agents import Agent, Runner, function_tool

@function_tool
def calculate_average(marks: list[float]) -> float:
    """Calculate the average of a list of student marks."""
    if not marks:
        return 0.0

    return sum(marks) / len(marks)

study_agent = Agent(
    name="Study Assistant",
    instructions=(
        "Help students understand their marks. "
        "When asked to calculate an average, use "
        "the calculate_average tool. "
        "Explain the result clearly."
    ),
    tools=[calculate_average],
)

async def main():
    result = await Runner.run(
        study_agent,
        "Calculate the average of these marks: 80, 90, 70, 100."
    )

    print(result.final_output)

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

Run the program again:

python main.py

The expected numerical result is 85, because the sum of the four marks is 340 and dividing it by four gives 85. The agent may express the result in different words.

How Does the Tool Work?

  1. The user asks the agent to calculate an average.
  2. The agent recognises that the calculation tool is relevant.
  3. The SDK validates the tool arguments and invokes the Python function.
  4. The function calculates the average and returns the result.
  5. The agent uses the returned value to formulate its answer.

The @function_tool decorator makes the Python function available to the agent. Its name, description, and type information help the SDK expose the function to the model.

Always validate inputs and restrict tool permissions appropriately. For example, a tool that modifies files or sends emails should have stricter controls than a tool that performs arithmetic.

Step 6: Add More Useful Capabilities

After your first tool works, you can extend the assistant with additional functions. Consider adding these features:

  • Study planner: Generate a revision schedule based on subjects and available study time.
  • Quiz generator: Create practice questions for a selected topic.
  • Calculator: Perform supported mathematical operations.
  • Document assistant: Summarise content from files that your application is authorised to access.
  • Research assistant: Use an appropriately configured search tool to retrieve information.

Each function should have a clear purpose, a precise description, and sensible input validation. Avoid giving an agent unrestricted access to your computer or sensitive data.

Step 7: Understand Multi-Agent Workflows

Some projects need more than one specialised agent. Instead of asking a single assistant to handle every task, you can create agents with different responsibilities.

For example, a learning platform could contain:

  • Planner Agent: Organises the learning task.
  • Research Agent: Collects relevant information using approved tools.
  • Tutor Agent: Explains the material in student-friendly language.
  • Review Agent: Checks the draft for clarity and completeness.

The SDK supports two useful coordination patterns. With a handoff, one agent transfers control to a specialist. With an agent-as-tool design, a coordinating agent can call another agent while retaining responsibility for the final response.

These patterns are helpful when responsibilities are genuinely different. For a small project, a single agent with a few well-designed tools is usually easier to build, test, and maintain.

Step 8: Test and Debug Your AI Agent

Getting a response does not automatically mean that your agent is reliable. Test it with a variety of normal, unusual, and invalid requests.

  • Ask a question that matches the agent's intended role.
  • Check whether the agent uses its tool when appropriate.
  • Test empty lists, invalid values, and unexpected inputs.
  • Verify calculations independently.
  • Check how the agent responds when it lacks enough information.
  • Inspect traces to understand model calls and tool execution.

The SDK includes tracing features that can help you understand the steps involved in a run. For production applications, also add logging, error handling, usage monitoring, and automated tests.

Common Mistakes Beginners Should Avoid

1. Forgetting the API key: Check that the environment variable is configured in the same environment where the application runs.

2. Installing the wrong package: Use pip install openai-agents for the Python Agents SDK.

3. Expecting automatic tool access: An agent can only use tools that are available and correctly configured for it.

4. Writing vague instructions: Clearly explain the agent's role, boundaries, output style, and preferred tool usage.

5. Trusting every response: AI-generated information can be incorrect. Validate important results, especially in financial, legal, medical, and other high-impact applications.

6. Giving excessive permissions: Use the least privilege necessary, and require human approval for sensitive or irreversible actions.

Where Can You Use Python AI Agents?

Once you understand the basic workflow, you can explore several practical applications:

  • Customer-support assistants that use approved knowledge sources.
  • AI research tools that organise information from permitted sources.
  • Educational assistants that generate quizzes and explain concepts.
  • Business automation systems that prepare reports or classify requests.
  • Developer assistants that review code or explain programming errors.
  • Document-processing applications that extract and summarise information.

For each application, define the task clearly, select the appropriate tools, protect sensitive information, and test the system before deploying it to users.

Conclusion

Building your first AI agent in Python with the OpenAI Agents SDK is a practical way to move from ordinary chatbot development to tool-enabled AI applications. You begin by defining an agent and running it, then extend its capabilities with Python functions and, when necessary, specialised agents.

The best approach is to start small. Build one useful feature, test it carefully, and improve it before introducing complex workflows. With a strong foundation in Python, tool design, validation, and debugging, you can gradually develop AI assistants for education, research, productivity, and business automation.

Next step: Explore the official Agents SDK Quickstart and Tools documentation to learn more about building reliable agent workflows.

Frequently Asked Questions

1. Is the OpenAI Agents SDK suitable for beginners?

Yes. Developers with basic Python knowledge can begin with a simple agent and add tools as they become more comfortable with the framework.

2. Do I need an API key?

For this OpenAI API-based example, yes. You need a valid API key and an account with access to the required model and API usage.

3. Can an AI agent execute Python code?

An agent can call Python functions that you expose as tools. Arbitrary code execution requires a separately configured execution environment and appropriate security controls.

4. What is the difference between an AI agent and a chatbot?

A basic chatbot primarily responds to messages. An AI agent can also use configured tools and follow a managed sequence of steps to accomplish a task.

5. Can I build a multi-agent application?

Yes. The SDK supports handoffs and agent-as-tool patterns, allowing specialised agents to cooperate on more complex tasks.

 Learn how to build your first AI agent in Python with the OpenAI Agents SDK. Follow a beginner-friendly tutorial covering setup, tools, execution, and multi-agent workflows.

The Hidden Costs of Coding With Generative AI: What Developers Need to Know

  The Hidden Costs of Coding With Generative AI: What Developers Need to Know Introduction Generative Artificial Intelligence (AI) is ch...