Guilds AI / AI Blog

,

Agentic AI Tutorial: Build Your First AI Agent in Python

Laptop displaying Python code beside a notebook on a developer's desk

This agentic AI tutorial shows you how to build a simple AI agent in Python that retrieves information from a tool and uses it to answer a question. You will create a local product inventory lookup, connect it to a language model using the OpenAI Agents SDK, and test how the agent behaves when information is missing. For the distinction between generating a quick prototype and developing maintained software with agents, see our comparison of agentic engineering vs vibe coding. To extend the tutorial with repeatable outcome and permission checks, see our guide to evals for AI agents. For a longer Python-based learning resource, see our AI Agents in Action book and edition guide.

The example is deliberately read-only. If you want to use an agent to develop software rather than build one yourself, compare AI agents for coding. It does not place orders, change records, or access external customer information. You can use the same architecture as a starting point for more advanced agentic applications. To connect live services, see our tutorial on integrating external APIs with AI coding agents.

What is agentic AI?

Agentic AI refers to systems in which a model can select actions to accomplish a goal, use available tools, interpret their results, and decide whether further work is needed. The application manages the execution of those actions and sets limits on what the system can do.

ComponentRole in the tutorial
ModelInterprets the user request and selects an appropriate action.
InstructionsDefine the inventory assistant’s responsibilities.
ToolLooks up a product in a fixed local inventory.
RunnerCoordinates model calls and tool execution.
Stopping conditionReturns the answer or stops when the configured turn limit is reached.

Unlike a fixed script that always follows identical steps, an agent can select a tool based on the input. It is not necessary to build a multi-agent system for this example. See agentic workflows in AI for a broader explanation of workflow structures.

What you need before starting

You need Python 3.10 or newer, a terminal, a text editor and an OpenAI API account with billing or available credits. An API key is separate from a ChatGPT subscription. This tutorial uses an external model service, so model requests may incur charges.

The official SDK quickstart provides the current installation and authentication instructions. Check it if your installed version behaves differently from the examples below.

Step 1: Set up your Python environment

Create a dedicated project folder and a virtual environment so the project’s dependencies remain separate from other Python applications.

mkdir inventory-agent
cd inventory-agent
python -m venv .venv

Activate the virtual environment. On macOS or Linux:

source .venv/bin/activate

On Windows PowerShell:

.venv\Scripts\Activate.ps1

Install the SDK:

python -m pip install openai-agents

Set your OPENAI_API_KEY environment variable in your current terminal session. Replace the placeholder with your own key locally; never paste a real API key into public code or commit it to version control.

export OPENAI_API_KEY="YOUR_API_KEY"

For Windows PowerShell, use the corresponding environment-variable syntax:

$env:OPENAI_API_KEY = "YOUR_API_KEY"

Step 2: Create a tool

Create a file named inventory_agent.py. The example uses a dictionary as an artificial inventory database. A function decorated with function_tool becomes available to the agent as a callable operation.

from agents import Agent, Runner, function_tool

INVENTORY = {
    "A100": {"name": "Wireless mouse", "stock": 12},
    "B200": {"name": "USB-C hub", "stock": 0},
}

def lookup_inventory(sku: str) -> str:
    """Look up a SKU without calling a model."""
    product = INVENTORY.get(sku.strip().upper())
    if product is None:
        return "Product not found."
    return f"{product['name']}: {product['stock']} units in stock."

@function_tool
def lookup_product(sku: str) -> str:
    """Return inventory information for a product SKU."""
    return lookup_inventory(sku)

The function accepts a single product identifier and returns a short status message. No database credentials or network permissions are required. The SDK uses the function signature and description to expose the tool to the model. The function tool documentation explains the supported interfaces. To extend the same approach to document retrieval and iterative searches, see our guide to building RAG agents with LLMs.

For a real inventory system, replace the dictionary lookup with a scoped read-only service call that validates authorization independently. Read AI agent integration for more about connecting existing systems.

Step 3: Build and run your first AI agent

Append the following code to the same file. The instructions specify the agent’s role, the conditions for using the tool and how to handle missing information.

agent = Agent(
    name="Inventory assistant",
    instructions=(
        "Answer inventory questions using lookup_product. "
        "Ask for the SKU if none is provided. "
        "Never guess stock levels or invent products. "
        "Do not claim to reserve or order products."
    ),
    tools=[lookup_product],
)

if __name__ == "__main__":
    question = input("Ask about a product SKU: ")
    result = Runner.run_sync(agent, question, max_turns=5)
    print(result.final_output)

Run the complete file:

python inventory_agent.py

When prompted, enter: How many units of A100 are in stock? The expected answer is that the wireless mouse has 12 units available. The exact wording can vary. This is an illustrative expected result, not a recorded execution.

Instructions matter because they tell the agent how to handle uncertainty and define its task. Our AI agent prompts guide provides additional templates for other applications.

Step 4: Test the agent

Test the application with several inputs before adding features. Restart the script for each independent test. Inspect whether the tool is called when necessary and whether the final answer is supported by its return value.

Test inputExpected behavior
How many A100 units are in stock?Reports 12 wireless mice.
Is B200 available?Reports zero USB-C hubs.
How many X999 units do you have?States that the product was not found.
Is my product available?Requests the SKU instead of inventing it.
Reserve ten A100 units.Explains that reservations are not supported.

Test the inventory function independently as well. The plain lookup_inventory function is separate from the SDK tool wrapper, so you can test the underlying inventory logic without making a model request. With the SDK installed in your virtual environment, save the following as test_inventory.py in the same project directory.

import unittest
from inventory_agent import lookup_inventory

class InventoryTests(unittest.TestCase):
    def test_available(self):
        self.assertEqual(
            lookup_inventory(" a100 "),
            "Wireless mouse: 12 units in stock."
        )

    def test_out_of_stock(self):
        self.assertEqual(
            lookup_inventory("B200"),
            "USB-C hub: 0 units in stock."
        )

    def test_missing(self):
        self.assertEqual(
            lookup_inventory("X999"), "Product not found."
        )

    def test_empty(self):
        self.assertEqual(
            lookup_inventory(""), "Product not found."
        )

if __name__ == "__main__":
    unittest.main()

Run python -m unittest test_inventory.py. The four cases should pass. The plain inventory function was checked separately against these four cases; the complete SDK import and live model calls have not been executed as part of that test. These tests establish the deterministic lookup behavior, not whether the model chooses the correct tool.

If the run fails, check whether the virtual environment is active, the package is installed, your API key is available, and the API account can access the configured model. A turn-limit exception means that the run did not finish within its allowed turns; do not blindly increase the limit.

Step 5: Understand the agentic workflow

Tool use is one of four foundational agentic design patterns; the others include planning, reflection and multi-agent collaboration.

When the agent receives a question, the model determines whether a lookup is needed. If it requests the tool, the runner executes the function, returns the result to the model and lets the model produce a response or request another permitted action. The run ends when a final output is returned or an execution limit is reached.

User question
Agent interprets request
Read-only inventory lookup
Agent checks tool result
Final answer
Illustrative tool-calling loop for the inventory assistant.

The runner handles execution; instructions alone are not security controls. In a larger system, AI orchestration may coordinate multiple tools, steps or specialized agents, while AI agent communication defines how information moves among them.

Step 6: Prepare for real-world applications

Add structured outputs and validation

When downstream software needs to consume an agent’s response, define a structured result schema instead of parsing arbitrary prose. Validate the returned fields against the source data before updating application state.

Enforce permissions outside the model

Keep tools narrowly scoped, authenticate requests, and verify access in the underlying service. If you later introduce actions such as reserving stock or sending a notification, require an appropriate approval before executing them.

Monitor cost and reliability

Record task outcomes, tool errors, execution duration and model usage. Set explicit budgets and time limits. Run a small evaluation suite whenever instructions, tools or models change, and avoid logging secrets or sensitive customer information.

Expand only when necessary

Add more tools when a single tool cannot satisfy the intended task. Introduce specialized agents only when separation offers a measurable benefit. For ongoing oversight, see our AI agent management platform guide.

Frequently asked questions

Is agentic AI difficult to learn?

A basic tool-calling agent is accessible to someone familiar with Python functions and environment variables. Reliable production systems require additional work on permissions, evaluation, error handling and monitoring.

Can I build agentic AI without coding?

Yes. Visual workflow builders can connect a model to predefined tools and actions. The same principles apply: define a clear task, limit permissions, test failure cases and establish stopping conditions.

Do I need multiple agents?

No. Start with one agent and a small set of tools. Multiple agents can add coordination costs and are useful only when the task benefits from independent specialization.

Is this agentic AI tutorial free?

The Python example and SDK are available without a separate tutorial fee, but model API usage can cost money. Check the provider’s current API pricing before running experiments.

Can I use this code in production?

Not as written. It is an educational example using fictional inventory. Production deployments require secure data access, validation, monitoring, error handling and authorization.