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

# Conversation History

> Configure message history and context window settings

Conversation history determines how many previous messages are included when your bot calls its AI integration. This context window is crucial for maintaining coherent conversations.

## Overview

When a user sends a message, your bot sends a history of recent messages to the AI integration:

```json theme={null}
{
  "messages": [
    {"role": "user", "content": "What's the weather?"},
    {"role": "assistant", "content": "It's sunny, 72°F"},
    {"role": "user", "content": "Perfect for a walk!"}
  ]
}
```

The number of messages included is controlled by the `history_limit` setting.

## History Limit Setting

### Default Configuration

**Default**: 10 messages (5 user messages + 5 bot responses)

This provides enough context for most conversations without excessive token usage.

### Configuring History Limit

**1. Navigate to Bot Settings**

Go to your bot's settings page.

**2. Find History Settings**

Look for **Message History** or **Context Window** setting.

**3. Set Limit**

Enter the number of messages to include (e.g., 10, 20, 50).

**4. Save**

Click **Save** to apply changes immediately.

### Recommended Settings

| Use Case | Recommended Limit | Reasoning |
| - | - | - |
| Simple Q\&A | 5-10 messages | Quick questions don't need much context |
| Customer Support | 10-20 messages | Moderate context for support issues |
| Conversational AI | 20-50 messages | Long conversations need more context |
| Complex Workflows | 50-100 messages | Multi-step processes need full history |

Larger history limits use more tokens and increase API costs. Find the right balance for your use case.

## Message Format

Messages follow the OpenAI/Anthropic format:

### User Messages

```json theme={null}
{
  "role": "user",
  "content": "The message text from the user"
}
```

### Assistant Messages

```json theme={null}
{
  "role": "assistant",
  "content": "The bot's previous response"
}
```

### System Messages (Optional)

```json theme={null}
{
  "role": "system",
  "content": "You are a helpful customer support assistant."
}
```

System messages are included at the beginning if configured in your integration.

## How History Works

### Example Conversation Flow

**Initial Message**:

```json theme={null}
{
  "messages": [
    {"role": "user", "content": "Hello!"}
  ]
}
```

History: 1 message

**After First Response**:

```json theme={null}
{
  "messages": [
    {"role": "user", "content": "Hello!"},
    {"role": "assistant", "content": "Hi! How can I help?"}
  ]
}
```

History: 2 messages

**After Second User Message**:

```json theme={null}
{
  "messages": [
    {"role": "user", "content": "Hello!"},
    {"role": "assistant", "content": "Hi! How can I help?"},
    {"role": "user", "content": "What's your return policy?"}
  ]
}
```

History: 3 messages

**When History Limit Reached (limit=10)**:

```json theme={null}
{
  "messages": [
    {"role": "user", "content": "Message 1"},
    {"role": "assistant", "content": "Response 1"},
    {"role": "user", "content": "Message 2"},
    {"role": "assistant", "content": "Response 2"},
    {"role": "user", "content": "Message 3"},
    {"role": "assistant", "content": "Response 3"},
    {"role": "user", "content": "Message 4"},
    {"role": "assistant", "content": "Response 4"},
    {"role": "user", "content": "Message 5"},
    {"role": "assistant", "content": "Response 5"}
  ]
}
```

The oldest messages are dropped as new ones arrive.

### Chronological Order

Messages are always sent in chronological order, oldest first:

```
[Oldest] Message 1 → Message 2 → ... → Message N [Newest]
```

This ensures the AI understands the conversation flow.

## Context Window vs Token Limits

### Bot History Limit

Controls how many messages are sent to your integration:

* **Setting**: `history_limit = 10`
* **Result**: Last 10 messages included

### AI Model Token Limit

Different AI models have different context windows:

| Model | Token Limit | Approximate Messages |
| - | - | - |
| GPT-3.5 | 4,096 tokens | \~40-50 messages |
| GPT-4 | 8,192 tokens | \~80-100 messages |
| GPT-4 Turbo | 128,000 tokens | \~1000+ messages |
| Claude 3.5 Sonnet | 200,000 tokens | \~1500+ messages |

Even with a large `history_limit`, the AI model may not be able to process all messages if they exceed its token limit.

### Balancing History and Tokens

**Too Few Messages**:

* Bot forgets context quickly
* Users must repeat information
* Poor conversation flow

**Too Many Messages**:

* Higher API costs
* Slower response times
* May exceed model limits
* Irrelevant old context

**Sweet Spot**:

* Enough context for continuity
* Within model token limits
* Cost-effective
* Fast responses

## Storage and Retrieval

### Full History Stored

The platform stores the **complete** conversation history, regardless of `history_limit`:

```
Stored: All 100 messages in database
Sent to AI: Last 10 messages (history_limit=10)
```

### Retrieving Full History

Use the API to retrieve complete conversation history:

> [accordion] Get full conversation history
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl https://api.chatbotplatform.io/v1/conversations/conv_123/messages \
> >   -H "Authorization: Bearer YOUR_API_KEY"
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const response = await fetch('https://api.chatbotplatform.io/v1/conversations/conv_123/messages', {
> >   headers: {
> >     'Authorization': 'Bearer YOUR_API_KEY'
> >   }
> > });
> >
> > const { data } = await response.json();
> > console.log(`Total messages: ${data.length}`);
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > use Illuminate\Support\Facades\Http;
> >
> > $response = Http::withToken('YOUR_API_KEY')
> >     ->get('https://api.chatbotplatform.io/v1/conversations/conv_123/messages');
> >
> > $messages = $response->json('data');
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > import requests
> >
> > response = requests.get(
> >     'https://api.chatbotplatform.io/v1/conversations/conv_123/messages',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'}
> > )
> >
> > messages = response.json()['data']
> > print(f"Total messages: {len(messages)}")
> > ```

> [accordion] Get paginated history
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl "https://api.chatbotplatform.io/v1/conversations/conv_123/messages?limit=50&offset=0" \
> >   -H "Authorization: Bearer YOUR_API_KEY"
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const response = await fetch('https://api.chatbotplatform.io/v1/conversations/conv_123/messages?limit=50&offset=0', {
> >   headers: {
> >     'Authorization': 'Bearer YOUR_API_KEY'
> >   }
> > });
> >
> > const { data, pagination } = await response.json();
> > console.log(`Page: ${data.length} messages`);
> > console.log(`Total: ${pagination.total} messages`);
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > $response = Http::withToken('YOUR_API_KEY')
> >     ->get('https://api.chatbotplatform.io/v1/conversations/conv_123/messages', [
> >         'limit' => 50,
> >         'offset' => 0
> >     ]);
> >
> > $data = $response->json();
> > $messages = $data['data'];
> > $total = $data['pagination']['total'];
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > response = requests.get(
> >     'https://api.chatbotplatform.io/v1/conversations/conv_123/messages',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'},
> >     params={'limit': 50, 'offset': 0}
> > )
> >
> > data = response.json()
> > messages = data['data']
> > total = data['pagination']['total']
> > ```

## Advanced Patterns

### Dynamic History Based on Topic

Adjust history limit based on conversation type:

```javascript theme={null}
// In your integration
function getHistoryLimit(messages) {
  const lastMessage = messages[messages.length - 1].content.toLowerCase();

  if (lastMessage.includes('order') || lastMessage.includes('tracking')) {
    return 20; // Order queries need more context
  }

  if (lastMessage.includes('hello') || lastMessage.includes('hi')) {
    return 5; // Greetings need less context
  }

  return 10; // Default
}
```

### Summarization for Long Conversations

For very long conversations, summarize old context:

```javascript theme={null}
async function buildContextWithSummary(messages, limit) {
  if (messages.length <= limit) {
    return messages; // No summarization needed
  }

  // Summarize old messages
  const oldMessages = messages.slice(0, -limit);
  const summary = await summarizeMessages(oldMessages);

  // Include summary + recent messages
  return [
    {
      role: 'system',
      content: `Previous conversation summary: ${summary}`
    },
    ...messages.slice(-limit)
  ];
}
```

### Custom Context Selection

Select specific messages based on relevance:

```javascript theme={null}
async function selectRelevantHistory(messages, query) {
  // Use semantic search to find relevant past messages
  const relevantMessages = await semanticSearch(messages, query, limit=5);

  // Combine with recent messages
  const recentMessages = messages.slice(-5);

  return [...relevantMessages, ...recentMessages];
}
```

## API Configuration

Configure history settings programmatically.

> [accordion] Update history limit
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl -X PATCH https://api.chatbotplatform.io/v1/bots/bot_123 \
> >   -H "Authorization: Bearer YOUR_API_KEY" \
> >   -H "Content-Type: application/json" \
> >   -d '{
> >     "history_limit": 20
> >   }'
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const response = await fetch('https://api.chatbotplatform.io/v1/bots/bot_123', {
> >   method: 'PATCH',
> >   headers: {
> >     'Authorization': 'Bearer YOUR_API_KEY',
> >     'Content-Type': 'application/json'
> >   },
> >   body: JSON.stringify({
> >     history_limit: 20
> >   })
> > });
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > $response = Http::withToken('YOUR_API_KEY')
> >     ->patch('https://api.chatbotplatform.io/v1/bots/bot_123', [
> >         'history_limit' => 20
> >     ]);
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > response = requests.patch(
> >     'https://api.chatbotplatform.io/v1/bots/bot_123',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'},
> >     json={'history_limit': 20}
> > )
> > ```

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

## Best Practices

> [card] Start Small
>
> Begin with 10 messages and adjust based on needs

> [card] Monitor Costs
>
> Track token usage as you increase history

> [card] Test Edge Cases
>
> Test very long conversations to ensure they work

> [card] Consider Use Case
>
> Support needs more context than simple Q\&A

Review actual conversations to determine optimal history limit. Too little context causes confusion; too much increases costs without benefit.

## Troubleshooting

### Bot Forgets Context Too Quickly

**Symptoms**:

* Users must repeat information
* Bot asks same questions
* Conversation feels disjointed

**Solution**:

* Increase `history_limit`
* Check conversations aren't timing out
* Verify messages are being stored

### Token Limit Exceeded

**Symptoms**:

* AI returns errors about context length
* Responses are cut off
* Integration timeouts

**Solution**:

* Decrease `history_limit`
* Use a model with larger context window
* Implement summarization for old messages

### High API Costs

**Symptoms**:

* Unexpectedly high bills
* High token usage per request

**Solution**:

* Reduce `history_limit`
* Monitor average message length
* Consider cheaper models for simple queries

## Next Steps

> [card] [Conversation API](https://docs.chatbotplatform.io/bots/conversations/api.md)
>
> Manage conversations programmatically

> [card] [Webhook Payload](https://docs.chatbotplatform.io/bots/integrations/webhook-payload.md)
>
> Understand message format

> [card] [Conversations Overview](https://docs.chatbotplatform.io/bots/conversations/index.md)
>
> Learn about conversation management


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