PYTHON + LLMS

Python AI Agents Tutorials

An AI agent is a language model that can call your Python functions, look at the results and keep going until the job is done. Start here to learn how agents work and how to build one.

  • 94 tutorials
  • 14 topic areas
  • 3.12 Python tested
The whole agent loop, with a step limitBuild this agent

What is a Python AI agent?

A Python AI agent is a large language model (LLM) that can call functions you write in Python, read what they return, and decide what to do next. It repeats that loop until it has a final answer or hits a step limit you set.

A chatbot only replies with text. A normal script follows the exact steps you coded. An agent sits in between: you supply the tools, and the model picks which ones to call, in what order, with what arguments.

The agent loop is simple. You send the question and a list of tools to the model. If it asks for a tool, your code runs that function and sends the result back. Then you call the model again. No tool call means a final answer.

Tools are plain Python functions plus a short JSON description: a name, what the tool does and its parameters. The model never runs your code. It only asks, and your program decides whether to run it.

Memory is the message history you pass in on each call. Short-term memory is that list. Long-term memory means saving facts to a file or database, or pulling relevant documents in with retrieval (RAG).

Guardrails keep an agent safe and affordable: a max-steps cap, input validation on every tool, read-only tools where possible, and a human approval step before anything that sends, pays or deletes.

When I build agents for clients, the most common mistake I see is using one where a plain function would do. If the steps never change, write a script. It is faster, cheaper and easier to test.

Set up Python for AI agents

You need Python 3.10 or newer, an OpenAI API key and two packages. Create a virtual environment so the agent’s packages stay separate from everything else on your machine.

Put the key in a .env file next to your script, never in the code itself. python-dotenv loads it, and the openai client reads it automatically.

Your .env file holds one line, OPENAI_API_KEY=your-key-here. Add .env to .gitignore so the key never reaches GitHub.

From an empty folder to a running agentFull walkthrough

Your learning path

Learn Python AI agents in this order

Each stage builds on the one before it. If you have never called an LLM from Python, start at step 1.

  1. 1

    Build your first agent

    Write the agent loop by hand with two real tools and a step limit.

  2. 2

    Learn the OpenAI API

    Make calls, read responses and handle errors in Python.

  3. 3

    Add tools and structured outputs

    Describe tools with JSON Schema and get typed data back.

  4. 4

    Add RAG and memory

    Ground answers in your own documents with embeddings.

  5. 5

    Use a framework and deploy

    Compare LangGraph, Pydantic AI, CrewAI and others, then ship it.

Quick reference

The Python agent loop at a glance

The pieces you will write in almost every agent.

TaskCodeWorth knowing
Call the modelclient.responses.create(...)One request, one response.
Describe a tool{"type": "function", "name": ...}Name, description and a JSON Schema.
Spot a tool callitem.type == "function_call"No calls means a final answer.
Send a result back{"type": "function_call_output"}Include the matching call_id.
Stop runaway loopsfor step in range(1, max_steps + 1)Always cap the steps.
Load the API keyload_dotenv()Keeps the key out of your code.

Pick the right tool

Chatbot, script or AI agent?

An agent is not always the answer. Here is how the three compare.

ChatbotPython scriptAI agent
Who decides the stepsNobody, it only repliesYou, in codeThe model, at run time
Can run your functionsNoYes, always the same onesYes, the ones it picks
Handles new requestsTalks about themOnly what you codedCombines tools to solve them
Cost and speedOne model callNo model callsSeveral model calls
Best forQ&A and draftingFixed, repeatable jobsOpen-ended, multi-step tasks

Every tutorial, by topic

Python AI agent tutorials by topic

Linked titles are ready to read. Grey titles are on the way and will be linked as they go live.

Getting Started

4

Your first agent, the OpenAI API and the core ideas.

How to Build Your First AI Agent in PythonHow to Write Better Prompts for Python LLM AppsBest Python AI Agent Frameworks ComparedPython AI Agent Project Ideas for Your Portfolio

Building Agents

11

Tools, memory, planning and multi-step agent loops.

How to Build an AI Chatbot in PythonHow to Build a Tool-Calling AI Agent in PythonHow to Build a ReAct Agent from Scratch in PythonHow to Connect a Python AI Agent to a REST APIHow to Add Memory to a Python AI AgentHow to Build a Multi-Agent System in PythonHow to Route Tasks Between AI Agents in PythonHow to Use the OpenAI Agents SDK in PythonHow to Use Agent Handoffs with the OpenAI Agents SDKCrewAI Tutorial: Build a Multi-Agent Crew in PythonHow to Use Microsoft Agent Framework in Python

OpenAI API

5

Calls, streaming, function calling and the Responses API.

Python OpenAI API Tutorial for BeginnersHow to Use the OpenAI Responses API in PythonHow to Stream OpenAI Responses in PythonHow to Use Function Calling with OpenAI in PythonHow to Analyze Images with OpenAI Vision in Python

Pydantic and Structured Outputs

5

Get clean, validated data back from a model.

How to Use Structured Outputs with OpenAI and PydanticHow to Use Pydantic AI in PythonHow to Validate LLM Output with PydanticHow to Use JSON Schema with Python LLM ApplicationsHow to Build Reliable Structured AI Outputs in Python

AI Agent Projects

11

Complete agents you can build, run and adapt.

How to Build a Web Search AI Agent in PythonHow to Build a SQL Database AI Agent in PythonHow to Build a Customer Support AI Agent in PythonHow to Build a Research AI Agent in PythonHow to Build a Sales Assistant AI Agent in PythonHow to Build an Email Assistant AI Agent in PythonHow to Build an AI Meeting Notes Assistant in PythonHow to Build an AI Data Analyst in PythonHow to Build an AI Resume Screening Tool in PythonHow to Build an AI Content Classification Tool in PythonHow to Build an AI Translation App in Python

Documents, RAG and Data

9

Ground answers in your own files, databases and embeddings.

How to Build a File Search AI Agent in PythonHow to Extract Data from Documents with OpenAI and PythonHow to Extract Structured Data from PDFs with Python AIHow to Build an AI Document Summarizer in PythonHow to Create Text Embeddings with OpenAI in PythonHow to Use ChromaDB as a Vector Database in PythonHow to Build a RAG Application in PythonHow to Build an AI Text-to-SQL Application in PythonLlamaIndex Tutorial: Build a Document Q&A App in Python

Claude, Gemini and Other LLMs

12

Use other providers and local models from Python.

How to Use the Anthropic Claude API in PythonHow to Stream Claude API Responses in PythonHow to Use Tool Calling with Claude in PythonHow to Use the Google Gemini API in PythonHow to Use Gemini Function Calling in PythonHow to Use the Claude Agent SDK in PythonHow to Use Azure OpenAI in PythonOpenAI vs Claude vs Gemini for Python DevelopersHow to Switch Between LLM Providers in PythonHow to Use Local LLMs with Ollama and PythonHow to Build a Local AI Agent with Ollama and PythonHow to Use Hugging Face Models in Python

LangChain

7

Chains, tools and agents with LangChain.

How to Use LangChain in PythonHow to Build an AI Agent with LangChainHow to Use LangChain Tools in PythonHow to Add Memory to a LangChain AgentHow to Build a LangChain Chatbot with Chat HistoryLangChain LCEL Tutorial for BeginnersLangChain vs LangGraph: Which Should You Use?

LangGraph

7

Stateful, graph-based agents with LangGraph.

How to Use LangGraph in PythonHow to Build a Stateful AI Agent with LangGraphHow to Create Agent Workflows with LangGraphHow to Add Human Approval to a LangGraph AgentHow to Build a Multi-Agent Workflow with LangGraphHow to Handle Agent Errors and Retries in LangGraphHow to Build an Agentic RAG System with LangGraph

Safety and Security

4

Guardrails, prompt injection and safe tool use.

How to Add Guardrails to a Python AI ApplicationHow to Prevent Prompt Injection in Python AI AgentsHow to Protect API Keys in Python AI ApplicationsHow to Add Content Moderation to a Python AI App

Testing, Evaluation and Observability

5

Test agents, score their answers and trace every step.

How to Evaluate LLM Responses in PythonHow to Test Python AI AgentsHow to Log LLM Requests and Responses in PythonHow to Track LLM Token Usage and Cost in PythonHow to Add Observability to Python AI Agents

Reliability and Performance

5

Retries, rate limits, caching and cost control.

How to Count Tokens with tiktoken in PythonHow to Handle Rate Limits in Python LLM ApplicationsHow to Retry Failed LLM API Requests in PythonHow to Cache LLM Responses in PythonHow to Use Async LLM Calls in Python

Deploy and UI

3

Put an agent behind an API or a simple web UI.

How to Build a FastAPI API for an AI AgentHow to Build a Streamlit AI Chatbot in PythonHow to Build a Gradio AI Application in Python

Integrations and MCP

6

Connect agents to MCP servers and outside services.

How to Connect a Python AI Agent to Microsoft GraphHow to Build a SharePoint AI Assistant with PythonHow to Connect a Python AI Agent to SalesforceHow to Build an MCP Server in PythonHow to Connect a Python AI Agent to an MCP ServerModel Context Protocol (MCP) in Python: A Beginner's Guide

Questions people ask

Frequently asked questions

What is an AI agent in Python?

It is a Python program that sends a task and a list of tools to an LLM, runs the tools the model asks for, and returns the results until the model gives a final answer.

Do I need a framework like LangChain to build an AI agent?

No. A working agent is about 40 lines with the openai package. I suggest writing one by hand first, then moving to LangGraph or Pydantic AI when you need state, retries or many agents.

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

A chatbot only produces text. An agent can take actions through tools, such as looking up an order or querying a database, and it decides on its own which steps to take.

Can I run a Python AI agent without an API key?

Yes. Ollama runs open models on your own computer, and several of them support tool calling. Expect slower answers and weaker tool use than the hosted models.

How do I stop an AI agent from looping forever?

Cap the loop with a max_steps value, return a clear message when the cap is hit, and log every tool call so you can see where it got stuck.

Where can I learn more about function calling?

Start with the tutorials above, then read OpenAI’s function calling guide for the full list of options.

Ready to build your first AI agent?

Start with a single loop and two tools, then add memory, RAG and a framework one step at a time.