Claude Code for Building LLM Agents: Tool Use, Memory, and Multi-Step Reasoning — Claude Skills 360 Blog
Blog / AI / Claude Code for Building LLM Agents: Tool Use, Memory, and Multi-Step Reasoning
AI

Claude Code for Building LLM Agents: Tool Use, Memory, and Multi-Step Reasoning

Published: August 21, 2026
Read time: 10 min read
By: Claude Skills 360

LLM agents go beyond single-turn completions: they use tools to take actions, maintain context across steps, and reason iteratively until a task is complete. Building reliable agents requires careful design of tool schemas, robust error handling when models call tools incorrectly, and memory management to keep agents focused on the current task. Claude Code, being an agent itself, generates agent code with deep understanding of these patterns.

This guide covers LLM agent development with Claude Code: tool calling, memory systems, ReAct orchestration, streaming, and evaluation.

CLAUDE.md for Agent Projects

## LLM Agent Stack
- Anthropic Claude API (claude-sonnet-4-6 for agents, haiku for quick tasks)
- Tool calling: Anthropic tool_use content blocks
- Memory: in-context window + Redis for longer-running agents
- Orchestration: custom ReAct loop (not LangChain — too much abstraction)

## Agent Patterns
- Tools: narrow and composable — one thing each, clear error messages
- Tools should be idempotent where possible
- Always handle ToolUseBlock and ToolResultBlock in message loops
- Stream long-running agent tasks — don't leave users waiting for 30+ second responses
- Evaluate with assertions on intermediate steps, not just final output

Tool Definition and Calling

Create an agent that can search a knowledge base, create tickets,
and send Slack notifications. Define the tools and the agent loop.
// src/tools/definitions.ts
import Anthropic from '@anthropic-ai/sdk';

export const tools: Anthropic.Tool[] = [
  {
    name: 'search_knowledge_base',
    description: 'Search the internal knowledge base for documentation, runbooks, and FAQs. Use this to answer questions before creating tickets.',
    input_schema: {
      type: 'object' as const,
      required: ['query'],
      properties: {
        query: {
          type: 'string',
          description: 'Search query — be specific for better results',
        },
        max_results: {
          type: 'number',
          description: 'Maximum results to return (default: 5, max: 20)',
          default: 5,
        },
      },
    },
  },
  {
    name: 'create_ticket',
    description: 'Create a support ticket in the issue tracker. Only use this when the knowledge base doesn\'t answer the question.',
    input_schema: {
      type: 'object' as const,
      required: ['title', 'description', 'priority'],
      properties: {
        title: { type: 'string', description: 'Brief ticket title (< 80 chars)' },
        description: { type: 'string', description: 'Full description with context and steps to reproduce' },
        priority: {
          type: 'string',
          enum: ['low', 'medium', 'high', 'critical'],
        },
        assignee_email: {
          type: 'string',
          format: 'email',
          description: 'Assign to specific team member (optional)',
        },
      },
    },
  },
  {
    name: 'send_slack_notification',
    description: 'Send a Slack message to a channel or user. Use for urgent issues or to notify team leads.',
    input_schema: {
      type: 'object' as const,
      required: ['channel', 'message'],
      properties: {
        channel: {
          type: 'string',
          description: 'Channel name (e.g., #ops-alerts) or user ID (e.g., U12345)',
        },
        message: { type: 'string' },
        urgent: {
          type: 'boolean',
          description: 'Add @here mention for urgent issues (default: false)',
          default: false,
        },
      },
    },
  },
];

Agent Orchestration Loop

// src/agent/support-agent.ts
import Anthropic from '@anthropic-ai/sdk';
import { tools } from '../tools/definitions';
import { executeTool } from '../tools/executor';

const client = new Anthropic();

export async function runSupportAgent(
  userMessage: string,
  conversationHistory: Anthropic.MessageParam[] = [],
): Promise<{ response: string; actionsLog: string[] }> {
  const actionsLog: string[] = [];
  
  const messages: Anthropic.MessageParam[] = [
    ...conversationHistory,
    { role: 'user', content: userMessage },
  ];

  const systemPrompt = `You are a support agent. When a user reports an issue:
1. First search the knowledge base to find existing documentation
2. If the knowledge base answers the question, respond directly
3. If the issue requires action, create a ticket
4. For critical issues (production down, data loss), also send a Slack notification to #ops-alerts

Always be concise and clear in your responses.`;

  // ReAct loop: reason → act → observe → repeat until done
  while (true) {
    const response = await client.messages.create({
      model: 'claude-sonnet-4-6',
      max_tokens: 4096,
      system: systemPrompt,
      tools,
      messages,
    });

    if (response.stop_reason === 'end_turn') {
      // Agent finished — extract text response
      const text = response.content
        .filter((b): b is Anthropic.TextBlock => b.type === 'text')
        .map(b => b.text)
        .join('');
      return { response: text, actionsLog };
    }

    if (response.stop_reason === 'tool_use') {
      // Add assistant's tool call to history
      messages.push({ role: 'assistant', content: response.content });

      // Execute all tool calls (may be multiple in one turn)
      const toolResults: Anthropic.ToolResultBlockParam[] = [];

      for (const block of response.content) {
        if (block.type !== 'tool_use') continue;

        actionsLog.push(`Tool: ${block.name} | Input: ${JSON.stringify(block.input)}`);

        try {
          const result = await executeTool(block.name, block.input);
          toolResults.push({
            type: 'tool_result',
            tool_use_id: block.id,
            content: JSON.stringify(result),
          });
        } catch (error) {
          // Return errors to the agent — let it decide how to proceed
          toolResults.push({
            type: 'tool_result',
            tool_use_id: block.id,
            is_error: true,
            content: `Error: ${(error as Error).message}`,
          });
        }
      }

      // Add tool results to history and continue the loop
      messages.push({ role: 'user', content: toolResults });
      continue;
    }

    // Unexpected stop reason
    break;
  }

  return { response: 'Agent stopped unexpectedly', actionsLog };
}

Memory Systems

The agent needs to remember context across multiple requests
from the same user. Add a memory layer.
// src/memory/agent-memory.ts
import { Redis } from 'ioredis';
import Anthropic from '@anthropic-ai/sdk';

const redis = new Redis(process.env.REDIS_URL!);

interface AgentMemory {
  userId: string;
  recentMessages: Anthropic.MessageParam[];
  facts: string[]; // Extracted facts about the user's environment
  openTickets: string[]; // Ticket IDs created this session
}

export async function loadMemory(userId: string): Promise<AgentMemory> {
  const stored = await redis.get(`agent:memory:${userId}`);
  if (!stored) {
    return { userId, recentMessages: [], facts: [], openTickets: [] };
  }
  return JSON.parse(stored);
}

export async function saveMemory(memory: AgentMemory): Promise<void> {
  // Keep last 20 messages for context window efficiency
  memory.recentMessages = memory.recentMessages.slice(-20);
  await redis.setex(
    `agent:memory:${memory.userId}`,
    7 * 24 * 60 * 60, // 7 day TTL
    JSON.stringify(memory),
  );
}

export async function extractAndSaveFacts(
  userId: string,
  conversation: Anthropic.MessageParam[],
): Promise<void> {
  // Use a quick model to extract facts from the conversation
  const client = new Anthropic();
  const response = await client.messages.create({
    model: 'claude-haiku-4-5-20251001',
    max_tokens: 500,
    system: 'Extract factual observations about the user\'s technical environment from this conversation. Return a JSON array of strings. Only extract concrete facts (OS, stack, error patterns), not questions or hypotheticals.',
    messages: [{ role: 'user', content: JSON.stringify(conversation) }],
  });

  try {
    const facts = JSON.parse((response.content[0] as Anthropic.TextBlock).text) as string[];
    const memory = await loadMemory(userId);
    memory.facts = [...new Set([...memory.facts, ...facts])].slice(-50); // Max 50 facts
    await saveMemory(memory);
  } catch {
    // Extraction failed — not critical
  }
}

Streaming Agent Responses

// src/agent/streaming-agent.ts
export async function* streamSupportAgent(
  userMessage: string,
  userId: string,
): AsyncGenerator<{ type: 'text' | 'tool_call' | 'error'; content: string }> {
  const memory = await loadMemory(userId);
  
  const stream = await client.messages.create({
    model: 'claude-sonnet-4-6',
    max_tokens: 4096,
    system: systemPrompt,
    tools,
    messages: [...memory.recentMessages, { role: 'user', content: userMessage }],
    stream: true,
  });

  let currentToolName = '';
  let currentToolInput = '';

  for await (const event of stream) {
    if (event.type === 'content_block_delta') {
      if (event.delta.type === 'text_delta') {
        yield { type: 'text', content: event.delta.text };
      } else if (event.delta.type === 'input_json_delta') {
        currentToolInput += event.delta.partial_json;
      }
    }

    if (event.type === 'content_block_start' && event.content_block.type === 'tool_use') {
      currentToolName = event.content_block.name;
      yield { type: 'tool_call', content: `Using ${currentToolName}...` };
    }
  }
}

Agent Evaluation

// tests/agent.eval.ts — Evaluation framework for agent correctness
describe('Support agent evaluations', () => {
  it('searches knowledge base before creating tickets', async () => {
    const { actionsLog } = await runSupportAgent(
      'How do I reset my 2FA device?'
    );
    
    // Must search before deciding to create a ticket
    const searchAction = actionsLog.find(a => a.includes('search_knowledge_base'));
    const ticketAction = actionsLog.find(a => a.includes('create_ticket'));
    
    expect(searchAction).toBeTruthy(); // Must search
    // For a knowable question, should not create a ticket
    expect(ticketAction).toBeUndefined();
  });

  it('creates ticket for novel issues not in knowledge base', async () => {
    const { actionsLog } = await runSupportAgent(
      'The deployment pipeline is failing with error code XZ-9991'
    );
    
    const ticketAction = actionsLog.find(a => a.includes('create_ticket'));
    expect(ticketAction).toBeTruthy();
  });

  it('notifies Slack for critical issues', async () => {
    const { actionsLog } = await runSupportAgent(
      'URGENT: Production database is down, all users affected'
    );
    
    const slackAction = actionsLog.find(a => a.includes('send_slack_notification'));
    expect(slackAction).toBeTruthy();
    
    // Should use #ops-alerts channel
    expect(slackAction).toContain('ops-alerts');
  });
});

For integrating ML models and embeddings into agent memory, see the machine learning guide. For streaming LLM responses over WebSockets and SSE, see the WebSockets guide. The Claude Skills 360 bundle includes LLM integration skill sets covering tool use patterns, agent orchestration, and evaluation frameworks. Start with the free tier to try agent code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free