Introduction
In our previous lesson, we established a clear architectural distinction between static chains, dynamic routers, and autonomous agents, identifying control flow ownership as the defining characteristic. We concluded that a true autonomous agent features a runtime control flow owned by the LLM, enabling it to dynamically plan and execute steps toward a goal.
Now, we will move from concept to code. This lesson is dedicated to implementing the very engine that drives such an agent: the core observe-think-act loop. We will build this from first principles in Python, focusing on asynchronous execution. Your background in event-driven architectures and async programming will be particularly relevant here, as we'll explore why non-blocking I/O isn't just a performance optimization for agents, but a fundamental architectural requirement for building responsive and efficient systems.
The Anatomy of an Agent Loop
At its heart, an autonomous agent operates in a continuous cycle. This cycle is often referred to as the observe-think-act loop, or sometimes thought-action-observation. It's an intuitive pattern that mirrors how humans approach tasks.
Let's watch a short, clear explanation of this core concept.
Python: Create a ReAct Agent from Scratch
This video provides a great conceptual breakdown of the agent loop.
Focus on the explanation of the "thought-action-observation" cycle, from this section. The cake-baking analogy is a simple but effective way to visualize the process: you assess the situation, think about the next step, and then perform an action.
The cycle consists of three phases:
- Observe: The agent gathers information. This could be the initial user request or the output from a tool it just used (an "observation"). This information forms the current state of the world for the agent.
- Think: The agent sends the current context (including the new observation) to an LLM. The LLM's task is to reason about the state, decide what to do next, and formulate a plan. This might involve calling a tool or, if the task is complete, generating the final answer.
- Act: The agent executes the LLM's decision. If the LLM decided to use a tool, the agent calls that tool. If the LLM generated a final answer, the agent outputs it and terminates the loop. The result of the action (the tool output) becomes the observation for the next cycle.
This loop continues until the agent determines the initial goal has been met.
Why Asynchronous? The Event Loop and I/O-Bound Systems
An agent's life is dominated by waiting. It waits for the LLM to generate a response. It waits for external APIs (tools) to return data. These are I/O-bound operations. If we were to implement the agent loop synchronously, the entire process would "block" during these waits, wasting CPU cycles and freezing the application.
Asynchronous programming solves this. When an async function encounters an I/O operation (e.g., a network request), it can cede control back to the event loop. The event loop can then run other tasks while waiting for the I/O to complete. Once the operation is done, the event loop resumes the original function right where it left off.
This flowchart illustrates the process within a single thread.

For an agentic system that might eventually handle multiple concurrent user requests, this non-blocking nature is not just efficient—it's essential for scalability.
Implementing the Asynchronous Agent Loop
Now, let's translate this theory into a practical implementation. We will build a Python Agent class that encapsulates the observe-think-act loop using async/await and the OpenAI API's function-calling capability, which we explored in Module 1.
The following article provides a clean, concise, and async-native implementation that serves as an excellent blueprint.
The Agent Execution Loop: How to Build ... - Designing with AI
This guide provides a complete, from-scratch Python implementation of an asynchronous agent loop.
Read the article from the beginning, focusing on these key parts: The Agent Execution Loop section, which lays out the pseudocode and the core async def run(...) method with its while loop. The Tool Execution section, which shows how to implement the execute_tool coroutine. The Complete Example section, which puts everything together into a self-contained Agent class.
Let's break down the code from the article to see how it maps to our observe-think-act model:
- The
runmethod and thewhile Trueloop: This is the engine of our agent, continuously cycling until a final answer is produced. messages.append(...): This is the Observe phase. At the start of the loop, the user's task is added. In subsequent iterations, the results from tool calls (role: "tool") are appended, providing the agent with its new observations.await self.client.chat.completions.create(...): This is the Think phase. We make an asynchronous call to the LLM, passing the entire history of messages. Theawaitkeyword is crucial; it pauses this function and allows the event loop to work on other things while we wait for the LLM's response.if not msg.tool_calls:: This is the decision point. If the LLM's response does not contain any tool calls, it means the agent has finished its work. The loop breaks, and the text content is returned.await self.execute_tool(...): This is the Act phase. If the LLM requests a tool, we loop through thetool_callsand execute each one. Again,awaitis used because the tool itself (e.g., a web search, a database query) is likely an I/O-bound operation.
This structure is simple, yet it forms the complete backbone of an autonomous agent.
A Look Ahead: Structured Concurrency for Parallel Actions
The LLM might return a request to call multiple tools in a single turn. For example: "Search for the weather in Paris AND look up the current exchange rate for EUR to USD." These two actions are independent and can be run in parallel.
The most straightforward way to implement this in Python is using asyncio.gather. Let's see how that looks.
Building AI Agents in Pure Python - Beginner Course
This part of the video demonstrates how to run multiple async calls in parallel.
Watch the section on parallelization from this timestamp. Notice the use of async def functions and asyncio.gather to run two "guardrail" checks simultaneously.
Using asyncio.gather is a good start, but for production-grade systems, it has significant drawbacks related to error handling and resource management. If one of the parallel tasks fails, the default behavior can lead to "orphaned" tasks that continue running in the background, consuming resources and potentially causing unpredictable side effects.
Given your background in distributed systems, you'll appreciate the need for more robust concurrency control. Python 3.11 introduced a superior primitive for this: asyncio.TaskGroup.
The following article explains the problem and the solution with technical precision.
Structured Concurrency for AI Pipelines: Why asyncio.gather() Isn't ...
This article is a deep dive into the practical engineering challenges of parallel execution in agentic systems.
First, read The Three Ways gather() Fails You to understand the risks of unstructured concurrency with asyncio.gather, especially the "orphaned task problem." Then, read What Structured Concurrency Actually Gives You. This section introduces asyncio.TaskGroup and explains its key guarantee: the async with block will not exit until all tasks within it are complete, ensuring no orphans and proper error propagation via ExceptionGroup.
A TaskGroup provides structured concurrency. It creates a scope, and the program is guaranteed not to proceed past that scope until every task spawned within it has terminated. This prevents resource leaks and makes error handling far more reliable. While we won't implement a full parallel tool executor today (we'll save that for Module 6), understanding the architectural principle of structured concurrency from the outset is vital for building reliable agentic systems.
Conclusion
In this lesson, we have moved from the abstract concept of an agent to a concrete, working implementation of its core engine. You now have the foundational code and architectural understanding to build upon.
Your key takeaways are:
- The
observe-think-actcycle is the fundamental operational loop of an autonomous agent, enabling it to perceive its environment, reason about its goals, and take actions. - Asynchronous execution is not optional; it is a core architectural requirement for building efficient, scalable agents that spend most of their time waiting on I/O-bound network calls.
- We can implement a complete, asynchronous agent loop from scratch using Python's
async/awaitsyntax and a modern LLM's tool-calling capabilities. - For production systems, structured concurrency using
asyncio.TaskGroupis a more robust and reliable pattern for managing parallel operations (like multiple tool calls) than simpler primitives likeasyncio.gather.
We have built a loop that can think and act. However, the "thinking" step is still a black box. The agent decides on an action, but it doesn't explicitly show its reasoning.
In our next lesson, we will implement the ReAct (Reason+Act) pattern. This will modify our loop to make the agent's thought process transparent by interleaving explicit reasoning traces with its actions, significantly improving the agent's power and debuggability.