You can build an AI agent without being a Python expert. But you do have to read Python — and most beginners stall not because agents are hard, but because the code uses a handful of patterns nobody stopped to explain. This primer fixes that. It is the Python for AI agents you actually need: the exact syntax, libraries, and structures you will meet in every agent file.
I came to agents from a Python and Java background, and even then a few things tripped me up the first time — type hints on a function the model was supposed to “call,” async def on every example, a dictionary that turned out to be the agent’s entire memory. None of it is advanced. It just needs naming once.
If the idea of an agent itself is still fuzzy, read what AI agents actually are first, then come back. By the end of this short read, you will be able to open any agent script in the rest of this series and follow what each line is doing.
Python for AI Agents: Read It, Don’t Master It
The single most useful mindset for this series is recognition over recall — you need to recognise the syntax when you see it, not write it from a blank page. That is a much lower bar, and it is the right one. Reading code you did not write is a real skill, and it is the one agent development actually demands: most of your early time is spent following examples, not inventing patterns. If you are already comfortable with Python, skip straight to Part 1; nothing here will be new.
The map above is the whole primer in one picture: five small groups of Python, and where each one shows up in agent code. The rest of this post walks through them in order, with the exact lines you will read later.
Dicts, Lists, and JSON: The Shape of Every Agent Message
Almost everything an agent says or hears travels as a list of dictionaries. A dictionary (dict) is a set of "key": value pairs in curly braces; a list is an ordered collection in square brackets. Stack them together and you get the messages list — the structure that holds an entire conversation.
messages = [{"role": "system", "content": "You are a helpful agent."},{"role": "user", "content": "What's the weather in Delhi?"},]
That list is the agent’s whole short-term memory — there is no hidden state behind it. It is also valid JSON (JavaScript Object Notation), the text format APIs use to send data. In Python you convert between the two with json.dumps (object to text) and json.loads (text to object), which you will do every time a tool returns a result.
Functions, Type Hints, and Pydantic: How Tools Describe Themselves
When an agent “uses a tool,” that tool is just a Python function — a named block of reusable code. What makes it agent-ready is the labels on it. A type hint tells Python (and the model) what kind of value each input is:
def get_weather(city: str) -> dict:"""Return the current weather for a city."""...
Here city: str says the input is a string, and -> dict says the function returns a dictionary. Agent frameworks read these hints to tell the model exactly how to call your function. For richer shapes, you will meet Pydantic — a library that defines and validates structured data through a class called BaseModel. It is worth recognising because modern agent code leans on it heavily; my Pydantic AI tutorial shows it in a full agent, and the Pydantic docs are the reference. You do not need to master classes to read one.
Loops, Conditionals, and Exceptions: An Agent’s Control Flow
An agent is, at heart, a loop that keeps going until the job is done. You will read three control-flow patterns constantly. A while loop repeats; an if statement branches; and try/except catches errors so one failed tool call does not crash everything.
while True:response = client.chat.completions.create(model="gpt-4o-mini", messages=messages,)reply = response.choices[0].messageif not reply.tool_calls: # no tool needed → we're donebreakfor call in reply.tool_calls:try:result = run_tool(call.function.name, call.function.arguments)except Exception as error:result = f"Tool failed: {error}"messages.append({"role": "tool", "content": result})
That client.chat.completions.create(...) line is the real OpenAI SDK call you will see everywhere; client is the SDK client you set up at the end of this post, and run_tool is your own function that runs the chosen tool (Part 3 builds it). You do not need to follow every line yet — just recognise the skeleton. One gotcha to file away: a loop with no stop condition runs forever and burns API credits, so real agents always cap the number of steps.
Async and Decorators: What Frameworks Add
The moment you add a framework, two new pieces of syntax appear. The first is async. Many LLM SDKs are asynchronous, meaning they can wait for a slow network reply without freezing the program. You will read async def on functions and await before calls:
async def main():response = await client.chat.completions.create(model="gpt-4o-mini", messages=messages,)asyncio.run(main())
The second is the decorator — a line starting with @ that wraps a function to give it extra powers, like @tool to register a tool or @app.get("/") for a web route. You will not write decorators of your own for a while; you will mostly apply ones the framework gives you. My honest advice: learn to read async before you try to write it, because the examples assume it long before you will need to author it yourself. Recognising these two symbols removes most of the “why does this look strange?” friction, and it is the difference between feeling lost in a framework’s quickstart and following it line by line.
Setup: venv, pip, and API Keys
Before any of this runs, you need three setup habits. A virtual environment keeps each project’s packages separate, pip installs those packages, and an environment variable stores your API key without writing it into the code.
python -m venv .venvsource .venv/bin/activatepip install openai python-dotenv
Then read the key from the environment instead of pasting it in:
import osapi_key = os.getenv("OPENAI_API_KEY")
The most common beginner mistake I see is hardcoding the key in the script and pushing it to GitHub, where bots scrape it within minutes and can run up a real bill on your account. Keep it in a .env file, load it with python-dotenv, and add .env to .gitignore so it never leaves your machine. These three habits take five minutes to set up once and save you from the two problems that derail more beginners than any agent bug. The official Python venv guide covers environments in depth if you want more.
Frequently Asked Questions
Do I need to memorise all of this? No. Bookmark this page and glance back when a symbol confuses you. After two or three parts, recognition becomes automatic.
Is plain Python really enough, with no machine learning? Yes, to build agents in 2026 you call hosted models through an API. You do not train anything, so no linear algebra or ML theory is required to start.
What if I only know another language, like Java or JavaScript? You will be fine. The concepts here — dicts, lists, functions, loops — exist in every language; only the syntax differs, and that is quick to absorb.
Conclusion
Python for AI agents comes down to five small things: the messages list of dicts, functions with type hints, the loop-and-branch control flow, the async and decorator syntax frameworks add, and a clean setup with a virtual environment and an API key. Recognise those, and the rest of this series reads like plain English. This primer will not make you a Python expert, and it does not need to — building will do that.
Which of these five tripped you up the most when you first saw agent code? Tell me in the comments — it helps me sharpen the next parts.
Read next: Build an Agentic AI App in Python (Part 1). It puts these basics to work in real, running code — and the next entry in this from-scratch series takes you there one LLM call at a time.








