# Python for AI Agents: The Basics to Read the Code (Part 0)

> The Python for AI agents you actually need to read the code: dicts, functions, type hints, loops, async, and setup — explained simply for beginners.

*Source: https://www.infowok.com/ai-agents-from-scratch-python-part-0/ · Sukhveer Kaur · Published June 18, 2026 · Updated July 6, 2026*

---

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](/what-are-ai-agents-complete-guide-2026/) 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.

<Prerequisites>

- Python 3.10+ installed and the ability to run a `.py` file — new to that? The [official Python tutorial](https://docs.python.org/3/tutorial/) gets you there
- That's the whole list. If you can follow a function, a list, and a loop, you're ready — this primer names the rest as you meet it

</Prerequisites>

<KeyTakeaways>

- **You don't need to master Python to read agent code** — you need to recognise the handful of patterns agents are built from.
- **Every agent message is just dicts, lists, and JSON;** tools are functions described by type hints and Pydantic.
- **Control flow (loops, conditionals, exceptions) *is* the agent loop;** async and decorators are mostly what frameworks add on top.
- **Set up a venv, pip, and API keys once** and you can run every example in the series.

</KeyTakeaways>

## 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.

![A map linking five groups of Python concepts to where each one appears in AI agent code, from data shapes to setup](./ai-agents-from-scratch-python-part-0-map.svg)

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.

```python
messages = [
    {"role": "system", "content": "You are a helpful agent."},
    {"role": "user", "content": "What's the weather in Delhi?"},
]
```

![An annotated agent messages list showing the outer list, each dictionary, the key-value pairs, and the text the model reads](./ai-agents-from-scratch-python-part-0-decoder.svg)

**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:

```python
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](/pydantic-ai-tutorial-type-safe-agents-python/) shows it in a full agent, and the [Pydantic docs](https://docs.pydantic.dev/latest/) 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.

```python
while True:
    response = client.chat.completions.create(
        model="gpt-5.4-mini", messages=messages,
    )
    reply = response.choices[0].message
    if not reply.tool_calls:          # no tool needed → we're done
        break
    for 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:

```python
async def main():
    response = await client.chat.completions.create(
        model="gpt-5.4-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.

<Callout type="note">

You don't need to **master** Python to build agents — you need to **read** it comfortably. If you can follow a dict, a function with type hints, and a for-loop, you know enough to start; pick up the rest as you hit it.

</Callout>

## 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.

```bash
python -m venv .venv
source .venv/bin/activate
pip install openai python-dotenv
```

Then read the key from the environment instead of pasting it in:

```python
import os
api_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](https://docs.python.org/3/library/venv.html) 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)](/build-agentic-ai-app-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.

<NextSteps>

- **Still fuzzy on what an agent is?** Read [What are AI agents?](/what-are-ai-agents-complete-guide-2026/) first.
- **Ready to write code?** [Build an Agentic AI App in Python (Part 1)](/build-agentic-ai-app-python-part-1/) puts these basics into a running agent.
- **Prefer the no-framework path?** Continue this series with [From Scratch, Part 1](/ai-agents-from-scratch-python-part-1/).

</NextSteps>
