FreeStack

Agent Loop

Autonomous agent execution loop with tool calling, memory management, and graceful error recovery. Supports OpenAI and Anthropic function calling formats.

TypeScriptAI WorkflowsBuilt with Claude
2.9k
Stars
11.4k
Installs
2
Deps
2
Comments

Install / Copy

npx create-freestack-module agent-loop

Code Preview

index.tsx
import Anthropic from "@anthropic-ai/sdk";

interface Tool { name: string; description: string; execute: (input: any) => Promise<string>; }

export async function agentLoop(prompt: string, tools: Tool[], maxIterations = 10) {
  const client = new Anthropic();
  const messages: Message[] = [{ role: "user", content: prompt }];

  for (let i = 0; i < maxIterations; i++) {
    const response = await client.messages.create({
      model: "claude-sonnet-4-20250514",
      max_tokens: 4096,
      tools: tools.map((t) => ({ name: t.name, description: t.description })),
      messages,
    });

    if (response.stop_reason === "end_turn") return response.content;

    for (const block of response.content) {
      if (block.type === "tool_use") {
        const tool = tools.find((t) => t.name === block.name);
        const result = await tool.execute(block.input);
        messages.push({ role: "tool", content: result, tool_use_id: block.id });
      }
    }
  }
}
AI
aidev2 days ago

The retry logic on tool failures is really well thought out. Saved me hours of debugging.

TO
toolmaker5 days ago

Added a custom memory tool and it plugged right in. Clean architecture.