agent-builder/skills/managed-agents/references/api-patterns.md
2026-04-12 06:44:39 +02:00

4.4 KiB

Managed Agents API Patterns

Code patterns for creating and managing agents via the Anthropic SDK. All examples use @anthropic-ai/sdk (TypeScript) with Python equivalents noted.


Basic agent creation

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

const client = new Anthropic();

// Create an agent with tools
const response = await client.messages.create({
  model: "claude-sonnet-4-6",
  max_tokens: 4096,
  system: "You are a research agent. Produce structured briefs.",
  tools: [
    {
      name: "web_search",
      description: "Search the web for information",
      input_schema: {
        type: "object",
        properties: {
          query: { type: "string", description: "Search query" }
        },
        required: ["query"]
      }
    }
  ],
  messages: [
    { role: "user", content: "Research the latest Claude Code features" }
  ]
});

Agent with persistent sessions

// Create a session-based agent
const session = await client.agents.sessions.create({
  agent_id: "ag_your_agent_id",
  system_prompt: `You are a data analyst. You have access to the
    company database via the query tool. Always verify your findings
    before reporting.`,
  tools: [/* your tool definitions */]
});

// First interaction
const result1 = await client.agents.sessions.messages.create({
  agent_id: "ag_your_agent_id",
  session_id: session.id,
  messages: [{ role: "user", content: "Analyze Q1 revenue trends" }]
});

// Continue the conversation (session remembers context)
const result2 = await client.agents.sessions.messages.create({
  agent_id: "ag_your_agent_id",
  session_id: session.id,
  messages: [{ role: "user", content: "Now compare with Q4 of last year" }]
});

Tool handling pattern

async function runAgentLoop(
  client: Anthropic,
  messages: Anthropic.MessageParam[],
  tools: Anthropic.Tool[]
) {
  let response = await client.messages.create({
    model: "claude-sonnet-4-6",
    max_tokens: 4096,
    tools,
    messages
  });

  while (response.stop_reason === "tool_use") {
    const toolUseBlocks = response.content.filter(
      (b): b is Anthropic.ToolUseBlock => b.type === "tool_use"
    );

    const toolResults: Anthropic.ToolResultBlockParam[] = [];
    for (const toolUse of toolUseBlocks) {
      const result = await executeToolCall(toolUse.name, toolUse.input);
      toolResults.push({
        type: "tool_result",
        tool_use_id: toolUse.id,
        content: JSON.stringify(result)
      });
    }

    messages.push({ role: "assistant", content: response.content });
    messages.push({ role: "user", content: toolResults });

    response = await client.messages.create({
      model: "claude-sonnet-4-6",
      max_tokens: 4096,
      tools,
      messages
    });
  }

  return response;
}

Cost optimization with prompt caching

const response = await client.messages.create({
  model: "claude-sonnet-4-6",
  max_tokens: 1024,
  system: [
    {
      type: "text",
      text: longSystemPrompt, // cached — 90% cheaper on reuse
      cache_control: { type: "ephemeral" }
    }
  ],
  messages: [{ role: "user", content: userQuery }]
});

Error handling

try {
  const response = await client.messages.create(/* ... */);
} catch (error) {
  if (error instanceof Anthropic.RateLimitError) {
    // Retry with exponential backoff
    await sleep(retryDelay);
    retryDelay *= 2;
  } else if (error instanceof Anthropic.APIError) {
    console.error(`API error ${error.status}: ${error.message}`);
    // Log for debugging, don't retry on 4xx
  }
}

Python equivalent

import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=4096,
    system="You are a research agent.",
    messages=[{"role": "user", "content": "Research topic X"}]
)

Deployment pattern: scheduled managed agent

// Run as a scheduled job (e.g., via cron or cloud scheduler)
async function dailyReport() {
  const client = new Anthropic();

  const response = await runAgentLoop(
    client,
    [{ role: "user", content: "Generate the daily status report" }],
    reportTools
  );

  // Extract and save the report
  const text = response.content
    .filter((b): b is Anthropic.TextBlock => b.type === "text")
    .map((b) => b.text)
    .join("\n");

  await saveReport(text);
}

dailyReport().catch(console.error);