← Blog

Claude API Agent Framework Examples You Can Build Today

2026-10-06 · 5 min read · SubToAPI Team

"Agent framework" gets used loosely, but when developers search for Claude API agent framework examples, they usually want one of two things: a working pattern for building an agent loop themselves, or a map of which existing frameworks (LangChain, LangGraph, custom code) pair well with Claude's tool-use API. This article covers both — concrete, runnable patterns you can adapt, plus guidance on when to reach for a framework versus writing the loop yourself.

The short version: an "agent" built on the Claude API is just a loop that (1) sends a message with tool definitions, (2) lets the model decide whether to call a tool, (3) executes that tool in your code, and (4) feeds the result back in. Everything else — planners, supervisors, memory, RAG — is a variation on that loop. Below are four patterns, each with a code example you can run against any Claude-compatible endpoint, including SubToAPI if you're already using it for your application's Claude access.

Pattern 1: The Basic Tool-Use Loop

This is the foundation of almost every Claude agent. The model is given tool schemas and decides when to invoke them; your code executes the tool and returns the result.

async function runAgent(userMessage, tools, executeTool) {
  let messages = [{ role: "user", content: userMessage }];

  while (true) {
    const res = await fetch("https://api.subtoapi.app/v1/messages", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        model: "claude-sonnet-4",
        max_tokens: 1024,
        messages,
        tools
      })
    });
    const data = await res.json();

    const toolUse = data.content.find(b => b.type === "tool_use");
    if (!toolUse) {
      return data.content.find(b => b.type === "text")?.text;
    }

    const result = await executeTool(toolUse.name, toolUse.input);
    messages.push({ role: "assistant", content: data.content });
    messages.push({
      role: "user",
      content: [{ type: "tool_result", tool_use_id: toolUse.id, content: result }]
    });
  }
}

This loop is the core of nearly every "agent framework" — LangGraph, CrewAI, and hand-rolled solutions all boil down to this exchange with extra bookkeeping on top. See /docs/tools for the full tool definition schema and /docs/messages for the request shape.

Pattern 2: Planner/Executor Separation

For tasks with multiple steps (research a topic, then summarize, then draft an email), a single loop can wander. Splitting planning from execution keeps it on track:

  1. Planner call — ask Claude to break the goal into an ordered list of subtasks, returned as structured JSON.
  2. Executor loop — run Pattern 1 for each subtask, passing prior results forward as context.
  3. Final synthesis — one last call that combines subtask outputs into the final answer.
const plan = await getPlan(goal); // returns ["search for X", "extract Y", "draft Z"]
let context = [];
for (const step of plan) {
  const result = await runAgent(step + "\nContext so far: " + JSON.stringify(context), tools, executeTool);
  context.push(result);
}
const final = await synthesize(goal, context);

This pattern works well when subtasks are loosely independent. It avoids the "agent forgets the original goal after three tool calls" problem common in long single loops.

Pattern 3: Supervisor and Worker Agents

For more complex systems, one Claude instance acts as a supervisor that routes work to specialized worker agents — a researcher, a coder, a reviewer — each with its own system prompt and tool set.

const workers = {
  researcher: { systemPrompt: "You find and summarize facts.", tools: [searchTool] },
  coder: { systemPrompt: "You write and test code.", tools: [execTool] },
  reviewer: { systemPrompt: "You critique output for correctness.", tools: [] }
};

async function supervise(task) {
  const route = await classifyTask(task); // "researcher" | "coder" | "reviewer"
  const worker = workers[route];
  return runAgent(task, worker.tools, executeTool, worker.systemPrompt);
}

This is roughly what frameworks like CrewAI or LangGraph's multi-agent graphs implement under the hood, with added state management and retry logic. If you're prototyping, writing it directly against the Claude API — without the framework layer — is often faster to debug, since you can see exactly what each agent sends and receives.

Pattern 4: Retrieval-Augmented Agent

Agents that need grounded answers combine a retrieval tool with the standard loop. The tool itself can call a vector database, a search API, or your own document store:

const retrievalTool = {
  name: "search_docs",
  description: "Search internal documentation for relevant passages",
  input_schema: {
    type: "object",
    properties: { query: { type: "string" } },
    required: ["query"]
  }
};

The agent decides when it needs more information and calls search_docs mid-conversation rather than you stuffing everything into the initial prompt. This keeps context smaller and answers more current.

Framework or Custom Loop?

Full frameworks (LangGraph, CrewAI, OpenAI's Agents SDK equivalents) add value when you need: persistent state across sessions, visual graph debugging, or built-in retry/backoff handling. For most products, though, the four patterns above cover 90% of real agent use cases, and writing them directly keeps the codebase smaller and easier to reason about — no framework abstraction to learn, no version lock-in.

Whichever route you choose, the underlying requirement is the same: a stable, well-documented Claude API endpoint with reliable tool-use support and visibility into usage. If you're running these loops in production — especially multi-agent patterns that make several calls per task — streaming partial output back to users matters for perceived latency (see /docs/streaming), and per-key usage metadata matters for knowing which agent or team is consuming your Claude budget. SubToAPI wraps your Claude access in application API keys (sub_live_...) with that metadata built in, so you can track cost by agent or by team seat without building your own logging layer. Start with /docs/quickstart, and check /pricing if you're scaling from a solo prototype to a team running multiple agents.

Questions

Do I need LangChain or similar to build a Claude agent? No. The core agent loop — send messages, handle tool_use, return tool_result — is simple enough to write directly in under 50 lines. Frameworks help with state persistence and visual debugging at scale, but they're not required to get a working agent.

What's the difference between a tool-use loop and a true "agent"? Not much in practice. A tool-use loop that runs until the model stops requesting tools is functionally an agent. The term "agent" typically implies some autonomy over multiple steps, which the loop provides once it can call itself repeatedly without manual intervention.

How do I avoid infinite tool-use loops? Cap the number of loop iterations (e.g., 10–15) and track a step counter in your code. If the limit is hit, return the best partial answer rather than erroring out, and log the trace for debugging — most runaway loops come from a tool returning ambiguous results the model keeps re-querying.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →