Back to Blog

Build AI Apps with Python: AI Agent Loop — Chain Multiple Tools | Episode 10

Celest KimCelest Kim

Video: Build AI Apps with Python: AI Agent Loop — Chain Multiple Tools | Episode 10 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Build AI Apps with Python: AI Agent Loop — Chain Multiple Tools

In this episode, we create an AI agent loop that allows Claude to plan and execute multi-step workflows by calling multiple tools repeatedly until the task is complete. Instead of a single call and response, Claude dynamically decides the next action based on the full conversation history, enabling complex task automation like file creation, reading, and summarization.

Code

import time

# Simulated tools for the agent to use
def create_file(filename, content):
  with open(filename, 'w') as f:
    f.write(content)
  return f"File '{filename}' created."

def read_file(filename):
  with open(filename, 'r') as f:
    return f.read()

def list_files():
  import os
  return os.listdir('.')

def summarize(text):
  # Placeholder for a real summarization tool
  return text[:75] + ('...' if len(text) > 75 else '')

# Agent loop that lets Claude plan and execute multiple steps
def agent_loop(goal, tools):
  messages = [{"role": "system", "content": f"Your goal is: {goal}"}]
  step = 0

  while True:
    step += 1
    # Claude decides next action based on conversation history
    # Here we simulate Claude's decision logic for demonstration
    if step == 1:
      # Step 1: create a file
      tool_result = tools['create_file']('example.txt', 'This is a test file.')
      messages.append({"role": "assistant", "content": "Create file 'example.txt' with content."})
      messages.append({"role": "tool_result", "content": tool_result})

    elif step == 2:
      # Step 2: read the file back
      tool_result = tools['read_file']('example.txt')
      messages.append({"role": "assistant", "content": "Read file 'example.txt'."})
      messages.append({"role": "tool_result", "content": tool_result})

    else:
      # Task complete
      print("Task completed.")
      break

    # Simulate delay and print conversation history for clarity
    time.sleep(1)
    print(f"Step {step} messages:")
    for msg in messages[-2:]:
      print(f"{msg['role']}: {msg['content']}")

# Define available tools
tools = {
  'create_file': create_file,
  'read_file': read_file,
  'list_files': list_files,
  'summarize': summarize,
}

# Run the agent loop with a goal
agent_loop("Create a file and verify its contents", tools)

Key Points

  • The agent loop uses a while True structure to repeatedly call tools until the task is finished.
  • Claude appends both its own messages and tool results to the conversation history each iteration.
  • By seeing the full history, Claude dynamically decides the next step in a multi-tool workflow.
  • This approach enables chaining multiple tool calls for complex, multi-step tasks without manual intervention.
  • Tracking the step count helps manage progress and determine when to exit the loop.