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

# Best Practices for Agentic Loops

> Optimize your agents for reliability, performance, and cost while eliminating hallucinations

Follow these best practices to build production-ready Agentic Loops that consistently ground responses in real-world data while maintaining optimal performance and cost efficiency.

## When to Use Agentic Loops

### Use Agentic Loops When You Need

> [card] Current Data
>
> Weather, stock prices, system status, inventory levels

> [card] Specific Facts
>
> Customer records, order details, account balances

> [card] Verifiable Information
>
> Calendar availability, product specs, policy details

> [card] Real-World Actions
>
> Create events, send notifications, update records

### Don't Use Agentic Loops When

Agentic Loops add latency and cost. Don't use them for tasks where the LLM's training data is sufficient.

**Skip Agentic Loops for**:

* General knowledge questions ("What is photosynthesis?")
* Creative writing tasks
* Text summarization or translation
* Brainstorming and ideation
* Mathematical calculations (LLMs can do this directly)

**Rule of Thumb**: If the answer is in the LLM's training data and doesn't need to be current, use a standard prompt instead of an Agentic Loop.

## Preventing Hallucinations

### 1. Make Tool Use Mandatory

**Bad System Prompt** (Allows Hallucinations):

```
You can check the order database if needed.
```

**Good System Prompt** (Enforces Grounding):

```
CRITICAL: You MUST query the order database for every order status
question. NEVER provide order information without calling the
get_order_status tool first. Do not guess or use training data.
```

### 2. Document Tool Usage Explicitly

**Bad** (Vague):

```
Available tools: database, API
```

**Good** (Explicit):

```
Available Tools:

1. get_order_status
   Purpose: Retrieve current order status
   Parameters:
     - order_id (string, required): Order ID, e.g., "12345"
   Returns:
     - status (string): "pending", "shipped", "delivered"
     - ship_date (string): ISO date or null
     - tracking_number (string): Tracking number or null
   When to use: Every time user asks about an order
   Example: get_order_status({order_id: "12345"})

2. get_tracking_info
   Purpose: Get detailed shipping information
   Parameters:
     - tracking_number (string, required): Carrier tracking number
   Returns:
     - current_location (string): Current package location
     - estimated_delivery (string): ISO date
     - status (string): Current shipping status
   When to use: After getting order status, if tracking needed
```

### 3. Provide Examples of Correct Usage

```
System Prompt Example Usage:

User: "Where is order #12345?"

Correct Process:
Step 1: Call get_order_status({order_id: "12345"})
Step 2: Receive response: {status: "shipped", tracking: "1Z999"}
Step 3: Call get_tracking_info({tracking_number: "1Z999"})
Step 4: Receive response: {location: "Chicago", delivery: "2024-01-18"}
Step 5: Respond: "Your order shipped and is currently in Chicago.
        Expected delivery: January 18."

WRONG: "Your order probably shipped 2-3 days ago."
[Never guess - always use tools]
```

### 4. Implement Verification Steps

```
System Prompt:

For critical information (financial, medical, legal):
1. Call the tool to get data
2. Verify the data is complete (no null/missing required fields)
3. If data is incomplete, say so explicitly
4. Never fill in missing data with assumptions

Example:
Retrieved: {balance: 1234.56, last_transaction: null}
Response: "Your account balance is $1,234.56. Last transaction
          information is not available."

WRONG: "Your last transaction was probably yesterday."
```

## Performance Optimization

### Minimize Iterations

More iterations = longer execution time and higher cost.

**Inefficient** (Wastes Iterations):

```
Iteration 1: "Hmm, I should probably check the database."
Iteration 2: "Yes, I'll use the get_order tool."
Iteration 3: [Calls tool]
Iteration 4: "I received the data."
Iteration 5: [Formats response]
```

**Efficient** (Minimizes Iterations):

```
Iteration 1: [Calls tool immediately]
Iteration 2: [Formats response with data]
```

**How to Achieve This**:

```
System Prompt:
Process (be direct, no thinking out loud):
1. Call get_order_status({order_id: extracted_id})
2. Format response with returned data

Do NOT waste iterations explaining what you're about to do.
Just do it.
```

### Set Appropriate Iteration Limits

| Task Type | Iterations | Reasoning |
| - | - | - |
| Single API call | 3-5 | Fetch data, format, respond |
| Multiple related calls | 5-10 | Query database, fetch details, format |
| Complex analysis | 10-20 | Multiple data sources, processing, insights |
| Multi-step workflow | 20-50 | Extensive data gathering and processing |

**Monitor Usage**:

```
Check execution logs:
- If agent consistently uses 80%+ of max iterations → increase limit
- If agent consistently uses <30% of max iterations → decrease limit
```

### Use Parallel Tool Calls When Possible

**Sequential** (Slower):

```
Iteration 1: Get user profile
Iteration 2: Get user orders
Iteration 3: Get user preferences
Total: 3 iterations
```

**Parallel** (Faster):

```
Iteration 1: Get user profile, orders, and preferences simultaneously
Total: 1 iteration
```

**System Prompt for Parallel Calls**:

```
When you need multiple independent pieces of data, call all tools
simultaneously in the same iteration instead of one at a time.

Example:
Need: user profile, order history, preferences
Do: Call all three tools in iteration 1
Don't: Call profile in iteration 1, orders in iteration 2, etc.
```

### Cache Frequently Accessed Data

For data that doesn't change often:

```
System Prompt:
If you called get_product_catalog in the last 5 minutes of this
conversation, use the cached results instead of calling again.

Product catalogs update hourly, so recent data is still accurate.
```

## Cost Management

### Choose the Right Model

| Model | Use Case | Cost | Tool Use Quality |
| - | - | - | - |
| Claude 3.5 Sonnet | Complex reasoning, critical tasks | \$\$\$ | Excellent |
| Claude 3 Haiku | Simple data fetching | \$ | Good |
| GPT-4 Turbo | Alternative for complex tasks | \$\$\$ | Excellent |
| GPT-3.5 Turbo | Simple, straightforward tasks | \$ | Good |

**Recommendation**: Start with Claude 3.5 Sonnet for development. Once you verify your agent works correctly, test with cheaper models for simple tasks.

### Optimize Prompt Length

Longer prompts = more tokens = higher cost.

**Inefficient** (500 tokens):

```
You are an extremely helpful, friendly, and professional customer
service agent working for our company. You have access to a wonderful
database tool that allows you to look up customer orders. This tool is
incredibly powerful and can help you find any order by its ID. When a
customer asks about their order, you should always use this tool to
provide them with the most accurate and up-to-date information possible.
The tool is called get_order_status and it takes one parameter called
order_id which should be a string...

[300+ more words of fluff]
```

**Efficient** (100 tokens):

```
You track customer orders using the order database.

Tool: get_order_status
Parameters: {order_id: string}
Returns: {status, ship_date, tracking}

Process:
1. Extract order ID from question
2. Call get_order_status
3. Format response with data

Never guess order information.
```

**Impact**: Reducing prompt from 500 to 100 tokens can cut costs by 80% per execution.

### Limit Tool Response Size

**Problem**: Tools returning massive JSON blobs waste tokens.

```javascript theme={null}
// Bad: Returns entire product catalog (10,000 products)
app.post('/tools/get_products', async (req, res) => {
  const products = await db.query('SELECT * FROM products');
  res.json({ success: true, data: products });
});

// Good: Returns only requested products
app.post('/tools/get_products', async (req, res) => {
  const { product_ids } = req.body.parameters;
  const products = await db.query(
    'SELECT * FROM products WHERE id IN (?)',
    [product_ids]
  );
  res.json({ success: true, data: products });
});
```

### Set Reasonable Timeouts

**Too Long**: Wastes resources if agent gets stuck.
**Too Short**: Premature failures for legitimate long-running tasks.

```
Task Complexity | Recommended Timeout
----------------|--------------------
Single API call | 30-60 seconds
Multiple calls  | 60-120 seconds
Data analysis   | 120-300 seconds
Complex workflow| 300-600 seconds
```

Monitor execution logs to find optimal timeout for your use case.

## Reliability Best Practices

### Implement Error Handling

```
System Prompt:

Error Handling Protocol:

If a tool call fails:
1. Check the error message
2. If it's a temporary error (timeout, rate limit), retry once
3. If it's a permanent error (not found, auth failed), inform user
4. Never make up data when a tool fails

Examples:

API Timeout:
"I'm experiencing a delay accessing the order system. Let me try again."
[Retry once]

Order Not Found:
"I couldn't find an order with ID 12345 in our system. Please verify
the order number."

Rate Limit:
"The order system is experiencing high traffic. Please try again in
a moment."

WRONG: "The API failed, so your order probably shipped yesterday."
[Never guess when tools fail]
```

### Validate Tool Responses

```
System Prompt:

After receiving tool response, validate:

1. success field is true
2. Required fields are present and not null
3. Data types are correct (string/number/boolean)
4. Values are reasonable (e.g., dates are not in future for past orders)

If validation fails:
"I received incomplete data from the order system. Please contact
support for assistance with order #12345."

Don't try to "fix" invalid data or fill in blanks.
```

### Handle Ambiguity

```
System Prompt:

When user input is ambiguous:

User: "Where's my order?"
Problem: No order ID provided

Response: "I'd be happy to check your order status. Could you please
provide your order number? It's usually in your confirmation email."

DON'T: Call get_order_status with a random ID
DON'T: Guess which order they mean
DO: Ask for clarification
```

### Test Edge Cases

Before deploying, test:

**Happy Path**:

* Tool returns expected data
* Agent formats response correctly
* Execution completes within iterations

**Error Cases**:

* Tool returns error
* Tool times out
* Invalid parameters sent
* Empty result sets
* Malformed data

**Edge Cases**:

* Multiple orders with same details
* Null/missing optional fields
* Very old or very new data
* Special characters in input
* Extremely long responses

## Monitoring and Maintenance

### Key Metrics to Track

```
1. Success Rate
   Target: >95%
   Alert if: <90% for 24 hours

2. Average Iterations Used
   Target: <50% of max iterations
   Alert if: >80% consistently

3. Average Execution Time
   Target: <10 seconds for simple tasks
   Alert if: >30 seconds consistently

4. Tool Call Success Rate
   Target: >98%
   Alert if: <95% for any tool

5. Hallucination Rate
   Target: 0%
   Method: Audit random sample of responses monthly
```

### Regular Audits

**Weekly**:

* Review failed executions
* Check for new error patterns
* Verify tool response times

**Monthly**:

* Audit random sample of responses for hallucinations
* Review system prompt effectiveness
* Check for opportunities to reduce iterations/cost

**Quarterly**:

* Full performance review
* Cost optimization analysis
* Consider model upgrades/downgrades
* Update tools and documentation

### Logging and Debugging

Enable detailed logging:

```
Execution Log Should Include:

- Agent loop ID and execution ID
- Timestamp for each iteration
- Agent's reasoning at each step
- Tool calls made (with parameters)
- Tool responses received
- Final response generated
- Total iterations used
- Total execution time
- Any errors or warnings
```

This transparency allows you to:

* Debug incorrect responses
* Identify hallucinations
* Optimize system prompts
* Improve tool design
* Build user trust

## Security Considerations

> [card] Input Validation
>
> Validate all user inputs before passing to tools

> [card] Authentication
>
> Secure all MCP servers with strong auth

> [card] Rate Limiting
>
> Prevent abuse with rate limits

> [card] Audit Logging
>
> Log all tool calls for security review

### Validate Inputs

```javascript theme={null}
// In your MCP server
app.post('/tools/get_order_status', async (req, res) => {
  const { order_id } = req.body.parameters;

  // Validate input
  if (!order_id || typeof order_id !== 'string') {
    return res.status(400).json({
      success: false,
      error: 'Invalid order_id parameter'
    });
  }

  // Sanitize input (prevent SQL injection)
  const sanitized_id = order_id.replace(/[^a-zA-Z0-9-]/g, '');

  // Continue with database query...
});
```

### Implement Authorization

```javascript theme={null}
// Check if agent loop has permission for this action
app.post('/tools/delete_order', async (req, res) => {
  const { agent_loop_id } = req.body.context;

  // Verify this agent loop is authorized for deletions
  if (!hasPermission(agent_loop_id, 'delete_orders')) {
    return res.status(403).json({
      success: false,
      error: 'Agent loop not authorized for delete operations'
    });
  }

  // Continue with deletion...
});
```

### Protect Sensitive Data

```
System Prompt:

When handling sensitive information:
- Never log full credit card numbers
- Redact PII in responses when not necessary
- Only return the minimum required data

Example:
User: "What's my account info?"

Bad Response:
"Your account email is john@example.com, password hash is abc123xyz,
credit card ending in 1234..."

Good Response:
"Your account email is john@example.com. Account status: Active.
Last login: Jan 15, 2024."
```

## Scaling Considerations

### High-Volume Scenarios

When running many agent loops simultaneously:

**Database Connections**:

* Use connection pooling
* Set reasonable max connections
* Implement query timeouts

**API Rate Limits**:

* Implement backoff/retry logic
* Cache frequent queries
* Consider API quota management

**Cost Control**:

* Set per-user or per-day execution limits
* Monitor spend in real-time
* Alert when approaching budget thresholds

### Load Testing

Before production deployment:

```
Test Scenarios:

1. Single execution
   - Verify correct behavior
   - Measure baseline performance

2. 10 concurrent executions
   - Check for race conditions
   - Verify all complete successfully

3. 100 concurrent executions
   - Test tool server scalability
   - Identify bottlenecks

4. Sustained load (1 hour)
   - Check for memory leaks
   - Verify consistent performance
```

## Migration from Traditional Chatbots

### Step-by-Step Migration

**1. Identify Hallucination-Prone Queries**

Review chatbot logs for queries where the bot likely guessed:

* Order status questions
* Product availability
* Account details
* Current information (weather, prices)

**2. Create MCP Servers**

Build tools for accessing the real data:

* Order database MCP
* Inventory database MCP
* Account API MCP

**3. Build Agentic Loop for One Use Case**

Start with the highest-impact use case:

```
Choose: Order status tracking (high impact, simple to implement)
Build: Agent loop with order database tool
Test: Verify accuracy improves
```

**4. A/B Test**

Compare old chatbot vs. new agentic loop:

* Track hallucination rate
* Measure customer satisfaction
* Monitor cost difference

**5. Migrate Additional Use Cases**

Once validated, expand to other areas:

* Product recommendations
* Account management
* Appointment scheduling

**6. Deprecate Old System**

After all use cases are migrated and validated, deprecate the
traditional chatbot.

### Measuring Improvement

| Metric | Traditional Bot | Agentic Loop | Improvement |
| - | - | - | - |
| Hallucination Rate | 35% | 0% | -100% |
| Customer Satisfaction | 3.2/5 | 4.7/5 | +47% |
| Resolution Time | 8 min | 2 min | -75% |
| Cost per Query | \$0.02 | \$0.08 | +300% |
| Net Value | - | - | +ROI |

**Note**: Agentic Loops cost more per query but deliver dramatically better outcomes, resulting in positive ROI through reduced support costs and increased satisfaction.

## Real-World Success Patterns

### Pattern 1: E-Commerce Order Tracking

**Before**: Customers frustrated by vague "shipped 2-3 days ago" responses.

**After**: Agents provide exact ship dates, tracking numbers, and delivery estimates from real data.

**Result**: 90% reduction in "where's my order?" follow-up contacts.

### Pattern 2: Healthcare Appointment Scheduling

**Before**: Bots suggest appointment times without checking availability, causing double-bookings.

**After**: Agents only offer times verified as available in real-time calendar.

**Result**: Zero double-bookings, 85% reduction in scheduling errors.

### Pattern 3: Financial Services Account Inquiry

**Before**: Agents provide generic responses, forcing customers to log in separately to check balances.

**After**: Agents fetch real-time account balances and transaction history.

**Result**: 70% reduction in calls to human support for basic account info.

## Summary: The Path to Zero Hallucinations

**1. Identify Hallucination-Prone Tasks**

Find queries where your AI currently guesses instead of knowing.

**2. Build or Connect MCP Servers**

Create tools that access your real data sources.

**3. Write Explicit System Prompts**

Make tool use mandatory, document everything clearly.

**4. Test Thoroughly**

Verify agents use tools correctly and don't hallucinate.

**5. Monitor and Optimize**

Track performance, reduce cost, maintain reliability.

**6. Scale with Confidence**

Deploy production-ready agents that users can trust.

## Next Steps

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

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

> [card] [Available MCP Servers](https://docs.chatbotplatform.io/mcp-servers/overview.md)
>
> Explore built-in tools and data sources

> [card] [Complete API Reference](https://app.chatbotplatform.io/openapi)
>
> View the full API specification for programmatic agent management


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