AI in Python

AI Agents in Python – A Simple Project for Beginners

Introduction: Taking Your First Steps with AI Agents in Python

Artificial intelligence is increasingly present in everyday life—from intelligent voice assistants and recommendation systems to autonomous vehicles. One of the key elements of AI are agents, which are programs capable of making decisions independently based on data from their environment. Learning how to create your own AI agents is a great way to understand how modern systems work and how they can be used in practice.

Python is one of the most popular programming languages in the world of artificial intelligence. Thanks to its clear syntax and rich library ecosystem, it allows you to quickly start your AI journey—even if you don’t have much programming experience. In this article, we’ll show you step by step how to create a simple AI agent in Python, which can be a starting point for more advanced projects.

Setting Up Your Environment: Essential Tools and Libraries

Before you start writing your own AI agent, it’s worth preparing the right working environment. Here’s what you’ll need:

Python – preferably version 3.8 or newer. You can download it from python.org.

Code editor – recommended options include Visual Studio Code, PyCharm, Sublime Text, or even a simple editor like Notepad++.

Terminal or command prompt – for running Python scripts.

Basic libraries – at the beginning, Python itself is enough, but it’s good to know libraries like numpy (for calculations), random (for generating random events), or matplotlib (for visualization, if you want to see your agent’s results).

To install additional libraries, you can use the command:

bash

Copy Code

pip install numpy matplotlib

It’s also good practice to create a virtual environment (e.g., using venv), which will keep your project separate from other Python installations on your computer:

bash

Copy Code

python -m venv myenv

source myenv/bin/activate  # Linux/Mac

myenv\Scripts\activate     # Windows

Once your environment is ready, you can move on to writing your first AI agent in Python!

The Basics: What Is an AI Agent?

An AI agent is a computer program that can independently make decisions and perform specific tasks based on information from its environment. In its simplest form, an agent receives input data (such as signals, numbers, or text), analyzes them according to predefined rules or algorithms, and then takes appropriate actions.

Key features of an AI agent:

Perception: The agent receives information from the environment using so-called sensors (e.g., reading temperature, detecting motion, analyzing text).

Decision: Based on the collected data, the agent analyzes the situation and chooses the best possible action.

Action: The agent performs the selected action, such as sending a response, changing a device setting, or performing calculations.

In practice, an AI agent can be very simple (e.g., an automatic light that turns on when motion is detected) or advanced (e.g., an autonomous car analyzing its surroundings and planning a route).

Example of a simple agent:

Imagine an agent whose task is to turn on a fan if the room temperature exceeds 25°C. Such an agent:

Receives data from a temperature sensor (perception),

Checks if the temperature is higher than 25°C (decision),

Turns on the fan if the condition is met (action).

How an AI agent works:

Receive data from the environment (e.g., temperature).

Analyze the data according to predefined rules.

Perform the appropriate action.

In the following sections, we will show how to implement such a simple agent in Python.

Step-by-Step Project: Building a Simple Reflex Agent

In this section, we’ll go through the entire process of creating a simple reflex agent in Python. This agent will make decisions based on current data from the environment, without remembering any history. It’s a great starter project to help you understand the basics of how AI agents work.

4.1 Defining the Environment and Agent

First, we need to specify the environment in which our agent will operate and the task it should perform. Let’s assume the agent is supposed to monitor the room temperature and turn on a fan when the temperature exceeds a certain threshold.

Example definition of the environment and agent in Python:

python

Copy Code

class Environment:

    def __init__(self, temperature):

        self.temperature = temperature

class FanAgent:

    def __init__(self, threshold):

        self.threshold = threshold

    def perceive_and_act(self, environment):

        if environment.temperature > self.threshold:

            return "Turn on the fan"

        else:

            return "Fan off"

4.2 Implementing the Agent’s Logic

Our agent operates according to a simple rule: if the temperature is higher than the set threshold, it turns on the fan. Otherwise, the fan remains off. This makes the agent fast and reliable in simple situations.

Example of using the agent:

python

Copy Code

# Create environment and agent

room = Environment(temperature=28)

agent = FanAgent(threshold=25)

# Agent makes a decision based on the environment

action = agent.perceive_and_act(room)

print(action)  # Output: Turn on the fan

You can change the temperature in the environment and check how the agent reacts to different conditions.

4.3 Testing the Agent in Practice

Testing is an important stage of any project. It’s worth checking how the agent behaves in various situations—both typical and unusual.

Example of testing the agent for different temperatures:

python

Copy Code

temperatures = [22, 25, 28, 30]

agent = FanAgent(threshold=25)

for temp in temperatures:

    room = Environment(temperature=temp)

    action = agent.perceive_and_act(room)

    print(f"Temperature: {temp}°C -> {action}")

Program output:

Temperature: 22°C -> Fan off

Temperature: 25°C -> Fan off

Temperature: 28°C -> Turn on the fan

Temperature: 30°C -> Turn on the fan

With this simple project, you learn the basics of creating AI agents in Python: defining the environment, implementing decision logic, and testing the agent’s behavior.

Expanding the Project: Adding Memory and Goals

After creating a simple reflex agent, you can expand the project by giving the agent memory and the ability to pursue goals. This makes the agent more flexible and “intelligent”—it can not only react to current stimuli but also take previous experiences into account and strive for specific outcomes.

Adding memory:

An agent with memory can store information about previous states of the environment or its own actions. For example, it can remember how many times it has turned on the fan during the day and use this information to make more informed decisions.

python

Copy Code

class MemoryFanAgent:

    def __init__(self, threshold):

        self.threshold = threshold

        self.fan_on_count = 0

    def perceive_and_act(self, environment):

        if environment.temperature > self.threshold:

            self.fan_on_count += 1

            return "Turn on the fan"

        else:

            return "Fan off"
python

Copy Code

class MemoryFanAgent:

    def __init__(self, threshold):

        self.threshold = threshold

        self.fan_on_count = 0

    def perceive_and_act(self, environment):

        if environment.temperature > self.threshold:

            self.fan_on_count += 1

            return "Turn on the fan"

        else:

            return "Fan off"

Adding goals:

An agent can have a defined goal, such as maintaining the temperature within a certain range throughout the day. To achieve this, it can analyze not only the current temperature but also predict how its actions will affect future states of the environment.

Exploring More Advanced Agents: A Brief Overview of Techniques

Once you’ve mastered the basics, you can start experimenting with more advanced techniques for building AI agents. Here are a few directions for development:

Learning agents: Use machine learning algorithms to improve their decisions based on historical data and interactions with the environment.

Complex (hybrid) agents: Combine different action strategies, such as quick reactions with long-term planning.

Multi-agent systems: Cooperate or compete with other agents, for example in games or logistics systems.

Integration with real devices: Agents can control IoT hardware, analyze sensor data, or communicate with other systems via APIs.

Each of these directions allows you to create increasingly advanced and practical solutions that can be used in business, science, or everyday life.

Best Practices: Writing Clean and Efficient Agent Code

Creating AI agents in Python is not just about making the program work correctly, but also about ensuring code quality. Following good programming practices makes your code easier to understand, develop, and test. Here are a few tips:

Use clear variable and function names – descriptive names make it easier to understand what each part of the program does.

Divide code into functions and classes – modularity makes it easier to manage the project and reuse code fragments.

Comment on key sections – short comments help others (and yourself in the future) quickly grasp the logic of the code.

Avoid code duplication – if you notice several sections doing the same thing, move them into a single function.

Test your code with different cases – check how the agent behaves in unusual situations to avoid errors in practice.

Use formatting and code analysis tools – such as black, flake8, or pylint, which help maintain a consistent style and detect potential issues.

By following these principles, your project will be more professional and easier to expand in the future.

Resources for Further Learning: Where to Develop Your Skills

If you want to deepen your knowledge of AI agents and Python, it’s worth turning to reliable sources. Here are a few suggestions:

Official Python documentation – python.org – a great place to learn the basics of the language.

Online courses – platforms like Coursera, Udemy, edX, or DataCamp offer courses in AI, machine learning, and agent programming.

Books – e.g., “Learning Python” by Mark Lutz, “Python Crash Course” by Eric Matthes, or “Artificial Intelligence: A Modern Approach” by Russell and Norvig.

Communities and forums – Stack Overflow, Reddit (e.g., r/learnpython), Facebook and Discord groups where you can ask questions and share experiences.

Open source projects – browsing and analyzing code available on GitHub lets you see how others solve similar problems.

Regular learning and practice are key to development—the more projects you complete, the better you’ll understand how AI agents work and how to program them effectively.

Conclusion: Your Journey with AI Agents Is Just Beginning

Creating a simple AI agent in Python is a great first step into the world of artificial intelligence. Through this project, you have learned basic concepts such as perception, decision-making, and action, as well as how to implement these mechanisms in practice. Working on an agent helps you understand how modern AI systems operate and how they can be used to automate everyday tasks or solve specific problems.

However, this is just the beginning. As you gain experience, you can develop your projects by adding memory, goals, or even the ability to learn from data. You can experiment with more advanced techniques, such as machine learning, multi-agent systems, or integration with real devices and services.

The most important thing is not to be afraid to try new things and to systematically expand your knowledge. Every new project is an opportunity for learning and growth—both technical and creative. The Python and AI community is very open, so don’t hesitate to use available resources, ask for advice, and share your achievements.

Your journey with AI agents is just beginning—good luck!

The AI Agent Revolution: Changing the Way We Develop Software

Building AI Agents: A Practical Approach to Python

Agents AI: A New Era of Automation and Intelligent Decision-Making in Business

Leave a Comment

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *