Introduction & Overview

Throughout this course, you have mastered the fundamentals of tool integration with Claude: creating tool schemas, understanding Claude's tool use responses, and executing single tool requests. However, the approach you've learned so far has a significant limitation — it only handles one tool call per conversation turn. While this works perfectly for simple tasks, many real-world problems require multiple sequential steps, and often the number and nature of these steps cannot be determined in advance.

In this lesson, we'll work together to transform Claude from a single-turn tool user into an autonomous agent capable of iterative problem-solving. We'll build an agent class that can call tools, analyze results, decide what to do next, and continue this process until complex multi-step tasks are completed. This represents a fundamental shift from reactive tool usage to proactive, intelligent problem-solving that mirrors how humans approach complex challenges.

The Action-Feedback Loop Concept

Before we start coding, let's understand how autonomous agents operate through action-feedback loops, in which each tool execution provides information that influences the next decision. This iterative process mirrors human problem-solving: we take an action, observe the result, decide what to do next, and repeat until we reach our goal. The action-feedback loop consists of four key phases that repeat until task completion:

  1. Decision Phase: Claude analyzes the current situation and determines the next action, which may include calling one or more tools.
  2. Action Phase: Our agent executes the requested tool(s) based on Claude's instructions.
  3. Feedback Phase: The results from the tool execution(s) are captured and added to the conversation history.
  4. Evaluation Phase: Claude reviews the new information, decides whether the task is complete or if additional steps are needed, and the loop continues.

This loop structure enables complex problem-solving because each iteration builds upon previous results. For example, when solving a quadratic equation, Claude might first calculate the discriminant, then use that result to determine if real solutions exist, then calculate the square root of the discriminant, and finally compute the two solutions. The key insight is that Claude doesn't need to plan all steps in advance — it can adapt its approach based on intermediate results, just like a human mathematician working through a problem.

Now let's start building our agent class to make this iterative process possible.

Setting Up Types and Interfaces

Let's begin by creating the foundation of our autonomous agent. We need to establish the core structure that will manage extended conversations, tool execution, and decision-making loops. We'll start by defining the types that will shape our agent's configuration:

import Anthropic from "@anthropic-ai/sdk";

export interface AgentOptions {
  name: string;
  systemPrompt?: string;
  model?: string;
  tools?: Record<string, Function>;
  toolSchemas?: Anthropic.Tool[];
  maxTurns?: number;
}

The AgentOptions interface defines the flexible configuration system for our agent:

  • name: Provides a clear identifier for the agent, useful for debugging, logging, and when working with multiple agents in complex systems.
  • systemPrompt: Optional custom instructions that will be combined with our base prompt to allow for domain-specific behavior.
  • model: Specifies which Claude model to use for agent interactions.
  • tools and toolSchemas: Accept any compatible object/array inputs for convenience, allowing agents to be created with or without tool capabilities.
  • maxTurns: Prevents infinite loops by limiting the number of iterative steps.

By using optional properties (marked with ?), we enable flexible agent creation while preparing for safe defaults in the constructor.

Defining the Agent Class Structure

Now let's define our Agent class with its base system prompt and instance properties:

export class Agent {
  // Base system prompt to be used for all agents
  private static BASE_SYSTEM_PROMPT = 
    "You are an autonomous agent that can take multiple tool-calling steps when helpful. " +
    "The user only sees your response when you stop using tools, not your tool usage or reasoning steps. " +
    "When you provide your answer without calling tools, make it complete and standalone.\n" +
    "Additional instructions:\n";

  private client: Anthropic;
  public name: string;
  private model: string;
  private systemPrompt: string;
  private maxTurns: number;
  private tools: Record<string, Function>;
  private toolSchemas: Anthropic.Tool[];
}

The class structure establishes key design decisions that enable autonomous behavior:

  • BASE_SYSTEM_PROMPT: A static constant that explicitly tells Claude it can make multiple tool calls and that users won't see the intermediate steps — only the final result. This is crucial for autonomous behavior, as it sets the expectation that Claude should continue iterating until it reaches a complete answer.
  • Private properties: Most properties are private to encapsulate internal state and prevent external interference with the agent's configuration. The client, model, systemPrompt, maxTurns, tools, and toolSchemas properties are implementation details that shouldn't be accessed directly.
  • Public name: The only public property provides a clear identifier for external systems to reference the agent without exposing its internal configuration.
Implementing the Constructor

Next, let's implement the constructor that brings our agent to life with sensible defaults and proper initialization:

constructor({
  name,
  systemPrompt = "You are a helpful assistant.",
  model = "claude-sonnet-4-6",
  tools = {},
  toolSchemas = [],
  maxTurns = 10,
}: AgentOptions) {
  this.client = new Anthropic();
  this.name = name;
  this.model = model;
  this.systemPrompt = Agent.BASE_SYSTEM_PROMPT + systemPrompt;
  this.maxTurns = maxTurns;

  // Copy to isolate from external mutation
  this.tools = { ...tools };
  this.toolSchemas = [...toolSchemas];
}

The constructor handles initialization with careful attention to safety and flexibility:

  • Default parameters: Provide sensible defaults for all optional properties, ensuring the agent can be created with minimal configuration while still being production-ready.
  • System prompt composition: Combines BASE_SYSTEM_PROMPT with the custom systemPrompt to ensure all agents have autonomous capabilities while allowing domain-specific customization.
  • Defensive copying: Uses spread operators ({ ...tools } and [...toolSchemas]) to create independent copies of the tools and schemas. This prevents external mutations from affecting the agent and ensures each agent instance has its own isolated registry.
  • Empty defaults: The tools = {} and toolSchemas = [] defaults allow agents to be created without tool capabilities, making the class flexible for different use cases.

This architecture separates concerns cleanly while preparing us to implement the core functionality that will make our agent truly autonomous.

Adding Helper Methods for State Management

As our agent works through complex problems, we need to manage conversation state properly. Let's add two essential helper methods that will support our main loop:

private extractText(content: Anthropic.ContentBlock[]): string {
  // Return a joined string of all text blocks from content
  return content
    .filter(block => block.type === "text")
    .map(block => (block as Anthropic.TextBlock).text)
    .join("");
}

private buildRequestArgs(messages: Anthropic.MessageParam[]): Anthropic.Messages.MessageCreateParams {
  // Create an object with the basic request arguments
  const requestArgs: Anthropic.Messages.MessageCreateParams = {
    model: this.model,
    system: this.systemPrompt,
    messages: messages,
    max_tokens: 8000,
  };

  // Add tool schemas only if they exist
  if (this.toolSchemas.length > 0) {
    requestArgs.tools = this.toolSchemas;
  }

  // Return the complete set of arguments to use for the API call
  return requestArgs;
}

These helper methods might seem simple, but they're essential for maintaining a clean separation between the complex orchestration logic we're about to write and the details of message handling:

  • extractText: Safely extracts and combines text blocks from Claude's responses, which could contain one or more text blocks mixed with other content like tool use blocks. We use .filter() to identify text blocks and .map() to extract their content, with a type assertion to access the text property. This ensures we return clean, readable final responses to users.

  • buildRequestArgs: Centralizes how we construct API requests, ensuring consistent parameters across all agent interactions. Notice how we conditionally include tool schemas — this prevents API errors when we create agents without tools while still supporting full tool integration when needed.

These helper methods might seem simple, but they're essential for maintaining a clean separation between the complex orchestration logic we're about to write and the details of message handling.

Implementing Tool Execution
Building the Core Loop - Part 1: Understanding Stateless Design

Now we're ready to implement the heart of our autonomous agent: the run method. This method will manage the iterative loop that enables multi-step problem-solving. Let's start by understanding how our agent handles conversation state:

public async run(inputMessages: Anthropic.MessageParam[]): Promise<[Anthropic.MessageParam[], string]> {
  // Create a copy of the input messages to avoid modifying the original
  const messages = [...inputMessages];
}

The spread operator [...inputMessages] is important because it ensures our agent remains stateless. Just like normal LLM API calls where you pass the complete conversation history each time, our agent doesn't store any conversation state between calls. Each time you call agent.run(), you provide the full context through inputMessages, and the agent processes only that specific conversation without any memory of previous interactions.

By copying the input messages instead of modifying them directly, we preserve the original conversation and allow the same agent instance to handle multiple independent conversations. This design also gives you complete control over context management — you can decide exactly what conversation history to include, filter out irrelevant messages, or combine conversations as needed before passing them to the agent.

Building the Core Loop - Part 2: Setting Up the Iteration

Now let's add the basic loop structure that will enable our agent's iterative problem-solving:

public async run(inputMessages: Anthropic.MessageParam[]): Promise<[Anthropic.MessageParam[], string]> {
  // Create a copy of the input messages to avoid modifying the original
  const messages = [...inputMessages];

  // Initialize turn counter to track iterations
  let turn = 0;

  // Loop until the model returns a final answer or the max turns is reached
  while (turn < this.maxTurns) {
    // Increment the turn
    turn++;

    // Ask the model for a response
    const response = await this.client.messages.create(this.buildRequestArgs(messages));

    // Add Claude's response to messages exactly as returned (text + tool_use blocks)
    messages.push({ role: "assistant", content: response.content });
  }
}

We're starting with a controlled loop that will continue until Claude provides a final answer or we reach our maximum turn limit. Each iteration represents one complete action-feedback cycle where Claude makes a decision (potentially including tool calls), and we capture that decision in our conversation history. The turn counter prevents infinite loops while allowing sufficient iterations for complex problems.

Note that we use await for the API call since the Anthropic SDK methods are asynchronous, and we declare the method as async to support this.

Building the Core Loop - Part 3: Handling Tool Calls

Now let's add the logic for handling tool calls within our loop. This is where the magic of autonomous behavior happens:

public async run(inputMessages: Anthropic.MessageParam[]): Promise<[Anthropic.MessageParam[], string]> {
  // Create a copy of the input messages to avoid modifying the original...

  // Loop until the model returns a final answer or the max turns is reached
  while (turn < this.maxTurns) {
    // Increment the turn...
    // Ask the model for a response...
    // Add Claude's response to messages...
    
    // Check if Claude wants to use any tools
    if (response.stop_reason === "tool_use") {
      // Initialize an array to store tool results
      const toolResults: Anthropic.ToolResultBlockParam[] = [];
      
      // Execute each tool use
      for (const contentItem of response.content) {
        // Check if the content item is a tool use
        if (contentItem.type === "tool_use") {
          // Execute the tool with the given input
          const toolResult = this.callTool(contentItem);
          // Add result to tool results array
          toolResults.push(toolResult);
        }
      }

      // Add all tool results to messages
      messages.push({
        role: "user",
        content: toolResults
      });
    }
  }
}

When Claude decides to use tools, we handle the execution through a systematic process:

  1. Execute all requested tools: Claude might call multiple tools in a single turn, and we need to execute each one to gather all the information it needs for its next decision.

  2. Collect results systematically: We iterate through all content items in Claude's response, identify tool use blocks, and execute each tool while collecting the results in an array.

  3. Feed results back as a user message: By adding the tool results as a "user" message, we maintain the proper conversation flow that Claude expects, ensuring the results become part of the context for the next iteration.

Each tool result influences Claude's subsequent reasoning, allowing it to build upon what it just learned and make more informed decisions in the next turn.

Building the Core Loop - Part 4: Managing Flow Control

Finally, let's complete our loop with the logic for handling final responses and error conditions:

public async run(inputMessages: Anthropic.MessageParam[]): Promise<[Anthropic.MessageParam[], string]> {
  // Create a copy of the input messages to avoid modifying the original...

  // Loop until the model returns a final answer or the max turns is reached
  while (turn < this.maxTurns) {
    // Increment the turn...
    // Ask the model for a response...
    // Add Claude's response to messages...
    
    // Check if Claude wants to use any tools
    if (response.stop_reason === "tool_use") {
      // Execute each tool use and add results to messages...
    } else {
      // Extract the text from the response
      const responseText = this.extractText(response.content);

      // Return the agent history and final output
      return [messages, responseText];
    }
  }

  // If the max turns is reached, throw an exception
  throw new Error("Max turns reached");
}

When Claude reaches a final answer, we handle the completion through a structured return process:

  1. Detect completion: When Claude doesn't want to use tools (indicated by a different stop_reason), it signals that it has reached a final answer and no further iterations are needed.

  2. Extract clean response: We use our extractText helper to pull out the readable text content from Claude's response, filtering out any non-text blocks.

  3. Return complete state: We return both the full conversation history (messages) and the final response text (responseText) to maintain our stateless design — the caller receives everything needed to understand what happened and can use the conversation history for follow-up questions or multi-turn interactions.

  4. Safety net for runaway loops: The error for reaching max turns prevents infinite loops if something goes wrong. You can control this limit through the maxTurns parameter, or alternatively implement a mechanism to force Claude to provide a final answer when approaching the limit rather than throwing an error.

This dual return approach reinforces our stateless architecture by giving the caller complete control over conversation state while providing both the detailed interaction history for continued conversations and the clean final answer for immediate use.

Complete Run Method

Here's how our complete run method looks when put together:

public async run(inputMessages: Anthropic.MessageParam[]): Promise<[Anthropic.MessageParam[], string]> {
  // Create a copy of the input messages to avoid modifying the original
  const messages = [...inputMessages];
  
  // Initialize turn counter to track iterations
  let turn = 0;

  // Loop until the model returns a final answer or the max turns is reached
  while (turn < this.maxTurns) {
    // Increment the turn
    turn++;

    // Ask the model for a response
    const response = await this.client.messages.create(this.buildRequestArgs(messages));

    // Add Claude's response to messages exactly as returned (text + tool_use blocks)
    messages.push({ role: "assistant", content: response.content });

    // Check if Claude wants to use any tools
    if (response.stop_reason === "tool_use") {
      // Initialize an array to store tool results
      const toolResults: Anthropic.ToolResultBlockParam[] = [];
      
      // Execute each tool use
      for (const contentItem of response.content) {
        // Check if the content item is a tool use
        if (contentItem.type === "tool_use") {
          // Execute the tool with the given input
          const toolResult = this.callTool(contentItem);
          // Add result to tool results array
          toolResults.push(toolResult);
        }
      }

      // Add all tool results to messages
      messages.push({
        role: "user",
        content: toolResults
      });
  
    } else {
      // Extract the text from the response
      const responseText = this.extractText(response.content);

      // Return the agent history and final output
      return [messages, responseText];
    }
  }

  // If the max turns is reached, throw an exception
  throw new Error("Max turns reached");
}
Testing Our Autonomous Agent

Now let's put our agent to work! We'll create a math-focused autonomous agent and see how it handles a complex quadratic equation. We'll provide more math tools following the same pattern used across the course, so you can easily extend your agent's capabilities as needed:

import fs from 'fs';
import { Agent } from './agent';
import { 
  sumNumbers,
  multiplyNumbers,
  subtractNumbers,
  divideNumbers,
  power,
  squareRoot
} from './functions';

// Load the schemas from JSON file
const schemasJson = fs.readFileSync('schemas.json', 'utf-8');
const toolSchemas = JSON.parse(schemasJson);

// Create a map of tool names to functions
const tools: Record<string, Function> = {
  "sum_numbers": sumNumbers,
  "multiply_numbers": multiplyNumbers,
  "subtract_numbers": subtractNumbers,
  "divide_numbers": divideNumbers,
  "power": power,
  "square_root": squareRoot
};

// Create a stateless autonomous agent
const agent = new Agent({
  name: "math_assistant",
  systemPrompt: "You are a helpful math assistant.",
  model: "claude-sonnet-4-6",
  tools: tools,
  toolSchemas: toolSchemas,
  maxTurns: 15
});

// Initialize conversation with user message
const messages: any[] = [{ role: "user", content: "Solve this equation: 2x² - 7x + 3 = 0" }];

// Send message to the stateless agent
const [finalMessages, result] = await agent.run(messages);

// Display the response
console.log("\nFinal response:");
console.log(result);

When we run this code, our agent demonstrates sophisticated autonomous reasoning:

🔧 Tool called: power({"base":-7,"exponent":2})
🔧 Tool called: multiply_numbers({"a":4,"b":2})
🔧 Tool called: multiply_numbers({"a":8,"b":3})
🔧 Tool called: subtract_numbers({"a":49,"b":24})
🔧 Tool called: square_root({"number":25})
🔧 Tool called: multiply_numbers({"a":2,"b":2})
🔧 Tool called: sum_numbers({"a":7,"b":5})
🔧 Tool called: divide_numbers({"a":12,"b":4})
🔧 Tool called: subtract_numbers({"a":7,"b":5})
🔧 Tool called: divide_numbers({"a":2,"b":4})

Final response:
The solutions to the equation 2x² - 7x + 3 = 0 are:

**x = 3** and **x = 0.5** (or x = 1/2)

Here's how I solved it using the quadratic formula:
- First, I calculated the discriminant: b² - 4ac = (-7)² - 4(2)(3) = 49 - 24 = 25
- Since the discriminant is positive, we have two real solutions
- The square root of 25 is 5
- Using x = (-b ± √(b² - 4ac)) / (2a):
  - x₁ = (7 + 5) / 4 = 12/4 = 3
  - x₂ = (7 - 5) / 4 = 2/4 = 0.5

You can verify: 2(3)² - 7(3) + 3 = 18 - 21 + 3 = 0 ✓
And: 2(0.5)² - 7(0.5) + 3 = 0.5 - 3.5 + 3 = 0 ✓

Our agent systematically applied the quadratic formula by calculating b² ((-7)²), computing 4ac (4×2×3), finding the discriminant (49-24), taking the square root (√25), and finally calculating both solutions through the complete quadratic formula. Each tool call built upon previous results, demonstrating true autonomous reasoning. The agent made 10 tool calls across multiple conversation turns, yet the user only sees the final, complete answer with verification.

Summary & Practice Preparation

Together, we've successfully built an autonomous agent capable of complex, multi-step problem-solving. Our agent class encapsulates conversation management, tool execution, and iterative decision-making in a reusable structure that can tackle problems requiring dozens of sequential operations.

The architecture we created enables Claude to operate as a true autonomous agent: it can assess situations, make decisions, execute tools, learn from results, and continue iterating until complex tasks are completed. This represents a fundamental advancement from simple tool usage to intelligent, adaptive problem-solving.

In the upcoming practice exercises, you'll implement your own autonomous agents, experiment with different system prompts and tool combinations, and tackle increasingly complex multi-step problems. You'll gain hands-on experience with the debugging and optimization techniques needed for production agent systems, building upon the solid foundation we've created together.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal