Course contentsShow
← Machine Learning and Deep Learning
Lesson 2070 of 3,53844. AI Agents: FoundationsFree lesson

Implementing a Basic Agent Loop

Build a minimal agent in code: loop over LLM calls, parse actions, execute tools, update state, and check termination.

Implementing a Basic Agent Loop

You'll learn how to build a minimal agent that loops over LLM calls, executes tools, and updates state until it reaches a goal.

The Core Idea

An agent loop is the engine that brings together everything you've learned: it repeatedly asks the LLM to reason (ReAct pattern), parses the LLM's chosen action, executes the corresponding tool, observes the result, updates the agent's state, and checks if we're done. Think of it like a chess player who thinks about their next move, makes that move, observes the board state, and decides whether the game is over.

Basic Loop Structure

def agent_loop(query, tools, max_iterations=10):
    state = {"query": query, "history": []}
    
    for i in range(max_iterations):
        # 1. Call LLM with current state
        prompt = build_agent_prompt(state, tools)
        response = llm_call(prompt)
        
        # 2. Parse action and input
        action, action_input = parse_action(response)
        
        # 3. Check termination
        if action == "Final Answer":
            return action_input
        
        # 4. Execute tool
        observation = tools[action].execute(action_input)
        
        # 5. Update state
        state["history"].append({
            "thought": response,
            "action": action,
            "observation": observation
        })
    
    return "Max iterations reached"

This loop maintains state (the conversation history), makes decisions (which tool to call), takes actions (executes tools), receives observations (tool outputs), and checks termination conditions (Final Answer or max iterations).

Key Takeaway: A basic agent loop is a cycle of LLM reasoning → action parsing → tool execution → state update → termination check, repeating until the agent solves the task or hits a limit.