> ## 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.

# Creating Agentic Loops

> Step-by-step guide to building AI agents that ground their responses in real-world data

Learn how to create Agentic Loops that eliminate hallucinations by connecting your AI to real-world data sources.

## Quick Start: Your First Agentic Loop

Let's build an agent that provides accurate weather information by calling a real weather API instead of guessing.

**1. Navigate to Agent Loops**

From your dashboard, click **Agent Loops** in the sidebar.

![Agent loops list](https://mintcdn.com/chatbotplatform/QhGUbEN05MzAjt2K/images/screenshots/04-agentic/01_agent_loops_list.png?fit=max\&auto=format\&n=QhGUbEN05MzAjt2K\&q=85\&s=889ee22ef0b7c9a587488da9f68b95ce)

Agent loops list

**2. Create New Loop**

Click **Create Agent Loop** to open the configuration form.

![Create form](https://mintcdn.com/chatbotplatform/QhGUbEN05MzAjt2K/images/screenshots/04-agentic/03_create_agent_loop_form.png?fit=max\&auto=format\&n=QhGUbEN05MzAjt2K\&q=85\&s=a216a802be35c9cafd00000a9f080993)

Create agent loop form

**3. Name Your Agent**

Give your agent a descriptive name: "Weather Information Agent"

![Named agent](https://mintcdn.com/chatbotplatform/QhGUbEN05MzAjt2K/images/screenshots/04-agentic/04_agent_loop_named.png?fit=max\&auto=format\&n=QhGUbEN05MzAjt2K\&q=85\&s=47e422b4c94ae76db528703e54f0188f)

Named agent loop

**4. Configure System Prompt**

Define the agent's role and available tools:

```
You are a weather information assistant. When users ask about weather,
you MUST use the weather API tool to fetch current data. Never guess
or use outdated training data.

Available tools:
- weather_api: Get current weather for any city

Process:
1. Identify the city from the user's question
2. Call the weather_api tool with the city name
3. Format the response with the real data received
4. If the API call fails, inform the user
```

![System prompt](https://mintcdn.com/chatbotplatform/QhGUbEN05MzAjt2K/images/screenshots/04-agentic/05_system_prompt.png?fit=max\&auto=format\&n=QhGUbEN05MzAjt2K\&q=85\&s=4564b8396fc8a9848f8e0125d1f967b2)

System prompt configuration

**5. Set User Message**

Provide the initial question or task:

```
What's the current weather in Paris?
```

![User message](https://mintcdn.com/chatbotplatform/QhGUbEN05MzAjt2K/images/screenshots/04-agentic/06_user_message.png?fit=max\&auto=format\&n=QhGUbEN05MzAjt2K\&q=85\&s=9633bf51dda8771c74475991c73e0d05)

User message input

**6. Configure MCP Server**

Add the tool that provides weather data:

* Click **Add MCP Server**
* Select **HTTP Client** (for calling weather APIs)
* Or select a pre-configured weather MCP server if available

![MCP server](https://mintcdn.com/chatbotplatform/IwOyuSig9ydzaHpG/images/screenshots/04-agentic/07_mcp_server_configured.png?fit=max\&auto=format\&n=IwOyuSig9ydzaHpG\&q=85\&s=bec5c6035662f70e5b6d997c1740bffe)

MCP server configured

**7. Add Callback (Optional)**

Configure where to send results:

```
Callback URL: https://your-app.com/webhooks/weather-reports
```

![Callback](https://mintcdn.com/chatbotplatform/IwOyuSig9ydzaHpG/images/screenshots/04-agentic/08_callback_configured.png?fit=max\&auto=format\&n=IwOyuSig9ydzaHpG\&q=85\&s=6f00b528301f15fe8619ee20fc4a6ec5)

Callback configuration

**8. Configure Advanced Settings**

Set execution parameters:

* **Max Iterations**: 5 (simple task)
* **Timeout**: 60 seconds
* **Model**: Claude 3.5 Sonnet (recommended for tool use)

![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

**9. Save and Test**

Click **Create** to save your Agentic Loop, then click **Run** to test it.

![Complete agent](https://mintcdn.com/chatbotplatform/QhGUbEN05MzAjt2K/images/screenshots/04-agentic/10_agent_loop_complete.png?fit=max\&auto=format\&n=QhGUbEN05MzAjt2K\&q=85\&s=3cfd56725f35009b045c00560c3f38ba)

Complete agent loop

## What Happens When It Runs

### Execution Flow

```
User Message: "What's the current weather in Paris?"

Iteration 1:
THINK: "I need current weather data for Paris. I'll call the weather API."
TOOL: weather_api({city: "Paris"})
OBSERVE: {temp: 22, condition: "sunny", humidity: 45%}

Iteration 2:
THINK: "I have the data. I'll format a clear response."
RESPOND: "The current weather in Paris is 22°C and sunny with 45% humidity."

✓ COMPLETE - Grounded response with zero hallucinations
```

### Execution Log

After running, you'll see a detailed log:

```
=== Agent Loop Execution ===
Status: Completed Successfully
Duration: 3.2 seconds
Iterations Used: 2 of 5
Tool Calls: 1

Iteration 1:
  Reasoning: "Need to fetch current weather for Paris"
  Action: Call weather_api
  Result: {temperature: 22, condition: "sunny"}

Iteration 2:
  Reasoning: "Have data, generating response"
  Action: Generate final answer
  Result: "The current weather in Paris is 22°C and sunny..."

Final Response: [grounded in real API data]
```

## Configuration Deep Dive

### System Prompt Best Practices

The system prompt is critical for preventing hallucinations. Here's how to write effective prompts:

#### Bad System Prompt (Allows Hallucinations)

```
You are a helpful weather assistant. Answer weather questions.
```

**Problems**:

* Doesn't mention tools
* No instruction to use real data
* Agent might guess instead of fetching

#### Good System Prompt (Prevents Hallucinations)

```
You are a weather assistant with access to real-time weather data.

CRITICAL: You MUST use tools to fetch current data. NEVER guess or
rely on training data for weather information.

Available Tools:
- weather_api: Returns current weather for any city
  Parameters: {city: string}
  Response: {temperature: number, condition: string, humidity: number}

Process:
1. Extract city name from user question
2. Call weather_api with city parameter
3. Wait for response
4. Format data into natural language
5. If API fails, say "Unable to fetch current weather data"

Never make up weather information. Every fact must come from the API.
```

**Why This Works**:

* Explicitly requires tool use
* Documents available tools
* Provides clear process
* Includes error handling
* Forbids guessing

### User Message Patterns

The user message can be static or dynamic:

#### Static Message (For Scheduled Tasks)

```
User Message: "Generate yesterday's sales report"

Use Case: Daily scheduled report
Result: Same query every day, different data
```

#### Dynamic Message (For API Triggers)

```
User Message: "What's the status of order #{{order_id}}?"

Use Case: Customer support bot
Result: Variable passed from your application
```

#### Multi-Step Instructions

```
User Message: "Analyze yesterday's data and identify trends:
1. Query sales database for all orders
2. Calculate total revenue and order count
3. Identify top 5 products
4. Compare to previous week
5. Generate summary report"

Use Case: Complex analysis task
Result: Agent executes multiple steps with multiple tool calls
```

### MCP Server Selection

Choose tools based on your data sources:

| Data Source | MCP Server | Use Case |
| - | - | - |
| REST APIs | HTTP Client | Weather, stock prices, external services |
| Databases | Database MCP | Order data, customer records |
| File Storage | File System MCP | CSV files, documents, logs |
| Custom Logic | Custom MCP Server | Your proprietary systems |

**Start with one tool**: Begin with a single MCP server. Only add more tools when the agent needs multiple data sources. Too many tools can confuse the agent.

### Iteration Limits

Set iterations based on task complexity:

```
Simple Task (3-5 iterations):
- Single API call
- Format response
Example: Get weather, check order status

Medium Task (5-10 iterations):
- Multiple API calls
- Data processing
- Response formatting
Example: Compare prices across services

Complex Task (10-20 iterations):
- Multi-step workflow
- Multiple data sources
- Analysis and insights
Example: Generate comprehensive report

Very Complex Task (20-50 iterations):
- Deep analysis
- Many tool calls
- Complex decision trees
Example: Automated research with multiple sources
```

## Real-World Examples

### Example 1: Customer Order Tracking

**Goal**: Eliminate "your order probably shipped" hallucinations.

**Configuration**:

```
Name: Order Tracking Agent

System Prompt:
You are an order tracking assistant with access to our order database.

Available Tools:
- query_order_db: Get order details
  Parameters: {order_id: string}
  Response: {status, ship_date, tracking_number, carrier}

- query_shipping_api: Get delivery estimates
  Parameters: {tracking_number, carrier}
  Response: {location, estimated_delivery}

Process:
1. Extract order ID from user question
2. Query order database
3. If shipped, get tracking details from shipping API
4. Provide accurate status and delivery date

NEVER guess order status. If data is unavailable, say so clearly.

User Message: "What's the status of order #{{order_id}}?"

MCP Servers:
- Order Database MCP
- Shipping API MCP

Max Iterations: 10
```

**Result**: Every order status is grounded in real database data.

### Example 2: Real-Time Inventory Checker

**Goal**: Stop telling customers items are in stock when they're not.

**Configuration**:

```
Name: Inventory Checker

System Prompt:
You check product availability using our real-time inventory system.

Available Tools:
- check_inventory: Get current stock levels
  Parameters: {product_id: string, location?: string}
  Response: {in_stock: boolean, quantity: number, locations: array}

Process:
1. Extract product ID from question
2. Query inventory database
3. Report exact availability
4. If out of stock, mention when restocking (if available)

CRITICAL: Only report in-stock if quantity > 0. Never assume availability.

User Message: "Is product {{product_id}} available?"

MCP Servers:
- Inventory Database MCP

Max Iterations: 5
```

**Result**: Accurate, real-time inventory information.

### Example 3: Meeting Scheduler

**Goal**: Schedule meetings with actual calendar data, not guesses.

**Configuration**:

```
Name: Meeting Scheduler

System Prompt:
You schedule meetings by checking real calendar availability.

Available Tools:
- check_calendar: View available time slots
  Parameters: {date: string, attendees: array}
  Response: {available_slots: array}

- create_meeting: Book a time slot
  Parameters: {date, time, attendees, title}
  Response: {meeting_id, confirmation}

Process:
1. Parse meeting request (attendees, preferred time)
2. Check calendar for availability
3. Propose available time slots
4. Once user confirms, create meeting
5. Provide confirmation with meeting details

NEVER suggest times without checking availability first.

User Message: "Schedule a meeting with {{attendees}} for {{date}}"

MCP Servers:
- Calendar API MCP

Max Iterations: 10
```

**Result**: Zero double-bookings, all meetings based on actual availability.

## Testing Your Agentic Loop

### Pre-Launch Checklist

Before deploying your agent:

* [ ] **Test with multiple scenarios**: Try edge cases, not just happy paths
* [ ] **Verify tool calls work**: Check that MCP servers respond correctly
* [ ] **Review execution logs**: Confirm agent is using tools, not guessing
* [ ] **Check error handling**: What happens when APIs fail?
* [ ] **Validate response format**: Is the output structured as expected?
* [ ] **Test iteration limits**: Does the agent complete within the limit?

### Common Issues & Fixes

#### Issue: Agent Guesses Instead of Using Tools

**Symptom**:

```
User: "What's the weather?"
Agent: "It's probably mild and pleasant today."
[HALLUCINATION: Didn't call weather API]
```

**Fix**:

```
Update System Prompt:
"CRITICAL: You MUST call the weather_api tool. Never provide
weather information without calling the API first."
```

#### Issue: Agent Runs Out of Iterations

**Symptom**:

```
Execution Failed: Reached max iterations (5) without completing
```

**Fix**:

```
Increase max iterations from 5 to 10, or simplify the task.

Check execution log to see where agent got stuck.
```

#### Issue: Tool Calls Fail

**Symptom**:

```
Tool Call Error: Connection timeout to MCP server
```

**Fix**:

* Verify MCP server URL is correct
* Check that server is running and accessible
* Increase timeout in advanced settings
* Add retry logic to system prompt

#### Issue: Agent Uses Wrong Tool

**Symptom**:

```
Agent called database tool for weather data (wrong tool)
```

**Fix**:

```
Update System Prompt:
"For weather information, use the weather_api tool.
For order information, use the order_database tool.

Example:
User asks about weather → Use weather_api
User asks about order → Use order_database"
```

## Monitoring and Optimization

### Key Metrics to Track

Monitor these metrics for each agent:

```
Execution Success Rate: 98% (target: >95%)
Average Iterations: 3.2 (target: <50% of max)
Average Duration: 4.5s (target: <10s)
Tool Call Success Rate: 99% (target: >98%)
Hallucination Rate: 0% (target: 0%)
```

### Cost Management

Agentic Loops cost more than simple prompts due to:

* Multiple iterations (more tokens)
* Tool call overhead
* Longer execution time

**Optimization Tips**:

* Set appropriate iteration limits (don't over-provision)
* Use efficient system prompts (fewer tokens)
* Cache frequently accessed data
* Choose appropriate model (smaller models for simple tasks)

### Improving Performance

**Reduce Iterations**:

```
Bad: "Figure out what to do"
Good: "1. Call weather API, 2. Format response"
[Explicit steps = fewer iterations]
```

**Parallel Tool Calls**:

```
Bad: Call API 1, wait, then call API 2
Good: Call both APIs simultaneously in iteration 1
[Faster execution]
```

**Efficient Prompts**:

```
Bad: 500-word system prompt with examples
Good: Clear, concise instructions (200 words)
[Lower token cost]
```

## API Integration

Trigger Agentic Loops programmatically:

> [accordion] Create an Agentic Loop via API
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl -X POST https://api.chatbotplatform.io/v1/agent-loops \
> >   -H "Authorization: Bearer YOUR_API_KEY" \
> >   -H "Content-Type: application/json" \
> >   -d '{
> >     "name": "Order Tracker",
> >     "system_prompt": "You track orders using the order database...",
> >     "user_message": "Check order #{{order_id}}",
> >     "mcp_servers": ["order_database", "shipping_api"],
> >     "max_iterations": 10,
> >     "timeout": 60
> >   }'
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const response = await fetch('https://api.chatbotplatform.io/v1/agent-loops', {
> >   method: 'POST',
> >   headers: {
> >     'Authorization': 'Bearer YOUR_API_KEY',
> >     'Content-Type': 'application/json'
> >   },
> >   body: JSON.stringify({
> >     name: 'Order Tracker',
> >     system_prompt: 'You track orders using the order database...',
> >     user_message: 'Check order #{{order_id}}',
> >     mcp_servers: ['order_database', 'shipping_api'],
> >     max_iterations: 10,
> >     timeout: 60
> >   })
> > });
> > const agentLoop = await response.json();
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > $response = Http::withToken('YOUR_API_KEY')
> >     ->post('https://api.chatbotplatform.io/v1/agent-loops', [
> >         'name' => 'Order Tracker',
> >         'system_prompt' => 'You track orders using the order database...',
> >         'user_message' => 'Check order #{{order_id}}',
> >         'mcp_servers' => ['order_database', 'shipping_api'],
> >         'max_iterations' => 10,
> >         'timeout' => 60
> >     ]);
> >
> > $agentLoop = $response->json();
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > response = requests.post(
> >     'https://api.chatbotplatform.io/v1/agent-loops',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'},
> >     json={
> >         'name': 'Order Tracker',
> >         'system_prompt': 'You track orders using the order database...',
> >         'user_message': 'Check order #{{order_id}}',
> >         'mcp_servers': ['order_database', 'shipping_api'],
> >         'max_iterations': 10,
> >         'timeout': 60
> >     }
> > )
> > agent_loop = response.json()
> > ```

> [accordion] Run an Agentic Loop
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl -X POST https://api.chatbotplatform.io/v1/agent-loops/{id}/run \
> >   -H "Authorization: Bearer YOUR_API_KEY" \
> >   -H "Content-Type: application/json" \
> >   -d '{"variables": {"order_id": "12345"}}'
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const response = await fetch(`https://api.chatbotplatform.io/v1/agent-loops/${id}/run`, {
> >   method: 'POST',
> >   headers: {
> >     'Authorization': 'Bearer YOUR_API_KEY',
> >     'Content-Type': 'application/json'
> >   },
> >   body: JSON.stringify({
> >     variables: { order_id: '12345' }
> >   })
> > });
> > const execution = await response.json();
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > $response = Http::withToken('YOUR_API_KEY')
> >     ->post("https://api.chatbotplatform.io/v1/agent-loops/{$id}/run", [
> >         'variables' => ['order_id' => '12345']
> >     ]);
> >
> > $execution = $response->json();
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > response = requests.post(
> >     f'https://api.chatbotplatform.io/v1/agent-loops/{id}/run',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'},
> >     json={'variables': {'order_id': '12345'}}
> > )
> > execution = response.json()
> > ```

> [card] [Complete API Reference](https://app.chatbotplatform.io/openapi)
>
> View the full API specification with all endpoints and parameters

## Next Steps

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

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


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