From the free course Start building with Claude on Lykke

Building with Claude Managed Agents

Key concepts: Autonomous Agents · Managed Workflows · Agentic Design

Leveraging fully managed autonomous agents for complex, multi-step task completion.

Building with Claude Managed Agents

The transition from Large Language Models (LLMs) as stateless text predictors to Managed Agents represents a fundamental shift in AI engineering. In a traditional request-response cycle, the developer is responsible for the "outer loop"—handling state, managing tool calls, and re-injecting results into the context. Managed Agents invert this relationship. By utilizing Claude’s native ability to reason, plan, and execute multi-step trajectories, developers can delegate the orchestration of complex tasks to the model itself.

This article explores the architectural underpinnings of Claude Managed Agents, the mechanics of agentic workflows, and the rigorous engineering required to deploy autonomous systems in production environments.

AI_IMAGEI_IMAGE## The Theoretical Foundation: From Inference to Agency

At its core, a standard LLM call is an approximation of the conditional probability $P(y | x)$, where $x$ is the prompt and $y$ is the completion. However, an Agentic Workflow treats the model as a policy $\pi$ in a partially observable Markov decision process (POMDP). The goal is no longer just a single output, but a trajectory $T$:

$$T = { (s_0, a_0, o_0), (s_1, a_1, o_1), \dots, (s_n, a_n, o_n) }$$

Where:

  • $s_t$ is the state (the conversation history and internal reasoning).
  • $a_t$ is the action (a tool call or a final response).
  • $o_t$ is the observation (the result of the tool execution).

Definition: Managed Agency Managed Agency is a high-level abstraction where the infrastructure provider (Anthropic) manages the loop of $s_t \to a_t \to o_t$. The developer defines the tools and the objective, while the managed service handles the iterative reasoning and state persistence required to reach the terminal state $s_n$.

The ReAct Paradigm

Claude Managed Agents primarily utilize the ReAct (Reason + Act) framework. Instead of jumping directly to an action, the model generates a "Thought" block. This internal monologue serves as a latent space for planning, allowing the model to decompose complex goals into atomic sub-tasks.

Component Function Managed Agent Implementation
Reasoning Decomposing goals into sub-tasks. Claude's internal "Thought" tokens and Extended Thinking blocks.
Acting Interacting with the external world. Structured tool_use blocks mapped to developer-defined APIs.
Observing Processing feedback from actions. tool_result blocks injected back into the model's context window.
Orchestration Managing the loop and state. Handled by the Managed Agents infrastructure to reduce overhead.

The Managed Agent Architecture

Building with managed agents requires understanding the interplay between the Messages API, Tool Definitions, and the Model Family. While Claude 3.5 Sonnet is often the "sweet spot" for agentic tasks due to its balance of speed and reasoning, Claude 3.5 Opus provides the higher-order logic necessary for extremely ambiguous or high-stakes planning.

Low-Level Implementation: The Agentic Loop

The following Python implementation demonstrates the manual construction of an agentic loop. In a "Managed" context, much of this logic is abstracted, but understanding the underlying state machine is critical for senior engineers.

import anthropic
import json

class ManagedAgentSimulator:
    def __init__(self, model="claude-3-5-sonnet-20241022", tools=None):
        self.client = anthropic.Anthropic()
        self.model = model
        self.tools = tools or []
        self.history = []

    def run(self, user_goal: str):
        self.history.append({"role": "user", "content": user_goal})
        
        while True:
            # The model decides whether to think, use a tool, or finish
            response = self.client.messages.create(
                model=self.model,
                max_tokens=4096,
                tools=self.tools,
                messages=self.history
            )
            
            self.history.append({"role": "assistant", "content": response.content})
            
            # Check for tool use requests
            tool_use_blocks = [b for b in response.content if b.type == "tool_use"]
            
            if not tool_use_blocks:
                # Terminal state reached: No more tools to call
                return response.content

            # Execute tools and append results to history
            for tool_call in tool_use_blocks:
                result = self.execute_tool(tool_call.name, tool_call.input)
                self.history.append({
                    "role": "user",
                    "content": [
                        {
                            "type": "tool_result",
                            "tool_use_id": tool_call.id,
                            "content": json.dumps(result),
                        }
                    ],
                })

    def execute_tool(self, name, args):
        # Logic to route to actual Python functions or API calls
        print(f"[*] Executing {name} with {args}")
        return {"status": "success", "data": "Sample observation"}

Tool Use: The Agent’s Sensory-Motor System

For an agent to be "autonomous," it must have a well-defined interface with the environment. This is achieved through Tool Use (also known as function calling). In the Claude ecosystem, tools are defined using JSON Schema.

Tool Definition Schema

A tool definition must be precise. Ambiguity in the description leads to "hallucinated parameters" or incorrect tool selection.

# Example Tool Configuration for a Financial Agent
tools:
  - name: "get_stock_price"
    description: "Retrieves the real-time stock price for a given ticker symbol."
    input_schema:
      type: "object"
      properties:
        ticker:
          type: "string"
          description: "The stock ticker symbol (e.g., AAPL, MSFT)."
        currency:
          type: "string"
          enum: ["USD", "EUR", "GBP"]
          default: "USD"
      required: ["ticker"]

  - name: "execute_trade"
    description: "Places a buy or sell order. Requires explicit user confirmation."
    input_schema:
      type: "object"
      properties:
        action:
          type: "string"
          enum: ["BUY", "SELL"]
        quantity:
          type: "integer"
          minimum: 1
      required: ["action", "quantity"]

The Importance of "Thinking" Blocks

In recent updates, Claude has introduced Extended Thinking (or Adaptive Thinking). This allows the model to allocate more compute to the "Reasoning" phase before emitting a tool call.

Theorem: The Compute-Optimal Agent The performance of an agent $P_{agent}$ is a function of its base reasoning capability $R$ and the thinking budget $B$ allocated per step: $P_{agent} \propto R \times \log(B)$. For complex multi-step tasks, increasing the thinking budget is often more effective than increasing the number of tool calls.

Managed Workflows vs. Custom Orchestration

Engineers must choose between using Anthropic's managed agent features or building a custom orchestration layer (e.g., using LangGraph or Haystack).

Feature Managed Agents (Anthropic) Custom Orchestration (Self-Built)
State Management Automatic; handled via API session. Manual; requires Redis/Postgres for history.
Latency Optimized via internal routing. Higher due to multiple round-trips.
Flexibility Limited to Claude's native logic. Full control over loop logic (e.g., DAGs).
Context Caching Native support; reduces cost of long loops. Must be manually implemented via headers.
Security Standardized sandbox for tool execution. Developer must secure the execution environment.

Advanced Concept: Context Management and Caching

One of the primary bottlenecks in agentic workflows is the accumulating context. As the agent performs more steps, the history grows, leading to:

  1. Increased Latency: More tokens for the model to process.
  2. Increased Cost: Every step bills for the entire preceding history.

To solve this, Claude Managed Agents utilize Prompt Caching. By marking the tool definitions and the initial system prompt as "cacheable," the model can skip the expensive pre-computation of these static elements.

Real-World API Invocation with Caching

This curl example demonstrates how to invoke a managed agent step while utilizing prompt caching to minimize costs during a long-running task.

curl https://api.anthropic.com/v1/messages \
     -H "x-api-key: $ANTHROPIC_API_KEY" \
     -H "anthropic-beta: prompt-caching-2024-07-31" \
     -H "content-type: application/json" \
     -d '{
       "model": "claude-3-5-sonnet-20241022",
       "max_tokens": 1024,
       "system": [
         {
           "type": "text",
           "text": "You are a senior research agent...",
           "cache_control": {"type": "ephemeral"} 
         }
       ],
       "messages": [
         {"role": "user", "content": "Analyze the last 10 years of semiconductor trends."}
       ],
       "tools": [
         {
           "name": "search_archive",
           "description": "Access historical data...",
           "input_schema": { ... },
           "cache_control": {"type": "ephemeral"}
         }
       ]
     }'

Evaluation and Safety: The "Agentic Sandbox"

Deploying an autonomous agent introduces risks that standard chatbots do not face. An agent with a delete_file tool can cause irreversible damage if it misinterprets a command.

The Evaluation Pipeline

Before deploying a managed agent, it must be benchmarked against a "Golden Dataset" of trajectories. Success is measured not just by the final answer, but by the Path Efficiency.

Metric Formula Description
Success Rate (SR) $S / N$ Percentage of tasks completed correctly.
Path Efficiency (PE) $O_{optimal} / O_{actual}$ Ratio of minimum required steps to actual steps taken.
Tool Accuracy $T_{correct} / T_{total}$ How often the agent provides valid arguments to tools.
Safety Violation Rate $V / N$ Frequency of the agent attempting unauthorized actions.

Implementing Guardrails

To prevent catastrophic failures, engineers should implement a Human-in-the-Loop (HITL) pattern for sensitive tools.

-- SQL Schema for Tracking Agent Trajectories and Human Approvals
CREATE TABLE agent_trajectories (
    trajectory_id UUID PRIMARY KEY,
    agent_id VARCHAR(255),
    start_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    status VARCHAR(50) -- 'running', 'pending_approval', 'completed', 'failed'
);

CREATE TABLE tool_calls (
    call_id UUID PRIMARY KEY,
    trajectory_id UUID REFERENCES agent_trajectories(trajectory_id),
    tool_name VARCHAR(255),
    arguments JSONB,
    requires_approval BOOLEAN DEFAULT FALSE,
    is_approved BOOLEAN DEFAULT NULL,
    observation JSONB
);

Common Pitfalls in Agentic Design

  1. The Infinite Loop: An agent repeatedly calls a tool with the same failing parameters.
    • Solution: Implement a max_iterations cap in the orchestration layer.
  2. Context Overflow: The trajectory exceeds the model's context window (e.g., 200k tokens).
    • Solution: Use a "Summarizer" agent to compress the history or utilize Claude's context caching effectively.
  3. Tool Over-Reliance: The agent calls tools for tasks it could solve via internal reasoning.
    • Solution: Refine the system prompt to emphasize "Think before you act."
  4. Brittle Tool Schemas: Using vague types like string for everything.
    • Solution: Use enums and strict JSON schemas to force the model into valid state spaces.

Conclusion: The Future of Managed Agency

As Claude continues to evolve, the boundary between "model" and "application" will blur. Managed Agents are the first step toward a future where developers build systems by defining intent and constraints rather than procedural logic. By mastering the ReAct loop, tool integration, and evaluation frameworks, engineers can build autonomous systems that are both powerful and predictable.

Building with Claude Managed Agents - Start building with Claude - image 1
Building with Claude Managed Agents - Start building with Claude - image 1

Source Materials

Study Start building with Claude on Lykke

This course page is free to open: signed out, you can read its first two sections, and signing in, on any plan, opens the rest. The free Lykke Chrome extension syncs your own Canvas courses, so ChatGPT, Claude and Muse can answer from your classes and deadlines. It only reads Canvas.

Add the free extensionSign in to open every section

All sections of Start building with Claude · Browse more course pages

Building with Claude Managed Agents — Start building with Claude | Lykke