> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chatbotplatform.io/llms.txt
> Use this file to discover all available pages before exploring further.

# How Agentic Loops Work

> The reasoning cycle that grounds AI responses in real-world data: think → tool call → observe → respond

Agentic Loops operate through a multi-step reasoning cycle where the AI agent thinks, acts, observes results, and responds - all while grounding its decisions in real-world data.

## The Reasoning Cycle

At the heart of every Agentic Loop is a continuous reasoning cycle:

```
┌─────────────────────────────────────────────┐
│                                             │
│  1. THINK                                   │
│  "What information do I need?"              │
│  "Which tool should I use?"                 │
│                                             │
└────────────────┬────────────────────────────┘
                 │
                 ▼
┌─────────────────────────────────────────────┐
│                                             │
│  2. TOOL CALL                               │
│  Execute: fetch_weather("Paris")            │
│  Request real-world data                    │
│                                             │
└────────────────┬────────────────────────────┘
                 │
                 ▼
┌─────────────────────────────────────────────┐
│                                             │
│  3. OBSERVE                                 │
│  Receive: {temp: 22, condition: "sunny"}    │
│  Process the tool's response                │
│                                             │
└────────────────┬────────────────────────────┘
                 │
                 ▼
┌─────────────────────────────────────────────┐
│                                             │
│  4. RESPOND                                 │
│  Generate grounded answer with real data    │
│  OR continue to next iteration if needed    │
│                                             │
└─────────────────────────────────────────────┘
```

This cycle repeats until the agent has gathered all necessary information and can provide a complete, grounded response.

## Step-by-Step: A Real Example

Let's trace how an Agentic Loop handles a customer support question.

### User Question

```
"What's the status of order #12345 and when will it arrive?"
```

### Iteration 1: Identify Needed Data

**THINK**:

```
Agent: I need to check two things:
1. Current order status
2. Expected delivery date

I have access to an order database tool. I'll query it.
```

**TOOL CALL**:

```json theme={null}
{
  "tool": "query_order_database",
  "parameters": {
    "order_id": "12345"
  }
}
```

**OBSERVE**:

```json theme={null}
{
  "order_id": "12345",
  "status": "shipped",
  "shipped_date": "2024-01-15",
  "tracking_number": "1Z999AA10123456784",
  "carrier": "UPS"
}
```

**DECISION**: I have the order status, but I need delivery estimate. Continue to next iteration.

### Iteration 2: Get Delivery Estimate

**THINK**:

```
Agent: I have the tracking number. I'll call the shipping API
to get the estimated delivery date.
```

**TOOL CALL**:

```json theme={null}
{
  "tool": "query_shipping_api",
  "parameters": {
    "carrier": "UPS",
    "tracking_number": "1Z999AA10123456784"
  }
}
```

**OBSERVE**:

```json theme={null}
{
  "status": "in_transit",
  "current_location": "Chicago, IL",
  "estimated_delivery": "2024-01-18",
  "last_update": "2024-01-16 14:23:00"
}
```

**DECISION**: I now have all the information needed. Generate final response.

### Iteration 3: Generate Grounded Response

**RESPOND**:

```
Your order #12345 has been shipped. Here are the details:

- Status: Shipped on January 15, 2024
- Tracking: 1Z999AA10123456784 (UPS)
- Current Location: Chicago, IL (as of Jan 16, 2:23 PM)
- Estimated Delivery: January 18, 2024

You can track your package at: https://www.ups.com/track?tracknum=1Z999AA10123456784
```

**Result**: Every fact in this response is grounded in real data from the order database and shipping API. Zero hallucinations.

## Why This Prevents Hallucinations

### Without Tools (High Hallucination Risk)

```
User: What's the status of order #12345?

LLM Brain: I don't have access to order data. But I should
give a helpful response. Orders usually ship within 2-3 days...

LLM Response: "Your order was likely shipped 2-3 days ago
and should arrive within 5-7 business days."

[HALLUCINATED: Made up timeline, no real data]
```

### With Agentic Loop (Grounded)

```
User: What's the status of order #12345?

Agent Brain: I don't know this order's status, but I have
a tool to check. Let me query the database.

Agent: [Calls order_database tool]
→ Receives real data: shipped Jan 15, tracking #123

Agent Response: "Your order #12345 shipped on January 15.
The tracking number is 123."

[GROUNDED: Every fact verified by tool]
```

## Iteration Management

Agents use multiple iterations to complete complex tasks. You control how many iterations are allowed.

### Simple Task (3-5 iterations)

```
Task: Get current weather

Iteration 1: Call weather API
Iteration 2: Process response
Iteration 3: Format answer
COMPLETE
```

### Complex Task (10-20 iterations)

```
Task: Generate sales report

Iteration 1:  Query sales database for yesterday's orders
Iteration 2:  Calculate total revenue
Iteration 3:  Query product database for product names
Iteration 4:  Join sales with product data
Iteration 5:  Calculate top 5 products by revenue
Iteration 6:  Query customer database for customer segments
Iteration 7:  Calculate sales by customer segment
Iteration 8:  Format all metrics into structured report
Iteration 9:  Generate insights from the data
Iteration 10: Send report via callback webhook
COMPLETE
```

![Advanced settings](https://mintcdn.com/chatbotplatform/IwOyuSig9ydzaHpG/images/screenshots/04-agentic/09_advanced_settings.png?fit=max\&auto=format\&n=IwOyuSig9ydzaHpG\&q=85\&s=7edc74e625fb70bd6d447fa9552a787a)

Advanced settings for iteration limits

### Setting Iteration Limits

| Task Complexity | Recommended Iterations |
| - | - |
| Simple data fetch | 3-5 iterations |
| Standard query + format | 5-10 iterations |
| Multi-step analysis | 10-20 iterations |
| Complex workflows | 20-50 iterations |

**Too few iterations**: Agent runs out of steps before completing the task.

**Too many iterations**: Increased cost and latency with no benefit.

Start with 10 iterations for most tasks, then adjust based on execution logs.

## Decision Making Process

How does the agent decide which tool to use?

### Tool Selection Logic

**Agent's Internal Reasoning**:

```
Question: "What's the weather in Paris?"

Step 1: Analyze the question
→ User wants current weather data
→ Location: Paris
→ Type: Weather information

Step 2: Review available tools
→ weather_api: Fetches current weather
→ database: Accesses stored data (not useful here)
→ http_client: Makes generic API calls

Step 3: Select best tool
→ weather_api is specifically designed for this
→ Has 'get_current_weather' function
→ Accepts city parameter

Step 4: Prepare tool call
→ Tool: weather_api
→ Function: get_current_weather
→ Parameters: {city: "Paris"}
```

### Multi-Tool Scenarios

Some tasks require multiple tools:

```
Question: "Send me the sales report for yesterday"

Agent Reasoning:
1. Need sales data → Use database tool
2. Need to calculate metrics → Process data internally
3. Need to send report → Use email tool

Execution:
Iteration 1: Query database for sales
Iteration 2: Calculate total revenue
Iteration 3: Calculate average order value
Iteration 4: Generate report text
Iteration 5: Send via email tool
```

## Observing Tool Responses

After calling a tool, the agent processes the response:

### Successful Tool Call

```json theme={null}
Tool Response: {
  "success": true,
  "data": {
    "temperature": 22,
    "condition": "sunny",
    "humidity": 45
  }
}

Agent Observation:
"The weather tool returned successfully. Temperature is 22°C,
condition is sunny, humidity is 45%. I have all the data needed
to answer the user's question."
```

### Failed Tool Call

```json theme={null}
Tool Response: {
  "success": false,
  "error": "API rate limit exceeded"
}

Agent Observation:
"The weather tool failed due to rate limiting. I should inform
the user that weather data is temporarily unavailable."

Agent Response:
"I'm unable to fetch the current weather data due to a temporary
API limitation. Please try again in a moment."
```

### Error Handling

Agents can be instructed to retry on failures:

```
System Prompt:
If a tool call fails, try once more after a brief pause.
If it fails again, inform the user of the issue.

Execution:
Iteration 1: Call weather_api → FAILED
Iteration 2: Retry weather_api → SUCCESS
Iteration 3: Format response with data
```

## Grounding in Data: Before & After

### Example 1: Order Tracking

**Without Grounding (Hallucination)**:

```
User: Where's my order?
Bot: Orders typically ship in 2-3 business days. Yours
     probably shipped recently.
[Guessed timeline]
```

**With Grounding (Data-Driven)**:

```
User: Where's my order?
Agent: [Queries order database]
Agent: Your order shipped on January 15th with tracking
       number 1Z999. It's currently in Chicago and will
       arrive January 18th.
[Every fact verified]
```

### Example 2: Account Balance

**Without Grounding (Hallucination)**:

```
User: What's my account balance?
Bot: Your account appears to be in good standing with
     a positive balance.
[Fabricated status]
```

**With Grounding (Data-Driven)**:

```
User: What's my account balance?
Agent: [Queries account database]
Agent: Your current account balance is $1,247.32. Your
       last transaction was a $45.00 deposit on January 16th.
[Exact figures from database]
```

### Example 3: Meeting Schedule

**Without Grounding (Hallucination)**:

```
User: When's my next meeting?
Bot: You likely have a meeting this afternoon. Check
     your calendar for the exact time.
[Guessed schedule]
```

**With Grounding (Data-Driven)**:

```
User: When's my next meeting?
Agent: [Queries calendar API]
Agent: Your next meeting is "Q1 Planning" at 2:00 PM today
       in Conference Room B. Attendees: Sarah, Mike, Jessica.
[Actual calendar data]
```

## Performance Optimization

### Parallel Tool Calls

For efficiency, agents can call multiple independent tools simultaneously:

```
Task: Create a comprehensive trip report

Sequential (Slow):
Iteration 1: Get flight details
Iteration 2: Get hotel details
Iteration 3: Get weather forecast
Iteration 4: Get local attractions
Total: 4 iterations

Parallel (Fast):
Iteration 1: Get flight, hotel, weather, and attractions simultaneously
Iteration 2: Combine and format results
Total: 2 iterations
```

### Caching Tool Results

Repeated tool calls can be cached:

```
Question 1: "What's the weather in Paris?"
→ Call weather_api → Cache result

Question 2: "Is it sunny in Paris?" (asked 30 seconds later)
→ Use cached result → No API call needed
```

## Transparency and Trust

Every Agentic Loop execution provides a complete audit trail:

```
Execution Log:

Iteration 1:
THINK: "Need to check order status"
TOOL: query_order_database({order_id: "12345"})
OBSERVE: {status: "shipped", date: "2024-01-15"}

Iteration 2:
THINK: "Need delivery estimate"
TOOL: query_shipping_api({tracking: "1Z999"})
OBSERVE: {estimated_delivery: "2024-01-18"}

Iteration 3:
THINK: "Have all data, generating response"
RESPOND: "Your order shipped on January 15..."
```

This transparency allows you to:

* Verify every fact came from a real source
* Debug when responses are incorrect
* Understand the agent's decision-making process
* Build trust with users by showing your sources

## Next Steps

> [card] [Create Your First Loop](https://docs.chatbotplatform.io/agentic-loops/creating-loops.md)
>
> Build an agent that grounds responses in data

> [card] [Configure Tools](https://docs.chatbotplatform.io/agentic-loops/using-tools.md)
>
> Connect to MCP servers and data sources

> [card] [Best Practices](https://docs.chatbotplatform.io/agentic-loops/best-practices.md)
>
> Optimize for performance and cost


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.