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

# Managing Conversation Context

> Master conversation history, context windows, and memory management for better bot responses

Learn how to effectively manage conversation context to create bots that remember past interactions, maintain coherent conversations, and provide contextually relevant responses. This guide covers context windows, history management, and advanced memory techniques.

## What You'll Learn

By the end of this guide, you'll understand:

* How conversation context works in Chatbot Platform
* Configuring context window sizes
* Managing conversation history effectively
* When to clear or preserve context
* Per-user vs per-channel context handling
* Advanced memory management patterns
* Context optimization for cost and performance

## Prerequisites

Before starting, you should:

* Have a working bot with at least one channel
* Understand basic bot concepts from [Support Bot Basics](https://docs.chatbotplatform.io/guides/support-bot-basics.md)
* Know how webhook integrations work
* Have some experience with chatbot conversations

## How Conversation Context Works

### The Basics

Every time a user sends a message, your bot needs context to provide relevant responses:

```
User: "What's your return policy?"
Bot: "We accept returns within 30 days of purchase..."

User: "What if it's been 35 days?"
Bot: [needs context to know "it" refers to a return]
     "Unfortunately, we can only accept returns within 30 days.
     However, you may be eligible for store credit..."
```

Without conversation history, the bot wouldn't understand what "it" refers to in the second question.

### Context Window

The **context window** determines how many previous messages are included when sending requests to your AI integration:

```
Context Window = 10 messages

Conversation:
1. User: Hi
2. Bot: Hello!
3. User: I need help
4. Bot: How can I assist?
5. User: Order issue
6. Bot: What's the order number?
7. User: 12345
8. Bot: Let me look that up...
9. User: Thanks
10. Bot: Order 12345 status is...
11. User: When will it arrive?  ← Current message

Messages sent to integration:
- Messages 2-11 (last 10 messages)
- Message 1 is excluded (outside window)
```

### Why Context Matters

**Good Context:**

* Bot remembers what you're talking about
* No need to repeat information
* Natural, flowing conversation
* Better user experience

**Poor Context:**

* Bot asks for information you already provided
* Doesn't understand references ("it", "that", "them")
* Repetitive or confused responses
* Frustrating user experience

## Step 1: Configure Context Window

**1. Go to Bot Settings**

Navigate to your bot and click the **Settings** or **Behavior** tab.

**2. Set Context Window**

Configure the number of messages to include:

* **Small (5-10 messages)**: Quick questions, minimal context needed
* **Medium (10-20 messages)**: Standard support conversations
* **Large (20-30 messages)**: Complex discussions, detailed troubleshooting
* **Very Large (30+ messages)**: Long-form consultations, extended sessions

Larger context windows cost more (more tokens sent to AI) but provide better context.

**3. Consider Token Costs**

Calculate approximate costs:

```
Average message: ~50 tokens
Context window: 20 messages
Context tokens: 20 × 50 = 1,000 tokens per request

With 1,000 requests/day:
- Input tokens: 1,000,000/day
- GPT-4 cost: ~$30/day input tokens
- GPT-3.5 cost: ~$1.50/day input tokens
```

**4. Test Different Sizes**

Try different window sizes:

1. Start with 15 messages
2. Monitor conversation quality
3. Check token usage
4. Adjust up or down based on needs

## Step 2: Understanding Per-User Context

Context is maintained **per user** and **per channel**:

### Same User, Different Channels

```
Alice on Telegram:
- Conversation A: "I need help with my order"
- Context: Order-related discussion

Alice on Slack:
- Conversation B: "How do I update my profile?"
- Context: Profile-related discussion

→ Two separate contexts
→ No shared history between channels
```

### Different Users, Same Channel

```
Telegram Group Chat:
- Alice: "What's the refund policy?" (Context A)
- Bob: "How do I track my order?" (Context B)
- Alice: "Thanks for the info" (Context A continues)

→ Each user has their own context
→ Bot doesn't confuse Alice's conversation with Bob's
```

### Platform-Specific Behavior

**Telegram:**

* Per-user context in groups
* Separate context for each private chat
* Group messages don't mix with private chats

**Slack:**

* Thread-based context in channels
* Per-user context in DMs
* Different threads = different contexts

**Discord:**

* Per-user context in servers
* Thread-based in thread channels
* DM context separate from server context

## Step 3: Managing Conversation History

### When to Clear Context

Clear conversation context when:

**User Explicitly Requests:**

```
User: "Start over" or "Clear history" or "New conversation"
→ Clear context, fresh start
```

**Topic Changes Dramatically:**

```
Long support conversation about Order #123
Then: "Actually, I want to ask about your pricing"
→ Consider clearing old order context
```

**Sensitive Information:**

```
User provided credit card or personal info
After transaction complete:
→ Clear context to remove sensitive data
```

**Error Recovery:**

```
Bot got confused or provided wrong information
User: "Let's start fresh"
→ Clear context, apologize, begin anew
```

### How to Clear Context

Via API:

> [accordion] Clear conversation context
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl -X DELETE https://api.chatbotplatform.io/v1/conversations/conv_123/messages \
> >   -H "Authorization: Bearer YOUR_API_KEY"
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > await fetch(
> >   'https://api.chatbotplatform.io/v1/conversations/conv_123/messages',
> >   {
> >     method: 'DELETE',
> >     headers: {
> >       'Authorization': 'Bearer YOUR_API_KEY'
> >     }
> >   }
> > );
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > Http::withToken('YOUR_API_KEY')
> >     ->delete('https://api.chatbotplatform.io/v1/conversations/conv_123/messages');
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > requests.delete(
> >     'https://api.chatbotplatform.io/v1/conversations/conv_123/messages',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'}
> > )
> > ```

### When to Preserve Context

Keep conversation context when:

**Follow-up Questions:**

```
User: "What's your shipping policy?"
Bot: [Explains policy]
User: "What about international shipping?"
→ Keep context to understand "shipping" reference
```

**Multi-Step Processes:**

```
User: "I want to return my order"
Bot: "What's the order number?"
User: "12345"
Bot: "What's the reason for return?"
User: "Too small"
→ Keep full context for complete transaction
```

**Troubleshooting:**

```
Long back-and-forth to diagnose an issue
Need full history to understand what's been tried
→ Keep context for effective support
```

## Advanced Context Patterns

### Pattern 1: Sliding Window with Summarization

For very long conversations, summarize older messages:

```javascript theme={null}
// In your integration
async function handleLongConversation(messages) {
  if (messages.length > 30) {
    // Summarize messages 1-20
    const oldMessages = messages.slice(0, 20);
    const summary = await summarizeMessages(oldMessages);

    // Keep recent messages + summary
    const contextMessages = [
      { role: 'system', content: `Previous conversation summary: ${summary}` },
      ...messages.slice(20)
    ];

    return callAI(contextMessages);
  } else {
    return callAI(messages);
  }
}

async function summarizeMessages(messages) {
  const conversation = messages
    .map(m => `${m.role}: ${m.content}`)
    .join('\n');

  const response = await callAI([{
    role: 'user',
    content: `Summarize this conversation in 2-3 sentences:\n\n${conversation}`
  }]);

  return response;
}
```

### Pattern 2: Contextual Memory Injection

Inject relevant context from external sources:

```javascript theme={null}
async function enrichContext(messages, user) {
  // Get user's recent orders
  const orders = await fetchUserOrders(user.id);

  // Get user preferences
  const preferences = await fetchUserPreferences(user.id);

  // Add to context
  const enrichedMessages = [
    {
      role: 'system',
      content: `User context:
- Recent orders: ${orders.map(o => `#${o.number} (${o.status})`).join(', ')}
- Preferences: ${JSON.stringify(preferences)}
- User since: ${user.created_at}`
    },
    ...messages
  ];

  return callAI(enrichedMessages);
}
```

### Pattern 3: Topic-Based Context Segmentation

Maintain separate contexts for different topics:

```javascript theme={null}
async function handleMessage(messages, user) {
  const currentTopic = detectTopic(messages);
  const previousTopic = await getLastTopic(user.id);

  if (currentTopic !== previousTopic) {
    // Topic changed, start with lighter context
    const recentMessages = messages.slice(-5);

    await saveTopic(user.id, currentTopic);

    return callAI([
      { role: 'system', content: `Topic: ${currentTopic}` },
      ...recentMessages
    ]);
  } else {
    // Same topic, keep full context
    return callAI(messages);
  }
}

function detectTopic(messages) {
  const lastMessage = messages[messages.length - 1].content.toLowerCase();

  if (lastMessage.includes('order') || lastMessage.includes('shipping')) {
    return 'orders';
  } else if (lastMessage.includes('account') || lastMessage.includes('password')) {
    return 'account';
  } else if (lastMessage.includes('product') || lastMessage.includes('price')) {
    return 'products';
  } else {
    return 'general';
  }
}
```

### Pattern 4: Selective Context Filtering

Remove irrelevant messages from context:

```javascript theme={null}
function filterContext(messages) {
  return messages.filter(message => {
    // Remove short acknowledgments
    if (message.content.length < 10 &&
        /^(ok|thanks|yes|no|sure)$/i.test(message.content)) {
      return false;
    }

    // Remove system messages older than 10 messages
    const position = messages.indexOf(message);
    if (message.role === 'system' && position < messages.length - 10) {
      return false;
    }

    return true;
  });
}
```

## Context Optimization

### Reducing Token Usage

**Strategy 1: Compress System Prompts**

```javascript theme={null}
// ❌ Verbose system prompt (200+ tokens)
const verbosePrompt = `
You are a helpful customer support assistant for Acme Corporation.
You should always be polite, professional, and friendly.
When answering questions, make sure to provide accurate information.
If you don't know the answer, you should say so and offer to escalate.
Always greet customers warmly and thank them for contacting us.
...
`;

// ✅ Concise system prompt (50 tokens)
const concisePrompt = `
You are Acme support. Be professional and helpful.
Admit when you don't know. Escalate complex issues.
`;
```

**Strategy 2: Remove Redundant Messages**

```javascript theme={null}
function deduplicateMessages(messages) {
  const seen = new Set();
  return messages.filter(message => {
    const key = `${message.role}:${message.content}`;
    if (seen.has(key)) {
      return false;
    }
    seen.add(key);
    return true;
  });
}
```

**Strategy 3: Dynamic Window Sizing**

```javascript theme={null}
function adaptiveContextWindow(messages, complexity) {
  // Simple queries: small window
  if (complexity === 'simple') {
    return messages.slice(-5);
  }
  // Complex queries: larger window
  else if (complexity === 'complex') {
    return messages.slice(-20);
  }
  // Default
  else {
    return messages.slice(-10);
  }
}

function assessComplexity(message) {
  const indicators = {
    simple: ['what', 'when', 'where', 'is', 'are'],
    complex: ['how can', 'why', 'explain', 'help me', 'problem']
  };

  const content = message.content.toLowerCase();

  if (indicators.complex.some(phrase => content.includes(phrase))) {
    return 'complex';
  } else if (indicators.simple.some(word => content.includes(word))) {
    return 'simple';
  }

  return 'medium';
}
```

### Improving Response Quality

**Strategy 1: Include Structured Context**

```javascript theme={null}
async function structuredContext(messages, user) {
  const context = {
    user: {
      name: user.name,
      tier: await getUserTier(user.id),
      active_orders: await getActiveOrders(user.id)
    },
    conversation: {
      topic: detectTopic(messages),
      sentiment: detectSentiment(messages),
      duration: messages.length
    }
  };

  return [
    {
      role: 'system',
      content: `Context: ${JSON.stringify(context, null, 2)}`
    },
    ...messages
  ];
}
```

**Strategy 2: Reference Previous Solutions**

```javascript theme={null}
async function addPreviousSolutions(messages, user) {
  const currentIssue = messages[messages.length - 1].content;

  // Search past conversations for similar issues
  const similarConversations = await searchConversations(user.id, currentIssue);

  if (similarConversations.length > 0) {
    const solutions = similarConversations
      .map(c => c.resolution)
      .join('\n');

    messages.unshift({
      role: 'system',
      content: `Previous solutions for similar issues:\n${solutions}`
    });
  }

  return messages;
}
```

## API Examples

> [accordion] Get 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 messages = await response.json();
> > console.log(`Conversation has ${messages.length} messages`);
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > $messages = Http::withToken('YOUR_API_KEY')
> >     ->get('https://api.chatbotplatform.io/v1/conversations/conv_123/messages')
> >     ->json();
> >
> > $messageCount = count($messages);
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > response = requests.get(
> >     'https://api.chatbotplatform.io/v1/conversations/conv_123/messages',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'}
> > )
> >
> > messages = response.json()
> > print(f"Conversation has {len(messages)} messages")
> > ```

> [accordion] Add context to conversation
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl -X POST https://api.chatbotplatform.io/v1/conversations/conv_123/context \
> >   -H "Authorization: Bearer YOUR_API_KEY" \
> >   -H "Content-Type: application/json" \
> >   -d '{
> >     "role": "system",
> >     "content": "User is a premium customer with order #12345 pending"
> >   }'
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > await fetch(
> >   'https://api.chatbotplatform.io/v1/conversations/conv_123/context',
> >   {
> >     method: 'POST',
> >     headers: {
> >       'Authorization': 'Bearer YOUR_API_KEY',
> >       'Content-Type': 'application/json'
> >     },
> >     body: JSON.stringify({
> >       role: 'system',
> >       content: 'User is a premium customer with order #12345 pending'
> >     })
> >   }
> > );
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > Http::withToken('YOUR_API_KEY')
> >     ->post('https://api.chatbotplatform.io/v1/conversations/conv_123/context', [
> >         'role' => 'system',
> >         'content' => 'User is a premium customer with order #12345 pending'
> >     ]);
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > requests.post(
> >     'https://api.chatbotplatform.io/v1/conversations/conv_123/context',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'},
> >     json={
> >         'role': 'system',
> >         'content': 'User is a premium customer with order #12345 pending'
> >     }
> > )
> > ```

> [accordion] Search conversation history
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl https://api.chatbotplatform.io/v1/conversations/search \
> >   -H "Authorization: Bearer YOUR_API_KEY" \
> >   -d "query=order 12345&user_id=user_123"
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const params = new URLSearchParams({
> >   query: 'order 12345',
> >   user_id: 'user_123'
> > });
> >
> > const response = await fetch(
> >   `https://api.chatbotplatform.io/v1/conversations/search?${params}`,
> >   {
> >     headers: {
> >       'Authorization': 'Bearer YOUR_API_KEY'
> >     }
> >   }
> > );
> >
> > const results = await response.json();
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > $results = Http::withToken('YOUR_API_KEY')
> >     ->get('https://api.chatbotplatform.io/v1/conversations/search', [
> >         'query' => 'order 12345',
> >         'user_id' => 'user_123'
> >     ])
> >     ->json();
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > response = requests.get(
> >     'https://api.chatbotplatform.io/v1/conversations/search',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'},
> >     params={'query': 'order 12345', 'user_id': 'user_123'}
> > )
> >
> > results = response.json()
> > ```

For complete API documentation, see the [OpenAPI specification](https://app.chatbotplatform.io/openapi).

## Best Practices

> [card] Right-Size Windows
>
> Use appropriate context window for your use case

> [card] Monitor Costs
>
> Track token usage and optimize for cost

> [card] Clear When Needed
>
> Don't let stale context confuse the bot

> [card] Enrich Context
>
> Add relevant external data to improve responses

### Context Window Guidelines

| Use Case | Recommended Window | Notes |
| - | - | - |
| Simple FAQ | 5-10 messages | Quick questions, minimal context |
| Customer Support | 15-20 messages | Standard conversations |
| Troubleshooting | 20-30 messages | Complex, multi-step issues |
| Consultations | 30-50 messages | Extended discussions |
| Personal Assistant | 15-25 messages | Task-oriented, varied topics |

### System Prompt Best Practices

Include context handling instructions in your system prompt:

```
You are a customer support assistant.

Context Management:
- Reference previous messages when relevant
- If user asks about something mentioned earlier, recall it
- If conversation is getting off-topic, politely refocus
- When user says "start over", treat as fresh conversation

Examples:
User: "I asked about this earlier"
You: "Yes, you asked about [topic]. [Provide answer]"

User: "Let's talk about something else"
You: "Of course! What would you like to discuss?"
```

## Troubleshooting

### Bot doesn't remember earlier messages

**Possible causes:**

* Context window too small
* Conversation history cleared accidentally
* Integration not receiving full message array

**Solutions:**

* Increase context window size
* Check conversation history via API
* Verify webhook payload includes `messages` array
* Review integration logs

### Bot confused by old context

**Possible causes:**

* Topic changed but old context still included
* Context window too large
* Multiple unrelated topics in same conversation

**Solutions:**

* Implement topic detection and context clearing
* Reduce context window size
* Add context filtering logic
* Provide clear conversation restart mechanism

### High token costs

**Possible causes:**

* Context window too large
* Verbose system prompts
* Not filtering irrelevant messages

**Solutions:**

* Reduce context window
* Compress system prompts
* Implement message filtering
* Use cheaper models for simple queries
* Add summarization for long conversations

### Different context per channel

**Expected behavior:** Each channel maintains separate context

**If you need shared context:**

* Use external database to store cross-channel history
* Implement custom context loading in integration
* Reference Conversation Archives MCP server
* Link user IDs across platforms

## Next Steps

> [card] [Build Grounded Bot](https://docs.chatbotplatform.io/guides/grounded-support-bot.md)
>
> Add external data sources to context

> [card] [Personal Assistant](https://docs.chatbotplatform.io/guides/personal-assistant.md)
>
> Advanced context with multiple tools

> [card] [Conversation API](https://docs.chatbotplatform.io/bots/conversations/api.md)
>
> Programmatic history management

> [card] [Message History](https://docs.chatbotplatform.io/bots/conversations/history.md)
>
> View and analyze conversations

## Related Documentation

* [Conversations Overview](https://docs.chatbotplatform.io/bots/conversations/index.md) - Conversation management concepts
* [Message History](https://docs.chatbotplatform.io/bots/conversations/history.md) - Viewing conversation logs
* [Conversation API](https://docs.chatbotplatform.io/bots/conversations/api.md) - API reference for conversations
* [Conversation Archives MCP](https://docs.chatbotplatform.io/mcp-servers/conversation-archives) - Search past conversations with AI
* [API Reference](https://app.chatbotplatform.io/openapi) - Complete API documentation


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