75% of C-suite leaders say agentic AI lives up to the hype or is underestimated. 48% still plan to cut headcount.
Back to Tutorials
aiTutorialbeginner

75% of C-suite leaders say agentic AI lives up to the hype or is underestimated. 48% still plan to cut headcount.

June 9, 202611 views5 min read

Learn how to build a basic agentic AI system using Python and OpenAI's API. This beginner-friendly tutorial walks you through creating an AI agent that can interact with users and make decisions based on input.

Introduction

Agentic AI refers to artificial intelligence systems that can perceive their environment, make decisions, and take autonomous actions to achieve specific goals. In simple terms, these are AI systems that don't just respond to commands but can think and act on their own. This tutorial will guide you through creating a basic agentic AI system using Python and the OpenAI API. You'll learn how to build a simple AI agent that can interact with users, process requests, and make decisions based on prompts.

Prerequisites

  • Basic understanding of Python programming
  • Python 3.7 or higher installed on your computer
  • An OpenAI API key (free to get at platform.openai.com)
  • Basic knowledge of how to use a terminal or command prompt

Step-by-step instructions

Step 1: Set Up Your Python Environment

Why this step is important

Before we can start coding, we need to create a clean environment for our project. This ensures that all the necessary tools and libraries are available and working correctly.

  1. Open your terminal or command prompt
  2. Create a new folder for this project by typing: mkdir agentic_ai_project
  3. Navigate to the folder: cd agentic_ai_project
  4. Create a virtual environment: python -m venv agentic_env
  5. Activate the virtual environment:
    • On Windows: agentic_env\Scripts\activate
    • On macOS/Linux: source agentic_env/bin/activate

Step 2: Install Required Libraries

Why this step is important

We need to install the OpenAI Python library to communicate with the OpenAI API. This library provides an easy way to send requests to OpenAI's models and receive responses.

  1. In your terminal, run: pip install openai
  2. Wait for the installation to complete

Step 3: Get Your OpenAI API Key

Why this step is important

The OpenAI API key is required to authenticate your requests to OpenAI's services. Without it, you won't be able to access the AI models we'll be using.

  1. Go to platform.openai.com
  2. Sign in or create an account
  3. Create a new API key
  4. Copy the key to your clipboard

Step 4: Create Your First Agentic AI Agent

Why this step is important

Now we'll write the core code that will create a basic AI agent. This agent will be able to receive user input, process it, and respond in a way that mimics decision-making behavior.

  1. Create a new file named agentic_agent.py in your project folder
  2. Open the file in a text editor and add the following code:
    import openai
    
    # Set up your API key
    openai.api_key = "YOUR_API_KEY_HERE"
    
    def get_ai_response(user_input):
        """Get a response from the AI based on user input"""
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a helpful assistant that can answer questions and make suggestions."},
                {"role": "user", "content": user_input}
            ]
        )
        return response.choices[0].message.content
    
    # Simple loop to interact with the agent
    print("Agentic AI Agent is ready! Type 'quit' to exit.")
    while True:
        user_input = input("You: ")
        if user_input.lower() in ['quit', 'exit', 'bye']:
            print("AI: Goodbye!")
            break
        ai_response = get_ai_response(user_input)
        print(f"AI: {ai_response}")
  3. Replace YOUR_API_KEY_HERE with your actual OpenAI API key

Step 5: Run Your Agentic AI Agent

Why this step is important

Running the code will test if everything is set up correctly and allow you to interact with your AI agent. This step confirms that your environment is properly configured and that the agent can communicate with OpenAI's API.

  1. In your terminal, make sure you're in the project folder
  2. Run the script: python agentic_agent.py
  3. Try asking simple questions like "What is artificial intelligence?" or "Tell me a joke"

Step 6: Enhance Your Agent's Capabilities

Why this step is important

Enhancing your agent makes it more interesting and useful. We'll add some decision-making logic that allows the agent to respond differently based on the type of input it receives.

  1. Modify your agentic_agent.py file with the enhanced code:
    import openai
    
    # Set up your API key
    openai.api_key = "YOUR_API_KEY_HERE"
    
    def get_ai_response(user_input):
        """Get a response from the AI based on user input"""
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a helpful assistant that can answer questions and make suggestions. If the user asks for a task, help them complete it step by step."},
                {"role": "user", "content": user_input}
            ]
        )
        return response.choices[0].message.content
    
    def categorize_input(user_input):
        """Categorize the input to determine how to respond"""
        if "calculate" in user_input.lower() or "math" in user_input.lower():
            return "math"
        elif "joke" in user_input.lower() or "funny" in user_input.lower():
            return "funny"
        elif "help" in user_input.lower() or "what can you do" in user_input.lower():
            return "help"
        else:
            return "general"
    
    # Simple loop to interact with the agent
    print("Agentic AI Agent is ready! Type 'quit' to exit.")
    while True:
        user_input = input("You: ")
        if user_input.lower() in ['quit', 'exit', 'bye']:
            print("AI: Goodbye!")
            break
        
        category = categorize_input(user_input)
        
        if category == "math":
            print("AI: I'll help you with that math problem!")
            # Add a simple math processing function here if desired
        elif category == "funny":
            print("AI: Here's a joke for you:")
        elif category == "help":
            print("AI: I can help with questions, calculations, jokes, and more!")
        
        ai_response = get_ai_response(user_input)
        print(f"AI: {ai_response}")

Step 7: Test Your Enhanced Agent

Why this step is important

Testing your enhanced agent helps verify that the new decision-making logic works as expected. This shows how your agent can behave differently based on the type of input it receives.

  1. Save your changes to the file
  2. Run the script again: python agentic_agent.py
  3. Try inputs like "Calculate 25 + 17", "Tell me a joke", and "What can you do?" to see how the agent responds differently

Summary

In this tutorial, you've learned how to create a basic agentic AI system using Python and OpenAI's API. You started by setting up your development environment, installed necessary libraries, and created a simple AI agent that can interact with users. You then enhanced the agent to make decisions based on the type of input it receives, which demonstrates the core concept of agentic AI - the ability to perceive inputs and respond appropriately.

This foundational knowledge is crucial as agentic AI becomes more prevalent in business environments, as mentioned in the recent survey where 75% of C-suite leaders believe agentic AI lives up to the hype. Understanding how these systems work is the first step toward implementing them in real-world applications.

Source: TNW Neural

Related Articles