DEV Community

Arun Purushothaman
Arun Purushothaman

Posted on

Agents in 60 lines of python : Part 4

Conversation = Messages Array

Lesson 4 of 9 — A Tour of Agents

The entire AI agent stack in 60 lines of Python.

Last lesson's agent could loop — call a tool, check the result, call again. But ask it what you said two messages ago. It has no idea. Every call started fresh.

The fix is one line of code.


The problem

In Lesson 3, the messages array lived inside the function. Every call created a new one. When the function returned, the array was gone. No history. No memory.

This is why ChatGPT remembers your conversation — and why "New Chat" forgets. Same mechanism. One array.


The fix: make it global

Move the messages array outside the function. That's it.

Now every call to agent() reads and writes to the same list. The conversation persists across calls. The LLM sees the full history every time it thinks.


The code

conversation = [
    {"role": "system", "content": "You have tools: add(a,b) and upper(text). Use them when needed."},
]
Enter fullscreen mode Exit fullscreen mode

One list. Initialized once with a system prompt. Every message after that — appended, never cleared. New Chat in ChatGPT just means creating a new empty array.

The agent function now appends to this global list:

async def agent(user_message, max_turns=5):
    conversation.append({"role": "user", "content": user_message})
    for turn in range(max_turns):
        msg = await ask_llm(conversation)
        if not msg.get("tool_calls"):
            conversation.append({"role": "assistant", "content": msg.get("content", "")})
            return msg.get("content", "")
        conversation.append(msg)
        for tc in msg["tool_calls"]:
            result = tools[tc["function"]["name"]](**args)
            conversation.append({"role": "tool", "tool_call_id": tc["id"], "content": str(result)})
Enter fullscreen mode Exit fullscreen mode

User question goes in before the loop. Assistant answer goes in after. Tool results go in during. Every turn, the list grows.


Watch it fill up

Send "add 3 and 4" — three messages in the array (system + user + assistant).

Send "uppercase hello" — the tool runs, result comes back. Five messages now.

Send "what were the results?" — the agent reads the full history and answers correctly: "7 and HELLO." Eight messages deep, and it remembers everything.

This is what LangChain calls ConversationBufferMemory. It's a list that doesn't get cleared.


Try it

Run this code yourself at tinyagents.dev. Send multiple messages and watch the conversation array grow in real time.

Next up: Lesson 5 — Structured Output. The agent can talk and use tools. But how do you get it to return data in a specific format?


This is Lesson 4 of A Tour of Agents — a free interactive course that builds an AI agent from scratch. No frameworks. No abstractions. Just the code.

Top comments (0)