# Build an Agent Tool Loop

This guide walks you through building a ReAct-style agent loop (Reason → Act → Observe → Repeat) where each iteration is a durable, retriable step.

## The basic loop

Create a function that takes a user message, calls an LLM, executes any requested tools, and repeats until the LLM returns a final answer:

```ts {{ title: "TypeScript" }}
import { inngest } from "./client";
import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic();

export const agent = inngest.createFunction(
  { id: "agent-loop", triggers: [{ event: "agent/message.received" }] },
  async ({ event, step }) => {
    const messages: Anthropic.MessageParam[] = [
	  // Prepare your initial messages array w/ system, user prompts
      { role: "user", content: event.data.message },
    ];

    const MAX_ITERATIONS = 10;
    let iterations = 0;
    let done = false;

    while (!done && iterations < MAX_ITERATIONS) {
      iterations++;

      // 1. Think — ask the LLM what to do next
      const llmResult = await step.run(`think`, async () => {
        return await anthropic.messages.create({
          model: "claude-opus-4-6",
          max_tokens: 4096,
          // Use your own expertly crafted prompt:
          system: "You are a helpful assistant with access to tools.",
          messages,
          tools, // your tool definitions
        });
      });

      // 2. Check if the LLM wants to use tools
      const toolCalls = llmResult.content.filter(
        (block): block is Anthropic.ToolUseBlock => block.type === "tool_use"
      );

      if (toolCalls.length === 0) {
        // No tools — we're done
        const text = llmResult.content.find(
          (b): b is Anthropic.TextBlock => b.type === "text"
        );
        done = true;
        return { response: text?.text ?? "", iterations };
      }

      // 3. Act — execute each tool
      messages.push({ role: "assistant", content: llmResult.content });
      const toolResults: Anthropic.ToolResultBlockParam[] = [];

      for (const toolCall of toolCalls) {
        const result = await step.run(
          `tool-${toolCall.name}`,
          async () => executeTool(toolCall.name, toolCall.input)
        );
        toolResults.push({
          type: "tool_result",
          tool_use_id: toolCall.id,
          content: result,
        });
      }

      // 4. Observe — feed results back and loop
      messages.push({ role: "user", content: toolResults });
    }

    return { response: "Reached iteration limit", iterations };
  }
);
```

```python {{ title: "Python" }}
import typing

import anthropic
import inngest

inngest_client = inngest.Inngest(app_id="my-app")
llm = anthropic.AsyncAnthropic()

@inngest_client.create_function(
    fn_id="agent-loop",
    trigger=inngest.TriggerEvent(event="agent/message.received"),
)
async def agent(ctx: inngest.Context) -> dict[str, typing.Any]:
    messages: list[dict[str, typing.Any]] = [
        # Prepare your initial messages list w/ system, user prompts
        {"role": "user", "content": ctx.event.data["message"]},
    ]

    max_iterations = 10
    iterations = 0
    done = False

    while not done and iterations < max_iterations:
        iterations += 1

        # 1. Think — ask the LLM what to do next
        async def think() -> dict[str, typing.Any]:
            response = await llm.messages.create(
                model="claude-opus-4-6",
                max_tokens=4096,
                # Use your own expertly crafted prompt:
                system="You are a helpful assistant with access to tools.",
                messages=messages,
                tools=tools,  # your tool definitions
            )
            # Step results must be JSON-serializable.
            return response.model_dump(mode="json")

        llm_result = await ctx.step.run("think", think)

        # 2. Check if the LLM wants to use tools
        tool_calls = [
            block
            for block in llm_result["content"]
            if block["type"] == "tool_use"
        ]

        if not tool_calls:
            # No tools — we're done
            text = next(
                (
                    b["text"]
                    for b in llm_result["content"]
                    if b["type"] == "text"
                ),
                "",
            )
            done = True
            return {"response": text, "iterations": iterations}

        # 3. Act — execute each tool
        messages.append(
            {"role": "assistant", "content": llm_result["content"]}
        )
        tool_results: list[dict[str, typing.Any]] = []

        for tool_call in tool_calls:
            result = await ctx.step.run(
                f"tool-{tool_call['name']}",
                execute_tool,
                tool_call["name"],
                tool_call["input"],
            )
            tool_results.append(
                {
                    "type": "tool_result",
                    "tool_use_id": tool_call["id"],
                    "content": result,
                }
            )

        # 4. Observe — feed results back and loop
        messages.append({"role": "user", "content": tool_results})

    return {"response": "Reached iteration limit", "iterations": iterations}
```

```go {{ title: "Go" }}
import (
	"context"
	"os"

	"github.com/inngest/inngestgo"
	"github.com/inngest/inngestgo/step"
	"github.com/sashabaranov/go-openai"
)

var llm = openai.NewClient(os.Getenv("OPENAI_API_KEY"))

type MessageReceived struct {
	Message string `json:"message"`
}

func AgentLoop(client inngestgo.Client) (inngestgo.ServableFunction, error) {
	return inngestgo.CreateFunction(
		client,
		inngestgo.FunctionOpts{ID: "agent-loop"},
		inngestgo.EventTrigger("agent/message.received", nil),
		func(ctx context.Context, input inngestgo.Input[MessageReceived]) (any, error) {
			// Prepare your initial messages w/ system, user prompts
			messages := []openai.ChatCompletionMessage{
				// Use your own expertly crafted prompt:
				{Role: openai.ChatMessageRoleSystem, Content: "You are a helpful assistant with access to tools."},
				{Role: openai.ChatMessageRoleUser, Content: input.Event.Data.Message},
			}

			const maxIterations = 10
			iterations := 0

			for iterations < maxIterations {
				iterations++

				// 1. Think — ask the LLM what to do next
				llmResult, err := step.Run(ctx, "think", func(ctx context.Context) (openai.ChatCompletionResponse, error) {
					return llm.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
						Model:     openai.GPT4o,
						MaxTokens: 4096,
						Messages:  messages,
						Tools:     tools, // your tool definitions
					})
				})
				if err != nil {
					return nil, err
				}
				message := llmResult.Choices[0].Message

				// 2. Check if the LLM wants to use tools
				if len(message.ToolCalls) == 0 {
					// No tools — we're done
					return map[string]any{"response": message.Content, "iterations": iterations}, nil
				}

				// 3. Act — execute each tool
				messages = append(messages, message)
				for _, toolCall := range message.ToolCalls {
					result, err := step.Run(ctx, "tool-"+toolCall.Function.Name, func(ctx context.Context) (string, error) {
						return executeTool(ctx, toolCall.Function.Name, toolCall.Function.Arguments)
					})
					if err != nil {
						return nil, err
					}
					// 4. Observe — feed results back and loop
					messages = append(messages, openai.ChatCompletionMessage{
						Role:       openai.ChatMessageRoleTool,
						ToolCallID: toolCall.ID,
						Content:    result,
					})
				}
			}

			return map[string]any{"response": "Reached iteration limit", "iterations": iterations}, nil
		},
	)
}
```

Implement `executeTool` however you want. It can be a switch statement, a map of functions, a plugin system. It takes a tool name and input, and returns a string result.

The Go example uses the `go-openai` client; any model provider works the same way. That's the entire pattern. Everything below breaks down each piece and how to tune it.

## Make LLM calls durable

Wrap every LLM call in [`step.run()`](/docs-markdown/reference/typescript/v4/functions/step-run) to make it retriable and checkpointed:

```ts {{ title: "TypeScript" }}
// ✅ Durable — retries on failure, result is checkpointed
const result = await step.run("think", async () => {
  return await anthropic.messages.create({ /* ... */ });
});

// ❌ Not durable — if this fails, you lose all prior work
const result = await anthropic.messages.create({ /* ... */ });
```

```python {{ title: "Python" }}
# ✅ Durable — retries on failure, result is checkpointed
async def think() -> dict[str, typing.Any]:
    response = await llm.messages.create(**request)
    return response.model_dump(mode="json")

result = await ctx.step.run("think", think)

# ❌ Not durable — if this fails, you lose all prior work
result = await llm.messages.create(**request)
```

```go {{ title: "Go" }}
// ✅ Durable — retries on failure, result is checkpointed
result, err := step.Run(ctx, "think", func(ctx context.Context) (openai.ChatCompletionResponse, error) {
	return llm.CreateChatCompletion(ctx, req)
})

// ❌ Not durable — if this fails, you lose all prior work
result, err = llm.CreateChatCompletion(ctx, req)
```

When an LLM call fails (rate limit, timeout, network error), Inngest retries just that step. Previous iterations, tool results — everything else is preserved.

## Run each tool as a step

Wrap each tool execution in its own `step.run()` so tools retry independently from the LLM call and from each other. Using `step.run()` provides:

- **Independent retries** — a failing tool doesn't re-run the LLM call
- **Granular observability** — see exactly which tool failed in the dashboard
- **Parallel execution** — tools that don't depend on each other can run concurrently

Sequential execution (most common):

```ts {{ title: "TypeScript" }}
for (const toolCall of toolCalls) {
  const result = await step.run(
    `tool-${toolCall.name}`,
    async () => executeTool(toolCall.name, toolCall.input)
  );
  toolResults.push({ type: "tool_result", tool_use_id: toolCall.id, content: result });
}
```

```python {{ title: "Python" }}
for tool_call in tool_calls:
    result = await ctx.step.run(
        f"tool-{tool_call['name']}",
        execute_tool,
        tool_call["name"],
        tool_call["input"],
    )
    tool_results.append(
        {
            "type": "tool_result",
            "tool_use_id": tool_call["id"],
            "content": result,
        }
    )
```

```go {{ title: "Go" }}
for _, toolCall := range toolCalls {
	result, err := step.Run(ctx, "tool-"+toolCall.Function.Name, func(ctx context.Context) (string, error) {
		return executeTool(ctx, toolCall.Function.Name, toolCall.Function.Arguments)
	})
	if err != nil {
		return nil, err
	}
	messages = append(messages, openai.ChatCompletionMessage{
		Role:       openai.ChatMessageRoleTool,
		ToolCallID: toolCall.ID,
		Content:    result,
	})
}
```

To run independent tools in parallel, use `Promise.all` (`group.Parallel` in Go, `ctx.group.parallel` in Python). Include the index to make each step ID unique and easier to debug parallel calls:

```ts {{ title: "TypeScript" }}
const results = await Promise.all(
  toolCalls.map((toolCall, idx) =>
    step.run(`tool-${toolCall.name}-${idx}`, async () => ({
      toolUseId: toolCall.id,
      result: executeTool(toolCall.name, toolCall.input),
    }))
  )
);
```

```python {{ title: "Python" }}
def run_tool(
    idx: int, tool_call: dict[str, typing.Any]
) -> typing.Callable[[], typing.Awaitable[dict[str, str]]]:
    async def handler() -> dict[str, str]:
        return {
            "tool_use_id": tool_call["id"],
            "result": await execute_tool(
                tool_call["name"], tool_call["input"]
            ),
        }

    return lambda: ctx.step.run(f"tool-{tool_call['name']}-{idx}", handler)

results = await ctx.group.parallel(
    tuple(run_tool(idx, call) for idx, call in enumerate(tool_calls))
)
```

```go {{ title: "Go" }}
fns := make([]func(ctx context.Context) (any, error), len(toolCalls))
for idx, toolCall := range toolCalls {
	fns[idx] = func(ctx context.Context) (any, error) {
		return step.Run(ctx, fmt.Sprintf("tool-%s-%d", toolCall.Function.Name, idx), func(ctx context.Context) (ToolResult, error) {
			result, err := executeTool(ctx, toolCall.Function.Name, toolCall.Function.Arguments)
			return ToolResult{ToolUseID: toolCall.ID, Result: result}, err
		})
	}
}
results := group.Parallel(ctx, fns...)
if err := results.AnyError(); err != nil {
	return nil, err
}
```

## Control the loop

### Set a max iteration count

Always cap iterations. Choose the limit based on task complexity — simple Q\&A might need 2–3, a coding agent that reads, edits, and tests might need 15–20.

### Track token usage

To stop before exceeding your budget, accumulate usage across iterations:

```ts {{ title: "TypeScript" }}
let totalInputTokens = 0;

while (!done && iterations < MAX_ITERATIONS) {
  const llmResult = await step.run(`think`, async () => {
    return await anthropic.messages.create({ /* ... */ });
  });

  totalInputTokens += llmResult.usage.input_tokens;
  if (totalInputTokens > 500_000) {
    return { response: "Token budget exceeded", iterations };
  }

  // ... rest of loop
}
```

```python {{ title: "Python" }}
total_input_tokens = 0

while not done and iterations < max_iterations:

    async def think() -> dict[str, typing.Any]:
        response = await llm.messages.create(**request)
        return response.model_dump(mode="json")

    llm_result = await ctx.step.run("think", think)

    total_input_tokens += llm_result["usage"]["input_tokens"]
    if total_input_tokens > 500_000:
        return {
            "response": "Token budget exceeded",
            "iterations": iterations,
        }

    # ... rest of loop
```

```go {{ title: "Go" }}
totalInputTokens := 0

for !done && iterations < maxIterations {
	llmResult, err := step.Run(ctx, "think", func(ctx context.Context) (openai.ChatCompletionResponse, error) {
		return llm.CreateChatCompletion(ctx, req)
	})
	if err != nil {
		return nil, err
	}

	totalInputTokens += llmResult.Usage.PromptTokens
	if totalInputTokens > 500_000 {
		return map[string]any{"response": "Token budget exceeded", "iterations": iterations}, nil
	}

	// ... rest of loop
}
```

### Detect stuck loops

If the agent keeps calling the same tool repeatedly, break the loop:

```ts {{ title: "TypeScript" }}
if (iterations > 3 && lastThreeTools.every(t => t === prevTool)) {
  done = true;
}
```

```python {{ title: "Python" }}
if iterations > 3 and all(t == prev_tool for t in last_three_tools):
    done = True
```

```go {{ title: "Go" }}
allSame := !slices.ContainsFunc(lastThreeTools, func(t string) bool { return t != prevTool })
if iterations > 3 && allSame {
	done = true
}
```

## Prune context as the loop grows

As your agent loops, the message array grows with each iteration. To avoid hitting context window limits, keep the original user message and recent messages, and drop the middle:

```ts {{ title: "TypeScript" }}
function pruneMessages(messages, maxMessages) {
  if (messages.length <= maxMessages) return messages;
  const first = messages[0];
  const recent = messages.slice(-maxMessages + 1);
  return [first, ...recent];
}
```

```python {{ title: "Python" }}
import typing

def prune_messages(
    messages: list[dict[str, typing.Any]], max_messages: int
) -> list[dict[str, typing.Any]]:
    if len(messages) <= max_messages:
        return messages
    first = messages[0]
    recent = messages[-max_messages + 1 :]
    return [first, *recent]
```

```go {{ title: "Go" }}
func pruneMessages(messages []openai.ChatCompletionMessage, maxMessages int) []openai.ChatCompletionMessage {
	if len(messages) <= maxMessages {
		return messages
	}
	first := messages[0]
	recent := messages[len(messages)-maxMessages+1:]
	return append([]openai.ChatCompletionMessage{first}, recent...)
}
```

## Next steps

- [Delegate subtasks to child agents](/docs-markdown/durable-execution/durable-agents/sub-agent-delegation) with `step.invoke()`
- [Pause the loop for user approval](/docs-markdown/durable-execution/durable-agents/human-in-the-loop) with `step.waitForEvent()`
- [How to build a durable AI agent with Inngest](/blog/ai-agents-inngest-durable-steps) — a deep dive covering context loading, session management, and observability